首先,我使用RxAndroidBLE库来管理我的 BLE 连接。
我有两个SensorTag 设备,我想同时读取这两个设备的温度。例如,我想每 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 毫秒调用一次的可运行文件中。
我觉得这是一种非常低效的方法。有人可以让我知道是否有更好的方法来做到这一点?