蓝牙LE收听多个特征通知

时间:2017-02-09 00:13:06

标签: android bluetooth notifications characteristics

我在与定制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。那么如何从这两个特征中接收通知?谢谢。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

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

boolen isSucsess = mGatt.writeDescriptor(descriptor);

您应该从以下位置等待回调以获取第一个特征:

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

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

例如,您可以扩展BluetoothGattDescriptor并在方法

中运行下一个特征及其描述符处理

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

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

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

最好, StaSer。

相关问题