6155完成部分协议对接

This commit is contained in:
liub
2025-08-15 16:39:00 +08:00
parent 6ef2bb08b9
commit e95b2466e1
10 changed files with 871 additions and 708 deletions

View File

@ -2,17 +2,14 @@
<view class="message-popup" :class="{ 'show': config.show }"> <view class="message-popup" :class="{ 'show': config.show }">
<view class="mask" @click="closeMenu" :class="{ 'show': config.show }" <view class="mask" @click="closeMenu" :class="{ 'show': config.show }"
:style="{backgroundColor:config.maskBgColor,display:(config.showMask?'':'none')}" :style="{backgroundColor:config.maskBgColor,display:(config.showMask?'':'none')}">
>
</view> </view>
<view class="bottom-slide-menu" :style="{ backgroundColor: config.bgColor }" :class="{ 'show': config.show }" <view class="bottom-slide-menu" :style="{ backgroundColor: config.bgColor }" :class="{ 'show': config.show }"
@touchmove.stop.prevent> @touchmove.stop.prevent>
<view class="menu-header" :class="config.showHeader?'':'displayNone'"> <view class="menu-header" :class="config.showHeader?'':'displayNone'">
<view class="title" :style="{ color: config.textColor}">{{ config.title }}</view> <view class="title" :style="{ color: config.textColor}">{{ config.title }}</view>
<view class="close-icon" @click="closeMenu" <view class="close-icon" @click="closeMenu" :style="{display:(config.showClose?'':'none')}">
:style="{display:(config.showClose?'':'none')}"
>
<image src="/static/Images/public/close.png" mode="aspectFit"></image> <image src="/static/Images/public/close.png" mode="aspectFit"></image>
</view> </view>
</view> </view>
@ -28,8 +25,14 @@
<view class="p100" :style="{backgroundColor:config.activeIndex==index?config.itemBgColor:'', <view class="p100" :style="{backgroundColor:config.activeIndex==index?config.itemBgColor:'',
justifyContent:config.textAlign justifyContent:config.textAlign
}">
<view class="imgContent" :style="{
height:config.itemHeight,
width:config.itemHeight
}"> }">
<image v-if="item.icon" :src="item.icon" mode="aspectFit"></image> <image v-if="item.icon" :src="item.icon" mode="aspectFit"></image>
</view>
<text>{{ item.text }}</text> <text>{{ item.text }}</text>
</view> </view>
@ -61,27 +64,27 @@
config: { config: {
type: Object, type: Object,
default: () => ({ default: () => ({
show: false,//是否显示 show: false, //是否显示
showHeader: false,//是否显示标头 showHeader: false, //是否显示标头
showMask:true,//是否显示mask showMask: true, //是否显示mask
showDivider: false,//是否在两个项之间显示分隔线 showDivider: false, //是否在两个项之间显示分隔线
showBtn: false,//是否显示底部按钮 showBtn: false, //是否显示底部按钮
showClose:false,//是否显示右上角关闭按钮 showClose: false, //是否显示右上角关闭按钮
maskBgColor:'',//mask的颜色 maskBgColor: '', //mask的颜色
menuItems: [],//菜单项 包含icon text menuItems: [], //菜单项 包含icon text
activeIndex: -1,//当前已选中的项编号 activeIndex: -1, //当前已选中的项编号
bgColor: '#2a2a2a',//主体背景 bgColor: '#2a2a2a', //主体背景
itemBgColor: '#3a3a3a',//各项被选中后的背景 itemBgColor: '#3a3a3a', //各项被选中后的背景
textColor: '#ffffffde',//各项的文字颜色 textColor: '#ffffffde', //各项的文字颜色
textAlign: 'flex-start',//各项的文字居中方式 textAlign: 'flex-start', //各项的文字居中方式
title: '',//header的文字 title: '', //header的文字
dividerColor: '#00000000',//分隔线颜色 dividerColor: '#00000000', //分隔线颜色
dividerThickness: '0rpx',//分隔线宽度 dividerThickness: '0rpx', //分隔线宽度
dividerMargin: '10rpx',//分隔线距离两边的宽度 dividerMargin: '10rpx', //分隔线距离两边的宽度
itemHeight: '80rpx',//各项的调试 itemHeight: '80rpx', //各项的调试
btnBgColor: "#bbe600",//按钮颜色 btnBgColor: "#bbe600", //按钮颜色
btnText: "确定",//按钮文字 btnText: "确定", //按钮文字
btnTextColor: "#000000",//按钮文字颜色 btnTextColor: "#000000", //按钮文字颜色
}) })
}, },
@ -112,7 +115,6 @@
} }
} }
</script> </script>
<style> <style>
@ -126,7 +128,7 @@
} }
.p100 { .p100 {
width: 100%; width: calc(100% - 20rpx);
height: 100%; height: 100%;
border-radius: 8rpx; border-radius: 8rpx;
display: flex; display: flex;
@ -136,7 +138,8 @@
justify-content: flex-start; justify-content: flex-start;
align-items: center; align-items: center;
box-sizing: border-box; box-sizing: border-box;
padding: 0rpx 20rpx; padding: 0rpx 20rpx 0rpx 0rpx;
margin-left: 20rpx;
} }
.displayNone { .displayNone {
@ -151,7 +154,7 @@
z-index: 9999; z-index: 9999;
transition: transform 0.3s ease-out; transition: transform 0.3s ease-out;
transform: translateY(100%); transform: translateY(100%);
border-radius: 16rpx 16rpx 0 0; border-radius: 32rpx 32rpx 0 0;
box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1); box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
} }
@ -217,11 +220,24 @@
width: 100%; width: 100%;
box-sizing: border-box; box-sizing: border-box;
position: relative; position: relative;
margin-bottom: 20rpx;
} }
.menu-item image { .menu-item image {
width: 40rpx; width: 40rpx;
height: 40rpx; height: 40rpx;
}
.imgContent {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-content: center;
justify-content: center;
align-items: center;
background: #4a4a4a;
border-radius: 10rpx;
margin-right: 20rpx; margin-right: 20rpx;
} }

View File

