Using RxAndroidBle, how do I subscribe to responses from writing to a characteristic?

前端 未结 2 1950
无人共我
无人共我 2020-12-20 08:05

The BLE device that I\'m connecting to emits bytes on one of its GATT characteristics in response to writes to the characteristic. Clients are supposed to enable notificatio

2条回答
  •  囚心锁ツ
    2020-12-20 08:50

    For those readers not using a Java version that supports lambdas, here's my implementation of @s_noopy's answer.

    connectionObservable
        .flatMap(new Func1>>() {
                @Override
                public Observable> call(RxBleConnection connection) {
                    return connection.setupNotification(AP_SCAN_DATA);
                }             
            }, new Func2, Observable>() {
                @Override
                public Observable call(RxBleConnection connection, Observable apScanDataNotificationObservable) {
                    return Observable.combineLatest(
                        connection.writeCharacteristic(AP_SCAN_DATA, CharacteristicValue.RESET.asBytes()),
                        apScanDataNotificationObservable.first(),
                        new Func2() {
                            @Override
                            public byte[] call(byte[] writtenBytes, byte[] responseBytes) {
                                        return responseBytes;
                                    }
                                }
                            );
                        }
                    }
                ).flatMap(new Func1, Observable>() {
                    @Override
                    public Observable call(Observable observable) {
                        return observable;
                    }
                })
                .first()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1() {
                    @Override
                    public void call(byte[] bytes) {
                        Log.i(TAG, "notification response...." + HexString.bytesToHex(bytes));
                    }
                }, new Action1() {
                    @Override
                    public void call(Throwable throwable) {
                        logError(throwable);
                    }
                });
    

提交回复
热议问题