藍牙BLE與設備交互研發錄一

本文建立在官方demo BluetoothLeGatt上進行探索。在BluetoothLeGatt工程代碼基礎上對藍牙設備進行連接與發送指令,並且接收到藍牙設備發回來的指令。

搜索藍牙設備

mBluetoothAdapter.startLeScan(mLeScanCallback);
 mBluetoothAdapter.stopLeScan(mLeScanCallback);
分別是這兩個代碼,demo裏面有,這裏就不要細講,回調看mLeScanCallback。

連接藍牙設備

Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
然後在回調mServiceConnection 裏面的onServiceConnected方法執行連接藍牙設備就行了。
如:
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
mDeviceAddress爲藍牙設備的mac地址
mGattCallback是回調

下面開始描述一個BLE設備進行開發的具體步驟。

設備的UUID

對於一種設備來說,需要知道它對應的UUID才能讀寫。一般先提前瞭解清楚產品的下面4個信息。

SERVICE_UUID
WRITE_UUID
READ_UUID
CLIENT_CHARACTERISTIC_CONFIG  

比如:
微信硬件規定的

SERVICE_UUID爲0000FEE7-0000-1000-8000-00805F9B34FB
WRITE_UUID爲0000FEC7-0000-1000-8000-00805F9B34FB
READ_UUID爲0000FEC8-0000-1000-8000-00805F9B34FB
CLIENT_CHARACTERISTIC_CONFIG  是一個固定值:00002902-0000-1000-8000-00805f9b34fb

能使讀characteristic

以下代碼片段描述了怎麼去使能對應的特徵。
流程:先找到產品對應的自定義service,在從service裏拿到讀的characteristic,然後根據characteristic的特性使能characteristic 的Notification模式或者INDICATION模式,這時候就可以接收藍牙設備發過來的信息了。

public void enableRxNotification() 
    BluetoothGattService service = mBluetoothGatt.getService(SERVICE_UUID);
    BluetoothGattCharacteristic readCharacteristic = service.getCharacteristic(READ_UUID);
    BluetoothGattDescriptor descriptor = readCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
    if ((readCharacteristic.getProperties() | BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        mBluetoothGatt.setCharacteristicNotification(readCharacteristic, true);
        mBluetoothGatt.writeDescriptor(descriptor);
     else if ((readCharacteristic.getProperties() | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) 
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.setCharacteristicNotification(readCharacteristic, true);
        mBluetoothGatt.writeDescriptor(descriptor);
}

寫數據

簡單來說就是寫characteristic,以下代碼片段描述了怎麼給一個藍牙設備寫數據。
流程:先找到產品對應的自定義service,在從service裏拿到寫的characteristic,然後設置characteristic的值,通過藍牙把characteristic的數據發到設備上。如果發送成功,就會回調在onCharacteristicWrite裏,這是能不能接收到信息取決了發過去的指令對不對,換句話說這時候沒法判斷髮送的指令對不對。
public boolean writeCharacter(String value) 
{           BluetoothGattService service = mBluetoothGatt.getService(SERVICE_UUID);
    BluetoothGattCharacteristic writeCharacteristic = service.getCharacteristic(WRITE_UUID);

    writeCharacteristic.setValue(Utils.hexStringToBytes(value));
    return mBluetoothGatt.writeCharacteristic(writeCharacteristic);
}

瞭解指令格式

不是隨便寫一點數據藍牙設備就會回信息過來的,需要滿足一定的指令格式,這個就得讀藍牙產品的一些文檔,看看裏面的指令格式。如果發送的指令格式是正確的,藍牙設備收到處理後就會回信息過來,這時,在onCharacteristicChanged
或者onCharacteristicRead裏就可以看到數據的回調了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章