How could i achieve maximum thread safety with a r

2019-06-16 19:45发布

问题:

I am communicating with a BLE device that sends me lots of data via one characteristic. The same CH 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 CH 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 ?

回答1:

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.



回答2:

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.