@ -1,19 +1,13 @@
<template> <template>
<view> <view>
<!-- 只创建一个Canvas用于复用 --> <canvas type="2d" canvas-id="reusableCanvas" :width="currentCanvasWidth" :height="currentCanvasHeight"
<canvas class="offscreen-canvas"></canvas>
type="2d"
canvas-id="reusableCanvas"
:width="currentCanvasWidth"
:height="currentCanvasHeight"
class="offscreen-canvas"
></canvas>
</view> </view>
</template> </template>
<script> <script>
export default { export default {
name: "TextToHex", name: "TextToHexV1",
props: { props: {
txts: { txts: {
type: Array, type: Array,
@ -25,13 +19,13 @@
default: 16, default: 16,
validator: (value) => value > 0 && value <= 100 validator: (value) => value > 0 && value <= 100
}, },
bgColor:{ bgColor: {
type:String, type: String,
default:"#000000" default: "#ffffff"
}, },
color:{ color: {
type:String, type: String,
default:"#FFFFFF" default: "#000000"
} }
}, },
data() { data() {
@ -72,16 +66,50 @@
* 复用单个Canvas处理所有文本行 * 复用单个Canvas处理所有文本行
*/ */
async drawAndGetPixels() { async drawAndGetPixels() {
if (this.validTxts.length === 0) {
return []; let convertCharToMatrix=function(imageData) {
// console.log("imgData=",imageData)
let matrix = [];
// 逐行处理
for (let y = 0; y < 16; y++) {
let byte1 = 0,
byte2 = 0;
// 每行16个像素分为两个字节
for (let x = 0; x < 16; x++) {
// 计算像素在imageData中的索引 (RGBA格式)
let index = (y * 16 + x) * 4;
let red = imageData[index];
// 黑色像素R值较低视为1白色视为0
let isBlack = red < 128;
if (x < 8) {
// 第一个字节左8位
if (isBlack) {
byte1 |= 0x80 >> x; // 从左到右设置位
}
} else {
// 第二个字节右8位
if (isBlack) {
byte2 |= 0x80 >> (x - 8);
}
}
} }
const result = []; // 将字节转换为两位十六进制字符串
const ctx = this.ctx; matrix.push('0x' + byte1.toString(16).padStart(2, '0').toUpperCase());
matrix.push('0x' + byte2.toString(16).padStart(2, '0').toUpperCase());
}
return matrix;
}
let drawTxt=async (textLine)=> {
let result = {};
let ctx = this.ctx;
// 循环处理每行文本
for (let i = 0; i < this.validTxts.length; i++) {
const textLine = this.validTxts[i];
// 1. 动态调整Canvas尺寸 // 1. 动态调整Canvas尺寸
this.currentCanvasWidth = this.calcLineWidth(textLine); this.currentCanvasWidth = this.calcLineWidth(textLine);
this.currentCanvasHeight = this.fontSize; this.currentCanvasHeight = this.fontSize;
@ -93,17 +121,17 @@
ctx.setFillStyle(this.color); ctx.setFillStyle(this.color);
ctx.setTextBaseline('middle'); ctx.setTextBaseline('middle');
ctx.setFontSize(this.fontSize); ctx.setFontSize(this.fontSize);
ctx.font = `${this.fontSize}px SimHei, Microsoft YaHei, Arial, sans-serif`; ctx.font = `${this.fontSize}px "PingFang SC", PingFang SC, Arial, sans-serif`;
// 4. 绘制当前行文本 // 4. 绘制当前行文本
let currentX = 0; let currentX = 0;
const currentY = this.fontSize / 2; let currentY = this.fontSize / 2;
for (let j = 0; j < textLine.length; j++) { for (let j = 0; j < textLine.length; j++) {
const char = textLine[j]; let char = textLine[j];
ctx.fillText(char, currentX, currentY); ctx.fillText(char, currentX, currentY);
// 按实际字符宽度计算间距 // 按实际字符宽度计算间距
const charWidth = ctx.measureText(char).width; let charWidth = ctx.measureText(char).width;
currentX += charWidth ; currentX += charWidth;
} }
// 5. 异步绘制并获取像素数据(串行处理避免冲突) // 5. 异步绘制并获取像素数据(串行处理避免冲突)
@ -116,30 +144,47 @@
width: this.currentCanvasWidth, width: this.currentCanvasWidth,
height: this.currentCanvasHeight, height: this.currentCanvasHeight,
success: res => { success: res => {
result.push({
result={
line: textLine, line: textLine,
pixelData: res.data, pixelData: res.data,
width: this.currentCanvasWidth, width: this.currentCanvasWidth,
height: this.currentCanvasHeight height: this.currentCanvasHeight
}); };
resolve(); resolve();
}, },
fail: err => { fail: err => {
// console.error(`处理第${i+1}行失败:`, err); // console.error(`处理第${i+1}行失败:`, err);
reject(err); reject(err)
} }
}); });
}); });
}); });
}
return result; return result;
} }
let arr = [];
// 循环处理每行文本
for (let i = 0; i < this.validTxts.length; i++) {
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));
}
console.log("hexs=",linePixls.join(","));
arr.push(linePixls);
}
return arr;
}
} }
}; };
</script> </script>
<style > <style>
.offscreen-canvas { .offscreen-canvas {
position: fixed; position: fixed;
left: -9999px; left: -9999px;

View File

@ -23,10 +23,10 @@
return { return {
visible: false, visible: false,
dotsCount: 12, dotsCount: 12,
dotColors: ['#CEF231c2'], dotColors: ['#CEF231'],
text: '请稍候...',//文本文字 text: '请稍候...',//文本文字
textColor: '#FFFFFFde',//文本颜色 textColor: '#FFFFFFde',//文本颜色
radius: 35,//圆的半径 radius: 32,//圆的半径
duration: 1200,//动画的播放速度 duration: 1200,//动画的播放速度
colorIndex: 0 colorIndex: 0
} }
@ -158,7 +158,7 @@
position: absolute; position: absolute;
top: 50%; top: 50%;
left: 50%; left: 50%;
width: 4rpx; width: 6rpx;
height: 30rpx; height: 30rpx;
border-radius: 12rpx; border-radius: 12rpx;
/* margin-top: -4rpx; /* margin-top: -4rpx;

View File

@ -24,11 +24,11 @@
<view class="eqinfo"> <view class="eqinfo">
<view class="item"> <view class="item">
<text class="lbl">蓝牙名称</text> <text class="lbl">蓝牙名称</text>
<text class="value">{{formData.name}}</text> <text class="value">{{formData.blename}}</text>
</view> </view>
<view class="item"> <view class="item">
<text class="lbl">信号强度</text> <text class="lbl">设备名称</text>
<text class="value">{{formData.RSSI}}</text> <text class="value">{{formData.deviceName}}</text>
</view> </view>
<view class="item"> <view class="item">
<text class="lbl">设备状态</text> <text class="lbl">设备状态</text>
@ -83,26 +83,23 @@
<text class="usrtitle fleft">人员信息登记</text> <text class="usrtitle fleft">人员信息登记</text>
<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>
<TextToHex class="TextToHex" ref="textToHex" :txts="textLines" :bgColor="'#000000'" :color="'#FFFFFF'" <TextToHex class="TextToHex" ref="textToHex" :txts="formData.textLines" :bgColor="'#000000'"
:fontSize="16" /> :color="'#FFFFFF'" :fontSize="16" />
</view> </view>
<view class="item"> <view class="item">
<text class="lbl">单位</text> <text class="lbl">单位</text>
<input class="value" v-model="textLines[0]" placeholder="请输入单位" placeholder-class="usrplace" /> <input class="value" v-model="formData.textLines[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" />
</view> </view>
<view class="item"> <view class="item">
<text class="lbl">姓名</text> <text class="lbl">姓名</text>
<input class="value" v-model="textLines[1]" placeholder="请输入姓名" placeholder-class="usrplace" /> <input class="value" v-model="formData.textLines[2]" placeholder="请输入职位" placeholder-class="usrplace" />
</view>
<view class="item">
<text class="lbl">职位</text>
<input class="value" v-model="textLines[2]" placeholder="请输入职位" placeholder-class="usrplace" />
</view>
<view class="item">
<text class="lbl">ID号</text>
<input class="value" v-model="textLines[3]" placeholder="请输入ID" placeholder-class="usrplace" />
</view> </view>
</view> </view>
<view class="proinfo lamp"> <view class="proinfo lamp">
<text class="title">产品信息</text> <text class="title">产品信息</text>
@ -141,25 +138,31 @@
</view> </view>
</BottomSlideMenuPlus> </BottomSlideMenuPlus>
<Progress :config="Status.Progress"></Progress> <global-loading ref="loading" />
</view> </view>
</template> </template>
<script> <script>
import TextToHexVue from '@/components/TextToHex/TextToHex.vue'; import TextToHexVue from '@/components/TextToHex/TextToHex.vue';
import bleTool from '@/utils/BleHelper.js'; import bleTool from '@/utils/BleHelper.js';
import {
showLoading,
hideLoading,
updateLoading
} from '@/utils/loading.js'
var ble = null; var ble = null;
var these = null;
export default { export default {
data() { data() {
return { return {
Status: { Status: {
refferKey: '',
Pop: { Pop: {
showPop: false, //是否显示弹窗 showPop: false, //是否显示弹窗
popType: 'custom', popType: 'custom',
textColor: '#ffffffde',
bgColor: '#383934bd', bgColor: '#383934bd',
borderColor: '#BBE600', borderColor: '#BBE600',
textColor: '#ffffffde',
buttonBgColor: '#BBE600', buttonBgColor: '#BBE600',
buttonTextColor: '#232323DE', buttonTextColor: '#232323DE',
iconUrl: '', iconUrl: '',
@ -206,105 +209,77 @@
showMask: true, showMask: true,
maskBgColor: '#00000066', maskBgColor: '#00000066',
showClose: false showClose: false
},
Progress: {
show: false, //是否显示
height: '20rpx',
showMask: true, //是否显示mask
maskBgColor: '#00000000', //mask背景颜色
contentBgColor: '#121212', //总背景颜色
showText: true, //是否显示当前进度的文字
txtColor: '#ffffffde', //文字的颜色
curr: 20, //当前进度
total: 100, //总进度
proBgColor: '#2a2a2a', //进度条底色,
proBorder: '', //进度条border
currBgColor: '#bbe600', //当前进度底色
currBorder: '', //当前进度border
borderRadius: '10rpx'
} }
}, },
formData: { formData: {
img: '/static/images/6155/DeviceDetail/equip.png', img: '',
battary: '60', battary: '',
xuhang: '1小时', xuhang: '',
name: 'JQZM-EF4651', deviceName: '',
RSSI: '-30', RSSI: '',
statu: '运行中', statu: '正常',
liangDu: '50', liangDu: '100',
id: '' id: '',
}, deviceId: '',
cEdit: { textLines: ['我爱你', '中国', '五星红旗'],
mode: '' mode: ''
}, },
textLines: ['黄石消防支队','菜英俊','小队长','HSXF01061'],
device: {
deviceId: '',
writeServiceId: '',
wirteCharactId: '',
notifyServiceid: '',
notifyCharactId: ''
}
} }
}, },
onUnload() { onUnload() {
ble.removeReceiveCallback(this); ble.removeReceiveCallback(this);
}, },
onLoad: function() { onLoad: function() {
var these = this; these = this;
let eventChannel = this.getOpenerEventChannel();
//eventChannel.on('deviceControl', function(data) {
let data = {
data: {
deviceMac: '35:06:00:EF:46:51',
bluetoothName: 'JQZM-EF4651',
deviceName: 'JQZM-EF4651',
devicePic: '',
id: '35:06:00:EF:46:51'
}
};
console.log("收到父页面的参数:" + JSON.stringify(data));
var device = data.data;
these.device.deviceId = device.deviceMac;
these.formData.name = device.bluetoothName ? device.bluetoothName : device.deviceName;
these.formData.img = device.devicePic;
these.formData.id = device.id;
//})
ble = bleTool.getBleTool(); ble = bleTool.getBleTool();
ble.addReceiveCallback(these.bleValueNotify); ble.addReceiveCallback(these.bleValueNotify);
let eventChannel = this.getOpenerEventChannel();
let startLink=()=>{ eventChannel.on('detailData', function(data) {
ble.addDeviceFound((res) => {
console.log("发现新设备,",res);
let f = res.devices.find((v) => {
return v.name == device.deviceName;
});
if (f) {
console.log("找到了目标设备,正在连接:"+f.deviceId)
these.device.deviceId = f.deviceId;
these.formData.id = f.deviceId;
ble.LinkBlue(f.deviceId);
}
});
ble.StartSearch();
let device = data.data;
console.log("收到父页面的参数:" + JSON.stringify(device));
let f = ble.data.LinkedList.find((v) => {
if (v.macAddress == device.deviceMac) {
console.log("找到设备了", v);
these.formData.deviceId = v.deviceId;
return true;
} }
if(ble.data.LinkedList && ble.data.LinkedList.length>0){ return false;
let f=ble.data.LinkedList.find((v)=>{
return v.name==device.deviceName;
}); });
if(!f){ if (!f) {
startLink();
}else{
these.device.deviceId = f.deviceId; these.showPop({
these.formData.id = f.deviceId; message: "蓝牙未连接过该设备,请使用蓝牙重新添加该设备",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
return;
} }
}else{ let form = f.formData;
startLink(); if (form) {
let keys = Object.keys(form);
for (var i = keys.length; i >= 0; i--) {
let key = keys[i];
these.formData[key] = form[key];
} }
}
these.formData.blename = f.name ? f.name : "Unname";
these.formData.deviceName = device.deviceName;
these.formData.img = device.devicePic;
these.formData.id = device.id;
these.formData.deviceId = f.deviceId;
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId);
these.setBleFormData();
});
}, },
onHide: function() { onHide: function() {
@ -312,46 +287,7 @@
}, },
onBackPress(e) { onBackPress(e) {
var these = this; ble.removeReceiveCallback();
console.log("these.device=" + JSON.stringify(these.device));
if (these.device.deviceId) {
if (e.from === 'backbutton') {
let res = {
devices: ble.data.LinkedList
};
if (res.devices.length == 0) {
console.log("没有已连接的蓝牙设备")
uni.navigateBack();
return false;
}
let f = res.devices.find(function(v) {
return v.deviceId == these.device.deviceId;
});
if (!f) {
console.log("该设备没有连接")
uni.navigateBack();
return false;
}
uni.showModal({
title: '提示',
content: '是否断开与设备的蓝牙连接?',
success: function(res) {
if (res.confirm) {
ble.disconnectDevice(these.device.deviceId);
}
uni.navigateBack();
}
});
return true;
}
}
return false;
}, },
computed: { computed: {
@ -374,40 +310,123 @@
}, },
methods: { methods: {
getDevice: function() { getDevice: function() {
var these = this; console.log("LinkedList=", ble.data.LinkedList);
console.log("these.device=",these.device);
console.log("LinkedList=",ble.data.LinkedList.LinkedList);
let f = ble.data.LinkedList.find((v) => { let f = ble.data.LinkedList.find((v) => {
return v.deviceId == these.device.deviceId; return v.deviceId == these.formData.deviceId;
}); });
return f; return f;
}, },
bleValueNotify: function(data) { bleValueNotify: function(receive) {
console.log("读取到设备发送的数据:" + JSON.stringify(data)); console.log("处理接收到的数据:" + receive);
// data.characteristicId
// data.deviceId let bytes = receive.bytes;
// data.serviceId
// data.value 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;
this.setBleFormData();
} catch (error) {
console.log('数据解析错误:', error);
}
}
}, },
proParam: function() { proParam: function() {
uni.showToast({ uni.navigateTo({
title: '敬请期待' url: '/pages/common/productDes/index?id=' + this.formData.id,
}) success(ev) {
}
});
}, },
handRemark: function() { handRemark: function() {
this.alert('提示', "敬请期待"); uni.navigateTo({
url: '/pages/common/operatingInstruct/index?id=' + this.formData.id,
success(ev) {
}
});
}, },
handVideo: function() { handVideo: function() {
this.alert('提示', "敬请期待"); uni.navigateTo({
url: '/pages/common/operationVideo/index?id=' + this.formData.id,
success(ev) {
}
});
}, },
checkImgUpload: function() { checkImgUpload: function() {
console.log("123213213213"); let f = these.getDevice();
var these = this;
if (!f) {
these.showPop({
message: "蓝牙未连接过该设备,请使用蓝牙重新添加该设备",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
return;
}
// 处理像素数据并发送 // 处理像素数据并发送
var processAndSendImageData = function(pixels) { var processAndSendImageData = function(pixels) {
@ -428,18 +447,18 @@
// 总数据包数 // 总数据包数
const totalPackets = 52; const totalPackets = 52;
let currentPacket = 1; let currentPacket = 1;
f = these.getDevice();
if (f) {
// 发送单个数据包 // 发送单个数据包
const sendNextPacket = () => { const sendNextPacket = () => {
if (currentPacket > totalPackets) { if (currentPacket > totalPackets) {
uni.hideLoading(); hideLoading(these);
these.Status.BottomMenu.show = false; these.Status.BottomMenu.show = false;
these.Status.Progress.show = false;
these.Status.Pop.showPop = true; these.showPop({
these.Status.Pop.message = "上传成功"; message: "上传成功",
these.Status.Pop.iconUrl = iconUrl: "/static/images/6155/DeviceDetail/uploadSuccess.png"
"/static/images/6155/DeviceDetail/uploadSuccess.png"; });
resolve(); resolve();
return; return;
} }
@ -495,45 +514,38 @@
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); // 大端字节序
} }
console.log(
`发送数据包${currentPacket}/${totalPackets},${dataView.getUint8(0)} ${dataView.getUint8(1)} ${dataView.getUint8(2)}`
)
//发送数据包 //发送数据包
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId,
30) 30)
.then(() => { .then(() => {
console.log("发送一个包完成了"); console.log("发送一个包完成了");
these.Status.Progress.curr = currentPacket;
updateLoading(these, {
text: "正在发送" + currentPacket + "/" +
totalPackets
})
currentPacket++; currentPacket++;
setTimeout(sendNextPacket, 100); setTimeout(sendNextPacket, 100);
}).catch(err => { }).catch(err => {
console.log("发送数据包失败了" + JSON.stringify(err)); console.log("发送数据包失败了", err);
// this.isSending = false;
these.Status.BottomMenu.show = false; these.Status.BottomMenu.show = false;
these.Status.Progress.show = false; these.showPop({
these.alert("发送数据包失败了"); message: "发送数据包失败了" + err.msg,
uni.hideLoading(); iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
hideLoading(these);
reject(err); reject(err);
}); });
} }
// 开始发送数据 // 开始发送数据
sendNextPacket(); sendNextPacket();
}
}); });
} }
@ -547,17 +559,15 @@
url: "/pages/6155/ImgCrop", url: "/pages/6155/ImgCrop",
events: { events: {
ImgCutOver: function(data) { ImgCutOver: function(data) {
console.log("我收到裁剪后的图片了,感谢老铁," + data)
uni.showLoading({ showLoading(these, {
title: "正在发送..." text: "正在发送0/52"
}); });
these.Status.Progress.show = true;
these.Status.Progress.curr = 0;
these.Status.Progress.total = 52;
these.Status.BottomMenu.show = false; these.Status.BottomMenu.show = false;
setTimeout(function() { setTimeout(function() {
processAndSendImageData(data).catch(() => { processAndSendImageData(data).catch((ex) => {
console.log("出现异常", ex);
}); });
}, 0) }, 0)
@ -585,7 +595,7 @@
}, },
ModeSetting: function(type) { ModeSetting: function(type) {
this.cEdit.mode = type; this.formData.mode = type;
let items = []; let items = [];
let title = ''; let title = '';
switch (type) { switch (type) {
@ -595,6 +605,10 @@
text: '强光', text: '强光',
icon: '/static/images/6155/DeviceDetail/qiang.png' icon: '/static/images/6155/DeviceDetail/qiang.png'
}, },
{
text: '工作光',
icon: '/static/images/6155/DeviceDetail/fan.png'
},
{ {
text: '弱光', text: '弱光',
icon: '/static/images/6155/DeviceDetail/ruo.png' icon: '/static/images/6155/DeviceDetail/ruo.png'
@ -602,6 +616,10 @@
{ {
text: '爆闪', text: '爆闪',
icon: '/static/images/6155/DeviceDetail/shan.png' icon: '/static/images/6155/DeviceDetail/shan.png'
},
{
text: '关闭',
icon: '/static/images/6155/DeviceDetail/close.png'
} }
]; ];
break; break;
@ -635,76 +653,90 @@
//发送指令给设备 //发送指令给设备
switch (this.Status.BottomMenu.type) { switch (this.Status.BottomMenu.type) {
case "main": case "main":
this.setMode(this.Status.BottomMenu.activeIndex); this.setMode(this.Status.BottomMenu.activeIndex, this.Status.BottomMenu.type);
break; break;
case "fu": case "fu":
this.setMode(this.Status.BottomMenu.activeIndex); this.setMode(this.Status.BottomMenu.activeIndex, this.Status.BottomMenu.type);
break; break;
} }
this.closeMenu(); this.closeMenu();
}, },
setMode(mode) { setMode(mode, type) {
let dataValue = 0;
this.setBleFormData();
if (type == 'main') {
type = 0x04;
} else if (type == 'fu') {
type = 0x05;
}
this.currentMode = mode; this.currentMode = mode;
let dataValue = 0;
switch (mode) { switch (mode) {
case 0: case 0:
dataValue = 0x01; dataValue = 0x01;
console.log('开始切换到弱光模式');
break; break;
case 1: case 1:
dataValue = 0x02;
console.log('开始切换到工作光模式');
break;
case 2:
dataValue = 0x03;
console.log('开始切换到强光模式');
break;
case 2:
dataValue = 0x04; dataValue = 0x04;
console.log('开始切换到爆闪模式'); break;
case 2:
dataValue = 0x02;
break;
case 3:
dataValue = 0x03;
break; break;
case 4: case 4:
dataValue = 0x00; // 爆关闭主灯光 dataValue = 0x00;
console.log('关闭主灯光');
break; break;
} }
// 构建数据包 // 构建数据包
const buffer = new ArrayBuffer(8); var buffer = new ArrayBuffer(6);
const dataView = new DataView(buffer); var dataView = new DataView(buffer);
dataView.setUint8(0, 0x4A); // 帧头 dataView.setUint8(0, 0xFA); // 帧头
dataView.setUint8(1, 0x51); dataView.setUint8(1, dataValue); // 帧类型
dataView.setUint8(2, 0x4F); dataView.setUint8(2, 0x00); // 数据
dataView.setUint8(3, 0x43); dataView.setUint8(3, 0x01); // 数据
dataView.setUint8(4, 0x00); // 数据
dataView.setUint8(5, 0xFF); // 数据
if (this.Status.BottomMenu.type == 'main') {
//主灯模式
dataView.setUint8(4, 0x04); // 帧类型
} else {
//副灯模式
dataView.setUint8(4, 0x05); // 帧类型
}
dataView.setUint8(5, dataValue); // 数据
dataView.setUint16(6, '9C41');
let f = this.getDevice(); let f = this.getDevice();
// 发送数据 // 发送数据
if(f){ if (!f) {
these.showPop({
message: "蓝牙未连接过该设备,请使用蓝牙重新添加该设备",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
return;
}
showLoading(these, {
text: "请稍候..."
});
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 30).then(() => { ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 30).then(() => {
}).catch((ex) => { }).catch((ex) => {
these.showPop({
message: "发送失败," + ex.msg,
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
}).finally(() => {
hideLoading(these);
}); });
}
@ -721,32 +753,71 @@
} }
this.Status.BottomMenu.activeIndex = index; this.Status.BottomMenu.activeIndex = index;
},
setBleFormData() {
ble.data.LinkedList.find((v) => {
if (v.deviceId == these.formData.deviceId) {
v.formData = these.formData;
return true;
}
return false;
});
uni.setStorage({
key: ble.StorageKey,
data: ble.data.LinkedList
})
}, },
HidePop: function() { HidePop: function() {
if (this.Status.Pop.clickEvt == 'SendUsr') { if (this.Status.Pop.clickEvt == 'SendUsr') {
} }
this.Status.Pop.showPop = false; this.Status.Pop.showPop = false;
}, },
async sendUsr(){ showPop: function(option) {
// this.alert(JSON.stringify(this.user)); if (!option) {
//生成位图并分包发送 //暂时弹出成功提示 option = {
var these = this; a: 1
};
}
let keys = Object.keys(option);
for (var i = 0; i < keys.length; i++) {
let key = keys[i];
these.Status.Pop[key] = option[key];
}
if (!option.borderColor) {
option.borderColor = '#BBE600';
option.buttonBgColor = '#BBE600';
}
these.Status.Pop.showPop = true;
},
sendUsr() {
let f = this.getDevice(); let f = this.getDevice();
if(!f){ if (!f) {
these.showPop({
text: "蓝牙未连接过该设备,请使用蓝牙重新添加该设备",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
return; return;
} }
showLoading(these, {
text: "请稍候..."
});
this.setBleFormData();
let task = async () => {
var sendTxtPackge = (rgbdata, type, str) => { var sendTxtPackge = (rgbdata, type, str) => {
var promise = new Promise((resolve, reject) => { var promise = new Promise((resolve, reject) => {
try { try {
let packetSize = 120; //每包均分的数量 let packetSize = rgbdata.length; //每包均分的数量
let mode = rgbdata.length % packetSize; //最后一包的数量 let mode = rgbdata.length % packetSize; //最后一包的数量
let cnt = parseInt(rgbdata.length / packetSize) + (mode > 0 ? 1 : 0); //总包数量 let cnt = parseInt(rgbdata.length / packetSize) + (mode > 0 ? 1 :
0); //总包数量
let curr = 1; //当前包序号 let curr = 1; //当前包序号
let sendNext = () => { let sendNext = () => {
@ -755,48 +826,50 @@
resolve(); resolve();
return; return;
} }
console.log("正在发送" + curr + "/" + cnt)
let bufferSize = 0;
if (curr == 1) {
bufferSize = packetSize * 2 + 5;
} else if (curr == cnt) {
bufferSize = mode > 0 ? (mode * 2) : (packetSize * 2);
} else {
bufferSize = packetSize * 2;
}
let bufferSize = 261;
console.log("bufferSize=", bufferSize)
let buffer = new ArrayBuffer(bufferSize); let buffer = new ArrayBuffer(bufferSize);
let dataView = new DataView(buffer); let dataView = new DataView(buffer);
let startIndex = (curr - 1) * packetSize; let startIndex = (curr - 1) * packetSize;
let endIndex = Math.min(startIndex + packetSize, rgbdata.length); let endIndex = Math.min(startIndex + packetSize, rgbdata
.length);
if (startIndex > endIndex) { if (startIndex > endIndex) {
return; return;
} }
let packetData = rgbdata.slice(startIndex, endIndex); //取一片数据发送 let packetData = rgbdata.slice(startIndex,
endIndex); //取一片数据发送
let start = 0; let start = 0;
if (curr == 1) { if (curr == 1) {
dataView.setUint8(0, 0x70); dataView.setUint8(0, 0xFA);
dataView.setUint8(1, 0x65); dataView.setUint8(1, type);
dataView.setUint8(2, type); dataView.setUint8(2, 0x01);
dataView.setUint16(3, str.length, false); dataView.setUint8(3, 0x00);
start = 5;
// dataView.setUint16(2, str.length, false);
start = 4;
} }
for (let i = 0; i < packetData.length; i++) { for (let i = 0; i < packetData.length; i++) {
dataView.setUint16(start + i * 2, packetData[i], false); // 大端字节序 dataView.setUint8(start + i, packetData[i]);
} }
dataView.setUint8(bufferSize - 1, 0xFF);
let inteval = parseInt(this.inteval ? this.inteval : 0); let inteval = parseInt(this.inteval ? this.inteval : 0);
//发送数据包 ble.sendData(f.deviceId, buffer, f.writeServiceId, f
ble.sendData(f.deviceId, buffer, f.writeServiceId, f.wirteCharactId, 30).then(() => { .wirteCharactId, 30).then(() => {
console.log("发送成功,准备发送下一包" + curr)
curr++; curr++;
setTimeout(sendNext, inteval); setTimeout(sendNext, inteval);
}).catch(err => { }).catch(err => {
console.log("出现错误", err)
if (err.code == '10007') { if (err.code == '10007') {
setTimeout(sendNext, inteval); setTimeout(sendNext, inteval);
} else { } else {
@ -808,7 +881,8 @@
sendNext(); sendNext();
} catch (ex) { } catch (ex) {
console.log("出现异常", ex) console.log("ex=", ex);
reject(ex); reject(ex);
} }
}); });
@ -816,48 +890,63 @@
return promise; return promise;
} }
var result = await this.$refs.textToHex.drawAndGetPixels(); var result = await this.$refs.textToHex.drawAndGetPixels();
result = result.map(level1 => {
return level1.flat(Infinity);
});
let h3dic = [0x06, 0x07, 0x08]; let h3dic = [0x06, 0x07, 0x08];
let pros = []; let pros = [];
let flag=true; let flag = true;
for (var i = 0; i < result.length; i++) { for (var i = 0; i < result.length; i++) {
let str = this.textLines[i]; let str = this.formData.textLines[i];
if (str.length > 0) { if (str.length > 0) {
let width = str.length * 16; let width = str.length * 16;
var rgb = ble.convertToRGB565(result[i].pixelData, width, 16); var rgb = result[i];
try{
try {
console.log("1111");
await sendTxtPackge(rgb, h3dic[i], str); await sendTxtPackge(rgb, h3dic[i], str);
}catch(ex){ console.log("222222");
flag=false; } catch (ex) {
flag = false;
console.log("33333");
break; break;
} }
} }
} }
if(flag){
uni.showModal({
title:"提示",
content:"发送成功"
}) hideLoading(these);
if (flag) {
}else{ console.log("发送成功");
uni.showModal({ this.showPop( {
title:"错误", message: "发送成功"
content:"出现了异常发送失败" });
}) } else {
this.showPop({
message: "出现异常发送失败",
iconUrl: "/static/images/6155/DeviceDetail/uploadErr.png",
borderColor: "#e034344d",
buttonBgColor: "#E03434",
});
}
} }
setTimeout(task, 0);
}, },
ack: function() { ack: function() {
var these = this;
let eventChannel = this.getOpenerEventChannel(); let eventChannel = this.getOpenerEventChannel();
eventChannel.emit('ack', { eventChannel.emit('ack', {
data: '我已收到了您的消息,谢谢。' data: '我已收到了您的消息,谢谢。'
@ -869,6 +958,7 @@
//给蓝牙设备发送信号更新亮度 //给蓝牙设备发送信号更新亮度
setTimeout(() => { setTimeout(() => {
this.sendBrightness(); this.sendBrightness();
this.setBleFormData();
}, 10); }, 10);
}, },
sendBrightness: function() { sendBrightness: function() {
@ -1217,10 +1307,10 @@
} }
.usrinfo .btnSend { .usrinfo .btnSend {
line-height: 40rpx; line-height: 65rpx;
border-radius: 8px; border-radius: 8px;
width: 82rpx; width: 120rpx;
height: 40rpx; height: 65rpx;
color: rgba(35, 35, 35, 0.87); color: rgba(35, 35, 35, 0.87);
font-family: "PingFang SC"; font-family: "PingFang SC";
font-size: 20rpx; font-size: 20rpx;
@ -1338,36 +1428,6 @@
} }
/* .custom-slider .uni-slider-handle-wrapper {
height: 60rpx !important;
border-radius: 3px;
}
.custom-slider .uni-slider-active {
background-color: #FF6B6B !important;
}
.custom-slider .uni-slider-handle {
width: 60rpx !important;
height: 60rpx !important;
border-radius: 16rpx !important;
background-color: #FFFFFFde !important;
margin-top: -15px !important;
border: none !important;
}
.custom-slider .uni-slider-thumb {
width: 60rpx !important;
height: 60rpx !important;
border-radius: 16rpx !important;
background-color: #00000000 !important;
border: none !important;
} */
.addIco { .addIco {
width: 100%; width: 100%;
height: 360rpx; height: 360rpx;

View File

@ -309,6 +309,7 @@
these.formData.deviceName = device.deviceName; these.formData.deviceName = device.deviceName;
these.formData.img = device.devicePic; these.formData.img = device.devicePic;
these.formData.id = device.id; these.formData.id = device.id;
these.formData.deviceId=f.deviceId;
ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId); ble.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId);
these.setBleFormData(); these.setBleFormData();
@ -321,9 +322,7 @@
}, },
onBackPress(e) { onBackPress(e) {
ble.removeReceiveCallback();
}, },
computed: { computed: {
RSSIRemark: function() { RSSIRemark: function() {
@ -488,7 +487,8 @@
}, },
getDevice: function() { getDevice: function() {
console.log("LinkedList=",ble.data.LinkedList);
console.log("formData=",these.formData);
let f = ble.data.LinkedList.find((v) => { let f = ble.data.LinkedList.find((v) => {
return v.deviceId == these.formData.deviceId; return v.deviceId == these.formData.deviceId;
}); });
@ -1112,6 +1112,10 @@
let key = keys[i]; let key = keys[i];
these.Status.Pop[key] = option[key]; these.Status.Pop[key] = option[key];
} }
if (!option.borderColor) {
option.borderColor = '#BBE600';
option.buttonBgColor = '#BBE600';
}
these.Status.Pop.showPop = true; these.Status.Pop.showPop = true;
}, },
sendUsr: function() { sendUsr: function() {
@ -1126,9 +1130,7 @@
]; ];
showLoading(this, {
text: "请稍候..."
});
let f = this.getDevice(); let f = this.getDevice();
if (!f) { if (!f) {
these.showPop({ these.showPop({
@ -1139,7 +1141,9 @@
}); });
return; return;
} }
showLoading(this, {
text: "请稍候..."
});
var sendText = function() { var sendText = function() {

View File

@ -19,13 +19,18 @@
连接 连接
</view> </view>
<global-loading ref="loading" />
</view> </view>
</template> </template>
<script> <script>
import request from '@/utils/request.js'; import request from '@/utils/request.js';
import bleTool from '@/utils/BleHelper.js' import bleTool from '@/utils/BleHelper.js'
import {
showLoading,
hideLoading,
updateLoading
} from '@/utils/loading.js'
var these = null; var these = null;
var eventChannel = null; var eventChannel = null;
var ble=null; var ble=null;
@ -110,9 +115,9 @@
} }
these.Statu.bound = null; these.Statu.bound = null;
these.Statu.boundRemark = ""; these.Statu.boundRemark = "";
uni.showLoading({ showLoading(these,{
mask: true,
title: "连接中..." text: "连接中..."
}) })
let promise = request({ let promise = request({
url: '/app/device/bind', url: '/app/device/bind',
@ -142,7 +147,7 @@
these.Statu.bound = false; these.Statu.bound = false;
these.Statu.boundRemark = '出现了未知的异常,操作失败'; these.Statu.boundRemark = '出现了未知的异常,操作失败';
}).finally(() => { }).finally(() => {
uni.hideLoading(); hideLoading(this);
}); });
} }
} }

