How to subscribe to multiple BluetoothLE Character

2019-08-15 00:27发布

问题:

I am developing an Android app which should subscribe to multiple BLE characteristics.

But whatever I do, I receive only the updated values from one characteristic.

Here is the code:

BluetoothGattCharacteristic characteristicVel = gatt.getService(BleDefinedUUIDs.Service.KOMMMODUL_SERVICE).getCharacteristic(BleDefinedUUIDs.Characteristic.VELOCITY);
                gatt.setCharacteristicNotification(characteristicVel, true);
                BluetoothGattDescriptor descriptorVel = characteristicVel.getDescriptor(
                        BleDefinedUUIDs.Descriptor.CHAR_CLIENT_CONFIG);
                descriptorVel.setValue(BleDefinedUUIDs.Descriptor.ENABLE_NOTIFICATION_VALUE);
                gatt.writeDescriptor(descriptorVel);

            BluetoothGattCharacteristic characteristicAcc = gatt.getService(BleDefinedUUIDs.Service.KOMMMODUL_SERVICE).getCharacteristic(BleDefinedUUIDs.Characteristic.ACCELERATION);
            gatt.setCharacteristicNotification(characteristicAcc, true);
            BluetoothGattDescriptor descriptorAcc = characteristicAcc.getDescriptor(
                    BleDefinedUUIDs.Descriptor.CHAR_CLIENT_CONFIG);
            descriptorAcc.setValue(BleDefinedUUIDs.Descriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptorAcc);

Whatever I do I get only the velocity data. If I change the order of the two blocks I get acceleration only but no more velocity data.

What have I to do in order to subscribe to many characteristics at once?

Thanks in advance

Reto

回答1:

To get descriptors to write one after another, please wait for the callback from a descriptor write before starting the next one.



回答2:

For all the future readers, here is how to do it:

List<BluetoothGattCharacteristic> characteristics = GetCharacteristicsWithNotifications(gatt);

subscribeToCharacteristics(gatt);

private void subscribeToCharacteristics(BluetoothGatt gatt) {
    if(characteristics.size() == 0) return;

    BluetoothGattCharacteristic characteristic = notifyCharacteristics.get(0);
    gatt.setCharacteristicNotification(characteristic, true);
    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);

    UUID uuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(uuid);
    if(descriptor != null) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        gatt.writeDescriptor(descriptor);
    }
}

@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    super.onDescriptorWrite(gatt, descriptor, status);

    characteristics.remove(0);
    subscribeToCharacteristics(gatt);
}