2016-12-27 76 views
0

我正在分析来自android的一个示例,它解释了Android上的蓝牙低能量使用情况。我发现了下面的代码,它设置了一个通知,但是我不能在ifs中使用一个属性整数和条件来获取这里发生的事情。有人能解释一下吗?阅读蓝牙低能耗属性(阅读,通知) - 它是如何工作的?

无论如何,也许你有一些更好的源代码,它可以解释android上的ble概念 - 在这里工作是什么?官方Android教程是真穷,和蓝牙官方页面是给几乎没有...

@Override 
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, 
          int childPosition, long id) { 
    if (mGattCharacteristics != null) { 
     final BluetoothGattCharacteristic characteristic = 
       mGattCharacteristics.get(groupPosition).get(childPosition); 
     final int charaProp = characteristic.getProperties(); 
     if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) { 
      // If there is an active notification on a characteristic, clear 
      // it first so it doesn't update the data field on the user interface. 
      if (mNotifyCharacteristic != null) { 
       mBluetoothLeService.setCharacteristicNotification(
         mNotifyCharacteristic, false); 
       mNotifyCharacteristic = null; 
      } 
      mBluetoothLeService.readCharacteristic(characteristic); 
     } 
     if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { 
      mNotifyCharacteristic = characteristic; 
      mBluetoothLeService.setCharacteristicNotification(
        characteristic, true); 
     } 
     return true; 
    } 
    return false; 
} 
+0

该样本实际上以各种可能的方式被打破。如果你只是搜索互联网,可能还有很多其他的例子。 – Emil

+0

@Emil,是的,有其他可能的例子,但我试图找到一些 - 他们是复杂的另一种方式。其中很多是用不同的方式写的。我找到的例子/教程都没有解释BLE的一些基础知识,例如从某些位读取等等,或者仅仅从16位创建中解释基本的UUID。 – Krystian

回答

0

你可以尝试阅读蓝牙技术规范(https://www.bluetooth.com/specifications/adopted-specifications,Core版本5.0),第3部分G.只是注意,当Android提取属性句柄。

然而,大多数人做的是写一个为特定硬件设计的应用程序,即假设gatt db是已知的。

为了获得代表服务,特性和描述符的对象,请调用gatt.discoverServices()。结果将使用onServicesDiscovered()回调异步返回。这应该在每次设备连接时完成(在newState为GATT_CONNECTED时,在onConnectionStateChange回调中)。

要写入特性,首先使用setValue方法在BluetoothGattCharacteristic对象上设置值,然后调用gatt.writeCharacteristic(characteristic)。操作完成后,将调用onCharacteristicWrite。

读操作以类似的方式工作;调用gatt.readCharacteristic(特性),并在调用onCharacteristicRead时结果已准备就绪。使用特征对象上的getValue()来获取值。

要使通知生效,必须先将BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE(0x0001)写入客户端特征配置描述符,以便外设将开始传递通知。您还必须通过调用setCharacteristicNotification来通知Android蓝牙堆栈将通知转发给您的应用程序。

请注意,您一次只能有一个未完成的操作(读/写),这意味着在发出新请求之前您必须等待回调。

如果您知道您正在处理的硬件,通常不需要检查特性属性(characteristic.getProperties())。该位掩码在Bluetooth Core V 5.0规范第3卷第G部分3.3.1.1节中进行了描述,并描述了为每个特性(例如读取,写入,通知)启用了哪些功能。

蓝牙核心V 5.0规范第3卷B部分第2.5.1节中介绍了如何处理16位和128位UUID之间的转换。请注意,Android的客户端库仅使用128位UUID。