From d1dbf4aa04b7ef6208b13d408aa5fadbb96904a1 Mon Sep 17 00:00:00 2001
From: chenJinxu <2183691628@qq.com>
Date: Tue, 4 Jun 2024 11:32:53 +0800
Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20=E8=93=9D=E7=89=99?=
=?UTF-8?q?=E8=B0=83=E8=AF=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
miniprogram/model/index.js | 117 ++++-
miniprogram/pages/bluetooth/bluetooth.js | 6 +-
miniprogram/pages/devicedetail/index.js | 546 +++++++++++++++++-----
miniprogram/pages/devicedetail/index.wxml | 10 +-
project.private.config.json | 27 +-
5 files changed, 568 insertions(+), 138 deletions(-)
diff --git a/miniprogram/model/index.js b/miniprogram/model/index.js
index cee34f3..d9dc8f7 100644
--- a/miniprogram/model/index.js
+++ b/miniprogram/model/index.js
@@ -4,40 +4,104 @@ export const CommandButtonList = {
// 下发
send: [
// 2.2.1.读取工作强度映射表(0x0101)
- {name:'读取工作强度映射表', enName: 'readWorkIntensityMapping', defaultSendData: 'FE0007010100FF'},
+ {id: '01', name:'读取工作强度映射表', enName: 'readWorkIntensityMapping', defaultSendData: /* '\xFE\x00\x07\x01\x01\x00\xFF' */'FE0007010100FF',
+ response: 'FE000881016F6BFF',
+ // 注意中间数据自行组装
+ concat: {
+ head: 'FE',
+ len: '0007',
+ command: '0101',
+ foot: 'FF'
+ }
+ },
// 2.2.2.设置设备工作强度映射表(0x0102)
- {name:'设置工作强度映射表', enName: 'sendWorkIntensityMapping', defaultSendData: 'FE000701027FF'},
+ {id: '02',name:'设置工作强度映射表', enName: 'sendWorkIntensityMapping', defaultSendData: 'FE0007010203070a0d111416191b1eFF',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '0102',
+ foot: 'FF'
+ }},
// 2.2.3.读取设备工作强度(0x0103)
- {name:'读取设备工作强度', enName: 'readWorkIntensity', defaultSendData: 'FE0007010300FF'},
+ {id: '03',name:'读取设备工作强度', enName: 'readWorkIntensity', defaultSendData: 'FE0007010300FF',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '0103',
+ foot: 'FF'
+ }},
// 2.2.4.设置设备工作强度(0x0104)
- {name:'设置设备工作强度', enName: 'sendWorkIntensity', defaultSendData: 'FE000E01040102FF'},
+ {id: '04',name:'设置设备工作强度', enName: 'sendWorkIntensity', defaultSendData: 'FE000E01040102FF',concat: {
+ head: 'FE',
+ len: '000E',
+ command: '0104',
+ foot: 'FF'
+ }},
// 2.2.5.读取设备工作流程(0x0105)
- {name:'读取设备工作流程', enName: 'readWorkProcess', defaultSendData: 'FE0007010500FF'},
+ {id: '05',name:'读取设备工作流程', enName: 'readWorkProcess', defaultSendData: 'FE0007010500FF',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '0105',
+ foot: 'FF'
+ }},
// 2.2.6.设置设备工作流程(0x0106)
- // {name:'设置设备工作流程', enName: 'sendWorkProcess', defaultSendData: 'FE00XX0016FF'},
+ {id: '06',name:'设置设备工作流程', enName: 'sendWorkProcess', defaultSendData: 'FE00XX0016FF',concat: {
+ head: 'FE',
+ len: '00XX',
+ command: '0106',
+ foot: 'FF'
+ }},
// 2.2.7.设备启动工作(0x0107)
- {name:'设备启动工作', enName: 'deviceStartWork', defaultSendData: 'FE00070107000000010060FF'},
+ {id: '07',name:'设备启动工作', enName: 'deviceStartWork', defaultSendData: 'FE00070107000000010060FF',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '0107',
+ foot: 'FF'
+ }},
// 2.2.8设备停止工作(0x0108)
- {name:'设备停止工作', enName: 'deviceStopWork', defaultSendData: 'FE0007010800000001FF'},
+ {id: '08',name:'设备停止工作', enName: 'deviceStopWork', defaultSendData: 'FE0007010800000001FF',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '0108',
+ foot: 'FF'
+ }},
// 2.2.9设备暂停工作(0x0109)
- {name:'设备暂停工作', enName: 'devicePauseWork', defaultSendData: 'FE0007010900000001FF'},
+ {id: '09',name:'设备暂停工作', enName: 'devicePauseWork', defaultSendData: 'FE0007010900000001FF',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '0109',
+ foot: 'FF'
+ }},
//2.2.10设备恢复工作(0x010A)
- {name:'设备恢复工作', enName: 'deviceResumeWork', defaultSendData: 'FE0007010A00000001FF'},
+ {id: '10',name:'设备恢复工作', enName: 'deviceResumeWork', defaultSendData: 'FE0007010A00000001FF',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '010A',
+ foot: 'FF'
+ }},
//2.2.11设置设备时钟(0x010B)
- {name:'设置设备时钟', enName: 'sendDeviceClock', defaultSendData: ''},
+ {id: '11',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '010B',
+ foot: 'FF'
+ },name:'设置设备时钟', enName: 'sendDeviceClock', defaultSendData: '',},
//2.2.12设备恢复出厂设置(0x010C)
- {name:'设备恢复出厂设置', enName: 'deviceReset', defaultSendData: 'FE0007010C00FF'},
+ {id: '12',name:'设备恢复出厂设置', enName: 'deviceReset', defaultSendData: 'FE0007010C00FF',concat: {
+ head: 'FE',
+ len: '0007',
+ command: '010C',
+ foot: 'FF'
+ }},
@@ -46,6 +110,35 @@ export const CommandButtonList = {
],
// 上报,解析
report: [
+ // 设备上报版本号(0x0001)
+ {cnName: '设备版本号', enName: 'deviceVersion', keyWord: '0001',response: 'FE000880016F6BFF'},
+
+ // 设备上报电池电量(0x0002)
+ {cnName: '设备电池电量', enName: 'deviceBattery', keyWord: '0002',response: 'FE000880026F6BFF'},
+
+ // 设备上报充电状态(0x0003)
+ {cnName: '设备充电状态', enName: 'deviceChargeState', keyWord: '0003',response: 'FE000880036F6BFF'},
+
+
+ // 设备上报极片工作状态(0x0004)
+ {cnName: '设备极片工作状态', enName: 'devicePoleWorkState', keyWord: '0004',response: 'FE000880046F6BFF'},
+
+
+ // 设备上报运行工作状态(0x0005)
+ {cnName: '设备运行工作状态', enName: 'deviceWorkState', keyWord: '0005',response: 'FE000880056F6BFF'},
+
+ // 设备上报异常(0x0006)
+ {cnName: '设备异常', enName: 'deviceError', keyWord: '0006',response: 'FE000880066F6BFF'},
+
+
+ // 设备上报工作开始(0x0007)
+ {cnName: '设备上报工作开始', enName: 'deviceWorkStart', keyWord: '0007',response: 'FE000880076F6BFF'},
+
+ // 设备上报工作结束(0x0008)
+ {cnName: '设备上报工作结束', enName: 'deviceWorkEnd', keyWord: '0008',response: 'FE000880086F6BFF'},
+
+ // 设备上报工作结果(0x0009)
+ {cnName: '设备上报工作结果', enName: 'deviceWorkResult', keyWord: '0009',response: 'FE000880096F6BFF'},
]
};
\ No newline at end of file
diff --git a/miniprogram/pages/bluetooth/bluetooth.js b/miniprogram/pages/bluetooth/bluetooth.js
index 627b157..8458670 100644
--- a/miniprogram/pages/bluetooth/bluetooth.js
+++ b/miniprogram/pages/bluetooth/bluetooth.js
@@ -75,7 +75,7 @@ Page({
title: '搜索中',
})
wx.startBluetoothDevicesDiscovery({
- services: [], // 可指定服务UUID筛选要搜索的设备
+ services: ['0000FEFF-0000-1000-8000-00805F9B34FB'], // 可指定服务UUID筛选要搜索的设备
success: function (res) {
if (res.errno === 0) {
console.log('蓝牙设备搜索成功');
@@ -93,7 +93,9 @@ Page({
icon: 'success'
})
that.setData({
- deviceslist: resu.devices
+ deviceslist: resu.devices.filter(item => {
+ return item.connectable
+ })
});
// 此时再监听搜索到新设备的事件
wx.onBluetoothDeviceFound(function(res) {
diff --git a/miniprogram/pages/devicedetail/index.js b/miniprogram/pages/devicedetail/index.js
index ff0bd0c..e235713 100644
--- a/miniprogram/pages/devicedetail/index.js
+++ b/miniprogram/pages/devicedetail/index.js
@@ -1,6 +1,8 @@
// 示例demo
const plugin = requirePlugin('ppScale-plugin');
-import { CommandButtonList } from '../../model/index'
+import {
+ CommandButtonList
+} from '../../model/index'
let app = getApp();
Page({
data: {
@@ -27,8 +29,21 @@ Page({
callBack: null,
// 蓝牙设备下发指令按钮数据
sendBtnList: CommandButtonList.send, //版本号
+ // 上报数据类型数组:
+ reportData: CommandButtonList.report,
// 手动输入文本域的值
inputValue: '',
+ deviceInfo: {
+ version: '',
+ battery:'',
+ chargeState: '',
+ poleWorkState: '',
+ workState: '',
+ error: '',
+ workStart: '',
+ workEnd: '',
+ workResult: '',
+ }
},
@@ -38,7 +53,8 @@ Page({
*/
onUnload() {
// 业务结束后需要调用此方法
-
+ wx.offBluetoothAdapterStateChange();
+ wx.closeBluetoothAdapte();
},
/**
@@ -61,7 +77,8 @@ Page({
})
wx.showToast({
title: '蓝牙已断开',
- })
+ });
+ that.connect();
/* setTimeout(() => {
that.initBlue();
}, 1500) */
@@ -70,6 +87,42 @@ Page({
that.setData({
devLink: true,
})
+ setTimeout(() => {
+ // 获取蓝牙低功耗设备所有服务 (service)
+ wx.getBLEDeviceServices({
+ deviceId: app.globalData.selmac.deviceId,
+ success: (res) => {
+ console.log("获取蓝牙低功耗设备所有服务成功", res);
+ let serviceId = '0000FFF0-0000-1000-8000-00805F9B34FB'
+ console.log("获取到的serviceId::", serviceId);
+ // 缓存数据 serviceId
+ app.globalData.serviceId = serviceId;
+
+ //获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
+ wx.getBLEDeviceCharacteristics({
+ deviceId: app.globalData.selmac.deviceId,
+ serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
+ success: (res) => {
+ console.log("获取蓝牙低功耗设备某个服务中所有特征", res);
+ let characteristicId = res.characteristics[0].uuid;
+ // 缓存数据 characteristicId
+ app.globalData.characteristicId = characteristicId;
+ that.notify();
+ },
+ fail: (e) => {
+ console.log("获取蓝牙低功耗设备某个服务中所有特征", e);
+ }
+ })
+ },
+ fail: (e) => {
+ console.log("获取蓝牙低功耗设备所有服务失败", e);
+ }
+ })
+
+
+
+
+ }, 800)
}
})
},
@@ -88,71 +141,81 @@ Page({
that.setData({
devLink: true
})
+
+ // setTimeout(() => {
+ // // 获取蓝牙低功耗设备所有服务 (service)
+ // wx.getBLEDeviceServices({
+ // deviceId: app.globalData.selmac.deviceId,
+ // success: (res) => {
+ // console.log("获取蓝牙低功耗设备所有服务成功", res);
+ // let serviceId = res.services.filter(item => {
+ // return item.uuid === '0000FEFF-0000-1000-8000-00805F9B34FB'
+ // })[0];
+ // // 缓存数据 serviceId
+ // app.globalData.serviceId = serviceId;
+
+ // //获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
+ // wx.getBLEDeviceCharacteristics({
+ // deviceId: app.globalData.selmac.deviceId,
+ // serviceId: serviceId,
+ // success: (res) => {
+ // console.log("获取蓝牙低功耗设备某个服务中所有特征", res);
+ // let characteristicId = res.characteristics[0].uuid;
+ // // 缓存数据 characteristicId
+ // app.globalData.characteristicId = characteristicId;
+ // },
+ // fail: (e) => {
+ // console.log("获取蓝牙低功耗设备某个服务中所有特征", e);
+ // }
+ // })
+ // },
+ // fail: (e) => {
+ // console.log("获取蓝牙低功耗设备所有服务失败", e);
+ // }
+ // })
+
+
+
+
+ // }, 1500)
+
},
fail: (e) => {
console.log("连接失败", e);
}
})
+ //this.listenValueChange()
- setTimeout(() => {
- // 获取蓝牙低功耗设备所有服务 (service)
- wx.getBLEDeviceServices({
- deviceId: app.globalData.selmac.deviceId,
- success: (res) => {
- console.log("获取蓝牙低功耗设备所有服务成功", res);
- let serviceId = res.services[0].uuid;
- // 缓存数据 serviceId
- app.globalData.serviceId = serviceId;
-
- //获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
- wx.getBLEDeviceCharacteristics({
- deviceId: app.globalData.selmac.deviceId,
- serviceId: serviceId,
- success: (res) => {
- console.log("获取蓝牙低功耗设备某个服务中所有特征", res);
- let characteristicId = res.characteristics[0].uuid;
- // 缓存数据 characteristicId
- app.globalData.characteristicId = characteristicId;
- },
- fail: (e) => {
- console.log("获取蓝牙低功耗设备某个服务中所有特征", e);
- }
- })
- },
- fail: (e) => {
- console.log("获取蓝牙低功耗设备所有服务失败", e);
- }
- })
-
-
- }, 1500)
-
},
connect() {
let that = this;
if (this.data.selmac.deviceId) {
- console.log("可以初始化");
- wx.openBluetoothAdapter({
- mode: 'peripheral',
- })
- // 连接设备
- wx.createBLEConnection({
- deviceId: that.data.selmac.deviceId,
- success: (res) => {
- console.log("建立连接成功", res);
- },
- fail: (e) => {
- console.log("建立连接失败", e);
- wx.showToast({
- title: '重新连接失败',
- icon: 'error'
- })
- }
- })
+ console.log("可以重新初始化蓝牙");
+ if(!this.data.devLink) {
+ // 如果已经断开,则重新初始化蓝牙
+ wx.openBluetoothAdapter({
+ mode: 'peripheral',
+ })
+ // 连接设备
+ wx.createBLEConnection({
+ deviceId: that.data.selmac.deviceId,
+ success: (res) => {
+ console.log("建立连接成功", res);
+ },
+ fail: (e) => {
+ console.log("建立连接失败", e);
+ wx.showToast({
+ title: '重新连接失败',
+ icon: 'error'
+ })
+ }
+ })
+ }
+
}
},
disconnect() {
@@ -179,24 +242,57 @@ Page({
},
startwrite() {
// 下发指令
- let text = this.cleanHexString('hello');
- let buffer = this.stringToCmdBuffer(text);
+ /* let text = this.cleanHexString('FE0007010100FF');
+
+
+ let string = this.hexCharCodeToStr(hexData); */
+ let testdata = new Uint16Array([...'FE0007010100FF'].map(v => v.codePointAt(0)));
+ console.log("testdata", testdata);
+ let strToHexCharCode = this.hexToByteString('FE0007010100FF');
+ let buffer = this.hexStringToArrayBuffer(strToHexCharCode);
let hexData = this.ab2hex(buffer);
- let string = this.hexCharCodeToStr(hexData);
- console.log("十六进制字符串转buffer", buffer);
+
+ console.log("十六进制转成二进制", strToHexCharCode);
+ console.log("二进制字符串转buffer", buffer);
console.log("buffer转hexData", hexData);
+ /* console.log("buffer转hexData", hexData);
console.log("hexData转string", string);
- this.sendMessage(text);
+ console.log("text", text); */
+ //this.sendMessage(text);
},
+ hexStringToArrayBuffer(hexStr) {
+ // 移除前缀并确保字符串长度为偶数
+ hexStr = hexStr.replace(/\\x/g, '').replace(/^0+/, '');
+
+ // 确保字符串长度是偶数,如果不是,前面补0
+ if (hexStr.length % 2 !== 0) {
+ hexStr = '0' + hexStr;
+ }
+
+ // 将每两个字符视为一个十六进制数,转换为字节数组
+ const bytes = new Uint8Array(hexStr.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
+
+ // 从Uint8Array创建ArrayBuffer
+ return bytes.buffer;
+ },
bindTextAreaBlur(e) {
this.data.inputValue = e.detail.value;
console.log(e.detail.value)
},
+ // 十六进制转成二进制
+ hexToByteString(hexString) {
+ let bytes = [];
+ for (let i = 0; i < hexString.length; i += 2) {
+ bytes.push("\\x" + hexString.substr(i, 2));
+ }
+ return bytes.join('');
+ },
+
// 手动输入文本域的值
onInputSend() {
console.log("this.data.inputValue", this.data.inputValue);
- if(this.data.inputValue) {
+ if (this.data.inputValue) {
this.sendMessage(this.data.inputValue, true);
} else {
wx.showToast({
@@ -206,27 +302,27 @@ Page({
}
},
// 发送数据
- sendMessage(event,type) {
+ sendMessage(event, type) {
let that = this;
let sendData = '';
- if(type) {
+ if (type) {
console.log("手动输出方式");
sendData = event
} else {
console.log("按钮点击输出方式");
- console.log("event", event.target.dataset);
+ console.log("指令名称::", event.target.dataset.command.name);
sendData = event.target.dataset.command.defaultSendData;
}
-
- if(!that.data.devLink) {
+
+ if (!that.data.devLink) {
wx.showToast({
title: '蓝牙已断开',
icon: 'error'
})
return
}
-
- if(!sendData) {
+
+ if (!sendData) {
wx.showToast({
title: '指令不存在',
icon: 'error'
@@ -236,16 +332,25 @@ Page({
this.setData({
sendData: sendData
})
- let buffer = this.stringToCmdBuffer(sendData);
- console.log("发送的指令",buffer);
+ /* let strToHexCharCode = this.hexToByteString('FE0007010100FF'); */
+ /* let strToHexCharCode = this.hexToByteString(sendData); */
+ console.log("未转换前的十六进制数据::", sendData)
+ let strToHexCharCode = this.hexToByteString(sendData);
+ console.log("十六进制转成二进制的数据::", strToHexCharCode);
+ let buffer = this.hexStringToArrayBuffer(strToHexCharCode);
+ console.log("二进制转成arrayBuffter的数据::", buffer);
+ console.log("特征值::", 'E4BAA7E5-908E-E5A1-91E5-BDA2E4BBAA02');
+
+
+ console.log("buffer", buffer);
wx.writeBLECharacteristicValue({
deviceId: app.globalData.selmac.deviceId, // 设备ID
- serviceId: app.globalData.selmac.serviceId, // 服务UUID
- characteristicId: app.globalData.selmac.characteristicId, // 特征值
+ serviceId: /* app.globalData.serviceId */ '0000FFF0-0000-1000-8000-00805F9B34FB', // 服务UUID
+ characteristicId: /* app.globalData.characteristicId */ 'E4BAA7E5-908E-E5A1-91E5-BDA2E4BBAA02', // 特征值
value: buffer,
success(res) {
console.log("write指令发送成功", res)
- that.notify();
+
},
fail(err) {
console.log("write指令发送失败", err);
@@ -256,86 +361,283 @@ Page({
title: '指令发送失败',
icon: 'error'
})
-
+
}
})
},
+ string2Hex(str) {
+ let val = ""
+ for (let i = 0; i < str.length; i++) {
+ if (val == "")
+ val = str.charCodeAt(i).toString(16)
+ else
+ val += str.charCodeAt(i).toString(16)
+ }
+ return val
+ },
+ hex2ArrayBuffer(hex_str) {
+ // let hex_str = 'AA5504B10000B5'
+ let typedArray = new Uint8Array(hex_str.match(/[\da-f]{2}/gi).map(function (h) {
+ return parseInt(h, 16)
+ }))
+ let buffer = typedArray.buffer
+ return buffer
+ },
cleanHexString(hexStr) {
// 使用正则表达式匹配并移除多余的'0x',并拼接剩下的部分
let cleanedHex = hexStr.replace(/0x/g, '').replace(/\b0+/g, ''); // 第二个正则表达式用于移除前导零
return cleanedHex;
},
- // 开启消息监听
-notify() {
- let that = this;
- wx.notifyBLECharacteristicValueChange({
+
+ // 开启读取蓝牙低功耗设备特征值的二进制数据
+ read() {
+ let that = this;
+ let text = 'fe000f000176657220312e302e31ff'
+ let string = that.hexCharCodeToStr(text);
+ console.log("测试", string);
+ /* wx.readBLECharacteristicValue({
deviceId: app.globalData.selmac.deviceId, // 设备ID,
- serviceId: app.globalData.selmac.serviceId, // 服务UUID
- characteristicId: app.globalData.selmac.characteristicId, // 特征值
+ serviceId: app.globalData.serviceId, // 服务UUID
+ characteristicId: app.globalData.characteristicId, // 特征值
+ success (res) {
+ console.log('readBLECharacteristicValue:', res);
+ }
+ }) */
+ },
+ // 根据type,向设备写入十六进制数据,
+ write(data, type) {
+ let that = this;
+ let characteristicId = type === 'read' ? 'E4BAA7E5-908E-E5A1-91E5-BDA2E4BBAA01' : 'E4BAA7E5-908E-E5A1-91E5-BDA2E4BBAA02';
+ console.log("监听到设备有数据上报,回应设备");
+ console.log("未转换前的十六进制数据::", data)
+ let strToHexCharCode = this.hexToByteString(data);
+ console.log("十六进制转成二进制的数据::", strToHexCharCode);
+ let buffer = this.hexStringToArrayBuffer(strToHexCharCode);
+ console.log("二进制转成arrayBuffter的数据::", buffer);
+ console.log("特征值::", characteristicId);
+ wx.writeBLECharacteristicValue({
+ deviceId: app.globalData.selmac.deviceId, // 设备ID
+ serviceId: /* app.globalData.serviceId */ '0000FFF0-0000-1000-8000-00805F9B34FB', // 服务UUID
+ characteristicId: characteristicId, // 特征值
+ value: buffer,
success(res) {
- console.log(res)
-
- // 监听消息变化的方法
- that.listenValueChange()
+ console.log("write指令发送成功", res)
+ //that.read();
+
},
fail(err) {
- console.error(err)
+ console.log("write指令发送失败", err);
+ that.setData({
+ callBack: err.errMsg
+ });
+ wx.showToast({
+ title: '指令发送失败',
+ icon: 'error'
+ })
+
+ }
+ })
+ },
+ // 将一个字符串截取前面多少位,后面多少位,返回中间值
+ extractMiddleData(encodedStr, startNum, endNum) {
+ // 前面截取10位
+ const start = encodedStr.substring(0, startNum);
+ // 后面截取2位
+ const end = encodedStr.substring(encodedStr.length - endNum);
+ // 计算中间部分的起始索引
+ const middleStartIndex = start.length;
+ // 总长度减去前后部分的长度得到中间部分的长度
+ const middleLength = encodedStr.length - middleStartIndex - end.length;
+ // 提取中间部分
+ const middlePart = encodedStr.substring(middleStartIndex, middleStartIndex + middleLength);
+ return middlePart;
+ },
+ // 开启设备通知消息监听
+ notify() {
+ let that = this;
+ wx.notifyBLECharacteristicValueChange({
+ deviceId: app.globalData.selmac.deviceId, // 设备ID,
+ serviceId: app.globalData.serviceId, // 服务UUID
+ characteristicId: app.globalData.characteristicId, // 特征值
+ state: true,
+ success(res) {
+ console.log("开启消息监听", res)
+ // 监听消息变化的方法
+ that.listenValueChange()
+
+
+ },
+ fail(err) {
+ console.error("消息监听失败", err)
}
- })
-},
+ })
+ },
// 消息变化
-listenValueChange() {
- let that = this;
- wx.onBLECharacteristicValueChange(res => {
- console.log(res)
- let resHex = that.ab2hex(res.value)
- console.log("resHex", resHex)
- let result = that.hexCharCodeToStr(resHex)
- console.log("消息变化", String(result))
+ listenValueChange() {
+ let that = this;
+ let result = "";
+ wx.onBLECharacteristicValueChange(res => {
+ console.log("设备响应", res)
+ console.log("设备上报的数据", res.value);
+ // ArrayBuffer转16进制字符串
+ let resHex = that.ab2hex(res.value);
+ console.log("设备上报的16进制字符串", resHex);
+ // 从第六位开始截取,截取10位,拿关键的数据识别上报数据类型
+ let sliceData = resHex.slice(6, 10);
+ // 通过截取的到数据区分是下发后上报还是自动上报的数据
+ console.log("截取到上报数据的关键指令", sliceData);
+ //console.log("ArrayBuffer转16进制字符串", resHex)
+ result = that.extractMiddleData(resHex, 10, 2);
+ console.log("上报截取关键内容::", result);
+ let isAuto = that.data.reportData.findIndex(item => {
+ return item.keyWord === sliceData;
+ })
+ if (isAuto > -1) {
+ // 证明是自动上报的数据,否则不是
+ let report = that.data.reportData.filter(item => {
+ return item.keyWord === sliceData
+ });
+ console.log("上报的数据类型:", report[0].cnName);
+ // 16进制字符串转字符串,根据情况,有些上报数据需要转字符串,有些则不需要
+ if (report[0].keyWord === '0001') {
+ that.setData({
+ ['deviceInfo.version']: that.hexCharCodeToStr(result)
+ })
+ } else if (report[0].keyWord === '0002') {
+ // 电池电量
+ that.setData({
+ ['deviceInfo.battery']: result
+ })
+ }else if (report[0].keyWord === '0003') {
+ // 充电状态
+ that.setData({
+ ['deviceInfo.chargeState']: result === '01' ? '以充电' : '未充电'
+ })
+ } else if (report[0].keyWord === '0004') {
+ // 极片工作状态
+ that.setData({
+ ['deviceInfo.poleWorkState']: result
+ })
+ }else if (report[0].keyWord === '0005') {
+ // 运行工作状态
+ that.setData({
+ ['deviceInfo.workState']: result
+ })
+ }else if (report[0].keyWord === '0006') {
+ // 上报异常
+ that.setData({
+ ['deviceInfo.error']: result
+ })
+ }else if (report[0].keyWord === '0007') {
+ // 上报工作开始
+ that.setData({
+ ['deviceInfo.workStart']: result
+ })
+ }else if (report[0].keyWord === '0008') {
+ // 上报工作结束
+ that.setData({
+ ['deviceInfo.workEnd']: result
+ })
+ }else if (report[0].keyWord === '0009') {
+ // 上报工作结果
+ that.setData({
+ ['deviceInfo.workResult']: result
+ })
+ }else {
+ }
+ // 返回结果后向设备回应
+ that.write(report[0].response, 'write');
+ } else {
+ // 是下发上报的
+ // 返回结果后向设备回应
+ /* that.write(report[0].response, 'write'); */
+ console.log("下发上报");
+ // 根据上报截取的数据解析下发上报的数据
+ if(sliceData === '8101'){
+ // 读取工作强度映射表,以每个字节分割
+ let resultArr = that.splitStringEveryTwoChars(result, 2);
+ let workMapList = resultArr.map(item => {
+ return that.hexToDecimal(item);
+ })
+ console.log("resultArr", resultArr);
+ console.log("workMapList", workMapList);
+ } else if (sliceData === '8102') {
+ // 设置设备工作强度映射表响应的
+ console.log("设置设备工作强度映射表响应", resHex);
+
+ }
+
+ }
that.setData({
callBack: String(result)
});
- })
-},
-// 将16进制的内容转成我们看得懂的字符串内容
-hexCharCodeToStr(hexCharCodeStr) {
- let trimedStr = hexCharCodeStr.trim();
- let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
- let len = rawStr.length;
- if (len % 2 !== 0) {
- alert("存在非法字符!");
- return "";
- }
- let curCharCode;
- let resultStr = [];
- for (let i = 0; i < len; i = i + 2) {
- curCharCode = parseInt(rawStr.substr(i, 2), 16);
- resultStr.push(String.fromCharCode(curCharCode));
- }
- return resultStr.join("");
-},
+
+
+ })
+ },
+ // 将16进制的内容转成我们看得懂的字符串内容
+ hexCharCodeToStr(hexCharCodeStr) {
+ var trimedStr = hexCharCodeStr.trim();
+ var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
+ var len = rawStr.length;
+ if (len % 2 !== 0) {
+ alert("存在非法字符!");
+ return "";
+ }
+ var curCharCode;
+ var resultStr = [];
+ for (var i = 0; i < len; i = i + 2) {
+ curCharCode = parseInt(rawStr.substr(i, 2), 16);
+ resultStr.push(String.fromCharCode(curCharCode));
+ }
+ return decodeURIComponent(resultStr.join(""));
+ },
/*字符串转换16进制buffer*/
stringToCmdBuffer(msg) {
+ console.log("msg", msg);
const buffer = new ArrayBuffer(msg.length)
const dataView = new DataView(buffer)
//dataView.setUint8(0, 0)
-
+
for (let i = 0; i < msg.length; i++) {
dataView.setUint8(i, msg.charAt(i).charCodeAt())
};
-
+
return buffer
},
+ // 十六进制转二进制
+ strToHexCharCode(str) {
+ if (str === "")
+ return "";
+ var hexCharCode = [];
+ hexCharCode.push("0x");
+ for (var i = 0; i < str.length; i++) {
+ hexCharCode.push((str.charCodeAt(i)).toString(16));
+ }
+ return hexCharCode.join("");
+ },
+ // 十六进制转十进制
+ hexToDecimal(hexString) {
+ return parseInt(hexString, 16);
+ },
// ArrayBuffer转16进度字符串示例
-ab2hex(buffer) {
- const hexArr = Array.prototype.map.call(
- new Uint8Array(buffer),
- function (bit) {
- return ('00' + bit.toString(16)).slice(-2)
+ ab2hex(buffer) {
+ let hexArr = Array.prototype.map.call(
+ new Uint8Array(buffer),
+ function (bit) {
+ return ('00' + bit.toString(16)).slice(-2)
+ }
+ )
+ return hexArr.join('');
+ },
+ // 通过几位分割成数组
+ splitStringEveryTwoChars(str, splitNumber) {
+ let result = [];
+ for (let i = 0; i < str.length; i += splitNumber) {
+ result.push(str.substring(i, i + splitNumber));
}
- )
- return hexArr.join('')
+ return result;
}
})
\ No newline at end of file
diff --git a/miniprogram/pages/devicedetail/index.wxml b/miniprogram/pages/devicedetail/index.wxml
index 888913b..0dcb230 100644
--- a/miniprogram/pages/devicedetail/index.wxml
+++ b/miniprogram/pages/devicedetail/index.wxml
@@ -12,6 +12,14 @@
设备mac:
{{selmac.deviceId}}
+
+ 设备版本:
+ {{deviceInfo.version}}
+
+
+ 设备充电状态:
+ {{deviceInfo.chargeState}}
+
发送内容:
{{sendData || '暂无指令'}}
@@ -27,7 +35,7 @@
-
+
diff --git a/project.private.config.json b/project.private.config.json
index e84c82c..a96ecc4 100644
--- a/project.private.config.json
+++ b/project.private.config.json
@@ -4,5 +4,30 @@
"urlCheck": false
},
"description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
- "libVersion": "2.33.0"
+ "libVersion": "2.33.0",
+ "condition": {
+ "miniprogram": {
+ "list": [
+ {
+ "name": "蓝牙",
+ "pathName": "pages/bluetooth/bluetooth",
+ "query": "",
+ "launchMode": "default",
+ "scene": null
+ },
+ {
+ "name": "pages/devicedetail/index",
+ "pathName": "pages/devicedetail/index",
+ "query": "",
+ "launchMode": "default",
+ "scene": null
+ },
+ {
+ "name": "db guide",
+ "pathName": "pages/databaseGuide/databaseGuide",
+ "query": ""
+ }
+ ]
+ }
+ }
}
\ No newline at end of file