[英]How to send more than 20 bytes data over ble in android?
我试图使用简单的循环发送超过33个字节,是否有人知道如何通过android ble发送超过20个字节的数据。
if(!mConnected) return;
for (int i = 0; i<str.length;i++) {
if(str[i] == str[str.length -1]){
val = str[i]+"\n";
}else {
val = str[i] + "_";
}
System.out.println(val);
mBluetoothLeService.WriteValue(val);
}
通过将数据拆分为20字节数据包并在发送每个数据包之间实现短延迟(即使用sleep()
),可以轻松实现通过BLE发送超过20个字节。
这是我正在处理的项目的一小段代码,它以byte[]
的形式获取数据,并以20字节的块的形式将其拆分为相同的数组( byte[][]
),然后发送它是另一种逐个传输每个数据包的方法。
int chunksize = 20;
byte[][] packets = new byte[packetsToSend][chunksize];
int packetsToSend = (int) Math.ceil( byteCount / chunksize);
for(int i = 0; i < packets.length; i++) {
packets[i] = Arrays.copyOfRange(source,start, start + chunksize);
start += chunksize;
}
sendSplitPackets(packets);
以下是另外两个关于如何实现这一目标的非常好的解释:
您可以发送超过20个字节的数据,而不会分成块并包括延迟。 您尝试编写的每个特征都分配了MTU值。 它是您可以一次写入的字节数。 在连接期间,MTU值被交换,您可以一次写入多个字节。 您可以增加服务器端的mtu值(最大512字节)并一次性发送那么多字节。
对于Android,您可能希望在使用服务器连接后手动请求mtu
requestMtu(int mtu)
根据您发送的mtu值返回true或false。 它会给onMtuChanged回调,其中Android设备和服务器协商最大可能的MTU值。
onMtuChanged(BluetoothGatt gatt,int mtu,int status)
并且您可以在此功能中设置MTU值,并且可以一次发送超过20个字节。
一些嵌入式蓝牙LE实现将特征的大小限制为20个字节。 我知道Laird BL600系列就是这么做的。 这是Laird模块的限制,即使BLE规范要求最大长度更长。 其他嵌入式BLE解决方案也有类似限制。 我怀疑这是你遇到的限制。
我没有为每个块使用sleep,而是为我的应用程序发送了一个更好,更有效的方法来发送超过20位的数据。
数据包将在触发onCharacteristicWrite()后发送。 我刚刚发现外围设备(BluetoothGattServer)发送sendResponse()方法后会自动触发此方法。
首先,我们必须使用此功能将数据包数据转换为块:
public void sendData(byte [] data){
int chunksize = 20; //20 byte chunk
packetSize = (int) Math.ceil( data.length / (double)chunksize); //make this variable public so we can access it on the other function
//this is use as header, so peripheral device know ho much packet will be received.
characteristicData.setValue(packetSize.toString().getBytes());
mGatt.writeCharacteristic(characteristicData);
mGatt.executeReliableWrite();
packets = new byte[packetSize][chunksize];
packetInteration =0;
Integer start = 0;
for(int i = 0; i < packets.length; i++) {
int end = start+chunksize;
if(end>data.length){end = data.length;}
packets[i] = Arrays.copyOfRange(data,start, end);
start += chunksize;
}
在我们准备好数据之后,我将迭代放在这个函数上:
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if(packetInteration<packetSize){
characteristicData.setValue(packets[packetInteration]);
mGatt.writeCharacteristic(characteristicData);
packetInteration++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.