Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3907764
  • 博文数量: 408
  • 博客积分: 10227
  • 博客等级: 上将
  • 技术积分: 9820
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-17 21:48
个人简介

非淡泊无以明志,非宁静无以致远

文章存档

2022年(1)

2021年(1)

2020年(2)

2019年(5)

2018年(4)

2017年(3)

2016年(24)

2015年(8)

2014年(7)

2013年(3)

2012年(1)

2011年(23)

2010年(179)

2009年(147)

分类: Android平台

2016-09-07 16:35:08

1. 问题引言:

想在gatt client上(一般是手机上)传输长一点的数据给gatt server(一般是一个Bluetooth smart设备,即只有BLE功能的设备),但通过

[java]

writeCharacteristic(BluetoothGattCharacteristic) 

来写的时候发现最多只能写入20byte的数据。

这篇文章会回答下面几个问题:

1)为什么会是20

2)如何突破20

3)如何更优雅的来实现?

2. 为什么为限制成20个字节?

core spec里面定义了ATT的默认MTU23bytes, 除去ATTopcode一个字节以及ATThandle 2个字节之后,剩下的20个字节便是留给GATT的了。

考虑到有些Bluetooth smart设备功能弱小,不敢太奢侈的使用内存空间,因此core spec规定每一个设备都必须支持MTU23

在两个设备连接初期,大家都像新交的朋友一样,不知对方底细,因此严格的按照套路来走,即最多一次发20个字节,是最保险的。

由于ATT的最大长度为512byte

因此一般认为MTU的最大长度为512byte就够了,再大也没什么意义,你不可能发一个超过512ATT的数据。

所以ATTMTU的最大长度可视为512bytes

3. 如何突破20

很简单嘛,改变传输的ATTMTU就行了,大家经过友好的协商,得到双方都想要的结果,是最好的。在Android上(API 21),改变ATT MTU的接口为:

public boolean requestMtu (int mtu)    

Added in API level 21 

Request an MTU size used for a given connection. 

When performing a write request operation (write without response), the data sent is truncated to the MTU size. This function may be used to request a larger MTU size to be able to send more data at once. 

 A onMtuChanged(BluetoothGatt, int, int) callback will indicate whether this operation was successful. 

  Requires BLUETOOTH permission. 

 

Returns 

true, if the new MTU value has been requested successfully 

大声的说出来你想要一下子传多少,调用上面的接口就可以了,然后在下面的函数中看最终结果(当然了,如果你的peripheral申请改变MTU并且成功的话,那这个回调也会被调用):

@Override 

public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { 

    super.onMtuChanged(gatt, mtu, status); 

 

    if (status == BluetoothGatt.GATT_SUCCESS) { 

        this.supportedMTU = mtu;//local var to record MTU size 

    } 

之后你就可以快乐的发送supported  MTU-3的长度的数据了。

                                                                                                

4. 如何优雅的来实现?

万一对方设备不同意你的请求怎么办?

对于app来说,一般是知道自己要最大发送多少数据的,例如一次要发100bytes,那么就首先试试申请一下103,失败的话,则申请一下53,即二分法,剩下的只能自己分段拆着发了。

一般来讲,app的开发者和对端设备的开发者都是同一伙儿人,这是好事,他们可以根据自己设备的硬件情况,来商量MTU应该是多少。

 

阅读(19296) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~