修改7305人员信息取模组件,文本自动居中

This commit is contained in:
liub
2026-03-19 09:13:48 +08:00
parent ede41f68fd
commit 61f00e1cbf
8 changed files with 405 additions and 222 deletions

View File

@ -27,7 +27,7 @@
// uni.removeStorageSync(val); // uni.removeStorageSync(val);
// } // }
// }); // });
// uni.clearStorageSync(); uni.clearStorageSync();
//以上代码仅在开发时使用,否则会出现不可预知的问题。 //以上代码仅在开发时使用,否则会出现不可预知的问题。
// #ifdef APP|APP-PLUS // #ifdef APP|APP-PLUS

View File

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

View File

@ -75,7 +75,7 @@
<view class="slider-container"> <view class="slider-container">
<slider min="1" max="100" step="1" :disabled="false" :value="formData.liangDu" activeColor="#bbe600" <slider min="1" max="100" step="1" :disabled="false" :value="formData.liangDu" activeColor="#bbe600"
backgroundColor="#00000000" block-size="20" block-color="#ffffffde" @change="sliderChange" backgroundColor="#00000000" block-size="20" block-color="#ffffffde" @change="sliderChange"
@changing="sliderChange" class="custom-slider" /> class="custom-slider" />
</view> </view>
</view> </view>
@ -129,17 +129,17 @@
<view class="item"> <view class="item">
<text class="lbl">单位</text> <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" /> placeholder-class="usrplace" />
</view> </view>
<view class="item"> <view class="item">
<text class="lbl">部门</text> <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" /> placeholder-class="usrplace" />
</view> </view>
<view class="item"> <view class="item">
<text class="lbl">姓名</text> <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" /> placeholder-class="usrplace" />
</view> </view>
@ -286,7 +286,7 @@
light: null, light: null,
bleStatu: '' bleStatu: ''
}, },
inteval: 80, inteval: 150,
device: { device: {
id: "", id: "",
deviceName: "", deviceName: "",
@ -768,14 +768,14 @@
these.showBleUnConnect(); these.showBleUnConnect();
return; return;
} }
let os = plus.os.name;
// 分包发送图片数据 // 分包发送图片数据
var sendImagePackets = function(ReSendNo) { var sendImagePackets = function(ReSendNo) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// 总数据包数 // 总数据包数
let totalPackets = 52; let totalPackets = os=='Android'?52:200;
let currentPacket = 1; let currentPacket = 1;
if (ReSendNo) { if (ReSendNo) {
@ -796,7 +796,8 @@
}); });
setTimeout(() => { setTimeout(() => {
ble.sendString(f.deviceId, "transmit complete", f.writeServiceId, f ble.sendString(f.deviceId, "transmit complete", f
.writeServiceId, f
.wirteCharactId); .wirteCharactId);
}, 1000); }, 1000);
@ -806,7 +807,7 @@
} }
// 计算当前包的数据 // 计算当前包的数据
let packetSize = 250; let packetSize = os == 'Android' ? 250 : 64;
// if (currentPacket <= 51) { // if (currentPacket <= 51) {
// packetSize = 250; // 前51个包每个500字节 // packetSize = 250; // 前51个包每个500字节
// } else { // } else {
@ -814,51 +815,33 @@
// } // }
// 创建数据包 // 创建数据包
const startIndex = (currentPacket - 1) * packetSize; let startIndex = (currentPacket - 1) * packetSize;
const endIndex = Math.min(startIndex + packetSize, these.rgb565Data let endIndex = Math.min(startIndex + packetSize, these.rgb565Data
.length); .length);
if (startIndex > endIndex) { if (startIndex > endIndex) {
return; return;
} }
const packetData = these.rgb565Data.slice(startIndex, let packetData = these.rgb565Data.slice(startIndex,
endIndex); endIndex);
// 构建数据包 // 构建数据包
const bufferSize = 505; // 5 + packetData.length * 2; // 头部5字节 + 数据部分 let bufferSize = os == 'Android' ? 505 :133; // 5 + packetData.length * 2; // 头部5字节 + 数据部分
const buffer = new ArrayBuffer(bufferSize); let buffer = new ArrayBuffer(bufferSize);
const dataView = new DataView(buffer); let dataView = new DataView(buffer);
// 填充头部 // 填充头部
dataView.setUint8(0, 0x55); // 帧头 dataView.setUint8(0, os == 'Android' ? 0x55 : 0x56); // 帧头
dataView.setUint8(1, 0x02); // 帧类型:开机画面 dataView.setUint8(1, 0x02); // 帧类型:开机画面
dataView.setUint8(2, '0x' + currentPacket.toString(16).padStart(2, dataView.setUint8(2, currentPacket); // 包序号
'0')); // 包序号 dataView.setUint16(3, packetData.length*2,false);
if (packetData.length == 250) {
dataView.setUint8(3, 0x01);
dataView.setUint8(4, 0xF4);
} else {
dataView.setUint8(3, 0x00);
dataView.setUint8(4, 0x64);
}
// 填充数据每个RGB565值占2字节 // 填充数据每个RGB565值占2字节
for (let i = 0; i < packetData.length; i++) { for (let i = 0; i < packetData.length; i++) {
dataView.setUint16(5 + i * 2, packetData[i], false); // 大端字节序 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, ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId,
10) 10).then(() => {
.then(() => {
updateLoading(these, { updateLoading(these, {
@ -867,7 +850,7 @@
}) })
currentPacket++; currentPacket++;
setTimeout(sendNextPacket, these.inteval); setTimeout(sendNextPacket,os=='Android'? these.inteval:these.inteval/2);
}).catch(err => { }).catch(err => {
console.log("发送数据包失败了" + JSON.stringify(err)); console.log("发送数据包失败了" + JSON.stringify(err));
if (err.code == '10007') { if (err.code == '10007') {
@ -923,7 +906,7 @@
ImgCutOver: function(data) { ImgCutOver: function(data) {
showLoading(these, { showLoading(these, {
text: "正在发送0/52" text: "正在发送..."
}); });
console.log("data=", data); console.log("data=", data);
these.Status.BottomMenu.show = false; these.Status.BottomMenu.show = false;
@ -964,6 +947,8 @@
}) })
return; return;
} }
let os=plus.os.name;
// os='Android';
let f = these.getDevice(); let f = these.getDevice();
if (!f) { if (!f) {
@ -983,7 +968,7 @@
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (f) { if (f) {
// 总数据包数 // 总数据包数
var totalPackets = 1536; //36; var totalPackets =os=='Android' ? 1536 : 6000; //36;
let currentPacket = 1; let currentPacket = 1;
console.log("发送数据准备中,总共" + totalPackets); console.log("发送数据准备中,总共" + totalPackets);
@ -996,27 +981,30 @@
const sendNextVideoPacket = () => { const sendNextVideoPacket = () => {
// console.log("准备发送一段数据"); // console.log("准备发送一段数据");
if (currentPacket > totalPackets) { if (currentPacket > totalPackets) {
updateLoading(these,{text:'发送完毕,正在处理'})
if (!ReSendNo) { if (!ReSendNo) {
setTimeout(() => { setTimeout(() => {
ble.sendString(f.deviceId, "transmit complete", f ble.sendString(f.deviceId, "transmit complete", f.writeServiceId, f.wirteCharactId, 20)
.writeServiceId, f.wirteCharactId, 20)
.then( .then(
() => { () => {
console.log("全部发送完毕") console.log("全部发送完毕")
}).catch((ex) => {
console.log("出现异常", ex);
});
}, 500);
}
these.Status.BottomMenu.show = false;
hideLoading(these); hideLoading(these);
these.showPop({ these.showPop({
showPop: true, showPop: true,
message: "上传成功", message: "上传成功",
iconUrl: "/static/images/common/success.png" iconUrl: "/static/images/common/success.png"
}); });
}).catch((ex) => {
console.log("出现异常", ex);
});
}, os=='Android'?500:15000);
}
these.Status.BottomMenu.show = false;
these.videoHexArray = null; these.videoHexArray = null;
resolve(); resolve();
@ -1024,7 +1012,7 @@
} }
// 计算当前包的数据 // 计算当前包的数据
let packetSize = 500; let packetSize =os=='Android'? 500:128;
// 创建数据包 // 创建数据包
@ -1040,33 +1028,28 @@
// 构建数据包 // 构建数据包
////console.log("packetData.length"+packetData.length); ////console.log("packetData.length"+packetData.length);
const bufferSize = 504; // 头部5字节 + 数据部分 const bufferSize =packetSize+4; // 头部5字节 + 数据部分
const buffer = new ArrayBuffer(bufferSize); const buffer = new ArrayBuffer(bufferSize);
const dataView = new DataView(buffer); 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(1, 0x04); // 帧类型:开机画面
dataView.setUint8(2, '0x' + sortNo.substring(0, 2)); // 包序号 dataView.setUint16(2, currentPacket,false); // 包序号
dataView.setUint8(3, '0x' + sortNo.substring(2, 4)); // 包序号
// dataView.setUint8(4, 0x01);
// dataView.setUint8(5, 0xF4);
for (let i = 0; i < packetData.length; i++) { 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 ble.sendData(f.deviceId, buffer, f.writeServiceId, f
.wirteCharactId, 10).then(() => { .wirteCharactId, 10).then(() => {
updateLoading(these, { updateLoading(these, {
text: "正在发送:" + currentPacket + "/" + text: "正在发送:" +currentPacket+'/'+totalPackets
totalPackets
}) })
currentPacket++; currentPacket++;
@ -1078,7 +1061,7 @@
if (err.code == '10007') { //遇到这个错误自动重新发送 if (err.code == '10007') { //遇到这个错误自动重新发送
console.log(err.errMsg + ",发送失败了,正在补偿:" + console.log(err.errMsg + ",发送失败了,正在补偿:" +
currentPacket); currentPacket);
setTimeout(sendNextVideoPacket, inteval); setTimeout(sendNextVideoPacket, 500);
} else { } else {
these.Status.BottomMenu.show = false; these.Status.BottomMenu.show = false;
hideLoading(these); hideLoading(these);
@ -1192,7 +1175,7 @@
if (res.data) { if (res.data) {
these.videoHexArray = res.data; these.videoHexArray = res.data;
updateLoading(these, { updateLoading(these, {
text: "正在发送:0/1536" text: "正在发送..."
}); });
these.Status.BottomMenu.show = false; these.Status.BottomMenu.show = false;
@ -1236,7 +1219,7 @@
}).catch((ex1) => { }).catch((ex1) => {
//console.log("出现了异常", ex1) //console.log("出现了异常", ex1)
}).finally(() => { }).finally(() => {
hideLoading(these);
}); });
} }
@ -1592,7 +1575,7 @@
let err = false; let err = false;
this.formData.textLines.find((txt) => { this.formData.textLines.find((txt) => {
if (txt.length === 0 || txt.length > 7) { if (txt.length === 0 || txt.length > 8) {
console.log("txt=", txt); console.log("txt=", txt);
err = true; err = true;
return true; return true;
@ -1601,7 +1584,7 @@
}) })
if (err) { if (err) {
this.showPop({ this.showPop({
message: "单位、部门、姓名必须填写且最多7字", message: "单位、部门、姓名必须填写且最多8字",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png", iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d", borderColor: "#e034344d",
buttonBgColor: "#E03434", buttonBgColor: "#E03434",
@ -1656,11 +1639,12 @@
linePixels.push(0x00); 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, combinedData.push([0x74, 0x72, 0x61, 0x6E, 0x73, 0x6D, 0x69, 0x74, 0x20, 0x63, 0x6F, 0x6D,
0x70, 0x6C, 0x65, 0x74, 0x65 0x70, 0x6C, 0x65, 0x74, 0x65
@ -1712,11 +1696,11 @@
text: '正在发送' + curr + '/' + len text: '正在发送' + curr + '/' + len
}); });
curr++; curr++;
setTimeout(sendPacket, 150); setTimeout(sendPacket, 300);
}).catch(err => { }).catch(err => {
if (err.code == '10007') { if (err.code == '10007') {
setTimeout(sendPacket, 150); setTimeout(sendPacket, 300);
} else { } else {
console.log("err:", err); console.log("err:", err);
hideLoading(these); hideLoading(these);
@ -1750,6 +1734,7 @@
setTimeout(() => { setTimeout(() => {
Promise.allSettled([holdHand(), drawText()]).then(results => { Promise.allSettled([holdHand(), drawText()]).then(results => {
console.log("results=", results)
if (results[0].status == 'rejected') { if (results[0].status == 'rejected') {
updateLoading(these, { updateLoading(these, {
text: results[0].reason text: results[0].reason

View File

@ -52,7 +52,7 @@
{{ deviceInfo.onlineStatus === 0 ? '离线' : deviceInfo.onlineStatus === 2 ? '故障' : '在线' }} {{ deviceInfo.onlineStatus === 0 ? '离线' : deviceInfo.onlineStatus === 2 ? '故障' : '在线' }}
</text> </text>
</view> </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-label">蓝牙状态</text>
<text class="info-value status-running" > <text class="info-value status-running" >
{{getbleStatu}} {{getbleStatu}}
@ -404,7 +404,8 @@
}, },
Status: { Status: {
pageHide: null pageHide: null
} },
inteval: 120
} }
}, },
computed: { computed: {
@ -432,10 +433,36 @@
} }
}, },
methods: { methods: {
getDevice: function() { 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("LinkedList=", ble.data.LinkedList);
console.log("this.device=", this.device); console.log("this.device=", this.itemInfo);
let f = ble.data.LinkedList.find((v) => { let f = ble.data.LinkedList.find((v) => {
if (v.macAddress == this.itemInfo.deviceMac) { if (v.macAddress == this.itemInfo.deviceMac) {
if (!this.formData.deviceId) { if (!this.formData.deviceId) {
@ -446,6 +473,8 @@
}); });
return f; return f;
}
return null;
}, },
initBle() { initBle() {
if (this.itemInfo.deviceMac) { if (this.itemInfo.deviceMac) {
@ -1259,9 +1288,11 @@
}); });
} }
setTimeout(function() { setTimeout(()=> {
sendImagePackets().catch(() => { sendImagePackets().catch(() => {
}).finally(()=>{
this.lightModeB=false;
}); });
}, 0) }, 0)
} }
@ -1938,12 +1969,13 @@
}, },
onShow() { onShow() {
debugger;
let f = this.getDevice(); let f = this.getDevice();
if (f) { if (f) {
these.formData.bleStatu = 'connecting'; this.formData.bleStatu = 'connecting';
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => { ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then(res => {
console.log("连接成功") console.log("连接成功")
these.formData.bleStatu = true; this.formData.bleStatu = true;
}); });
} }
}, },

View File

@ -114,20 +114,20 @@
<view class="btnSend fright" v-on:click.stop="sendUsr">发送</view> <view class="btnSend fright" v-on:click.stop="sendUsr">发送</view>
<view class="clear"></view> <view class="clear"></view>
<textToDotMatrixFor7305 class="TextToHex" ref="textToHex" :txts="formData.textLines" <textToDotMatrixFor7305 class="TextToHex" ref="textToHex" :txts="formData.textLines"
:bgColor="'#FFFFFF'" :color="'#000000'" :fontSize="11" /> :bgColor="'#FFFFFF'" :color="'#000000'" :fontSize="13" />
</view> </view>
<view class="item"> <view class="item">
<text class="lbl">单位</text> <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>
<view class="item"> <view class="item">
<text class="lbl">部门</text> <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>
<view class="item"> <view class="item">
<text class="lbl">姓名</text> <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>
</view> </view>
@ -272,9 +272,10 @@
liangDu: '100', liangDu: '100',
id: '', id: '',
deviceId: '', deviceId: '',
textLines: ['', '', ''], textLines: [],
mode: '', mode: '',
bleStatu: '' bleStatu: '',
inputLines:[]
}, },
inteval: 500, inteval: 500,
device: { device: {
@ -1195,8 +1196,9 @@ debugger;
these.showBleUnConnect() these.showBleUnConnect()
return; return;
} }
debugger;
let err = false; let err = false;
this.formData.textLines.find((txt) => { this.formData.inputLines.find((txt) => {
if (txt.length === 0 || txt.length > 5) { if (txt.length === 0 || txt.length > 5) {
console.log("txt=", txt); console.log("txt=", txt);
err = true; err = true;
@ -1213,12 +1215,16 @@ debugger;
}); });
return; return;
} }
this.formData.textLines=[this.formData.inputLines[0],this.formData.inputLines[1],this.formData.inputLines[2]];
showLoading(these, { showLoading(these, {
text: "请稍候..." text: "发送中..."
}); });
this.setBleFormData(); this.setBleFormData();
let task = async () => { let task = async () => {
var sendTxtPackge = (rgbdata, type, str) => { var sendTxtPackge = (rgbdata, type, str,index) => {
var promise = new Promise((resolve, reject) => { var promise = new Promise((resolve, reject) => {
try { try {
@ -1261,7 +1267,7 @@ debugger;
.toString(16).padStart(2, '0')); .toString(16).padStart(2, '0'));
console.log(`发送数据块 ${chunkIndex + 1}/${numChunks}:`, hexArray console.log(`发送数据块 ${chunkIndex + 1}/${numChunks}:`, hexArray
.join(' ')); .join(' '));
updateLoading(these,{text:'正在发送'+((index-1)*14+chunkIndex + 1)+'/42'})
ble.sendData(f.deviceId, chunk, f.writeServiceId, f ble.sendData(f.deviceId, chunk, f.writeServiceId, f
.wirteCharactId, 100).then(() => { .wirteCharactId, 100).then(() => {
chunkIndex++; chunkIndex++;
@ -1318,7 +1324,7 @@ debugger;
try { try {
// console.log("1111"); // console.log("1111");
await sendTxtPackge(rgb, h3dic[i], str); await sendTxtPackge(rgb, h3dic[i], str,i+1);
// console.log("222222"); // console.log("222222");
} catch (ex) { } catch (ex) {
flag = false; flag = false;
@ -1371,9 +1377,9 @@ debugger;
res = res.data; res = res.data;
let personnelInfo = res.personnelInfo; let personnelInfo = res.personnelInfo;
if (personnelInfo) { if (personnelInfo) {
these.formData.textLines[2] = personnelInfo.unitName; these.formData.inputLines[2] = personnelInfo.unitName;
these.formData.textLines[1] = personnelInfo.name; these.formData.inputLines[1] = personnelInfo.name;
these.formData.textLines[0] = personnelInfo.position; these.formData.inputLines[0] = personnelInfo.position;
} }
} }

View File

@ -337,6 +337,21 @@
}, pagePath); }, 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 => { ble.addDisposeCallback(res => {
if (these.Status.isPageHidden) { if (these.Status.isPageHidden) {

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: { methods: {

View File

@ -1852,7 +1852,7 @@ class BleHelper {
} }
//向蓝牙设备发送一个字符串的ASCII码 //向蓝牙设备发送一个字符串的ASCII码
sendString(deviceid, str, writeServiceId, wirteCharactId, ms) { sendString(deviceid, str, writeServiceId, wirteCharactId, ms, iosIsChuck, chunkSize) {
if (str && typeof(str) == 'object') { if (str && typeof(str) == 'object') {
str = JSON.stringify(str); str = JSON.stringify(str);
} }
@ -1876,7 +1876,7 @@ class BleHelper {
} }
//向蓝牙设备发送一个16进制的数组数据 //向蓝牙设备发送一个16进制的数组数据
sendHexs(deviceid, array, writeServiceId, wirteCharactId, ms) { sendHexs(deviceid, array, writeServiceId, wirteCharactId, ms, iosIsChuck, chunkSize) {
if (array && array.length) { if (array && array.length) {
let bufferSize = array.length; let bufferSize = array.length;
let buffer = new ArrayBuffer(bufferSize); let buffer = new ArrayBuffer(bufferSize);
@ -1885,7 +1885,7 @@ class BleHelper {
dataView.setUint8(i, array[i]); dataView.setUint8(i, array[i]);
} }
return this.sendData(deviceid, buffer, writeServiceId, wirteCharactId, ms); return this.sendData(deviceid, buffer, writeServiceId, wirteCharactId, ms, iosIsChuck, chunkSize);
} else { } else {
return Promise.resolve({ return Promise.resolve({
@ -1896,33 +1896,33 @@ class BleHelper {
} }
//向蓝牙设备发送数据,如果没连接将自动连接后再发 //向蓝牙设备发送数据,如果没连接将自动连接后再发
sendData(deviceid, buffer, writeServiceId, wirteCharactId, ms) { sendData(deviceid, buffer, writeServiceId, wirteCharactId, ms, iosIsChuck, chunkSize) {
if (this.data.platform == 'web') { if (this.data.platform == 'web') {
return Promise.resolve("h5平台默认成功"); return Promise.resolve("h5平台默认成功");
} }
// 打印发送的蓝牙指令 // 打印发送的蓝牙指令
let bufferHex = ''; // let bufferHex = '';
if (buffer) { // if (buffer) {
let bytes = []; // let bytes = [];
// 处理不同类型的bufferArrayBuffer、Uint8Array等 // // 处理不同类型的bufferArrayBuffer、Uint8Array等
if (buffer instanceof ArrayBuffer) { // if (buffer instanceof ArrayBuffer) {
let dataView = new DataView(buffer); // let dataView = new DataView(buffer);
for (let i = 0; i < buffer.byteLength; i++) { // for (let i = 0; i < buffer.byteLength; i++) {
bytes.push(dataView.getUint8(i)); // bytes.push(dataView.getUint8(i));
} // }
} else if (buffer.byteLength !== undefined) { // } else if (buffer.byteLength !== undefined) {
// 如果是 Uint8Array 或其他类型 // // 如果是 Uint8Array 或其他类型
for (let i = 0; i < buffer.byteLength; i++) { // for (let i = 0; i < buffer.byteLength; i++) {
bytes.push(buffer[i] || 0); // bytes.push(buffer[i] || 0);
} // }
} else if (Array.isArray(buffer)) { // } else if (Array.isArray(buffer)) {
bytes = buffer; // bytes = buffer;
} // }
if (bytes.length > 0) { // if (bytes.length > 0) {
bufferHex = bytes.map(b => '0x' + b.toString(16).padStart(2, '0').toUpperCase()).join(' '); // bufferHex = bytes.map(b => '0x' + b.toString(16).padStart(2, '0').toUpperCase()).join(' ');
} // }
} // }
// console.log("准备发送蓝牙指令 - deviceId:", deviceid, "writeServiceId:", writeServiceId, "writeCharactId:", wirteCharactId); // console.log("准备发送蓝牙指令 - deviceId:", deviceid, "writeServiceId:", writeServiceId, "writeCharactId:", wirteCharactId);
// console.log("发送数据(Hex):", bufferHex || "(空数据)"); // console.log("发送数据(Hex):", bufferHex || "(空数据)");
// console.log("发送数据(原始buffer长度):", buffer ? (buffer.byteLength || buffer.length || 0) : 0); // console.log("发送数据(原始buffer长度):", buffer ? (buffer.byteLength || buffer.length || 0) : 0);
@ -1952,9 +1952,11 @@ class BleHelper {
let sendBuffer = () => { let sendBuffer = () => {
return new Promise(async (resolve, reject) => { return new Promise((resolve, reject) => {
let os = plus.os.name;
var promise = new Promise((succ, err) => { var promise = new Promise((succ, err) => {
if (!c) { if (!c) {
@ -1963,31 +1965,128 @@ class BleHelper {
})); //没有找到指定设备 })); //没有找到指定设备
return; return;
} }
// console.log("device=", device); let sendPacket = (data) => {
return new Promise((_succ, _err) => {
uni.writeBLECharacteristicValue({ uni.writeBLECharacteristicValue({
deviceId: device.deviceId, deviceId: device.deviceId,
serviceId: device.writeServiceId, serviceId: device.writeServiceId,
characteristicId: device.wirteCharactId, characteristicId: device.wirteCharactId,
value: buffer, value: data,
writeType: 'write', writeType: 'write',
success: () => { success: () => {
console.log("✓ 蓝牙指令发送成功 - deviceId:", device // console.log("✓ 蓝牙指令发送成功 - deviceId:",device.deviceId);
.deviceId); _succ();
succ();
}, },
fail: (ex) => { fail: (ex) => {
ex = this.getError(ex); ex = this.getError(ex);
console.error("✗ 蓝牙指令发送失败 - deviceId:", device console.error("✗ 蓝牙指令发送失败 - deviceId:",device.deviceId, "错误:", ex);
.deviceId, "错误:", ex);
err(ex); _err(ex);
} }
}); });
}); });
if (plus.os.name == 'iOS') {
}
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 (os == 'iOS') {
Promise.race([this.timeOut(ms), promise]).then(resolve).catch((ex) => { Promise.race([this.timeOut(ms), promise]).then(resolve).catch((ex) => {
// console.error("ex=", ex); // console.error("ex=", ex);
if (ex.code == -1) { if (ex.code == -1) {