修复一个Uniapp蓝牙的坑,App首页蓝牙状态功能添加

This commit is contained in:
liub
2025-12-02 11:32:56 +08:00
parent 5fec8eff30
commit cd6d529523
4 changed files with 188 additions and 78 deletions

View File

@ -24,8 +24,7 @@
"Geolocation" : {},
"Maps" : {},
"Record" : {},
"VideoPlayer" : {},
"Push" : {}
"VideoPlayer" : {}
},
/* */
"distribute" : {

View File

@ -48,7 +48,7 @@
</view>
<view class="lblTitle">
<text>搜索设备</text>
<text>发现设备:{{deviceCnt}}</text>
<view @click="refreshBleList()">刷新</view>
</view>
<view class="lblTitle">
@ -163,7 +163,12 @@
}
},
computed: {
deviceCnt:function(){
let arr=this.EquipMents.filter(item=>{
return item.name.toLowerCase().indexOf(this.search.toLowerCase())>-1;
});
return arr.length;
}
},
onHide: function() {
this.Status.isPageHidden = true;

View File

@ -57,8 +57,9 @@
v-if="item.communicationMode==0 && item.onlineStatus==1 && item.alarmStatus==1">
报警中</view>
<view v-if="item.communicationMode==1">
<view class="device-status online">已连接</view>
<view class="device-status unline">未连接</view>
<view class="device-status" :class="item.bleStatu?'online':'unline'">
{{item.bleStatu?'已连接':'未连接'}}
</view>
</view>
</view>
<image src="/static/images/common/cires.png" class="circle" mode="aspectFit"></image>
@ -145,7 +146,8 @@
deviceReName
} from '@/api/common/index.js'
import BleHelper from '@/utils/BleHelper.js';
var ble=null;
var pagePath = 'pages/common/index';
var ble = null;
export default {
onPullDownRefresh() {
// 执行下拉刷新时的操作,比如重新获取数据
@ -212,6 +214,69 @@
}
},
methods: {
bleStateRecovery() {
console.log("蓝牙适配器恢复可用,重连断开的设备");
ble.linkAllDevices();
// if (ble.data && ble.data.LinkedList) {
// for (var i = 0; i < this.deviceList.length; i++) {
// if (this.deviceList[i].communicationMode !== '0' || this.deviceList[i].communicationMode !== 0) {
// ble.data.LinkedList.find(v => {
// if (v.macAddress && v.device && v.device.id && v.device.id == this.deviceList[i]
// .id) {
// ble.LinkBlue(v.deviceId);
// return true;
// }
// });
// }
// }
// }
},
bleBreak(res) {
console.log("蓝牙断开连接", res);
if (res.deviceId) {
this.updateBleStatu(res.deviceId);
}
},
bleRecovery(res) {
console.log("蓝牙连接成功", res);
if (res.deviceId) {
this.updateBleStatu(res.deviceId);
}
},
updateBleStatu(deviceId) {//更新列表的蓝牙连接状态
if (ble) {
for (var i = 0; i < this.deviceList.length; i++) {
let bleStatu = false;
if (ble.data && ble.data.LinkedList) {
ble.data.LinkedList.find(v => {
if (deviceId && v.deviceId != deviceId) {
return false;
}
if (v.macAddress && v.device && v.device.id) {
if (v.device.id == this.deviceList[i].id && v.Linked) {
bleStatu = true;
return true;
}
}
});
}
this.$set(this.deviceList[i], 'bleStatu', bleStatu);
}
return;
}
console.error("ble is null")
},
// 更多
allMore() {
this.showshare = !this.showshare;
@ -291,6 +356,10 @@
// 如果是第一页或切换分类,替换数据
this.deviceList = this.page === 1 ? newDevices : [...this.deviceList, ...newDevices];
this.updateBleStatu();
this.total = res.total;
// 判断是否加载完成
if (res.rows.length < this.size || this.deviceList.length >= this.total) {
@ -390,8 +459,8 @@
}, 500);
this.deleteShow = false
// 关闭所有滑动项
this.$refs.swipeAction.closeAll();
this.$refs.swipeAction.closeAll();
ble && ble.DropDevice(data.id);
} else {
uni.showToast({
@ -492,7 +561,7 @@
let url = item.detailPageUrl;
// console.log("url=",url);
// if(!url){
//url="/pages/670/HBY670"
//url="/pages/670/HBY670"
// }
uni.navigateTo({
url: url,
@ -506,8 +575,9 @@
deviceType: this.tabs[this.activeTab].id || '',
apiType: 'listA' //标识,根据这个参数,区分普通详情,分享跳转详情,查不一样的权限信息
});
},fail(ex) {
console.log("ex=",ex);
},
fail(ex) {
console.log("ex=", ex);
}
})
},
@ -559,14 +629,35 @@
console.log('列表收到消息了么');
this.onIntall()
});
ble=BleHelper.getBleTool();
ble = BleHelper.getBleTool();
//蓝牙连接成功的回调
ble.addRecoveryCallback((res) => {
console.log("11111");
this.bleRecovery(res);
}, pagePath);
//蓝牙断开连接的回调
ble.addDisposeCallback((res) => {
console.log("2222222");
this.bleBreak(res);
}, pagePath);
//蓝牙适配器恢复可用的回调,一般是重连设备
ble.addStateRecoveryCallback(res => {
this.bleStateRecovery();
}, pagePath);
},
beforeDestroy() {
// 组件销毁前移除监听器
uni.$off('refreshDeviceList');
},
onUnload() {
uni.$off('deviceStatusUpdate');
ble && ble.removeAllCallback();
}
}

