Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Built application files
*.apk
*.ap_
*.jar

# Files for the ART/Dalvik VM
*.dex
Expand All @@ -12,7 +13,7 @@
bin/
gen/
out/

libs/
# Gradle files
.gradle/
build/
Expand Down
13 changes: 12 additions & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,22 @@ android {
}
}

repositories {
maven {
url "https://repo.eclipse.org/content/repositories/paho-releases/"
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.0'
testCompile 'junit:junit:4.12'
compile 'com.github.nkzawa:socket.io-client:0.3.0'
// compile files('libs/yunba-sdk-release1.8.0.jar')

}
17 changes: 10 additions & 7 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,17 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="io.yunba.android.core.YunBaService"> </service>
<receiver android:name="io.yunba.android.core.YunBaReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<!--<service android:name="io.yunba.android.core.YunBaService"> </service>-->
<!--<receiver android:name="io.yunba.android.core.YunBaReceiver">-->
<!--<intent-filter>-->
<!--<action android:name="android.intent.action.USER_PRESENT" />-->
<!--<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />-->
<!--</intent-filter>-->
<!--</receiver>-->

<!-- Mqtt Service -->
<service android:name="org.eclipse.paho.android.service.MqttService">
</service>
</application>

</manifest>
216 changes: 163 additions & 53 deletions app/src/main/java/net/chaoc/blescanner/MainActivity.java
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
package net.chaoc.blescanner;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.support.v4.util.SparseArrayCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;

import java.io.ByteArrayInputStream;

import io.yunba.android.manager.YunBaManager;
import android.widget.Toast;
import android.widget.ToggleButton;

import static android.content.ContentValues.TAG;

Expand All @@ -40,7 +39,15 @@ public class MainActivity extends AppCompatActivity implements android.view.View
Button stopScanningButton;
TextView peripheralTextView;
private final static int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
public String advDataStr;
AdvertiseData advData;
BluetoothLeAdvertiser advertiser;
AdvertiseSettings advSettings;

AdvertiseCallback advCallback;

long matchCount = 0;
long otherCount = 0;


@Override
Expand All @@ -66,56 +73,82 @@ public void onClick(View v) {
}
});
stopScanningButton.setVisibility(View.INVISIBLE);
}

YunBaManager.start(getApplicationContext());
YunBaManager.subscribe(getApplicationContext(), new String[]{"t1"}, new IMqttActionListener() {

@Override
public void onSuccess(IMqttToken arg0) {
Log.d("main", "Subscribe topic succeed");

}

@Override
public void onFailure(IMqttToken arg0, Throwable arg1) {
Log.d("main", "Subscribe topic failed" );
}
});

registerMessageReceiver();

@Override
public void onClick(View v) {
}


public void init(){
btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
btScanner = btAdapter.getBluetoothLeScanner();
advertiser = btAdapter.getBluetoothLeAdvertiser();

if (btAdapter != null && !btAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}
// ble advertisers
advSettings = new AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
.setConnectable( false )
.build();
advDataStr = "121383000000";
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton2);
final EditText eText = (EditText) findViewById(R.id.editText4);
eText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {


}

@Override
public void afterTextChanged(Editable s) {
String text;
text = s.toString();
if (text.matches("-?[0-9a-fA-F]+") == true) {
advDataStr = s.toString();
} else {
s.clear();
s.append("121383000000");
}
}
});

toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//enabled
//update text value;
//validated it; if false then disabled this
//start advertising;
advertise(toByteArray(advDataStr));


} else {
//disabled
//stop advertising;
stopAdvertise();
}
}
});

// Make sure we have access coarse location enabled, if not, prompt the user to enable it
// if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("This app needs location access");
// builder.setMessage("Please grant location access so this app can detect peripherals.");
// builder.setPositiveButton(android.R.string.ok, null);
// builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
// @Override
// public void onDismiss(DialogInterface dialog) {
// requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
// }
// });
// builder.show();
// }
}

public void startScanning() {
System.out.println("start scanning");
peripheralTextView.setText("");

startScanningButton.setVisibility(View.INVISIBLE);
stopScanningButton.setVisibility(View.VISIBLE);
AsyncTask.execute(new Runnable() {
Expand Down Expand Up @@ -144,13 +177,50 @@ public void run() {
private ScanCallback leScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
peripheralTextView.append("Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() + " : " + result.getScanRecord().getManufacturerSpecificData().keyAt(0) + "\n" + toHexString(result.getScanRecord().getManufacturerSpecificData().valueAt(0))+ "\n");

// auto scroll for text view
final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
//if (result.getScanRecord().getManufacturerSpecificData().keyAt(0) == 65280) {
if (false) {
matchCount += 1;

peripheralTextView.append("$" + matchCount + ":N:" + result.getDevice().getName() + " rssi: " + result.getRssi() + " : " + result.getScanRecord().getManufacturerSpecificData().keyAt(0) + "\n" + toHexString(result.getScanRecord().getBytes()) + "\n");

// auto scroll for text view
final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
} else {
if (result.getDevice().getName() != null ) {
//if (result.getDevice().getName().toString().startsWith("Brac")) {
try {
String data = toHexString(result.getScanRecord().getManufacturerSpecificData().valueAt(0));
String payload = toHexString(result.getScanRecord().getBytes());
String name = result.getDevice().getName();
int key = result.getScanRecord().getManufacturerSpecificData().keyAt(0);
int rssi = result.getRssi();

String str = "$:" + name + " rssi" + rssi + " : " + key + "\n"
+ data + "\n"
+ payload + "\n";
if (key == 65281 && data.startsWith("12")) {
peripheralTextView.append(Html.fromHtml("<font color=#00ee00>"+str+"</font>"));
} else {
peripheralTextView.append(str);
}
peripheralTextView.append("\n");

otherCount += 1;
Log.w(this.getClass().getSimpleName(), toHexString(result.getScanRecord().getBytes()));
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "get manufacture data error");
}
// auto scroll for text view
final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
//}
}
}
}
};

Expand All @@ -168,5 +238,45 @@ public String toHexString(byte[] bytes){
return hexString.toString();
}

public static byte[] toByteArray(String s){
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}


public void advertise(byte[] manuData){
advData = new AdvertiseData.Builder()
.setIncludeDeviceName(true)
.addManufacturerData(65281, manuData)
.build();
advCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
Toast.makeText(getApplicationContext(), "start advertising", Toast.LENGTH_LONG).show();
}
};
advertiser.startAdvertising(advSettings, advData, advCallback);
}

public void stopAdvertise(){
advertiser.stopAdvertising(advCallback);

}

public class MessageReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Action - " + intent.getAction());
Toast.makeText(getApplicationContext(), "msg received", Toast.LENGTH_SHORT).show();
}
}
}


Loading