【发布时间】:2019-10-11 00:59:48
【问题描述】:
我有一个用于发送消息缓冲区的消息线程。在特征写入下一条消息之前,每条消息都会排队等待onCharacteristicWrite 成功发送。特征也设置为WRITE_TYPE_NO_RESPONSE,因此消息缓冲区队列在特征写入调用之间非常快(大约 0-7 毫秒)。
主要问题:“卡住”特性
在大多数情况下,这很有效。当有大量消息时,似乎会出现问题(可能在消息较少时发生,但在发送大量消息时更明显)。发生的情况是 writeCharacteristic 将被调用,并且特性似乎被锁定,因为 onCharacteristicChanged 不再读取任何新数据,也无法访问 onCharacteristicWrite。
我注意到的其他事项:
在每个
characteristicWrite之后添加 5-10 毫秒的睡眠延迟似乎 帮助,但我不明白为什么当onCharacteristicWrite返回成功时蓝牙 GATT 对象需要延迟。有时我会在
onConnectionStateChange收到回调,状态为 8,设备超出范围。不过,这并不总是发生。- 有时
characteristicWrite返回假;但是,它也可以在进入上述“阻塞特性”状态之前返回 true
消息线程代码:
private boolean stopMessageThread = false;
private boolean characteristicWriteSuccessful = true;
private ArrayList<byte[]> messageQueue = new ArrayList<byte[]>();
private Thread messageThread = new Thread( new Runnable() {
private long lastTime = 0;
private int count = 0;
@Override
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopMessageThread) {
if(messageQueue.size() != 0 && characteristicWriteSuccessful) {
Log.i(TAG, ""+(System.currentTimeMillis()-lastTime));
Log.i(TAG, "Queue count: "+messageQueue.size());
characteristicWriteSuccessful = false;
byte[] message = messageQueue.remove(0);
customCharacteristic.setValue(message);
boolean status = bluetoothGatt.writeCharacteristic(customCharacteristic);
Log.i(TAG, "write characteristic status "+status);
lastTime = System.currentTimeMillis();
//sleep(10); // this kinda helps but can still throw the error
}
}
}
});
【问题讨论】:
-
首先,请不要通过繁忙的循环来最大化 CPU。二、onCharacteristicChanged在这里起什么作用?第三,onCharacteristicWrite 不能“返回”false,因为它是一个回调。四、你的characteristicWriteSuccessful 必须是volatile。
-
@Emil 当然,我将更改繁忙循环,第二个,onCharacteristicChanged 从我的设备接收数据,当我收到此错误时不再这样做。第三,我的意思是“characteristicWrite”函数,而不是回调。我也会更改布尔值。
-
writeCharacteristic 在已经有另一个挂起的 GATT 操作时返回 false。在此写入线程运行时,您是否执行任何其他请求?对于 onCharacteristicChanged,它是您收到通知的另一个特征吗?
-
没有其他请求。与 oncharacteristicChanged 相同,“customCharacteristic”。
-
由于 Android stackoverflow.com/questions/38922639/… 中的竞争条件,我建议具有两个特征。 writeCharacteristic 通常返回 false,因为您还有另一个请求待处理 android.googlesource.com/platform/frameworks/base/+/master/core/…
标签: java android bluetooth-lowenergy bluetooth-gatt