Просмотр исходного кода

feature: 处理定位权限和搜索设备

Damon 8 месяцев назад
Родитель
Сommit
1acec3a0d6
5 измененных файлов с 182 добавлено и 155 удалено
  1. 12 4
      .idea/workspace.xml
  2. 3 11
      app.json
  3. 140 116
      devices/ble_manager.js
  4. 23 19
      devices/bt_helper.js
  5. 4 5
      pages/connectBle/connectBle.js

+ 12 - 4
.idea/workspace.xml

@@ -4,10 +4,10 @@
     <option name="autoReloadType" value="NONE" />
   </component>
   <component name="ChangeListManager">
-    <list default="true" id="420a40af-e4b9-41e7-b569-424cfc67e65d" name="Changes" comment="feature: 处理外部类与内部类的问题">
+    <list default="true" id="420a40af-e4b9-41e7-b569-424cfc67e65d" name="Changes" comment="feature: 解决图片报错的问题">
       <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
+      <change beforePath="$PROJECT_DIR$/devices/ble_manager.js" beforeDir="false" afterPath="$PROJECT_DIR$/devices/ble_manager.js" afterDir="false" />
       <change beforePath="$PROJECT_DIR$/devices/bt_helper.js" beforeDir="false" afterPath="$PROJECT_DIR$/devices/bt_helper.js" afterDir="false" />
-      <change beforePath="$PROJECT_DIR$/pages/connectBle/connectBle.js" beforeDir="false" afterPath="$PROJECT_DIR$/pages/connectBle/connectBle.js" afterDir="false" />
     </list>
     <option name="SHOW_DIALOG" value="false" />
     <option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -179,7 +179,14 @@
       <option name="project" value="LOCAL" />
       <updated>1733126619647</updated>
     </task>
-    <option name="localTasksCounter" value="16" />
+    <task id="LOCAL-00016" summary="feature: 解决图片报错的问题">
+      <created>1733127373473</created>
+      <option name="number" value="00016" />
+      <option name="presentableId" value="LOCAL-00016" />
+      <option name="project" value="LOCAL" />
+      <updated>1733127373473</updated>
+    </task>
+    <option name="localTasksCounter" value="17" />
     <servers />
   </component>
   <component name="Vcs.Log.History.Properties">
@@ -254,6 +261,7 @@
     <MESSAGE value="feature: 整理" />
     <MESSAGE value="feature: 添加测试蓝牙类" />
     <MESSAGE value="feature: 处理外部类与内部类的问题" />
-    <option name="LAST_COMMIT_MESSAGE" value="feature: 处理外部类与内部类的问题" />
+    <MESSAGE value="feature: 解决图片报错的问题" />
+    <option name="LAST_COMMIT_MESSAGE" value="feature: 解决图片报错的问题" />
   </component>
 </project>

+ 3 - 11
app.json

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

+ 140 - 116
devices/ble_manager.js

@@ -1,18 +1,103 @@
 // 引入必要的微信小程序 API
 // const wx = require('wx');