View File

@ -513,58 +513,71 @@ class BleHelper {
return bytes.map(byte => byte.toString(16).padStart(2,
'0'));
}
let adapterStateTime=null;
uni.onBluetoothAdapterStateChange((state) => {
console.log('蓝牙状态发生变化:' + JSON.stringify(state));
this.data.discovering = state.discovering;
if (this.data.available !== state.available) {
this.data.available = state.available;
clearTimeout(adapterStateTime);
setTimeout(()=>{
if (this.data.available && this.data
.isOpenBlue) { //蓝牙状态再次可用,重连所有设备
if (this.cfg.stateRecoveryCallback.length > 0) {
this.cfg.stateRecoveryCallback.forEach(
c => {
try {
c.callback();
} catch (error) {
console.error(
"蓝牙适配器已恢复,但回调函数发生错误",
error);
}
})
}
if(this.data.discovering === state.discovering && this.data.available===state.available){
console.error("专业给Uniapp填坑,适配器状态错误");
return;
}
}
if (!state.available) { //蓝牙状态不可用了,将所有设备标记为断开连接
this.data.LinkedList.filter((v) => {
v.Linked = false;
v.notifyState = false;
return true;
});
let keys = Object.keys(bleDeviceStates)
keys.filter(v => {
bleDeviceStates[v] = false;
});
this.cfg.stateBreakCallback.forEach(f => {
try {
f.callback();
} catch (error) {
console.error("蓝牙状态不可用了,执行回调异常",
error)
console.log('蓝牙模块状态发生变化:' + JSON.stringify(state));
this.data.discovering = state.discovering;
if (this.data.available !== state.available) {
this.data.available = state.available;
if (this.data.available && this.data
.isOpenBlue) { //蓝牙适配器再次可用
if (this.cfg.stateRecoveryCallback.length > 0) {//执行适配器恢复的回调
console.log('蓝牙状态再次可用,执行恢复连接的回调');
this.cfg.stateRecoveryCallback.forEach(
c => {
try {
c.callback();
console.log("执行恢复连接的回调成功");
} catch (error) {
console.error(
"蓝牙适配器已恢复,但回调函数发生错误",
error);
}
})
}
}
})
this.updateCache();
}
}
if (!state.available) { //蓝牙状态不可用了,将所有设备标记为断开连接
console.log("蓝牙模块不可用了,将所有设备标记为断开连接");
this.data.LinkedList.filter((v) => {
v.Linked = false;
v.notifyState = false;
return true;
});
// let keys = Object.keys(bleDeviceStates)
// keys.filter(v => {
// bleDeviceStates[v] = false;
// });
this.cfg.stateBreakCallback.forEach(f => {
try {
f.callback();
console.log("执行断开连接的回调成功");
} catch (error) {
console.error("蓝牙状态不可用了,执行回调异常",
error)
}
})
this.updateCache();
}
},500);
});
@ -594,8 +607,8 @@ class BleHelper {
return false;
});
this.updateCache();
if (f && f.device && f.device.id) {
console.log("尝试5次恢复连接,", f
if (f && f.device && f.device.id && this.data.available) {
console.log("蓝牙状态可用,尝试5次恢复连接,", f
.deviceId);
this.LinkBlue(res.deviceId, f
.writeServiceId, f
@ -609,6 +622,7 @@ class BleHelper {
(c) => {
try {
c.callback(res);
console.log("执行蓝牙断开连接的回调成功");
} catch (error) {
console.error(
"执行蓝牙断开连接的回调出现异常,",
@ -618,20 +632,7 @@ class BleHelper {
}
} else {
console.log("蓝牙连接已恢复", res);
if (this.cfg.recoveryCallback.length >
0) {
this.cfg.recoveryCallback.forEach((
c) => {
try {
c.callback(res);
} catch (error) {
console.error(
"执行蓝牙恢复连接的回调出现异常,",
error)
}
});
}
console.log("蓝牙连接已恢复",res);
}
}, 0);
@ -1501,6 +1502,20 @@ class BleHelper {
this.updateCache();
// console.log("LinkedList=", this.data
// .LinkedList);
//执行连接成功的回调
if (this.cfg.recoveryCallback.length >0) {
this.cfg.recoveryCallback.forEach((
c) => {
try {
c.callback({deviceId:deviceId,connected:true});
} catch (error) {
console.error(
"执行蓝牙恢复连接的回调出现异常,",
error)
}
});
}
// 处理 MTU 设置
if (plus.os.name === 'Android') {
@ -1830,7 +1845,7 @@ class BleHelper {
Promise.race([timeOut(ms), promise]).then(resolve).catch((ex) => {
// console.error("ex=", ex);
if (ex.code == -1) {
// console.error('专业给Uniapp填坑,发送消息永无回调');
console.error('专业给Uniapp填坑,发送消息永无回调');
resolve(ex);
} else {
reject(ex);