【发布时间】:2021-08-18 13:21:52
【问题描述】:
我正在使用 RxAndroidBle 2 来观察 CSC 的特征,但我之前无法读取某些特征。这也是我第一次使用 ReactiveX,所以我必须处理 flatMap、flatMapSingle 等。
这是我注册处理程序以观看 CSC Measure 的代码:
connectionSubscription = device.establishConnection(false)
// Register for notifications on CSC Measure
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(Constants.CSC_MEASURE))
.doOnNext(notificationObservable -> {
// Notification has been set up
Log.d(TAG, "doOnNext = " + notificationObservable.toString());
})
.flatMap(notificationObservable -> {
Log.d(TAG, "flatMap = " + notificationObservable);
return notificationObservable;
}) // <-- Notification has been set up, now observe value changes.
.subscribe(
this::onCharacteristicChanged,
throwable -> {
if (throwable instanceof BleDisconnectedException) {
Log.e(TAG, "getCanonicalName = " + throwable.getClass().getCanonicalName());
}
}
);
然后是提取值的代码:
private void onCharacteristicChanged(byte[] bytes) {
Integer f = ValueInterpreter.getIntValue(bytes, ValueInterpreter.FORMAT_UINT8, 0);
Log.d(TAG, "flags " + f);
switch (f) {
case 0: // 0x00000000 is not authorized
Log.w(TAG, "flags cannot be properly detected for this CSC device");
break;
case 1:
// sensor is in speed mode (mounted on the rear wheel)
// Cumulative Wheel Revolutions
Integer sumWheelRevs = ValueInterpreter.getIntValue(bytes, ValueInterpreter.FORMAT_UINT32, 1);
// Last Wheel event time
Integer lastWheelEvent = ValueInterpreter.getIntValue(bytes, ValueInterpreter.FORMAT_UINT16, 5);
Log.d(TAG, "Last wheel event detected at " + lastWheelEvent + ", wheel revs = " + sumWheelRevs);
break;
case 2:
// sensor is in cadence mode (mounted on the crank)
// Last Crank Event Time
// Cumulative Crank Revolutions
break;
}
}
我还有一段工作代码可以读取 ONE 特征,但如何处理特征列表?
.flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(Constants.DEVICE_HARDWARE))
.subscribe(
characteristicValue -> {
String deviceHardware = ValueInterpreter.getStringValue(characteristicValue, 0);
Log.d(TAG, "characteristicValue deviceHardware = " + deviceHardware);
},
throwable -> {
// Handle an error here.
}
)
常量定义如下:
public static final UUID CSC_MEASURE = UUID.fromString("00002a5b-0000-1000-8000-00805f9b34fb");
我尝试整合here 中提供的答案,但代码不再编译。此外,代码应结合多达 12 个特征(UUID 到 Int/String/Boolean 的简单映射)。我曾经通过创建BluetoothGattCallback 的子类来获得工作代码,但我的代码越来越难以使用标准的 Android 蓝牙类进行维护。
【问题讨论】:
标签: android bluetooth-lowenergy reactivex bluetooth-gatt rxandroidble