我想将相同的命令写入多个设备并从每个设备接收通知。使用我当前的代码,我能够做到这一点,但我不能告诉每个通知对应的MAC地址,因为它们都共享相同的特征UUID。
这是我的代码:
for (Map.Entry<String, RxBleDevice> entry : rxBleDeviceHashMap.entrySet()) {
bleDevice = MyApplication.getRxBleClient(context).getBleDevice(entry.getKey()); // key is MAC
connectionObservable = prepareConnectionObservable();
connectionObservable
.flatMap(new Func1<RxBleConnection, Observable<Observable<byte[]>>>() {
@Override
public Observable<Observable<byte[]>> call(RxBleConnection connection) {
return connection.setupNotification(UUID.fromString(Constants.CHARACTERISTIC_UUID));
}
}, new Func2<RxBleConnection, Observable<byte[]>, Observable<byte[]>>() {
@Override
public Observable<byte[]> call(RxBleConnection connection, Observable<byte[]> apScanDataNotificationObservable) {
return Observable.combineLatest(
connection.writeCharacteristic(UUID.fromString(Constants.CHARACTERISTIC_UUID), command),
apScanDataNotificationObservable.first(),
new Func2<byte[], byte[], byte[]>() {
@Override
public byte[] call(byte[] writtenBytes, byte[] responseBytes) {
runOnUiThread(new Runnable() {
@Override
public void run() {
onWriteSuccess(writtenBytes);
}
});
Log.d(TAG, "responseBytes: " + ByteUtil.bytesToHex(responseBytes));
return responseBytes;
}
}
);
}
}
).flatMap(new Func1<Observable<byte[]>, Observable<byte[]>>() {
@Override
public Observable<byte[]> call(Observable<byte[]> observable) {
return observable;
}
})
.first()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<byte[]>() {
@Override
public void call(byte[] bytes) {
onNotificationReceived(bytes);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
onNotificationSetupFailure(throwable);
}
});
}
使用bleDevice.getMacAddress()
获取MAC地址不准确,因为与循环相比,响应通知要慢得多。我总是在循环中得到最后一个bleDevice
。
希望有一些方法可以传递MAC地址。
谢谢。
答案 0 :(得分:1)
您可以做的第一件事就是更改一行:
bleDevice = MyApplication.getRxBleClient(context).getBleDevice(entry.getKey()); // key is MAC
到
RxBleDevice bleDevice = MyApplication.getRxBleClient(context).getBleDevice(entry.getKey()); // key is MAC
然后你可以呼吁成功:
onNotificationReceived(bytes, bleDevice.getMacAddress());