首先,我使用RxAndroidBLE库来管理我的BLE连接。
我有两个SensorTag devices,我想同时读取两者的温度。例如,我想每隔500毫秒从两个设备读取温度,并在两个TextView中显示给用户。
我的应用程序目前已成功连接到这两个BLE设备:
@OnClick(R.id.connectButton1)
public void connectFirstSensorTag(Button b) {
if (!isDeviceConnected(sensorTag1)) {
connectionObservable1 = sensorTag1.establishConnection(getApplicationContext(), false).compose(new ConnectionSharingAdapter());
}
connectionObservable1.subscribe(new Subscriber<RxBleConnection>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
updateStatus(statusTextView1, "SensorTag not found");
}
@Override
public void onNext(RxBleConnection rxBleConnection) {
updateStatus(statusTextView1, "Connected");
enableSensorTagTemperatureSensor(connectionObservable1);
}
});
}
@OnClick(R.id.connectButton2)
public void connectSecondSensorTag(Button b) {
if (!isDeviceConnected(sensorTag2)) {
connectionObservable2 = sensorTag2.establishConnection(getApplicationContext(), false).compose(new ConnectionSharingAdapter());
}
connectionObservable2.subscribe(new Subscriber<RxBleConnection>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
updateStatus(statusTextView2, "SensorTag not found");
}
@Override
public void onNext(RxBleConnection rxBleConnection) {
updateStatus(statusTextView2, "Connected");
enableSensorTagTemperatureSensor(connectionObservable2);
}
});
}
现在我正在寻找每500毫秒同时读取温度的最佳方法。
现在,我正在做这样的事情:
connectionObservable1
.flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(uuidFromShortCode("AA01")))
.subscribe(bytes -> {
// first temperature was successfully read here
connectionObservable2
.flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(uuidFromShortCode("AA01")))
.subscribe(bytes -> {
// second temperature was successfully read here
}, error -> {
updateStatus(error.toString());
});
}, error -> {
updateStatus(error.toString());
});
这段代码位于每500毫秒调用一次的runnable中。
我觉得这是一种非常低效的方法。如果有更好的方法,有人可以告诉我吗?
答案 0 :(得分:0)
我建议你开始两个线程。线程1检查第一个设备,线程2检查第二个设备。这确保了两者同时被读取。为了在两个代码完成后继续执行代码,我会做一个阻塞连接循环。
//Threads array has been created, with 0 checking the first
//device and 1 checking the second
for(i = 0; i < threads.length(); i++)
threads[i].join();