View File

@ -81,12 +81,20 @@
</view> </view>
</view> </view>
</BottomSlideMenuPlus> </BottomSlideMenuPlus>
<global-loading ref="loading" />
</view> </view>
</template> </template>
<script> <script>
import bleTool from '@/utils/BleHelper.js'; import bleTool from '@/utils/BleHelper.js';
import request from '@/utils/request.js'; import request from '@/utils/request.js';
import {
showLoading,
hideLoading,
updateLoading
} from '@/utils/loading.js'
var ble = null; var ble = null;
var these = null; var these = null;
export default { export default {
@ -131,7 +139,8 @@
}, },
onBackPress: (e) => { onBackPress: (e) => {
ble.StopSearch(); ble.StopSearch();
ble.removeDeviceFound();
ble.removeReceiveCallback();
}, },
onLoad() { onLoad() {
these = this; these = this;
@ -142,6 +151,9 @@
for (var i = 0; i < arr.length; i++) { for (var i = 0; i < arr.length; i++) {
arr[i].linkStatu = false; arr[i].linkStatu = false;
if(!arr[i].name){
continue;
}
let f = these.EquipMents.find(function(v) { let f = these.EquipMents.find(function(v) {
return v.deviceId == arr[i].deviceId; return v.deviceId == arr[i].deviceId;
}); });
@ -229,9 +241,8 @@
}, },
Link: function(item, index) { Link: function(item, index) {
uni.showLoading({ showLoading(this,{
title: "正在连接", text: "正在连接"
mask: true
}); });
setTimeout(() => { setTimeout(() => {
let serviceid=null; let serviceid=null;
@ -262,7 +273,7 @@
content:"连接失败:"+ex.msg content:"连接失败:"+ex.msg
}); });
}).finally(()=>{ }).finally(()=>{
uni.hideLoading(); hideLoading(this);
}); });
}, 0); }, 0);

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -123,18 +123,18 @@ class BleHelper {
} }
const currentPage = pages[pages.length - 1]; const currentPage = pages[pages.length - 1];
console.log("currentPage=",currentPage.route); console.log("currentPage=", currentPage.route);
return currentPage.route; return currentPage.route;
} }
//设置发现新设备的回调 //设置发现新设备的回调
addDeviceFound(callback) { addDeviceFound(callback) {
let key = this.getCurrentPagePath(); let key = this.getCurrentPagePath();
if(!key){ if (!key) {
key=new Date().getTime(); key = new Date().getTime();
} }
if (key) { if (key) {
console.log("key="+key); console.log("key=" + key);
let f = this.cfg.onDeviceFound.findIndex((v) => { let f = this.cfg.onDeviceFound.findIndex((v) => {
return v.key == key; return v.key == key;
}); });
@ -154,16 +154,16 @@ class BleHelper {
let key = this.getCurrentPagePath(); let key = this.getCurrentPagePath();
if (key) { if (key) {
console.log("key="+key); console.log("key=" + key);
let f = this.cfg.onDeviceFound.findIndex((v) => { let f = this.cfg.onDeviceFound.findIndex((v) => {
return v.key == key; return v.key == key;
}); });
if (f > -1) { if (f > -1) {
this.cfg.onDeviceFound.splice(f, 1); this.cfg.onDeviceFound.splice(f, 1);
} }
}else{ } else {
if(this.cfg.onDeviceFound.length>0){ if (this.cfg.onDeviceFound.length > 0) {
this.cfg.onDeviceFound.splice(this.cfg.onDeviceFound.length-1, 1); this.cfg.onDeviceFound.splice(this.cfg.onDeviceFound.length - 1, 1);
} }
} }
@ -172,8 +172,8 @@ class BleHelper {
//添加接收到数据的回调 //添加接收到数据的回调
addReceiveCallback(callback) { addReceiveCallback(callback) {
let key = this.getCurrentPagePath(); let key = this.getCurrentPagePath();
if(!key){ if (!key) {
key=new Date().getTime(); key = new Date().getTime();
} }
if (key) { if (key) {
let f = this.cfg.receivDataCallback.findIndex((v) => { let f = this.cfg.receivDataCallback.findIndex((v) => {
@ -196,7 +196,7 @@ class BleHelper {
removeReceiveCallback(ev) { removeReceiveCallback(ev) {
let key = this.getCurrentPagePath(); let key = this.getCurrentPagePath();
if (key) { if (key) {
console.log("key="+key); console.log("key=" + key);
let f = this.cfg.receivDataCallback.findIndex((v) => { let f = this.cfg.receivDataCallback.findIndex((v) => {
return v.key == key; return v.key == key;
}); });
@ -205,9 +205,9 @@ class BleHelper {
this.cfg.receivDataCallback.splice(f, 1); this.cfg.receivDataCallback.splice(f, 1);
} }
}else{ } else {
if(this.cfg.receivDataCallback.length>0){ if (this.cfg.receivDataCallback.length > 0) {
this.cfg.receivDataCallback.splice(this.cfg.receivDataCallback.length-1, 1); this.cfg.receivDataCallback.splice(this.cfg.receivDataCallback.length - 1, 1);
} }
} }
} }
@ -445,12 +445,14 @@ class BleHelper {
// 将每个字节转换为对应的字符 // 将每个字节转换为对应的字符
str += String.fromCharCode(uint8Array[i]); str += String.fromCharCode(uint8Array[i]);
} }
let header="mac address:"; let header = "mac address:";
if (str.indexOf(header) == 0) { if (str.indexOf(header) == 0) { //650以文本传输mac
this.data.LinkedList.find((v) => { this.data.LinkedList.find((v) => {
if (v.deviceId == receive.deviceId) { if (v.deviceId == receive
v.macAddress = str.replace(header,""); .deviceId) {
v.macAddress = str.replace(
header, "");
console.log("收到mac地址:", str) console.log("收到mac地址:", str)
} }
}); });
@ -458,7 +460,20 @@ class BleHelper {
.LinkedList); .LinkedList);
} }
if (bytes[0] == 0xFC) { //6155以0xFC开头代表mac地址
if (arr.length >= 7) {
let mac = arr.slice(1, 7).join(":");
this.data.LinkedList.find((v) => {
if (v.deviceId == receive
.deviceId) {
v.macAddress = mac;
console.log("收到mac地址:", str)
}
});
uni.setStorageSync(this.StorageKey, this
.data.LinkedList);
}
}
} catch (ex) { } catch (ex) {
////console.log("将数据转文本失败", ex); ////console.log("将数据转文本失败", ex);
} }
@ -546,7 +561,7 @@ class BleHelper {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.startBluetoothDevicesDiscovery({ uni.startBluetoothDevicesDiscovery({
services: [], services: [],
allowDuplicatesKey: false, allowDuplicatesKey: true,
success: (res) => { success: (res) => {
//console.log('开始搜索蓝牙设备成功'); //console.log('开始搜索蓝牙设备成功');
resolve(res); resolve(res);
@ -629,8 +644,7 @@ class BleHelper {
} }
console.log("c=", c); console.log("c=", c);
let startSubScribe = (id, serviceId, characteristicId) => { let startSubScribe = (id, serviceId, characteristicId) => {
console.log("id, serviceId, characteristicId=" + id + "," + serviceId +
"," + characteristicId);
return new Promise((succ, err) => { return new Promise((succ, err) => {
uni.notifyBLECharacteristicValueChange({ uni.notifyBLECharacteristicValueChange({
deviceId: id, deviceId: id,
@ -652,10 +666,7 @@ class BleHelper {
succ(); succ();
}, },
fail: (ex) => { fail: (ex) => {
console.log("deviceId=", id);
console.log("serviceId=", serviceId);
console.log("characteristicId=",
characteristicId);
err(this.getError(ex)); err(this.getError(ex));
} }
}); });
@ -676,10 +687,10 @@ class BleHelper {
results.forEach((result, index) => { results.forEach((result, index) => {
if (result.status === "fulfilled") { if (result.status === "fulfilled") {
console.log(`操作${index + 1}成功:`, result.value); //console.log(`操作${index + 1}成功:`, result.value);
} else { } else {
console.log(`操作${index + 1}失败:`, result.reason // console.log(`操作${index + 1}失败:`, result.reason
.message); // .message);
} }
}); });
@ -752,7 +763,7 @@ class BleHelper {
return this.subScribe(id, true); return this.subScribe(id, true);
}) })
.then((res) => { .then((res) => {
console.log('所有操作成功完成', res); console.log('设备连接成功,初始化完成', res);
console.log("LinkedList=", this.data console.log("LinkedList=", this.data
.LinkedList); .LinkedList);
resolve(); resolve();
@ -975,7 +986,7 @@ class BleHelper {
}).then((res) => { }).then((res) => {
////console.log("11111111"); ////console.log("11111111");
if (res) { //新连接 if (res) { //新连接
console.log("开始获取服务",targetServiceId) console.log("开始获取服务", targetServiceId)
return this.getService(deviceId, targetServiceId, writeCharId, return this.getService(deviceId, targetServiceId, writeCharId,
notifyCharId); //获取服务 notifyCharId); //获取服务
} else { //已连接过,直接订阅消息 } else { //已连接过,直接订阅消息
@ -989,9 +1000,9 @@ class BleHelper {
}).then(() => { }).then(() => {
setTimeout(()=>{ setTimeout(() => {
resolve(); resolve();
},500); }, 500);
}).catch((ex) => { }).catch((ex) => {
////console.log("出现异常", ex); ////console.log("出现异常", ex);
reject(ex); reject(ex);
@ -1102,7 +1113,7 @@ class BleHelper {
})); //没有找到指定设备 })); //没有找到指定设备
return; return;
} }
console.log("device=",device); console.log("device=", device);
uni.writeBLECharacteristicValue({ uni.writeBLECharacteristicValue({
deviceId: device.deviceId, deviceId: device.deviceId,
serviceId: device.writeServiceId, serviceId: device.writeServiceId,
@ -1156,14 +1167,18 @@ class BleHelper {
} else { } else {
// console.log("先连接蓝牙再发送"); // console.log("先连接蓝牙再发送");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let f=this.data.LinkedList.find((v)=>{ let f = this.data.LinkedList.find((v) => {
return v.deviceId==deviceid; return v.deviceId == deviceid;
});
if (!f) {
reject({
code: '-9',
msg: '蓝牙未连接过此设备,请重新使用蓝牙添加该设备'
}); });
if(!f){
reject({code:'-9',msg:'蓝牙未连接过此设备,请重新使用蓝牙添加该设备'});
retrn; retrn;
} }
this.LinkBlue(f.deviceId,f.writeServiceId,f.wirteCharactId,f.notifyCharactId).then((res) => { this.LinkBlue(f.deviceId, f.writeServiceId, f.wirteCharactId, f.notifyCharactId).then((
res) => {
console.log("连接成功"); console.log("连接成功");
return sendBuffer(); return sendBuffer();
}).then(() => { }).then(() => {

View File

@ -9,7 +9,14 @@ export const showLoading = (ev,options) => {
if(!options){ if(!options){
options={a:1}; options={a:1};
} }
ev.$refs.loading.show(options) if(!options.text && options.title){
options.text=options.title;
}
if(!options.text){
options.text="请稍候...";
}
ev.$refs.loading.show(options);
} }