uni.createBLEConnection在故意多次超时后,调用api立马出现10012超时错误,只有重启app才能正常。目前只有在vivo x70上复现
- Dominant language
- JavaScript
- Stars
- 41.6k
- Forks
- 3.7k
- Avg merge
- 7h 6m
- Merged PRs (30d)
- 6
Description
功能逻辑是首页点击操作设备按钮,进入到连接设备页面,依次执行
```
await uni.openBluetoothAdapter();
await uni.getBluetoothAdapterState();
await uni.startBluetoothDevicesDiscovery();
const joinResult = await connectBluetooth(blueId);
uni.stopBluetoothDevicesDiscovery({
success(res) {
console.log("停止搜索成功", res);
},
fail(err) {
console.log("停止失败", err);
},
});
```
**connectBluetooth逻辑如下**
```
/**
* 连接蓝牙 + 获取主服务 + 获取特征码
*/
export const connectBluetooth = async (deviceId) => {
try {
// 连接蓝牙设备
await uni.createBLEConnection({
deviceId,
timeout: 8000,
});
// 获取主服务
const serviceId = await getServiceIdWithRetry(deviceId, 10);
// 获取特征码
const characteristicId = await getCharacteristicId(deviceId, serviceId);
// 返回设备数据
const deviceData = {
deviceId,
serviceId,
characteristicId,
};
return deviceData;
} catch (error) {
console.log('连接蓝牙发生错误', error);
// 连接失败
return {
err: true,
errName: error.toString(),
...error,
};
}
};
// 获取主服务,最多重试retryCount次
const getServiceIdWithRetry = async (deviceId, retryCount) => {
let attempt = 0;
while (attempt < retryCount) {
try {
return await getServiceId(deviceId);
} catch (error) {
attempt++;
if (attempt >= retryCount) {
throw new Error(`获取主服务失败: ${error.message}`);
}
console.log(`获取主服务失败,重试第${attempt}次`);
}
}
};
// 获取主服务
const getServiceId = async (deviceId) => {
return new Promise((resolve, reject) => {
let timer = setTimeout(() => {
reject(new Error('获取主服务超时'));
}, 3500); // 设置超时时间为3秒
setTimeout(() => {
uni.getBLEDeviceServices({
deviceId,
success(res) {
clearTimeout(timer);
console.log('获取主服务成功', res);
if (res.services.length < 4) {
reject(new Error('服务数量不足'));
} else {
resolve(res.services[3].uuid);
}
},
fail(error) {
clearTimeout(timer);
reject(error);
},
});
}, 1000);
});
};
// 获取特征码
const getCharacteristicId = async (deviceId, serviceId) => {
return new Promise((resolve, reject) => {
let timer = setTimeout(() => {
reject(new Error('获取特征码超时'));
}, 5000); // 设置超时时间为5秒
setTimeout(() => {
uni.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success(res) {
clearTimeout(timer);
console.log('获取特征码成功', res);
if (res.characteristics.length === 0) {
reject(new Error('特征码数量为0'));
} else {
resolve(res.characteristics[0].uuid);
}
},
fail(error) {
clearTimeout(timer);
reject(error);
},
});
}, 1000);
});
};
```
`
Contributor guide
Assessment
This issue has not been assessed yet.