浏览代码

feature: 处理路由两处搜索兼容问题

Damon 8 月之前
父节点
当前提交
39eafa9001
共有 7 个文件被更改,包括 124 次插入68 次删除
  1. 1 9
      app.js
  2. 82 12
      devices/ble_manager.js
  3. 4 22
      devices/bt_helper.js
  4. 12 18
      pages/connectBle/connectBle.js
  5. 15 7
      pages/index/index.js
  6. 2 0
      utils/route_constant.js
  7. 8 0
      utils/route_util.js

+ 1 - 9
app.js

@@ -1,7 +1,3 @@
-// app.ts
-import {
-  BtHelper
-} from './devices/bt_helper';
 import mqtt from './utils/mqtt';
 import update from './utils/update';
 import strings from './utils/strings';
@@ -280,11 +276,7 @@ App({
       }
     })
   },
-  onUnload() {
-    console.log("小程序销毁")
-    btHelper = BtHelper.getInstance()
-    btHelper.disconnect()
-  },
+
 })
 
 

+ 82 - 12
devices/ble_manager.js

@@ -10,6 +10,9 @@ class bleManager {
     that.compareList = [];
     that.connectWillDevice = null;
     that.callBackConnect = null;
+    that.requestBlueTime = 0;
+    ///正在执行扫描中
+    that.doStartScaning = false;
   }
 
   ///获取比较的数据
@@ -17,10 +20,6 @@ class bleManager {
     return this.compareList;
   }
 
-  getConnectWillDevice() {
-    return this.connectWillDevice;
-  }
-
   setConnectWillDevice(connectWillDevice) {
     this.connectWillDevice = connectWillDevice;
   }
@@ -137,26 +136,93 @@ class bleManager {
     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));
+  }
+
+
+
   // 开始搜索蓝牙设备
-  startScan(boolean) {
+  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) {},
+              success: function (res) {
+                that.doStartScaning = false;
+              },
               fail(err) {
-                boolean(false);
+                that.doStartScaning = false;
+                if (boolean != null) {
+                  boolean(false);
+                }
               },
             })
             wx.startBluetoothDevicesDiscovery({
               allowDuplicatesKey: false,
               success: function (res) {
-                boolean(true);
+                that.doStartScaning = false;
+                that.requestBlueTime = that.getCurrentMills();
+                if (boolean != null) {
+                  boolean(true);
+                }
+                that.setConnectWillDevice(connectWillDevice);
+                that.setCallBackConnect(callBackConnect);
                 that.compareList = [];
               },
-              fail(err) {},
+              fail(err) {
+                that.doStartScaning = false;
+                that.requestBlueTime = that.getCurrentMills();
+                if (boolean != null) {
+                  boolean(false);
+                }
+              },
             })
           },
           fail: function (res) {
@@ -166,7 +232,10 @@ class bleManager {
               showCancel: false,
               success: function (res) {}
             });
-            boolean(false);
+            that.doStartScaning = false;
+            if (boolean != null) {
+              boolean(false);
+            }
           }
         })
       }
