3

我在与自定义 BLE 传感器板通信的 Android 手机上使用 BLE 应用程序。该板提供了两个特性,加速度和心电图。在电话方面,我想从传感器板接收两个特性的通知。我设置通知的代码:

mGatt.setCharacteristicNotification(ecgChar, true);
            BluetoothGattDescriptor descriptor = ecgChar.getDescriptor(
                    UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mGatt.writeDescriptor(descriptor);
            mGatt.setCharacteristicNotification(accelChar, true);
            descriptor = ecgChar.getDescriptor(
                    UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mGatt.writeDescriptor(descriptor);

但是,我只能收到第一个特征的通知。当我只为一个特性注册通知时,它运行良好。ECG 和加速度的采样频率均为 100Hz。那么如何接收来自这两个特征的通知呢?谢谢。

4

2 回答 2

11

一次只能有一个未完成的 gatt 操作。在这种情况下,您在等待第一个完成之前执行两次 writeDescriptor 调用。您必须等待https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html#onDescriptorWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int)才能发送下一个。

于 2017-02-09T00:30:53.247 回答
2

我同意埃米尔的回答。当您为第一个特征编写描述符时:

boolen isSucsess = mGatt.writeDescriptor(descriptor);

您应该等待来自以下第一个特征的回调:

onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor 描述符, int status) - BluetoothGattCallback 的方法。

只有在那之后,您才应该进行下一个特征及其描述符处理。

例如,您可以扩展 BluetoothGattDescriptor 并在方法中运行下一个特征及其描述符处理

onDescriptorWrite(...) { ... 这里 ...}。

还请注意,有时您应该为所有特征设置通知,然后编写其描述符。我在使用体重秤设备的练习中遇到了这个问题。为了获得重量,我需要为电池、时间、重量设置通知,然后为所有特性编写描述符(等待每个人的回调)。

对于清晰的代码,您最好使用多重交易。

最好的,StaSer。

于 2018-07-10T12:55:57.400 回答