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
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.