// 连接蓝牙
async linkDevice() {
const that = this;
const maxRetryCount = 3;
let retryCount = 0;
// 连接连接失败,重试3次
async function connectWithRetry() {
try {
const blueId = that.getBluetoothId();
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);
},
});
if (joinResult.err) {
throw new Error("连接失败");
}
} catch (err) {
console.log("初始化蓝牙失败", err);
if (retryCount < maxRetryCount) {
retryCount++;
console.log(`重试连接,当前第 ${retryCount} 次`);
await connectWithRetry();
} else {
// 达到最大重试次数,执行失败处理
uni.showModal({
title: "提示!",
content: "蓝牙连接失败,请重新操作设备!",
showCancel: false,
confirmText: "确定",
success: (res) => {
if (res.confirm) {
that.unlockingFailure();
}
},
});
}
}
}
// 开始首次连接尝试
await connectWithRetry();
},
/**
* 连接蓝牙 + 获取主服务 + 获取特征码
*/
export const connectBluetooth = async (deviceId) => {
console.log('deviceId---------------------', deviceId);
try {
// 连接蓝牙设备
await uni.createBLEConnection({
deviceId,
timeout: 3000,
});
// 获取主服务
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,
};
}
};
图片是第4次重新操作设备的日志输出,可以看到在1秒钟直接超时失败重连3次都是超时