There's something I'm not quite getting with using Gatt to communicate with a BLE device. According to this: 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(){....})
I can connect to a BLE device and give it a callbacks object to be notified on stuff like onCharacteristicRead and onCharacteristicWrite
What I'm not getting is how do which write corresponds to which read callback?
This method signatures are:
public void onCharacteristicRead (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
public void onCharacteristicWrite (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
so if I do:
BluetoothGattCharacteristic char = gatt.getService(UART_SERVICE_UUID).getCharacteristic(UART_TX_CHARACTERISTIC_UUID);
char1.setValue("command1");
gatt.writeCharacteristic(char);
char1.setValue("command2");
gatt.writeCharacteristic(char);
in the onCharacteristicRead callback, how do I know if the characteristic.getStringValue() is for command1 or command2?
Thanks!
In this implementation you should wait for the
onCharacteristicWrite
after the first write before issuing the next write operation. But this holds if you did not change the write type withsetWriteType (int writeType)
from the defaultWRITE_TYPE_DEFAULT
, which calls back on write operations. You might need to keep state for these ops.Another option is to have a command code (e.g. 1 byte) in the response so you can map it to the command.