const app = getApp(); var util = require('../../utils/util'); var datagramHelp = require('../../utils/datagramHelp'); var task_timer; var scan_timer; Page({ data: { devices: [], alreadyConnectDevices: [], connected: false, chs: [], isOpenBluetooth: false, bluetoothOpening: false, findBtnDisabled: true, isFinding: false, scanBtn: 'inline', rtu_wakeup: '唤醒中...', btnName: '开始扫描', bluetoothConnectBtn: '连接设备', connectedBluetoothName: '', datagramBuff: '', rtuWakeup: false, read_datagram_bluebooth_css: '', deviceId: '', serviceId: '', characteristicId: '', showBleOpenFailDig: false, showBleOtherErrorDig: false, bleOtherErrorReeponseMsg: '', discoveryStarted: false, loadingHidden: true, wakeupCount: 0, scanDeviceTimeCount: 0, }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { console.log('bluebooth home load ', '**********************************************') this.connectBle(); // var devices = []; // var d = {}; // d['name'] = "1"; // d['localName'] = "1"; // d['RSSI'] = "1"; // d['deviceId'] = "1"; // devices.push(d); // devices.push(d); // devices.push(d); // devices.push(d); // devices.push(d); // devices.push(d); // var devices2 = []; // devices2.push(d); // this.setData({ // rtuWakeup: false, // devices: devices, // alreadyConnectDevices: devices2 // }) var tmpDevices = wx.getStorageSync('alreadyConnectDevices'); if (null != tmpDevices && undefined != tmpDevices) { this.setData({ alreadyConnectDevices: tmpDevices }) } }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { console.log('bluebooth home onHide ', '**********************************************') this.cancelTaskTime(); this.cancelScanTime(); }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { console.log('bluebooth home onUnload ', '**********************************************') this.cancelTaskTime(); this.cancelScanTime(); this.closeBluetoothAdapter(); this.blueboothCloseState(); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { console.log('bluebooth home onShow ', '**********************************************') }, /** * 蓝牙适配器-打开状态 */ blueboothOpenState() { this.setData({ isOpenBluetooth: true, }) }, /** * 蓝牙适配器-关闭状态 */ blueboothCloseState() { this.setData({ isOpenBluetooth: false, }) }, /** * 开始连接蓝牙 */ connectBle() { console.log("connectBle ", "isOpenBluetooth " + this.data.isOpenBluetooth); if (!this.data.isOpenBluetooth) { if (!this.data.bluetoothOpening) { this.setData({ bluetoothOpening: true, }) this.openBluetoothAdapter(); } } }, /** * 打开蓝牙适配器 */ openBluetoothAdapter() { let that = this; console.log("openBluetoothAdapter", "***** open **********") wx.openBluetoothAdapter({ success: (res) => { //改变连接状态 that.blueboothOpenState(); console.log("openBluetoothAdapter", "***** open success " + that.data.isOpenBluetooth); that.setData({ bluetoothOpening: false, }) //初始化成功,监听 that.onBluetoothAdapterStateChange(); //消息提示 wx.showToast({ title: '蓝牙设备打开成功', icon: 'none', duration: 2000, }) }, fail: (res) => { if (res.errCode != undefined) { let code = res.errCode; // if (code == app.globalData.bluetoothErrCode.alreadyConnect) { // console.log("openBluetoothAdapter","***** openBluetoothAdapter alreadyConnect **********") // //已连接,监听 // that.onBluetoothAdapterStateChange(); // //改变连接状态 // that.blueboothOpenState(); // } else if (code == app.globalData.bluetoothErrCode.notAvailable) { console.log("openBluetoothAdapter", "***** openBluetoothAdapter notAvailable **********") //蓝牙未打开,提示用户 that.setData({ showBleOpenFailDig: true, loadingHidden: true, }) } else { //其它错误 console.log("openBluetoothAdapter", "***** openBluetoothAdapter error code " + code + " **********") that.setData({ bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误代码: " + code, showBleOtherErrorDig: true, loadingHidden: true, }) } } else { //未知错误 console.log("openBluetoothAdapter", "***** openBluetoothAdapter error msg " + res.errMsg + " **********") that.setData({ bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg, showBleOtherErrorDig: true, loadingHidden: true, }) } that.setData({ bluetoothOpening: false, }) } }) }, /** * 关闭蓝牙适配器 */ closeBluetoothAdapter() { if (this.data.isOpenBluetooth) { wx.closeBluetoothAdapter(); this.setData({ bluetoothOpening: false }) } }, /** * 监听蓝牙适配器的变化 */ onBluetoothAdapterStateChange() { let that = this; wx.onBluetoothAdapterStateChange(function (res) { if (res.available) { console.log("onBluetoothAdapterStateChange", "******* onBluetoothAdapterStateChange available *********") that.connectBle(); } else { console.log("onBluetoothAdapterStateChange", "******* onBluetoothAdapterStateChange unavailable *********") that.blueboothCloseState(); wx.showToast({ title: '蓝牙设备断开', icon: 'none', duration: 2000 }) } if (res.discovering) { console.log("onBluetoothAdapterStateChange", "******* onBluetoothAdapterStateChange discovering *********") } else { console.log("onBluetoothAdapterStateChange", "******* onBluetoothAdapterStateChange stop discovering *********") } }) }, /** * 打开蓝牙失败确认事件 * @param {}} e */ bluetoothOpenEvent(e) { this.setData({ showBleOpenFailDig: false }) const btn = e.detail.index; if (btn == 0) { this.closeBluetoothAdapter(); wx.navigateBack(); } else if (btn == 1) { this.connectBle(); } }, /** * 蓝牙系统错误确认事件 * @param {*} e */ bluetoothOtherErrorEvent(e) { this.setData({ showBleOtherErrorDig: false }) this.closeBluetoothAdapter(); wx.navigateBack(); }, /** * 开始扫描操作事件 */ scanBluetoothDevicesHandle() { if (this.data.isFinding) { this.stopBluetoothDevicesDiscovery() this.cancelScanTime(); console.log('scanBluetoothDevicesHandle', 'stop scan bluebooth devices *****************'); } else { this.startBluetoothDevicesDiscovery() console.log('scanBluetoothDevicesHandle', 'start scan bluebooth devices *****************'); } }, /** * 开始扫描蓝牙设置 */ startBluetoothDevicesDiscovery() { if (this.data.discoveryStarted) { return } const that = this; let data = []; this.setData({ btnName: '停止扫描', isFinding: true, devices: data, rtuWakeu: false, scanDeviceTimeCount: 0 }) wx.startBluetoothDevicesDiscovery({ allowDuplicatesKey: true, success: (res) => { console.log('startBluetoothDevicesDiscovery success', res) that.setData({ discoveryStarted: true }) that.scanTimeCallback(); wx.onBluetoothDeviceFound((res) => { res.devices.forEach(device => { if (device.name != undefined && device.name.length > 0) { //console.log('bluetooth find *************************************', device.name) if (device.name.indexOf('XT-') == 0 || device.name.indexOf('DH') == 0 || device.name.indexOf('dh') == 0) { let foundDevices = that.data.devices let idx = util.inArray(foundDevices, 'deviceId', device.deviceId) if (idx === -1) { foundDevices[foundDevices.length] = device; that.setData({ scanDeviceTimeCount: 0 }); } else { foundDevices[idx] = device; } that.setData({ devices: foundDevices }); } } }) }) }, fail: (res) => { console.log('startBluetoothDevicesDiscovery fail', res) that.setData({ isFinding: false, btnName: '开始扫描', discoveryStarted: false }) } }) }, /** * 停止扫描蓝牙设备 */ stopBluetoothDevicesDiscovery() { let that = this; wx.stopBluetoothDevicesDiscovery({ success(res) { that.cancelScanTime(); that.setData({ isFinding: false, btnName: '开始扫描', discoveryStarted: false }) } }); }, /** * 连接蓝牙设备 * @param {*} e */ onBLEConnectionHandle(e) { var that = this; const ds = e.currentTarget.dataset; const deviceId = ds.deviceId; const name = ds.name; if (this.data.discoveryStarted) { this.stopBluetoothDevicesDiscovery(); this.cancelScanTime(); } this.setData({ connectedBluetoothName: name, deviceId: deviceId, isFinding: false, loadingHidden: false, wakeupCount: 1, rtuWakeup: false }) console.log('onBLEConnectionHandle connect ', name) wx.createBLEConnection({ deviceId, timeout: 5000, success: (res) => { console.log('onBLEConnectionHandle connect success ', name) that.setData({ connected: true }) // wx.onBLEConnectionStateChange(function (res) { // // 该方法回调中可以用于处理连接意外断开等异常情况 // console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`) // }) that.getBLEDeviceServices(deviceId); }, fail(res) { if (res.errCode != undefined) { if (res.errCode == app.globalData.bluetoothErrCode.alreadyConnect) { that.setData({ loadingHidden: true, rtuWakeup: false, wakeupCount: 1 }) that.datagramReadTask(); that.taskTimeCallback(); } else { console.log("onBLEConnectionHandle ", "***** error code " + res.errCode + " **********") that.setData({ bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误代码: " + res.errCode, showBleOtherErrorDig: true, loadingHidden: true }) } } else { console.log("onBLEConnectionHandle ", "***** error msg " + res.errMsg + " **********") that.setData({ bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg, showBleOtherErrorDig: true, loadingHidden: true }) } } }) }, onBLEConnectionFormQr(device) { var that = this; const deviceId = device.deviceId; const name = device.name; if (this.data.discoveryStarted) { this.stopBluetoothDevicesDiscovery(); this.cancelScanTime(); } this.setData({ connectedBluetoothName: name, deviceId: deviceId, isFinding: false, loadingHidden: false, wakeupCount: 1, rtuWakeup: false }) console.log('onBLEConnectionHandle connect ', name) wx.createBLEConnection({ deviceId, timeout: 5000, success: (res) => { console.log('onBLEConnectionHandle connect success ', name) that.setData({ connected: true }) that.getBLEDeviceServices(deviceId); }, fail(res) { if (res.errCode != undefined) { if (res.errCode == app.globalData.bluetoothErrCode.alreadyConnect) { that.setData({ loadingHidden: true, rtuWakeup: false, wakeupCount: 1 }) that.datagramReadTask(); that.taskTimeCallback(); } else { console.log("onBLEConnectionHandle ", "***** error code " + res.errCode + " **********") that.setData({ bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误代码: " + res.errCode, showBleOtherErrorDig: true, loadingHidden: true }) } } else { console.log("onBLEConnectionHandle ", "***** error msg " + res.errMsg + " **********") that.setData({ bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg, showBleOtherErrorDig: true, loadingHidden: true }) } } }) }, onStartQr: function (e) { var that = this; // 允许从相机和相册扫码 wx.scanCode({ success: (res) => { var result = res.result; if (result != undefined && result.length > 0) { that.findDeviceByQr(result) } } }) }, findDeviceByQr(qr) { for (let i = 0; i < this.data.devices.length; i++) { let d = this.data.devices[i]; if (d.name == qr) { this.onBLEConnectionFormQr(d); return; } } for (let i = 0; i < this.data.alreadyConnectDevices.length; i++) { let d = this.data.alreadyConnectDevices[i]; if (d.name == qr) { this.onBLEConnectionFormQr(d); return; } } wx.showToast({ title: '没匹配到设备', icon: 'error', duration: 2000 }) }, /** * 获取蓝牙设备所有服务(service) * @param {*} deviceId */ getBLEDeviceServices(deviceId) { const that = this; console.log('*************************** getBLEDeviceServices start', deviceId); wx.getBLEDeviceServices({ deviceId, success: (res) => { console.log('*************************** getBLEDeviceServices ', "ok"); let toNext = false; for (let i = 0; i < res.services.length; i++) { console.log(' res++++++++++++ ', res.services[i]) if (res.services[i].isPrimary) { toNext = true; that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid); break; } } if (!toNext) { that.setData({ loadingHidden: true }) } }, fail: (res) => { console.log("getBLEDeviceServices ", "***** error msg " + res.errMsg + " **********") that.setData({ bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg, showBleOtherErrorDig: true, loadingHidden: true }) } }) }, /** * 获取蓝牙设备某个服务中所有特征值(characteristic) * @param {*} deviceId * @param {*} serviceId */ getBLEDeviceCharacteristics(deviceId, serviceId) { var that = this wx.getBLEDeviceCharacteristics({ deviceId, serviceId, success: (res) => { console.log('getBLEDeviceCharacteristics success', res.characteristics) that.setData({ canWrite: false }) let write_uuid = []; for (let i = 0; i < res.characteristics.length; i++) { let item = res.characteristics[i] if (item.properties.read) { console.log("read uuid", item.uuid) // that.setData({ // deviceId: deviceId, // serviceId: serviceId, // characteristicId: item.uuid // }) wx.readBLECharacteristicValue({ deviceId, serviceId, characteristicId: item.uuid, }) } if (item.properties.write) { //使用透传UUID进行读 console.log("write uuid", item.uuid) let u = "" + item.uuid; write_uuid.push(u); // if (u.includes("FFE1", 0)) { that.setData({ canWrite: true, // deviceId: deviceId, // serviceId: serviceId, // characteristicId: item.uuid }) // } } if (item.properties.notify || item.properties.indicate) { console.log("notify uuid", item.uuid) // console.log('notify success+++++++++++++++++++++++ ') // that.setData({ // deviceId: deviceId, // serviceId: serviceId, // characteristicId: item.uuid // }) wx.notifyBLECharacteristicValueChange({ deviceId, serviceId, characteristicId: item.uuid, state: true, }) } } that.setData({ loadingHidden: true }) if (this.data.canWrite) { if (write_uuid.length == 1) { console.log("get uuid", write_uuid[0]) that.setData({ deviceId: deviceId, serviceId: serviceId, characteristicId: write_uuid[0] }) } else { for (let j = 0; j < write_uuid.length; j++) { let uid = "" + write_uuid[j]; if (uid.includes("FFE1", 0)) { console.log("get uuid", uid) that.setData({ // canWrite: true, deviceId: deviceId, serviceId: serviceId, characteristicId: uid }) break; } } } that.canWriteBLECharacteristicValue() } }, fail(res) { console.log("getBLEDeviceCharacteristics ", "***** error msg " + res.errMsg + " **********") that.setData({ bleOtherErrorReeponseMsg: "蓝牙模块系统异常,请重新打开蓝牙助手再试,错误信息: " + res.errMsg, showBleOtherErrorDig: true, loadingHidden: true }) } }) }, /** * 发送蓝牙设备唤醒报文 */ datagramReadTask() { const that = this; this.setData({ read_datagram_bluebooth_css: 'shanshuo' }) if (!this.data.rtuWakeup) { console.log("------------------------------------f6 datagram----------------------------"); this.sendWakeupDatagram(); } }, processWakeupDatagram() { let datagram = this.data.datagramBuff; if (datagram.length > 0) { if (datagram.indexOf("7e7e") >= 0) { if (datagram.length >= 50) { const funcode = datagram.substring(20, 22); if (funcode == 'f6') { console.log("------------------------------------find f6 datagram----------------------------"); this.setData({ read_datagram_bluebooth_css: '', rtuWakeup: true, datagramBuff: '' }) } else { this.setData({ datagramBuff: '' }) } } } else { this.setData({ datagramBuff: '' }) } } if (this.data.rtuWakeup) { this.cancelTaskTime(); this.cancelScanTime(); this.setData({ loadingHidden: true }) var tmpDevices = []; var device = {}; device['deviceId'] = this.data.deviceId; device['name'] = this.data.connectedBluetoothName; device['serviceId'] = this.data.serviceId; device['characteristicId'] = this.data.characteristicId; tmpDevices.push(device); var devices = this.data.alreadyConnectDevices; for (var i = 0; i < devices.length; i++) { var d = devices[i]; if (device['deviceId'] !== d['deviceId']) { tmpDevices.push(d); } if (tmpDevices.length >= 5) { break; } } try { wx.setStorageSync('alreadyConnectDevices', tmpDevices); } catch (e) { console.log(e); } this.setData({ alreadyConnectDevices: tmpDevices }) //跳转到蓝牙主页 wx.navigateTo({ url: '/pages/bluetooth/home/bluetoothHome?connectedBluetoothName=' + this.data.connectedBluetoothName + '&deviceId=' + this.data.deviceId + '&serviceId=' + this.data.serviceId + '&characteristicId=' + this.data.characteristicId, }) } }, /** * 接收到数据 * @param {} datagram */ pushDatagram(datagram) { if (null != datagram && datagram.length > 0) { var tmpdatagramBuff = this.data.datagramBuff; if (tmpdatagramBuff.length > 0) { tmpdatagramBuff = tmpdatagramBuff + datagram; } else { tmpdatagramBuff = datagram; } console.log(" datagram buff ==========", tmpdatagramBuff) this.setData({ datagramBuff: tmpdatagramBuff }) this.processWakeupDatagram(); } }, /** * 发送唤醒蓝牙设备操作 */ sendWakeupDatagram() { let datagram = datagramHelp.datagram_f6(); let buffer = util.HexStr2Bytes(datagram); var that = this wx.writeBLECharacteristicValue({ deviceId: this.data.deviceId, serviceId: this.data.serviceId, characteristicId: this.data.characteristicId, value: buffer, success(res) { console.log('writeBLECharacteristicValue success', res.errMsg) // 操作之前先监听,保证第一时间获取数据 wx.onBLECharacteristicValueChange((characteristic) => { console.log("read datagram==========", util.ab2hex(characteristic.value)) let datagram = util.ab2hex(characteristic.value); that.pushDatagram(datagram); }) wx.readBLECharacteristicValue({ deviceId: that.data.deviceId, serviceId: that.data.serviceId, characteristicId: that.data.characteristicId, success: function (res) { console.log('readBLECharacteristicValue') } }) }, fail(res) { console.log('writeBLECharacteristicValue success', res.errMsg); } }) }, taskTimeCallback() { console.log("------------------------------------Task Time CallBack----------------------------"); var that = this; if (!this.data.rtuWakeup) { if (this.data.wakeupCount >= 5) { this.setData({ loadingHidden: true }) } else { task_timer = setTimeout(function () { that.datagramReadTask(); that.taskTimeCallback(); }, 3000); } } }, cancelTaskTime() { if (task_timer != undefined) { clearTimeout(task_timer); task_timer = undefined; } }, scanTimeCallback() { console.log("------------------------------------Scan Time CallBack----------------------------"); var that = this; if (this.data.scanDeviceTimeCount >= 6) { console.log("Scan Time CallBack stopBluetoothDevicesDiscovery"); this.stopBluetoothDevicesDiscovery(); } else { let c = this.data.scanDeviceTimeCount + 2; this.setData({ scanDeviceTimeCount: c }) scan_timer = setTimeout(function () { that.scanTimeCallback(); }, 2000); } }, cancelScanTime() { if (scan_timer != undefined) { clearTimeout(scan_timer); scan_timer = undefined; } }, canWriteBLECharacteristicValue() { if (!this.data.rtuWakeup) { this.setData({ isFinding: false, btnName: '开始扫描', rtuWakeup: false }) console.log("----------------------------------- 发送第一个包----------------------------"); this.datagramReadTask(); this.taskTimeCallback(); } } })