فهرست منبع

代码整理4-todo

chaooo 1 سال پیش
والد
کامیت
f6678fb7ee
5فایلهای تغییر یافته به همراه814 افزوده شده و 429 حذف شده
  1. 26 44
      src/components/connection/index.vue
  2. 7 0
      src/store/bluetooth.js
  3. 0 10
      src/store/game.js
  4. 368 368
      src/utils/bluetooth.js
  5. 413 7
      src/utils/connection.js

+ 26 - 44
src/components/connection/index.vue

@@ -36,23 +36,29 @@ export default {
 
 
       // $this.$bluetooth 设置的参数
+      // 设置图标的颜色
+      device_bg: false,
       // 电量
       device_power: 0,
-      device_voltage: 0,
-      rssi: 0,
-      current_hex:"",
       // 判断是否已经连接教具
       toy_connected: false,
       toy_sn:"",
       toy_power:0,
-      toy_voltage:0,
-      // 设置图标的颜色
-      device_bg: false,
-      toy_UUID:"",
-      hasUsb:false,
+
+
+
+
+
 
       connect_show: false,
       device:{},
+      toy_UUID:"",
+      // 信号强度
+      RSSI:0,
+      device_voltage: 0,
+      toy_voltage:0,
+      current_hex:"",
+      hasUsb:false,
 
     }
   },
@@ -76,14 +82,15 @@ export default {
       $this.device_status = $status * 1;
       console.log("接收到设备连接状态:", $status);
       if ($status * 1 === 2) {
+        // 已连接
         let $checkServices = setInterval(() => {
           let $serviceId = ble_store.getters.getServiceId();
           if ($serviceId) {
             clearInterval($checkServices);
             // 监听数据
-            $this.$bluetooth.openNotify($this);
-            $this.$bluetooth.notifyDatas($this);
-            $this.$bluetooth.watchBLEstatus($this);
+            //$this.$bluetooth.openNotify($this);
+            $this.$connection.notifyDatas($this);
+            $this.$connection.watchBLEstatus($this);
           }
         }, 1500);
       } else {
@@ -94,34 +101,9 @@ export default {
         $this.device_bg = false;
         $this.connect_status = false;
         if ($status * 1 > 0) {
-          // 断开教具及蓝牙连接
-          $this.$bluetooth.SendOrder("31");
-          // 移除搜索到新设备的事件的全部监听函数
-          wx.offBluetoothDeviceFound();
-          // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
-          wx.stopBluetoothDevicesDiscovery();
-          $this.$bluetooth.SendOrder("09");
-          let deviceId = ble_store.getters.getDeviceId();
-          //断开蓝牙连接
-          wx.closeBLEConnection({
-            deviceId: deviceId,
-            success() {
-              Toast.success({
-                message: "断开蓝牙连接成功",
-              });
-              game_store.setters.clearDeviceToy();
-              wx.closeBluetoothAdapter();
-              console.log("断开蓝牙连接成功", deviceId);
-            },
-            fail(err) {
-              console.log("断开蓝牙连接"+deviceId+"失败error:", err);
-            },
-            complete() {
-              $this.device = {};
-              $this.toy_UUID = "";
-              $this.$forceUpdate();
-            },
-          });
+          // 关闭脑机蓝牙连接
+          $this.$connection.closeConnection($this);
+
         }
       }
     },
@@ -202,8 +184,8 @@ export default {
       $this.$bluetooth.notifyDatas($this);
       $this.$bluetooth.watchBLEstatus($this);
 
-      $this.toy_UUID = "";
-      $this.$forceUpdate();
+      //$this.toy_UUID = "";
+
       // 状态为1的时候重置为1 小乌龟
       if ($game_close_status === 1) {
         // 重置默认条件
@@ -211,11 +193,11 @@ export default {
         $this.connect_show = false;
         $this.device_status = 0;
         $this.$bluetooth.watchBLEstatus($this);
-        $this.toy_UUID = "";
-        $this.$forceUpdate();
+        //$this.toy_UUID = "";
         // 清空链接的设备
-        game_store.setters.clearDeviceToy();
+        ble_store.setters.clearDeviceToy();
       }
+      $this.$forceUpdate();
     }
   },
 };

+ 7 - 0
src/store/bluetooth.js