-
 class bleManager {
   constructor() {
     var that = this;
-    that.hasPermission = false;
     that.isAvailable = false;
+    that.hasPermission = false;
     that.scanDevices = [];
     that.device = null;
   }
 
+  // 初始化蓝牙适配器
+  async initBluetoothAdapter(callback) {
+    var that = this
+    return new Promise((resolve, reject) => {
+      wx.openBluetoothAdapter({
+        success: (res) => {
+          that.isAvailable = true;
+          if (callback) {
+            callback(true);
+          }
+          resolve(true);
+        },
+        fail: (err) => {
+          that.isAvailable = false;
+          console.log('adapterState fail, now is', err)
+          if (callback) {
+            callback(false);
+          }
+          reject(false);
+        }
+      });
+      wx.onBluetoothAdapterStateChange(function (res) {
+        // console.log('adapterState changed, now is', res)
+        // if (callback) {
+        //   callback(res.available ?? false);
+        // }
+        that.isAvailable = res.available ?? false
+      })
+    });
+  }
+
+  // 开始搜索蓝牙设备
+  async startScan(success, fail) {
+    var that = this;
+    var open = await that.getLocalSetting();
+    if (!open) {
+      return false;
+    }
+    if (!that.isAvailable) {
+      wx.showToast({
+        title: '请打开蓝牙',
+        icon: 'none',
+        duration: 2000
+      });
+      return false;
+    }
+
+    if (!that.hasPermission) {
+      wx.showToast({
+        title: '请打开蓝牙权限',
+        icon: 'none',
+        duration: 2000
+      });
+      return false;
+    }
+
+    wx.startBluetoothDevicesDiscovery({
+      allowDuplicatesKey: false,
+      // services: ["ffc0", "ab00", "ffe5"],
+      success: (res) => {
+        console.log('蓝牙设备搜索已启动:', res);
+        if (res) {
+          wx.onBluetoothDeviceFound((devicesRes) => {
+            devicesRes.devices.forEach(device => {
+              if (device.name) {
+                console.log("gadsfadfqwerqwerqr==aaa====" + device.name + "===" + device.deviceId);
+              }
+            })
+          });
+        }
+      },
+      fail: (err) => {
+        if (fail) {
+          if (err.errno == 1509008) {
+            wx.showToast({
+              title: '搜索蓝牙需要先开启定位权限',
+              icon: 'none',
+              duration: 2000
+            });
+          }
+          fail(err);
+        }
+        console.log('启动蓝牙设备搜索失败', err ?? "err is null");
+      }
+    });
+  }
+
   // 检查蓝牙权限
   async checkBluetoothPermission(callback) {
-    // return new Promise((resolve, reject) => {
     // 获取蓝牙权限
     var that = this;
     const _app = getApp();
@@ -21,12 +106,9 @@ class bleManager {
         if (res.authSetting["scope.bluetooth"]) {
           _app.globalData.scopeBluetooth = true;
           that.hasPermission = true;
-          // console.log('checkBluetoothPermission success, now is', res)
           if (callback) {
             callback(true);
           }
-          // resolve(true);
-
         } else if (res.authSetting["scope.bluetooth"] === undefined) {
           _app.globalData.scopeBluetooth = false;
           that.hasPermission = false;
@@ -37,11 +119,8 @@ class bleManager {
             scope: "scope.bluetooth",
             complete() {
               that.checkBluetoothPermission()
-              // resolve(that.checkBluetoothPermission());
-
             }
           });
-
         } else {
           that.globalData.scopeBluetooth = false;
           that.hasPermission = false;
@@ -55,53 +134,16 @@ class bleManager {
               if (res.confirm) {
                 console.log('用户点击确定')
                 wx.openSetting({
-                  complete() {
-                    // that.getBluetoothStatus();
-                  }
+                  complete() {}
                 })
               } else if (res.cancel) {
                 console.log('用户点击取消')
               }
             }
-          })
-          // resolve(false);
+          });
         };
       }
     })
-    // })
-
-  }
-
-  // 初始化蓝牙适配器
-  async initBluetoothAdapter(callback) {
-    var that = this
-    return new Promise((resolve, reject) => {
-      wx.openBluetoothAdapter({
-        success: (res) => {
-          that.isAvailable = true;
-          // console.log('adapterState success, now is', res)
-          if (callback) {
-            callback(true);
-          }
-          resolve(true);
-        },
-        fail: (err) => {
-          that.isAvailable = false;
-          console.log('adapterState fail, now is', err)
-          if (callback) {
-            callback(false);
-          }
-          reject(false);
-        }
-      });
-      wx.onBluetoothAdapterStateChange(function (res) {
-        console.log('adapterState changed, now is', res)
-        if (callback) {
-          callback(res.available ?? false);
-        }
-        that.isAvailable = res.available ?? false
-      })
-    });
   }
 
   closeBle() {
@@ -154,7 +196,6 @@ class bleManager {
           //     name: device.name || device.localName
           // }));
           let newDevices = that.fiterDevice(res)
-
           resolve(newDevices);
         },
         fail: (err) => {
@@ -224,94 +265,39 @@ class bleManager {
     });
   }
 
