7305添加文字发送、图片发送。蓝牙通用模块增加连接/断开订阅

This commit is contained in:
liub
2025-10-16 11:07:04 +08:00
parent fe87727e2d
commit 0ce4f4bef0
7 changed files with 191 additions and 285 deletions

View File

@ -30,7 +30,7 @@
//以上代码仅在开发时使用,否则会出现不可预知的问题。
uni.getSystemInfo({success:function(res){
if(res.uniPlatform=='app'){
if(res.uniPlatform=='app'){
bleTool.getBleTool();
upgrade.checkAndUpdateWgt();

View File

@ -2,7 +2,7 @@
"name" : "星汉物联",
"appid" : "__UNI__A21EF43",
"description" : "设备管控",
"versionName" : "1.0.4",
"versionName" : "1.0.3",
"versionCode" : "100",
"transformPx" : false,
/* 5+App */

View File

@ -20,17 +20,17 @@
src: "",
Statu: false,
width:160,
height:80
height:80,
times:10
}
},
computed:{
cropWidth(){
return this.width*10;
return this.width*this.times;
}
,
cropHeight(){
return this.height*10;
return this.height*this.times;
}
},
onLoad: function(option) {
@ -41,6 +41,7 @@
this.src = rec.data;
this.width=rec.width?rec.width:160;
this.height=rec.height?rec.height:80;
this.times=rec.times?rec.times:10;
})
},
methods: {

View File

@ -430,88 +430,25 @@
},
bleValueNotify: function(receive, device, path) {
let str = recei.ReceiveData(receive, device, path);
console.log("处理接收到的数据:" + str);
return;
let data = recei.ReceiveData(receive, device, path);
let bytes = receive.bytes;
if (bytes[0] == 0xFB && bytes[1] == 0x64 && bytes.length >= 8) {
try {
let staticLevelByte = bytes[2];
let getName = function(type) {
let name = "";
switch (type) {
case 0x02:
name = '弱光';
break;
case 0x04:
name = '工作光';
break;
case 0x01:
name = '强光';
break;
case 0x03:
name = '爆闪';
break;
case 0x00:
name = '关闭';
break;
}
return name;
}
let staticLevelText = getName(staticLevelByte);
// 解析照明档位
let lightingLevelByte = bytes[3];
let lightingLevelText = getName(lightingLevelByte);
// 解析剩余电量
let batteryLevelByte = bytes[4];
// 电量百分比范围检查
let batteryLevel = Math.max(0, Math.min(100, batteryLevelByte));
//充电状态
let warn = bytes[5];
if (warn == 0x00) {
warn = '未充电';
} else if (warn == 0x01) {
warn = '充电中';
}
// 解析剩余照明时间(第三和第四字节,小端序)
let lightingTime = "";
let HH = Math.max(0, Math.min(100, bytes[6]));
let mm = Math.max(0, Math.min(100, bytes[7]));
lightingTime = HH + "小时" + mm + "分钟";
this.formData.mode = staticLevelText;
this.formData.fuMode = lightingLevelText;
this.formData.battary = batteryLevel;
this.formData.statu = warn;
this.formData.xuhang = lightingTime;
if (batteryLevel <= 20) {
this.showPop({
message: "设备电量低",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
}
this.setBleFormData();
} catch (error) {
console.log('数据解析错误:', error);
}
let json = recei.ReceiveData(receive, device, path);
if(!json){
return;
}
let keys=Object.keys(json);
keys.forEach((key)=>{
if(key in these.formData){
these.formData[key] = json[key];
}
});
if (this.formData.battary <= 20) {
this.showPop({
message: "设备电量低",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
}
},
proParam: function() {

View File

@ -430,86 +430,24 @@
},
bleValueNotify: function(receive, device, path) {
let str = recei.ReceiveData(receive, device, path);
console.log("处理接收到的数据:" + str);
return;
let data = recei.ReceiveData(receive, device, path);
let bytes = receive.bytes;
if (bytes[0] == 0xFB && bytes[1] == 0x64 && bytes.length >= 8) {
try {
let staticLevelByte = bytes[2];
let getName = function(type) {
let name = "";
switch (type) {
case 0x02:
name = '弱光';
break;
case 0x04:
name = '工作光';
break;
case 0x01:
name = '强光';
break;
case 0x03:
name = '爆闪';
break;
case 0x00:
name = '关闭';
break;
}
return name;
}
let staticLevelText = getName(staticLevelByte);
// 解析照明档位
let lightingLevelByte = bytes[3];
let lightingLevelText = getName(lightingLevelByte);
// 解析剩余电量
let batteryLevelByte = bytes[4];
// 电量百分比范围检查
let batteryLevel = Math.max(0, Math.min(100, batteryLevelByte));
//充电状态
let warn = bytes[5];
if (warn == 0x00) {
warn = '未充电';
} else if (warn == 0x01) {
warn = '充电中';
}
// 解析剩余照明时间(第三和第四字节,小端序)
let lightingTime = "";
let HH = Math.max(0, Math.min(100, bytes[6]));
let mm = Math.max(0, Math.min(100, bytes[7]));
lightingTime = HH + "小时" + mm + "分钟";
this.formData.mode = staticLevelText;
this.formData.fuMode = lightingLevelText;
this.formData.battary = batteryLevel;
this.formData.statu = warn;
this.formData.xuhang = lightingTime;
if (batteryLevel <= 20) {
this.showPop({
message: "设备电量低",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
}
this.setBleFormData();
} catch (error) {
console.log('数据解析错误:', error);
}
let json = recei.ReceiveData(receive, device, path);
if(!json){
return;
}
let keys=Object.keys(json);
keys.forEach((key)=>{
if(key in these.formData){
these.formData[key] = json[key];
}
});
if (this.formData.battary <= 20) {
this.showPop({
message: "设备电量低",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
}
},

View File

@ -120,7 +120,7 @@
// 确定
handleAgree() {
// 退出登录
Logout().then((res) => {
Logout().finally((res) => {
this.showAgreement = false
uni.showTabBar()
// 1. 清除本地存储的 token

View File

@ -17,18 +17,18 @@ const serviceDic = [ //合作供应商的蓝牙主服务
class BleHelper {
constructor() {
this.StorageKey = "linkedDevices";
this.dropKey = "DeletedDevices";
recei = receivTool.getBleReceive();
this.init();
}
init() {
let key = this.StorageKey;
var store = uni.getStorageInfoSync();
var f = store.keys.includes(key);
var f = store.keys.includes(this.StorageKey);
var linkedDevices = [];
if (f) {
linkedDevices = uni.getStorageSync(key);
linkedDevices = uni.getStorageSync(this.StorageKey);
}
if (linkedDevices && linkedDevices.length && linkedDevices.length > 0) {
// console.log("111111", linkedDevices);
@ -39,11 +39,7 @@ class BleHelper {
});
}
var deletedEqs = [];
f = store.keys.includes(this.dropKey);
if (f) {
deletedEqs = uni.getStorageSync(this.dropKey);
}
setTimeout(() => {
this.OpenBlue().then(() => {
@ -57,12 +53,15 @@ class BleHelper {
discovering: false, //蓝牙是否正在搜索
searchList: [], //已搜索到的设备列表,
isSubscribe: false, //是否开启了订阅
LinkedList: linkedDevices, //已连接的设备列表
deletedEqs: deletedEqs
LinkedList: linkedDevices //已连接的设备列表
}
this.cfg = {
onDeviceFound: [], //发现新设备的事件
receivDataCallback: [] //接收到数据的事件
receivDataCallback: [], //接收到数据的事件
bleDisposeCallback: [], //蓝牙断开连接的事件
recoveryCallback: [], //蓝牙连接恢复的事件
stateRecoveryCallback: [] //蓝牙适配器恢复可用事件
}
// this.addReceiveCallback((a, b, c) => {
// recei.ReceiveData(a, b, c);
@ -129,13 +128,8 @@ class BleHelper {
}
//从缓存中删除某个设备bleId蓝牙iddeviceId数据库中的设备id
DropDevice(bleId, deviceId) {
let flag = false;
let delItem=null;
if (!this.data.deletedEqs || !this.data.deletedEqs.length) {
this.data.deletedEqs = [];
}
let flag = false;
for (var i = 0; i < this.data.LinkedList.length; i++) {
let item = this.data.LinkedList[i];
if (bleId && item.device) {
@ -144,9 +138,6 @@ class BleHelper {
this.data.LinkedList.splice(i, 1);
this.disconnectDevice(item.deviceId);
flag = true;
delItem=item;
break;
}
@ -155,21 +146,12 @@ class BleHelper {
// console.log("找到要删除的设备1,", item)
this.data.LinkedList.splice(i, 1);
this.disconnectDevice(item.deviceId);
flag = true;
delItem=item;
flag = true;
break;
}
}
}
if (flag) {
this.data.deletedEqs=this.data.deletedEqs.filter(v => {
return v.deviceId != delItem.deviceId;
});
this.data.deletedEqs.push(delItem);
if (flag) {
this.updateCache();
}
@ -177,11 +159,11 @@ class BleHelper {
//更新缓存
updateCache() {
// console.log("this.StorageKey=", this.StorageKey)
uni.setStorageSync(this.StorageKey, this.data.LinkedList);
uni.setStorageSync(this.dropKey, this.data.deletedEqs);
}
//连接所有已连接过的设备
linkAllDevices() {
// console.log("模块启动时,自动连接已连接过的设备", this.data.LinkedList);
@ -205,7 +187,7 @@ class BleHelper {
this.updateCache();
}
}
//获取当前页面栈
getCurrentPagePath() {
const pages = getCurrentPages();
@ -218,91 +200,106 @@ class BleHelper {
// console.log("currentPage=", currentPage.route);
return currentPage.route;
}
//设置发现新设备的回调
addDeviceFound(callback, currKey) {
//添加事件回调
addCallback(callback, currKey, type) {
if (!type) {
return;
}
let key = currKey ? currKey : this.getCurrentPagePath();
if (!key) {
key = new Date().getTime();
}
if (key) {
// console.log("key=" + key);
let f = this.cfg.onDeviceFound.findIndex((v) => {
let f = this.cfg[type].findIndex((v) => {
return v.key == key;
});
if (f > -1) {
this.cfg.onDeviceFound[f].callback = callback;
this.cfg[type][f].callback = callback;
return;
}
this.cfg.onDeviceFound.push({
this.cfg[type].push({
key: key,
callback: callback
});
}
}
//移除事件回调
removeCallback(currKey, type) {
if (!type) {
return;
}
let key = currKey ? currKey : this.getCurrentPagePath();
if (key) {
// console.log("key=" + key);
let f = this.cfg[type].findIndex((v) => {
return v.key == key;
});
if (f > -1) {
this.cfg[type].splice(f, 1);
}
} else {
if (this.cfg[type].length > 0) {
this.cfg[type].splice(this.cfg[type].length - 1, 1);
}
}
}
//设置蓝牙适配器恢复可用的回调
addstateRecoveryCallback(callback, currKey) {
addCallback(callback, currKey, 'stateRecoveryCallback');
}
//移除蓝牙适配器恢复的回调
removestateRecoveryCallback(currKey) {
removeCallback(currKey, 'stateRecoveryCallback');
}
//设置蓝牙恢复连接的回调
addRecoveryCallback(callback, currKey) {
addCallback(callback, currKey, 'recoveryCallback');
}
//移除蓝牙恢复连接的回调
removeRecoveryCallback(currKey) {
removeCallback(currKey, 'recoveryCallback');
}
//设置蓝牙断开连接的回调
addDisposeCallback(callback, currKey) {
addCallback(callback, currKey, 'bleDisposeCallback');
}
//移除蓝牙断开连接的回调
removeDisposeCallback(currKey) {
removeCallback(currKey, 'bleDisposeCallback');
}
//设置发现新设备的回调
addDeviceFound(callback, currKey) {
addCallback(callback, currKey, 'onDeviceFound');
}
//移除发现新设备的回调
removeDeviceFound(currKey) {
let key = currKey ? currKey : this.getCurrentPagePath();
if (key) {
// console.log("key=" + key);
let f = this.cfg.onDeviceFound.findIndex((v) => {
return v.key == key;
});
if (f > -1) {
this.cfg.onDeviceFound.splice(f, 1);
}
} else {
if (this.cfg.onDeviceFound.length > 0) {
this.cfg.onDeviceFound.splice(this.cfg.onDeviceFound.length - 1, 1);
}
}
removeCallback(currKey, 'onDeviceFound');
}
//添加接收到数据的回调
addReceiveCallback(callback, currKey) {
let key = currKey ? currKey : this.getCurrentPagePath();
if (!key) {
key = new Date().getTime();
}
if (key) {
// console.log("订阅消息回调,key=" + key);
let f = this.cfg.receivDataCallback.findIndex((v) => {
return v.key == key;
});
if (f > -1) {
this.cfg.receivDataCallback.callback = callback;
return;
}
this.cfg.receivDataCallback.push({
key: key,
callback: callback
});
}
addCallback(callback, currKey, 'receivDataCallback');
}
//设置接收到数据的回调
removeReceiveCallback(currKey) {
let key = currKey ? currKey : this.getCurrentPagePath();
if (key) {
// console.log("移除消息回调:" + key);
let f = this.cfg.receivDataCallback.findIndex((v) => {
return v.key == key;
});
if (f > -1) {
this.cfg.receivDataCallback.splice(f, 1);
}
} else {
if (this.cfg.receivDataCallback.length > 0) {
this.cfg.receivDataCallback.splice(this.cfg.receivDataCallback.length - 1, 1);
}
}
removeCallback(currKey, 'receivDataCallback');
}
@ -453,7 +450,7 @@ class BleHelper {
uni.openBluetoothAdapter({
success: (args) => {
// console.log("蓝牙初始化成功:" + JSON.stringify(args));
// console.log("蓝牙初始化成功:" + JSON.stringify(args));
this.data.isOpenBlue = true;
this.data.available = true;
resolve(true);
@ -461,7 +458,7 @@ class BleHelper {
if (this.data.isSubscribe) { //整个App生命周期只订阅一次
return;
}
console.log("开始订阅各类变化消息");
console.log("开始订阅各类变化消息");
this.data.isSubscribe = true;
@ -471,13 +468,22 @@ class BleHelper {
}
uni.onBluetoothAdapterStateChange((state) => {
console.log('蓝牙状态发生变化:' + JSON.stringify(state));
console.log('蓝牙状态发生变化:' + JSON.stringify(state));
if (this.data.available !== state.available) {
this.data.available = state.available;
this.data.discovering = state.discovering;
if (this.data.available && this.data
.isOpenBlue) { //蓝牙状态再次可用,重连所有设备
// this.linkAllDevices();
if(this.cfg.stateRecoveryCallback.length>0){
this.cfg.stateRecoveryCallback.forEach(c=>{
try {
c.callback();
} catch (error) {
console.error("蓝牙适配器已恢复,但回调函数发生错误",error);
}
})
}
}
}
@ -498,7 +504,7 @@ class BleHelper {
if (!res.connected) {
console.error("蓝牙适配器已不可用", res);
console.error("蓝牙已断开", res);
let f = this.data.LinkedList.find((v) => {
if (v.deviceId == res.deviceId) {
v.Linked = false;
@ -511,31 +517,53 @@ class BleHelper {
if (f.device && f.device.id) {
console.log("尝试5次恢复连接,", f.deviceId);
this.LinkBlue(res.deviceId, f.writeServiceId, f
.wirteCharactId, f.notifyCharactId, 5)
.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);
console.log("蓝牙连接已恢复,", res);
if (this.cfg.recoveryCallback.length > 0) {
this.cfg.recoveryCallback.forEach((c)=>{
try {
c.callback();
} catch (error) {
console.error("执行蓝牙恢复连接的回调出现异常,", error)
}
});
}
}
});
uni.onBluetoothDeviceFound((res) => {
// console.log("发现新设备:" + JSON.stringify(devices));
let arr=[];
let arr = [];
for (var i = 0; i < res.devices.length; i++) {
let item = res.devices[i];
let f=serviceDic.find(v=>{
return item.advertisServiceUUIDs.includes(v.serviceId);
let f = serviceDic.find(v => {
return item.advertisServiceUUIDs
.includes(v.serviceId);
});
if(f){
if (f) {
arr.push(item);
}
}
if(arr.length===0){
if (arr.length === 0) {
return;
}
res.devices=arr;
res.devices = arr;
this.data.searchList = this.data.searchList.concat(
res);
if (this.cfg.onDeviceFound) {
@ -720,7 +748,7 @@ class BleHelper {
this.data.isOpenBlue = false;
},
fail: (ex) => {
console.error('无法关闭蓝牙模块:',ex);
console.error('无法关闭蓝牙模块:', ex);
ex = this.getError(ex);
////console.log(msg);
},
@ -795,7 +823,7 @@ class BleHelper {
//停止搜索
StopSearch() {
let p1= new Promise((resolve, reject) => {
let p1 = new Promise((resolve, reject) => {
uni.stopBluetoothDevicesDiscovery({
success: (res) => {
// console.log("停止搜索蓝牙设备成功");
@ -808,7 +836,7 @@ class BleHelper {
}
});
});
let p2 = new Promise((succ, err) => {
setTimeout(() => {
err({
@ -816,10 +844,10 @@ class BleHelper {
});
}, 50);
});
return new Promise((resolve,reject)=>{
Promise.race([p1,p2]).then(resolve).catch(ex=>{
return new Promise((resolve, reject) => {
Promise.race([p1, p2]).then(resolve).catch(ex => {
if (ex.code == -1) {
resolve();
return;
@ -827,8 +855,8 @@ class BleHelper {
reject(ex);
});
});
}
//获取已连接的设备
@ -1313,7 +1341,8 @@ class BleHelper {
resolve(true);
},
fail: () => {
console.error("mtu设置失败");
console.error(
"mtu设置失败");
resolve(
true
); // MTU设置失败不影响连接成功
@ -1328,7 +1357,8 @@ class BleHelper {
},
fail: (ex) => {
ex = this.getError(ex);
console.error("蓝牙" + deviceId + "连接失败" + JSON.stringify(ex));
console.error("蓝牙" + deviceId + "连接失败" + JSON.stringify(
ex));
// 连接超时后自动重试
if (ex.code === 10012 && retryCount < maxRetries) {