BLE通信(续)

来源:互联网 发布:软件开发需求阶段 编辑:程序博客网 时间:2024/05/18 07:20

本文接着上面一篇文章进行的说明,继续通信过程。

上文已经说明了,对于一个蓝牙设备device,可以有多个service,每个service有多个characteristic,每个characteristic又包含多个descriptor,而通信一般使用characteristic进行。

那么怎么通信呢,这个需要获取characteristic的property,

BluetoothGattCharacteristic的property一般的说明见下:

 /**     * Characteristic property: Characteristic is readable.     */    public static final int PROPERTY_READ = 0x02;    /**     * Characteristic property: Characteristic can be written without response.     */    public static final int PROPERTY_WRITE_NO_RESPONSE = 0x04;    /**     * Characteristic property: Characteristic can be written.     */    public static final int PROPERTY_WRITE = 0x08;    /**     * Characteristic property: Characteristic supports notification     */    public static final int PROPERTY_NOTIFY = 0x10;    /**     * Characteristic property: Characteristic supports indication     */    public static final int PROPERTY_INDICATE = 0x20;

当然这是16进制表示,比如PROPERTY_NOTIFY表示10进制的16.

如果property是read,那么这个characteristic可以读取内容,如果为write,那么可以写入内容,但都没有notirication,而如果一个characteristic的property为notiry,那么当characteristic执行写操作的时候,之后会调用onCharacteristicWrite,然后便会调用onCharacteristicChanged,而回调中会携带返回内容。

上面的characteristic貌似底下需要有至少一个descriptor,否则无法执行写操作,这个结论待验证。目前只是一个猜测。

所以,如果想要回调,只需要调用相关的characteristic的setnotification即可。

执行setnotification的时候,需要注意执行次序和时间间隔,最好每一个走完回调onDescriptorWrite才能执行下一个,不然连续执行,可能会发生问题。

这里再说另一个问题,关于设置characteristic的descriptor的问题,

BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(UUIDDes));if (descriptor != null) {Log.w(TAG, "setCharacteristicNotification   writeDescriptor===");descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);return (bluetoothGatt.writeDescriptor(descriptor));} else {Log.e(TAG, "descriptor is null");return false;}

这里用的是ENABLE_INDICATION_VALUE,实际上,可以有几个值:

/**     * Value used to enable notification for a client configuration descriptor     */    public static final byte[] ENABLE_NOTIFICATION_VALUE = {0x01, 0x00};    /**     * Value used to enable indication for a client configuration descriptor     */    public static final byte[] ENABLE_INDICATION_VALUE = {0x02, 0x00};    /**     * Value used to disable notifications or indicatinos     */    public static final byte[] DISABLE_NOTIFICATION_VALUE = {0x00, 0x00};

这几个值之间有什么区别,目前还不是很清楚,待验证。

不过感觉ENABLE_INDICATION_VALUE比ENABLE_NOTIFICATION_VALUE通知更高,带响应的通知?不理解。。。从目前看,ENABLE_NOTIFICATION_VALUE就够用了。


更多蓝牙相关文章请参考http://m.blog.csdn.net/article/details?id=50504406链接下面的

相关博文

下面的列表进行查看。


这里特别说明一下http://blog.csdn.net/chenxh515/article/details/45723299这篇文章,

说的是蓝牙的UUID的常用定义。

另外贴一篇eoe的文章,说的也不错,总之,ble很多问题都需要调试解决优化。文章见下:

http://www.eoeandroid.com/thread-573261-1-6.html?_dsign=7fe4649e

0 0
原创粉丝点击