@@ -17,6 +17,13 @@ const getters = {
 }
 
 const setters = {
+  clearDeviceToy() {
+    wx.removeStorageSync('deviceId')
+    wx.removeStorageSync('deviceSn')
+    wx.removeStorageSync('serviceId')
+    wx.removeStorageSync('is_new')
+    wx.removeStorageSync('characteristicId')
+  },
   setBluetoothLinkStatus($bool) {
     wx.setStorageSync("ble_link_status", $bool)
   },

+ 0 - 10
src/store/game.js

@@ -1,14 +1,4 @@
 const setters = {
-  clearDeviceToy() {
-    wx.removeStorageSync('deviceId')
-    wx.removeStorageSync('deviceSn')
-    wx.removeStorageSync('serviceId')
-    wx.removeStorageSync('is_new')
-    // wx.removeStorageSync('characteristicId')
-  },
-  //setter模块
-
-
   // 游戏状态: 0未开始 1游戏中 3游戏结束
   setGameStatus(status) {
     wx.setStorageSync('game_status', status)

+ 368 - 368
src/utils/bluetooth.js

@@ -251,96 +251,96 @@ export default {
     return $power;
   },
 
-  /**
-   *  todo:监听蓝牙连接状态
-   *  监听蓝牙低功耗连接状态改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等
-   */
-  watchBLEstatus($this) {
-    let that = this;
-    // 微信自身监听低功耗蓝牙连接状态的改变事件
-    wx.onBLEConnectionStateChange((res) => {
-      // 该方法回调中可以用于处理连接意外断开等异常情况
-      ble_store.setters.setBluetoothLinkStatus(res.connected);
-      LogInDb(`${that.getNowTime()} 监听脑机断连`)
-      if (res.connected == false) {
-        //判断游戏是否游戏中
-        let $game_status = game_store.getters.getGameStatus();
-        if ($game_status == 1) {
-          // $that.game_finished();
-          Notify({
-            type: 'danger',
-            duration: 0,
-            message: '智脑机已断开连接,正在尝试重新连接',
-            onOpened() {
-              that.reconnect(res.deviceId, $this)
-            }
-          });
-          control_close = true
-          // connect_toy = false;
-        } else {
-          //关闭脑控
-          connect_toy = false;
-          game_store.setters.setGameStatus(0);
-          // 清空链接得设备 三值
-          game_store.setters.clearDeviceToy();
-          $this.connect_toy = 0;
-          $this.connect_show = false;
-          $this.device_bg = false;
-          $this.device_status = 0;
-          $this.device = {}
-          $this.toy_UUID = "";
-          $this.$forceUpdate();
-          wx.closeBluetoothAdapter();
-          version = "";
-        }
-      }
-    });
-  },
-
-  /**
-   * todo:重新连接蓝牙
-   */
-  reconnect($deviceId, $this) {
-    let that = this;
-    let $deviceInfo = getServicesAndCharateristc();
-    //重连的次数
-    let $connect_count = 0;
-    let $rec = setInterval(() => {
-      let $game_status = game_store.getters.getGameStatus();
-      if ($game_status == 1) {
-        wx.createBLEConnection({
-          deviceId: $deviceInfo.deviceId,
-          success(res) {
-            clearInterval($rec)
-            Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
-            LogInDb(`${that.getNowTime()} 第${$connect_count}次重新连接成功`)
-            let $system = wx.getSystemInfoSync()
-            if ($system.platform == 'ios') {
-              that.getBLEDeviceServices($deviceInfo.deviceId)
-              that.notifyDatas($this)
-            } else {
-              that.openNotify($this)
-              that.watchBLEstatus($this);
-            }
-            // that.sendToyPower();
-
-          },
-          fail(res) {
-            Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
-            game_store.setters.setGameCloseStatus(1);
-          }
-        })
-        if ($connect_count >= 3) {
-          $this.game_finished();
-          clearInterval($rec)
-        }
-        $connect_count += 1;
-      } else {
-        clearInterval($rec)
-      }
-    }, 7000)
-
-  },
+  // /**
+  //  *  todo:监听蓝牙连接状态
+  //  *  监听蓝牙低功耗连接状态改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等
+  //  */
+  // watchBLEstatus($this) {
+  //   let that = this;
+  //   // 微信自身监听低功耗蓝牙连接状态的改变事件
+  //   wx.onBLEConnectionStateChange((res) => {
+  //     // 该方法回调中可以用于处理连接意外断开等异常情况
+  //     ble_store.setters.setBluetoothLinkStatus(res.connected);
+  //     LogInDb(`${that.getNowTime()} 监听脑机断连`)
+  //     if (res.connected == false) {
+  //       //判断游戏是否游戏中
+  //       let $game_status = game_store.getters.getGameStatus();
+  //       if ($game_status == 1) {
+  //         // $that.game_finished();
+  //         Notify({
+  //           type: 'danger',
+  //           duration: 0,
+  //           message: '智脑机已断开连接,正在尝试重新连接',
+  //           onOpened() {
+  //             that.reconnect(res.deviceId, $this)
+  //           }
+  //         });
+  //         control_close = true
+  //         // connect_toy = false;
+  //       } else {
+  //         //关闭脑控
+  //         connect_toy = false;
+  //         game_store.setters.setGameStatus(0);
+  //         // 清空链接得设备 三值
+  //         ble_store.setters.clearDeviceToy();
+  //         $this.connect_toy = 0;
+  //         $this.connect_show = false;
+  //         $this.device_bg = false;
+  //         $this.device_status = 0;
+  //         $this.device = {}
+  //         $this.toy_UUID = "";
+  //         $this.$forceUpdate();
+  //         wx.closeBluetoothAdapter();
+  //         version = "";
+  //       }
+  //     }
+  //   });
+  // },
+  //
+  // /**
+  //  * todo:重新连接蓝牙
+  //  */
+  // reconnect($deviceId, $this) {
+  //   let that = this;
+  //   let $deviceInfo = getServicesAndCharateristc();
+  //   //重连的次数
+  //   let $connect_count = 0;
+  //   let $rec = setInterval(() => {
+  //     let $game_status = game_store.getters.getGameStatus();
+  //     if ($game_status == 1) {
+  //       wx.createBLEConnection({
+  //         deviceId: $deviceInfo.deviceId,
+  //         success(res) {
+  //           clearInterval($rec)
+  //           Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
+  //           LogInDb(`${that.getNowTime()} 第${$connect_count}次重新连接成功`)
+  //           let $system = wx.getSystemInfoSync()
+  //           if ($system.platform == 'ios') {
+  //             that.getBLEDeviceServices($deviceInfo.deviceId)
+  //             that.notifyDatas($this)
+  //           } else {
+  //             that.openNotify($this)
+  //             that.watchBLEstatus($this);
+  //           }
+  //           // that.sendToyPower();
+  //
+  //         },
+  //         fail(res) {
+  //           Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
+  //           game_store.setters.setGameCloseStatus(1);
+  //         }
+  //       })
+  //       if ($connect_count >= 3) {
+  //         $this.game_finished();
+  //         clearInterval($rec)
+  //       }
+  //       $connect_count += 1;
+  //     } else {
+  //       clearInterval($rec)
+  //     }
+  //   }, 7000)
+  //
+  // },
 
   // /**
   //  * todo 获取蓝牙设备服务
@@ -419,21 +419,21 @@ export default {
   //     },
   //   });
   // },
-  // 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征。
-  openNotify($this) {
-    let that = this;
-    let $deviceInfo = getServicesAndCharateristc();
-    console.log($deviceInfo)
-    wx.notifyBLECharacteristicValueChange({
-      deviceId: $deviceInfo.deviceId,
-      serviceId: $deviceInfo.service,
-      characteristicId: $deviceInfo.charateristic.notify,
-      state: true,
-      success() {
-        that.notifyDatas($this)
-      }
-    });
-  },
+  // // 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征。
+  // openNotify($this) {
+  //   let that = this;
+  //   let $deviceInfo = getServicesAndCharateristc();
+  //   console.log($deviceInfo)
+  //   wx.notifyBLECharacteristicValueChange({
+  //     deviceId: $deviceInfo.deviceId,
+  //     serviceId: $deviceInfo.service,
+  //     characteristicId: $deviceInfo.charateristic.notify,
+  //     state: true,
+  //     success() {
+  //       that.notifyDatas($this)
+  //     }
+  //   });
+  // },
 
   /**
    * todo ArrayBuffer转16进度字符串示例
@@ -451,268 +451,268 @@ export default {
   },
 
 
-  /**
-   * todo 监听脑机数据
-   * @param $this
-   */
-  notifyDatas($this) {
-    const that = this;
-    let DeviceId = ble_store.getters.getDeviceId();
-    // 监听蓝牙低功耗设备的特征值变化事件
-    wx.onBLECharacteristicValueChange((characteristic) => {
-      // 获取脑机信号值
-      wx.getBLEDeviceRSSI({
-        deviceId: DeviceId,
-        success(res) {
-          if (game_store.getters.getGameStatus() == 1) {
-            $this.rssi = res.RSSI;
-          }
-        }
-      })
-
-      let hexStr = that.ab2hex(characteristic.value);
-      console.log("plant监听脑机数据:", hexStr, "当前页面名称:", $this.$options.name);
-
-      if (hexStr.toUpperCase().indexOf("AADD") != -1 || hexStr.toUpperCase().indexOf("AAEE") != -1 && update_state == false) {
-        let nowTime = Math.round(new Date() / 1000);
-        console.log("应答", hexStr, '时间:' + that.getNowTime(), "长度", hexStr.length / 2);
-        LogInDb(`${that.getNowTime()} 应答:${hexStr}`)
-      }
-      let $data = that.get_big_data(hexStr);
-      let $game_status = game_store.getters.getGameStatus();
-
-      // 教具断链
-      if (hexStr.toUpperCase().indexOf("AAEE70") != -1) {
-        connect_toy = false
-        wx.showModal({
-          content: "教具已断开",
-          success(res) {
-            if (res.confirm) {
-              //重连机制
-              if ($game_status == 1) {
-                $this.game_finished();
-              }
-            }
-          }
-        })
-
-      }
-
-
-      if (hexStr.toUpperCase().indexOf("AAEE8A0000005A") != -1) {
-        that.SendOrder("8a")
-      }
-
-      //防止在首页 连接的时候重复 选择教具 产生了发送多个教具电量
-      // if(hexStr.toUpperCase().indexOf("AAEE8A000000FF76") != -1){
-      //   that.connect_toy = false;
-      // }
-
-      if (hexStr.toUpperCase().indexOf("AAEE07") != -1) {
-        that.sendControl();
-      }
-      // 2021年10月20日17:18:13 判断教具 连接
-      if (hexStr.toUpperCase().indexOf("AADD0A") != -1) {
-        //没连接上教具
-        if (hexStr.toUpperCase().indexOf("AADD0A0000") != -1) {
-          //if (is_new) {
-            $this.connect_toy = 3;
-          //}
-          return false;
-        }
-        let $mHexStrIndex = hexStr.toUpperCase().indexOf("AADD0A");
-        let $hex_index = hexStr.substr($mHexStrIndex + 28, 2)
-        let $toy_id = hexStr.substr($mHexStrIndex + 8, 2)
-        console.log("连接", $hex_index)
-        console.log("教具", $toy_id)
-        // 连接上教具
-        if (new RegExp("00").test($hex_index) == true) {
-          //if (is_new) {
-            that.sendConnectOneToOne($toy_id)
-            $this.current_hex = `03 00 ${$toy_id} 01 0A`
-            console.log("一对多")
-          // } else {
-          //   $this.current_hex = "";
-          //   wx.showToast({
-          //     title: "已连接到" + $this.toy_item.name
-          //   });
-          //   $this.toy_connected = true;
-          //   $this.connect_toy = 2;
-          // }
-        }
-        if (new RegExp("01").test($hex_index) == true) {
-          console.log("一对一")
-          $this.current_hex = "";
-          wx.showToast({
-            title: "已连接到" + $this.toy_item.name
-          });
-          $this.toy_connected = true;
-          connect_toy = true;
-          $this.connect_toy = 2;
-
-          //连接成功后 获取一次教具名称
-          //TODO 2022-5-25 08:51:15 延迟发送教具UUID
-          //2022年5月25日17:21:57 从2秒更换到3秒
-          // 判断冥想模式不发送获取教具名字
-          if ($toy_id != 80) {
-            setTimeout(() => {
-              that.SendOrder('87')
-            }, 3000)
-
-            // 更改为不断获取教具电量
-            setTimeout(() => {
-              that.sendToyPower();
-            }, 5000)
-          }
-
-        }
-
-      }
-
-      //2021年11月23日10:39:49
-      // 获取教具名称
-      if (hexStr.toUpperCase().indexOf("AADD87") != -1) {
-        let $mHexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD87"))
-        let $datas = that.DoAnalysis($mHexStr, 10)
-        let $number = $datas.match(/\d+/)
-        let toy_list_pre = {'01': "SW", '02': "KL", '04': "SC", '05': "PP", '06': "SU", '09': "UF", '12': "JM", '13': "QM"}
-        let $sn = toy_list_pre[current_toy_id] + $number;
-        $this.toy_sn = $sn;
-        //保存教具sn
-        game_store.setters.setToySn($sn);
-        console.log("获取教具名称hexStr",hexStr)
-        console.log("获取教具名称$sn",$sn)
-      }
-      if (hexStr.toUpperCase().indexOf("AAEE87") != -1) {
-        //获取教具电量
-        if (current_toy_id != '80') {
-          that.SendOrder('87')
-        }
-      }
-
-      //2021年10月21日16:30:07
-      // 获取教具电量
-      if (hexStr.toUpperCase().indexOf("AADD8A") != -1) {//接收教具电量状态
-        let $_hexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD8A") + 6);
-        let $power = parseInt($_hexStr.substr(0, 2), 16)
-        let $voltage = parseInt($_hexStr.substr(2, 2), 16)
-        connect_toy = true;
-        // $this.toy_power = Math.round(that.CalBLEPower($voltage));
-        if ($power > 0) {
-          $this.toy_power = $power
-          $this.toy_voltage = $voltage
-          ToyPower = $power;
-        }
-
-
-        if (current_toy_UUID == "") {
-          //获取教具UUID
-          that.SendOrder('84')
-        }
-      }
-
-      //监听佩戴正确
-      if (hexStr.substr(0, 6) == "555520") {
-        //当s1为 00时 数据有效
-        let $s1 = hexStr.substr(8, 2);
-        // console.log("监听脑机是否带正:", $s1 == '00')
-
-        $this.device_bg = $s1 == "00";
-      }
-
-      // 2021年10月25日09:15:50
-      // 读取教具UUID
-      if (hexStr.toUpperCase().indexOf("AADD84") != -1) {//接收UUID 5个字节
-        let $hex_index = hexStr.toUpperCase().indexOf("AADD84") + 6;
-        let $datas = hexStr.substr($hex_index, 10);
-        if ($datas != "0000000000") {
-          console.log("以获取UUID:" + $datas)
-          current_toy_UUID = $datas;
-          $this.toy_UUID = $datas;
-        }
-      }
-
-
-      if (hexStr.toUpperCase().indexOf("AADD09") != -1) {
-        control_close = true;
-        connect_toy = false;
-      }
-
-      //收到发送UUID的应答立马发送连接教具的指令
-      if (hexStr.toUpperCase().indexOf("AADD8E") != -1) {
-        //发送教具连接
-        that.WriteBufferInBle(`03 00 ${current_toy_id} 02 0A`)
-      }
-
-
-      // 处理打开脑控的应答
-      if (hexStr.toUpperCase().indexOf("AADD07") != -1) {
-        ble_store.setters.setBluetoothLinkStatus(true)
-        FlagOpenControl = true;
-      }
-
-      //todo 监听脑机电量
-      if (hexStr.substr(0, 8) == "55550203") {
-        let $power = parseInt(hexStr.substr(8, 2), 16);
-        let $voltage = parseInt(hexStr.substr(10, 2), 16);
-        //监听是否插入USB
-        $this.hasUsb = $voltage.toString().substr(0, 1) == 1
-        //  监听脑机电量
-        if ($power) {
-          // console.log("当前脑机电量:", $power)
-          $this.device_power = $power;
-          $this.device_voltage = $voltage;
-        }
-        if ($power < 10 && $power > 0) {
-          wx.showToast({
-            title: "脑机电量不足",
-            icon: "none",
-            duration: 2000,
-            success() {
-              // $this.change_device_status(0);
-            },
-          });
-        }
-      }
-
-      //游戏中模块
-      if ($game_status == 1 && $data) {
-        $this.do_datas($data);
-      }
-
-
-      // 监听原始数据
-      if (hexStr.substr(0, 6) == "5555e2") {
-        let _buffer = that.doOriginBufferToData(hexStr)
-        if ($game_status == 1) {
-          wx.setStorageSync('origin_buffer', wx.getStorageSync('origin_buffer') + _buffer.join(',') + ",")
-        }
-      }
-
-      //todo 打开原始数据
-      if (hexStr.toUpperCase().indexOf("AADD04") != -1) {
-        raw_data_open = true;
-        that.Send2BOrder(true)
-        wx.setStorageSync('origin_buffer', "");
-      }
-
-      //todo 接收脑机关机指令
-      if (hexStr.toUpperCase().indexOf("AADD5A00000000A5") != -1) {
-        Notify({
-          type: 'danger',
-          duration: 0,
-          message: '智脑机已关机,训练结束',
-          onOpened() {
-            setTimeout(() => {
-              $this.game_finished();
-              clearInterval(control_close_intv)
-            }, 2000)
-          }
-        });
-
-      }
-    });
-  },
+  // /**
+  //  * todo 监听脑机数据
+  //  * @param $this
+  //  */
+  // notifyDatas($this) {
+  //   const that = this;
+  //   let DeviceId = ble_store.getters.getDeviceId();
+  //   // 监听蓝牙低功耗设备的特征值变化事件
+  //   wx.onBLECharacteristicValueChange((characteristic) => {
+  //     // 获取蓝牙低功耗设备(脑机)的信号强度
+  //     wx.getBLEDeviceRSSI({
+  //       deviceId: DeviceId,
+  //       success(res) {
+  //         if (game_store.getters.getGameStatus() == 1) {
+  //           $this.rssi = res.RSSI;
+  //         }
+  //       }
+  //     })
+  //
+  //     let hexStr = that.ab2hex(characteristic.value);
+  //     console.log("plant监听脑机数据:", hexStr, "当前页面名称:", $this.$options.name);
+  //
+  //     if (hexStr.toUpperCase().indexOf("AADD") != -1 || hexStr.toUpperCase().indexOf("AAEE") != -1 && update_state == false) {
+  //       let nowTime = Math.round(new Date() / 1000);
+  //       console.log("应答", hexStr, '时间:' + that.getNowTime(), "长度", hexStr.length / 2);
+  //       LogInDb(`${that.getNowTime()} 应答:${hexStr}`)
+  //     }
+  //     let $data = that.get_big_data(hexStr);
+  //     let $game_status = game_store.getters.getGameStatus();
+  //
+  //     // 教具断链
+  //     if (hexStr.toUpperCase().indexOf("AAEE70") != -1) {
+  //       connect_toy = false
+  //       wx.showModal({
+  //         content: "教具已断开",
+  //         success(res) {
+  //           if (res.confirm) {
+  //             //重连机制
+  //             if ($game_status == 1) {
+  //               $this.game_finished();
+  //             }
+  //           }
+  //         }
+  //       })
+  //
+  //     }
+  //
+  //
+  //     if (hexStr.toUpperCase().indexOf("AAEE8A0000005A") != -1) {
+  //       that.SendOrder("8a")
+  //     }
+  //
+  //     //防止在首页 连接的时候重复 选择教具 产生了发送多个教具电量
+  //     // if(hexStr.toUpperCase().indexOf("AAEE8A000000FF76") != -1){
+  //     //   that.connect_toy = false;
+  //     // }
+  //
+  //     if (hexStr.toUpperCase().indexOf("AAEE07") != -1) {
+  //       that.sendControl();
+  //     }
+  //     // 2021年10月20日17:18:13 判断教具 连接
+  //     if (hexStr.toUpperCase().indexOf("AADD0A") != -1) {
+  //       //没连接上教具
+  //       if (hexStr.toUpperCase().indexOf("AADD0A0000") != -1) {
+  //         //if (is_new) {
+  //           $this.connect_toy = 3;
+  //         //}
+  //         return false;
+  //       }
+  //       let $mHexStrIndex = hexStr.toUpperCase().indexOf("AADD0A");
+  //       let $hex_index = hexStr.substr($mHexStrIndex + 28, 2)
+  //       let $toy_id = hexStr.substr($mHexStrIndex + 8, 2)
+  //       console.log("连接", $hex_index)
+  //       console.log("教具", $toy_id)
+  //       // 连接上教具
+  //       if (new RegExp("00").test($hex_index) == true) {
+  //         //if (is_new) {
+  //           that.sendConnectOneToOne($toy_id)
+  //           $this.current_hex = `03 00 ${$toy_id} 01 0A`
+  //           console.log("一对多")
+  //         // } else {
+  //         //   $this.current_hex = "";
+  //         //   wx.showToast({
+  //         //     title: "已连接到" + $this.toy_item.name
+  //         //   });
+  //         //   $this.toy_connected = true;
+  //         //   $this.connect_toy = 2;
+  //         // }
+  //       }
+  //       if (new RegExp("01").test($hex_index) == true) {
+  //         console.log("一对一")
+  //         $this.current_hex = "";
+  //         wx.showToast({
+  //           title: "已连接到" + $this.toy_item.name
+  //         });
+  //         $this.toy_connected = true;
+  //         connect_toy = true;
+  //         $this.connect_toy = 2;
+  //
+  //         //连接成功后 获取一次教具名称
+  //         //TODO 2022-5-25 08:51:15 延迟发送教具UUID
+  //         //2022年5月25日17:21:57 从2秒更换到3秒
+  //         // 判断冥想模式不发送获取教具名字
+  //         if ($toy_id != 80) {
+  //           setTimeout(() => {
+  //             that.SendOrder('87')
+  //           }, 3000)
+  //
+  //           // 更改为不断获取教具电量
+  //           setTimeout(() => {
+  //             that.sendToyPower();
+  //           }, 5000)
+  //         }
+  //
+  //       }
+  //
+  //     }
+  //
+  //     //2021年11月23日10:39:49
+  //     // 获取教具名称
+  //     if (hexStr.toUpperCase().indexOf("AADD87") != -1) {
+  //       let $mHexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD87"))
+  //       let $datas = that.DoAnalysis($mHexStr, 10)
+  //       let $number = $datas.match(/\d+/)
+  //       let toy_list_pre = {'01': "SW", '02': "KL", '04': "SC", '05': "PP", '06': "SU", '09': "UF", '12': "JM", '13': "QM"}
+  //       let $sn = toy_list_pre[current_toy_id] + $number;
+  //       $this.toy_sn = $sn;
+  //       //保存教具sn
+  //       game_store.setters.setToySn($sn);
+  //       console.log("获取教具名称hexStr",hexStr)
+  //       console.log("获取教具名称$sn",$sn)
+  //     }
+  //     if (hexStr.toUpperCase().indexOf("AAEE87") != -1) {
+  //       //获取教具电量
+  //       if (current_toy_id != '80') {
+  //         that.SendOrder('87')
+  //       }
+  //     }
+  //
+  //     //2021年10月21日16:30:07
+  //     // 获取教具电量
+  //     if (hexStr.toUpperCase().indexOf("AADD8A") != -1) {//接收教具电量状态
+  //       let $_hexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD8A") + 6);
+  //       let $power = parseInt($_hexStr.substr(0, 2), 16)
+  //       let $voltage = parseInt($_hexStr.substr(2, 2), 16)
+  //       connect_toy = true;
+  //       // $this.toy_power = Math.round(that.CalBLEPower($voltage));
+  //       if ($power > 0) {
+  //         $this.toy_power = $power
+  //         $this.toy_voltage = $voltage
+  //         ToyPower = $power;
+  //       }
+  //
+  //
+  //       if (current_toy_UUID == "") {
+  //         //获取教具UUID
+  //         that.SendOrder('84')
+  //       }
+  //     }
+  //
+  //     //监听佩戴正确
+  //     if (hexStr.substr(0, 6) == "555520") {
+  //       //当s1为 00时 数据有效
+  //       let $s1 = hexStr.substr(8, 2);
+  //       // console.log("监听脑机是否带正:", $s1 == '00')
+  //
+  //       $this.device_bg = $s1 == "00";
+  //     }
+  //
+  //     // 2021年10月25日09:15:50
+  //     // 读取教具UUID
+  //     if (hexStr.toUpperCase().indexOf("AADD84") != -1) {//接收UUID 5个字节
+  //       let $hex_index = hexStr.toUpperCase().indexOf("AADD84") + 6;
+  //       let $datas = hexStr.substr($hex_index, 10);
+  //       if ($datas != "0000000000") {
+  //         console.log("以获取UUID:" + $datas)
+  //         current_toy_UUID = $datas;
+  //         $this.toy_UUID = $datas;
+  //       }
+  //     }
+  //
+  //
+  //     if (hexStr.toUpperCase().indexOf("AADD09") != -1) {
+  //       control_close = true;
+  //       connect_toy = false;
+  //     }
+  //
+  //     //收到发送UUID的应答立马发送连接教具的指令
+  //     if (hexStr.toUpperCase().indexOf("AADD8E") != -1) {
+  //       //发送教具连接
+  //       that.WriteBufferInBle(`03 00 ${current_toy_id} 02 0A`)
+  //     }
+  //
+  //
+  //     // 处理打开脑控的应答
+  //     if (hexStr.toUpperCase().indexOf("AADD07") != -1) {
+  //       ble_store.setters.setBluetoothLinkStatus(true)
+  //       FlagOpenControl = true;
+  //     }
+  //
+  //     //todo 监听脑机电量
+  //     if (hexStr.substr(0, 8) == "55550203") {
+  //       let $power = parseInt(hexStr.substr(8, 2), 16);
+  //       let $voltage = parseInt(hexStr.substr(10, 2), 16);
+  //       //监听是否插入USB
+  //       $this.hasUsb = $voltage.toString().substr(0, 1) == 1
+  //       //  监听脑机电量
+  //       if ($power) {
+  //         // console.log("当前脑机电量:", $power)
+  //         $this.device_power = $power;
+  //         $this.device_voltage = $voltage;
+  //       }
+  //       if ($power < 10 && $power > 0) {
+  //         wx.showToast({
+  //           title: "脑机电量不足",
+  //           icon: "none",
+  //           duration: 2000,
+  //           success() {
+  //             // $this.change_device_status(0);
+  //           },
+  //         });
+  //       }
+  //     }
+  //
+  //     //游戏中模块
+  //     if ($game_status == 1 && $data) {
+  //       $this.do_datas($data);
+  //     }
+  //
+  //
+  //     // 监听原始数据
+  //     if (hexStr.substr(0, 6) == "5555e2") {
+  //       let _buffer = that.doOriginBufferToData(hexStr)
+  //       if ($game_status == 1) {
+  //         wx.setStorageSync('origin_buffer', wx.getStorageSync('origin_buffer') + _buffer.join(',') + ",")
+  //       }
+  //     }
+  //
+  //     //todo 打开原始数据
+  //     if (hexStr.toUpperCase().indexOf("AADD04") != -1) {
+  //       raw_data_open = true;
+  //       that.Send2BOrder(true)
+  //       wx.setStorageSync('origin_buffer', "");
+  //     }
+  //
+  //     //todo 接收脑机关机指令
+  //     if (hexStr.toUpperCase().indexOf("AADD5A00000000A5") != -1) {
+  //       Notify({
+  //         type: 'danger',
+  //         duration: 0,
+  //         message: '智脑机已关机,训练结束',
+  //         onOpened() {
+  //           setTimeout(() => {
+  //             $this.game_finished();
+  //             clearInterval(control_close_intv)
+  //           }, 2000)
+  //         }
+  //       });
+  //
+  //     }
+  //   });
+  // },
 
   /**
    * todo 游玩时间倒计时
@@ -929,7 +929,7 @@ export default {
 
 
   getNowTime() {
-    var date = new Date();
+    const date = new Date();
     const year = date.getFullYear();
     const month = date.getMonth() + 1;
     const day = date.getDate();

+ 413 - 7
src/utils/connection.js

@@ -1,4 +1,20 @@
 import ble_store from "../store/bluetooth";
+import game_store from "../store/game";
+import Toast from "../../static/vant/toast/toast";
+import Notify from "../../static/vant/notify/notify";
+
+//记录教具连接的id
+let current_toy_id = "00";
+//记录教具连接状态
+let connect_toy = true;
+let ToyPower = 0;
+
+function getDeviceInfo() {
+  let deviceId = ble_store.getters.getDeviceId();
+  let serviceId = ble_store.getters.getServiceId();
+  let characteristicId = ble_store.getters.getCharacteristicId();
+  return { deviceId, serviceId, characteristicId };
+}
 
 export default {
   /**
@@ -22,7 +38,7 @@ export default {
           }
         }
       },
-      fail(res) {
+      fail() {
         let deviceId = wx.getStorageSync('deviceId');
         //断开蓝牙连接
         wx.closeBLEConnection({
@@ -36,6 +52,7 @@ export default {
    * 获取蓝牙设备某个服务中所有特征值
    */
   getBLEDeviceCharacteristics(deviceId, serviceId) {
+    const that = this;
     wx.getBLEDeviceCharacteristics({
       deviceId,
       serviceId,
@@ -54,12 +71,16 @@ export default {
           }
           if (item.properties.notify || item.properties.indicate) {
             console.log("第" + (i + 1) + ",该特征值可监听:" + item.uuid);
-            // 必须先启用 wx.notifyBLECharacteristicValueChange 才能监听到设备 onBLECharacteristicValueChange 的事件
+            // 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征。
             wx.notifyBLECharacteristicValueChange({
-              deviceId,
-              serviceId,
+              deviceId: deviceId,
+              serviceId: serviceId,
               characteristicId: item.uuid,
               state: true,
+              success() {
+                that.notifyDatas(null);
+                console.log("正在监听特征值:", item.uuid);
+              }
             });
           }
         }
@@ -103,9 +124,7 @@ export default {
    * @constructor
    */
   WriteBufferInBle($hex, $buffer_len = 8) {
-    let deviceId = ble_store.getters.getDeviceId();
-    let serviceId = ble_store.getters.getServiceId();
-    let characteristicId = ble_store.getters.getCharacteristicId()
+    let { deviceId, serviceId, characteristicId } = getDeviceInfo();
     if (deviceId && serviceId && characteristicId) {
       let that = this;
       let $hex_header = "aa cc ";
@@ -136,4 +155,391 @@ export default {
       });
     }
   },
+
+  /**
+   * 监听脑机数据
+   * @param $this
+   * @param characteristicId
+   */
+  notifyDatas($this) {
+    const that = this;
+    let deviceId = ble_store.getters.getDeviceId();
+    // 监听蓝牙低功耗设备的特征值变化事件
+    wx.onBLECharacteristicValueChange((characteristic) => {
+      let hexStr = that.ab2hex(characteristic.value);
+      console.log("监听脑机数据:", hexStr, "当前页面名称:", $this?$this.$options.name:"");
+      // 监听佩戴正确, 当s1为 00时 数据有效
+      if (hexStr.substring(0, 6) === "555520") {
+        $this.device_bg = (hexStr.substring(8, 10) === "00");
+      }
+      // 监听脑机电量
+      if (hexStr.substring(0, 8) === "55550203") {
+        let $power = parseInt(hexStr.substr(8, 2), 16);
+        let $voltage = parseInt(hexStr.substr(10, 2), 16);
+        //监听是否插入USB
+        $this.hasUsb = $voltage.toString().substr(0, 1) === "1";
+        //  监听脑机电量
+        if ($power) {
+          $this.device_power = $power;
+          $this.device_voltage = $voltage;
+        }
+        if ($power < 10 && $power > 0) {
+          wx.showToast({ title: "脑机电量不足", icon: "none", duration: 2000});
+        }
+      }
+      // // 收到发送UUID的应答立马发送连接教具的指令
+      // if (hexStr.toUpperCase().indexOf("AADD8E") >= 0) {
+      //   //发送教具连接
+      //   that.WriteBufferInBle(`03 00 ${current_toy_id} 02 0A`)
+      // }
+
+      // 2021年10月20日17:18:13 判断教具 连接
+      if (hexStr.toUpperCase().indexOf("AADD0A") >= 0) {
+        //没连接上教具
+        if (hexStr.toUpperCase().indexOf("AADD0A0000") >= 0) {
+          $this.connect_toy = 3;
+          return false;
+        }
+        let $mHexStrIndex = hexStr.toUpperCase().indexOf("AADD0A");
+        let $hex_index = hexStr.substr($mHexStrIndex + 28, 2)
+        let $toy_id = hexStr.substr($mHexStrIndex + 8, 2)
+        console.log("连接", $hex_index)
+        console.log("教具", $toy_id)
+        // 连接上教具
+        if (new RegExp("00").test($hex_index) === true) {
+          console.log("一对多")
+          // 发送一对一连接 03 00 ${$toy_id} 01 0A
+          that.sendConnectOneToOne($toy_id);
+          current_toy_id = $toy_id;
+        }
+        if (new RegExp("01").test($hex_index) === true) {
+          console.log("一对一")
+          wx.showToast({title: "已连接到" + $this.toy_item.name });
+          $this.toy_connected = true;
+          //connect_toy = true;
+          $this.connect_toy = 2;
+          //连接成功后 获取一次教具名称
+          // 判断冥想模式不发送获取教具名字
+          if ($toy_id !== "80") {
+            setTimeout(() => {
+              that.SendOrder('87')
+            }, 3000)
+            // 更改为不断获取教具电量
+            let toy_interval = setInterval(() => {
+              let $game_status = game_store.getters.getGameStatus();
+              if($game_status === 1){
+                clearInterval(toy_interval);
+              } else{
+                that.SendOrder('8a');
+              }
+            }, 8000);
+          }
+        }
+      }
+      // 获取教具名称
+      if (hexStr.toUpperCase().indexOf("AADD87") >= 0) {
+        let $mHexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD87"))
+        let $datas = that.DoAnalysis($mHexStr, 10)
+        let $number = $datas.match(/\d+/)
+        let toy_list_pre = {'01': "SW", '02': "KL", '04': "SC", '05': "PP", '06': "SU", '09': "UF", '12': "JM", '13': "QM"}
+        let $sn = toy_list_pre[current_toy_id] + $number;
+        $this.toy_sn = $sn;
+        //保存教具sn
+        game_store.setters.setToySn($sn);
+        console.log("获取教具名称hexStr:",hexStr,",获取教具名称$sn",$sn);
+      }
+      if (hexStr.toUpperCase().indexOf("AAEE87") >= 0) {
+        //获取教具电量
+        if (current_toy_id !== '80') {
+          that.SendOrder('87')
+        }
+      }
+      // 获取教具电量
+      if (hexStr.toUpperCase().indexOf("AADD8A") >= 0) {//接收教具电量状态
+        let $_hexStr = hexStr.substr(hexStr.toUpperCase().indexOf("AADD8A") + 6);
+        let $power = parseInt($_hexStr.substr(0, 2), 16)
+        let $voltage = parseInt($_hexStr.substr(2, 2), 16)
+        connect_toy = true;
+        // $this.toy_power = Math.round(that.CalBLEPower($voltage));
+        if ($power > 0) {
+          $this.toy_power = $power
+          $this.toy_voltage = $voltage
+          ToyPower = $power;
+        }
+
+
+        // if (current_toy_UUID == "") {
+        //   //获取教具UUID
+        //   that.SendOrder('84')
+        // }
+      }
+
+
+
+
+      // 获取蓝牙低功耗设备(脑机)的信号强度
+      if (game_store.getters.getGameStatus() === 1) {
+        wx.getBLEDeviceRSSI({
+          deviceId: deviceId,
+          success(res) {$this.RSSI = res.RSSI;}
+        });
+      }
+
+
+
+
+
+
+      if (hexStr.toUpperCase().indexOf("AADD") >= 0 || hexStr.toUpperCase().indexOf("AAEE") >= 0 && update_state == false) {
+        let nowTime = Math.round(new Date() / 1000);
+        console.log("应答", hexStr, '时间:' + that.getNowTime(), "长度", hexStr.length / 2);
+        LogInDb(`${that.getNowTime()} 应答:${hexStr}`)
+      }
+      let $data = that.get_big_data(hexStr);
+      let $game_status = game_store.getters.getGameStatus();
+
+      // 教具断链
+      if (hexStr.toUpperCase().indexOf("AAEE70") >= 0) {
+        connect_toy = false
+        wx.showModal({
+          content: "教具已断开",
+          success(res) {
+            if (res.confirm) {
+              //重连机制
+              if ($game_status == 1) {
+                $this.game_finished();
+              }
+            }
+          }
+        })
+
+      }
+
+
+      if (hexStr.toUpperCase().indexOf("AAEE8A0000005A") >= 0) {
+        that.SendOrder("8a")
+      }
+
+      //防止在首页 连接的时候重复 选择教具 产生了发送多个教具电量
+      // if(hexStr.toUpperCase().indexOf("AAEE8A000000FF76") >= 0){
+      //   that.connect_toy = false;
+      // }
+
+      if (hexStr.toUpperCase().indexOf("AAEE07") >= 0) {
+        that.sendControl();
+      }
+
+
+
+
+      // 2021年10月25日09:15:50
+      // 读取教具UUID
+      if (hexStr.toUpperCase().indexOf("AADD84") >= 0) {//接收UUID 5个字节
+        let $hex_index = hexStr.toUpperCase().indexOf("AADD84") + 6;
+        let $datas = hexStr.substr($hex_index, 10);
+        if ($datas != "0000000000") {
+          console.log("以获取UUID:" + $datas)
+          // current_toy_UUID = $datas;
+          $this.toy_UUID = $datas;
+        }
+      }
+
+
+      if (hexStr.toUpperCase().indexOf("AADD09") >= 0) {
+        control_close = true;
+        connect_toy = false;
+      }
+
+
+
+
+      // 处理打开脑控的应答
+      if (hexStr.toUpperCase().indexOf("AADD07") >= 0) {
+        ble_store.setters.setBluetoothLinkStatus(true)
+        FlagOpenControl = true;
+      }
+
+
+
+      //游戏中模块
+      if ($game_status == 1 && $data) {
+        $this.do_datas($data);
+      }
+
+
+      // 监听原始数据
+      if (hexStr.substr(0, 6) == "5555e2") {
+        let _buffer = that.doOriginBufferToData(hexStr)
+        if ($game_status == 1) {
+          wx.setStorageSync('origin_buffer', wx.getStorageSync('origin_buffer') + _buffer.join(',') + ",")
+        }
+      }
+
+      //todo 打开原始数据
+      if (hexStr.toUpperCase().indexOf("AADD04") >= 0) {
+        raw_data_open = true;
+        that.Send2BOrder(true)
+        wx.setStorageSync('origin_buffer', "");
+      }
+
+      //todo 接收脑机关机指令
+      if (hexStr.toUpperCase().indexOf("AADD5A00000000A5") >= 0) {
+        Notify({
+          type: 'danger',
+          duration: 0,
+          message: '智脑机已关机,训练结束',
+          onOpened() {
+            setTimeout(() => {
+              $this.game_finished();
+              clearInterval(control_close_intv)
+            }, 2000)
+          }
+        });
+
+      }
+    });
+  },
+
+  /**
+   *  todo:监听蓝牙连接状态
+   *  监听蓝牙低功耗连接状态改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等
+   */
+  watchBLEstatus($this) {
+    let that = this;
+    // 微信自身监听低功耗蓝牙连接状态的改变事件
+    wx.onBLEConnectionStateChange((res) => {
+      // 该方法回调中可以用于处理连接意外断开等异常情况
+      ble_store.setters.setBluetoothLinkStatus(res.connected);
+      LogInDb(`${that.getNowTime()} 监听脑机断连`)
+      if (res.connected == false) {
+        //判断游戏是否游戏中
+        let $game_status = game_store.getters.getGameStatus();
+        if ($game_status == 1) {
+          // $that.game_finished();
+          Notify({
+            type: 'danger',
+            duration: 0,
+            message: '智脑机已断开连接,正在尝试重新连接',
+            onOpened() {
+              that.reconnect(res.deviceId, $this)
+            }
+          });
+          control_close = true
+          // connect_toy = false;
+        } else {
+          //关闭脑控
+          connect_toy = false;
+          game_store.setters.setGameStatus(0);
+          // 清空链接得设备 三值
+          ble_store.setters.clearDeviceToy();
+          $this.connect_toy = 0;
+          $this.connect_show = false;
+          $this.device_bg = false;
+          $this.device_status = 0;
+          $this.device = {}
+          $this.toy_UUID = "";
+          $this.$forceUpdate();
+          wx.closeBluetoothAdapter();
+          version = "";
+        }
+      }
+    });
+  },
+
+  /**
+   * todo:重新连接蓝牙
+   */
+  reconnect($deviceId, $this) {
+    let that = this;
+    let $deviceInfo = getServicesAndCharateristc();
+    //重连的次数
+    let $connect_count = 0;
+    let $rec = setInterval(() => {
+      let $game_status = game_store.getters.getGameStatus();
+      if ($game_status == 1) {
+        wx.createBLEConnection({
+          deviceId: $deviceInfo.deviceId,
+          success(res) {
+            clearInterval($rec)
+            Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
+            LogInDb(`${that.getNowTime()} 第${$connect_count}次重新连接成功`)
+            let $system = wx.getSystemInfoSync()
+            if ($system.platform == 'ios') {
+              that.getBLEDeviceServices($deviceInfo.deviceId)
+              that.notifyDatas($this)
+            } else {
+              that.openNotify($this)
+              that.watchBLEstatus($this);
+            }
+            // that.sendToyPower();
+
+          },
+          fail(res) {
+            Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
+            game_store.setters.setGameCloseStatus(1);
+          }
+        })
+        if ($connect_count >= 3) {
+          $this.game_finished();
+          clearInterval($rec)
+        }
+        $connect_count += 1;
+      } else {
+        clearInterval($rec)
+      }
+    }, 7000)
+
+  },
+
+  /**
+   * 关闭脑机蓝牙连接
+   */
+  closeConnection($this) {
+    const that = this;
+    // 断开教具及蓝牙连接
+    that.SendOrder("31");
+    setTimeout(()=>{
+      that.SendOrder("09");
+      // 移除搜索到新设备的事件的全部监听函数
+      wx.offBluetoothDeviceFound();
+      // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
+      wx.stopBluetoothDevicesDiscovery();
+
+      let deviceId = ble_store.getters.getDeviceId();
+      //断开蓝牙连接
+      wx.closeBLEConnection({
+        deviceId: deviceId,
+        success() {
+          Toast.success({
+            message: "断开蓝牙连接成功",
+          });
+          ble_store.setters.clearDeviceToy();
+          wx.closeBluetoothAdapter();
+          console.log("断开蓝牙连接成功", deviceId);
+        },
+        fail(err) {
+          console.log("断开蓝牙连接"+deviceId+"失败error:", err);
+        },
+        complete() {
+          $this.device = {};
+          $this.toy_UUID = "";
+          $this.$forceUpdate();
+        },
+      });
+    },500);
+  },
+  /**
+   * 获取当前时间
+   */
+  getNowTime() {
+    const date = new Date();
+    const year = date.getFullYear();
+    const month = date.getMonth() + 1;
+    const day = date.getDate();
+    const hour = date.getHours();
+    const minutes = date.getMinutes();
+    const seconds = date.getSeconds();
+    const millSeconds = date.getMilliseconds();
+    return `${year}/${month}/${day} ${hour}:${minutes}:${seconds}.${millSeconds}`;
+  },
 };