@@ -175,14 +244,15 @@ class bleManager {
 
   // 停止搜索
   stopSearch() {
+    var that = this;
+    that.setCallBackConnect(null);
+    that.setConnectWillDevice(null);
     return new Promise((resolve, reject) => {
       wx.stopBluetoothDevicesDiscovery({
         success: (res) => {
-          console.log('停止搜索成功:', res);
           resolve(res);
         },
         fail: (err) => {
-          console.error('停止搜索失败:', err);
           reject(new Error('停止搜索失败'));
         }
       });

+ 4 - 22
devices/bt_helper.js

@@ -78,22 +78,10 @@ class BtHelper {
     return this.bleManager.getCompareList();
   }
 
-  getConnectWillDevice() {
-    return this.bleManager.connectWillDevice;
-  }
-
-  setConnectWillDevice(connectWillDevice) {
-    this.bleManager.setConnectWillDevice(connectWillDevice);
-  }
-
   getCallBackConnect() {
     return this.bleManager.getCallBackConnect();
   }
 
-  setCallBackConnect(callBackConnect) {
-    this.bleManager.setCallBackConnect(callBackConnect);
-  }
-
   ///初始化蓝牙适配器
   initBluetoothAdapter() {
     var that = this;
@@ -107,12 +95,12 @@ class BtHelper {
   }
 
   ///搜索蓝牙设备
-  startScan(boolean) {
+  startScan(connectWillDevice, boolean, callBackConnect) {
     var that = this;
     that.bleManager.startScan(
-      function (b) {
-        boolean(b);
-      }
+      connectWillDevice,
+      boolean,
+      callBackConnect,
     );
   }
 
@@ -133,12 +121,6 @@ class BtHelper {
     await this.bleManager.disconnect()
   }
 
-  ///获取所有在线连接过的设备
-  getAllOnlineDevices(callBack) {
-    var that = this;
-    that.bleManager.getAllOnlineDevices(callBack);
-  }
-
   handleCommand(event, mDevice) {
     let name = event.cmdEvent;
     switch (name) {

+ 12 - 18
pages/connectBle/connectBle.js

@@ -1,5 +1,3 @@
-// pages/connectBle/connectBle.js
-const app = getApp();
 const {
   BtHelper
 } = require('../../devices/bt_helper');
@@ -32,15 +30,6 @@ Page({
     that.setData({
       connectDevice: json
     });
-
-    ///准备连接的设备
-    BtHelper.getInstance().setConnectWillDevice(that.data.connectDevice);
-    BtHelper.getInstance().setCallBackConnect(function (res) {
-      that.setStatus(2);
-      BtHelper.getInstance().stopSearch();
-      that.data.connectDevice.deviceId = res.deviceId;
-      that.data.connectDevice.connectable = res.connectable;
-    });
     that.startSearch();
   },
 
@@ -48,14 +37,21 @@ Page({
   async startSearch() {
     var that = this;
     that.setStatus(0);
-    ///搜索到对应的设备
     await BtHelper.getInstance().stopSearch();
     BtHelper.getInstance().startScan(
-      function (b) {
-        if (!b) {
-          that.setStatus(1);
+      that.data.connectDevice,
+      async function (b) {
+          if (!b) {
+            await BtHelper.getInstance().stopSearch();
+            that.setStatus(1);
+          }
+        },
+        async function (res) {
+          await BtHelper.getInstance().stopSearch();
+          that.setStatus(2);
+          that.data.connectDevice.deviceId = res.deviceId;
+          that.data.connectDevice.connectable = res.connectable;
         }
-      },
     );
   },
 
@@ -156,8 +152,6 @@ Page({
 
   ///关闭界面时候触发
   onUnload: function () {
-    BtHelper.getInstance().setConnectWillDevice(null);
-    BtHelper.getInstance().setCallBackConnect(null);
     BtHelper.getInstance().stopSearch();
   }
 })

+ 15 - 7
pages/index/index.js

@@ -138,13 +138,18 @@ Page({
     ///监听蓝牙设备
     BtHelper.getInstance().getBluetoothDevices();
     ///3秒去处理一下
-    that.compareList();
-    that.data.intervalId = setInterval(async function () {
+    BtHelper.getInstance().startScan(null, null, null);
+    ///先接收数据
+    setTimeout(() => {
       that.compareList();
+      ///再秒再对比一次
+      that.data.intervalId = setInterval(async function () {
+        that.compareList();
+      }, 10 * 1000);
     }, 3 * 1000);
   },
 
-  compareList() {
+  async compareList() {
     var that = this;
     if (BtHelper.getInstance().getCallBackConnect() == null) {
       var compareList = BtHelper.getInstance().getCompareList();
@@ -171,10 +176,7 @@ Page({
           that.updateDeviceList(tempList, false);
         }
       }
-      // await BtHelper.getInstance().stopSearch();
-      BtHelper.getInstance().startScan(
-        function (b) {},
-      );
+      BtHelper.getInstance().startScan(null, null, null);
     }
   },
 
@@ -547,6 +549,7 @@ Page({
   },
 
   onUnload() {
+    var that = this;
     if (!strings.isEmpty(that.data.intervalId)) {
       clearInterval(that.data.intervalId);
       that.data.intervalId = null;
@@ -991,6 +994,11 @@ Page({
       wx.setStorageSync("homeBanner", res);
     })
   },
+
+  ///销毁蓝牙
+  onUnload() {
+    BtHelper.getInstance().disconnect();
+  }
 })
 
 // 去掉此功能,先留着吧

+ 2 - 0
utils/route_constant.js

@@ -1,6 +1,7 @@
 ///路由
 const indexRoot = "pages/index/index";
 const loginRoot = "pages/login/login";
+const connectBleRoot = "pages/connectBle/connectBle";
 
 const index = "../index/index";
 ///登录界面
@@ -15,6 +16,7 @@ module.exports = {
   ///路由
   indexRoot: indexRoot,
   loginRoot: loginRoot,
+  connectBleRoot: connectBleRoot,
 
   ///跳转路径
   index: index,

+ 8 - 0
utils/route_util.js

@@ -1,4 +1,5 @@
 module.exports = {
+  getLastPageRoute: getLastPageRoute,
   goBackHomePage: goBackHomePage,
   goBackRoute: goBackRoute,
   jump: jump,
@@ -7,6 +8,13 @@ module.exports = {
   redirectTo: redirectTo,
 }
 
+///获取最后一个界面的路由名称
+function getLastPageRoute() {
+  const pages = getCurrentPages();
+  const currentPage = pages[pages.length - 1];
+  return currentPage.route;
+};
+
 ///跳转,不摧毁界面
 async function jump(url) {
   await wx.navigateTo({