Android 低功耗蓝牙获取对特定请求的响应

tal*_*ari 5 android bluetooth bluetooth-lowenergy gatt

使用 Gatt 与 BLE 设备进行通信时,我不太明白。根据这个:https : //developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback)

BluetoothGatt gatt = device.connectGatt(context,true,new BluetoothGattCallback(){....})
Run Code Online (Sandbox Code Playgroud)

我可以连接到一个 BLE 设备并给它一个回调对象,以便在 onCharacteristicRead 和 onCharacteristicWrite 之类的东西上得到通知

我没有得到的是哪个写入对应哪个读取回调?

此方法签名是:

public void onCharacteristicRead (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
public void onCharacteristicWrite (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
Run Code Online (Sandbox Code Playgroud)

所以如果我这样做:

BluetoothGattCharacteristic char = gatt.getService(UART_SERVICE_UUID).getCharacteristic(UART_TX_CHARACTERISTIC_UUID);
char1.setValue("command1");
gatt.writeCharacteristic(char);
char1.setValue("command2");
gatt.writeCharacteristic(char);
Run Code Online (Sandbox Code Playgroud)

在 onCharacteristicRead 回调中,我怎么知道characteristic.getStringValue() 是用于command1 还是command2?

谢谢!

Rob*_*man 5

在使用BluetoothGatt.writeCharacteristic()和相关BluetoothGatt方法时,有一些重要的事情需要了解。

  1. 请注意writeCharacteristic()(以及 的许多其他方法BluetoothGatt)返回一个布尔值。当结果为 false 时,表示操作未成功启动。什么时候发生?请参阅下一项。

  2. 使用一个BluetoothGatt对象,不可能同时发起两个操作。启动第二个的调用将失败并返回 false。调用后writeCharacteristic(),代码必须等待回调响应 ( onCharacteristicWrite) 才能发出另一个写入。在这个问题的示例代码中,writeCharacteristic()由于这个原因,第二次调用几乎肯定会返回 false。

通过这种方式,如果每个 BluetoothGatt 操作都等待先前发出的命令的回调,则您可以成功地配对命令启动和回调——实际上您是被迫的。


小智 0

在此实现中,您应该在第一次写入之后等待,onCharacteristicWrite然后再发出下一个写入操作。setWriteType (int writeType)但是,如果您没有使用默认值更改写入类型WRITE_TYPE_DEFAULT,则此情况成立,默认值会回调写入操作。您可能需要保留这些操作的状态。

另一种选择是在响应中包含命令代码(例如 1 个字节),以便您可以将其映射到命令。