1
0
forked from dyf/APP

Merge pull request 'new-20250827 解决合并冲突' (#38) from liubiao/APP:new-20250827 into main

Reviewed-on: dyf/APP#38
This commit is contained in:
dyf
2026-03-19 11:42:40 +08:00
23 changed files with 792 additions and 418 deletions

35
App.vue
View File

@ -1,6 +1,7 @@
<script>
import bleTool from '@/utils/BleHelper.js'
import upgrade from '@/utils/update.js'
import bleTool from '@/utils/BleHelper.js';
import upgrade from '@/utils/update.js';
export default {
onLaunch: function() {
@ -26,15 +27,13 @@
// uni.removeStorageSync(val);
// }
// });
// uni.clearStorageSync();
uni.clearStorageSync();
//以上代码仅在开发时使用,否则会出现不可预知的问题。
// #ifdef APP|APP-PLUS
if (plus.runtime.isAgreePrivacy()) {
let initOS = () => {
let ble = bleTool.getBleTool();
bleTool.getBleTool();
uni.getPushClientId({
success(res) {
console.log("推送信息:", res);
@ -62,8 +61,13 @@
});
});
}
if (plus.os.name == 'Android') {
if(plus.runtime.isAgreePrivacy()){
initOS();
}
}else{
initOS();
}
// #endif
@ -76,14 +80,23 @@
let appid = plus.runtime.appid;
console.log("appid=", appid);
if (appid !== 'HBuilder') {
if (appid !== 'HBuilder') {
upgrade.checkAndUpdateWgt();
}
// #endif
},
onHide: function() {
console.log('App Hide');
// #ifdef APP|APP-PLUS
let ble = bleTool.getBleTool();
if (ble) {
console.log("断开所有蓝牙设备");
ble.disconnectDevice();
}
// #endif
},
onError(ex) {
console.error("出现了未知的异常", ex);

View File

@ -23,7 +23,7 @@
paddingRight: config.dividerMargin
}" @click="handleItemClick(item, index)">
<view class="p100" :style="{backgroundColor:(config.activeIndex==index || item[config.valueMember]==config.value) ?config.itemBgColor:'',
<view class="p100" :data-acIdx="config.activeIndex" :data-ac="config.activeIndex==index" :style="{backgroundColor:(config.activeIndex==index || (item[config.valueMember]==config.value && config.value) ) ?config.itemBgColor:'',
justifyContent:config.textAlign
}">
<view class="imgContent" v-if="item.icon" :style="{

View File

@ -14,7 +14,7 @@
default: () => [],
validator: (value) => value.every(item => typeof item === 'string')
},
fontSize: {
type: Number,
default: 16,
@ -27,6 +27,10 @@
color: {
type: String,
default: "#000000"
},
maxLength: {
type: Number,
default: 5
}
},
data() {
@ -145,13 +149,21 @@
return hexString;
}
let convertCharToMatrix = (imageData, item) => {
let convertCharToMatrix = (imageData) => {
const charWidth = 13;
const charHeight = 13;
const pixels = [];
for (let i = 0; i < imageData.length; i += 4) {
// const R = imageData[i];
// pixels.push(R < 128 ? 1 : 0);
const R = imageData[i];
pixels.push(R < 128 ? 1 : 0);
const G = imageData[i + 1];
const B = imageData[i + 2];
const gray = 0.299 * R + 0.587 * G + 0.114 * B; // 灰度转换
pixels.push(gray < 128 ? 1 : 0);
}
const lowBytes = new Array(charWidth).fill(0);
@ -173,11 +185,12 @@
}
let drawTxt = async (textLine) => {
debugger;
let result = {};
let ctx = this.ctx;
// 1. 动态调整Canvas尺寸
this.currentCanvasWidth = 13;
this.currentCanvasWidth = 13 * this.maxLength;
this.currentCanvasHeight = 13;
// 2. 清空Canvas绘制背景
@ -191,16 +204,15 @@
ctx.font = `${this.fontSize}px "PingFangBold", "PingFang SC", Arial, sans-serif`;
// 4. 绘制当前行文本
let currentX = 0;
let currentY = this.fontSize / 2 + 1;
for (let j = 0; j < textLine.length; j++) {
let char = textLine[j];
ctx.fillText(char, currentX, currentY);
// 按实际字符宽度计算间距
let charWidth = ctx.measureText(char).width;
currentX += charWidth;
}
debugger;
let currentX =(this.maxLength - textLine.length) * this.fontSize / 2;
let currentY = this.fontSize / 2 + 1;
ctx.fillText(textLine, currentX, currentY);
// 5. 异步绘制并获取像素数据(串行处理避免冲突)
await new Promise((resolve, reject) => {
ctx.draw(false, () => {
@ -212,11 +224,14 @@
width: this.currentCanvasWidth,
height: this.currentCanvasHeight,
success: res => {
debugger;
result = {
line: textLine,
pixelData: res.data,
width: this.currentCanvasWidth,
height: this.currentCanvasHeight
width: this
.currentCanvasWidth,
height: this
.currentCanvasHeight
};
resolve();
},
@ -234,15 +249,34 @@
let arr = [];
// 循环处理每行文本
for (let i = 0; i < this.validTxts.length; i++) {
debugger;
let linePixls = [];
let item = this.validTxts[i];
// console.log("item=", item);
for (var j = 0; j < item.length; j++) {
let result = await drawTxt(item[j]);
linePixls.push(convertCharToMatrix(result.pixelData, item));
let res = await drawTxt(item);
let rawData= res.pixelData;
let result = [[], [], [], [], []];
for (let char = 0; char < 5; char++) {
for (let row = 0; row < 13; row++) {
let start = row * (5 * 52) + char * 52 + 1;
let end = start + 51;
for (let i = 0; i < 52; i++) {
result[char].push(rawData[start + i]);
}
}
}
// console.log("hexs=", linePixls.join(","));
debugger;
for (var j = 0; j < result.length; j++) {
linePixls.push(convertCharToMatrix(result[j]));
}
arr.push(linePixls);
}

View File

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

View File

@ -95,7 +95,7 @@
<view style="padding-bottom: 20rpx;">
<view style="padding-bottom: 20rpx;">
<view class="proinfo lamp">
@ -355,6 +355,15 @@
},
onShow() {
this.Status.pageHide = false;
let f = this.getDevice();
if (f) {
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
computed: {
@ -363,14 +372,14 @@
methods: {
LighSetting(item, index) {
let val=item.key;
let val = item.key;
if (item.key === this.formData.sta_LedType) {
val='led_off';
val = 'led_off';
}
let f = this.getDevice();
// #ifdef APP-PLUS
if (!f) {
this.showBleUnConnect();
@ -382,7 +391,7 @@
deviceId: '12345'
}
// #endif
let json = {
ins_LedType: val
}
@ -390,10 +399,10 @@
ble.sendString(f.deviceId, json, f.writeServiceId, f.wirteCharactId, 30).then(res => {
this.formData.sta_LedType = val;
these.setBleFormData();
}).catch(ex => {
this.showMsg(ex.msg);
});
},
@ -501,13 +510,13 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if(res.device){
if (res.device) {
these.formData.bleStatu = 'connecting';
}else{
} else {
this.formData.bleStatu = false;
}
setTimeout(() => {

View File

@ -519,7 +519,7 @@
ble = BleTool.getBleTool();
this.$watch("formData.sta_battery", (newVal, oldVal) => {
if (newVal <= 20 && this.formData.sta_system==2) {
if (newVal <= 20 && this.formData.sta_system == 2) {
this.showMsg("设备电量低");
}
});
@ -595,6 +595,15 @@
},
onShow() {
this.Status.pageHide = false;
let f = this.getDevice();
if (f) {
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
computed: {
getbleStatu() {
@ -1197,9 +1206,9 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if (res.device) {
these.formData.bleStatu = 'connecting';

View File

@ -509,6 +509,16 @@
},
onShow() {
this.Status.pageHide = false;
let f = this.getDevice();
if (f) {
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
this.getLinkedCnt();
},
computed: {
@ -975,13 +985,13 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if(res.device){
if (res.device) {
these.formData.bleStatu = 'connecting';
}else{
} else {
this.formData.bleStatu = false;
}
setTimeout(() => {

View File

@ -574,6 +574,15 @@
},
onShow() {
this.Status.pageHide = false;
let f=this.getDevice();
if(f){
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
computed: {
getbleStatu() {
@ -1083,9 +1092,9 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if(res.device){
these.formData.bleStatu = 'connecting';

View File

@ -599,9 +599,9 @@ import request, { baseURL } from '@/utils/request.js';
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
//if (this.Status.pageHide) {
// return;
//}
if (res.deviceId == these.formData.deviceId) {
if(res.device){
these.formData.bleStatu = 'connecting';

View File

@ -679,7 +679,7 @@
}
let that = this;
uni.navigateTo({
url: "/pages/ImgCrop/ImgCrop",
url: "/pages/common/ImgCrop/ImgCrop",
events: {
ImgCutOverPath: function(data) {
that.selectedImage = data.picPath;

View File

@ -486,6 +486,15 @@
},
onShow() {
this.Status.pageHide = false;
let f=this.getDevice();
if(f){
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
onHide: function() {
this.Status.pageHide = true;
@ -1145,7 +1154,7 @@
sourceType: ['album'],
success: function(res) {
uni.navigateTo({
url: "/pages/ImgCrop/ImgCrop",
url: "/pages/common/ImgCrop/ImgCrop",
events: {
ImgCutOver: function(data) {
@ -2012,9 +2021,9 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if (res.device) {
these.formData.bleStatu = 'connecting';

View File

@ -433,6 +433,14 @@
},
onShow() {
this.Status.pageHide = false;
let f = this.getDevice();
if (f) {
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
computed: {
@ -689,9 +697,9 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
//if (this.Status.pageHide) {
// return;
//}
if (res.deviceId == these.formData.deviceId) {
this.formData.bleStatu = false;
setTimeout(() => {

View File

@ -75,7 +75,7 @@
<view class="slider-container">
<slider min="1" max="100" step="1" :disabled="false" :value="formData.liangDu" activeColor="#bbe600"
backgroundColor="#00000000" block-size="20" block-color="#ffffffde" @change="sliderChange"
@changing="sliderChange" class="custom-slider" />
class="custom-slider" />
</view>
</view>
@ -129,17 +129,17 @@
<view class="item">
<text class="lbl">单位</text>
<input class="value" v-model.trim="formData.textLines[0]" placeholder="请输入单位"
<input class="value" v-model.trim="formData.textLines[0]" placeholder="请输入单位" maxlength="8"
placeholder-class="usrplace" />
</view>
<view class="item">
<text class="lbl">部门</text>
<input class="value" v-model.trim="formData.textLines[1]" placeholder="请输入姓名"
<input class="value" v-model.trim="formData.textLines[1]" placeholder="请输入姓名" maxlength="8"
placeholder-class="usrplace" />
</view>
<view class="item">
<text class="lbl">姓名</text>
<input class="value" v-model.trim="formData.textLines[2]" placeholder="请输入职位"
<input class="value" v-model.trim="formData.textLines[2]" placeholder="请输入职位" maxlength="8"
placeholder-class="usrplace" />
</view>
@ -286,7 +286,7 @@
light: null,
bleStatu: ''
},
inteval: 80,
inteval: 150,
device: {
id: "",
deviceName: "",
@ -426,6 +426,15 @@
},
onShow() {
this.Status.pageHide = false;
let f = this.getDevice();
if (f) {
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
onBackPress(e) {
@ -581,13 +590,13 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if(res.device){
if (res.device) {
these.formData.bleStatu = 'connecting';
}else{
} else {
this.formData.bleStatu = false;
}
setTimeout(() => {
@ -759,14 +768,14 @@
these.showBleUnConnect();
return;
}
let os = plus.os.name;
// 分包发送图片数据
var sendImagePackets = function(ReSendNo) {
return new Promise((resolve, reject) => {
// 总数据包数
let totalPackets = 52;
let totalPackets = os=='Android'?52:200;
let currentPacket = 1;
if (ReSendNo) {
@ -785,19 +794,20 @@
message: "上传成功",
iconUrl: "/static/images/common/success.png",
});
setTimeout(()=>{
ble.sendString(f.deviceId, "transmit complete", f.writeServiceId, f
.wirteCharactId);
},1000);
setTimeout(() => {
ble.sendString(f.deviceId, "transmit complete", f
.writeServiceId, f
.wirteCharactId);
}, 1000);
these.rgb565Data = null;
resolve();
return;
}
// 计算当前包的数据
let packetSize = 250;
let packetSize = os == 'Android' ? 250 : 64;
// if (currentPacket <= 51) {
// packetSize = 250; // 前51个包每个500字节
// } else {
@ -805,77 +815,59 @@
// }
// 创建数据包
const startIndex = (currentPacket - 1) * packetSize;
const endIndex = Math.min(startIndex + packetSize, these.rgb565Data
let startIndex = (currentPacket - 1) * packetSize;
let endIndex = Math.min(startIndex + packetSize, these.rgb565Data
.length);
if (startIndex > endIndex) {
return;
}
const packetData = these.rgb565Data.slice(startIndex,
let packetData = these.rgb565Data.slice(startIndex,
endIndex);
// 构建数据包
const bufferSize = 505; // 5 + packetData.length * 2; // 头部5字节 + 数据部分
const buffer = new ArrayBuffer(bufferSize);
const dataView = new DataView(buffer);
let bufferSize = os == 'Android' ? 505 :133; // 5 + packetData.length * 2; // 头部5字节 + 数据部分
let buffer = new ArrayBuffer(bufferSize);
let dataView = new DataView(buffer);
// 填充头部
dataView.setUint8(0, 0x55); // 帧头
dataView.setUint8(0, os == 'Android' ? 0x55 : 0x56); // 帧头
dataView.setUint8(1, 0x02); // 帧类型:开机画面
dataView.setUint8(2, '0x' + currentPacket.toString(16).padStart(2,
'0')); // 包序号
if (packetData.length == 250) {
dataView.setUint8(3, 0x01);
dataView.setUint8(4, 0xF4);
} else {
dataView.setUint8(3, 0x00);
dataView.setUint8(4, 0x64);
}
dataView.setUint8(2, currentPacket); // 包序号
dataView.setUint16(3, packetData.length*2,false);
// 填充数据每个RGB565值占2字节
for (let i = 0; i < packetData.length; i++) {
dataView.setUint16(5 + i * 2, packetData[i], false); // 大端字节序
}
if (currentPacket > 51) { //第52包补FF
for (var i = 105; i < bufferSize; i++) {
dataView.setUint8(i, 0xFF);
}
}
//发送数据包
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId,
10)
.then(() => {
10).then(() => {
updateLoading(these, {
text: "正在发送:" + currentPacket + "/" +
totalPackets
})
currentPacket++;
updateLoading(these, {
text: "正在发送:" + currentPacket + "/" +
totalPackets
})
currentPacket++;
setTimeout(sendNextPacket,os=='Android'? these.inteval:these.inteval/2);
}).catch(err => {
console.log("发送数据包失败了" + JSON.stringify(err));
if (err.code == '10007') {
setTimeout(sendNextPacket, these.inteval);
}).catch(err => {
console.log("发送数据包失败了" + JSON.stringify(err));
if (err.code == '10007') {
setTimeout(sendNextPacket, these.inteval);
return;
}
these.Status.BottomMenu.show = false;
these.showPop({
message: err.msg,
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
hideLoading(these);
these.rgb565Data = null;
reject(err);
return;
}
these.Status.BottomMenu.show = false;
these.showPop({
message: err.msg,
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
hideLoading(these);
these.rgb565Data = null;
reject(err);
});
}
if (ReSendNo) {
@ -909,12 +901,12 @@
sourceType: ['album'],
success: function(res) {
uni.navigateTo({
url: "/pages/ImgCrop/ImgCrop",
url: "/pages/common/ImgCrop/ImgCrop",
events: {
ImgCutOver: function(data) {
showLoading(these, {
text: "正在发送0/52"
text: "正在发送..."
});
console.log("data=", data);
these.Status.BottomMenu.show = false;
@ -955,6 +947,8 @@
})
return;
}
let os=plus.os.name;
// os='Android';
let f = these.getDevice();
if (!f) {
@ -974,7 +968,7 @@
return new Promise((resolve, reject) => {
if (f) {
// 总数据包数
var totalPackets = 1536; //36;
var totalPackets =os=='Android' ? 1536 : 6000; //36;
let currentPacket = 1;
console.log("发送数据准备中,总共" + totalPackets);
@ -987,27 +981,30 @@
const sendNextVideoPacket = () => {
// console.log("准备发送一段数据");
if (currentPacket > totalPackets) {
updateLoading(these,{text:'发送完毕,正在处理'})
if (!ReSendNo) {
setTimeout(() => {
ble.sendString(f.deviceId, "transmit complete", f
.writeServiceId, f.wirteCharactId, 20)
ble.sendString(f.deviceId, "transmit complete", f.writeServiceId, f.wirteCharactId, 20)
.then(
() => {
console.log("全部发送完毕")
hideLoading(these);
these.showPop({
showPop: true,
message: "上传成功",
iconUrl: "/static/images/common/success.png"
});
}).catch((ex) => {
console.log("出现异常", ex);
});
}, 500);
}, os=='Android'?500:15000);
}
these.Status.BottomMenu.show = false;
hideLoading(these);
these.showPop({
showPop: true,
message: "上传成功",
iconUrl: "/static/images/common/success.png"
});
these.videoHexArray = null;
resolve();
@ -1015,7 +1012,7 @@
}
// 计算当前包的数据
let packetSize = 500;
let packetSize =os=='Android'? 500:128;
// 创建数据包
@ -1031,33 +1028,28 @@
// 构建数据包
////console.log("packetData.length"+packetData.length);
const bufferSize = 504; // 头部5字节 + 数据部分
const bufferSize =packetSize+4; // 头部5字节 + 数据部分
const buffer = new ArrayBuffer(bufferSize);
const dataView = new DataView(buffer);
let sortNo = currentPacket.toString(16).padStart(4, '0');
// 填充头部
dataView.setUint8(0, 0x55); // 帧头
dataView.setUint8(0, os=='Android'?0x55:0x56); // 帧头
dataView.setUint8(1, 0x04); // 帧类型:开机画面
dataView.setUint8(2, '0x' + sortNo.substring(0, 2)); // 包序号
dataView.setUint8(3, '0x' + sortNo.substring(2, 4)); // 包序号
// dataView.setUint8(4, 0x01);
// dataView.setUint8(5, 0xF4);
dataView.setUint16(2, currentPacket,false); // 包序号
for (let i = 0; i < packetData.length; i++) {
dataView.setUint8(4 + i, '0x' + packetData[i]);
dataView.setUint8(4 + i, parseInt(packetData[i],16));
}
let inteval = 40;
let inteval = os=='Android'? 100:40;
ble.sendData(f.deviceId, buffer, f.writeServiceId, f
.wirteCharactId, 10).then(() => {
updateLoading(these, {
text: "正在发送:" + currentPacket + "/" +
totalPackets
text: "正在发送:" +currentPacket+'/'+totalPackets
})
currentPacket++;
@ -1069,7 +1061,7 @@
if (err.code == '10007') { //遇到这个错误自动重新发送
console.log(err.errMsg + ",发送失败了,正在补偿:" +
currentPacket);
setTimeout(sendNextVideoPacket, inteval);
setTimeout(sendNextVideoPacket, 500);
} else {
these.Status.BottomMenu.show = false;
hideLoading(these);
@ -1183,7 +1175,7 @@
if (res.data) {
these.videoHexArray = res.data;
updateLoading(these, {
text: "正在发送:0/1536"
text: "正在发送..."
});
these.Status.BottomMenu.show = false;
@ -1227,7 +1219,7 @@
}).catch((ex1) => {
//console.log("出现了异常", ex1)
}).finally(() => {
hideLoading(these);
});
}
@ -1583,7 +1575,7 @@
let err = false;
this.formData.textLines.find((txt) => {
if (txt.length === 0 || txt.length > 7) {
if (txt.length === 0 || txt.length > 8) {
console.log("txt=", txt);
err = true;
return true;
@ -1592,7 +1584,7 @@
})
if (err) {
this.showPop({
message: "单位、部门、姓名必须填写且最多7字",
message: "单位、部门、姓名必须填写且最多8字",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
@ -1647,11 +1639,12 @@
linePixels.push(0x00);
}
linePixels = [0xFA, 0x06, 0x03, i + 1].concat(linePixels);
combinedData.push([0xFA, 0x06, i + 1, 1].concat(linePixels.slice(0, 128)));
combinedData.push([0xFA, 0x06, i + 1, 2].concat(linePixels.slice(128, 256)));
linePixels.push(0xFF)
combinedData.push(linePixels);
}
combinedData.push([0x74, 0x72, 0x61, 0x6E, 0x73, 0x6D, 0x69, 0x74, 0x20, 0x63, 0x6F, 0x6D,
0x70, 0x6C, 0x65, 0x74, 0x65
@ -1703,11 +1696,11 @@
text: '正在发送' + curr + '/' + len
});
curr++;
setTimeout(sendPacket, 150);
setTimeout(sendPacket, 300);
}).catch(err => {
if (err.code == '10007') {
setTimeout(sendPacket, 150);
setTimeout(sendPacket, 300);
} else {
console.log("err:", err);
hideLoading(these);
@ -1741,6 +1734,7 @@
setTimeout(() => {
Promise.allSettled([holdHand(), drawText()]).then(results => {
console.log("results=", results)
if (results[0].status == 'rejected') {
updateLoading(these, {
text: results[0].reason

View File

@ -396,6 +396,15 @@
},
onShow() {
this.Status.pageHide = false;
let f=this.getDevice();
if(f){
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
onBackPress(e) {
@ -562,9 +571,9 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if(res.device){
these.formData.bleStatu = 'connecting';
@ -926,7 +935,7 @@
sourceType: ['album'],
success: function(res) {
uni.navigateTo({
url: "/pages/ImgCrop/ImgCrop",
url: "/pages/common/ImgCrop/ImgCrop",
events: {
ImgCutOver: function(data) {

View File

@ -52,9 +52,9 @@
{{ deviceInfo.onlineStatus === 0 ? '离线' : deviceInfo.onlineStatus === 2 ? '故障' : '在线' }}
</text>
</view>
<view class="info-row" v-if="itemInfo.deviceMac">
<view class="info-row" v-if="itemInfo.deviceMac" @click="bleStatuToggle">
<text class="info-label">蓝牙状态</text>
<text class="info-value status-running">
<text class="info-value status-running" >
{{getbleStatu}}
</text>
</view>
@ -331,7 +331,7 @@
var ble = null;
var rec = null;
var pagePath = "pages/6170/BJQ6170";
var pagePath = "/pages/6170/deviceControl/index";
export default {
components: {
@ -404,7 +404,8 @@
},
Status: {
pageHide: null
}
},
inteval: 120
}
},
computed: {
@ -432,20 +433,48 @@
}
},
methods: {
bleStatuToggle() {
let f = this.getDevice();
if (!f) {
this.showBleUnConnect();
return;
}
if (this.formData.bleStatu === true) {
this.formData.bleStatu = 'dicconnect';
ble.disconnectDevice(f.deviceId).finally(r => {
this.formData.bleStatu = false;
});
return;
}
if (this.formData.bleStatu === false || this.formData.bleStatu === 'err') {
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
these.formData.bleStatu = true;
}).catch(ex => {
these.formData.bleStatu = 'err';
});
return;
}
},
getDevice: function() {
if (ble) {
console.log("LinkedList=", ble.data.LinkedList);
console.log("this.device=", this.itemInfo);
let f = ble.data.LinkedList.find((v) => {
if (v.macAddress == this.itemInfo.deviceMac) {
if (!this.formData.deviceId) {
this.formData.deviceId = v.deviceId
};
return true;
}
});
console.log("LinkedList=", ble.data.LinkedList);
console.log("this.device=", this.device);
let f = ble.data.LinkedList.find((v) => {
if (v.macAddress == this.itemInfo.deviceMac) {
if (!this.formData.deviceId) {
this.formData.deviceId = v.deviceId
};
return true;
}
});
return f;
return f;
}
return null;
},
initBle() {
if (this.itemInfo.deviceMac) {
@ -498,9 +527,12 @@
if (receive.deviceId !== this.formData.deviceId) {
return;
}
let data = recei.ReceiveData(receive, device, pagePath, recArr);
let data = rec.ReceiveData(receive, device, pagePath, recArr);
console.log("蓝牙收到消息", data)
this.receivData(data);
},
receivData(data) {
},
bleStateBreak() {
if (this.Status.pageHide) {
@ -542,9 +574,9 @@
});
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if (res.device) {
these.formData.bleStatu = 'connecting';
@ -856,20 +888,26 @@
})
uni.hideLoading();
}
}).catch(ex => {
console.error("ex=", ex);
});
}
if (ble && this.itemInfo.deviceMac) {
console.log("111111")
let f = this.getDevice();
if (f) {
console.log("222222");
let json = {
instruct: [1, 0, 0, 0, 0]
};
json.instruct[1] = parseInt(selectedItem.instructValue);
ble.sendString(f.deviceId, json).then(res => {
console.log("ble send success")
this.lightModeA = false;
}).catch(ex => {
console.error("ble send fail,mqsending....")
mqSend();
});
} else {
@ -979,7 +1017,7 @@
}
let that = this;
uni.navigateTo({
url: "/pages/ImgCrop/ImgCrop",
url: "/pages/common/ImgCrop/ImgCrop",
events: {
ImgCutOver: function(data) {
that.selectedImage = data.picPath;
@ -990,6 +1028,9 @@
ev.eventChannel.emit('checkImg', {
data: res.tempFiles[0].path,
});
},
fail(ex) {
console.error("跳转失败", ex);
}
});
}
@ -1247,9 +1288,11 @@
});
}
setTimeout(function() {
setTimeout(()=> {
sendImagePackets().catch(() => {
}).finally(()=>{
this.lightModeB=false;
});
}, 0)
}
@ -1797,7 +1840,7 @@
onLoad(options) {
these = this;
rec = BleReceive.getBleReceive();
const eventChannel = this.getOpenerEventChannel();
// 监听 'detailData' 事件,获取传过来的数据
uni.showLoading({
@ -1815,7 +1858,7 @@
// 根据 apiType 设置右图标的显示状态
this.isRightIconVisible = this.apiType === 'listA';
this.initBle();
// 初始化并连接MQTT
this.mqttClient = new MqttClient();
this.mqttClient.connect(() => {
@ -1896,6 +1939,9 @@
rec = BleReceive.getBleReceive();
ble = BleTool.getBleTool();
this.initBle();
console.log("ble=", ble);
let f = ble.data.LinkedList.find((v) => {
if (v.macAddress == this.itemInfo.deviceMac) {
console.log("找到设备了", v);
@ -1908,9 +1954,9 @@
if (f) {
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(
res => {
these.formData.bleStatu = true;
});
res => {
these.formData.bleStatu = true;
});
}
}
@ -1922,6 +1968,17 @@
})
},
onShow() {
debugger;
let f = this.getDevice();
if (f) {
this.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
this.formData.bleStatu = true;
});
}
},
onUnload() {
// 页面卸载时断开MQTT连接
if (this.mqttClient) {

View File

@ -414,6 +414,14 @@ import request, { baseURL } from '@/utils/request.js';
},
onShow() {
this.Status.pageHide = false;
let f = this.getDevice();
if (f) {
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
computed: {
@ -613,9 +621,9 @@ import request, { baseURL } from '@/utils/request.js';
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
//if (this.Status.pageHide) {
// return;
//}
if (res.deviceId == these.formData.deviceId) {
if(res.device){
these.formData.bleStatu = 'connecting';

View File

@ -418,6 +418,15 @@ import request, { baseURL } from '@/utils/request.js';
},
onShow() {
this.Status.pageHide = false;
let f=this.getDevice();
if(f){
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
computed: {
getbleStatu(){
@ -510,9 +519,9 @@ import request, { baseURL } from '@/utils/request.js';
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if(res.device){
these.formData.bleStatu = 'connecting';
@ -1051,7 +1060,7 @@ import request, { baseURL } from '@/utils/request.js';
var gotoCutImg = (imgPath) => {
uni.navigateTo({
url: "/pages/ImgCrop/ImgCrop",
url: "/pages/common/ImgCrop/ImgCrop",
events: {
ImgCutOver: function(data) {
// console.log("我收到裁剪后的图片了,感谢老铁," + data)

View File

@ -16,7 +16,7 @@
<view class="eq" :style="{marginTop:Status.navbar.height+'px'}">
<view class="eq" >
<view class="leftImg" @click.stop="previewImg(device.devicePic?device.devicePic:formData.img)">
<image class="img" :src="device.devicePic?device.devicePic:formData.img" mode="aspectFit"></image>
</view>
@ -561,6 +561,15 @@
},
onShow() {
this.Status.pageHide = false;
let f=this.getDevice();
if(f){
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
onHide: function() {
this.Status.pageHide = true;
@ -634,9 +643,9 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if(res.device){
these.formData.bleStatu = 'connecting';
@ -1871,7 +1880,7 @@
var gotoCutImg = (imgPath) => {
uni.navigateTo({
url: "/pages/ImgCrop/ImgCrop",
url: "/pages/common/ImgCrop/ImgCrop",
events: {
ImgCutOver: function(data) {
// console.log("我收到裁剪后的图片了,感谢老铁," + data)

View File

@ -114,20 +114,20 @@
<view class="btnSend fright" v-on:click.stop="sendUsr">发送</view>
<view class="clear"></view>
<textToDotMatrixFor7305 class="TextToHex" ref="textToHex" :txts="formData.textLines"
:bgColor="'#FFFFFF'" :color="'#000000'" :fontSize="11" />
:bgColor="'#FFFFFF'" :color="'#000000'" :fontSize="13" />
</view>
<view class="item">
<text class="lbl">单位</text>
<input class="value" v-model="formData.textLines[0]" placeholder="请输入单位" placeholder-class="usrplace" />
<input class="value" v-model="formData.inputLines[0]" placeholder="请输入单位" placeholder-class="usrplace" />
</view>
<view class="item">
<text class="lbl">部门</text>
<input class="value" v-model="formData.textLines[1]" placeholder="请输入姓名" placeholder-class="usrplace" />
<input class="value" v-model="formData.inputLines[1]" placeholder="请输入姓名" placeholder-class="usrplace" />
</view>
<view class="item">
<text class="lbl">姓名</text>
<input class="value" v-model="formData.textLines[2]" placeholder="请输入职位" placeholder-class="usrplace" />
<input class="value" v-model="formData.inputLines[2]" placeholder="请输入职位" placeholder-class="usrplace" />
</view>
</view>
@ -243,7 +243,7 @@
],
activeIndex: -1,
bgColor: '#2a2a2a',
itemBgColor: '#00000000',
itemBgColor: '#3a3a3a',
textColor: '#ffffffde',
textAlign: 'flex-start',
title: '主灯模式',
@ -272,9 +272,10 @@
liangDu: '100',
id: '',
deviceId: '',
textLines: ['', '', ''],
textLines: [],
mode: '',
bleStatu: ''
bleStatu: '',
inputLines:[]
},
inteval: 500,
device: {
@ -376,6 +377,15 @@
},
onShow: function() {
this.Status.pageHide = false;
let f=this.getDevice();
if(f){
these.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功")
these.formData.bleStatu = true;
});
}
},
computed: {
getbleStatu() {
@ -399,22 +409,20 @@
return txt;
}
switch (this.formData.mode) {
case 0:
case 1:
txt = "强光模式";
break;
case 1:
case 2:
txt = "弱光模式";
break;
case 2:
case 3:
txt = "爆闪模式";
break;
case 3:
txt = "关闭";
break;
default:
txt = "关闭";
break;
@ -481,9 +489,9 @@
})
},
deviceRecovry(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
this.formData.bleStatu = true;
// 重新连接后状态以设备上报为准
@ -498,9 +506,9 @@
},
deviceDispose(res) {
if (this.Status.pageHide) {
return;
}
// if (this.Status.pageHide) {
// return;
// }
if (res.deviceId == these.formData.deviceId) {
if (res.device) {
these.formData.bleStatu = 'connecting';
@ -587,7 +595,7 @@
}
let json = recei.ReceiveData(receive, device, path, recArr);
console.log("收到消息:", receive.hexs);
console.log("收到消息:", receive);
if (!json) {
return;
}
@ -597,6 +605,8 @@
these.formData[key] = json[key];
}
});
these.formData.mode=parseInt(receive.hexs[2],16);
console.error("mode="+these.formData.mode);
if ('statu' in json) {
const chargingVal = json.statu;
const isCharging = chargingVal === 1 || chargingVal === '1' || chargingVal === true ||
@ -783,7 +793,7 @@
sourceType: ['album'],
success: function(res) {
uni.navigateTo({
url: "/pages/ImgCrop/ImgCrop",
url: "/pages/common/ImgCrop/ImgCrop",
events: {
ImgCutOver: function(data) {
//将8位的二进制数组转换成16进制数据
@ -1023,21 +1033,16 @@
case 0:
if (type == 'main') {
dataValue = 0x01;
} else if (type == 'fu') {
dataValue = 0x04;
}
break;
case 1:
dataValue = 0x02;
break;
// case 2:
// dataValue = 0x02;
// break;
case 2:
dataValue = 0x03;
break;
@ -1071,7 +1076,7 @@
});
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 100).then(() => {
this.formData.mode = mode;
this.formData.mode = mode+1;
this.setBleFormData();
}).catch((ex) => {
these.showPop({
@ -1088,7 +1093,7 @@
},
handleItemClick(item, index) {
debugger;
this.Status.BottomMenu.activeIndex = index;
@ -1191,8 +1196,9 @@
these.showBleUnConnect()
return;
}
debugger;
let err = false;
this.formData.textLines.find((txt) => {
this.formData.inputLines.find((txt) => {
if (txt.length === 0 || txt.length > 5) {
console.log("txt=", txt);
err = true;
@ -1209,12 +1215,16 @@
});
return;
}
this.formData.textLines=[this.formData.inputLines[0],this.formData.inputLines[1],this.formData.inputLines[2]];
showLoading(these, {
text: "请稍候..."
text: "发送中..."
});
this.setBleFormData();
let task = async () => {
var sendTxtPackge = (rgbdata, type, str) => {
var sendTxtPackge = (rgbdata, type, str,index) => {
var promise = new Promise((resolve, reject) => {
try {
@ -1257,7 +1267,7 @@
.toString(16).padStart(2, '0'));
console.log(`发送数据块 ${chunkIndex + 1}/${numChunks}:`, hexArray
.join(' '));
updateLoading(these,{text:'正在发送'+((index-1)*14+chunkIndex + 1)+'/42'})
ble.sendData(f.deviceId, chunk, f.writeServiceId, f
.wirteCharactId, 100).then(() => {
chunkIndex++;
@ -1314,7 +1324,7 @@
try {
// console.log("1111");
await sendTxtPackge(rgb, h3dic[i], str);
await sendTxtPackge(rgb, h3dic[i], str,i+1);
// console.log("222222");
} catch (ex) {
flag = false;
@ -1367,9 +1377,9 @@
res = res.data;
let personnelInfo = res.personnelInfo;
if (personnelInfo) {
these.formData.textLines[2] = personnelInfo.unitName;
these.formData.textLines[1] = personnelInfo.name;
these.formData.textLines[0] = personnelInfo.position;
these.formData.inputLines[2] = personnelInfo.unitName;
these.formData.inputLines[1] = personnelInfo.name;
these.formData.inputLines[0] = personnelInfo.position;
}
}

View File

@ -104,6 +104,7 @@
</view>
</BottomSlideMenuPlus>
<MsgBox ref="msgPop" />
<global-loading ref="loading" />
</view>
</template>
@ -115,7 +116,15 @@
showLoading,
hideLoading,
updateLoading
} from '@/utils/loading.js'
} from '@/utils/loading.js';
import {
MsgSuccess,
MsgError,
MsgClose,
MsgWarning,
showPop,
MsgClear
} from '@/utils/MsgPops.js';
const pagePath = "pages/common/addBLE/addEquip";
var ble = null;
var these = null;
@ -327,6 +336,21 @@
these.showOpenSetting();
}, pagePath);
//蓝牙恢复可用的回调
ble.addStateRecoveryCallback(res=>{
if (these.Status.isPageHidden) {
return;
}
these.Status.BottomMenu.show = false;
these.PairEquip = [];
these.EquipMents = [];
uni.showToast({
icon: 'fail',
title: '蓝牙恢复可用'
});
these.refreshBleList();
}),pagePath;
//蓝牙断开连接的回调
ble.addDisposeCallback(res => {
@ -490,24 +514,17 @@
console.log('定位权限已授予');
resolve(true);
} else {
console.warn('定位权限被拒绝');
uni.showModal({
title: '权限提醒',
content: '为了正常扫描蓝牙设备,需要您开启定位权限',
showCancel: false,
success: () => {
uni.openSetting(); // 引导用户去设置页
}
});
// console.warn('定位权限被拒绝');
MsgClear(these);
showPop({headerTxt:'权限提醒',message:'扫描蓝牙设备,需要您开启定位权限',buttonText:'去开启',okCallback:uni.openSetting},these,true);
resolve(false);
}
},
(error) => {
console.error('请求定位权限失败:', error);
uni.showToast({
title: '权限请求异常',
icon: 'none'
});
MsgError('请求定位权限失败:'+error.code,'确定',these);
resolve(false);
}
);
@ -537,7 +554,7 @@
}
}
showLoading(these, {
text: '正在刷新'
text: '正在扫描蓝牙设备'
})
let time = null;
let startSearch = () => {
@ -558,10 +575,9 @@
if (err.code === 10001) {
these.showOpenSetting();
} else {
uni.showModal({
title: '提示',
content: '出现错误:' + err.msg
});
MsgClear(these);
MsgError('出现错误:' + err.msg,'确定',these);
}
}).finally(() => {
@ -571,7 +587,9 @@
}
ble.StopSearch().finally(startSearch);
ble.StopSearch().catch(err=>{
console.error("err=",err);
}).finally(startSearch);
@ -806,9 +824,9 @@
linkCallback(res);
}).catch(ex => {
console.error("ex=", ex)
uni.showModal({
content: "连接失败:" + ex.msg
});
MsgClear(these);
MsgError("连接失败:" + ex.msg,'确定',these);
hideLoading(these);
});

View File

@ -106,6 +106,18 @@
}
}
let appid='';
// #ifdef APP|APP-PLUS
appid = plus.runtime.appid;
// #endif
// #ifdef WEB
appid='HBuilder';
// #endif
if (appid === 'HBuilder') {
this.phone='17671332251';
this.password='123456';
this.isChecked=true;
}
},
methods: {

View File

@ -56,7 +56,7 @@ class BleHelper {
isOpenBlue: false, //蓝牙模块是否开启
available: false, //蓝牙状态是否可用
discovering: false, //蓝牙是否正在搜索
isSubscribe: false, //是否开启了订阅
LinkedList: linkedDevices, //已连接的设备列表
platform: systemInfo.uniPlatform,
@ -139,7 +139,7 @@ class BleHelper {
{
key: '10013',
remark: '连接 deviceId 为空或者是格式不正确'
},
},
{
key: '10016',
remark: '定位服务已关闭'
@ -234,11 +234,11 @@ class BleHelper {
}
if (key) {
// console.log("key=" + key);
let f =-1;
this.cfg[type].find((v,index) => {
if(v.key == key){
f=index;
let f = -1;
this.cfg[type].find((v, index) => {
if (v.key == key) {
f = index;
}
});
if (f > -1) {
@ -262,10 +262,10 @@ class BleHelper {
if (key) {
// console.log("key=" + key);
let f =-1;
this.cfg[type].find((v,index) => {
if(v.key == key){
f=index;
let f = -1;
this.cfg[type].find((v, index) => {
if (v.key == key) {
f = index;
}
});
if (f > -1) {
@ -281,26 +281,26 @@ class BleHelper {
//获取某个事件的所有订阅者,但不包含某些订阅者
getCfgAllKeys(type,retains){
if(!retains){
retains=[];
getCfgAllKeys(type, retains) {
if (!retains) {
retains = [];
}
if(!Array.isArray(retains)){
retains=[retains];
if (!Array.isArray(retains)) {
retains = [retains];
}
let keys=null;
let keys = null;
for (let index = 0; index < this.cfg[type]; index++) {
let ele = this.cfg[type];
let f=retains.find(v=>{
return v.toLowerCase()==ele.key.toLowerCase();
let f = retains.find(v => {
return v.toLowerCase() == ele.key.toLowerCase();
});
if(!f){
if(!keys){
keys=[ele.key];
}else{
keys.push(ele.key);
if (!f) {
if (!keys) {
keys = [ele.key];
} else {
keys.push(ele.key);
}
}
}
return keys;
@ -316,15 +316,15 @@ class BleHelper {
this.removeCallback(currKey, 'recoveryCallback');
}
//移除所有蓝牙恢复连接的回调,但不包括currkey
removeAllRecoveryCallback(currKey) {
let keys=this.getCfgAllKeys('recoveryCallback',currKey);
if(keys){
removeAllRecoveryCallback(currKey) {
let keys = this.getCfgAllKeys('recoveryCallback', currKey);
if (keys) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
this.removeRecoveryCallback(key);
}
}
}
//设置蓝牙断开连接的回调
@ -337,14 +337,14 @@ class BleHelper {
this.removeCallback(currKey, 'bleDisposeCallback');
}
removeAllDisposeCallback(currKey) {
let keys=this.getCfgAllKeys('bleDisposeCallback',currKey);
if(keys){
let keys = this.getCfgAllKeys('bleDisposeCallback', currKey);
if (keys) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
this.removeDisposeCallback(key);
}
}
}
@ -358,14 +358,14 @@ class BleHelper {
this.removeCallback(currKey, 'onDeviceFound');
}
removeAllDeviceFound(currKey) {
let keys=this.getCfgAllKeys('onDeviceFound',currKey);
if(keys){
let keys = this.getCfgAllKeys('onDeviceFound', currKey);
if (keys) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
this.removeDeviceFound(key);
}
}
}
//添加接收到数据的回调
@ -378,14 +378,14 @@ class BleHelper {
this.removeCallback(currKey, 'receivDataCallback');
}
removeAllReceiveCallback(currKey) {
let keys=this.getCfgAllKeys('receivDataCallback',currKey);
if(keys){
let keys = this.getCfgAllKeys('receivDataCallback', currKey);
if (keys) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
this.removeReceiveCallback(key);
}
}
}
//添加蓝牙不可用的回调
@ -398,14 +398,14 @@ class BleHelper {
this.removeCallback(currKey, 'stateBreakCallback');
}
removeAllStateBreakCallback(currKey) {
let keys=this.getCfgAllKeys('stateBreakCallback',currKey);
if(keys){
let keys = this.getCfgAllKeys('stateBreakCallback', currKey);
if (keys) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
this.removeStateBreakCallback(key);
}
}
}
//设置蓝牙适配器恢复可用的回调
@ -418,14 +418,14 @@ class BleHelper {
this.removeCallback(currKey, 'stateRecoveryCallback');
}
removeAllStateRecoveryCallback(currKey) {
let keys=this.getCfgAllKeys('stateRecoveryCallback',currKey);
if(keys){
let keys = this.getCfgAllKeys('stateRecoveryCallback', currKey);
if (keys) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
this.removeStateRecoveryCallback(key);
}
}
}
//清除所有事件回调
@ -448,10 +448,11 @@ class BleHelper {
}
getError(ex) {
let code = ex.code;
ex.msg = code
ex.msg = ex.code + ':' + ex.errMsg;
let f = this.dic.errRemarks.find((v) => {
return v.key == code;
return v.key == ex.code;
});
if (f) {
ex.msg = f.remark;
@ -733,20 +734,26 @@ class BleHelper {
let trimmedStr = str.trim();
if (trimmedStr && (trimmedStr.startsWith('{') || trimmedStr.startsWith('['))) {
let receivJson = JSON.parse(str);
let key = "sta_address"; //HBY100以此方式上传mac地址
if (key in receivJson) {
if ("sta_address" in receivJson || "sta_imei" in receivJson) {
this.data.LinkedList.find((v) => {
if (v.deviceId == receive
.deviceId) {
let macStr = receivJson[
key];
if (macStr.includes(':')) {
v.macAddress = macStr;
} else {
v.macAddress = macStr
.replace(/(.{2})/g,
'$1:').slice(0,
-1)
let macStr = receivJson["sta_address"];
if (macStr) {
if (macStr.includes(':')) {
v.macAddress = macStr;
} else {
v.macAddress = macStr
.replace(/(.{2})/g,
'$1:').slice(0,
-1)
}
}
let sta_imei = receivJson["sta_imei"];
if (sta_imei) {
v.imei = sta_imei;
}
isUpdate = true;
@ -754,6 +761,8 @@ class BleHelper {
});
}
}
} catch (convertException) {
if (str && (str.trim().startsWith('{') || str.trim().startsWith('['))) {
@ -779,23 +788,23 @@ class BleHelper {
str: str,
hexs: hexs
};
// console.log("监听到特征值:",recData);
// console.log("监听到特征值:", recData);
if (this.cfg.receivDataCallback) {
if (this.cfg.receivDataCallback.length > 0) {
// console.log("有人订阅消息")
// console.log("有人订阅消息")
this.cfg.receivDataCallback.forEach((
rec) => {
// console.log("有人订阅消息111", )
// console.log("有人订阅消息111", )
if (rec.callback) {
try {
// console.log("正在处理订阅消息",rec);
// console.log("正在处理订阅消息",rec);
rec.callback(recData, f,
rec.key, this.cfg
.receivDataCallback
);
// console.log("处理订阅消息完毕");
// console.log("处理订阅消息完毕");
} catch (err) {
console.error(
"订阅消息出现异常",
@ -886,10 +895,10 @@ class BleHelper {
}
BleConnChange() {
let stateTimeout=null;
let stateTimeout = null;
uni.onBLEConnectionStateChange((res) => {
// 检查状态是否真的发生了变化
let ble = this.data.LinkedList.find(dev => {
return res.deviceId === dev.deviceId;
@ -903,7 +912,7 @@ class BleHelper {
// console.log("蓝牙连接状态变化了", res);
clearTimeout(stateTimeout);
stateTimeout=setTimeout(() => {
stateTimeout = setTimeout(() => {
if (!res.connected) {
// console.error("蓝牙已断开", res);
let f = this.data.LinkedList.find((
@ -1001,7 +1010,7 @@ class BleHelper {
return;
}
res.devices = arr;
if (this.cfg.onDeviceFound) {
if (this.cfg.onDeviceFound.length > 0) {
this.cfg.onDeviceFound.forEach((found) => {
@ -1026,7 +1035,7 @@ class BleHelper {
this.data.available = false;
this.data.discovering = false;
this.data.isOpenBlue = false;
return Promise.resolve();
}
@ -1043,7 +1052,7 @@ class BleHelper {
this.data.available = false;
this.data.discovering = false;
this.data.isOpenBlue = false;
resolve();
},
fail: (ex) => {
@ -1078,7 +1087,7 @@ class BleHelper {
if (this.data.platform == 'web') {
return Promise.resolve({});
}
var these = this;
//开始搜索
var Search = () => {
@ -1086,7 +1095,7 @@ class BleHelper {
let RunSearch = () => {
return new Promise((resolve, reject) => {
uni.startBluetoothDevicesDiscovery({
services:[],
services: [],
allowDuplicatesKey: true,
success: (res) => {
console.log('开始搜索蓝牙设备成功');
@ -1242,7 +1251,7 @@ class BleHelper {
// console.log("success SubScribe");
succ(
res
); //见了鬼了有时候执行了succ但promise永远pending了
); //见了鬼了有时候执行了succ但promise永远pending了
},
fail: (ex) => {
@ -1385,8 +1394,7 @@ class BleHelper {
// notifyCharId));
} else
{
} else {
console.error("预设的蓝牙服务和特征中找不到");
for (var i = 0; i < res.services.length; i++) {
let service = res.services[i];
@ -1619,23 +1627,23 @@ class BleHelper {
timeout: 15000,
success: (info) => {
//释放连接锁
delete this.data.connectingDevices[deviceId];
console.log("新连接成功", this.data.LinkedList);
// 处理 MTU 设置
if (plus.os.name === 'Android') {
this.setMtu(deviceId).catch(ex => {
console.error("mtu设置失败=", ex);
});
}
this.getLinkBlue().then((arr) => {
let linkId=new Date().getTime();//本次连接的id
let linkId = new Date().getTime(); //本次连接的id
let cr = arr.devices.find(c => {
if (c.deviceId == deviceId) {
c.Linked = true;
c.linkId=linkId
c.linkId = linkId
return true;
}
return false;
@ -1643,7 +1651,8 @@ class BleHelper {
if (fIndex > -1) {
this.data.LinkedList[fIndex].Linked = true;
this.data.LinkedList[fIndex].linkId=linkId;
this.data.LinkedList[fIndex].linkId =
linkId;
} else {
this.data.LinkedList.push(cr);
}
@ -1677,7 +1686,7 @@ class BleHelper {
});
}
resolve(true);
}).catch((ex) => {
@ -1858,7 +1867,7 @@ class BleHelper {
}
//向蓝牙设备发送一个字符串的ASCII码
sendString(deviceid, str, writeServiceId, wirteCharactId, ms) {
sendString(deviceid, str, writeServiceId, wirteCharactId, ms, iosIsChuck, chunkSize) {
if (str && typeof(str) == 'object') {
str = JSON.stringify(str);
}
@ -1882,7 +1891,7 @@ class BleHelper {
}
//向蓝牙设备发送一个16进制的数组数据
sendHexs(deviceid, array, writeServiceId, wirteCharactId, ms) {
sendHexs(deviceid, array, writeServiceId, wirteCharactId, ms, iosIsChuck, chunkSize) {
if (array && array.length) {
let bufferSize = array.length;
let buffer = new ArrayBuffer(bufferSize);
@ -1891,7 +1900,7 @@ class BleHelper {
dataView.setUint8(i, array[i]);
}
return this.sendData(deviceid, buffer, writeServiceId, wirteCharactId, ms);
return this.sendData(deviceid, buffer, writeServiceId, wirteCharactId, ms, iosIsChuck, chunkSize);
} else {
return Promise.resolve({
@ -1902,33 +1911,33 @@ class BleHelper {
}
//向蓝牙设备发送数据,如果没连接将自动连接后再发
sendData(deviceid, buffer, writeServiceId, wirteCharactId, ms) {
sendData(deviceid, buffer, writeServiceId, wirteCharactId, ms, iosIsChuck, chunkSize) {
if (this.data.platform == 'web') {
return Promise.resolve("h5平台默认成功");
}
// 打印发送的蓝牙指令
let bufferHex = '';
if (buffer) {
let bytes = [];
// 处理不同类型的bufferArrayBuffer、Uint8Array等
if (buffer instanceof ArrayBuffer) {
let dataView = new DataView(buffer);
for (let i = 0; i < buffer.byteLength; i++) {
bytes.push(dataView.getUint8(i));
}
} else if (buffer.byteLength !== undefined) {
// 如果是 Uint8Array 或其他类型
for (let i = 0; i < buffer.byteLength; i++) {
bytes.push(buffer[i] || 0);
}
} else if (Array.isArray(buffer)) {
bytes = buffer;
}
if (bytes.length > 0) {
bufferHex = bytes.map(b => '0x' + b.toString(16).padStart(2, '0').toUpperCase()).join(' ');
}
}
// let bufferHex = '';
// if (buffer) {
// let bytes = [];
// // 处理不同类型的bufferArrayBuffer、Uint8Array等
// if (buffer instanceof ArrayBuffer) {
// let dataView = new DataView(buffer);
// for (let i = 0; i < buffer.byteLength; i++) {
// bytes.push(dataView.getUint8(i));
// }
// } else if (buffer.byteLength !== undefined) {
// // 如果是 Uint8Array 或其他类型
// for (let i = 0; i < buffer.byteLength; i++) {
// bytes.push(buffer[i] || 0);
// }
// } else if (Array.isArray(buffer)) {
// bytes = buffer;
// }
// if (bytes.length > 0) {
// bufferHex = bytes.map(b => '0x' + b.toString(16).padStart(2, '0').toUpperCase()).join(' ');
// }
// }
// console.log("准备发送蓝牙指令 - deviceId:", deviceid, "writeServiceId:", writeServiceId, "writeCharactId:", wirteCharactId);
// console.log("发送数据(Hex):", bufferHex || "(空数据)");
// console.log("发送数据(原始buffer长度):", buffer ? (buffer.byteLength || buffer.length || 0) : 0);
@ -1958,9 +1967,11 @@ class BleHelper {
let sendBuffer = () => {
return new Promise(async (resolve, reject) => {
return new Promise((resolve, reject) => {
let os = plus.os.name;
var promise = new Promise((succ, err) => {
if (!c) {
@ -1969,31 +1980,128 @@ class BleHelper {
})); //没有找到指定设备
return;
}
// console.log("device=", device);
uni.writeBLECharacteristicValue({
deviceId: device.deviceId,
serviceId: device.writeServiceId,
characteristicId: device.wirteCharactId,
value: buffer,
writeType: 'write',
success: () => {
console.log("✓ 蓝牙指令发送成功 - deviceId:", device
.deviceId);
succ();
},
fail: (ex) => {
ex = this.getError(ex);
console.error("✗ 蓝牙指令发送失败 - deviceId:", device
.deviceId, "错误:", ex);
let sendPacket = (data) => {
return new Promise((_succ, _err) => {
uni.writeBLECharacteristicValue({
deviceId: device.deviceId,
serviceId: device.writeServiceId,
characteristicId: device.wirteCharactId,
value: data,
writeType: 'write',
success: () => {
// console.log("✓ 蓝牙指令发送成功 - deviceId:",device.deviceId);
_succ();
},
fail: (ex) => {
ex = this.getError(ex);
console.error("✗ 蓝牙指令发送失败 - deviceId:",device.deviceId, "错误:", ex);
err(ex);
_err(ex);
}
});
});
}
if (os === 'iOS' && iosIsChuck) {
console.error("正在分包发送");
let splitArrayBuffer = (buffer) => {
if (!chunkSize) {
chunkSize = 150;
}
const chunks = [];
const uint8Array = new Uint8Array(buffer);
for (let i = 0; i < uint8Array.length; i += chunkSize) {
const end = Math.min(i + chunkSize, uint8Array.length);
const chunk = uint8Array.slice(i, end).buffer;
chunks.push(chunk);
}
return chunks;
}
});
let arrs = splitArrayBuffer(buffer);
console.error("分包数量", arrs.length);
// 如果数据块数量小于2直接发送原始数据或第一个数据块
if (arrs.length < 2) {
return sendPacket(buffer).then(resolve).catch(reject);
}
// 多块数据需要按顺序发送
let index = 0;
const sendNext = () => {
return new Promise((_resolve, _reject) => {
console.log("正在发送分包" + index);
if (index >= arrs.length) {
return _resolve();
}
Promise.race([this.timeOut(ms), sendPacket(arrs[
index])]).then((
result) => {
console.log(
`✗ 第${index + 1}/${arrs.length}个数据包发送成功`
);
index++;
if (index < arrs.length) {
// iOS平台需要延迟发送避免数据包发送过快
return new Promise(resolve1 => {
setTimeout(() => {
resolve1(
sendNext()
);
},
20
); // 20ms延迟可根据需要调整
});
}
_resolve(result);
}).catch((ex) => {
// console.error("ex=", ex);
if (ex.code == -1) {
console.log(
`✗ 第${index + 1}/${arrs.length}个数据包发送成功`
);
index++;
if (index < arrs.length) {
// iOS平台需要延迟发送避免数据包发送过快
return new Promise(resolve1 => {
setTimeout(() => {
resolve1
(
sendNext()
);
},
20
); // 20ms延迟可根据需要调整
});
}
_resolve(ex);
} else {
console.error(
`✗ 第${index + 1}/${arrs.length}个数据包发送失败:`,
error);
_reject(ex);
}
});
});
};
return sendNext();
} else {
return sendPacket(buffer).then(resolve).catch(reject);
}
});
if (plus.os.name == 'iOS') {
if (os == 'iOS') {
Promise.race([this.timeOut(ms), promise]).then(resolve).catch((ex) => {
// console.error("ex=", ex);
if (ex.code == -1) {
@ -2045,7 +2153,7 @@ class BleHelper {
}
@ -2063,5 +2171,5 @@ export default {
return instance;
},
constService:serviceDic
}
constService: serviceDic
}

View File

@ -12,6 +12,8 @@ class BleReceive {
'/pages/670/HBY670': this.Receive_670.bind(this),
'/pages/4877/BJQ4877': this.Receive_4877.bind(this),
'/pages/100/HBY100': this.Receive_100.bind(this),
'/pages/102/HBY102': this.Receive_102.bind(this),
'/pages/6170/deviceControl/index':this.Receive_6170.bind(this),
'/pages/100J/HBY100-J': this.Receive_100J.bind(this),
'/pages/102/HBY102': this.Receive_102.bind(this)
};
@ -688,6 +690,43 @@ class BleReceive {
return receiveData;
}
Receive_6170(receive, f, path, recArr) {
let receiveData = {};
try {
console.log("订阅消息者:", path);
console.log("设备收到消息:", f);
console.log("消息内容:", receive);
receiveData = JSON.parse(receive.str);
let recCnt = recArr.find(v => {
return v.key.replace(/\//g, "").toLowerCase() == f.device.detailPageUrl
.replace(/\//g, "").toLowerCase();
});
if (!recCnt) {
if (receiveData.sta_PowerPercent <= 20) {
uni.showModal({
title: "提示",
content: "设备'" + f.device.deviceName + "'电量低",
showCancel: false
});
}
}
} catch (error) {
receiveData = {};
console.error("文本解析失败", error)
}
return receiveData;
}
Receive_102(receive, f, path, recArr) {
let receiveData = {};