-  async getSetting() {
+  ///获取定位权限
+  async getLocalSetting() {
     var that = this;
     return new Promise((resolve, reject) => {
       wx.getSetting({
         success(res) {
-          if (res.authSetting["scope.userFuzzyLocation"]) {
-            // 成功
-            // that.getBluetoothStatus();
+          if (res.authSetting["scope.userLocation"]) {
             console.log("有定位权限")
             resolve(true);
-          } else if (res.authSetting["scope.userFuzzyLocation"] === undefined) {
-
+          } else if (res.authSetting["scope.userLocation"] === undefined) {
             wx.authorize({
-              scope: "scope.userFuzzyLocation",
+              scope: "scope.userLocation",
               success() {
-                console.log("再次获取定位权限")
-                resolve(that.getSetting());
-
+                resolve(that.getLocalSetting());
               }
             });
           } else {
-
             wx.showModal({
               title: '请打开系统位置获取定位权限',
               success(res) {
                 if (res.confirm) {
-                  console.log('用户点击确定')
                   wx.openSetting({
-                    complete() {
-                      // that.getSetting();
-                      // resolve(that.getSetting());
-
-                    }
+                    complete() {}
                   })
-                } else if (res.cancel) {
-                  console.log('用户点击取消');
-                }
+                } else if (res.cancel) {}
               }
             })
             console.log("没有有定位权限")
             reject(false);
-
           }
-        }
-      })
-
-    });
-
-  }
-  // 开始搜索蓝牙设备
-  async startScan(success, fail) {
-    var that = this;
-    let open = await that.getSetting()
-    if (!open) {
-      if (fail) {
-        fail("需要先开启定位");
-      }
-      console.log('需要先开启定位');
-    }
-    if (!that.isAvailable && !that.hasPermission) {
-      return false;
-    }
-
-    wx.startBluetoothDevicesDiscovery({
-      // services: ["ffc0", "ab00", "ffe5"],
-      success: (res) => {
-        // that.onBluetoothDeviceFound();
-        console.log('蓝牙设备搜索已启动:', res);
-        if (success) {
-          success(res);
-        }
-        // resolve(res);
-      },
-      fail: (err) => {
-        if (fail) {
-          if (err.errno == 1509008) {
-            wx.showToast({
-              title: '搜索蓝牙需要先开启定位权限',
-              icon: 'none',
-              duration: 2000
-            })
-          }
-          fail(err);
-        }
-        console.log('启动蓝牙设备搜索失败', err ?? "err is null");
-
-        // reject(new Error('启动蓝牙设备搜索失败', err ?? "err is null"));
-      }
+        },
+        fail(err) {}
+      });
     });
   }
 
