Browse Source

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

zeng.chen 6 months atrás
parent
commit
68976a098b
5 changed files with 95 additions and 33 deletions
  1. 66 12
      devices/ble_manager.js
  2. 9 10
      devices/bt_helper.js
  3. 10 4
      pages/connectBle/connectBle.js
  4. 3 1
      pages/deviceDetail/detail.js
  5. 7 6
      pages/index/index.js

+ 66 - 12
devices/ble_manager.js

@@ -55,11 +55,12 @@ class bleManager {
     });
   }
 
-  ///监听搜索设备列表
+  ///监听搜索设备列表 监听设备列表
   getBluetoothDevices() {
     var that = this;
     const hex_util = require('./../utils/hex_util');
     wx.onBluetoothDeviceFound(function (res) {
+      // console.log("蓝牙设备列表", res.length);
       ///第一种情况
       if (res.deviceId) {
         if (that.callBackConnect != null) {
@@ -104,11 +105,21 @@ class bleManager {
               temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
               temp.mac2 = that.ab2hex(temp.advertisData ?? "")
               // if (that.callBackConnect != null) {
-              console.log("2222:", temp.mac, ":", temp.mac2, ":", temp.deviceId, temp);
-              if (that.callBackConnect != null) {
-                // if (that.callBackConnect != null && (temp.deviceId != "6E:66:C2:CA:74:F8" || temp.deviceId != "1A:B4:E0:40:22:8B")) {
-                that.callBackConnect(temp);
+              // C8:96:D9:51:37:98
+              // 1A:B4:E0:40:22:8B
+              // if (that.callBackConnect != null) {
+              //  || temp.deviceId != "1A:B4:E0:40:22:8B"
+              // A3:7B:97:45:CC:22
+              // DA:D5:FB:DC:91:30
+              if ((temp.deviceId === "1A:B4:E0:40:22:8B")) {
+                return
               }
+              console.log("2222:", temp.mac, ":", temp.mac2, ":", temp.deviceId, temp, temp.connectable);
+
+              // if ((temp.deviceId === "07:F6:F4:66:FB:FA")) {
+              //   that.callBackConnect(temp);
+              // }
+              that.callBackConnect(temp);
               break;
             }
           }
@@ -193,6 +204,7 @@ class bleManager {
       }
       // that.disconnect(result)
       //断开连接是失败的, 只能监听到下线。
+      console.log("监听到设备状态变化:", result);
       that.errorDisconnect(result);
 
 
@@ -212,8 +224,28 @@ class bleManager {
   getConnectedDevices() {
     var that = this;
     const hex_util = require('./../utils/hex_util');
+
+    wx.getConnectedBluetoothDevices({
+      // services: ['ab00'],
+      search: ['ab00', 'ab01', 'ab02', '0000AB00-0000-1000-8000-00805F9B34FB', '0000AB01-0000-1000-8000-00805F9B34FB', '0000AB02-0000-1000-8000-00805F9B34FB'],
+      success: (res) => {
+        // ble连接上,才会有这个返回
+        console.log('根据主服务 UUID 获取已连接的蓝牙设备:', res.devices);
+        if (res.devices.length > 0) {
+          for (var i = 0; i < res.devices.length; i++) {
+            var device = res.devices[i];
+            if (device.name != "") {
+              that.callBackConnect(device);
+            }
+          }
+        }
+      }
+    })
+
     wx.getBluetoothDevices({
       success: (res) => {
+        console.log("搜索到的:" + res.length);
+
         if (that.callBackConnect != null) {
           for (var i = 0; i < res.devices.length; i++) {
             var temp = res.devices[i];
@@ -224,8 +256,16 @@ class bleManager {
               }
               // if (that.callBackConnect != null) {
               if (that.callBackConnect != null) {
-                // if (that.callBackConnect != null && temp.mac.includes("CF:CA")) {
+                if ((temp.deviceId === "1A:B4:E0:40:22:8B")) {
+                  return
+                }
+                console.log("444:" + JSON.stringify(temp));
+
+                // if ((temp.deviceId === "07:F6:F4:66:FB:FA")) {
+                //   that.callBackConnect(temp);
+                // }
                 that.callBackConnect(temp);
+
               }
               break;
             }
@@ -424,8 +464,10 @@ class bleManager {
   async connectToDevice(device) {
     var that = this;
     if (that.isConnecting) {
+      // 防止多次进入连接
       return;
     }
+    that.isConnecting = true
     return new Promise((resolve, reject) => {
       console.log("开始连接蓝牙:", device.deviceId)
       wx.createBLEConnection({
@@ -437,8 +479,14 @@ class bleManager {
           resolve(true);
         },
         fail: (err) => {
-          that.isConnecting = false;
-          that.publicDevice = null
+          // {errno: 1509007, errCode: -1, errMsg: "createBLEConnection:fail:already connect"}
+          if (err.errno == 1509007) {
+            that.disconnect({ "deviceId": device.deviceId })
+          } else {
+            that.isConnecting = false;
+            that.errorDisconnect()
+            that.publicDevice = null
+          }
           console.error('连接失败:', err);
           resolve(false);
         }
@@ -474,6 +522,7 @@ class bleManager {
         characteristicId: that.publicDevice.characteristicId,
         value: buffer,
         success: (res) => {
+          console.log('发送数据成功:', res, callback);
           if (callback) {
             callback(true)
           }
@@ -567,14 +616,18 @@ class bleManager {
             service_id = res.services[i].uuid;
 
           }
-          that.publicDevice.serviceId = service_id;
-          console.log('发现服务2:', service_id);
+          if (that.publicDevice) {
+            that.publicDevice.serviceId = service_id;
+            console.log('发现服务2:', that.publicDevice.service_id);
+          }
 
           resolve(service_id);
           // resolve(res.services);
         },
         fail: (err) => {
-          that.publicDevice.serviceId = null;
+          if (that.publicDevice) {
+            that.publicDevice.serviceId = null;
+          }
 
           console.error('发现服务失败:', err);
           reject([]);
@@ -685,7 +738,8 @@ class bleManager {
   errorDisconnect() {
     // this.disconnect();
     if (this.stateChangeCallback) {
-      this.stateChangeCallback({ "deviceId": this.publicDevice.deviceId, "state": "offline" });
+      let device = this.publicDevice ?? {};
+      this.stateChangeCallback({ "deviceId": device.deviceId ?? "", "state": "offline" });
     }
   }
 }

+ 9 - 10
devices/bt_helper.js

@@ -92,7 +92,7 @@ class BtHelper {
     var that = this;
     that.bleManager.initBluetoothAdapter();
     that.bleManager.onBLEConnectionStateChange();
-    that.bleManager.setCallBackConnect(function (e) {
+    that.bleManager.setStateChangeCallback(function (e) {
       event_bus.fire(CmdEvent.onoffline({ deviceId: e.deviceId, state: e.connected ? "online" : "offline" }));
     });
   }
@@ -113,12 +113,6 @@ class BtHelper {
     );
   }
 
-  ///停止搜索蓝牙设备
-  async stopSearch() {
-    var that = this;
-    await that.bleManager.stopSearch();
-  }
-
   ///获取蓝牙权限
   async getBluetoothPermission() {
     var that = this;
@@ -362,6 +356,7 @@ class BtHelper {
   }
 
   async stopSearch() {
+    console.log("停止搜索0");
     clearTimeout(this.timer);
     this.timer = null;
     await this.bleManager.stopSearch();
@@ -375,12 +370,14 @@ class BtHelper {
   async connect(device, onChanged) {
     var that = this;
     // todo 暂时不掉线
-    // await that.disconnect(device);
+    await that.disconnect(device);
     clearTimeout(that.timer);
     that.timer = null;
     that.bleManager.stopSearch()
+    console.log("停止搜索1");
+
     var res = await that.bleManager.connectToDevice(device);
-    if (res === false) {
+    if (res != true) {
       console.log("连接失败了,")
       // 失败应该不用断开连接
       // that.disconnect(device)
@@ -390,9 +387,10 @@ class BtHelper {
       return
     }
 
+    console.log("连接成功了", res)
     const serviceId = await that.bleManager.discoverServices(device.deviceId);
     if (serviceId == "") {
-      console.log("连接失败")
+      console.log("服务连接失败")
       that.disconnect(device)
       if (onChanged) {
         onChanged(false, device)
@@ -788,6 +786,7 @@ class BtHelper {
   async closeBle() {
     var that = this;
     that.bleManager.closeBle();
+    console.log("停止搜索3");
     await that.bleManager.stopSearch();
   }
 

+ 10 - 4
pages/connectBle/connectBle.js

@@ -21,14 +21,18 @@ Page({
   onLoad(options) {
     var that = this;
     var json = JSON.parse(options.param)
-    console.log("要连接设备:", json)
 
     BtHelper.getInstance().initBluetoothAdapter();
     BtHelper.getInstance().getBluetoothDevices();
 
-    that.setData({
-      connectDevice: json
-    });
+
+    if (json) {
+      that.data.connectDevice = json;
+      that.setData({
+        connectDevice: json
+      });
+    }
+
     that.startSearch();
   },
 
@@ -37,6 +41,7 @@ Page({
     var that = this;
     that.setStatus(0);
     var connectDevice = that.data.connectDevice;
+    console.log("要连接设备:", connectDevice)
     BtHelper.getInstance().startScan(connectDevice,
       async function (b) {
         if (!b) {
@@ -45,6 +50,7 @@ Page({
       },
       async function (res) {
         await BtHelper.getInstance().stopSearch();
+        console.log("搜索到设备11:", res);
         that.setStatus(2);
         that.data.connectDevice.deviceId = res.deviceId;
         that.data.connectDevice.connectable = res.connectable;

+ 3 - 1
pages/deviceDetail/detail.js

@@ -112,7 +112,9 @@ Page({
         case EnumCmdEvent.onoffline:
           console.log("详情页3:")
           //目前只有下线
-          _this.data.device.state = event.commonValue
+          if (event.deviceId === _this.data.device.deviceId) {
+            _this.data.device.state = event.commonValue
+          }
           break;
       }
     }, this)

+ 7 - 6
pages/index/index.js

@@ -756,24 +756,25 @@ Page({
     event_bus.addNotification(CmdEvent.eventName, function (event) {
       if (event.cmdEvent == EnumCmdEvent.onoffline) {
 
+        console.log("首页ble通知:", event.deviceId)
         let disDevice = that.data.deviceList.find(item => {
           return item.deviceId == event.deviceId
         })
         // that.data.deviceList.forEach(element => {
         //   if (item.deviceId == tmp.deviceId) {
-
         //   }
         // });
-        console.log("设备状态变化", disDevice)
-        if (disDevice != null) {
-          disDevice.state = event.commonValue;
+        if (!disDevice) {
+          return;
         }
+        console.log("首页设备状态变化", disDevice)
+        disDevice.state = event.commonValue;
 
         if (event.commonValue == "online") {
           // BtHelper.getInstance().connect()
-          console.log("上线连接", disDevice)
+          console.log("首页上线连接", disDevice)
         } else {
-          console.log("断开连接", disDevice)
+          console.log("首页断开连接", disDevice)
           that.updateDeviceList(that.data.deviceList, false, false);
         }