Flutter for ble 之set_notification_error, could not locate CCCD descriptor for characteristic分析

一、背景
本文主要给前端同学提供建议,对于android的原生开发者可能过于简单哦。

库:flutter_blue

flutter下使用该库开发ble应用,在调用如下方法时:

      await mCharacteristic.setNotifyValue(true);

出现:

E/flutter (18304): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(set_notification_error, could not locate CCCD descriptor for characteristic: xxxxx, null)
E/flutter (18304): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (18304): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
二、分析
我们可以从log的报错信息:could not locate CCCD descriptor for characteristic 中可以看出报错的原因是没有找到cccd的描述符。

首先我们在github的Issues中找找,找到如下的修复信息:

chaochaox1990 commented on 27 Dec 2019

@chaochaox1990 same error, have you fixed it?
yes I already fixed. All I do just change the value of CCCD.

change the value of CCCD!

那么CCCD是什么的,这里博主给大家介绍一下。在Android中的GATT中的可Notify的characteristic中,有个特征值的描述Descriptor(uuid:00002902-0000-1000-8000-00805f9b34fb),这个值由蓝牙硬件出厂的时候写入,主要作用就是characteristic的权限控制,例如,是否开启等。在Android中的构造方法如下:

public BluetoothGattDescriptor(UUID uuid, int permissions) {
initDescriptor(null, uuid, 0, permissions);
}
一般来说uuid如上,是固定的,参数为其读写等权限。BluetoothGattDescriptor详细介绍

那么为什么插件会报这个错呢,我们进入其源码看一下,在bluetooth_characteristic.dart文件中,可以看到报错代码如下:

await FlutterBlue.instance._channel
.invokeMethod('setNotification', request.writeToBuffer());
这里还是看不出端倪来,那我们去github项目中的源码看一看,这里它调用的是setNotification这个方法。我们来到这个路径:android/src/main/java/com/pauldemarco/flutter_blue/FlutterBluePlugin.java,查看这部分代码:

case "setNotification":
{
byte[] data = call.arguments();
Protos.SetNotificationRequest request;
try {
request = Protos.SetNotificationRequest.newBuilder().mergeFrom(data).build();
} catch (InvalidProtocolBufferException e) {
result.error("RuntimeException", e.getMessage(), e);
break;
}

            BluetoothGatt gattServer;
            BluetoothGattCharacteristic characteristic;
            BluetoothGattDescriptor cccDescriptor;
            try {
                gattServer = locateGatt(request.getRemoteId());
                characteristic = locateCharacteristic(gattServer, request.getServiceUuid(), request.getSecondaryServiceUuid(), request.getCharacteristicUuid());
                cccDescriptor = characteristic.getDescriptor(CCCD_ID);
                if(cccDescriptor == null) {
                    throw new Exception("could not locate CCCD descriptor for characteristic: " +characteristic.getUuid().toString());
                }
            } catch(Exception e) {
                result.error("set_notification_error", e.getMessage(), null);
                return;
            }

            byte[] value = null;

            if(request.getEnable()) {
                boolean canNotify = (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0;
                boolean canIndicate = (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0;
                if(!canIndicate && !canNotify) {
                    result.error("set_notification_error", "the characteristic cannot notify or indicate", null);
                    return;
                }
                if(canIndicate) {
                    value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
                }
                if(canNotify) {
                    value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
                }
            } else {
                value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
            }

            if(!gattServer.setCharacteristicNotification(characteristic, request.getEnable())){
                result.error("set_notification_error", "could not set characteristic notifications to :" + request.getEnable(), null);
                return;
            }

            if(!cccDescriptor.setValue(value)) {
                result.error("set_notification_error", "error when setting the descriptor value to: " + value, null);
                return;
            }

            if(!gattServer.writeDescriptor(cccDescriptor)) {
                result.error("set_notification_error", "error when writing the descriptor", null);
                return;
            }

            result.success(null);
            break;
        }

这部分就是在Android环境下执行的代码。从:

cccDescriptor = characteristic.getDescriptor(CCCD_ID);
if(cccDescriptor == null) {
throw new Exception("could not locate CCCD descriptor for characteristic: " +characteristic.getUuid().toString());
}
static final private UUID CCCD_ID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
可以看出,只要characteristic中没有uuid为"00002902-0000-1000-8000-00805f9b34fb"的descriptor,就会报错,下面notify的关键代码没有执行,因此notify失败。

gattServer.setCharacteristicNotification(characteristic, request.getEnable())
这看似苛刻,其实这就是标准。可以notify的characteristic必须要有uuid为:"00002902-0000-1000-8000-00805f9b34fb"的descriptor。很多硬件都会有这个问题呢?造成这样的原因就是国内蓝牙厂商开发标准参差不齐,要不是没有descriptor,就是descriptor的uuid不是标准的。那么为什么他们不统一标准的,因为在原生开发中,我们一般不这样苛刻,下面给大家看看我们原生一般怎么写的:

String bluetoothGattInfoKey = entry.getKey();
BluetoothGattChannel bluetoothGattInfoValue = entry.getValue();
if (bluetoothGatt != null && bluetoothGattInfoValue.getCharacteristic() != null) {
BreoLog.d("enable-" + bluetoothGattInfoValue.getCharacteristic().getUuid().toString());

            success = bluetoothGatt.setCharacteristicNotification(bluetoothGattInfoValue.getCharacteristic(), enable);
        }
        BluetoothGattDescriptor bluetoothGattDescriptor = null;
        if (bluetoothGattInfoValue.getCharacteristic() != null && bluetoothGattInfoValue.getDescriptor() != null) {
            bluetoothGattDescriptor = bluetoothGattInfoValue.getDescriptor();
        } else if (bluetoothGattInfoValue.getCharacteristic() != null && bluetoothGattInfoValue.getDescriptor() == null) {
            if (bluetoothGattInfoValue.getCharacteristic().getDescriptors() != null
                    && bluetoothGattInfoValue.getCharacteristic().getDescriptors().size() == 1) {
                bluetoothGattDescriptor = bluetoothGattInfoValue.getCharacteristic().getDescriptors().get(0);
            } else {
                bluetoothGattDescriptor = bluetoothGattInfoValue.getCharacteristic()
                        .getDescriptor(UUID.fromString(BleConstant.CLIENT_CHARACTERISTIC_CONFIG));
            }
        }
        if (bluetoothGattDescriptor != null) {
            bluetoothGattInfoValue.setDescriptor(bluetoothGattDescriptor);
            if (isIndication) {
                if (enable) {
                    bluetoothGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                } else {
                    bluetoothGattDescriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                }
            } else {
                if (enable) {
                    bluetoothGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                } else {
                    bluetoothGattDescriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                }
            }
            if (bluetoothGatt != null) {
                bluetoothGatt.writeDescriptor(bluetoothGattDescriptor);
            }
        }

看吧,这两步操作是并行的,有的话就设置一下,没有也很佛系的。

image.png

image.png

这里给大家看两张图,图一的就是不正常的,characteristic是支持notify的,但是没有descriptor。图二就是正常的,有descriptor。

三、解决方案
1、让ble模块的供应商把descriptor写进去(推荐)。

2、修改一下flutter_blue插件,不让它那么苛刻严格。

3、试一试其他插件。pub仓库

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容