问题描述
CoreBluetooth 代理方法:
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
断开蓝牙连接后,回调参数error为:Error Domain=CBErrorDomain Code=6 “The connection has timed out unexpectedly.” UserInfo={NSLocalizedDescription=The connection has timed out unexpectedly.}
原因
参考 connection关键参数说明;
iOS设备作为主设connect过程中系统交互,connection supervision timeout参数实际查验为720ms,即72*10ms,如果当前蓝牙环境差或其他原因导致连接不稳定,超过720ms,即timeout断开;
优化
1、蓝牙协议允许从机来协商调整 connection supervision timeout 参数;
2、参考苹果官方《Accessory Design Guidelines for Apple Devices》41.6 章节规定如下:
- Supervision Timeout from 2 seconds to 6 seconds.
- Supervision Timeout greater than Interval Max * (Peripheral Latency + 1) * 3.
以此通过设置从机参数来优化这个报错,但是需注意的是如果timeout设置过大,容易造成假连接,请根据实际应用来灵活调整此参数;