1

我目前正在尝试使用 rxandroidble 来替换我们其中一款应用的 Android 原生 BLE API。

如何禁用通知?我可以使用示例代码启用它,这个:

device.establishConnection(context, false)
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(characteristicUuid)) 
.doOnNext(notificationObservable -> { // OK }) 
.flatMap(notificationObservable -> notificationObservable)     
.subscribe(bytes -> { // OK });

但是在我的产品中,我有一个用例,我必须按需禁用/启用通知。

另外,我尝试直接取消订阅/重新连接而不是禁用/启用通知,但取消订阅命令显然从未执行,我的假设是因为我的吞吐量很高(我的设备以 300 - 400Hz 通知),这是否合理?

(我知道 BLE 不是最适合高吞吐量的技术,但它在这里用于研发目的 :))

谢谢你的帮助!

4

2 回答 2

1

Observable只要订阅了from,RxBleConnection.setupNotification()就会启用通知。要禁用通知,必须取消订阅上述订阅。

有几种编码方式。其中之一是:

    final RxBleDevice rxBleDevice = // your RxBleDevice
    final Observable<RxBleConnection> sharedConnectionObservable = rxBleDevice.establishConnection(this, false).share();

    final Observable<Boolean> firstNotificationStateObservable = // an observable that will emit true when notification should be enabled and false when disabled
    final UUID firstNotificationUuid = // first of the needed UUIDs to enable / disable
    final Subscription subscription = firstNotificationStateObservable
            .distinctUntilChanged() // to be sure that we won't get more than one enable commands
            .filter(enabled -> enabled) // whenever it will emit true
            .flatMap(enabled -> sharedConnectionObservable // we take the shared connection
                    .flatMap(rxBleConnection -> rxBleConnection.setupNotification(firstNotificationUuid)) // enable the notification
                    .flatMap(notificationObservable -> notificationObservable) // and take the bytes
                    .takeUntil(firstNotificationStateObservable.filter(enabled1 -> !enabled1)) // and we are subscribing to this Observable until we want to disable - note that only the observable from sharedConnectionObservable will be unsubscribed
            )
            .subscribe(
                    notificationBytes -> { /* handle the bytes */ },
                    throwable -> { /* handle exception */ }
            );

请注意,在上面的示例中,只要最后一次订阅结束,连接就会关闭sharedConnectionObservable

Observable<Boolean>要启用/禁用不同的特性,您可以使用不同的启用/禁用输入和不同的复制并粘贴上述代码UUID

于 2016-11-08T12:03:06.200 回答
1

科特林

在 kotlin 中,使用 dispose() 禁用通知。

#ENABLE NOTIFICATION
val result = device.establishConnection(false)
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(characteristicUuid))
.doOnNext(notificationObservable -> {
    // Notification has been set up
})
.flatMap(notificationObservable -> notificationObservable) // <-- Notification has been set up, now observe value changes.
.subscribe(
    bytes -> {
        // Given characteristic has been changes, here is the value.
    },
    throwable -> {
        // Handle an error here.
    }
);


#DISABLE NOTIFICATION
result.dispose()

尝试取消订阅,但没有成功,仍然不确定哪个最好 dispose() 或 unsubscribe()

于 2020-09-03T04:12:32.257 回答