androidkotlinbluetooth-lowenergyandroid-bluetoothrxandroidble

Subscribing to notification changes with RxBLe Android


I'm trying to subscribe to notification changes from a BLE device that I built, and print the value of the notification. I know the characteristic UUID that I want to read the notifications from:

scanSubscription = rxBleClient.scanBleDevices(
        ScanSettings.Builder().build(),
        ScanFilter.Builder().setDeviceName("MyDevice").build() // Filter for devices named MyDevice
    )
    .take(1) // stop the scan when a matching device will be scanned for the first time
    .flatMap {
        val device = it.bleDevice
        device.establishConnection(false)
            .flatMap < Any > {
                rxBleConnection: RxBleConnection - > rxBleConnection.setupNotification(charUUID)
            }
            .doOnNext {
                notificationObservable: Any ? - >
            }
            .flatMap < Any > {
                notificationObservable: Any ? - > notificationObservable
            } // <-- Notification has been set up, now observe value changes.

    }
    .subscribe({ /* written */ }, {
        throwable - >
        // Handle an error here.
        // println("Scan Error: $throwable")
    })

To prove that the device is working as intended, I observe the notification changes using the BLE Scanner app for Android.

When I wave my hand over the sensor, the value changes. In my case, it increments.

My question is how can I print that value when the notification value changes? When debugging, I can't get the Count to print. It doesn't even appear in my console.


Solution

  • Usually on Android one uses Log class to log data to logcat. You could use it like this:

    scanSubscription = rxBleClient.scanBleDevices(
            ScanSettings.Builder().build(),
            ScanFilter.Builder().setDeviceName("MyDevice").build() // Filter for devices named MyDevice
        )
        .take(1) // stop the scan when a matching device will be scanned for the first time
        .flatMap {
            val device = it.bleDevice
            device.establishConnection(false)
                .flatMap < Any > {
                    rxBleConnection: RxBleConnection - > rxBleConnection.setupNotification(charUUID)
                }
                .doOnNext {
                    notificationObservable: Any ? - >
                }
                .flatMap < Any > {
                    notificationObservable: Any ? - > notificationObservable
                } // <-- Notification has been set up, now observe value changes.
    
        }
        .subscribe(
            { notification -> Log.i("Notification!", notification.contentToString()) }, 
            { throwable -> Log.e("Whoops!", "Scan Error", throwable) }
        )