Pārlūkot izejas kodu

feature: 无限次连接蓝牙处理

Damon 8 mēneši atpakaļ
vecāks
revīzija
b9fbbf3b66
5 mainītis faili ar 225 papildinājumiem un 455 dzēšanām
  1. 1 15
      app.json
  2. 122 286
      devices/ble_manager.js
  3. 35 35
      devices/bt_helper.js
  4. 67 93
      pages/connectBle/connectBle.js
  5. 0 26
      pages/index/index.js

+ 1 - 15
app.json

@@ -41,20 +41,6 @@
     "getFuzzyLocation"
   ],
 
-  "deviceOrientation": "portrait",
-  "permission": {
-    "scope.userLocation": {
-      "desc": "你的旧版本的位置信息将用于小程序位置接口的效果展示"
-    },
-    "scope.userFuzzyLocation": {
-      "desc": "你的模糊位置信息将用于小程序位置接口的效果展示"
-    },
-    "scope.bluetooth": {
-      "desc": "需要蓝牙进行连接手柄"
-    },
-    "scope.userInfo": {
-      "desc": "需要用户同意授权隐私信息,确保蓝牙功能可用"
-    }
-  }
+  "deviceOrientation": "portrait"
 
 }

+ 122 - 286
devices/ble_manager.js

@@ -6,176 +6,86 @@ class bleManager {
     that.isAvailable = false;
     that.hasPermission = false;
     that.scanDevices = [];
-    that.device = null;
+    that.publicDevice = null;
   }
 
-  // 初始化蓝牙适配器
+  /// 监控蓝牙打开状态
   initBluetoothAdapter() {
-    var that = this
-    wx.openBluetoothAdapter({
-      success: (res) => {
-        that.isAvailable = true;
-      },
-      fail: (err) => {
-        that.isAvailable = false;
-      }
-    });
+    var that = this;
     wx.onBluetoothAdapterStateChange(function (res) {
       that.isAvailable = res.available;
     })
   }
 
