diff --git a/utils/BleHelper.js b/utils/BleHelper.js index aa8ba3d..f734158 100644 --- a/utils/BleHelper.js +++ b/utils/BleHelper.js @@ -105,17 +105,17 @@ class BleHelper { } linkAllDevices() { - console.log("模块启动时,自动连接已连接过的设备", this.data.LinkedList); + console.log("模块启动时,自动连接已连接过的设备", this.data.LinkedList); if (this.data.LinkedList && this.data.LinkedList.length > 0) { for (var i = 0; i < this.data.LinkedList.length; i++) { let device = this.data.LinkedList[i]; // console.log("自动连接绑定过的设备:" + device.deviceId); - if(device.macAddress && device.device && device.device.id){ + if (device.macAddress && device.device && device.device.id) { this.LinkBlue(device.deviceId, device.writeServiceId, device.wirteCharactId, device - .notifyCharactId); + .notifyCharactId); } - + } } else { // console.log("无设备连接"); @@ -389,7 +389,7 @@ class BleHelper { this.data.discovering = state.discovering; if (this.data.available && this.data .isOpenBlue) { //蓝牙状态再次可用,重连所有设备 - this.linkAllDevices(); + this.linkAllDevices(); } @@ -468,14 +468,17 @@ class BleHelper { this.data.LinkedList.find((v) => { if (v.deviceId == receive .deviceId) { - str= str.replace( + str = str.replace( header, ""); - if(str.includes(':')){ - v.macAddress =str; - }else{ - v.macAddress=str.replace(/(.{2})/g, '$1:').slice(0, -1) - } - console.log("收到mac地址:", v.macAddress) + if (str.includes(':')) { + v.macAddress = str; + } else { + v.macAddress = str.replace( + /(.{2})/g, '$1:') + .slice(0, -1) + } + console.log("收到mac地址:", v + .macAddress) } }); uni.setStorageSync(this.StorageKey, this.data @@ -512,29 +515,31 @@ class BleHelper { hexs: hexs }; console.log("监听到特征值:" + JSON.stringify(recData)); - try{ + try { if (this.cfg.receivDataCallback) { - + if (this.cfg.receivDataCallback.length > 0) { console.log("有人订阅消息") let path = this.getCurrentPagePath(); - - this.cfg.receivDataCallback.forEach((rec) => { - + + this.cfg.receivDataCallback.forEach(( + rec) => { + if (rec.callback) { - rec.callback(recData, f, path); + rec.callback(recData, f, + path); } }) - }else{ + } else { console.log("无人订阅消息"); } } else { console.log("无人订阅receivDataCallback,不处理数据"); } - }catch(ex){ - console.log("ex=",ex); + } catch (ex) { + console.log("ex=", ex); } - + }); @@ -687,9 +692,10 @@ class BleHelper { } // console.log("c=", c); let startSubScribe = (id, serviceId, characteristicId) => { - console.log("serviceId=",serviceId); - console.log("characteristicId=",characteristicId); - return new Promise((succ, err) => { + console.log("serviceId=", serviceId); + console.log("characteristicId=", characteristicId); + let p1= new Promise((succ, err) => { + uni.notifyBLECharacteristicValueChange({ deviceId: id, serviceId: serviceId, @@ -697,7 +703,7 @@ class BleHelper { state: state, success: (res) => { if (state) { - console.log("订阅消息成功", res); + console.log("订阅消息成功", res); } else { console.log("取消订阅成功", res); } @@ -707,7 +713,8 @@ class BleHelper { v.notifyState = state; } }); - succ(); + console.log("success SubScribe"); + succ(res);//见了鬼了,有时候执行了succ但promise永远pending了 }, fail: (ex) => { @@ -715,37 +722,59 @@ class BleHelper { } }); }); + + let p2=new Promise((succ,err)=>{ + setTimeout(()=>{ + err({code:-1}); + },50); + }); + return new Promise((succ,err)=>{ + Promise.race([p1,p2]).then(succ).catch(ex=>{ + if(ex.code==-1){ + succ(); + return; + } + err(ex); + }) + }); + } let promies = new Array(); - if(c.Characteristics && c.Characteristics.length){ + if (c.Characteristics && c.Characteristics.length) { for (var i = 0; i < c.Characteristics.length; i++) { let item = c.Characteristics[i]; let serviceId = item.serviceId; let characteristicId = item.uuid; - + if (item.properties.notify) { promies.push(startSubScribe(deviceId, serviceId, characteristicId)); } } } - - if (promies.length > 0) { - Promise.allSettled(promies).then((results) => { + if (promies.length > 0) { + + console.log("234324324324"); + Promise.allSettled(promies).then((results) => { + console.log("11111"); results.forEach((result, index) => { if (result.status === "fulfilled") { console.log(`操作${index + 1}成功:`, result.value); } else { - console.log(`操作${index + 1}失败:`, result.reason - .message); + console.log(`操作${index + 1}失败:`, result.reason + .message); } }); resolve(); }).catch((ex) => { + console.log("222222"); reject(ex); + }).finally(()=>{ + console.log("finally") }); } else { + console.log("33333"); resolve(); } @@ -958,89 +987,95 @@ class BleHelper { //连接设备 var linkDevice = () => { - // 添加重试次数限制 - let retryCount = 0; - const maxRetries = 1; // 最大重试次数 - - const connect = () => { - return new Promise((resolve, reject) => { - if (fIndex > -1 && f?.Linked) { - console.log("当前已连接,跳过其他步骤"); - resolve(false); - return; - } - - if (!this.data.available) { - reject(this.getError({ code: 10001 })); - return; - } - - console.log("正在连接" + deviceId); - uni.createBLEConnection({ - deviceId: deviceId, - timeout: 30000, - success: (info) => { - console.log("新连接成功", this.data.LinkedList); - this.getLinkBlue().then((arr) => { - let cr = arr.devices.find(c => { - if (c.deviceId == deviceId) { - c.Linked = true; - return true; - } - return false; - }); - - if (fIndex > -1) { - this.data.LinkedList[fIndex].Linked = true; - } else { - this.data.LinkedList.push(cr); - } - - uni.setStorageSync(this.StorageKey, this.data.LinkedList); - console.log("LinkedList=", this.data.LinkedList); - - // 处理 MTU 设置 - if (plus.os.name === 'Android') { - uni.setBLEMTU({ - deviceId: deviceId, - mtu: 512, - success: (mtu) => { - console.log("mtu设置成功", mtu); - resolve(true); - }, - fail: () => { - console.log("mtu设置失败"); - resolve(true); // MTU设置失败不影响连接成功 - } - }); - } else { - resolve(true); - } - }).catch((ex) => { - reject(this.getError(ex)); - }); - }, - fail: (ex) => { - ex = this.getError(ex); - console.log("蓝牙连接失败" + JSON.stringify(ex)); - - // 连接超时后自动重试 - if (ex.code === 10012 && retryCount < maxRetries) { - retryCount++; - console.log(`重试连接 (${retryCount}/${maxRetries})`); - // 使用 setTimeout 避免递归调用栈溢出 - setTimeout(() => { - connect().then(resolve).catch(reject); - }, 1000); // 延迟1秒后重试 - } else { - reject(ex); - } - } - }); - }); - }; - - return connect(); + // 添加重试次数限制 + let retryCount = 0; + const maxRetries = 1; // 最大重试次数 + + const connect = () => { + return new Promise((resolve, reject) => { + if (fIndex > -1 && f?.Linked) { + console.log("当前已连接,跳过其他步骤"); + resolve(false); + return; + } + + if (!this.data.available) { + reject(this.getError({ + code: 10001 + })); + return; + } + + console.log("正在连接" + deviceId); + uni.createBLEConnection({ + deviceId: deviceId, + timeout: 30000, + success: (info) => { + console.log("新连接成功", this.data.LinkedList); + this.getLinkBlue().then((arr) => { + let cr = arr.devices.find(c => { + if (c.deviceId == deviceId) { + c.Linked = true; + return true; + } + return false; + }); + + if (fIndex > -1) { + this.data.LinkedList[fIndex].Linked = true; + } else { + this.data.LinkedList.push(cr); + } + + uni.setStorageSync(this.StorageKey, this.data + .LinkedList); + console.log("LinkedList=", this.data + .LinkedList); + + // 处理 MTU 设置 + if (plus.os.name === 'Android') { + uni.setBLEMTU({ + deviceId: deviceId, + mtu: 512, + success: (mtu) => { + console.log("mtu设置成功", + mtu); + resolve(true); + }, + fail: () => { + console.log("mtu设置失败"); + resolve( + true); // MTU设置失败不影响连接成功 + } + }); + } else { + resolve(true); + } + }).catch((ex) => { + reject(this.getError(ex)); + }); + }, + fail: (ex) => { + ex = this.getError(ex); + console.log("蓝牙连接失败" + JSON.stringify(ex)); + + // 连接超时后自动重试 + if (ex.code === 10012 && retryCount < maxRetries) { + retryCount++; + console.log(`重试连接 (${retryCount}/${maxRetries})`); + // 使用 setTimeout 避免递归调用栈溢出 + setTimeout(() => { + connect().then(resolve).catch(reject); + }, 1000); // 延迟1秒后重试 + } else { + reject(ex); + } + } + }); + }); + }; + + return connect(); }; @@ -1051,32 +1086,32 @@ class BleHelper { ////console.log("2222222"); return linkDevice(deviceId); }).then((res) => { - + if (res) { //新连接 - console.log("11111111"); + console.log("11111111"); if (fIndex == -1) { console.log("开始获取服务", targetServiceId) return this.getService(deviceId, targetServiceId, writeCharId, notifyCharId); //获取服务 } else { - if(f.wirteCharactId && f.notifyCharactId){ + if (f.wirteCharactId && f.notifyCharactId) { if (!f.notifyState) { console.log("开始订阅特征"); this.subScribe(deviceId, true); - }else{ + } else { console.log("不订阅消息"); } return Promise.resolve(true); - }else{ + } else { console.log("开始获取服务", targetServiceId) return this.getService(deviceId, targetServiceId, writeCharId, notifyCharId); } - - + + } } else { //已连接过,直接订阅消息 - console.log("11111111"); + console.log("11111111"); if (fIndex > -1 && f && !f.notifyState) { this.subScribe(deviceId, true); @@ -1085,13 +1120,13 @@ class BleHelper { } }).then(() => { - + console.log("then....."); setTimeout(() => { resolve(); }, 500); }).catch((ex) => { - ////console.log("出现异常", ex); + console.log("出现异常", ex); reject(ex); }); });