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

1

3

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.

Hairtail answered 20/11, 2018 at 14:22 Comment(0)
H
4

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);
}
Hairtail answered 24/11, 2018 at 0:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.