我能通过连接外部BLE设备发送最多20字节的数据。如果我要发送超过20字节的数据,该怎么办?我读到了我们必须要么分段数据,要么将特征值拆分为所需的部分。如果我假设我的数据是32字节,你能告诉我需要对代码进行哪些更改才能使其工作吗?以下是我代码中的必要片段:
public boolean send(byte[] data) {
if (mBluetoothGatt == null || mBluetoothGattService == null) {
Log.w(TAG, "BluetoothGatt not initialized");
return false;
}
BluetoothGattCharacteristic characteristic =
mBluetoothGattService.getCharacteristic(UUID_SEND);
if (characteristic == null) {
Log.w(TAG, "Send characteristic not found");
return false;
}
characteristic.setValue(data);
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
return mBluetoothGatt.writeCharacteristic(characteristic);
}
这是我用来发送数据的代码。在下面的onclick事件中使用了“send”函数。
sendValueButton = (Button) findViewById(R.id.sendValue);
sendValueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = dataEdit.getText().toString();
yableeService.send(text.getBytes());
}
});
当字符串text
大于20字节时,只有前20字节被接收。如何纠正?为了测试发送多个特征,我尝试了这个:
sendValueButton = (Button) findViewById(R.id.sendValue);
sendValueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = "Test1";
yableeService.send(text.getBytes());
text = "Test2";
yableeService.send(text.getBytes());
text = "Test3";
yableeService.send(text.getBytes());
}
});
但我只收到了“Test3”,也就是最后一个特征,我犯了什么错误?我是BLE的新手,请忽略任何愚蠢的问题。
编辑:
在接受答案之后,对于以后查看此内容的任何人。
有两种方法可以完成这个过程。
1. 将您的数据拆分并像所选答案一样使用循环写入。
2. 拆分您的数据并使用回调来写入,即onCharacterisitcWrite()
。如果在写入过程中出现任何错误,这将使您免受错误的影响。
但是,在写入之间使用Thread.sleep(200)
非常重要,如果您只是写入而不等待来自固件的响应。这将确保您的所有数据都到达。如果没有sleep
,我总是得到最后一个数据包。如果您注意到已接受的答案,他也在写入之间使用了sleep
。
yableeService.send(text.getBytes());
三次。但是只有第一个特征被发送出去了,之后的内容都没有发送成功。如果我做错了,请告诉我应该怎么做? - Ankit Aggarwal