فهرست منبع

feature: 加入蓝牙ble新方法

Damon 7 ماه پیش
والد
کامیت
3f3c84f413
5فایلهای تغییر یافته به همراه430 افزوده شده و 2 حذف شده
  1. 344 0
      utils/blue_ble/manager.js
  2. 60 0
      utils/blue_ble/util.js
  3. 8 0
      utils/hex_util.js
  4. 17 1
      utils/time_util.js
  5. 1 1
      utils/util.js

+ 344 - 0
utils/blue_ble/manager.js

@@ -0,0 +1,344 @@
+module.exports = Manager;
+
+class Manager {
+  constructor() {
+    var that = this;
+    ///正在连接中的设备
+    that.connectWillDevice = null;
+    ///正在连接的设备,成功后返回的数据
+    that.callBackConnect = null;
+    ///搜索过快会失败,给的一定的缓冲时间
+    that.requestBlueTime = 0;
+    ///蓝牙是否已打开,是否可用
+    that.isAvailable = false;
+    ///蓝牙正在搜索中,则不允许继续搜索
+    that.doStartScaning = false;
+    ///蓝牙设备搜索的所有在线设备,用来和现有设备比较
+    that.compareList = [];
+    ///离线的所有设备,也可以用来比较
+    that.dissmissDevice = [];
+  }
+
+  ///获取比较的数据
+  getCompareList() {
+    var that = this;
+    return that.compareList;
+  }
+
+  setCompareList(compareList) {
+    var that = this;
+    that.compareList = compareList;
+  }
+
+  getDissmissDevice() {
+    var that = this;
+    return that.dissmissDevice;
+  }
+
+  setConnectWillDevice(connectWillDevice) {
+    var that = this;
+    that.connectWillDevice = connectWillDevice;
+  }
+
+  getCallBackConnect() {
+    var that = this;
+    return that.callBackConnect;
+  }
+
+  setCallBackConnect(callBackConnect) {
+    this.callBackConnect = callBackConnect;
+  }
+
+  /// 监控蓝牙打开状态
+  initBlueAdapter() {
+    var that = this;
+    wx.onBluetoothAdapterStateChange(function (res) {
+      that.isAvailable = res.available;
+      if (!that.isAvailable) {
+        that.compareList = [];
+        that.dissmissDevice = [];
+        getCurrentPages()[0].closeBlueResetOffline(false, true);
+      }
+    })
+  }
+
+  ///监听搜索设备列表
+  listenBlueDevices() {
+    var that = this;
+    const hex_util = require('./../../utils/hex_util');
+    wx.onBluetoothDeviceFound(function (res) {
+      ///第一种情况
+      if (res.deviceId) {
+        if (that.callBackConnect != null) {
+          if (that.connectWillDevice != null && res.name == that.connectWillDevice.clientType) {
+            res.mac = res.advertisData ? hex_util.buf2hex(res.advertisData) : '';
+            if (that.callBackConnect != null) {
+              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.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
+              temp.mac2 = that.ab2hex(temp.advertisData ?? "")
+              if (that.callBackConnect != null) {
+                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].mac = res[0].advertisData ? hex_util.buf2hex(res[0].advertisData) : '';
+            if (that.callBackConnect != null) {
+              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]);
+            }
+          }
+        }
+      }
+    });
+
+    ///监听  离线和连接成功设备导入
+    // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
+    wx.onBLEConnectionStateChange((result) => {
+      if (result.connected) {
+        for (var i = 0; i < that.dissmissDevice.length; i++) {
+          if (result.deviceId == that.dissmissDevice[i].deviceId) {
+            that.dissmissDevice.splice(i, 1);
+            break;
+          }
+        }
+      } else {
+        var has = false;
+        for (var i = 0; i < that.dissmissDevice.length; i++) {
+          if (result.deviceId == that.dissmissDevice[i].deviceId) {
+            has = true;
+            break;
+          }
+        }
+        if (!has) {
+          that.dissmissDevice.push(result);
+        }
+      }
+    });
+  }
+
+  // 开始搜索蓝牙设备
+  async startScan(connectWillDevice, boolean, callBackConnect) {
+    var that = this;
+    ///限制搜索没有打开蓝牙一直询问打开蓝牙
+    var isAvailable = that.isAvailable;
+    if (!isAvailable && callBackConnect == null) {
+      return;
+    }
+
+    const route_util = require('../utils/route_util');
+    const route_constant = require('../utils/route_constant');
+    const indexRoot = route_constant.indexRoot;
+    const connectBleRoot = route_constant.connectBleRoot;
+    var lastPageRoute = route_util.getLastPageRoute();
+    if (lastPageRoute != indexRoot && lastPageRoute != connectBleRoot) {
+      return;
+    }
+
+    ///蓝牙连接 做限制
+    if (lastPageRoute == indexRoot) {
+      if (that.doStartScaning == true) {
+        return;
+      }
+    }
+
+    const time_util = require('./../../utils/time_util');
+    that.doStartScaning = true;
+    var currentMill = time_util.getCurrentMills();
+    var waitMills = 0;
+    var reduce = currentMill - that.requestBlueTime;
+    const delayMills = 6 * 1000;
+    if (reduce > 0 && reduce < delayMills) {
+      waitMills = delayMills - reduce;
+    }
+
+    if (waitMills > 0) {
+      await time_util.delayMills(waitMills);
+    }
+
+    if (callBackConnect == null && lastPageRoute == connectBleRoot) {
+      that.doStartScaning = false;
+      return;
+    }
+
+    wx.openBluetoothAdapter({
+      success: function (res) {
+        wx.stopBluetoothDevicesDiscovery({
+          success: (res) => {
+            that.search(connectWillDevice, boolean, callBackConnect);
+          },
+          fail: (err) => {
+            that.doStartScaning = false;
+            that.requestBlueTime = time_util.getCurrentMills();
+            if (boolean != null) {
+              boolean(false);
+            }
+          }
+        });
+      },
+      fail: function (res) {
+        that.doStartScaning = false;
+        that.requestBlueTime = time_util.getCurrentMills();
+        if (boolean != null) {
+          boolean(false);
+        }
+      }
+    });
+  }
+
+  ///搜索设备
+  search(connectWillDevice, boolean, callBackConnect) {
+    var that = this;
+    const time_util = require('./../../utils/time_util');
+    wx.startBluetoothDevicesDiscovery({
+      allowDuplicatesKey: true,
+      success: function (res) {
+        that.getConnectedDevices();
+        that.doStartScaning = false;
+        that.requestBlueTime = time_util.getCurrentMills();
+        if (boolean != null) {
+          boolean(true);
+        }
+        that.setConnectWillDevice(connectWillDevice);
+        that.setCallBackConnect(callBackConnect);
+        that.compareList = [];
+      },
+      fail(err) {
+        that.doStartScaning = false;
+        that.requestBlueTime = time_util.getCurrentMills();
+        if (boolean != null) {
+          boolean(false);
+        }
+      },
+    });
+  }
+
+  // 停止搜索
+  stopScan() {
+    var that = this;
+    that.setCallBackConnect(null);
+    that.setConnectWillDevice(null);
+    return new Promise((resolve, reject) => {
+      wx.stopBluetoothDevicesDiscovery({
+        success: (res) => {
+          resolve(res);
+        },
+        fail: (err) => {
+          reject('停止搜索失败');
+        }
+      });
+    });
+  }
+
+  ///获取 所有搜索到的蓝牙设备
+  getConnectedDevices() {
+    var that = this;
+    const hex_util = require('./../../utils/hex_util');
+    wx.getBluetoothDevices({
+      success: (res) => {
+        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.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
+              if (that.callBackConnect != null) {
+                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]);
+            }
+          }
+        }
+      },
+      fail: (err) => {
+        console.error('获取蓝牙设备列表失败', err);
+      }
+    });
+  }
+}

