1
0
forked from dyf/APP

解决订阅消息有时候会永远pending的问题

This commit is contained in:
liub
2025-09-16 17:30:46 +08:00
parent 6331190f0d
commit ed8f02fb39

View File

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