2016-12-27 71 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。