藍牙防丟profile
1.TXP(txpower) Characteristic, 設備端需要通過主機控制接口HCI來獲得發射功率參數,並以read屬性提供給master。
2.IAS(immediate alter service), write屬性,供master寫告警級別。當master寫入新的值時,設備端會收到write的回調,其根據告警級別進行相應告警。
- LLS(link loss service),write/read屬性,供master設置鏈路斷開情況下默認的告警級別。
RSSI通過接收端的接口來獲得,並不需要設備端提供service。
以上Characteristic都通過GATT profile提供服務,在藍牙通信協議上,每個Characteristic都會對應一個UUID。
android藍牙BLE接口編程
androidBLE接口在android4.3版本以上提供。
- 判斷當前系統是否支持BLE
getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
返回真表示支持。
- 獲得藍牙適配器類
用戶通過統一的藍牙適配器類BluetoothAdapter來使用BLE API。
先獲得藍牙管理器:
BluetoothManagerbluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE);
再獲得藍牙適配器實例(單體對象):
BluetoothAdaptermBluetoothAdapter = bluetoothManager.getAdapter();
- 啓動手機藍牙硬件功能(相當於在設置界面開啓藍牙功能)
mBluetoothAdapter.enable();
- 開始掃描
BluetoothAdapter.startLeScan(android.bluetooth.BluetoothAdapter.LeScanCallbackcallback)
callback是當掃描到藍牙設備時的回調接口。實現callback中的onLeScan接口:
@Override
public void onLeScan(finalBluetoothDevice device, int rssi, byte[] scanRecord)
其中,device代表掃描到的設備,可以獲得其MAC地址、設備名等等;rssi即信號強度,這是未連接時獲取RSSI的方法;scanRecord代表掃描設備得到的響應參數,ibeacon即通過該參數來獲得廣播內容。
假設String bluetoothAddress = device.getAddress(),獲取藍牙48位MAC地址
- 連接GATT,獲取設備端的UUID服務,並進行數據通信交互
通過MAC地址獲得代表設備端的藍牙設備類
BluetoothDevicedevice = mBluetoothAdapter.getRemoteDevice(bluetoothAddress);
連接GATT
BluetoothGatt mBluetoothGatt = device.connectGatt(android.content.Context context, booleanautoConnect, android.bluetooth.BluetoothGattCallback callback);
Callback是連接GATT之後,所有數據交互的回調入口。分別包括:
1)設備服務發現
@Override
publicvoid onServicesDiscovered(BluetoothGatt gatt, int status)
mBluetoothGatt.getServices()代表設備服務集合,
for (BluetoothGattService gattService : mBluetoothGatt.getServices())
對於每個服務service,用getUuid()可以獲得服務的UUID,getCharacteristics()代表該服務的Characteristic集合。
for(BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics)
對於每個Characteristic,getUuid()獲得UUID,getPermissions()獲得屬性權限,getValue()獲得屬性值。
在該回調中我們只提取感興趣的三個Characteristic的UUID,對於其他的如電池、設備服務等UUID可以不管。
gattCharacteristic_char5_TXP=gattCharacteristic;
2)連接狀態改變
@Override
public voidonConnectionStateChange(BluetoothGatt gatt, int status,intnewState)
有兩種狀態,BluetoothProfile.STATE_CONNECTED代表連接,BluetoothProfile.STATE_DISCONNECTED代表斷開連接。
3)讀回調
@Override
public voidonCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristiccharacteristic, intstatus)
其對應手機端發出讀請求後,當收到設備端的數據時的回調。如
mBluetoothGatt.readCharacteristic(gattCharacteristic_char5_TXP)
4)設備端數據變化回調
這裏對應設備的characteristic的屬性是notify或者indication,即相當手機端訂閱這個characteristic的值變更服務,當設備端的characteristic發生變化時,設備端會主動發出通知給手機端。
@Override
public voidonCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristiccharacteristic)
在回調中獲得新的值characteristic.getValue()。
5)獲取到RSSI值的回調
RSSI在掃描時可以通過掃描回調接口獲得,但是在連接之後要不斷地使用
mBluetoothGatt.readRemoteRssi()向底層驅動發出讀取RSSI請求,當底層獲取到新的RSSI後會進行以下回調:
@Override
public voidonReadRemoteRssi(BluetoothGatt gatt, int rssi, int status)
rssi即是新的信號強度值。
連接後,由於手機和設備端的距離在發生變化,因此要不斷地讀取RSSI,實時計算兩者之間的距離才能保證防丟功能的實現。