// 示例demo const plugin = requirePlugin('ppScale-plugin'); import { CommandButtonList } from '../../model/index' let app = getApp(); Page({ data: { // 选择的设备对象 selmac: null, // 是否在测量中 scaleing: false, // 蓝牙连接状态 devLink: false, // 扫描筛选出的设备 selectDev: null, // 设备模型 deviceModel: null, // 通讯结果 contnectResult: null, // 发送指令内容 sendData: null, // 蓝牙设备返回的结果 callBack: null, // 蓝牙设备下发指令按钮数据 sendBtnList: CommandButtonList.send, //版本号 // 手动输入文本域的值 inputValue: '', }, /** * 页面卸载时调用 */ onUnload() { // 业务结束后需要调用此方法 }, /** * 页面隐藏时调用 */ onHide() { }, onLoad() { let that = this; //监听蓝牙连接状态 wx.onBLEConnectionStateChange(function (res) { // 该方法回调中可以用于处理连接意外断开等异常情况 console.log(`设备蓝牙连接状态`, res); // 如果蓝牙断开 if (!res.connected) { // 关闭蓝牙连接事件,再重新初始化连接? that.setData({ devLink: false, }) wx.showToast({ title: '蓝牙已断开', }) /* setTimeout(() => { that.initBlue(); }, 1500) */ } else { that.setData({ devLink: true, }) } }) }, onShow() { let that = this; // 记录设备对象 this.setData({ selmac: app.globalData.selmac }) console.log("selmac", that.data.selmac); // 连接设备 wx.createBLEConnection({ deviceId: app.globalData.selmac.deviceId, success: (res) => { console.log("连接成功", res); that.setData({ devLink: true }) }, fail: (e) => { console.log("连接失败", e); } }) 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' }) } }) } }, disconnect() { let that = this; if (this.data.selmac.deviceId) { // 连接设备 wx.closeBLEConnection({ deviceId: that.data.selmac.deviceId, success: (res) => { console.log("断开连接成功", res); }, fail: (e) => { console.log("断开连接失败", e); } }) } }, onClearInput() { this.setData({ callBack: '', sendData: '', }); }, startwrite() { // 下发指令 let text = this.cleanHexString('hello'); let buffer = this.stringToCmdBuffer(text); let hexData = this.ab2hex(buffer); let string = this.hexCharCodeToStr(hexData); console.log("十六进制字符串转buffer", buffer); console.log("buffer转hexData", hexData); console.log("hexData转string", string); this.sendMessage(text); }, bindTextAreaBlur(e) { this.data.inputValue = e.detail.value; console.log(e.detail.value) }, // 手动输入文本域的值 onInputSend() { console.log("this.data.inputValue", this.data.inputValue); if(this.data.inputValue) { this.sendMessage(this.data.inputValue, true); } else { wx.showToast({ title: '指令不能为空', icon: 'error' }) } }, // 发送数据 sendMessage(event,type) { let that = this; let sendData = ''; if(type) { console.log("手动输出方式"); sendData = event } else { console.log("按钮点击输出方式"); console.log("event", event.target.dataset); sendData = event.target.dataset.command.defaultSendData; } if(!that.data.devLink) { wx.showToast({ title: '蓝牙已断开', icon: 'error' }) return } if(!sendData) { wx.showToast({ title: '指令不存在', icon: 'error' }) return } this.setData({ sendData: sendData }) let buffer = this.stringToCmdBuffer(sendData); console.log("发送的指令",buffer); wx.writeBLECharacteristicValue({ deviceId: app.globalData.selmac.deviceId, // 设备ID serviceId: app.globalData.selmac.serviceId, // 服务UUID characteristicId: app.globalData.selmac.characteristicId, // 特征值 value: buffer, success(res) { console.log("write指令发送成功", res) that.notify(); }, fail(err) { console.log("write指令发送失败", err); that.setData({ callBack: err.errMsg }); wx.showToast({ title: '指令发送失败', icon: 'error' }) } }) }, cleanHexString(hexStr) { // 使用正则表达式匹配并移除多余的'0x',并拼接剩下的部分 let cleanedHex = hexStr.replace(/0x/g, '').replace(/\b0+/g, ''); // 第二个正则表达式用于移除前导零 return cleanedHex; }, // 开启消息监听 notify() { let that = this; wx.notifyBLECharacteristicValueChange({ deviceId: app.globalData.selmac.deviceId, // 设备ID, serviceId: app.globalData.selmac.serviceId, // 服务UUID characteristicId: app.globalData.selmac.characteristicId, // 特征值 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)) 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进制buffer*/ stringToCmdBuffer(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 }, // ArrayBuffer转16进度字符串示例 ab2hex(buffer) { const hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join('') } })