// 引入必要的微信小程序 API // const wx = require('wx'); class bleManager { constructor() { var that = this; that.isAvailable = false; that.hasPermission = false; that.scanDevices = []; that.publicDevice = null; that.compareList = []; that.connectWillDevice = null; that.callBackConnect = null; that.requestBlueTime = 0; ///正在执行扫描中 that.doStartScaning = false; } ///获取比较的数据 getCompareList() { return this.compareList; } setConnectWillDevice(connectWillDevice) { this.connectWillDevice = connectWillDevice; } getCallBackConnect() { return this.callBackConnect; } setCallBackConnect(callBackConnect) { this.callBackConnect = callBackConnect; } /// 监控蓝牙打开状态 initBluetoothAdapter() { var that = this; wx.onBluetoothAdapterStateChange(function (res) { that.isAvailable = res.available; }) } ///监听搜索设备列表 getBluetoothDevices() { var that = this; wx.onBluetoothDeviceFound(function (res) { ///第一种情况 if (res.deviceId) { if (that.callBackConnect != null) { if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) { res.advertisData = res.advertisData ? that.buf2hex(res.advertisData) : ''; that.callBackConnect(res); } } else { if (res.name != "") { if (that.compareList.length > 0) { var has = false; for (var i = 0; i < that.compareList.length; i++) { if (res.deviceId == that.compareList[i].deviceId) { has = true; break; } } if (!has) { that.compareList.push(res); } } else { that.compareList.push(res); } } } } ///第二种情况 else if (res.devices) { if (that.callBackConnect != null) { for (var i = 0; i < res.devices.length; i++) { var temp = res.devices[i]; if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) { temp.advertisData = temp.advertisData ? that.buf2hex(temp.advertisData) : ''; that.callBackConnect(temp); break; } } } else { for (var i = 0; i < res.devices.length; i++) { if (that.compareList.length > 0) { var has = false; for (var j = 0; j < that.compareList.length; j++) { if (res.devices[i].name != "") { if (res.devices[i].deviceId == that.compareList[j].deviceId) { has = true; break; } } } if (!has) { that.compareList.push(res.devices[i]); } } else { that.compareList.push(res.devices[i]); } } } } ///第三种情况 else if (res[0]) { if (that.callBackConnect != null) { if (that.connectWillDevice != null && res[0].name == that.connectWillDevice.clientType) { res[0].advertisData = res[0].advertisData ? that.buf2hex(res[0].advertisData) : ''; that.callBackConnect(res[0]); } } else { if (res[0].name != "") { if (that.compareList.length > 0) { var has = false; for (var i = 0; i < that.compareList.length; i++) { if (res[0].deviceId == that.compareList[i].deviceId) { has = true; break; } } if (!has) { that.compareList.push(res[0]); } } else { that.compareList.push(res[0]); } } } } }); } ///获取数据 buf2hex(buffer) { return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(''); } ///获取毫秒 getCurrentMills() { var currentDate = new Date(); var currentTimeMillis = currentDate.getTime(); // return Math.floor(currentTimeMillis / 1000); return currentTimeMillis; } // 等待多少秒 delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // 开始搜索蓝牙设备 async startScan(connectWillDevice, boolean, callBackConnect) { var that = this; const route_constant = require('../utils/route_constant'); const connectBleRoot = route_constant.connectBleRoot; const route_util = require('../utils/route_util'); var lastPageRoute = route_util.getLastPageRoute(); ///蓝牙连接 做限制 if (callBackConnect == null && lastPageRoute != connectBleRoot) { if (that.doStartScaning == true) { return; } } that.doStartScaning = true; var currentMill = that.getCurrentMills(); var waitMills = 0; var reduce = currentMill - that.requestBlueTime; const delayMiliis = 5 * 1000; if (reduce > 0 && reduce < delayMiliis) { waitMills = delayMiliis - reduce; } if (callBackConnect == null && lastPageRoute == connectBleRoot) { return; } if (waitMills > 0) { await that.delay(waitMills); } if (callBackConnect == null && lastPageRoute == connectBleRoot) { return; } wx.closeBluetoothAdapter({ complete: function (res) { wx.openBluetoothAdapter({ success: function (res) { wx.getBluetoothAdapterState({ success: function (res) { that.doStartScaning = false; }, fail(err) { that.doStartScaning = false; if (boolean != null) { boolean(false); } }, }) wx.startBluetoothDevicesDiscovery({ allowDuplicatesKey: false, success: function (res) { that.doStartScaning = false; that.requestBlueTime = that.getCurrentMills(); if (boolean != null) { boolean(true); } that.setConnectWillDevice(connectWillDevice); that.setCallBackConnect(callBackConnect); that.compareList = []; }, fail(err) { that.doStartScaning = false; that.requestBlueTime = that.getCurrentMills(); if (boolean != null) { boolean(false); } }, }) }, fail: function (res) { wx.showModal({ title: '提示', content: '请检查手机蓝牙是否打开', showCancel: false, success: function (res) {} }); that.doStartScaning = false; if (boolean != null) { boolean(false); } } }) } }) } // 停止搜索 stopSearch() { var that = this; that.setCallBackConnect(null); that.setConnectWillDevice(null); return new Promise((resolve, reject) => { wx.stopBluetoothDevicesDiscovery({ success: (res) => { resolve(res); }, fail: (err) => { reject(new Error('停止搜索失败')); } }); }); } closeBle() { console.log('关闭蓝牙了') closeBluetoothAdapter(); } // 断开与指定设备的连接 disconnect() { var that = this; let device = that.publicDevice ?? {}; let deviceId = device.deviceId ?? "" if (deviceId.length === 0) { return; } return new Promise((resolve, reject) => { wx.closeBLEConnection({ deviceId: that.publicDevice.deviceId ?? "", success: (res) => { that.publicDevice = null; console.log('断开连接成功:', res); resolve(res); }, fail: (err) => { console.error('断开连接失败:', err); reject(new Error('断开连接失败')); } }); }); } // 发送数据到指定设备 async sendData(data) { var that = this return new Promise((resolve, reject) => { var buffer = null; // todo 判断是否是buffer // if (Buffer.isBuffer(data)) { // buffer = data; // } else { buffer = new ArrayBuffer(data.length); // 下面是赋值,不能删 const dataView = new DataView(buffer); data.forEach((value, index) => { dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中 }); // } console.log('开始发送数据:', data, buffer); wx.writeBLECharacteristicValue({ deviceId: that.publicDevice.deviceId, serviceId: that.publicDevice.serviceId, characteristicId: that.publicDevice.characteristicId, value: buffer, success: (res) => { // console.log('数据发送成功:'); resolve(res); }, fail: (err) => { console.error('数据发送失败:', err); reject(new Error('数据发送失败')); } }); }); } ab2hex(buffer) { var hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join(':'); } fiterDevice(res) { var that = this; var devices = res.devices.filter(device => { const name = device.name || ''; const localName = device.localName || ''; let isNot = that.isNotEmpty(name) || that.isNotEmpty(localName); if (isNot) { // console.log('是猫王设备名称:', device.advertisData, device.serviceData) let mac = that.ab2hex(device.advertisData) // console.log(mac) device.mac = mac } return isNot }); let newDevices = devices.map((device) => { let uuid = device.advertisServiceUUIDs[0] ?? "" return { deviceId: device.deviceId, name: device.name, localName: device.localName, uuid: uuid, mac: device.mac, connectable: device.connectable } }); return newDevices } isNotEmpty(name) { let isNot = (name !== '' && (name.startsWith("MW_") || name.startsWith("MW-") || // name.startsWith("猫王") || // name.startsWith("妙播") || // name.startsWith("AirSmart") || name === "le") ) // if (!isNot && name !== '') { // console.log('不是猫王设备名称:', name) // } return isNot; } // 连接到指定设备 async connectToDevice(device) { var that = this; return new Promise((resolve, reject) => { console.log("开始连接蓝牙:", device.deviceId) wx.createBLEConnection({ deviceId: device.deviceId, success: (res) => { that.publicDevice = device console.log('连接成功:', res); resolve(true); }, fail: (err) => { that.publicDevice = null console.error('连接失败:', err); resolve(false); } }); }); } // 发现服务 discoverServices(deviceId) { var that = this; console.log('发现服务:', deviceId); return new Promise((resolve, reject) => { wx.getBLEDeviceServices({ deviceId: deviceId, success: (res) => { // that.publicDevice .services = res.services; let service_id = ""; for (let i = 0; i < res.services.length; i++) { if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 || res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1 // res.services[i].uuid.toUpperCase().indexOf("ae800") != -1 ) { service_id = res.services[i].uuid; break; } console.log('发现服务1:', service_id); service_id = res.services[i].uuid; } that.publicDevice.serviceId = service_id; console.log('发现服务2:', service_id); resolve(service_id); // resolve(res.services); }, fail: (err) => { that.publicDevice.serviceId = null; console.error('发现服务失败:', err); reject([]); } }); }); } // 发现特征值 read / write discoverCharacteristics(deviceId, serviceId) { var that = this; console.log('发现特征值:' + deviceId + " , " + serviceId); // if (deviceId !== that.publicDevice .deviceId) { // console.log('设备id不匹配') // return false // } return new Promise((resolve, reject) => { wx.getBLEDeviceCharacteristics({ deviceId: deviceId, serviceId: serviceId, success: (res) => { // that.characteristics[serviceId] = res.characteristics; console.log('发现特征值2:', res); // that.publicDevice .characteristics = res.characteristics; resolve(res.characteristics); }, fail: (err) => { that.publicDevice.characteristics = null; console.error('发现特征值失败:', err); reject(""); } }); }); } // 读取特征值 readCharacteristicValue(characteristicId) { var that = ths; console.log('开始读取特征值', characteristicId) return new Promise((resolve, reject) => { wx.readBLECharacteristicValue({ deviceId: that.publicDevice.deviceId, serviceId: that.publicDevice.serviceId, characteristicId: characteristicId, success: (res) => { const name = that.parseBLEValue(res.value); // 解析读取到的值 console.log('读取特征值成功:', name, res); resolve(res); }, fail: (err) => { console.error('读取特征值失败:', err); reject(""); } }); }); } // 解析读取到的设备名称 parseBLEValue(buffer) { return String.fromCharCode.apply(null, new Uint8Array(buffer)); } // 监听特征值变化 notifyCharacteristicValueChange(characteristicId, callback) { var that = this; console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId); wx.notifyBLECharacteristicValueChange({ deviceId: that.publicDevice.deviceId, //设备mac IOS和安卓系统不一样 serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify characteristicId: characteristicId, //notify uuid state: true, success: function (res) { console.log("开启notify 成功") //TODO onBLECharacteristicValueChange 监听特征值 设备的数据在这里获取到 wx.onBLECharacteristicValueChange(function (characteristic) { let buffer = characteristic.value let dataView = new DataView(buffer) let dataResult = [] for (let i = 0; i < dataView.byteLength; i++) { // console.log("0x" + dataView.getUint8(i).toString(16)) // dataResult.push("0x" + dataView.getUint8(i).toString(16)) dataResult.push(dataView.getUint8(i)) } const result = dataResult console.log("拿到的数据:", result) if (callback) { callback(result) } }) }, fail: function (res) { console.log("订阅特征失败:", res) } }) } setWrite(wirte, characteristicId) { var that = this; console.log('写入特征值:', characteristicId) // that.publicDevice .wirte = wirte that.publicDevice.characteristicId = characteristicId; } } // const ble = new bleManager(); // 导出 bleManager 类 module.exports = bleManager; // wx.getSetting({ // success(res) { // if (res.authSetting["scope.userFuzzyLocation"]) { // // 成功 // // that.getBluetoothStatus(); // console.log("有定位权限") // resolve(true); // } else if (res.authSetting["scope.userFuzzyLocation"] === undefined) { // wx.authorize({ // scope: "scope.userFuzzyLocation", // success() { // console.log("再次获取定位权限") // resolve(that.getSetting()); // } // }); // } else { // wx.showModal({ // title: '请打开系统位置获取定位权限', // success(res) { // if (res.confirm) { // console.log('用户点击确定') // wx.openSetting({ // complete() { // // that.getSetting(); // // resolve(that.getSetting()); // } // }) // } else if (res.cancel) { // console.log('用户点击取消'); // } // } // }) // console.log("没有有定位权限") // reject(false); // } // } // }) // // 获取已连接的蓝牙设备 // getConnectedDevices() { // var that = this; // if (!that.isAvailable && !that.hasPermission) { // return []; // } // return new Promise((resolve, reject) => { // wx.getConnectedBluetoothDevices({ // // services: ["FFC0", "ffc0", "FFC1", "FFC2", "ffc1", "ffc2", "AB00", "ab00", "AB01", "AB02", "FFF1", "fff1", "FFE2", "FFE5",], // // services: ["ab00", "ffe5", "1111", "FFC0", "FFC1", "FFF1", ], // // services: [], // // services: [ // // "0000ab00-0000-1000-8000-00805f9b34fb", // // "0000ffc0-0000-1000-8000-00805f9b34fb", // // "0000FFF0-0000-1000-8000-00805F9B34FB", // // "0000FFF1-0000-1000-8000-00805F9B34FB", // // "0000FFE5-0000-1000-8000-00805F9B34FB", // // ], // success: (res) => { // console.log('已连接的蓝牙设备==11==:', newDevices); // let newDevices = that.fiterDevice(res) // console.log('已连接的蓝牙设备==22==:', newDevices); // resolve(newDevices); // }, // fail: (err) => { // console.error('获取已连接的蓝牙设备失败:', err); // reject([]); // } // }); // }); // }