RxAndroidBle: Setup notification, write on characteristic and wait for notification to proceed

狂风中的少年 提交于 2019-12-11 17:09:41

问题


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:

  1. Setup Notification in one characteristic (Characteristic A).
  2. When notification setup is done, write to another characteristic (Characteristic B). This will trigger a Notification coming from Characteristic A.
  3. When the write operation is done, wait for the arrival of the Notification in Characteristic A.
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!