+ 60 - 0
utils/blue_ble/util.js

@@ -0,0 +1,60 @@
+const manager = require('./manager');
+module.exports = {
+  BleUtil
+}
+
+class BleUtil {
+  static _instance = new BleUtil();
+  static getInstance() {
+    return BleUtil._instance;
+  }
+
+  constructor() {
+    var that = this;
+    that.manager = new manager();
+  }
+
+  ///获取比较的数据
+  getCompareList() {
+    var that = this;
+    return that.manager.getCompareList();
+  }
+
+  getDissmissDevice() {
+    var that = this;
+    return that.manager.getDissmissDevice();
+  }
+
+  getCallBackConnect() {
+    var that = this;
+    return that.manager.getCallBackConnect();
+  }
+
+  ///初始化蓝牙适配器
+  initBluetoothAdapter() {
+    var that = this;
+    that.manager.initBlueAdapter();
+  }
+
+  ///获取蓝牙设备 connect:true,去连接,false,去对比
+  listenBlueDevices() {
+    var that = this;
+    that.manager.listenBlueDevices();
+  }
+
+  ///搜索蓝牙设备
+  startScan(connectWillDevice, boolean, callBackConnect) {
+    var that = this;
+    that.manager.startScan(
+      connectWillDevice,
+      boolean,
+      callBackConnect,
+    );
+  }
+
+  ///停止搜索蓝牙设备
+  async stopScan() {
+    var that = this;
+    await that.manager.stopScan();
+  }
+}

+ 8 - 0
utils/hex_util.js

@@ -0,0 +1,8 @@
+module.exports = {
+  buf2hex: buf2hex,
+}
+
+///获取数据
+function buf2hex(buffer) {
+  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
+}

+ 17 - 1
utils/time_util.js

@@ -1,7 +1,23 @@
 module.exports = {
-  getGreet: getGreet
+  delayMills: delayMills,
+  getCurrentMills: getCurrentMills,
+  getGreet: getGreet,
 }
 
+// 等待毫秒数
+function delayMills(mills) {
+  return new Promise(resolve => setTimeout(resolve, mills));
+}
+
+///获取毫秒
+function getCurrentMills() {
+  var currentDate = new Date();
+  var currentTimeMillis = currentDate.getTime();
+  // return Math.floor(currentTimeMillis / 1000);
+  return currentTimeMillis;
+}
+
+///获取上午、下午、晚上
 function getGreet() {
   const now = new Date();
   const hour = now.getHours();

+ 1 - 1
utils/util.js

@@ -12,7 +12,7 @@ const urlencodeType = {
   "content-type": "application/x-www-form-urlencoded"
 }
 
-import strings from '../utils/strings.js';
+import strings from './strings.js';
 
 // 错误类型
 let statusCode = {