Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I achieve maximum thread safety with a read/write BLE Gatt Characteristic?

I am communicating with a BLE device that sends me lots of data via one characteristic. The same Characteristic is used to send data to the device.

Inside Androids BluetoothGattCharacteristic there are the methods

public byte[] getValue() {
    return mValue;
}

public boolean setValue(byte[] value) {
    mValue = value;
    return true;
}

However, the execution happens from different threads. Android runs about 5 different binder-threads and they call

onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)

I now try to grab the array as first operation in the callback, but it is NOT guaranteed that another thread (not under my control) is setting the array at the same time.

While above seems to do the trick, a more complicated matter is sending data 'against an incoming stream of data'.

I have to use the same Characteristic to send data down to the device, so I setValue() and then BluetoothGatt.writeCharacteristic.

public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic) {
// some null checks etc

//now it locks the device
synchronized(mDeviceBusy) {
    if (mDeviceBusy) return false;
    mDeviceBusy = true;
}

//the actual execution

return true;
}

I will then at some point receive a callback from some thread

onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) 

However, when I grab the value and try to check if it is what I wanted to send, sometimes it already is a received package that has just been updated from some other thread.

How could i make this more thread-safe without having access to Androids BLE API or the stack etc ?

like image 507
NikkyD Avatar asked Aug 12 '16 16:08

NikkyD


People also ask

What is a GATT characteristic?

A GATT characteristic is a basic data element used to construct a GATT service, BluetoothGattService . The characteristic contains a value as well as additional information and optional GATT descriptors, BluetoothGattDescriptor .

What is GATT in BLE?

GATT is an acronym for the Generic ATTribute Profile, and it defines the way that two Bluetooth Low Energy devices transfer data back and forth using concepts called Services and Characteristics.

What is characteristic in BLE?

A characteristic object represents a characteristic of a Bluetooth® Low Energy peripheral device. If read or write are supported in the object Attributes property, you can read characteristic values using read or you can write characteristic values using write .

What is GATT service on Android?

The GATT profile is a general specification for sending and receiving short pieces of data known as "attributes" over a BLE link. All current BLE application profiles are based on GATT.


2 Answers

Before SDK27, it appears to be impossible to have reliable full duplex communication over a single characteristic - using the public API.

Quite vexing.

There appears to be a way, though, if you're willing to cheat a little. (There is probably more than one way to cheat; the one described below is fairly low-impact.)

The problem is the use of the mValue field in BluetoothGattCharacteristic for two conflicting purposes - send and receive. It is fairly bad API design; one API-level fix would have been to introduce another field, so that there would be one for each direction. Another would have been to not use the setValue() method when sending data, but instead provided the data in question as a parameter to writeCharacteristic() (though this is complicated by the fact that the value field may be encoded during get/set, supporting several data types). However, it appears that the API maintainers have chosen a different path.

Anyway - to fix the problem, ensure that the received value and the value-to-be-sent are stored in different locations. More specifically, in the value fields of two different instances of BluetoothGattCharacteristic.

Now, cloning a BGC is not possible using the official API. Using the public constructor, you can get an instance which has all fields set except service and instanceId. These have public getters - to set them, use reflection to access setService() and setInstanceId() - this is the cheaty part.

I have tested this approach[1], and it appears to work as desired. :-)

[1] A variation of this approach, in fact; in newer SDK versions, the class in question is Parcelable, so when possible I clone the object through Parcel-serialization, just in case future implementations add more fields. This takes care of everything except the service field, which you still need to set using reflection.

like image 62
eriksoe Avatar answered Nov 07 '22 09:11

eriksoe


In SDK27, the onNotify() callback function in BluetoothGatt.java was updated to call BOTH BluetoothGattCharacteristic.setValue() and BluetoothGattCallback.onCharacteristicChanged() in the Runnable's run().

This change allows us to force all calls to BluetoothGattCharacteristic.setValue() - both for our outbound writing to the characteristic and the inbound notifications - onto the same thread, which eliminates the race condition corrupting the BluetoothGattCharacteristic.mValue;

  1. Create a HandlerThread
  2. Create a Handler attached to your HandlerThread
  3. Pass your Handler into BluetoothDevice.connectGatt() - congratulations, when a notify is received the setValue() and onCharacteristicChanged() will be called on your HandlerThread.
  4. When you want to write to the characteristic, post your setValue() and writeCharacteristic() to your HandlerThread via your Handler

Now all the function calls that were involved in the race condition are being executed on the same thread, eliminating the race condition.

like image 39
Michael Fomin Avatar answered Nov 07 '22 09:11

Michael Fomin