@@ -564,4 +550,42 @@ class bleManager {
 // const ble = new bleManager();
 
 // 导出 bleManager 类
-module.exports = bleManager;
+module.exports = bleManager;
+
+// wx.getSetting({
+//   success(res) {
+//     if (res.authSetting["scope.userFuzzyLocation"]) {
+//       // 成功
+//       // that.getBluetoothStatus();
+//       console.log("有定位权限")
+//       resolve(true);
+//     } else if (res.authSetting["scope.userFuzzyLocation"] === undefined) {
+//       wx.authorize({
+//         scope: "scope.userFuzzyLocation",
+//         success() {
+//           console.log("再次获取定位权限")
+//           resolve(that.getSetting());
+//         }
+//       });
+//     } else {
+//       wx.showModal({
+//         title: '请打开系统位置获取定位权限',
+//         success(res) {
+//           if (res.confirm) {
+//             console.log('用户点击确定')
+//             wx.openSetting({
+//               complete() {
+//                 // that.getSetting();
+//                 // resolve(that.getSetting());
+//               }
+//             })
+//           } else if (res.cancel) {
+//             console.log('用户点击取消');
+//           }
+//         }
+//       })
+//       console.log("没有有定位权限")
+//       reject(false);
+//     }
+//   }
+// })

+ 23 - 19
devices/bt_helper.js

@@ -68,7 +68,6 @@ class BtHelper {
     that.queueManager.listenTask((task) => {
       _this.bleManager.sendData(task);
     });
-
     addNotification(CmdEvent.eventName, function (event) {
       console.log("蓝牙helper:", event)
       let device = getApp().globalData.mDeviceList[0] ?? {};
@@ -76,13 +75,31 @@ class BtHelper {
         return;
       }
       _this.handleCommand(event, device);
-
     }, this)
   }
 
+  ///搜索蓝牙设备
+  async search(stopCall) {
+    var that = this;
+    var res = await that.bleManager.startScan();
+    // console.log("gadsfadfqwerqwerqr==444====" + res);
+    ///失败
+    if (!res) {
+
+    }
+    // that.timer = null;
+    // that.timer = setTimeout(() => {
+    //   that.stopSearch();
+    //   if (stopCall) {
+    //     stopCall()
+    //   }
+    // }, 10000);
+    // console.log(res);
+    // return await that._helper.search();
+  }
+
   handleCommand(event, mDevice) {
     let name = event.name;
-
     switch (name) {
       ///音量  设备控制手机
       case EnumCmdEvent.volume:
@@ -312,20 +329,6 @@ class BtHelper {
     // BtHelper._isConnecting = connect;
   }
 
-  async search(stopCall) {
-    var that = this;
-    let res = await that.bleManager.startScan()
-    that.timer = null;
-    that.timer = setTimeout(() => {
-      that.stopSearch();
-      if (stopCall) {
-        stopCall()
-      }
-    }, 10000);
-    // console.log(res);
-    // return await that._helper.search();
-  }
-
   async findDevices(callback) {
     this.bleManager.onBluetoothDeviceFound(callback)
     // return await this._helper.search();
@@ -448,7 +451,7 @@ class BtHelper {
     var that = this;
     ///是否已打开蓝牙
     var adpter = await that.bleManager.initBluetoothAdapter((res) => {
-      console.log("gadsfeqwrqwerqr==00=" + JSON.stringify(res));
+      console.log("gadsfadfqwerqwerqr==000====" + res);
       if (!res) {
         wx.showToast({
           title: '请开启蓝牙功能',
@@ -461,8 +464,9 @@ class BtHelper {
       }
 
       ///获取蓝牙权限
+      console.log("gadsfadfqwerqwerqr==111====" + res);
       that.bleManager.checkBluetoothPermission(function (per) {
-        console.log("gadsfeqwrqwerqr==111=" + per);
+        console.log("gadsfadfqwerqwerqr==222====" + per);
         if (!per) {
           wx.showToast({
             title: '没有蓝牙权限',

+ 4 - 5
pages/connectBle/connectBle.js

@@ -27,7 +27,7 @@ Page({
 
   onLoad(options) {
     var that = this;
-    let json = JSON.parse(options.param)
+    var json = JSON.parse(options.param)
     console.log("要连接设备:", json)
     that.setData({
       connectDevice: json
@@ -43,8 +43,7 @@ Page({
         that.setStatus(1);
       }
     })
-
-    that.findAllDevice()
+    // that.findAllDevice()
   },
 
   async startSearch() {
@@ -67,7 +66,7 @@ Page({
     let typeList = that.data.connectDevice.typeList ?? []
     let bleTypes = typeList.find(v => v.connectType == 1)
     let deviceLinkResp = bleTypes.deviceLinkResp ?? {}
-  
+
     console.log("搜索状态", bleType)
     switch (bleType) {
       case 0:
@@ -171,7 +170,7 @@ Page({
         console.log('已连接的蓝牙设备:', element);
         that.didFindDevice(element)
       });
-    } else { }
+    } else {}
     return connectedDevices;
   },