蓝牙添加连接、断开、可用、不可用控制

This commit is contained in:
liub
2025-10-17 11:52:26 +08:00
parent 0ce4f4bef0
commit b114f6690d
13 changed files with 3024 additions and 407 deletions

31
App.vue
View File

@ -29,17 +29,23 @@
// uni.clearStorageSync(); // uni.clearStorageSync();
//以上代码仅在开发时使用,否则会出现不可预知的问题。 //以上代码仅在开发时使用,否则会出现不可预知的问题。
uni.getSystemInfo({success:function(res){
if(res.uniPlatform=='app'){
bleTool.getBleTool();
upgrade.checkAndUpdateWgt();
}
}});
}, },
onShow: function() { onShow: function() {
console.log('App Show'); console.log('App Show');
//将检查更新换到onshow,因为苹果用户喜欢一直挂着
uni.getSystemInfo({success:function(res){
if(res.uniPlatform=='app'){
let appid=plus.runtime.appid;
if(appid!=='HBuilder'){
console.log("appid=",appid);
bleTool.getBleTool();
upgrade.checkAndUpdateWgt();
}
}
}});
}, },
onHide: function() { onHide: function() {
console.log('App Hide'); console.log('App Hide');
@ -92,6 +98,15 @@
background: rgba(42, 42, 42, 1); background: rgba(42, 42, 42, 1);
} }
.green{
color: #BBE600 !important;
}
.red{
color:#E03434 !important;
}
@font-face { @font-face {
font-family: "PingFang SC"; font-family: "PingFang SC";
src: url("~@/static/fonts/PingFangSC.ttf") format("opentype"); src: url("~@/static/fonts/PingFangSC.ttf") format("opentype");

View File

@ -250,6 +250,13 @@
"style": { "style": {
"navigationBarTitleText": "BJQ7305" "navigationBarTitleText": "BJQ7305"
} }
},
{
"path" : "pages/6331/BJQ6331",
"style" :
{
"navigationBarTitleText" : "BJQ6331"
}
} }

View File

@ -34,6 +34,10 @@
<text class="lbl">充电状态</text> <text class="lbl">充电状态</text>
<text class="value">{{formData.statu}}</text> <text class="value">{{formData.statu}}</text>
</view> </view>
<view class="item">
<text class="lbl">蓝牙状态</text>
<text class="value" :class="formData.bleStatu?'green':'red'">{{formData.bleStatu?'已连接':'未连接'}}</text>
</view>
</view> </view>
<view class="lamp"> <view class="lamp">
<view class="title"> <view class="title">
@ -124,8 +128,8 @@
:borderColor="Status.Pop.borderColor" :textColor="Status.Pop.textColor" :borderColor="Status.Pop.borderColor" :textColor="Status.Pop.textColor"
:buttonBgColor="Status.Pop.buttonBgColor" :buttonTextColor="Status.Pop.buttonTextColor" :buttonBgColor="Status.Pop.buttonBgColor" :buttonTextColor="Status.Pop.buttonTextColor"
:iconUrl="Status.Pop.iconUrl" :message="Status.Pop.message" :buttonText="Status.Pop.buttonText" :iconUrl="Status.Pop.iconUrl" :message="Status.Pop.message" :buttonText="Status.Pop.buttonText"
@buttonClick="HidePop" @closePop="closePop" :visiblePrompt="Status.Pop.visiblePrompt" :promptTitle="Status.Pop.promptTitle" @buttonClick="HidePop" @closePop="closePop" :visiblePrompt="Status.Pop.visiblePrompt"
v-model="Status.Pop.modelValue" /> :promptTitle="Status.Pop.promptTitle" v-model="Status.Pop.modelValue" />
<!-- 下方菜单 --> <!-- 下方菜单 -->
<BottomSlideMenuPlus :config="Status.BottomMenu" @close="closeMenu" @itemClick="handleItemClick" <BottomSlideMenuPlus :config="Status.BottomMenu" @close="closeMenu" @itemClick="handleItemClick"
@ -152,7 +156,7 @@
updateLoading updateLoading
} from '@/utils/loading.js' } from '@/utils/loading.js'
import BleReceive from '@/utils/BleReceive'; import BleReceive from '@/utils/BleReceive';
var pagePath = "pages/6155/HBY6155";
var ble = null; var ble = null;
var these = null; var these = null;
@ -166,6 +170,7 @@
data() { data() {
return { return {
Status: { Status: {
pageHide: false,
Pop: { Pop: {
showPop: false, //是否显示弹窗 showPop: false, //是否显示弹窗
popType: 'custom', popType: 'custom',
@ -182,7 +187,7 @@
promptTitle: '设备名称', promptTitle: '设备名称',
modelValue: '', modelValue: '',
visibleClose: false, visibleClose: false,
okCallback:null okCallback: null
}, },
BottomMenu: { BottomMenu: {
show: false, show: false,
@ -232,7 +237,8 @@
id: '', id: '',
deviceId: '', deviceId: '',
textLines: ['', '', ''], textLines: ['', '', ''],
mode: '' mode: '',
bleStatu: ''
}, },
inteval: 200, inteval: 200,
device: { device: {
@ -258,7 +264,7 @@
} }
}, },
onUnload() { onUnload() {
ble.removeReceiveCallback(this); ble.removeAllCallback(pagePath);
}, },
onLoad: function() { onLoad: function() {
these = this; these = this;
@ -310,7 +316,12 @@
// link(); // link();
// } // }
console.log("6155"); console.log("6155");
ble.addReceiveCallback(these.bleValueNotify); ble.addReceiveCallback(these.bleValueNotify, pagePath);
ble.addStateBreakCallback(these.bleStateBreak, pagePath);
ble.addStateRecoveryCallback(these.bleStateRecovry, pagePath);
ble.addDisposeCallback(these.deviceDispose, pagePath);
ble.addRecoveryCallback(these.deviceRecovry, pagePath);
let eventChannel = this.getOpenerEventChannel(); let eventChannel = this.getOpenerEventChannel();
eventChannel.on('detailData', function(data) { eventChannel.on('detailData', function(data) {
@ -346,7 +357,9 @@
these.formData.img = device.devicePic; these.formData.img = device.devicePic;
these.formData.id = device.id; these.formData.id = device.id;
these.formData.deviceId = f.deviceId; these.formData.deviceId = f.deviceId;
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId); ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
these.formData.bleStatu = true;
});
these.setBleFormData(); these.setBleFormData();
these.getDetail(); these.getDetail();
@ -355,7 +368,10 @@
}, },
onHide: function() { onHide: function() {
this.Status.pageHide = true;
},
onShow() {
this.Status.pageHide = false;
}, },
onBackPress(e) { onBackPress(e) {
@ -410,13 +426,83 @@
} }
}, },
methods: { methods: {
previewImg(img){ deviceRecovry(res) {
if(!img){ if (this.Status.pageHide) {
return; return;
} }
if (res.deviceId == these.formData.deviceId) {
this.formData.bleStatu = true;
setTimeout(() => {
hideLoading(these, 1000);
});
uni.showToast({
icon: 'success',
title: '蓝牙连接成功'
});
}
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
if (res.deviceId == these.formData.deviceId) {
this.formData.bleStatu = false;
setTimeout(() => {
hideLoading(these, 1000);
});
uni.showToast({
icon: 'fail',
title: '蓝牙连接已断开'
});
}
},
bleStateBreak() {
if (this.Status.pageHide) {
return;
}
//蓝牙适配器不可用
this.formData.bleStatu = false;
uni.showToast({
icon: 'fail',
title: '蓝牙已不可用'
})
hideLoading(this);
},
bleStateRecovry() {
console.log("蓝牙可用");
if (this.Status.pageHide) {
return;
}
console.log("蓝牙可用");
//蓝牙适配器再次可用,尝试恢复连接
showLoading(this, {
text: "蓝牙恢复可用,正在连接设备"
});
ble.LinkBlue(these.formData.deviceId).then(() => {
these.formData.bleStatu = true;
updateLoading(these, {
text: '连接成功'
});
}).catch(ex => {
updateLoading(these, {
text: ex.msg
})
}).finally(() => {
setTimeout(() => {
hideLoading(these);
}, 1000);
});
},
previewImg(img) {
if (!img) {
return;
}
uni.previewImage({ uni.previewImage({
urls:[img] urls: [img]
}) })
}, },
getDevice: function() { getDevice: function() {
@ -429,18 +515,20 @@
return f; return f;
}, },
bleValueNotify: function(receive, device, path) { bleValueNotify: function(receive, device, path) {
if (this.Status.pageHide) {
let json = recei.ReceiveData(receive, device, path);
if(!json){
return; return;
} }
let keys=Object.keys(json); let json = recei.ReceiveData(receive, device, path);
keys.forEach((key)=>{ if (!json) {
if(key in these.formData){ return;
these.formData[key] = json[key]; }
} let keys = Object.keys(json);
keys.forEach((key) => {
if (key in these.formData) {
these.formData[key] = json[key];
}
}); });
if (this.formData.battary <= 20) { if (this.formData.battary <= 20) {
this.showPop({ this.showPop({
message: "设备电量低", message: "设备电量低",
@ -490,6 +578,7 @@
events: { events: {
BindOver: function(data) { BindOver: function(data) {
console.log(data) console.log(data)
these.formData.bleStatu = true;
} }
}, },
success: function(res) { success: function(res) {
@ -921,12 +1010,12 @@
}, },
closePop: function() { closePop: function() {
this.Status.Pop.showPop = false; this.Status.Pop.showPop = false;
if (this.Status.Pop.cancelCallback) { if (this.Status.Pop.cancelCallback) {
this.Status.Pop.cancelCallback(); this.Status.Pop.cancelCallback();
} }
}, },
HidePop: function() { HidePop: function() {
// console.log("1111"); // console.log("1111");
if (this.Status.Pop.clickEvt == 'SendUsr') { if (this.Status.Pop.clickEvt == 'SendUsr') {

2048
pages/6331/BJQ6331.vue Normal file

File diff suppressed because it is too large Load Diff

View File

@ -30,6 +30,10 @@
<text class="lbl">设备名称</text> <text class="lbl">设备名称</text>
<text class="value">{{formData.deviceName}}</text> <text class="value">{{formData.deviceName}}</text>
</view> </view>
<view class="item">
<text class="lbl">蓝牙状态</text>
<text class="value" :class="formData.bleStatu?'green':'red'">{{formData.bleStatu?'已连接':'未连接'}}</text>
</view>
<view class="item"> <view class="item">
<text class="lbl">预警级别</text> <text class="lbl">预警级别</text>
<text class="value">{{formData.warnLevel}}</text> <text class="value">{{formData.warnLevel}}</text>
@ -180,6 +184,7 @@
import usrApi from '@/api/670/HBY670.js' import usrApi from '@/api/670/HBY670.js'
const pagePath = "pages/650/HBY650"; const pagePath = "pages/650/HBY650";
var ble = null; var ble = null;
var these = null; var these = null;
var recei = null; var recei = null;
@ -263,7 +268,8 @@
name: '', name: '',
job: '', job: '',
id: '', id: '',
iswarn: false iswarn: false,
bleStatu: false
}, },
rgb565Data: [], rgb565Data: [],
videoHexArray: [], videoHexArray: [],
@ -291,14 +297,21 @@
onUnload() { onUnload() {
console.log("页面卸载,释放资源"); console.log("页面卸载,释放资源");
ble.removeReceiveCallback(pagePath); ble.removeAllCallback(pagePath);
}, },
onLoad: function() { onLoad: function() {
these = this; these = this;
recei = BleReceive.getBleReceive(); recei = BleReceive.getBleReceive();
ble = BleTool.getBleTool(); ble = BleTool.getBleTool();
console.log("650")
ble.addReceiveCallback(these.bleValueNotify);
ble.addReceiveCallback(these.bleValueNotify, pagePath);
ble.addStateBreakCallback(these.bleStateBreak, pagePath);
ble.addStateRecoveryCallback(these.bleStateRecovry, pagePath);
ble.addDisposeCallback(these.deviceDispose, pagePath);
ble.addRecoveryCallback(these.deviceRecovry, pagePath);
let eventChannel = this.getOpenerEventChannel(); let eventChannel = this.getOpenerEventChannel();
eventChannel.on('detailData', function(data) { eventChannel.on('detailData', function(data) {
@ -332,9 +345,11 @@
these.formData.blename = f.name ? f.name : "Unname"; these.formData.blename = f.name ? f.name : "Unname";
these.formData.deviceName = device.deviceName; these.formData.deviceName = device.deviceName;
these.formData.img = device.devicePic; these.formData.img = device.devicePic;
these.formData.id = device.id;
these.formData.deviceId = f.deviceId; these.formData.deviceId = f.deviceId;
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId); ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res=>{
these.formData.bleStatu=true;
});
these.setBleFormData(); these.setBleFormData();
these.getDetail(); these.getDetail();
@ -343,10 +358,10 @@
}, },
onHide: function() { onHide: function() {
this.Status.pageHide = true;
}, },
onBackPress(e) { onShow() {
ble.removeReceiveCallback(pagePath); this.Status.pageHide = false;
}, },
computed: { computed: {
RSSIRemark: function() { RSSIRemark: function() {
@ -367,13 +382,83 @@
} }
}, },
methods: { methods: {
previewImg(img){ deviceRecovry(res) {
if(!img){ if (this.Status.pageHide) {
return; return;
} }
if (res.deviceId == these.formData.deviceId) {
this.formData.bleStatu = true;
setTimeout(() => {
hideLoading(these, 1000);
});
uni.showToast({
icon: 'success',
title: '蓝牙连接成功'
});
}
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
if (res.deviceId == these.formData.deviceId) {
this.formData.bleStatu = false;
setTimeout(() => {
hideLoading(these, 1000);
});
uni.showToast({
icon: 'fail',
title: '蓝牙连接已断开'
});
}
},
bleStateBreak() {
if (this.Status.pageHide) {
return;
}
//蓝牙适配器不可用
this.formData.bleStatu = false;
uni.showToast({
icon: 'fail',
title: '蓝牙已不可用'
})
hideLoading(this);
},
bleStateRecovry() {
console.log("蓝牙可用");
if (this.Status.pageHide) {
return;
}
console.log("蓝牙可用");
//蓝牙适配器再次可用,尝试恢复连接
showLoading(this, {
text: "蓝牙恢复可用,正在连接设备"
});
ble.LinkBlue(these.formData.deviceId).then(() => {
these.formData.bleStatu = true;
updateLoading(these, {
text: '连接成功'
});
}).catch(ex => {
updateLoading(these, {
text: ex.msg
})
}).finally(() => {
setTimeout(() => {
hideLoading(these);
}, 1000);
});
},
previewImg(img) {
if (!img) {
return;
}
uni.previewImage({ uni.previewImage({
urls:[img] urls: [img]
}) })
}, },
getWarnStyle(index) { getWarnStyle(index) {
@ -474,7 +559,7 @@
getDetail() { getDetail() {
var that = this; var that = this;
usrApi.getDetail(this.device.id).then(res => { usrApi.getDetail(this.device.id).then(res => {
console.log("res=",res);
if (res && res.code == 200) { if (res && res.code == 200) {
res = res.data; res = res.data;
let personnelInfo = res.personnelInfo; let personnelInfo = res.personnelInfo;
@ -599,9 +684,9 @@
borderColor: "#e034344d", borderColor: "#e034344d",
buttonBgColor: "#E03434", buttonBgColor: "#E03434",
buttonText: '去连接', buttonText: '去连接',
buttonTextColor:'#FFFFFFde', buttonTextColor: '#FFFFFFde',
okCallback: function() { okCallback: function() {
uni.navigateTo({ uni.navigateTo({
url: "/pages/common/addBLE/addEquip", url: "/pages/common/addBLE/addEquip",
events: { events: {
@ -630,7 +715,7 @@
proParam: function() { proParam: function() {
uni.navigateTo({ uni.navigateTo({
url: '/pages/common/productDes/index?id=' + this.formData.id, url: '/pages/common/productDes/index?id=' + this.device.id,
success(ev) { success(ev) {
} }
@ -638,7 +723,7 @@
}, },
handRemark: function() { handRemark: function() {
uni.navigateTo({ uni.navigateTo({
url: '/pages/common/operatingInstruct/index?id=' + this.formData.id, url: '/pages/common/operatingInstruct/index?id=' + this.device.id,
success(ev) { success(ev) {
} }
@ -646,7 +731,7 @@
}, },
handVideo: function() { handVideo: function() {
uni.navigateTo({ uni.navigateTo({
url: '/pages/common/operationVideo/index?id=' + this.formData.id, url: '/pages/common/operationVideo/index?id=' + this.device.id,
success(ev) { success(ev) {
} }

View File

@ -33,10 +33,15 @@
<text class="lbl">设备名称</text> <text class="lbl">设备名称</text>
<text class="value valueFont">{{device.deviceName}}</text> <text class="value valueFont">{{device.deviceName}}</text>
</view> </view>
<view class="item">
<text class="lbl">蓝牙状态</text>
<text class="value" :class="formData.bleStatu?'green':'red'">{{formData.bleStatu?'已连接':'未连接'}}</text>
</view>
<view class="item"> <view class="item">
<text class="lbl">设备状态</text> <text class="lbl">设备状态</text>
<text class="value valueFont">{{formData.sta_system}}</text> <text class="value valueFont">{{formData.sta_system}}</text>
</view> </view>
<view class="item"> <view class="item">
<text class="lbl">定位信息</text> <text class="lbl">定位信息</text>
<view class="multiValue" @click.stop="gotoMap()"> <view class="multiValue" @click.stop="gotoMap()">
@ -293,6 +298,7 @@
data() { data() {
return { return {
Status: { Status: {
pageHide: false,
apiType: "listA", apiType: "listA",
navbar: { navbar: {
icons: [{ icons: [{
@ -369,7 +375,7 @@
showClose: false showClose: false
}, },
usrToggle: true, usrToggle: true,
bleLinkCnt:0 bleLinkCnt: 0
}, },
formData: { formData: {
battary: "", //电量 battary: "", //电量
@ -391,7 +397,8 @@
staticWarn: false, //静止报警 staticWarn: false, //静止报警
fourGStrenth: 0, //4G信号强度 fourGStrenth: 0, //4G信号强度
deviceId: "", deviceId: "",
sta_system: "" //设备状态0关机1仅充电2开机未充电,3开机且充电 sta_system: "", //设备状态0关机1仅充电2开机未充电,3开机且充电
bleStatu: false
}, },
device: { device: {
id: "", id: "",
@ -446,7 +453,7 @@
onUnload() { onUnload() {
console.log("页面卸载,释放资源"); console.log("页面卸载,释放资源");
let statusTopic = `A/${this.formData.imei?this.formData.imei:this.device.deviceImei}`; let statusTopic = `A/${this.formData.imei?this.formData.imei:this.device.deviceImei}`;
ble.removeReceiveCallback(pagePath); ble.removeAllCallback(pagePath);
if (mqttClient) { if (mqttClient) {
mqttClient.unsubscribe(statusTopic); mqttClient.unsubscribe(statusTopic);
mqttClient.disconnect(); mqttClient.disconnect();
@ -460,8 +467,14 @@
these = this; these = this;
recei = BleReceive.getBleReceive(); recei = BleReceive.getBleReceive();
ble = BleTool.getBleTool(); ble = BleTool.getBleTool();
console.log("670")
ble.addReceiveCallback(these.bleValueNotify);
ble.addReceiveCallback(these.bleValueNotify, pagePath);
ble.addStateBreakCallback(these.bleStateBreak, pagePath);
ble.addStateRecoveryCallback(these.bleStateRecovry, pagePath);
ble.addDisposeCallback(these.deviceDispose, pagePath);
ble.addRecoveryCallback(these.deviceRecovry, pagePath);
let eventChannel = this.getOpenerEventChannel(); let eventChannel = this.getOpenerEventChannel();
eventChannel.on('detailData', function(data) { eventChannel.on('detailData', function(data) {
@ -510,12 +523,17 @@
these.formData['imei'] = these.device.deviceImei; these.formData['imei'] = these.device.deviceImei;
} }
these.getDetail(); these.getDetail();
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId); ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
these.formData.bleStatu = true;
});
}); });
}, },
onShow() {
this.Status.pageHide=false;
},
onHide: function() { onHide: function() {
this.Status.pageHide=true;
}, },
onBackPress(e) { onBackPress(e) {
ble.removeReceiveCallback(pagePath); ble.removeReceiveCallback(pagePath);
@ -524,22 +542,92 @@
}, },
methods: { methods: {
previewImg(img){ deviceRecovry(res) {
if(!img){ if (this.Status.pageHide) {
return; return;
} }
if (res.deviceId == these.formData.deviceId) {
this.formData.bleStatu = true;
setTimeout(() => {
hideLoading(these, 1000);
});
uni.showToast({
icon: 'success',
title: '蓝牙连接成功'
});
}
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
if (res.deviceId == these.formData.deviceId) {
this.formData.bleStatu = false;
setTimeout(() => {
hideLoading(these, 1000);
});
uni.showToast({
icon: 'fail',
title: '蓝牙连接已断开'
});
}
},
bleStateBreak() {
if (this.Status.pageHide) {
return;
}
//蓝牙适配器不可用
this.formData.bleStatu = false;
uni.showToast({
icon: 'fail',
title: '蓝牙已不可用'
})
hideLoading(this);
},
bleStateRecovry() {
console.log("蓝牙可用");
if (this.Status.pageHide) {
return;
}
console.log("蓝牙可用");
//蓝牙适配器再次可用,尝试恢复连接
showLoading(this, {
text: "蓝牙恢复可用,正在连接设备"
});
ble.LinkBlue(these.formData.deviceId).then(() => {
these.formData.bleStatu = true;
updateLoading(these, {
text: '连接成功'
});
}).catch(ex => {
updateLoading(these, {
text: ex.msg
})
}).finally(() => {
setTimeout(() => {
hideLoading(these);
}, 1000);
});
},
previewImg(img) {
if (!img) {
return;
}
uni.previewImage({ uni.previewImage({
urls:[img] urls: [img]
}) })
}, },
showBleUnConnect() { showBleUnConnect() {
this.Status.bleLinkCnt++; this.Status.bleLinkCnt++;
if(this.Status.bleLinkCnt>3){ if (this.Status.bleLinkCnt > 3) {
return; return;
} }
this.showPop({ this.showPop({
message: "蓝牙未连接过该设备,请使用蓝牙重新添加该设备", message: "蓝牙未连接过该设备,请使用蓝牙重新添加该设备,取消"+(4-this.Status.bleLinkCnt)+"次后不再提醒",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png", iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d", borderColor: "#e034344d",
buttonBgColor: "#E03434", buttonBgColor: "#E03434",
@ -571,7 +659,7 @@
}); });
}, },
gotoMap() { gotoMap() {
let lnglat=lnglatConvert.wgs84_to_gcj02(this.formData.Lon,this.formData.Lat); let lnglat = lnglatConvert.wgs84_to_gcj02(this.formData.Lon, this.formData.Lat);
this.detailData.longitude = lnglat[0]; this.detailData.longitude = lnglat[0];
this.detailData.latitude = lnglat[1]; this.detailData.latitude = lnglat[1];
uni.navigateTo({ uni.navigateTo({
@ -1175,6 +1263,7 @@
} }
if (this.formData.SOS == type) { if (this.formData.SOS == type) {
console.log("111111");
type = "close"; type = "close";
} }
@ -1210,26 +1299,28 @@
message.deviceImei = these.device.deviceImei; message.deviceImei = these.device.deviceImei;
let requestSend = (callback) => { let requestSend = (callback) => {
debugger;
message.isBluetooth = false; message.isBluetooth = false;
api.sendSos(message).then((res) => { api.sendSos(message).then((res) => {
console.log("res=>", res); console.log("res=>", res);
if (res && res.code == 200) { if (res && res.code == 200) {
console.log("接口发送SOS指令成功"); console.log("接口发送SOS指令成功");
if (callback) {
callback();
}
return Promise.resolve({ return Promise.resolve({
code: 200, code: 200,
msg: '操作成功' msg: '操作成功'
}); });
if(callback){
callback();
}
} else { } else {
return this.sendMQ(json); return this.sendMQ(json);
} }
}).then((res) => { }).then((res) => {
console.log("res=", res); console.log("res=", res);
if(callback){ if (callback) {
callback(); callback();
} }
}).catch((ex) => { }).catch((ex) => {
@ -1262,15 +1353,15 @@
dataView.setUint8(3, 0x00); // 数据长度 dataView.setUint8(3, 0x00); // 数据长度
dataView.setUint8(4, 0x01); // 数据长度 dataView.setUint8(4, 0x01); // 数据长度
dataView.setUint8(5, dic.ble[type]); // 数据 dataView.setUint8(5, dic.ble[type]); // 数据
console.log("type=", type);
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 10).then( ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 10).then(
() => { () => {
console.log("蓝牙发送成功了"); console.log("蓝牙发送成功了");
hideLoading(these); hideLoading(these);
these.setBleFormData(); these.setBleFormData();
message.isBluetooth = true; message.isBluetooth = true;
api.sendSos(message); // api.sendSos(message);
if(callback){ if (callback) {
callback(); callback();
} }
}).catch((ex) => { }).catch((ex) => {
@ -1286,41 +1377,45 @@
} }
let OpenSOS = () => { let OpenSOS = () => {
let execSos=()=>{ let execSos = () => {
these.formData.qzwarn = true; //标记为强制报警了 these.formData.qzwarn = true; //标记为强制报警了
these.Status.staticWarn.time = 180; these.Status.staticWarn.time = 180;
this.formData.SOS = type; this.formData.SOS = type;
let loopFunc = () => { let loopFunc = () => {
if (these.Status.staticWarn.inteval === null) { if (these.Status.staticWarn.inteval === null) {
return; return;
} }
if (these.Status.staticWarn.time === 0) { if (these.Status.staticWarn.time === 0) {
clearInterval(these.Status.staticWarn.inteval); clearInterval(these.Status.staticWarn.inteval);
these.Status.staticWarn.inteval = null; these.Status.staticWarn.inteval = null;
these.formData.qzwarn = false; these.formData.qzwarn = false;
if(this.Status.Pop.okCallback){
these.CloseWarn(false);
these.formData.SOS = 'close'; these.formData.SOS = 'close';
these.CloseWarn(false); }
return; return;
} }
these.Status.staticWarn.time = these.Status.staticWarn these.Status.staticWarn.time = these.Status.staticWarn
.time - 1; .time - 1;
if (these.Status.Pop.clickEvt == 'time' && this.Status.Pop.showPop) { if (these.Status.Pop.clickEvt == 'time' && this.Status.Pop.showPop) {
console.log("111111"); console.log("111111");
this.showQzWarn(this.Status.Pop.okCallback); this.showQzWarn(this.Status.Pop.okCallback);
} }
} }
these.Status.staticWarn.inteval = setInterval(() => { these.Status.staticWarn.inteval = setInterval(() => {
loopFunc(); loopFunc();
}, 1000); }, 1000);
} }
bleSendCmd(execSos); bleSendCmd(execSos);
} }
@ -1329,14 +1424,16 @@
if (type == 'rb') { //红蓝报警 if (type == 'rb') { //红蓝报警
console.log("11111"); console.log("11111");
let sendRb = () => { let sendRb = () => {
this.formData.SOS = type; this.formData.SOS = type;
bleSendCmd(); bleSendCmd();
these.formData.qzwarn = false; these.formData.qzwarn = false;
this.Status.staticWarn.time = 0; this.Status.staticWarn.time = 0;
return; return;
} }
if (these.formData.qzwarn && these.Status.staticWarn.inteval) { if (these.formData.qzwarn && these.Status.staticWarn.inteval && these.Status.staticWarn.time) {
console.log("222222"); console.log("222222");
this.Status.Pop.okCallback=null;
these.showQzWarn(sendRb); these.showQzWarn(sendRb);
} else { } else {
sendRb(); sendRb();
@ -2121,8 +2218,8 @@
} }
let requestSend = () => { let requestSend = () => {
let json = { let json = {
deviceId: this.device.id, deviceId: this.device.id,
deviceImei: this.device.deviceImei ? this.device.deviceImei : this.formData.imei, deviceImei: this.device.deviceImei ? this.device.deviceImei : this.formData.imei,
@ -2283,7 +2380,7 @@
setTimeout(sendNextPacket, 200); setTimeout(sendNextPacket, 200);
}).catch(err => { }).catch(err => {
if (err.code == '10007') { if (err.code == '10007') {
setTimeout(sendNextPacket,200); setTimeout(sendNextPacket, 200);
} else { } else {
requestSend(); requestSend();
} }

View File

@ -34,6 +34,10 @@
<text class="lbl">充电状态</text> <text class="lbl">充电状态</text>
<text class="value">{{formData.statu}}</text> <text class="value">{{formData.statu}}</text>
</view> </view>
<view class="item">
<text class="lbl">蓝牙状态</text>
<text class="value" :class="formData.bleStatu?'green':'red'">{{formData.bleStatu?'已连接':'未连接'}}</text>
</view>
</view> </view>
<view class="lamp"> <view class="lamp">
<view class="title"> <view class="title">
@ -158,7 +162,7 @@
var these = null; var these = null;
var BrighInteval = null; var BrighInteval = null;
var recei = null; var recei = null;
var pagePath = "pages/7305/BJQ7305";
export default { export default {
components: { components: {
textToDotMatrix textToDotMatrix
@ -166,6 +170,7 @@
data() { data() {
return { return {
Status: { Status: {
pageHide: false,
Pop: { Pop: {
showPop: false, //是否显示弹窗 showPop: false, //是否显示弹窗
popType: 'custom', popType: 'custom',
@ -232,7 +237,8 @@
id: '', id: '',
deviceId: '', deviceId: '',
textLines: ['', '', ''], textLines: ['', '', ''],
mode: '' mode: '',
bleStatu: ''
}, },
inteval: 200, inteval: 200,
device: { device: {
@ -258,59 +264,18 @@
} }
}, },
onUnload() { onUnload() {
ble.removeReceiveCallback(this); ble.removeAllCallback(pagePath);
}, },
onLoad: function() { onLoad: function() {
these = this; these = this;
recei = BleReceive.getBleReceive(); recei = BleReceive.getBleReceive();
ble = bleTool.getBleTool(); ble = bleTool.getBleTool();
// let bleName = 'FB_Site_UART'; //JQZM-EF4651 FB_Site_UART
ble.addReceiveCallback(these.bleValueNotify, pagePath);
// let f = ble.data.LinkedList.find((v) => { ble.addStateBreakCallback(these.bleStateBreak, pagePath);
// if (v.name == bleName) { ble.addStateRecoveryCallback(these.bleStateRecovry,pagePath);
// console.log("找到设备了", v); ble.addDisposeCallback(these.deviceDispose,pagePath);
// these.formData.deviceId = v.deviceId; ble.addRecoveryCallback(these.deviceRecovry,pagePath);
// return true;
// }
// return false;
// });
// let link = () => {
// if (bleName == 'FB_Site_UART') {
// ble.LinkBlue(f.deviceId, '0000AE30-0000-1000-8000-00805F9B34FB',
// '0000AE03-0000-1000-8000-00805F9B34FB', '0000AE02-0000-1000-8000-00805F9B34FB');
// } else {
// ble.LinkBlue(f.deviceId, '0000FFE0-0000-1000-8000-00805F9B34FB',
// '0000FFE1-0000-1000-8000-00805F9B34FB', '0000FFE2-0000-1000-8000-00805F9B34FB');
// }
// }
// if (!f) {
// ble.addDeviceFound((res) => {
// // console.log("发现新设备", res);
// f = res.devices.find((v) => {
// return v.name == bleName;
// });
// if (f) {
// console.log("找到目标设备了", f);
// these.formData.deviceId = f.deviceId;
// link();
// ble.StopSearch();
// }
// });
// ble.StartSearch();
// } else {
// link();
// }
console.log("6155");
ble.addReceiveCallback(these.bleValueNotify);
let eventChannel = this.getOpenerEventChannel(); let eventChannel = this.getOpenerEventChannel();
eventChannel.on('detailData', function(data) { eventChannel.on('detailData', function(data) {
@ -346,7 +311,10 @@
these.formData.img = device.devicePic; these.formData.img = device.devicePic;
these.formData.id = device.id; these.formData.id = device.id;
these.formData.deviceId = f.deviceId; these.formData.deviceId = f.deviceId;
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId); ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res=>{
console.log("连接成功")
these.formData.bleStatu=true;
});
these.setBleFormData(); these.setBleFormData();
these.getDetail(); these.getDetail();
@ -355,12 +323,11 @@
}, },
onHide: function() { onHide: function() {
this.Status.pageHide = true;
console.log("页面隐藏");
}, },
onBackPress(e) { onShow: function() {
this.Status.pageHide = false;
ble.removeReceiveCallback();
}, },
computed: { computed: {
RSSIRemark: function() { RSSIRemark: function() {
@ -410,6 +377,76 @@
} }
}, },
methods: { methods: {
deviceRecovry(res){
if(this.Status.pageHide){
return;
}
if(res.deviceId==these.formData.deviceId){
this.formData.bleStatu=true;
setTimeout(()=>{
hideLoading(these,1000);
});
uni.showToast({
icon:'success',
title:'蓝牙连接成功'
});
}
},
deviceDispose(res){
if(this.Status.pageHide){
return;
}
if(res.deviceId==these.formData.deviceId){
this.formData.bleStatu=false;
setTimeout(()=>{
hideLoading(these,1000);
});
uni.showToast({
icon:'fail',
title:'蓝牙连接已断开'
});
}
},
bleStateBreak() {
if(this.Status.pageHide){
return;
}
//蓝牙适配器不可用
this.formData.bleStatu = false;
uni.showToast({
icon: 'fail',
title: '蓝牙已不可用'
})
hideLoading(this);
},
bleStateRecovry() {
console.log("蓝牙可用");
if(this.Status.pageHide){
return;
}
console.log("蓝牙可用");
//蓝牙适配器再次可用,尝试恢复连接
showLoading(this, {
text: "蓝牙恢复可用,正在连接设备"
});
ble.LinkBlue(these.formData.deviceId).then(() => {
these.formData.bleStatu = true;
updateLoading(these,{
text:'连接成功'
});
}).catch(ex => {
updateLoading(these, {
text: ex.msg
})
}).finally(() => {
setTimeout(() => {
hideLoading(these);
}, 1000);
});
},
previewImg(img) { previewImg(img) {
if (!img) { if (!img) {
return; return;
@ -429,19 +466,21 @@
return f; return f;
}, },
bleValueNotify: function(receive, device, path) { bleValueNotify: function(receive, device, path) {
if (this.Status.pageHide) {
let json = recei.ReceiveData(receive, device, path);
if(!json){
return; return;
} }
let keys=Object.keys(json); let json = recei.ReceiveData(receive, device, path);
keys.forEach((key)=>{ if (!json) {
if(key in these.formData){ return;
these.formData[key] = json[key]; }
} let keys = Object.keys(json);
keys.forEach((key) => {
if (key in these.formData) {
these.formData[key] = json[key];
}
}); });
if (this.formData.battary <= 20) { if ('battary' in json && this.formData.battary <= 20) {
this.showPop({ this.showPop({
message: "设备电量低", message: "设备电量低",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png", iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
@ -491,6 +530,7 @@
events: { events: {
BindOver: function(data) { BindOver: function(data) {
console.log(data) console.log(data)
these.formData.bleStatu=true;
} }
}, },
success: function(res) { success: function(res) {
@ -521,37 +561,37 @@
// 分包发送图片数据 // 分包发送图片数据
var sendImagePackets = function(packetData) { var sendImagePackets = function(packetData) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// 总数据包数 // 总数据包数
const totalPackets = 3; const totalPackets = 3;
let currentPacket = 1; let currentPacket = 1;
// 发送单个数据包 // 发送单个数据包
const sendNextPacket = () => { const sendNextPacket = () => {
if (currentPacket > totalPackets) { if (currentPacket > totalPackets) {
setTimeout(() => { setTimeout(() => {
hideLoading(these); hideLoading(these);
these.Status.BottomMenu.show = false; these.Status.BottomMenu.show = false;
these.showPop({ these.showPop({
message: "上传成功", message: "上传成功",
iconUrl: "/static/images/6155/DeviceDetail/uploadSuccess.png", iconUrl: "/static/images/6155/DeviceDetail/uploadSuccess.png",
borderColor: '#BBE600', borderColor: '#BBE600',
buttonBgColor: '#BBE600' buttonBgColor: '#BBE600'
}); });
resolve(); resolve();
}, 0) }, 0)
return; return;
} }
let start = 0; let start = 0;
let bufferSize = 343; //总共1029字节3包正好每包343字节 let bufferSize = 343; //总共1029字节3包正好每包343字节
//FA 09 04 00 1024字节 FF //FA 09 04 00 1024字节 FF
var buffer = new ArrayBuffer(bufferSize); var buffer = new ArrayBuffer(bufferSize);
var dataView = new DataView(buffer); var dataView = new DataView(buffer);
@ -560,37 +600,37 @@
dataView.setUint8(1, 0x09); // 帧头 dataView.setUint8(1, 0x09); // 帧头
dataView.setUint8(2, 0x04); // 帧头 dataView.setUint8(2, 0x04); // 帧头
dataView.setUint8(3, 0x00); // 帧头 dataView.setUint8(3, 0x00); // 帧头
for (let i = 0; i < packetData.length; i++) { for (let i = 0; i < packetData.length; i++) {
dataView.setUint8(4 + i, parseInt(packetData[i],16)); dataView.setUint8(4 + i, parseInt(packetData[i], 16));
} }
} }
if (currentPacket == totalPackets) { if (currentPacket == totalPackets) {
dataView.setUint8(bufferSize - 1, 0xFF); dataView.setUint8(bufferSize - 1, 0xFF);
} }
//发送数据包 //发送数据包
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId,
30) 30)
.then(() => { .then(() => {
updateLoading(these, { updateLoading(these, {
text: "正在发送" + currentPacket + "/"+totalPackets text: "正在发送" + currentPacket + "/" + totalPackets
}) })
currentPacket++; currentPacket++;
setTimeout(sendNextPacket, 100); setTimeout(sendNextPacket, 100);
}).catch(err => { }).catch(err => {
if (err.code == 10007) { if (err.code == 10007) {
setTimeout(sendNextPacket, 100); setTimeout(sendNextPacket, 100);
return; return;
} }
console.log("发送数据包失败了", err); console.log("发送数据包失败了", err);
these.Status.BottomMenu.show = false; these.Status.BottomMenu.show = false;
these.showPop({ these.showPop({
message: "发送数据包失败了" + err.msg, message: "发送数据包失败了" + err.msg,
@ -598,14 +638,14 @@
borderColor: "#e034344d", borderColor: "#e034344d",
buttonBgColor: "#E03434", buttonBgColor: "#E03434",
}); });
hideLoading(these); hideLoading(these);
reject(err); reject(err);
}); });
} }
// 开始发送数据 // 开始发送数据
sendNextPacket(); sendNextPacket();
}); });
} }
@ -620,7 +660,7 @@
url: "/pages/6155/ImgCrop", url: "/pages/6155/ImgCrop",
events: { events: {
ImgCutOver: function(data) { ImgCutOver: function(data) {
//将8位的二进制数组转换成16进制数据
let binaryToHex = (binaryArray) => { let binaryToHex = (binaryArray) => {
if (!Array.isArray(binaryArray) || binaryArray if (!Array.isArray(binaryArray) || binaryArray
.length !== 8) { .length !== 8) {
@ -652,19 +692,14 @@
let imageData = data.piexls; let imageData = data.piexls;
let arr = []; let arr = [];
for (let x = 0; x < imageData.length; x += 4) { for (let currIndex = 0; currIndex < imageData
let R = imageData[x]; .length; currIndex += 4) {
let G = imageData[x + 1]; let R = imageData[currIndex];
let B = imageData[x + 2]; let G = imageData[currIndex + 1];
let A = imageData[x + 3]; let B = imageData[currIndex + 2];
if (A < 128) { let A = imageData[currIndex + 3];
arr.push(0);
continue;
}
let grayVal = Math.floor(R * 0.299 + G * 0.587 + B * let grayVal = Math.floor(R * 0.299 + G * 0.587 + B *
0.114); 0.114);
// console.log("RGBA", R + "," + G + "," + B + "," + A +
// ',' + grayVal);
arr.push(grayVal < 128 ? 1 : 0); arr.push(grayVal < 128 ? 1 : 0);
} }
@ -732,6 +767,8 @@
sendImagePackets(matrix).catch(( sendImagePackets(matrix).catch((
ex) => { ex) => {
console.log("出现异常", ex); console.log("出现异常", ex);
hideLoading(these);
}); });
}, 0) }, 0)
@ -741,7 +778,8 @@
ev.eventChannel.emit('checkImg', { ev.eventChannel.emit('checkImg', {
data: res.tempFiles[0].path, data: res.tempFiles[0].path,
width: 64, width: 64,
height: 32 height: 32,
times: 10
}) })
}, },
fail(ex) { fail(ex) {
@ -1199,7 +1237,14 @@
if (f) { if (f) {
// 发送数据 // 发送数据
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 100); ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 100).catch(ex=>{
these.showPop({
message: "发送失败," + ex.msg,
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
});
} }
@ -1241,7 +1286,14 @@
if (f) { if (f) {
// 发送数据 // 发送数据
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 100); ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 100).catch(ex=>{
these.showPop({
message: "发送失败," + ex.msg,
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
});
} }
@ -1429,6 +1481,7 @@
letter-spacing: 0.07px; letter-spacing: 0.07px;
text-align: left; text-align: left;
} }
.lamp { .lamp {
margin-top: 24rpx; margin-top: 24rpx;

View File

@ -46,14 +46,14 @@
var these = null; var these = null;
var eventChannel = null; var eventChannel = null;
var ble = null; var ble = null;
export default { export default {
data() { data() {
return { return {
Statu: { Statu: {
bound: null, bound: null,
timeInteval:null, timeInteval: null,
isSearch:false isSearch: false
}, },
device: { device: {
"deviceId": "", "deviceId": "",
@ -64,12 +64,12 @@
"advertisServiceUUIDs": [ "advertisServiceUUIDs": [
], ],
"linkStatu": false, "linkStatu": true,
"macAddress": "", "macAddress": "",
"communicationMode":"", "communicationMode": "",
"imei":"" "imei": ""
}, },
serverDevice:null serverDevice: null
} }
}, },
computed: { computed: {
@ -83,51 +83,84 @@
return "red"; return "red";
} }
}, },
deviceStatu:function(){ deviceStatu: function() {
if(!this.device.name){ if (!this.device.name) {
return ""; return "";
} }
if(!this.device.macAddress){ if (!this.device.linkStatu) {
return "蓝牙未连接";
}
if (!this.device.macAddress) {
return '等待设备上报Mac地址'; return '等待设备上报Mac地址';
} }
if(!this.device.deviceName ){ if (!this.device.deviceName) {
if(this.Statu.isSearch){ if (this.Statu.isSearch) {
return "无效设备"; return "无效设备";
}else{ } else {
if(this.Statu.timeInteval===null){ if (this.Statu.timeInteval === null) {
return "等待查询设备" return "等待查询设备"
}else{ } else {
return "正在查询设备"; return "正在查询设备";
} }
} }
}else{ } else {
return "找到有效设备" return "找到有效设备"
} }
return ""; return "";
} }
}, },
onUnload() { onUnload() {
console.log("返回时断开蓝牙连接,取消订阅"); console.log("返回取消订阅");
ble.removeReceiveCallback(pagePath); ble.removeAllCallback(pagePath);
}, },
onLoad(option) { onLoad(option) {
these = this; these = this;
ble = bleTool.getBleTool(); ble = bleTool.getBleTool();
console.log("LinkBle")
ble.addStateBreakCallback(res => {
these.device.linkStatu = false;
hideLoading(these);
uni.showToast({
icon:'fail',
title:'蓝牙已不可用'
})
},pagePath);
ble.addStateRecoveryCallback(res => {
if (these.device.deviceId) {
showLoading(these, {
text: '蓝牙已恢复正在连接设备'
});
these.reLinkdevice();
}
},pagePath);
ble.addDisposeCallback(res => {
console.log("处理蓝牙断开连接");
these.device.linkStatu = false;
if (these.device.deviceId == res.deviceId) {
showLoading(these, {
text: '蓝牙已断开,正在重连'
});
these.reLinkdevice();
}
},pagePath);
ble.addReceiveCallback((receive, f, path) => { ble.addReceiveCallback((receive, f, path) => {
console.log("收到设备消息,", receive); console.log("收到设备消息,", receive);
if (these.device.deviceId == receive.deviceId) { if (these.device.deviceId == receive.deviceId) {
console.log("11111:",receive); console.log("11111:", receive);
these.device.imei=f.imei; these.device.imei = f.imei;
if (receive.bytes[0] == 0xFC || receive.str.indexOf('mac address:') == 0) { if (receive.bytes[0] == 0xFC || receive.str.indexOf('mac address:') == 0) {
if (f && f.macAddress) { if (f && f.macAddress) {
these.device.macAddress = f.macAddress; these.device.macAddress = f.macAddress;
console.log("222222"); console.log("222222");
these.Statu.isSearch=false; these.Statu.isSearch = false;
these.initDevice(); these.initDevice();
} }
} }
@ -157,19 +190,41 @@
} }
}) })
let inteval = setInterval(this.initDevice, 10000); let inteval = setInterval(this.initDevice, 10000);
}, },
methods: { methods: {
reLinkdevice() {
ble.LinkBlue(these.device.deviceId).then(res => {
updateLoading(these, {
text: '连接成功'
});
these.device.linkStatu = true;
setTimeout(() => {
hideLoading(these);
}, 2000);
}).catch(ex => {
updateLoading(these, {
text: ex.msg
});
setTimeout(() => {
hideLoading(these);
}, 2000);
});
},
initDevice: function() { initDevice: function() {
if(!these.device.macAddress){ if (!these.device.macAddress) {
return; return;
} }
//无效的设备回调
let deviceInvalid = () => {
these.$set(these.device, "deviceName", "");
}
clearTimeout(this.Statu.timeInteval); clearTimeout(this.Statu.timeInteval);
this.Statu.timeInteval = setTimeout(() => { this.Statu.timeInteval = setTimeout(() => {
this.Statu.isSearch=true; this.Statu.isSearch = true;
showLoading(these, { showLoading(these, {
text: '正在获取设备信息' text: '正在获取设备信息'
}); });
@ -181,45 +236,34 @@
deviceMac: these.device.macAddress deviceMac: these.device.macAddress
} }
}).then(res => { }).then(res => {
console.log("获取设备信息", res); console.log("获取设备信息", res);
if (res && res.code == 200) { if (res && res.code == 200) {
console.log("res=", res);
let data = res.data; let data = res.data;
this.serverDevice=data; this.serverDevice = data;
if (data) { if (data) {
let keys = Object.keys(data); let keys = Object.keys(data);
ble.data.LinkedList.find((v) => { ble.data.LinkedList.find((v) => {
if (v.deviceId == these.device.deviceId) { if (v.deviceId == these.device.deviceId) {
for (var i = 0; i < keys.length; i++) { for (var i = 0; i < keys.length; i++) {
let key = keys[i]; let key = keys[i];
// if(!v.device){
// v.device={};
// }
// v.device[key] = data[key];
// console.log("key="+key);
// console.log("value="+data[key]);
these.$set(these.device, key, data[key]); these.$set(these.device, key, data[key]);
} }
// ble.setBleData();
} }
}); });
} else {
// console.log("device=", these.device); deviceInvalid();
// console.log("LinkedList=", ble.data.LinkedList);
} }
} else {
deviceInvalid();
} }
}).catch((ex) => { }).catch((ex) => {
console.error("获取设备出现异常:", ex); console.error("获取设备出现异常:", ex);
}).finally(() => { }).finally(() => {
this.Statu.timeInteval=null; this.Statu.timeInteval = null;
this.Statu.isSearch=false; this.Statu.isSearch = false;
hideLoading(these); hideLoading(these);
}); });
@ -242,7 +286,7 @@
these.Statu.boundRemark = "设备上报Mac地址异常"; these.Statu.boundRemark = "设备上报Mac地址异常";
return; return;
} }
if(!this.device.deviceName){ if (!this.device.deviceName) {
these.Statu.bound = false; these.Statu.bound = false;
these.Statu.boundRemark = "设备未入库"; these.Statu.boundRemark = "设备未入库";
return; return;
@ -267,26 +311,26 @@
if (res.code == 200) { if (res.code == 200) {
these.Statu.bound = true; these.Statu.bound = true;
these.Statu.boundRemark = "设备绑定成功!"; these.Statu.boundRemark = "设备绑定成功!";
let data=these.serverDevice; let data = these.serverDevice;
let keys = Object.keys(data); let keys = Object.keys(data);
ble.data.LinkedList.find((v) => { ble.data.LinkedList.find((v) => {
if (v.deviceId == these.device.deviceId) { if (v.deviceId == these.device.deviceId) {
for (var i = 0; i < keys.length; i++) { for (var i = 0; i < keys.length; i++) {
let key = keys[i]; let key = keys[i];
if(!v.device){ if (!v.device) {
v.device={}; v.device = {};
} }
v.device[key] = data[key]; v.device[key] = data[key];
} }
ble.updateCache(); ble.updateCache();
} }
}); });
ble.removeReceiveCallback(pagePath); ble.removeReceiveCallback(pagePath);
clearTimeout(this.Statu.timeInteval); clearTimeout(this.Statu.timeInteval);
this.device.macAddress=null; this.device.macAddress = null;
this.Statu.timeInteval=null; this.Statu.timeInteval = null;
uni.$emit("refreshDeviceList"); uni.$emit("refreshDeviceList");
setTimeout(() => { setTimeout(() => {
uni.switchTab({ uni.switchTab({
@ -300,7 +344,7 @@
}).catch((ex) => { }).catch((ex) => {
these.Statu.bound = false; these.Statu.bound = false;
these.Statu.boundRemark = '出现了未知的异常,操作失败'; these.Statu.boundRemark = '出现了未知的异常,操作失败';
console.log("ex=",ex); console.log("ex=", ex);
}).finally(() => { }).finally(() => {
hideLoading(this); hideLoading(this);
}); });

View File

@ -32,7 +32,9 @@
</view> </view>
<view class="centertxt "> <view class="centertxt ">
<view class="name" v-text="item.name"></view> <view class="name" v-text="item.name"></view>
<view class="id" v-text="item.deviceId"></view> <view class="id">
<text>信号:{{110+item.RSSI>100?100:110+item.RSSI}}%</text>
</view>
</view> </view>
<view class="rightIco center"> <view class="rightIco center">
<image src="/static/images/BLEAdd/linked.png" class="img" mode="aspectFit"> <image src="/static/images/BLEAdd/linked.png" class="img" mode="aspectFit">
@ -63,7 +65,7 @@
</view> </view>
<view class="id"> <view class="id">
<text>信号强度:{{110+item.RSSI>100?100:110+item.RSSI}}%</text> <text>信号:{{110+item.RSSI>100?100:110+item.RSSI}}%</text>
</view> </view>
</view> </view>
@ -116,6 +118,7 @@
data() { data() {
return { return {
Status: { Status: {
isPageHidden: false,
intval: null, intval: null,
time: null, time: null,
BottomMenu: { BottomMenu: {
@ -156,13 +159,14 @@
}, },
onHide: function() { onHide: function() {
this.Status.isPageHidden = true;
ble.StopSearch(); ble.StopSearch();
}, },
onUnload() { onUnload() {
ble.StopSearch(); ble.StopSearch();
ble.removeDeviceFound(pagePath); ble.removeAllCallback(pagePath);
ble.removeReceiveCallback(pagePath);
}, },
onLoad(option) { onLoad(option) {
let search = option.search; let search = option.search;
@ -203,14 +207,86 @@
let StartSubsrib = () => { let StartSubsrib = () => {
these.EquipMents=[]; these.EquipMents = [];
ble = bleTool.getBleTool(); ble = bleTool.getBleTool();
//蓝牙不可用的回调
ble.addStateBreakCallback(res=>{
if (these.Status.isPageHidden) {
return;
}
console.log("处理蓝牙不可用");
hideLoading(these);
these.PairEquip=[];
these.EquipMents=[];
uni.showToast({
icon:'fail',
title:'蓝牙已不可用'
});
these.showOpenSetting();
},pagePath);
//蓝牙再次可用的回调
ble.addStateRecoveryCallback(res=>{
if (these.Status.isPageHidden) {
return;
}
uni.showToast({
icon:'success',
title:'蓝牙恢复可用'
});
these.Status.BottomMenu.show = false;
these.EquipMents=[];
these.refreshBleList();
},pagePath);
//蓝牙断开连接的回调
ble.addDisposeCallback(res => {
if (these.Status.isPageHidden) {
return;
}
console.log("处理蓝牙断开连接");
hideLoading(these);
these.PairEquip.find(function(v, ind) {
these.PairEquip.splice(ind, 1);
return v.deviceId == res.deviceId;
});
}, pagePath);
//蓝牙连接已恢复的回调
ble.addRecoveryCallback(res => {
if (these.Status.isPageHidden) {
return;
}
// hideLoading(these);
these.EquipMents.find(function(v, ind) {
if (v.deviceId == res.deviceId) {
these.PairEquip.push(v);
return true;
}
return false;
});
if (these.device) {
clearInterval(this.Status.intval);
showLoading(these, {
text: '蓝牙连接已恢复,正在验证设备'
});
setTimeout(() => {
these.DeviceVerdict(res.deviceId);
}, 0);
} else {
hideLoading(these);
}
}, pagePath);
//搜索到新设备的回调
ble.addDeviceFound((arr) => { ble.addDeviceFound((arr) => {
if (these.Status.isPageHidden) {
return;
}
arr = arr.devices; arr = arr.devices;
for (var i = 0; i < arr.length; i++) { for (var i = 0; i < arr.length; i++) {
@ -246,8 +322,11 @@
} }
console.log("EquipMents=", these.EquipMents) console.log("EquipMents=", these.EquipMents)
}, pagePath); }, pagePath);
//收到设备的消息回调
ble.addReceiveCallback((receivData, f, path, arr) => { ble.addReceiveCallback((receivData, f, path, arr) => {
if (these.Status.isPageHidden) {
return;
}
if (f.macAddress && these.device) { if (f.macAddress && these.device) {
clearInterval(this.Status.intval); clearInterval(this.Status.intval);
this.Status.intval = null; this.Status.intval = null;
@ -265,6 +344,7 @@
}, pagePath); }, pagePath);
} }
if (search) { if (search) {
@ -281,6 +361,7 @@
}, },
onShow: function() { onShow: function() {
this.Status.isPageHidden = false;
this.refreshBleList(); this.refreshBleList();
}, },
methods: { methods: {
@ -288,26 +369,37 @@
if (!ble) { if (!ble) {
return; return;
} }
let promis = [];
for (let index = 0; index < this.PairEquip.length; index++) {
let item = this.PairEquip[index];
promis.push(ble.disconnectDevice(item.deviceId));
ble.StopSearch().then(res => { }
// console.log("停止搜索成功");
this.EquipMents = []; Promise.allSettled(promis).finally(() => {
ble.StartSearch().then(result => { ble.StopSearch().then(res => {
// console.log("开始搜索成功"); // console.log("停止搜索成功");
}).catch(err => { these.EquipMents = [];
console.error("开始搜索失败,err=", err); these.PairEquip = [];
if(err.code===10001){ ble.StartSearch().then(result => {
these.showOpenSetting(); // console.log("开始搜索成功");
}else{ }).catch(err => {
uni.showModal({ console.error("开始搜索失败,err=", err);
title:'提示', if (err.code === 10001) {
content:'出现异常:'+err.msg these.showOpenSetting();
}); } else {
} uni.showModal({
title: '提示',
content: '出现异常:' + err.msg
});
}
});
}).catch(ex => {
console.error("ex=", ex);
}); });
}).catch(ex => {
console.error("ex=", ex);
}); });
}, },
isItemLink: function(item, index) { isItemLink: function(item, index) {
let src = '/static/images/BLEAdd/noLink.png'; let src = '/static/images/BLEAdd/noLink.png';
@ -348,15 +440,16 @@
}); });
let removeLink = () => { let removeLink = () => {
ble.subScribe(deviceId, false); //取消订阅消息 ble.subScribe(deviceId, false); //取消订阅消息
ble.DropDevice(deviceId); //从缓存中删除该设备 ble.DropDevice(deviceId, null); //从缓存中删除该设备并断开连接
ble.disconnectDevice(deviceId); //断开与该设备的连接
these.device.deviceMac = ""; these.device.deviceMac = "";
let index = this.PairEquip.findIndex(function(v) { let index = these.PairEquip.findIndex(function(v) {
return v.deviceId == deviceId; return v.deviceId == deviceId;
}); });
if (index > -1) { if (index > -1) {
this.PairEquip.splice(index, 1); this.PairEquip.splice(index, 1);
} }
} }
console.log("f=", f); console.log("f=", f);
@ -372,24 +465,30 @@
hideLoading(these); hideLoading(these);
}, 1000) }, 1000)
return; return;
} } else {
}
hideLoading(these); hideLoading(these);
ble.updateCache(); ble.updateCache();
uni.navigateBack(); uni.navigateBack();
return true; return true;
} else { } else {
this.Status.time = 30; this.Status.time = 30;
showLoading(these, {
text: "等待设备上报Mac地址," + these.Status.time + 's'
});
console.log("11111111", this.Status.time);
clearInterval(this.Status.intval);
this.Status.intval = null; this.Status.intval = null;
this.Status.intval = setInterval(() => { this.Status.intval = setInterval(() => {
this.Status.time = this.Status.time - 1; this.Status.time = this.Status.time - 1;
if (this.Status.time < 0) { if (this.Status.time < 0) {
console.log("停止倒计时", this.Status.time);
clearInterval(this.Status.intval) clearInterval(this.Status.intval)
this.Status.intval = null; this.Status.intval = null;
this.Status.time = null; this.Status.time = null;
@ -408,15 +507,14 @@
setTimeout(() => { setTimeout(() => {
hideLoading(these) hideLoading(these)
}, 1000); }, 1500);
} }
return; return;
} }
updateLoading(these, {
updateLoading(these, {
text: "等待设备上报Mac地址," + these.Status.time + 's' text: "等待设备上报Mac地址," + these.Status.time + 's'
}); });
}, 1000); }, 1000);
return undefined; return undefined;
} }
@ -617,22 +715,24 @@
} }
@keyframes expand { @keyframes expand {
0% { 0% {
width: 0; width: 0;
height: 0; height: 0;
opacity: 0.8; opacity: 0.8;
} }
80% {
width: 18.75rem; 80% {
height: 18.75rem; width: 18.75rem;
opacity: 0.2; height: 18.75rem;
} opacity: 0.2;
100% { }
width: 0.5rem; 100% {
height: 0.5rem;
opacity: 0.5; width: 0.5rem;
} height: 0.5rem;
opacity: 0.5;
}
} }
.mainContent { .mainContent {

View File

@ -458,7 +458,7 @@
} }
console.log("111111",this.deviceId); console.log("111111",this.deviceId);
console.log("ble==null,",ble) console.log("ble==null,",ble)
ble && ble.DropDevice(this.deviceId.id); ble && ble.DropDevice(null,this.deviceId.id);
} else { } else {
uni.showToast({ uni.showToast({
title: res.msg, title: res.msg,

View File

@ -84,6 +84,7 @@
} }
}, },
onLoad() { onLoad() {
this.phone= uni.getStorageSync('phone');
if (uni.getStorageSync("token") && uni.getStorageSync("clientID")) { //免登陆 if (uni.getStorageSync("token") && uni.getStorageSync("clientID")) { //免登陆
let time = uni.getStorageSync("tokenTime"); let time = uni.getStorageSync("tokenTime");
if (!time) { if (!time) {
@ -101,7 +102,7 @@
uni.removeStorageSync("token") uni.removeStorageSync("token")
uni.removeStorageSync("clientID") uni.removeStorageSync("clientID")
uni.removeStorageSync("tokenTime") uni.removeStorageSync("tokenTime")
this.phone= uni.getStorageInfoSync('phone');
} }
} }

View File

@ -22,7 +22,7 @@
<text class="title">隐私协议</text> <text class="title">隐私协议</text>
<uni-icons type="right" size="25" color="rgba(255, 255, 255, 0.4)" class="uniIcon"></uni-icons> <uni-icons type="right" size="25" color="rgba(255, 255, 255, 0.4)" class="uniIcon"></uni-icons>
</view> </view>
<view class="menu-item" @click="gotoAppStore()"> <view class="menu-item" @click="gotoAppStore()" v-if="appVersion?true:false">
<image src="/static/images/common/ver.png" class="icon"></image> <image src="/static/images/common/ver.png" class="icon"></image>
<text class="title">版本更新 ({{appVersion}})</text> <text class="title">版本更新 ({{appVersion}})</text>
<uni-icons type="right" size="25" color="rgba(255, 255, 255, 0.4)" class="uniIcon"></uni-icons> <uni-icons type="right" size="25" color="rgba(255, 255, 255, 0.4)" class="uniIcon"></uni-icons>

View File

@ -17,13 +17,13 @@ const serviceDic = [ //合作供应商的蓝牙主服务
class BleHelper { class BleHelper {
constructor() { constructor() {
this.StorageKey = "linkedDevices"; this.StorageKey = "linkedDevices";
recei = receivTool.getBleReceive(); recei = receivTool.getBleReceive();
this.init(); this.init();
} }
init() { init() {
var store = uni.getStorageInfoSync(); var store = uni.getStorageInfoSync();
var f = store.keys.includes(this.StorageKey); var f = store.keys.includes(this.StorageKey);
var linkedDevices = []; var linkedDevices = [];
@ -39,7 +39,7 @@ class BleHelper {
}); });
} }
setTimeout(() => { setTimeout(() => {
this.OpenBlue().then(() => { this.OpenBlue().then(() => {
@ -54,14 +54,15 @@ class BleHelper {
searchList: [], //已搜索到的设备列表, searchList: [], //已搜索到的设备列表,
isSubscribe: false, //是否开启了订阅 isSubscribe: false, //是否开启了订阅
LinkedList: linkedDevices //已连接的设备列表 LinkedList: linkedDevices //已连接的设备列表
} }
this.cfg = { this.cfg = {
onDeviceFound: [], //发现新设备的事件 onDeviceFound: [], //发现新设备的事件
receivDataCallback: [], //接收到数据的事件 receivDataCallback: [], //接收到数据的事件
bleDisposeCallback: [], //蓝牙断开连接的事件 bleDisposeCallback: [], //蓝牙断开连接的事件
recoveryCallback: [], //蓝牙连接恢复的事件 recoveryCallback: [], //蓝牙连接恢复的事件
stateRecoveryCallback: [] //蓝牙适配器恢复可用事件 stateRecoveryCallback: [], //蓝牙适配器恢复可用事件
stateBreakCallback: [] //蓝牙适配器不可用事件
} }
// this.addReceiveCallback((a, b, c) => { // this.addReceiveCallback((a, b, c) => {
// recei.ReceiveData(a, b, c); // recei.ReceiveData(a, b, c);
@ -128,13 +129,13 @@ class BleHelper {
} }
//从缓存中删除某个设备bleId蓝牙iddeviceId数据库中的设备id //从缓存中删除某个设备bleId蓝牙iddeviceId数据库中的设备id
DropDevice(bleId, deviceId) { DropDevice(bleId, deviceId) {
let flag = false; let flag = false;
for (var i = 0; i < this.data.LinkedList.length; i++) { for (var i = 0; i < this.data.LinkedList.length; i++) {
let item = this.data.LinkedList[i]; let item = this.data.LinkedList[i];
if (bleId && item.device) { if (deviceId && item.device) {
if (item.device.id == bleId) { if (item.device.id == deviceId) {
// console.log("找到要删除的设备", item); console.log("找到要删除的设备", item);
this.data.LinkedList.splice(i, 1); this.data.LinkedList.splice(i, 1);
this.disconnectDevice(item.deviceId); this.disconnectDevice(item.deviceId);
flag = true; flag = true;
@ -142,16 +143,16 @@ class BleHelper {
} }
} else { } else {
if (deviceId && item.deviceId == deviceId) { if (bleId && item.deviceId == bleId) {
// console.log("找到要删除的设备1,", item) console.log("找到要删除的设备1,", item)
this.data.LinkedList.splice(i, 1); this.data.LinkedList.splice(i, 1);
this.disconnectDevice(item.deviceId); this.disconnectDevice(item.deviceId);
flag = true; flag = true;
break; break;
} }
} }
} }
if (flag) { if (flag) {
this.updateCache(); this.updateCache();
} }
@ -159,9 +160,9 @@ class BleHelper {
//更新缓存 //更新缓存
updateCache() { updateCache() {
uni.setStorageSync(this.StorageKey, this.data.LinkedList); uni.setStorageSync(this.StorageKey, this.data.LinkedList);
} }
//连接所有已连接过的设备 //连接所有已连接过的设备
linkAllDevices() { linkAllDevices() {
@ -248,60 +249,80 @@ class BleHelper {
} }
//设置蓝牙适配器恢复可用的回调
addstateRecoveryCallback(callback, currKey) {
addCallback(callback, currKey, 'stateRecoveryCallback');
}
//移除蓝牙适配器恢复的回调
removestateRecoveryCallback(currKey) {
removeCallback(currKey, 'stateRecoveryCallback');
}
//设置蓝牙恢复连接的回调 //设置蓝牙恢复连接的回调
addRecoveryCallback(callback, currKey) { addRecoveryCallback(callback, currKey) {
addCallback(callback, currKey, 'recoveryCallback'); this.addCallback(callback, currKey, 'recoveryCallback');
} }
//移除蓝牙恢复连接的回调 //移除蓝牙恢复连接的回调
removeRecoveryCallback(currKey) { removeRecoveryCallback(currKey) {
removeCallback(currKey, 'recoveryCallback'); this.removeCallback(currKey, 'recoveryCallback');
} }
//设置蓝牙断开连接的回调 //设置蓝牙断开连接的回调
addDisposeCallback(callback, currKey) { addDisposeCallback(callback, currKey) {
addCallback(callback, currKey, 'bleDisposeCallback'); this.addCallback(callback, currKey, 'bleDisposeCallback');
} }
//移除蓝牙断开连接的回调 //移除蓝牙断开连接的回调
removeDisposeCallback(currKey) { removeDisposeCallback(currKey) {
removeCallback(currKey, 'bleDisposeCallback'); this.removeCallback(currKey, 'bleDisposeCallback');
} }
//设置发现新设备的回调 //设置发现新设备的回调
addDeviceFound(callback, currKey) { addDeviceFound(callback, currKey) {
addCallback(callback, currKey, 'onDeviceFound'); this.addCallback(callback, currKey, 'onDeviceFound');
} }
//移除发现新设备的回调 //移除发现新设备的回调
removeDeviceFound(currKey) { removeDeviceFound(currKey) {
removeCallback(currKey, 'onDeviceFound'); this.removeCallback(currKey, 'onDeviceFound');
} }
//添加接收到数据的回调 //添加接收到数据的回调
addReceiveCallback(callback, currKey) { addReceiveCallback(callback, currKey) {
addCallback(callback, currKey, 'receivDataCallback'); this.addCallback(callback, currKey, 'receivDataCallback');
} }
//移除接收到数据的回调
//设置接收到数据的回调
removeReceiveCallback(currKey) { removeReceiveCallback(currKey) {
removeCallback(currKey, 'receivDataCallback'); this.removeCallback(currKey, 'receivDataCallback');
} }
//添加蓝牙不可用的回调
addStateBreakCallback(callback, currKey) {
this.addCallback(callback, currKey, 'stateBreakCallback');
}
//移除蓝牙不可用的回调
removeStateBreakCallback(currKey) {
this.removeCallback(currKey, 'stateBreakCallback');
}
//设置蓝牙适配器恢复可用的回调
addStateRecoveryCallback(callback, currKey) {
this.addCallback(callback, currKey, 'stateRecoveryCallback');
}
//移除蓝牙适配器恢复的回调
removeStateRecoveryCallback(currKey) {
this.removeCallback(currKey, 'stateRecoveryCallback');
}
//清除所有事件回调
removeAllCallback(currKey) {
this.removeDeviceFound(currKey)
this.removeDisposeCallback(currKey);
this.removeReceiveCallback(currKey);
this.removeRecoveryCallback(currKey);
this.removeStateRecoveryCallback(currKey);
this.removeStateBreakCallback(currKey);
}
getError(ex) { getError(ex) {
@ -461,6 +482,9 @@ class BleHelper {
console.log("开始订阅各类变化消息"); console.log("开始订阅各类变化消息");
this.data.isSubscribe = true; this.data.isSubscribe = true;
// 保存每个设备的连接状态
let bleDeviceStates = {};
var bytesToHexString = (bytes) => { var bytesToHexString = (bytes) => {
return bytes.map(byte => byte.toString(16).padStart(2, return bytes.map(byte => byte.toString(16).padStart(2,
@ -468,21 +492,24 @@ class BleHelper {
} }
uni.onBluetoothAdapterStateChange((state) => { uni.onBluetoothAdapterStateChange((state) => {
console.log('蓝牙状态发生变化:' + JSON.stringify(state)); // console.log('蓝牙状态发生变化:' + JSON.stringify(state));
if (this.data.available !== state.available) { if (this.data.available !== state.available) {
this.data.available = state.available; this.data.available = state.available;
this.data.discovering = state.discovering; this.data.discovering = state.discovering;
if (this.data.available && this.data if (this.data.available && this.data
.isOpenBlue) { //蓝牙状态再次可用,重连所有设备 .isOpenBlue) { //蓝牙状态再次可用,重连所有设备
if(this.cfg.stateRecoveryCallback.length>0){ if (this.cfg.stateRecoveryCallback.length > 0) {
this.cfg.stateRecoveryCallback.forEach(c=>{ this.cfg.stateRecoveryCallback.forEach(
try { c => {
c.callback(); try {
} catch (error) { c.callback();
console.error("蓝牙适配器已恢复,但回调函数发生错误",error); } catch (error) {
} console.error(
}) "蓝牙适配器已恢复,但回调函数发生错误",
error);
}
})
} }
} }
@ -490,60 +517,99 @@ class BleHelper {
if (!state.available) { //蓝牙状态不可用了,将所有设备标记为断开连接 if (!state.available) { //蓝牙状态不可用了,将所有设备标记为断开连接
this.data.LinkedList.filter((v) => { this.data.LinkedList.filter((v) => {
v.Linked = false; v.Linked = false;
v.notifyState = false; v.notifyState = false;
return true; 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)
}
})
this.updateCache(); this.updateCache();
} }
}); });
uni.onBLEConnectionStateChange((res) => { uni.onBLEConnectionStateChange((res) => {
console.log("蓝牙连接状态变化了", res);
if (!res.connected) { // 检查状态是否真的发生了变化
if (bleDeviceStates[res.deviceId] === res.connected) {
console.error("蓝牙已断开", res); console.error('专业给Uniapp填坑,连接状态');
let f = this.data.LinkedList.find((v) => { return;
if (v.deviceId == res.deviceId) {
v.Linked = false;
v.notifyState = false;
return true;
}
return false;
});
this.updateCache();
if (f.device && f.device.id) {
console.log("尝试5次恢复连接,", f.deviceId);
this.LinkBlue(res.deviceId, f.writeServiceId, f
.wirteCharactId, f.notifyCharactId, 5);
}
if (this.cfg.bleDisposeCallback.length > 0) {
this.cfg.bleDisposeCallback.forEach((c)=>{
try {
c.callback();
} catch (error) {
console.error("执行蓝牙断开连接的回调出现异常,", error)
}
});
}
} else {
console.log("蓝牙连接已恢复,", res);
if (this.cfg.recoveryCallback.length > 0) {
this.cfg.recoveryCallback.forEach((c)=>{
try {
c.callback();
} catch (error) {
console.error("执行蓝牙恢复连接的回调出现异常,", error)
}
});
}
} }
// 更新状态记录
bleDeviceStates[res.deviceId] = res.connected;
setTimeout(() => {
if (!res.connected) {
console.error("蓝牙已断开", res);
let f = this.data.LinkedList.find((
v) => {
if (v.deviceId == res
.deviceId) {
v.Linked = false;
v.notifyState = false;
return true;
}
return false;
});
this.updateCache();
if (f && f.device && f.device.id) {
console.log("尝试5次恢复连接,", f
.deviceId);
this.LinkBlue(res.deviceId, f
.writeServiceId, f
.wirteCharactId, f
.notifyCharactId, 5);
}
if (this.cfg.bleDisposeCallback.length >
0) {
this.cfg.bleDisposeCallback.forEach(
(c) => {
try {
c.callback(res);
} catch (error) {
console.error(
"执行蓝牙断开连接的回调出现异常,",
error)
}
});
}
} else {
console.log("蓝牙连接已恢复,", res);
if (this.cfg.recoveryCallback.length >
0) {
this.cfg.recoveryCallback.forEach((
c) => {
try {
c.callback(res);
} catch (error) {
console.error(
"执行蓝牙恢复连接的回调出现异常,",
error)
}
});
}
}
}, 0);
}); });
uni.onBluetoothDeviceFound((res) => { uni.onBluetoothDeviceFound((res) => {
@ -556,11 +622,14 @@ class BleHelper {
.includes(v.serviceId); .includes(v.serviceId);
}); });
if (f) { if (f) {
console.log("发现新设备:", item);
arr.push(item); arr.push(item);
} }
} }
if (arr.length === 0) { if (arr.length === 0) {
// console.error("发现了设备,但不是想要的设备", res);
return; return;
} }
res.devices = arr; res.devices = arr;
@ -569,7 +638,13 @@ class BleHelper {
if (this.cfg.onDeviceFound) { if (this.cfg.onDeviceFound) {
if (this.cfg.onDeviceFound.length > 0) { if (this.cfg.onDeviceFound.length > 0) {
this.cfg.onDeviceFound.forEach((found) => { this.cfg.onDeviceFound.forEach((found) => {
found.callback(res); try {
found.callback(res);
} catch (error) {
console.error("处理发现设备的回调出现异常,",
error);
}
}); });
} }
@ -745,12 +820,12 @@ class BleHelper {
uni.closeBluetoothAdapter({ uni.closeBluetoothAdapter({
success: () => { success: () => {
// console.log("蓝牙模块已关闭"); // console.log("蓝牙模块已关闭");
this.data.isOpenBlue = false;
}, },
fail: (ex) => { fail: (ex) => {
console.error('无法关闭蓝牙模块:', ex); console.error('无法关闭蓝牙模块:', ex);
ex = this.getError(ex); ex = this.getError(ex);
////console.log(msg);
}, },
complete: () => { complete: () => {
resolve(); resolve();
@ -842,13 +917,14 @@ class BleHelper {
err({ err({
code: -1 code: -1
}); });
}, 50); }, 100);
}); });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Promise.race([p1, p2]).then(resolve).catch(ex => { Promise.race([p1, p2]).then(resolve).catch(ex => {
if (ex.code == -1) { if (ex.code == -1) {
console.error('专业给Uniapp填坑,停止搜索');
resolve(); resolve();
return; return;
} }
@ -960,6 +1036,7 @@ class BleHelper {
Promise.race([p1, p2]).then(succ).catch(ex => { Promise.race([p1, p2]).then(succ).catch(ex => {
// console.error("异常了:",ex); // console.error("异常了:",ex);
if (ex.code == -1) { if (ex.code == -1) {
console.error('专业给Uniapp填坑,订阅成功');
succ(); succ();
return; return;
} }
@ -1342,7 +1419,7 @@ class BleHelper {
}, },
fail: () => { fail: () => {
console.error( console.error(
"mtu设置失败"); "mtu设置失败");
resolve( resolve(
true true
); // MTU设置失败不影响连接成功 ); // MTU设置失败不影响连接成功
@ -1358,7 +1435,7 @@ class BleHelper {
fail: (ex) => { fail: (ex) => {
ex = this.getError(ex); ex = this.getError(ex);
console.error("蓝牙" + deviceId + "连接失败" + JSON.stringify( console.error("蓝牙" + deviceId + "连接失败" + JSON.stringify(
ex)); ex));
// 连接超时后自动重试 // 连接超时后自动重试
if (ex.code === 10012 && retryCount < maxRetries) { if (ex.code === 10012 && retryCount < maxRetries) {
@ -1441,12 +1518,12 @@ class BleHelper {
uni.closeBLEConnection({ uni.closeBLEConnection({
deviceId: id, deviceId: id,
success: (res) => { success: (res) => {
console.log("蓝牙连接已断开:" + id); console.log("用户主动断开了蓝牙:" + id);
this.subScribe(id, false); this.subScribe(id, false);
resolve(); resolve();
}, },
fail: (ex) => { fail: (ex) => {
console.error("无法断开蓝牙连接", ex);
reject(this.getError(ex)); reject(this.getError(ex));
} }
}); });
@ -1570,6 +1647,7 @@ class BleHelper {
Promise.race([timeOut(ms), promise]).then(resolve).catch((ex) => { Promise.race([timeOut(ms), promise]).then(resolve).catch((ex) => {
// console.error("ex=", ex); // console.error("ex=", ex);
if (ex.code == -1) { if (ex.code == -1) {
console.error('专业给Uniapp填坑,发送成功');
resolve(ex); resolve(ex);
} else { } else {
reject(ex); reject(ex);