问题
I am using Polidea's RxAndroidBle library to communicate with a Device in my Android application.
I am very new to Reactive Programming so I can't figure out exactly how to do the following:
- Setup Notification in one characteristic (Characteristic A).
- When notification setup is done, write to another characteristic (Characteristic B). This will trigger a Notification coming from Characteristic A.
- When the write operation is done, wait for the arrival of the Notification in Characteristic A.
- Repeat the same steps (1 to 3) many times in different parts of the application.
I have seen this related answer, but it is done using the first version of the library and I can't figure out how to do it using the new version.
Thanks.
回答1:
I ended figuring it out by myself. Here is a method that setup the indication or notification in a characteristic, then writes some bytes to another characteristic and returns an Observable<String>
that emits the byte[]
parsed to a hex String
that were read on the notification/indication.
Hope it helps someone else looking for this solution in RxJava2.
private Observable<String> writeAndReadOnNotification(UUID writeTo, UUID readOn,
String hexString,
boolean isIndication,
RxBleConnection rxBleConnection) {
Observable<Observable<byte[]>> notifObservable =
isIndication ?
rxBleConnection.setupIndication(readOn) :
rxBleConnection.setupNotification(readOn);
return notifObservable.flatMap(
(notificationObservable) -> Observable.combineLatest(
rxBleConnection.writeCharacteristic(writeTo, hexToBytes(hexString)).toObservable(),
notificationObservable.take(1),
(writtenBytes, responseBytes) -> bytesToHex(responseBytes)
)
).take(1)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(this::throwException);
}
来源:https://stackoverflow.com/questions/53395079/rxandroidble-setup-notification-write-on-characteristic-and-wait-for-notificat