Browse Source

feature:修改蓝牙设备的掉线监听

zeng.chen 6 months ago
parent
commit
ac5a7a2baa
5 changed files with 123 additions and 46 deletions
  1. 19 7
      devices/ble_manager.js
  2. 6 8
      devices/bt_helper.js
  3. 1 5
      pages/components/navbar/navbar.js
  4. 35 25
      pages/index/index.js
  5. 62 1
      utils/lexin/scan.js

+ 19 - 7
devices/ble_manager.js

@@ -13,6 +13,8 @@ class bleManager {
     that.doStartScaning = false;
     that.compareList = [];
     that.dissmissDevice = [];
+    that.stateChangeCallback = null;
+    that.isConnecting = false;
   }
 
   ///获取比较的数据
@@ -164,7 +166,7 @@ class bleManager {
       }
     });
   }
-  onBLEConnectionStateChange(callback) {
+  onBLEConnectionStateChange() {
     ///监听已连接或没有连接 连接和断开的时候会回调
     // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
     let that = this;
@@ -191,9 +193,8 @@ class bleManager {
       }
       // that.disconnect(result)
       //断开连接是失败的, 只能监听到下线。
-      if (callback != null) {
-        callback(result);
-      }
+      that.errorDisconnect(result);
+
 
       // ///是否已配对
       // wx.isBluetoothDevicePaired({
@@ -271,7 +272,7 @@ class bleManager {
       }
 
       ///做搜索蓝牙适配器权限
-      const permission_util = require('./../utils/permission_util');
+      const permission_util = require('../utils/permission_util');
       var available = await permission_util.openBluetoothAdapter();
       that.isAvailable = available;
       if (!available) {
@@ -422,6 +423,9 @@ class bleManager {
   // 连接到指定设备
   async connectToDevice(device) {
     var that = this;
+    if (that.isConnecting) {
+      return;
+    }
     return new Promise((resolve, reject) => {
       console.log("开始连接蓝牙:", device.deviceId)
       wx.createBLEConnection({
@@ -429,9 +433,11 @@ class bleManager {
         success: (res) => {
           that.publicDevice = device
           console.log('连接成功:', res);
+          that.isConnecting = false;
           resolve(true);
         },
         fail: (err) => {
+          that.isConnecting = false;
           that.publicDevice = null
           console.error('连接失败:', err);
           resolve(false);
@@ -577,7 +583,7 @@ class bleManager {
     });
   }
 
-  connect() {}
+  connect() { }
 
   // 发现特征值 read / write
   discoverCharacteristics(deviceId, serviceId) {
@@ -673,8 +679,14 @@ class bleManager {
     // that.publicDevice .wirte = wirte
     that.publicDevice.characteristicId = characteristicId;
   }
+  setStateChangeCallback(callback) {
+    this.stateChangeCallback = callback;
+  }
   errorDisconnect() {
-    this.disconnect();
+    // this.disconnect();
+    if (this.stateChangeCallback) {
+      this.stateChangeCallback({ "deviceId": this.publicDevice.deviceId, "state": "offline" });
+    }
   }
 }
 // const ble = new bleManager();

+ 6 - 8
devices/bt_helper.js

@@ -91,12 +91,8 @@ class BtHelper {
   initBluetoothAdapter() {
     var that = this;
     that.bleManager.initBluetoothAdapter();
-  }
-
-  onConnectionStateChange(callback) {
-    var that = this;
-    that.bleManager.onBLEConnectionStateChange(function (e) {
-
+    that.bleManager.onBLEConnectionStateChange();
+    that.bleManager.setCallBackConnect(function (e) {
       event_bus.fire(CmdEvent.onoffline({ deviceId: e.deviceId, state: e.connected ? "online" : "offline" }));
     });
   }
@@ -378,14 +374,16 @@ class BtHelper {
 
   async connect(device, onChanged) {
     var that = this;
+    // todo 暂时不掉线
     // await that.disconnect(device);
     clearTimeout(that.timer);
     that.timer = null;
     that.bleManager.stopSearch()
     var res = await that.bleManager.connectToDevice(device);
     if (res === false) {
-      console.log("连接失败")
-      that.disconnect(device)
+      console.log("连接失败了,")
+      // 失败应该不用断开连接
+      // that.disconnect(device)
       if (onChanged) {
         onChanged(false, device)
       }

+ 1 - 5
pages/components/navbar/navbar.js

@@ -10,10 +10,6 @@ Component({
       type: Object,
       value: {},
     },
-    callback: {
-      type: Boolean,
-      value: false
-    },
   },
   externalClasses: ['nav-bgc-class', 'nav-title-class'],
   options: {
@@ -33,7 +29,7 @@ Component({
    */
   methods: {
     _navback() {
-      if (this.properties.callback) {
+      if (this.properties.navbarData.callback) {
         this.triggerEvent('callback',); // 触发确定事件  
         return;
       };

+ 35 - 25
pages/index/index.js

@@ -79,7 +79,7 @@ Page({
     deviceMacId: null,
     deviceListSelect: null,
     deviceList: [],
-    _willConnectBle: true,
+    _willConnectBle: null,
     // deviceList: [{
     //   "connectType": 3,
     //   "devName": "猫王小王子OTR-X",
@@ -235,6 +235,7 @@ Page({
       ///监听蓝牙设备
       BtHelper.getInstance().initBluetoothAdapter();
       BtHelper.getInstance().getBluetoothDevices();
+      BtHelper.getInstance().startScan(null, null, function (res) { });
       var isFirst = true;
       console.log("开始监听蓝牙设备");
       ///再秒再对比一次
@@ -243,7 +244,7 @@ Page({
       that.data.intervalId1 = setInterval(async function () {
         isFirst = false;
         that.compareList();
-        if (count > 3) {
+        if (count > 4) {
           that.stopIntervalId1();
         } else {
           count++;
@@ -254,21 +255,22 @@ Page({
 
   /// 对比蓝牙数据
   compareList() {
-    var that = this;
-    if (that.data.deviceList.length == 1) {
-      let device = that.data.deviceList[0];
-      if (device.state === 'online') {
-        return;
+
+    let that = this;
+    lexin_scan.compareList2(that.data.deviceList, function (device) {
+      if (device) {
+        that.data._willConnectBle = device;
+        getApp().getBluetoothStatus();
       }
-      getApp().getBluetoothStatus();
-      that.data._willConnectBle = true;
-      return;
-    }
-    lexin_scan.compareList(function (list) {
-      that.updateDeviceList(list, false, false);
-    }, function (item) {
-      that.addBlueDevice(item);
+
     });
+
+    // lexin_scan.compareList(function (list) {
+    //   console.log("对比蓝牙数据", list);
+    //   that.updateDeviceList(list, false, false);
+    // }, function (item) {
+    //   that.addBlueDevice(item);
+    // });
   },
   getBluetoothStatusCallck(v) {
     var that = this;
@@ -277,7 +279,7 @@ Page({
       return;
     }
     if (v) {
-      var device = that.data.deviceList[0];
+      var device = that.data._willConnectBle;
       console.log("开始连接设备0", device);
       if (device.state === 'online' || device.connectType != 1) {
         return;
@@ -287,7 +289,7 @@ Page({
         if (isConnected) {
           device.state = 'online';
           that.addBlueDevice(device);
-
+          that.stopIntervalId1();
         } else {
           device.state = 'offline';
         }
@@ -301,7 +303,7 @@ Page({
       //   success: function (res) { }
       // });
     }
-    that.data._willConnectBle = false;
+    that.data._willConnectBle = null;
   },
   // 回调
   mqttCallback(type, option) {
@@ -577,7 +579,7 @@ Page({
     }
 
     ///去蓝牙连接处理
-    if (index === deviceListSelect) {
+    if (index === deviceListSelect && device.state === "online") {
       route_util.jumpParam('/pages/deviceDetail/detail', JSON.stringify(device))
     } else if (device.state === "offline") {
       console.log("去连接蓝牙", device)
@@ -753,9 +755,7 @@ Page({
     event_bus.removeNotification(CmdEvent.eventName, that);
     event_bus.addNotification(CmdEvent.eventName, function (event) {
       if (event.cmdEvent == EnumCmdEvent.onoffline) {
-        if (tmp.connected != false) {
-          return
-        }
+
         let disDevice = that.data.deviceList.find(item => {
           return item.deviceId == event.deviceId
         })
@@ -764,9 +764,19 @@ Page({
 
         //   }
         // });
-        disDevice.state = event.commonValue;
-        console.log("断开连接", disDevice)
-        that.updateDeviceList(that.data.deviceList, false, false);
+        console.log("设备状态变化", disDevice)
+        if (disDevice != null) {
+          disDevice.state = event.commonValue;
+        }
+
+        if (event.commonValue == "online") {
+          // BtHelper.getInstance().connect()
+          console.log("上线连接", disDevice)
+        } else {
+          console.log("断开连接", disDevice)
+          that.updateDeviceList(that.data.deviceList, false, false);
+        }
+
       }
 
     });

+ 62 - 1
utils/lexin/scan.js

@@ -1,5 +1,65 @@
 module.exports = {
   compareList: compareList,
+  compareList2: compareList2,
+}
+
+async function compareList2(deviceList, callback) {
+  let isHasWifi = deviceList.find(item => {
+    return item.connectType == 3;
+  });
+  if (isHasWifi) {
+    //有wifi
+    callback()
+    return;
+  }
+
+  if (deviceList.length == 1) {
+    // 只有一个直接连接
+    let device = deviceList[0];
+    if (device.state === 'online') {
+      return;
+    }
+    getApp().getBluetoothStatus();
+    callback(deviceList[0])
+    return;
+  }
+
+  let hasOnline = deviceList.find(item => {
+    return item.state === 'online';
+  });
+
+  if (hasOnline) {
+    //有在线的
+    callback(hasOnline)
+    return;
+  }
+
+  let index = 0;
+  _startScan(index, deviceList, callback);
+}
+
+function _startScan(index, deviceList, callback) {
+  if (index >= deviceList.length) {
+    callback()
+    return
+  }
+  let element = deviceList[index];
+
+  BtHelper.getInstance().startScan(element, function (boolean) {
+    if (!boolean) {
+      index++;
+      if (index < deviceList.length) {
+        element = deviceList[index];
+        // _startScan(index, deviceList, callback);
+      } else {
+        // callback()
+        // return
+      }
+    }
+  }, function (res) {
+    console.log("自动连接上的", res);
+    callback(res)
+  });
 }
 
 function compareList(changeCallback, addBlueCallback) {
@@ -12,7 +72,8 @@ function compareList(changeCallback, addBlueCallback) {
     if (BtHelper.getInstance().getCallBackConnect() == null) {
       var compareList = BtHelper.getInstance().getCompareList();
       var dissmissDevice = BtHelper.getInstance().getDissmissDevice();
-
+      console.log("compareList", compareList);
+      console.log("dissmissDevice", dissmissDevice);
       ///去掉未连接的离线的
       for (var i = 0; i < dissmissDevice.length; i++) {
         for (var j = 0; j < compareList.length; j++) {