能够经过如下两点加速蓝牙链接:
一、更新链接参数
interval:链接间隔(connection intervals ),范围在 7.5 毫秒 到 4 秒。
latency:链接延迟
。。。 还有一些其它参数.
Android API不提供具体的参数值, 只提供了三个常量:
CONNECTION_PRIORITY_HIGH
CONNECTION_PRIORITY_BALANCED
CONNECTION_PRIORITY_LOW_POWER
从Android的源码找到对应的参数:
在发起链接请求时,经过BluetoothGatt实例发起更新:
mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
二、在请求链接时,设置自动链接标识为 false。
自动链接标识为true 时,虽然能提升链接成功的几率,可是会致使链接时间加长.
具体解释以下:
链接失败的问题
因为Android的蓝牙协议栈bluedroid 在低版本存在一些bug,如当链接的时候,callback 返回 status=133 的状况. 出现这种状况的缘由应该手机APP频繁的操做链接以及断开。解决的方式能够参考如下几种:
一、当断开链接时,调用mBluetoothGatt.disconnect(); 该方式只是断开链接,并无真正释放资源,能够在 disconnect 的回调里调用 mBluetoothGatt.close()
二、当链接同一台设备时,可经过判断地址是否同样,使用mBluetoothGatt.connect(); 但这方式彷佛会致使链接放慢.
三、出现这种状况,delay 一下子,而后再重连. 只能经过屡次重连方式。
四、从google 回来的一些资料显示,当手机断开链接 mBluetoothGatt.disconnect(); 甚至是mBluetoothGatt.close()。 app蓝牙只是给蓝牙服务发送了一个断开链接,蓝牙服务是以队列的形式去处理它. 要完全断开该链接,能够经过让对方设备(从设备)也主动断开。我尝试过这种方式,确实解决了我当前的问题.
connection fail 资料:
status=133, 对于状态的错误:GATT_ERROR
connections fail :
1)If your connections fail to happen, the BLE peripheral may be sending packets too slowly, or their signal level may be too low. This can be an issue with output power, range between the devices, interference, or other issues.
2)The BLE connection settings are some of the most critical parameters to understand in BLE. Connection interval, slave latency and other settings are sent upon during a connection, and they can tell you a lot about what the devices agree to. If you’re having connection problems, it can be that the two devices don’t agree on the parameters (and the central device disconnects).
另外能够查看一下Android源码 packages\apps\Bluetooth 目录下 bluetooth APP 的源码,看处理的方式.
BLE 链接过程:
注:图中M表明手机,S表明设备B,M->S表示手机将数据包发给设备B,即手机开启Tx窗口,设备B开启Rx窗口;S->M正好相反,表示设备B将数据包发给手机,即设备B开启Tx窗口,手机开启Rx窗口。
如图所示,手机在收到A1广播包ADV_IND后,以此为初始锚点(这个锚点不是链接的锚点),T_IFS后给Advertiser发送一个connection request命令,即A2数据包,告诉advertiser我将要过来连你,请作好准备。Advertiser根据connect_req命令信息作好接收准备,connect_req包含以下关键信息:
- Transmit window offset,发送窗口偏移
- Transmit window size, 发送窗口大小
- connection interval 链接间隔
- latency 从设备延迟
- timeout 监控超时
.......
这些参数能够由主设备肯定,也可让从设备肯定. 咱们取了最优(也是最耗电的配置)
connection interval = 7.5ms
latency = 0
timeout = 4000ms
当主设备发起一个链接请求后(意思告诉从设备,我要连你, 要你作好准备), 在一个1.25ms时间单位, 加上发送窗口大小,发送窗口偏移时间后,发送一个空白给 从设备,并准备接收从设备的包,当接收到从设备的空包后,表示链接正式确立。咱们能够理想大概这样计算链接时间:
time = 1.25ms + Transmit window offset + Transmit window size + connection interval
链接成功后,master和slave在每个connection interval开始的时候,都必须交互一次,即master给slave发一个包,slave再给master发一个包,整个交互过程称为一个connection event。
其它资料:
Android BLE Issues:
开源框架 SweetBlue 对蓝牙问题的总结:
google bluetooth的问题列表: