本文建立在官方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里就可以看到数据的回调了