const util = require("../../utils/util"); const { inArray, ab2hex } = util Page({ data: { connected: false, height: "", devices: [], deviceId: null, }, onLoad: function() {}, // 初始化蓝牙模块 openBluetoothAdapter() { wx.openBluetoothAdapter({ success: (res) => { console.log('openBluetoothAdapter success', res) wx.showToast({ title: '蓝牙连接中', icon: "none" }) this.startBluetoothDevicesDiscovery() }, fail: (res) => { if (res.errCode === 10001) { wx.showToast({ title: '请打开蓝牙', icon: "none" }) // 监听本机蓝牙状态变化的事件 wx.onBluetoothAdapterStateChange((res) => { console.log('onBluetoothAdapterStateChange', res) if (res.available) { this.startBluetoothDevicesDiscovery() } }) } } }) }, // 开始搜寻附近的蓝牙外围设备 startBluetoothDevicesDiscovery() { if (this._discoveryStarted) { return } this._discoveryStarted = true wx.startBluetoothDevicesDiscovery({ allowDuplicatesKey: true, interval: 1000, //上报设备的间隔 services: [ "FFF0", ], success: (res) => { this.onBluetoothDeviceFound() }, }) }, // 停止搜寻附近的蓝牙外围设备 stopBluetoothDevicesDiscovery() { wx.stopBluetoothDevicesDiscovery() }, // 找到新设备的事件 onBluetoothDeviceFound() { let that = this wx.onBluetoothDeviceFound((res) => { res.devices.forEach(device => { if (!device.name && !device.localName) { return } if (device.name.indexOf("WSD") !== -1) { let value = ab2hex(device.advertisData, "") let type = value.substring(22, 24) let num = value.substring(28, 29) let dw = value.substring(29, 30) let data = parseInt(value.substring(24, 28), 16) let unit = "cm" const foundDevices = this.data.devices const idx = inArray(foundDevices, 'deviceId', device.deviceId) const dataT = {} let buffer = device.advertisData.slice(3, 9) device.mac = new Uint8Array(buffer) // 保存广播数据中的mac地址,这是由于iOS不直接返回mac地址 let tempMac = Array.from(device.mac) // tempMac.reverse() device.macAddr = ab2hex(tempMac, ':').toUpperCase() if (idx === -1) { dataT[`devices[${foundDevices.length}]`] = device } else { dataT[`devices[${idx}]`] = device } this.setData(dataT) if (dw == "1") { unit = "FT" data = data * 2.54 } if (num == "1") { data = data / 10 } if (num == "2") { data = data / 100 } if (num == "3") { data = data / 1000 } if (type == "01") { that.setData({ height: data + unit }) return } } }) }) }, //监听蓝牙连接状态 onBLEConnectionStateChange() { wx.onBLEConnectionStateChange((res) => { if (!res.connected) { wx.stopBluetoothDevicesDiscovery(); setTimeout(() => { wx.showToast({ title: '连接已断开', icon: 'none' }) }, 500) this.setData({ connected: false, devices: [], height: "", }) } }) }, /** * 断开蓝牙模块 */ closeBluetoothAdapter() { wx.stopBluetoothDevicesDiscovery(); wx.closeBluetoothAdapter() this._discoveryStarted = false wx.showToast({ title: '结束流程', icon: 'none' }) this.setData({ devices: [], height: "", }) }, });