-  // 获取蓝牙权限
-  async getBluetoothPermission() {
+  ///监听搜索设备列表
+  getBluetoothDevices(callBack) {
     var that = this;
-    console.log("gadsfasdfqwwerqewrqr");
-    return new Promise((resolve, reject) => {
-      wx.getSetting({
-        success(res) {
-          if (res.authSetting["scope.bluetooth"]) {
-            that.hasPermission = true;
-            getApp().globalData.scopeBluetooth = true;
-            resolve(true);
-          } else if (res.authSetting["scope.bluetooth"] === undefined) {
-            that.hasPermission = false;
-            getApp().globalData.scopeBluetooth = false;
-            resolve(false);
-            wx.authorize({
-              scope: "scope.bluetooth",
-              complete() {
-                that.getBluetoothPermission()
-              }
-            });
-          } else {
-            that.hasPermission = false;
-            that.globalData.scopeBluetooth = false;
-            wx.showModal({
-              title: '请打开系统蓝牙进行配网',
-              content: '如已打开蓝牙仍然弹框,请尝试重启小程序',
-              success(res) {
-                if (res.confirm) {
-                  console.log('用户点击确定')
-                  wx.openSetting({
-                    complete() {}
-                  })
-                } else if (res.cancel) {
-                  console.log('用户点击取消')
-                }
-              }
-            });
-            resolve(false);
-          };
-        },
-        fail(err) {
-          resolve(false);
+    wx.onBluetoothDeviceFound(function (res) {
+      ///第一种情况
+      if (res.deviceId) {
+        if (res.name == getApp().globalData.connectWillDevice.clientType) {
+          res.advertisData = res.advertisData ? that.buf2hex(res.advertisData) : '';
+          callBack(res);
         }
-      });
-    });
-  }
-
-  ///获取定位权限
-  async getLocalSetting() {
-    var that = this;
-    return new Promise((resolve, reject) => {
-      wx.getSetting({
-        success(res) {
-          if (res.authSetting["scope.userLocation"]) {
-            resolve(true);
-          } else if (res.authSetting["scope.userLocation"] === undefined) {
-            wx.authorize({
-              scope: "scope.userLocation",
-              success() {
-                resolve(that.getLocalSetting());
-              }
-            });
-          } else {
-            wx.showModal({
-              title: '请打开系统位置获取定位权限',
-              success(res) {
-                if (res.confirm) {
-                  wx.openSetting({
-                    complete() {}
-                  })
-                } else if (res.cancel) {}
-              }
-            })
-            reject(false);
+      }
+      ///第二种情况
+      else if (res.devices) {
+        for (var i = 0; i < res.devices.length; i++) {
+          var temp = res.devices[i];
+          if (temp.name == getApp().globalData.connectWillDevice.clientType) {
+            temp.advertisData = temp.advertisData ? that.buf2hex(temp.advertisData) : '';
+            callBack(temp);
+            break;
           }
-        },
-        fail(err) {
-          reject(false);
         }
-      });
+      }
+      ///第三种情况
+      else if (res[0]) {
+        if (res[0].name == getApp().globalData.connectWillDevice.clientType) {
+          res[0].advertisData = res[0].advertisData ? that.buf2hex(res[0].advertisData) : '';
+          callBack(res[0]);
+        }
+      }
     });
   }
 
-  // 开始搜索蓝牙设备
-  async startScan(callBack, boolean) {
-    var that = this;
-    if (!that.isAvailable) {
-      wx.showToast({
-        title: '请打开蓝牙',
-        icon: 'none',
-        duration: 2000
-      });
-      boolean(false);
-      return;
-    }
-
-    var open = await that.getLocalSetting();
-    if (!open) {
-      wx.showToast({
-        title: '请打开定位权限',
-        icon: 'none',
-        duration: 2000
-      });
-      boolean(false);
-      return;
-    }
+  ///获取数据
+  buf2hex(buffer) {
+    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
+  }
 
-    ///没有权限再获取
-    if (!that.hasPermission) {
-      var per = await that.getBluetoothPermission();
-      if (!per) {
-        wx.showToast({
-          title: '请打开蓝牙权限',
-          icon: 'none',
-          duration: 2000
-        });
-        boolean(false);
-        return;
-      }
-    }
-    // services: ["ffc0", "ab00", "ffe5"],
-    wx.startBluetoothDevicesDiscovery({
-      allowDuplicatesKey: true,
-      success: (res) => {
-        if (res) {
-          console.log("gadsfasdfqwerqwerdfasdfqr==000===");
-          wx.onBluetoothDeviceFound((devicesRes) => {
-            for (var i = 0; i < devicesRes.devices.length; i++) {
-              if (devicesRes.devices[i].name != "") {
-                if (devicesRes.devices[i].name === getApp().globalData.connectWillDevice.clientType) {
-                  console.log("gadsfasdfqwerqwerdfasdfqr=====" + devicesRes.devices[i].name);
-                  callBack(devicesRes.devices[i]);
-                  break;
-                }
-              }
-            }
-          });
-        }
-      },
-      fail: (err) => {
-        if (err.errno == 1509008) {
-          wx.showToast({
-            title: '搜索蓝牙需要先开启定位权限',
-            icon: 'none',
-            duration: 2000
-          });
-        }
-        boolean(false);
+  // 开始搜索蓝牙设备
+  startScan(boolean) {
+    wx.closeBluetoothAdapter({
+      complete: function (res) {
+        wx.openBluetoothAdapter({
+          success: function (res) {
+            wx.getBluetoothAdapterState({
+              success: function (res) {},
+              fail(err) {
+                boolean(false);
+              },
+            })
+            wx.startBluetoothDevicesDiscovery({
+              allowDuplicatesKey: false,
+              success: function (res) {
+                boolean(true);
+              },
+              fail(err) {},
+            })
+          },
+          fail: function (res) {
+            wx.showModal({
+              title: '提示',
+              content: '请检查手机蓝牙是否打开',
+              showCancel: false,
+              success: function (res) {}
+            });
+            boolean(false);
+          }
+        })
       }
-    });
+    })
   }
 
   // 停止搜索
@@ -194,117 +104,25 @@ class bleManager {
     });
   }
 
-  ///获取已经连接过手机的设备
-  async getAllOnlineDevices(callBack) {
-    var that = this;
-    if (!that.isAvailable) {
-      setTimeout(() => {
-        that.getAllOnlineDevices(callBack);
-      }, 3 * 1000);
-      return;
-    }
-
-    if (!that.hasPermission) {
-      var per = await that.getBluetoothPermission();
-      if (!per) {
-        setTimeout(() => {
-          that.getAllOnlineDevices(callBack);
-        }, 3 * 1000);
-        return;
-      }
-    }
-
-    that.getConnectedDevices();
-    wx.getBluetoothDevices({
-      success: (res) => {
-        // && res.devices.length > 0
-        if (res) {
-          callBack(res.devices);
-        }
-        setTimeout(() => {
-          that.getAllOnlineDevices(callBack);
-        }, 3 * 1000);
-      },
-      fail: (err) => {
-        setTimeout(() => {
-          that.getAllOnlineDevices();
-        }, 3 * 1000);
-      }
-    });
-  }
-
-  // 获取已连接的蓝牙设备
-  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([]);
-        }
-      });
-    });
-  }
-
-  // 获取获取在蓝牙模块生效期间所有搜索到的蓝牙设备。包括已经和本机处于连接状态的设备。
-  getAllConnectedDevices() {
-    var that = this;
-    if (!that.isAvailable && !that.hasPermission) {
-      return [];
-    }
-
-    return new Promise((resolve, reject) => {
-      wx.getBluetoothDevices({
-        success: (res) => {
-          let newDevices = that.fiterDevice(res)
-          resolve(newDevices);
-        },
-        fail: (err) => {
-          console.error('已扫描过的蓝牙设备失败:', err);
-          reject([]);
-        }
-      });
-    });
-  }
-
   closeBle() {
     console.log('关闭蓝牙了')
-    wx.closeBluetoothAdapter();
+    closeBluetoothAdapter();
   }
 
   // 断开与指定设备的连接
   disconnect() {
     var that = this;
-    let device = that.device ?? {};
+    let device = that.publicDevice ?? {};
     let deviceId = device.deviceId ?? ""
     if (deviceId.length === 0) {
       return;
     }
+
     return new Promise((resolve, reject) => {
       wx.closeBLEConnection({
-        deviceId: that.device.deviceId ?? "",
+        deviceId: that.publicDevice.deviceId ?? "",
         success: (res) => {
-          that.device = null;
+          that.publicDevice = null;
           console.log('断开连接成功:', res);
           resolve(res);
         },
@@ -335,9 +153,9 @@ class bleManager {
 
       console.log('开始发送数据:', data, buffer);
       wx.writeBLECharacteristicValue({
-        deviceId: that.device.deviceId,
-        serviceId: that.device.serviceId,
-        characteristicId: that.device.characteristicId,
+        deviceId: that.publicDevice.deviceId,
+        serviceId: that.publicDevice.serviceId,
+        characteristicId: that.publicDevice.characteristicId,
         value: buffer,
         success: (res) => {
           // console.log('数据发送成功:');
@@ -351,23 +169,6 @@ class bleManager {
     });
   }
 
-  // 监听发现新设备的事件
-  onBluetoothDeviceFound(callback) {
-    var that = this;
-    wx.onBluetoothDeviceFound((res) => {
-      let newDevices = that.fiterDevice(res)
-      // that.devices.push(...devices);
-      if (newDevices.length > 0) {
-        // console.log('发现设备1:', res);
-      }
-      if (callback) {
-        callback(newDevices);
-      }
-    });
-  }
-  getMac() {
-
-  }
   ab2hex(buffer) {
     var hexArr = Array.prototype.map.call(
       new Uint8Array(buffer),
@@ -377,6 +178,7 @@ class bleManager {
     )
     return hexArr.join(':');
   }
+
   fiterDevice(res) {
     var that = this;
     var devices = res.devices.filter(device => {
@@ -428,12 +230,12 @@ class bleManager {
       wx.createBLEConnection({
         deviceId: device.deviceId,
         success: (res) => {
-          that.device = device
+          that.publicDevice = device
           console.log('连接成功:', res);
           resolve(true);
         },
         fail: (err) => {
-          that.device = null
+          that.publicDevice = null
           console.error('连接失败:', err);
           resolve(false);
         }
@@ -449,7 +251,7 @@ class bleManager {
       wx.getBLEDeviceServices({
         deviceId: deviceId,
         success: (res) => {
-          // that.device.services = res.services;
+          // 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 ||
@@ -463,14 +265,14 @@ class bleManager {
             service_id = res.services[i].uuid;
 
           }
-          that.device.serviceId = service_id;
+          that.publicDevice.serviceId = service_id;
           console.log('发现服务2:', service_id);
 
           resolve(service_id);
           // resolve(res.services);
         },
         fail: (err) => {
-          that.device.serviceId = null;
+          that.publicDevice.serviceId = null;
 
           console.error('发现服务失败:', err);
           reject([]);
@@ -483,7 +285,7 @@ class bleManager {
   discoverCharacteristics(deviceId, serviceId) {
     var that = this;
     console.log('发现特征值:' + deviceId + " ,  " + serviceId);
-    // if (deviceId !== that.device.deviceId) {
+    // if (deviceId !== that.publicDevice .deviceId) {
     //     console.log('设备id不匹配')
     //     return false
     // }
@@ -494,11 +296,11 @@ class bleManager {
         success: (res) => {
           // that.characteristics[serviceId] = res.characteristics;
           console.log('发现特征值2:', res);
-          // that.device.characteristics = res.characteristics;
+          // that.publicDevice .characteristics = res.characteristics;
           resolve(res.characteristics);
         },
         fail: (err) => {
-          that.device.characteristics = null;
+          that.publicDevice.characteristics = null;
           console.error('发现特征值失败:', err);
           reject("");
         }
@@ -512,8 +314,8 @@ class bleManager {
     console.log('开始读取特征值', characteristicId)
     return new Promise((resolve, reject) => {
       wx.readBLECharacteristicValue({
-        deviceId: that.device.deviceId,
-        serviceId: that.device.serviceId,
+        deviceId: that.publicDevice.deviceId,
+        serviceId: that.publicDevice.serviceId,
         characteristicId: characteristicId,
         success: (res) => {
           const name = that.parseBLEValue(res.value); // 解析读取到的值
@@ -531,13 +333,14 @@ class bleManager {
   parseBLEValue(buffer) {
     return String.fromCharCode.apply(null, new Uint8Array(buffer));
   }
+
   // 监听特征值变化
   notifyCharacteristicValueChange(characteristicId, callback) {
     var that = this;
-    console.log('监听特征值变化:', characteristicId, that.device.deviceId, that.device.serviceId);
+    console.log('监听特征值变化:', characteristicId, that.publicDevice.deviceId, that.publicDevice.serviceId);
     wx.notifyBLECharacteristicValueChange({
-      deviceId: that.device.deviceId, //设备mac   IOS和安卓系统不一样
-      serviceId: that.device.serviceId, //服务通道,这里主要是notify
+      deviceId: that.publicDevice.deviceId, //设备mac   IOS和安卓系统不一样
+      serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
       characteristicId: characteristicId, //notify uuid
       state: true,
       success: function (res) {
@@ -569,8 +372,8 @@ class bleManager {
   setWrite(wirte, characteristicId) {
     var that = this;
     console.log('写入特征值:', characteristicId)
-    // that.device.wirte = wirte
-    that.device.characteristicId = characteristicId;
+    // that.publicDevice .wirte = wirte
+    that.publicDevice.characteristicId = characteristicId;
   }
 }
 // const ble = new bleManager();
@@ -614,4 +417,37 @@ module.exports = bleManager;
 //       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([]);
+//       }
+//     });
+//   });
+// }

+ 35 - 35
devices/bt_helper.js

@@ -79,19 +79,18 @@ class BtHelper {
     that.bleManager.initBluetoothAdapter();
   }
 
-  ///获取蓝牙权限
-  async getBluetoothPermission() {
+  ///获取蓝牙设备
+  getBluetoothDevices(callBack) {
     var that = this;
-    await that.bleManager.getBluetoothPermission();
+    that.bleManager.getBluetoothDevices(function (res) {
+      callBack(res);
+    });
   }
 
   ///搜索蓝牙设备
-  search(callBack, boolean) {
+  startScan(boolean) {
     var that = this;
     that.bleManager.startScan(
-      function (c) {
-        callBack(c);
-      },
       function (b) {
         boolean(b);
       }
@@ -99,11 +98,22 @@ class BtHelper {
   }
 
   ///停止搜索蓝牙设备
-  stopSearch() {
+  async stopSearch() {
     var that = this;
     await that.bleManager.stopSearch();
   }
 
+  ///获取蓝牙权限
+  async getBluetoothPermission() {
+    var that = this;
+    await that.bleManager.getBluetoothPermission();
+  }
+
+  ///断开设备连接
+  async disconnect() {
+    await this.bleManager.disconnect()
+  }
+
   ///获取所有在线连接过的设备
   getAllOnlineDevices(callBack) {
     var that = this;
@@ -341,11 +351,6 @@ class BtHelper {
     // BtHelper._isConnecting = connect;
   }
 
-  async findDevices(callback) {
-    this.bleManager.onBluetoothDeviceFound(callback)
-    // return await this._helper.search();
-  }
-
   async stopSearch() {
     clearTimeout(this.timer);
     this.timer = null;
@@ -385,7 +390,6 @@ class BtHelper {
     }
     // this.setData({ services });
     console.log("服务ID:" + serviceId)
-
     var characteristics = await this.bleManager.discoverCharacteristics(data.deviceId, serviceId)
     if (characteristics == "") {
       console.log("连接失败")
@@ -432,10 +436,6 @@ class BtHelper {
 
   }
 
-  async disconnect() {
-    this.bleManager.disconnect()
-  }
-
   async dispose() {
     // await this._helper.dispose();
   }
@@ -457,23 +457,23 @@ class BtHelper {
   //     this.initBluetooth();
   //   }
 
-  async getConnectedDevices() {
-    var that = this;
-    try {
-      const connectedDevices = await that.bleManager.getConnectedDevices();
-      console.log("全部设备1:", connectedDevices)
-      if (connectedDevices.length) {
-        // todo 已经连接上的设备
-      }
-      const allDevices = await that.bleManager.getAllConnectedDevices()
-      console.log("全部设备2:", allDevices)
-      let newDevices = connectedDevices.concat(allDevices);
-      return newDevices
-    } catch (error) {
-      console.error(error);
-      return []
-    }
-  }
+  // async getConnectedDevices() {
+  //   var that = this;
+  //   try {
+  //     const connectedDevices = await that.bleManager.getConnectedDevices();
+  //     console.log("全部设备1:", connectedDevices)
+  //     if (connectedDevices.length) {
+  //       // todo 已经连接上的设备
+  //     }
+  //     const allDevices = await that.bleManager.getAllConnectedDevices()
+  //     console.log("全部设备2:", allDevices)
+  //     let newDevices = connectedDevices.concat(allDevices);
+  //     return newDevices
+  //   } catch (error) {
+  //     console.error(error);
+  //     return []
+  //   }
+  // }
 
   async checkDevice() {
     var that = this;

+ 67 - 93
pages/connectBle/connectBle.js

@@ -32,25 +32,29 @@ Page({
     that.setData({
       connectDevice: json
     });
+
     ///准备连接的设备
     app.globalData.connectWillDevice = that.data.connectDevice;
+    BtHelper.getInstance().getBluetoothDevices(function (res) {
+      that.setStatus(2);
+      BtHelper.getInstance().stopSearch();
+      that.data.connectDevice.deviceId = res.deviceId;
+      that.data.connectDevice.connectable = res.connectable;
+    });
     that.startSearch();
   },
 
+  ///搜索设备
   startSearch() {
     var that = this;
     that.setStatus(0);
     ///搜索到对应的设备
-    BtHelper.getInstance().search(
-      function (c) {
-        that.setStatus(2);
-        BtHelper.getInstance().stopSearch();
-        that.data.connectDevice.deviceId = c.deviceId;
-        that.data.connectDevice.connectable = c.connectable;
-      },
+    BtHelper.getInstance().startScan(
       function (b) {
-        that.setStatus(1);
-      }
+        if (!b) {
+          that.setStatus(1);
+        }
+      },
     );
   },
 
@@ -74,6 +78,28 @@ Page({
     })
   },
 
+  ///连接设备按钮
+  connectDeviceTap() {
+    var that = this;
+    console.log("点击搜索状态", that.data.connectStatus)
+    switch (that.data.connectStatus) {
+      case 0:
+        // 搜索中
+        break;
+      case 1:
+      case 4:
+        // 搜索失败,点击重新搜索了
+        that.startSearch()
+        break;
+      case 2:
+        that.connectToDvice()
+        break;
+      case 3:
+        // 连接成功
+        break;
+    }
+  },
+
   setStatus(bleType) {
     var that = this;
     var searchTips = ""
@@ -132,91 +158,8 @@ Page({
     })
   },
 
-  ///连接设备按钮
-  async connectDeviceTap() {
-    var that = this;
-    console.log("点击搜索状态", that.data.connectStatus)
-    switch (that.data.connectStatus) {
-      case 0:
-        // 搜索中
-        break;
-      case 1:
-      case 4:
-        // 搜索失败,点击重新搜索了
-        that.startSearch()
-        break;
-      case 2:
-        that.connectToDvice()
-        break;
-      case 3:
-        // 连接成功
-        break;
-    }
-  },
-
-  getConnectedDevices: async function () {
-    var that = this;
-    const connectedDevices = await BtHelper.getInstance().getConnectedDevices()
-    console.log("全部设备", connectedDevices)
-    if (connectedDevices.length > 0) {
-      connectedDevices.forEach(element => {
-        console.log('已连接的蓝牙设备:', element);
-        that.didFindDevice(element)
-      });
-    } else {}
-    return connectedDevices;
-  },
-
-  findAllDevice() {
-    var that = this;
-    BtHelper.getInstance().findDevices(function (devices) {
-      let hasFind = false;
-      devices.forEach(element => {
-        console.log('发现设备2:', element);
-        if (that.didFindDevice(element)) {
-          hasFind = true
-        }
-      });
-      if (!hasFind) {
-        that.setStatus(1)
-      }
-    });
-  },
-
-  didFindDevice(element) {
-    let deviceId = element.deviceId
-    var that = this;
-    // todo 暂定这样
-
-    if (
-      // deviceId.includes("D8:24:07:89:31") ||
-      // // 2axk
-      // element.deviceId.includes("F5:A5:43:70:C8:F1") ||
-      /// sr1
-      element.deviceId.includes("E4:9F:80:09:40:EC") ||
-      // 黑色2x
-      // element.deviceId.includes("F6:61:D8:24:E5:98")
-      // /// mac: D7:92:84:87:09:7D
-      // ||
-      // element.deviceId.includes("F6:61:D8:24:E5:98") ||
-      // 黑胶
-      deviceId.includes("00:33:52:A7:3E:D0")
-    ) {
-      if (element.connectable == true) {
-        console.log("找到设备ble", element);
-        that.data.connectDevice.mac = element.mac
-        that.data.connectDevice.deviceId = element.deviceId
-        BtHelper.getInstance().stopSearch()
-        that.setStatus(2)
-        return true
-      }
-    }
-    return false
-  },
-
   ///关闭界面时候触发
   onUnload: function () {
-    var that = this;
     BtHelper.getInstance().stopSearch();
   }
 })
@@ -227,4 +170,35 @@ Page({
 //     console.log('UUID: ' + JSON.stringify(res));
 //     console.log('MAC: ' + res.macaddress);
 //   }
-// });
+// });
+
+// didFindDevice(element) {
+//   let deviceId = element.deviceId
+//   var that = this;
+//   // todo 暂定这样
+
+//   if (
+//     // deviceId.includes("D8:24:07:89:31") ||
+//     // // 2axk
+//     // element.deviceId.includes("F5:A5:43:70:C8:F1") ||
+//     /// sr1
+//     element.deviceId.includes("E4:9F:80:09:40:EC") ||
+//     // 黑色2x
+//     // element.deviceId.includes("F6:61:D8:24:E5:98")
+//     // /// mac: D7:92:84:87:09:7D
+//     // ||
+//     // element.deviceId.includes("F6:61:D8:24:E5:98") ||
+//     // 黑胶
+//     deviceId.includes("00:33:52:A7:3E:D0")
+//   ) {
+//     if (element.connectable == true) {
+//       console.log("找到设备ble", element);
+//       that.data.connectDevice.mac = element.mac
+//       that.data.connectDevice.deviceId = element.deviceId
+//       BtHelper.getInstance().stopSearch()
+//       that.setStatus(2)
+//       return true
+//     }
+//   }
+//   return false
+// },

+ 0 - 26
pages/index/index.js

@@ -127,38 +127,12 @@ Page({
   onDeviceLoad() {
     var that = this;
     BtHelper.getInstance().initBluetoothAdapter();
-
     var deviceList = wx.getStorageSync("deviceList") || "";
     if (!strings.isEmpty(deviceList)) {
       var list = JSON.parse(deviceList);
       that.updateDeviceList(list, true);
       // that.tryConnectBle()
     }
-
-    // BtHelper.getInstance().getAllOnlineDevices(function (devices) {
-    //   ///对比在线的蓝牙设备
-    //   var isChanged = false;
-    //   var tempList = that.data.deviceList;
-    //   for (var i = 0; i < tempList.length; i++) {
-    //     var tempItem = tempList[i];
-    //     if (tempItem.connectType != 3) {
-    //       for (var j = 0; j < devices.length; j++) {
-    //         // "state":"online"
-    //         if (tempItem.deviceId === devices[j].deviceId) {
-    //           console.log("ggadsfqwerqwrqr===" + JSON.stringify(devices[j]));
-    //           isChanged = true;
-    //           tempItem.state = "online";
-    //           break;
-    //         }
-    //       }
-    //     }
-    //   }
-    //   console.log("gadfafqewrqrwerqr===fffff=" + isChanged);
-    //   if (isChanged) {
-    //     that.updateDeviceList(list, false);
-    //   }
-    // });
-
   },
 
   addNewDeviceId() {