问题描述
我正在开发一个使用BLE在设备之间交换数据的应用程序.
I'm working on an app that exchange data between devices using BLE.
为了获得更好的性能,在连接两个设备之后,我正在协商增加MTU,以便通过BLE交换更大的数据包.
In order to get better performance, after connecting two devices I'm negotiating to increase the MTU in order to exchange bigger data packages over BLE.
连接BluetoothDevice并读取所有服务和特征后,我请求使用以下方法增加MTU:
Once the BluetoothDevice is connected and all services and characteristics are read, I request to increase the MTU using:
private void requestMtu() {
//gatt is a BluetoothGatt instance and MAX_MTU is 512
this.gatt.requestMtu(MAX_MTU);
}
此后,在BluetoothGattCallback
实现上,我获得了MTU请求成功,并且新的MTU与我请求的MTU匹配:
After that, on the BluetoothGattCallback
implementation I get the MTU request succeeded and the new MTU matches the one I requested:
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
this.supportedMTU = mtu;
}
}
问题是,当我尝试发送512字节的数据包时,在另一端(onCharacteristicWriteRequest:
)我得到509字节.
The problem is, when I try to send a data package of 512 bytes, on the other side (onCharacteristicWriteRequest:
) I get 509 bytes.
有什么想法吗?
推荐答案
MTU大小表示可在ATT负载中使用的最大字节数. ATT写入请求有效负载(正在发送以进行特征写入)如下所示:
The MTU size represents maximum amount of bytes which can be utilized in an ATT payload. An ATT write request payload (which is being send for a characteristic write) looks like the following:
1个字节的属性操作码2字节属性句柄N字节属性值
1 byte Attribute Opcode2 byte Attribute HandleN Byte Attribute Value
由于MTU大小为512字节,所以最大大小N可以为512-3 = 509字节
Since the MTU size is 512 bytes, the maximum size N can be is 512 - 3 = 509 bytes
这篇关于BluetoothGatt:协商新的MTU成功,但是无法使用新的大小(3字节差)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!