Kaynağa Gözat

优化蓝牙连接流程2

chaooo 1 yıl önce
ebeveyn
işleme
b372065813

+ 2 - 2
src/components/connection/brains/scan.vue

@@ -123,7 +123,7 @@ export default {
                     fail(err) {
                       setTimeout(() => {
                         Toast.fail({
-                          message: $this.$bluetooth.GetopenBluetoothAdapterError(err["errCode"]),
+                          message: $this.$connection.connectionError(err["errCode"]),
                         });
                       }, 3000);
                     },
@@ -133,7 +133,7 @@ export default {
               fail(err) {
                 setTimeout(() => {
                   Toast.fail({
-                    message: $this.$bluetooth.GetopenBluetoothAdapterError(err["errCode"]),
+                    message: $this.$connection.connectionError(err["errCode"]),
                   });
                 }, 3000);
               },

+ 10 - 37
src/components/connection/index.vue

@@ -34,32 +34,15 @@ export default {
       connect_toy: 0,
 
 
-
-      // $this.$bluetooth 设置的参数
+      // $this.$connection 设置的参数
       // 设置图标的颜色
       device_bg: false,
       // 电量
       device_power: 0,
       // 判断是否已经连接教具
-      toy_connected: false,
+      // toy_connected: false,
       toy_sn:"",
       toy_power:0,
-
-
-
-
-
-
-      connect_show: false,
-      device:{},
-      toy_UUID:"",
-      // 信号强度
-      RSSI:0,
-      device_voltage: 0,
-      toy_voltage:0,
-      current_hex:"",
-      hasUsb:false,
-
     }
   },
   created() {
@@ -88,7 +71,6 @@ export default {
           if ($serviceId) {
             clearInterval($checkServices);
             // 监听数据
-            //$this.$bluetooth.openNotify($this);
             $this.$connection.notifyDatas($this);
             $this.$connection.watchBLEstatus($this);
           }
@@ -97,7 +79,7 @@ export default {
         game_store.setters.setGameStatus(0);
         // todo 清空链接的设备
         $this.connect_toy = $status;
-        $this.connect_show = false;
+        //$this.connect_show = false;
         $this.device_bg = false;
         $this.connect_status = false;
         if ($status * 1 > 0) {
@@ -115,7 +97,7 @@ export default {
       this.toy_sn = "教具";
       if ($this.device_status*1 === 2) {
         // 关闭脑控
-        this.$bluetooth.SendOrder("09");
+        this.$connection.SendOrder("09");
       }
     },
     //关闭窗口
@@ -129,18 +111,9 @@ export default {
       if($this.toy_item && $this.toy_item.id > 0) {
         $this.setToyStatus(1);
         $this.$connection.sendToyConnection($this.toy_item);
-        // let $hex = ($this.toy_hex = $this.toy_item["hex"].substr($this.toy_item["hex"].length - 2, 2));
-        // if ($hex === "80") {
-        //   wx.setStorageSync("report_mode", 2)
-        // } else {
-        //   wx.setStorageSync("report_mode", 1)
-        // }
-        // console.log("连接教具:", `03 00 ${$hex} 00 0a`, JSON.stringify($this.toy_item));
-        // // 连接教具: 03 00 ${$hex} 00 0a
-        // $this.$bluetooth.sendConnectOneToMore($hex);
         //2022-5-25 09:07:59 设置10秒后是否已经连接
         setTimeout(() => {
-          if ($this.toy_connected === false) {
+          if ($this.connect_toy !== 2) {
             $this.setToyStatus(3);
           }
         }, 10000);
@@ -179,10 +152,10 @@ export default {
 
       //不在游戏状态
       $this.connect_toy = 0;
-      $this.connect_show = true;
+      //$this.connect_show = true;
       // 监听数据
-      $this.$bluetooth.notifyDatas($this);
-      $this.$bluetooth.watchBLEstatus($this);
+      $this.$connection.notifyDatas($this);
+      $this.$connection.watchBLEstatus($this);
 
       //$this.toy_UUID = "";
 
@@ -190,9 +163,9 @@ export default {
       if ($game_close_status === 1) {
         // 重置默认条件
         $this.connect_toy = 0;
-        $this.connect_show = false;
+        //$this.connect_show = false;
         $this.device_status = 0;
-        $this.$bluetooth.watchBLEstatus($this);
+        $this.$connection.watchBLEstatus($this);
         //$this.toy_UUID = "";
         // 清空链接的设备
         ble_store.setters.clearDeviceToy();

+ 27 - 20
src/pages/start/index.vue

@@ -175,6 +175,7 @@ import mpvueEcharts from "mpvue-echarts";
 import echarts from "../../../static/echarts.min";
 import {LogInDb} from "@/requests/log";
 import WechatLog from '@/utils/wechat_log'
+import {formatPlaySeconds, get_big_data} from "../../utils/game";
 var att_charts, med_charts, $this;
 
 // 大脑图表初始化
@@ -207,7 +208,7 @@ function initMedChart(canvas, width, height) {
 
 var $timeout;
 export default {
-  name: "start_container",
+  name: "StartGames",
   components: {
     mpvueEcharts,
   },
@@ -217,6 +218,10 @@ export default {
       echarts,
       attCharts: initAttChart,
       medCharts: initMedChart,
+      // 监听到的蓝牙数据
+      hexStr:"",
+
+
       // 使用类型 1次数 2时间 0未选择
       mode: 0,
 
@@ -276,9 +281,9 @@ export default {
       game_status: 0,
 
       toy_power: 0,
-      toy_voltage: 0,
+      //toy_voltage: 0,
       device_power: 0,
-      device_voltage: 0,
+      //device_voltage: 0,
 
       toy_UUID: "",
 
@@ -309,9 +314,9 @@ export default {
     //游戏结束方法
     game_finished() {
       if (!$this.executed) {
-        LogInDb(`${$this.$bluetooth.getNowTime()} 游戏结束`)
+        LogInDb(`${$this.$connection.getNowTime()} 游戏结束`)
         // 关闭脑控
-        $this.$bluetooth.sendControlClose();
+        $this.$connection.sendControlClose();
 
         $this.$emit("closePop", true);
 
@@ -365,26 +370,26 @@ export default {
           $this.attList = [];
           $this.medList = [];
           $this.ampList = [];
-          LogInDb(`${$this.$bluetooth.getNowTime()} 生成报告`)
+          LogInDb(`${$this.$connection.getNowTime()} 生成报告`)
         },
       });
     },
     // 开始游戏
     start_game() {
-      LogInDb(`${$this.$bluetooth.getNowTime()} 开始游戏`)
+      LogInDb(`${$this.$connection.getNowTime()} 开始游戏`)
       wx.setKeepScreenOn({
         keepScreenOn: true,
       });
-      $this.$bluetooth.sendAutoConnectRf(true, Math.round($this.played_time / 60));
-      $this.$bluetooth.notifyDatas($this);
+      $this.$connection.sendAutoConnectRf(true, Math.round($this.played_time / 60));
+      $this.$connection.notifyDatas($this);
       setTimeout(()=>{
         // 获取LED灯状态并设置
         let led_status = game_store.getters.getLED();
         console.log("开始游戏获取LED灯状态", led_status)
         if(led_status){
-          $this.$bluetooth.SendLedOrder("01");
+          $this.$connection.SendLedOrder("01");
         }else{
-          $this.$bluetooth.SendLedOrder("00");
+          $this.$connection.SendLedOrder("00");
         }
       },500);
       setTimeout(()=>{
@@ -392,9 +397,9 @@ export default {
         let $toy_sn = game_store.getters.getToySn().toUpperCase();
         if($toy_sn.includes("SW") || $toy_sn.includes("KL") || $toy_sn.includes("SC")){
           // 设置教具为无运动状态 AA CC 03 00 00 00 34 CKS
-          $this.$bluetooth.SendMotionOrder("01");
+          $this.$connection.SendMotionOrder("01");
         } else {
-          $this.$bluetooth.SendMotionOrder("00");
+          $this.$connection.SendMotionOrder("00");
         }
       },1000);
       // 开始倒计时
@@ -404,12 +409,12 @@ export default {
           //自定义定时器
           $this.played_time -= 1;
           game_store.setters.setPlayedTime($this.played_time)
-          $this.played_time_text = $this.$bluetooth.formatPlaySeconds($this.played_time);
+          $this.played_time_text = formatPlaySeconds($this.played_time);
         }
         if ($this.played_time === 0) {
           $this.post_data();
           //判断是否隐藏 隐藏则不绘画
-          $this.$bluetooth.sendControlClose();
+          $this.$connection.sendControlClose();
           let $hide_status = game_store.getters.getHideStatus();
           if (!$hide_status) {
             $this.game_finished();
@@ -484,9 +489,12 @@ export default {
         game_store.setters.setMode(0);
       });
     },
+    analysisGameData: function(hexStr){
+      let $data = get_big_data(hexStr);
+      this.do_datas($data);
+    },
     //  处理游戏中数据的方法
     do_datas: function ($data) {
-
       $this.online_att = $data["att"];
       $this.online_med = $data["med"];
       let $att_msg = "";
@@ -597,23 +605,22 @@ export default {
     }
   },
   mounted() {
-    console.log($this.$bluetooth.ToyPower)
     $this.executed = false;
     $this.deviceId = "";
-    $this.toy_UUID = "";
+    //$this.toy_UUID = "";
     $this.deviceId = ble_store.getters.getDeviceId();
     // setTimeout(() => {
     $this.game_status = game_store.getters.getGameStatus();
     // }, 1000)
     //判断是否结束游戏
-    if ($this.is_end == true) {
+    if ($this.is_end === true) {
       $this.game_finished();
     } else {
       $this.calThePlayedTime();
       $this.start_game();
 
       //打开蓝牙监听
-      $this.$bluetooth.watchBLEstatus($this);
+      $this.$connection.watchBLEstatus($this);
     }
   },
   created() {

+ 3 - 3
src/pages/user_center/firmware/index.vue

@@ -145,7 +145,7 @@ export default {
                     },
                     fail(err) {
                       let $msg =
-                        $this.$bluetooth.GetopenBluetoothAdapterError(
+                        $this.$connection.connectionError(
                           err["errCode"]
                         );
                       setTimeout(() => {
@@ -158,7 +158,7 @@ export default {
                 }
               },
               fail(err) {
-                let $msg = $this.$bluetooth.GetopenBluetoothAdapterError(
+                let $msg = $this.$connection.connectionError(
                   err["errCode"]
                 );
                 setTimeout(() => {
@@ -179,7 +179,7 @@ export default {
                 }
               },
               fail(err) {
-                let $msg = $this.$bluetooth.GetopenBluetoothAdapterError(
+                let $msg = $this.$connection.connectionError(
                   err["errCode"]
                 );
                 setTimeout(() => {

+ 332 - 332
src/utils/bluetooth.js

@@ -122,59 +122,59 @@ export default {
     //   }
     // }, 3000)
   },
-  /**
-   *  todo:关闭脑控
-   */
-  sendControlClose() {
-    let that = this
-    setTimeout(()=>{
-      // 打开LED
-      that.SendLedOrder("01");
-    },500);
-    setTimeout(()=>{
-      // 关闭脑控
-      that.SendOrder('09');
-      //清空当前数据
-      that.clearLocalDatas();
-      //设置打开脑控为false
-      FlagOpenControl = false;
-      //清空当前数据
-      that.clearLocalDatas()
-    },1000);
-    // setTimeout(()=>{
-    //   // 断开教具及蓝牙连接
-    //   that.SendOrder("31");
-    // },1500);
-    // 兼容二代脑机,不能退出循环
-    // if (!is_new) {
-    //   control_close = false;
-    //   control_close_intv = setInterval(() => {
-    //     if (!control_close) {
-    //       //如果是jellyfish则发送00教具
-    //         that.sendConnectOneToMore('00')
-    //     } else {
-    //       //设置打开脑控为false
-    //       FlagOpenControl = false;
-    //       clearInterval(control_close_intv)
-    //       //清空当前数据
-    //       that.clearLocalDatas()
-    //     }
-    //   }, 2000)
-    // }
-  },
-  /**
-   *  todo:发送一对多连接
-   */
-  sendConnectOneToMore(id) {
-    this.WriteBufferInBle(`03 00 ${id} 00 0A`);
-  },
-  /**
-   *  todo:发送一对一连接
-   */
-  sendConnectOneToOne(id) {
-    current_toy_id = id;
-    this.WriteBufferInBle(`03 00 ${id} 01 0A`)
-  },
+  // /**
+  //  *  todo:关闭脑控
+  //  */
+  // sendControlClose() {
+  //   let that = this
+  //   setTimeout(()=>{
+  //     // 打开LED
+  //     that.SendLedOrder("01");
+  //   },500);
+  //   setTimeout(()=>{
+  //     // 关闭脑控
+  //     that.SendOrder('09');
+  //     //清空当前数据
+  //     that.clearLocalDatas();
+  //     //设置打开脑控为false
+  //     FlagOpenControl = false;
+  //     //清空当前数据
+  //     that.clearLocalDatas()
+  //   },1000);
+  //   // setTimeout(()=>{
+  //   //   // 断开教具及蓝牙连接
+  //   //   that.SendOrder("31");
+  //   // },1500);
+  //   // 兼容二代脑机,不能退出循环
+  //   // if (!is_new) {
+  //   //   control_close = false;
+  //   //   control_close_intv = setInterval(() => {
+  //   //     if (!control_close) {
+  //   //       //如果是jellyfish则发送00教具
+  //   //         that.sendConnectOneToMore('00')
+  //   //     } else {
+  //   //       //设置打开脑控为false
+  //   //       FlagOpenControl = false;
+  //   //       clearInterval(control_close_intv)
+  //   //       //清空当前数据
+  //   //       that.clearLocalDatas()
+  //   //     }
+  //   //   }, 2000)
+  //   // }
+  // },
+  // /**
+  //  *  todo:发送一对多连接
+  //  */
+  // sendConnectOneToMore(id) {
+  //   this.WriteBufferInBle(`03 00 ${id} 00 0A`);
+  // },
+  // /**
+  //  *  todo:发送一对一连接
+  //  */
+  // sendConnectOneToOne(id) {
+  //   current_toy_id = id;
+  //   this.WriteBufferInBle(`03 00 ${id} 01 0A`)
+  // },
 
   /**
    *  todo:获取教具电量
@@ -198,48 +198,48 @@ export default {
     // }
   },
 
-  /**
-   *  todo:获取大包数据进行绘制图表
-   */
-  get_big_data(hex) {
-    let hexAry = []
-    for (let i = 0; i < hex.length; i += 2) {
-      hexAry.push(hex.substr(i, 2))
-    }
-    if (hex.substr(0, 6) != "555520") {
-      return false;
-    }
-    //当s1为 00时 数据有效
-    // let hex_str = hex.substr(hex.indexOf("555520"))
-    // let $s1 = hex_str.substr(8, 2);
-    let $s1 = hexAry[4]
-    if ($s1 !== "00") {
-      return false;
-    }
-
-    //专注度数据
-    let $att = parseInt(hexAry[6], 16)
-    //放松度数据
-    let $med = parseInt(hexAry[8], 16)
-
-    let idx = 0
-    let dataIndex = ['delta', 'theta', "low_alpha", "high_alpha", "low_beta", "high_beta", "low_gamma", "middle_gamma"]
-    let datas = []
-    hexAry.pop()
-    for (let i = 11; i < hexAry.length; i += 3) {
-      let num_1 = parseInt(hexAry[i], 16)
-      let num_2 = parseInt(hexAry[i + 1], 16)
-      let num_3 = parseInt(hexAry[i + 2], 16)
-      let show_value = num_1 + num_2 + num_3;
-      let basic_value = parseInt("0x" + hexAry[i] << 16 | "0x" + hexAry[i + 1] << 8 | "0x" + hexAry[i + 2], 16)
-      datas[dataIndex[idx]] = show_value
-      datas[`${dataIndex[idx]}_basic`] = basic_value
-      idx += 1;
-    }
-    datas['att'] = $att;
-    datas['med'] = $med;
-    return datas
-  },
+  // /**
+  //  *  todo:获取大包数据进行绘制图表
+  //  */
+  // get_big_data(hex) {
+  //   let hexAry = []
+  //   for (let i = 0; i < hex.length; i += 2) {
+  //     hexAry.push(hex.substr(i, 2))
+  //   }
+  //   if (hex.substr(0, 6) != "555520") {
+  //     return false;
+  //   }
+  //   //当s1为 00时 数据有效
+  //   // let hex_str = hex.substr(hex.indexOf("555520"))
+  //   // let $s1 = hex_str.substr(8, 2);
+  //   let $s1 = hexAry[4]
+  //   if ($s1 !== "00") {
+  //     return false;
+  //   }
+  //
+  //   //专注度数据
+  //   let $att = parseInt(hexAry[6], 16)
+  //   //放松度数据
+  //   let $med = parseInt(hexAry[8], 16)
+  //
+  //   let idx = 0
+  //   let dataIndex = ['delta', 'theta', "low_alpha", "high_alpha", "low_beta", "high_beta", "low_gamma", "middle_gamma"]
+  //   let datas = []
+  //   hexAry.pop()
+  //   for (let i = 11; i < hexAry.length; i += 3) {
+  //     let num_1 = parseInt(hexAry[i], 16)
+  //     let num_2 = parseInt(hexAry[i + 1], 16)
+  //     let num_3 = parseInt(hexAry[i + 2], 16)
+  //     let show_value = num_1 + num_2 + num_3;
+  //     let basic_value = parseInt("0x" + hexAry[i] << 16 | "0x" + hexAry[i + 1] << 8 | "0x" + hexAry[i + 2], 16)
+  //     datas[dataIndex[idx]] = show_value
+  //     datas[`${dataIndex[idx]}_basic`] = basic_value
+  //     idx += 1;
+  //   }
+  //   datas['att'] = $att;
+  //   datas['med'] = $med;
+  //   return datas
+  // },
   /**
    *  todo:获取设备电量
    */
@@ -435,20 +435,20 @@ export default {
   //   });
   // },
 
-  /**
-   * todo ArrayBuffer转16进度字符串示例
-   * @param buffer
-   * @returns {string}
-   */
-  ab2hex(buffer) {
-    var hexArr = Array.prototype.map.call(
-      new Uint8Array(buffer),
-      function (bit) {
-        return ("00" + bit.toString(16)).slice(-2);
-      }
-    );
-    return hexArr.join("");
-  },
+  // /**
+  //  * todo ArrayBuffer转16进度字符串示例
+  //  * @param buffer
+  //  * @returns {string}
+  //  */
+  // ab2hex(buffer) {
+  //   var hexArr = Array.prototype.map.call(
+  //     new Uint8Array(buffer),
+  //     function (bit) {
+  //       return ("00" + bit.toString(16)).slice(-2);
+  //     }
+  //   );
+  //   return hexArr.join("");
+  // },
 
 
   // /**
@@ -714,131 +714,131 @@ export default {
   //   });
   // },
 
-  /**
-   * todo 游玩时间倒计时
-   * @param value
-   * @returns {string}
-   */
-  formatPlaySeconds(value) {
-    // 字符串转数字
-    var secondTime = parseInt(value); // 秒
-    var minuteTime = 0; // 分
-    if (secondTime > 60) {
-      //如果秒数大于60,将秒数转换成整数
-      //获取分钟,除以60取整数,得到整数分钟
-      minuteTime = parseInt(secondTime / 60);
-      //获取秒数,秒数取佘,得到整数秒数
-      secondTime = parseInt(secondTime % 60);
-      //如果分钟大于60,将分钟转换成小时
-    }
-    var result = "" + parseInt(secondTime);
-
-    if (minuteTime > 0) {
-      if (result.length == 1) {
-        result = "0" + result;
-      }
-      if (parseInt(minuteTime).toString().length == 1) {
-        minuteTime = "0" + parseInt(minuteTime);
-      }
-      result = "" + minuteTime + ":" + result;
-    } else {
-      result = "00:" + result;
-    }
-    return result;
-  },
-
-  /**
-   * todo 根据错误代码返回字符串信息
-   * @param errCode
-   * @returns {string}
-   * @constructor
-   */
-  GetopenBluetoothAdapterError(errCode) {
-
-    let $errmsg = "";
-    if (errCode == 10000) {
-      $errmsg = "未初始化蓝牙适配器"
-    }
-
-    if (errCode == 10001) {
-      $errmsg = "当前蓝牙适配器不可用"
-    }
-
-    if (errCode == 10002) {
-      $errmsg = "没有找到指定设备"
-    }
-
-    if (errCode == 10003) {
-      $errmsg = "连接失败"
-    }
-
-    if (errCode == 10006) {
-      $errmsg = "当前连接已断开"
-    }
-
-    return $errmsg;
-  },
-
-  /**
-   * todo 写入buffer
-   * @param $hex
-   * @param $buffer_len
-   * @constructor
-   */
-  WriteBufferInBle($hex, $buffer_len = 8) {
-    let that = this;
-    let $deviceInfo = getServicesAndCharateristc();
-    let $hex_header = "aa cc ";
-    // let $hex = "03 00 01 00 0a";
-
-    let $hex_sum = 0;
-    let $hex_ary = $hex.split(" ");
-    $hex_ary.forEach(($val, $index) => {
-      $hex_sum += parseInt($val, 16);
-    })
-
-    let $checksum = ($hex_sum ^ parseInt($8f, 16)) & parseInt($ff, 16);
-
-    $hex = $hex_header + $hex + " " + ("00" + $checksum.toString(16)).substr(-2, 2);
-    let buffer = new ArrayBuffer($buffer_len);
-    let dataView = new DataView(buffer);
-    $hex_ary = $hex.split(" ");
-    $hex_ary.forEach(($val, $index) => {
-      dataView.setUint8($index, parseInt($val, 16))
-    })
+  // /**
+  //  * todo 游玩时间倒计时
+  //  * @param value
+  //  * @returns {string}
+  //  */
+  // formatPlaySeconds(value) {
+  //   // 字符串转数字
+  //   var secondTime = parseInt(value); // 秒
+  //   var minuteTime = 0; // 分
+  //   if (secondTime > 60) {
+  //     //如果秒数大于60,将秒数转换成整数
+  //     //获取分钟,除以60取整数,得到整数分钟
+  //     minuteTime = parseInt(secondTime / 60);
+  //     //获取秒数,秒数取佘,得到整数秒数
+  //     secondTime = parseInt(secondTime % 60);
+  //     //如果分钟大于60,将分钟转换成小时
+  //   }
+  //   var result = "" + parseInt(secondTime);
+  //
+  //   if (minuteTime > 0) {
+  //     if (result.length == 1) {
+  //       result = "0" + result;
+  //     }
+  //     if (parseInt(minuteTime).toString().length == 1) {
+  //       minuteTime = "0" + parseInt(minuteTime);
+  //     }
+  //     result = "" + minuteTime + ":" + result;
+  //   } else {
+  //     result = "00:" + result;
+  //   }
+  //   return result;
+  // },
 
+  // /**
+  //  * todo 根据错误代码返回字符串信息
+  //  * @param errCode
+  //  * @returns {string}
+  //  * @constructor
+  //  */
+  // GetopenBluetoothAdapterError(errCode) {
+  //
+  //   let $errmsg = "";
+  //   if (errCode == 10000) {
+  //     $errmsg = "未初始化蓝牙适配器"
+  //   }
+  //
+  //   if (errCode == 10001) {
+  //     $errmsg = "当前蓝牙适配器不可用"
+  //   }
+  //
+  //   if (errCode == 10002) {
+  //     $errmsg = "没有找到指定设备"
+  //   }
+  //
+  //   if (errCode == 10003) {
+  //     $errmsg = "连接失败"
+  //   }
+  //
+  //   if (errCode == 10006) {
+  //     $errmsg = "当前连接已断开"
+  //   }
+  //
+  //   return $errmsg;
+  // },
 
-    if (!$deviceInfo.charateristic.write) {
-      return false;
-    }
-    wx.writeBLECharacteristicValue({
-      deviceId: $deviceInfo.deviceId,
-      serviceId: $deviceInfo.service,
-      characteristicId: $deviceInfo.charateristic.write,
-      value: buffer,
-      success: function (res) {
-        if ($buffer_len <= 16) {
-          console.log($hex + ',写入成功,时间:' + that.getNowTime())
-        } else {
-          console.log('写入成功,时间:' + that.getNowTime())
-        }
-        // LogInDb(`${that.getNowTime()} ${$hex}',写入成功`)
-      },
-      fail: function (err) {
-        console.log($hex + "写入失败", err);
-      },
-    });
-  },
+  // /**
+  //  * todo 写入buffer
+  //  * @param $hex
+  //  * @param $buffer_len
+  //  * @constructor
+  //  */
+  // WriteBufferInBle($hex, $buffer_len = 8) {
+  //   let that = this;
+  //   let $deviceInfo = getServicesAndCharateristc();
+  //   let $hex_header = "aa cc ";
+  //   // let $hex = "03 00 01 00 0a";
+  //
+  //   let $hex_sum = 0;
+  //   let $hex_ary = $hex.split(" ");
+  //   $hex_ary.forEach(($val, $index) => {
+  //     $hex_sum += parseInt($val, 16);
+  //   })
+  //
+  //   let $checksum = ($hex_sum ^ parseInt($8f, 16)) & parseInt($ff, 16);
+  //
+  //   $hex = $hex_header + $hex + " " + ("00" + $checksum.toString(16)).substr(-2, 2);
+  //   let buffer = new ArrayBuffer($buffer_len);
+  //   let dataView = new DataView(buffer);
+  //   $hex_ary = $hex.split(" ");
+  //   $hex_ary.forEach(($val, $index) => {
+  //     dataView.setUint8($index, parseInt($val, 16))
+  //   })
+  //
+  //
+  //   if (!$deviceInfo.charateristic.write) {
+  //     return false;
+  //   }
+  //   wx.writeBLECharacteristicValue({
+  //     deviceId: $deviceInfo.deviceId,
+  //     serviceId: $deviceInfo.service,
+  //     characteristicId: $deviceInfo.charateristic.write,
+  //     value: buffer,
+  //     success: function (res) {
+  //       if ($buffer_len <= 16) {
+  //         console.log($hex + ',写入成功,时间:' + that.getNowTime())
+  //       } else {
+  //         console.log('写入成功,时间:' + that.getNowTime())
+  //       }
+  //       // LogInDb(`${that.getNowTime()} ${$hex}',写入成功`)
+  //     },
+  //     fail: function (err) {
+  //       console.log($hex + "写入失败", err);
+  //     },
+  //   });
+  // },
 
-  /**
-   * todo写入8位指令
-   * @param id 末尾id
-   * @constructor
-   */
-  SendOrder(id) {
-    let $hexStr = `03 00 00 00 ${id}`;
-    this.WriteBufferInBle($hexStr)
-  },
+  // /**
+  //  * todo写入8位指令
+  //  * @param id 末尾id
+  //  * @constructor
+  //  */
+  // SendOrder(id) {
+  //   let $hexStr = `03 00 00 00 ${id}`;
+  //   this.WriteBufferInBle($hexStr)
+  // },
 
   /**
    * todo 写入16个字节的指令
@@ -859,43 +859,43 @@ export default {
     this.WriteBufferInBle($hexStr, 16)
   },
 
-  /**
-   * 打开或关闭LED灯 AA CC 03 00 00 ctrl EC CKS
-   * 00/01
-   */
-  SendLedOrder(id) {
-    let $hexStr = `03 00 00 ${id} ec`;
-    this.WriteBufferInBle($hexStr)
-  },
-
-  /**
-   * 设置教具为无运动状态 AA CC 03 00 00 00 34 CKS
-   * 00/01
-   */
-  SendMotionOrder(id) {
-    let $hexStr = `03 00 00 ${id} 34`;
-    this.WriteBufferInBle($hexStr)
-  },
+  // /**
+  //  * 打开或关闭LED灯 AA CC 03 00 00 ctrl EC CKS
+  //  * 00/01
+  //  */
+  // SendLedOrder(id) {
+  //   let $hexStr = `03 00 00 ${id} ec`;
+  //   this.WriteBufferInBle($hexStr)
+  // },
+  //
+  // /**
+  //  * 设置教具为无运动状态 AA CC 03 00 00 00 34 CKS
+  //  * 00/01
+  //  */
+  // SendMotionOrder(id) {
+  //   let $hexStr = `03 00 00 ${id} 34`;
+  //   this.WriteBufferInBle($hexStr)
+  // },
 
-  /**
-   * todo 解析hex
-   * @param hexStr
-   * @param byte_count
-   * @param sublen
-   * @returns {string}
-   * @constructor
-   */
-  DoAnalysis(hexStr, byte_count, sublen = 6) {
-    //byte_count
-    let $_str5 = hexStr.substr(sublen);
-    let $datas = $_str5.substr(0, byte_count * 2);
-    let $_data = "";
-    for (let $i = 0; $i < $datas.length; $i += 2) {
-      let $code = parseInt($datas.substr($i, 2), 16)
-      $_data += String.fromCharCode($code)
-    }
-    return $_data;
-  },
+  // /**
+  //  * todo 解析hex
+  //  * @param hexStr
+  //  * @param byte_count
+  //  * @param sublen
+  //  * @returns {string}
+  //  * @constructor
+  //  */
+  // DoAnalysis(hexStr, byte_count, sublen = 6) {
+  //   //byte_count
+  //   let $_str5 = hexStr.substr(sublen);
+  //   let $datas = $_str5.substr(0, byte_count * 2);
+  //   let $_data = "";
+  //   for (let $i = 0; $i < $datas.length; $i += 2) {
+  //     let $code = parseInt($datas.substr($i, 2), 16)
+  //     $_data += String.fromCharCode($code)
+  //   }
+  //   return $_data;
+  // },
 
   /**
    * todo 清空当前脚本的变量值
@@ -928,39 +928,39 @@ export default {
   },
 
 
-  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}`;
-  },
-
-  /**
-   * 自动发送RF重连
-   * @param  {Boolean} isOn    是否打开重连功能
-   * @param  {[type]}  timeOut 有效时间
-   * @return {[type]}          [description]
-   * AA CC 03 00 01 0a d0 21
-   */
-  sendAutoConnectRf(isOn, timeOut) {
-    let that = this;
-    let onVal = isOn ? '01' : '00';
-    let mTimeOut = timeOut.toString(16);
-
-    if (mTimeOut.length == 1) {
-      mTimeOut = `0${mTimeOut}`
-    }
+  // 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}`;
+  // },
 
-    let $hexStr = `03 00 ${onVal} ${mTimeOut} d0`;
-    this.WriteBufferInBle($hexStr)
-  },
+  // /**
+  //  * 自动发送RF重连
+  //  * @param  {Boolean} isOn    是否打开重连功能
+  //  * @param  {[type]}  timeOut 有效时间
+  //  * @return {[type]}          [description]
+  //  * AA CC 03 00 01 0a d0 21
+  //  */
+  // sendAutoConnectRf(isOn, timeOut) {
+  //   let that = this;
+  //   let onVal = isOn ? '01' : '00';
+  //   let mTimeOut = timeOut.toString(16);
+  //
+  //   if (mTimeOut.length == 1) {
+  //     mTimeOut = `0${mTimeOut}`
+  //   }
+  //
+  //   let $hexStr = `03 00 ${onVal} ${mTimeOut} d0`;
+  //   this.WriteBufferInBle($hexStr)
+  // },
 
   /**
    * 打开原始数据
@@ -970,18 +970,18 @@ export default {
     this.SendOrder('04')
   },
 
-  /**
-   * 接收原始数据开关
-   * @param status
-   * @constructor
-   */
-  Send2BOrder(status = true) {
-    let $hexStr = `03 00 00 01 2b`;
-    if (!status) {
-      $hexStr = `03 00 00 00 2b`;
-    }
-    this.WriteBufferInBle($hexStr)
-  },
+  // /**
+  //  * 接收原始数据开关
+  //  * @param status
+  //  * @constructor
+  //  */
+  // Send2BOrder(status = true) {
+  //   let $hexStr = `03 00 00 01 2b`;
+  //   if (!status) {
+  //     $hexStr = `03 00 00 00 2b`;
+  //   }
+  //   this.WriteBufferInBle($hexStr)
+  // },
 
   /**
    * 打开原始数据
@@ -991,27 +991,27 @@ export default {
     this.SendOrder('05')
   },
 
-  /**
-   * 转移原始数据
-   * @param buffer
-   * @returns {*[]}
-   */
-  doOriginBufferToData(buffer) {
-    let buffer_ary = []
-    for (let i = 8; i < buffer.length; i += 2) {
-      buffer_ary.push(parseInt(buffer.substr(i, 2), 16))
-    }
-    let _buffer_ary = buffer_ary.slice(0, buffer_ary.length - 2)
-    let _buffer_16_ary = []
-    for (let i = 0; i < _buffer_ary.length; i += 2) {
-      let high = _buffer_ary[i];
-      let low = _buffer_ary[i + 1]
-      var _firstNumber = (((high & 0xff) << 8) | (low & 0xff));
-      _buffer_16_ary.push(this.hex2int(_firstNumber.toString(16)))
-    }
-
-    return _buffer_16_ary;
-  },
+  // /**
+  //  * 转移原始数据
+  //  * @param buffer
+  //  * @returns {*[]}
+  //  */
+  // doOriginBufferToData(buffer) {
+  //   let buffer_ary = []
+  //   for (let i = 8; i < buffer.length; i += 2) {
+  //     buffer_ary.push(parseInt(buffer.substr(i, 2), 16))
+  //   }
+  //   let _buffer_ary = buffer_ary.slice(0, buffer_ary.length - 2)
+  //   let _buffer_16_ary = []
+  //   for (let i = 0; i < _buffer_ary.length; i += 2) {
+  //     let high = _buffer_ary[i];
+  //     let low = _buffer_ary[i + 1]
+  //     var _firstNumber = (((high & 0xff) << 8) | (low & 0xff));
+  //     _buffer_16_ary.push(this.hex2int(_firstNumber.toString(16)))
+  //   }
+  //
+  //   return _buffer_16_ary;
+  // },
 
   /**
    * 十六进制数转十进制

+ 354 - 200
src/utils/connection.js

@@ -7,14 +7,69 @@ import Notify from "../../static/vant/notify/notify";
 let current_toy_id = "00";
 //记录教具连接状态
 let connect_toy = true;
-let ToyPower = 0;
+//标记是否打开脑控
+let FlagOpenControl = false;
 
-function getDeviceInfo() {
+function getDeviceWriteInfo() {
   let deviceId = ble_store.getters.getDeviceId();
   let serviceId = ble_store.getters.getServiceId();
   let characteristicId = ble_store.getters.getCharacteristicId();
   return { deviceId, serviceId, characteristicId };
 }
+/**
+ * 转移原始数据
+ * @param buffer
+ * @returns {*[]}
+ */
+function doOriginBufferToData(buffer) {
+  let buffer_ary = []
+  for (let i = 8; i < buffer.length; i += 2) {
+    buffer_ary.push(parseInt(buffer.substr(i, 2), 16))
+  }
+  let _buffer_ary = buffer_ary.slice(0, buffer_ary.length - 2)
+  let _buffer_16_ary = []
+  for (let i = 0; i < _buffer_ary.length; i += 2) {
+    let high = _buffer_ary[i];
+    let low = _buffer_ary[i + 1]
+    var _firstNumber = (((high & 0xff) << 8) | (low & 0xff));
+    _buffer_16_ary.push(this.hex2int(_firstNumber.toString(16)))
+  }
+  return _buffer_16_ary;
+}
+/**
+ *  ArrayBuffer转16进度字符串示例
+ * @param buffer
+ * @returns {string}
+ */
+function ab2hex(buffer) {
+  const hexArr = Array.prototype.map.call(
+    new Uint8Array(buffer),
+    function (bit) {
+      return ("00" + bit.toString(16)).slice(-2);
+    }
+  );
+  return hexArr.join("");
+}
+
+/**
+ * todo 解析hex
+ * @param hexStr
+ * @param byte_count
+ * @param sublen
+ * @returns {string}
+ * @constructor
+ */
+function doAnalysis(hexStr, byte_count, sublen = 6) {
+  //byte_count
+  let $_str5 = hexStr.substring(sublen);
+  let $datas = $_str5.substring(0, byte_count * 2);
+  let $_data = "";
+  for (let $i = 0; $i < $datas.length; $i += 2) {
+    let $code = parseInt($datas.substring($i, $i+2), 16)
+    $_data += String.fromCharCode($code)
+  }
+  return $_data;
+}
 
 export default {
   /**
@@ -99,32 +154,124 @@ export default {
    * 脑机连接教具
    */
   sendToyConnection(toyItem) {
+    let that = this;
     if(toyItem && toyItem["hex"]) {
-      let $hex = $this.toy_item["hex"].substr($this.toy_item["hex"].length - 2, 2);
+      let $hex = toyItem["hex"].substr(toyItem["hex"].length - 2, 2);
       if ($hex === "80") {
         wx.setStorageSync("report_mode", 2)
       } else {
         wx.setStorageSync("report_mode", 1)
       }
-      console.log("连接教具:", `03 00 ${$hex} 00 0A`, JSON.stringify($this.toy_item));
+      console.log("连接教具(获取连接ID):", `03 00 ${$hex} 00 0A`, JSON.stringify(toyItem));
       // 连接教具: 03 00 ${$hex} 00 0a
-      $this.$bluetooth.sendConnectOneToMore($hex);
+      that.sendConnectOneToMore($hex);
     }
   },
   /**
    *  发送一对多连接
+   *  连接教具(获取连接ID)
    */
   sendConnectOneToMore(id) {
     this.WriteBufferInBle(`03 00 ${id} 00 0A`);
   },
   /**
+   * 发送一对一连接
+   * 连接教具(使用获取的ID)
+   */
+  sendConnectOneToOne(id) {
+    current_toy_id = id;
+    this.WriteBufferInBle(`03 00 ${id} 01 0A`)
+  },
+  /**
+   * 连接教具(使用下发的ID)
+   */
+  sendConnectOneToToy(id) {
+    this.WriteBufferInBle(`03 00 ${id} 02 0A`)
+  },
+  /**
+   * todo 写入8位指令
+   * @param id 末尾id
+   * @constructor
+   */
+  SendOrder(id) {
+    let $hexStr = `03 00 00 00 ${id}`;
+    this.WriteBufferInBle($hexStr)
+  },
+  /**
+   * 接收原始数据开关
+   */
+  Send2BOrder(status = true) {
+    let $hexStr = `03 00 00 01 2b`;
+    if (!status) {
+      $hexStr = `03 00 00 00 2b`;
+    }
+    this.WriteBufferInBle($hexStr)
+  },
+  /**
+   * 打开或关闭LED灯 AA CC 03 00 00 ctrl EC CKS
+   * 00/01
+   */
+  SendLedOrder(id) {
+    let $hexStr = `03 00 00 ${id} ec`;
+    this.WriteBufferInBle($hexStr)
+  },
+
+  /**
+   * 设置教具为无运动状态 AA CC 03 00 00 00 34 CKS
+   * 00/01
+   */
+  SendMotionOrder(id) {
+    let $hexStr = `03 00 00 ${id} 34`;
+    this.WriteBufferInBle($hexStr)
+  },
+  /**
+   * 自动发送RF重连
+   * @param  {Boolean} isOn    是否打开重连功能
+   * @param  {[type]}  timeOut 有效时间
+   * @return {[type]}          [description]
+   * AA CC 03 00 01 0a d0 21
+   */
+  sendAutoConnectRf(isOn, timeOut) {
+    let that = this;
+    let onVal = isOn ? '01' : '00';
+    let mTimeOut = timeOut.toString(16);
+
+    if (mTimeOut.length === 1) {
+      mTimeOut = `0${mTimeOut}`
+    }
+
+    let $hexStr = `03 00 ${onVal} ${mTimeOut} d0`;
+    this.WriteBufferInBle($hexStr)
+  },
+  /**
+   * 关闭脑控
+   */
+  sendControlClose() {
+    let that = this
+    setTimeout(()=>{
+      // 打开LED
+      that.SendLedOrder("01");
+    },500);
+    setTimeout(()=>{
+      // 关闭脑控
+      that.SendOrder('09');
+      //设置打开脑控为false
+      FlagOpenControl = false;
+      //清空当前数据
+      //control_close = false
+      connect_toy = false;
+      current_toy_id = "00";
+      //current_toy_UUID = "";
+    },1000);
+  },
+  /**
    * todo 写入buffer
    * @param $hex
    * @param $buffer_len
    * @constructor
    */
   WriteBufferInBle($hex, $buffer_len = 8) {
-    let { deviceId, serviceId, characteristicId } = getDeviceInfo();
+    let { deviceId, serviceId, characteristicId } = getDeviceWriteInfo();
     if (deviceId && serviceId && characteristicId) {
       let that = this;
       let $hex_header = "aa cc ";
@@ -166,237 +313,226 @@ export default {
     let deviceId = ble_store.getters.getDeviceId();
     // 监听蓝牙低功耗设备的特征值变化事件
     wx.onBLECharacteristicValueChange((characteristic) => {
-      let hexStr = that.ab2hex(characteristic.value);
+      let hexStr = ab2hex(characteristic.value);
+      let $game_status = game_store.getters.getGameStatus();
       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;
+      // 连接页面
+      if($this && $this.$options.name){
+        // 监听佩戴正确, 当s1为 00时 数据有效
+        if (hexStr.substring(0, 6) === "555520") {
+          $this.device_bg = (hexStr.substring(8, 10) === "00");
         }
-        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 (hexStr.substring(0, 8) === "55550203") {
+          let $power = parseInt(hexStr.substring(8, 10), 16);
+          let $voltage = parseInt(hexStr.substring(10, 12), 16);
+          // 监听是否插入USB
+          $this.hasUsb = $voltage.toString().substring(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});
+          }
         }
-        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("AADD0A") >= 0) {
+          //没连接上教具
+          if (hexStr.toUpperCase().indexOf("AADD0A0000") >= 0) {
+            $this.connect_toy = 3;
+            return false;
+          }
+          let $baseIndex = hexStr.toUpperCase().indexOf("AADD0A");
+          let $hex_index = hexStr.substring($baseIndex + 28, 30)
+          let $toy_id = hexStr.substring($baseIndex + 8, 10)
+          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');
+                }
+              }, 10000);
+            }
           }
         }
-      }
-      // 获取教具名称
-      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("AADD87") >= 0) {
+          let $mHexStr = hexStr.substring(hexStr.toUpperCase().indexOf("AADD87"))
+          let $datas = 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("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 (hexStr.toUpperCase().indexOf("AADD8A") >= 0) {//接收教具电量状态
+          let $_hexStr = hexStr.substring(hexStr.toUpperCase().indexOf("AADD8A") + 6);
+          let $power = parseInt($_hexStr.substring(0, 2), 16)
+          let $voltage = parseInt($_hexStr.substring(2, 4), 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 (!$this.toy_UUID) {
+          //   //获取教具UUID
+          //   that.SendOrder('84')
+          // }
         }
-
-
-        // if (current_toy_UUID == "") {
-        //   //获取教具UUID
-        //   that.SendOrder('84')
+        // // 读取教具UUID
+        // if (hexStr.toUpperCase().indexOf("AADD84") >= 0) {//接收UUID 5个字节
+        //   let $hex_index = hexStr.toUpperCase().indexOf("AADD84") + 6;
+        //   let $datas = hexStr.substring($hex_index, $hex_index+10);
+        //   if ($datas !== "0000000000") {
+        //     console.log("以获取UUID:" + $datas)
+        //     $this.toy_UUID = $datas;
+        //   }
         // }
-      }
-
-
+        // 教具断链(连续多次到教具的命令没有响应)
+        if (hexStr.toUpperCase().indexOf("AAEE70") >= 0) {
+          connect_toy = false
+          wx.showModal({
+            content: "教具已断开",
+            success(res) {
+              if (res.confirm) {
+                let $game_status = game_store.getters.getGameStatus();
+                if ($game_status === 1) {
+                  $this.game_finished();
+                }
+              }
+            }
+          })
 
+        }
 
-      // 获取蓝牙低功耗设备(脑机)的信号强度
-      if (game_store.getters.getGameStatus() === 1) {
-        wx.getBLEDeviceRSSI({
-          deviceId: deviceId,
-          success(res) {$this.RSSI = res.RSSI;}
-        });
-      }
 
+        if (game_store.getters.getGameStatus() === 1) {
 
+        }
 
+        //游戏中模块
+        let $game_status = game_store.getters.getGameStatus();
+        if ($game_status === 1) {
+          // 获取蓝牙低功耗设备(脑机)的信号强度
+          wx.getBLEDeviceRSSI({
+            deviceId: deviceId,
+            success(res) {$this.RSSI = res.RSSI;}
+          });
+          // 分析实时数据
+          if($this.$options.name === "StartGames"){
+            $this.analysisGameData(hexStr);
+          }
+          // $this.hexStr = hexStr;
+          // let $data = that.get_big_data(hexStr);
+          // $this.do_datas($data);
+        }
 
+        //todo 接收脑机关机指令
+        if (hexStr.toUpperCase().indexOf("AADD5A00000000A5") >= 0) {
+          Notify({
+            type: 'danger',
+            duration: 0,
+            message: '智脑机已关机,训练结束',
+            onOpened() {
+              setTimeout(() => {
+                $this.game_finished();
+                //clearInterval(control_close_intv)
+              }, 2000)
+            }
+          });
 
+        }
 
-      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();
-              }
-            }
-          }
-        })
 
+      // 收到发送UUID的应答立马发送连接教具的指令
+      if (hexStr.toUpperCase().indexOf("AADD8E") >= 0) {
+        //发送教具连接(连接教具(使用下发的ID))
+        that.sendConnectOneToToy(current_toy_id)
+      }
+      if (hexStr.toUpperCase().indexOf("AAEE87") >= 0) {
+        //获取教具电量
+        if (current_toy_id !== '80') {
+          that.SendOrder('87')
+        }
       }
 
+      // 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}`)
+      // }
 
-      if (hexStr.toUpperCase().indexOf("AAEE8A0000005A") >= 0) {
-        that.SendOrder("8a")
-      }
+      // // 发送到教具的命令没有得到响应
+      // if (hexStr.toUpperCase().indexOf("AAEE8A000000A5") >= 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("AAEE07") >= 0) {
+      //   that.sendControl();
+      // }
 
 
       if (hexStr.toUpperCase().indexOf("AADD09") >= 0) {
-        control_close = true;
+        // 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) {
+      if (hexStr.substring(0, 6) === "5555e2") {
+        let _buffer =  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;
+        // 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)
-          }
-        });
-
-      }
     });
   },
 
@@ -410,11 +546,11 @@ export default {
     wx.onBLEConnectionStateChange((res) => {
       // 该方法回调中可以用于处理连接意外断开等异常情况
       ble_store.setters.setBluetoothLinkStatus(res.connected);
-      LogInDb(`${that.getNowTime()} 监听脑机断连`)
-      if (res.connected == false) {
+      console.log(`${that.getNowTime()} 监听脑机是否断连:`, res.connected);
+      if (res.connected === false) {
         //判断游戏是否游戏中
         let $game_status = game_store.getters.getGameStatus();
-        if ($game_status == 1) {
+        if ($game_status === 1) {
           // $that.game_finished();
           Notify({
             type: 'danger',
@@ -424,7 +560,7 @@ export default {
               that.reconnect(res.deviceId, $this)
             }
           });
-          control_close = true
+          // control_close = true
           // connect_toy = false;
         } else {
           //关闭脑控
@@ -433,14 +569,14 @@ export default {
           // 清空链接得设备 三值
           ble_store.setters.clearDeviceToy();
           $this.connect_toy = 0;
-          $this.connect_show = false;
+          //$this.connect_show = false;
           $this.device_bg = false;
           $this.device_status = 0;
-          $this.device = {}
-          $this.toy_UUID = "";
+          // $this.device = {}
+          //$this.toy_UUID = "";
           $this.$forceUpdate();
           wx.closeBluetoothAdapter();
-          version = "";
+          // version = "";
         }
       }
     });
@@ -468,7 +604,7 @@ export default {
               that.getBLEDeviceServices($deviceInfo.deviceId)
               that.notifyDatas($this)
             } else {
-              that.openNotify($this)
+              // that.openNotify($this)
               that.watchBLEstatus($this);
             }
             // that.sendToyPower();
@@ -521,8 +657,8 @@ export default {
           console.log("断开蓝牙连接"+deviceId+"失败error:", err);
         },
         complete() {
-          $this.device = {};
-          $this.toy_UUID = "";
+          //$this.device = {};
+          //$this.toy_UUID = "";
           $this.$forceUpdate();
         },
       });
@@ -542,4 +678,22 @@ export default {
     const millSeconds = date.getMilliseconds();
     return `${year}/${month}/${day} ${hour}:${minutes}:${seconds}.${millSeconds}`;
   },
+  connectionError(errCode) {
+    if (errCode === 10000) {
+      return "未初始化蓝牙适配器";
+    }
+    if (errCode === 10001) {
+      return "当前蓝牙适配器不可用";
+    }
+    if (errCode === 10002) {
+      return "没有找到指定设备";
+    }
+    if (errCode === 10003) {
+      return "连接失败";
+    }
+    if (errCode === 10006) {
+      return "当前连接已断开";
+    }
+    return "未知连接错误:"+errCode;
+  },
 };

+ 71 - 2
src/utils/game.js

@@ -96,10 +96,79 @@ function to_report() {
   })
 }
 
+/**
+ * 游玩时间倒计时
+ * @param value
+ * @returns {string}
+ */
+export function formatPlaySeconds(value) {
+  // 字符串转数字
+  var secondTime = parseInt(value); // 秒
+  var minuteTime = 0; // 分
+  if (secondTime > 60) {
+    //如果秒数大于60,将秒数转换成整数
+    //获取分钟,除以60取整数,得到整数分钟
+    minuteTime = parseInt(secondTime / 60);
+    //获取秒数,秒数取佘,得到整数秒数
+    secondTime = parseInt(secondTime % 60);
+    //如果分钟大于60,将分钟转换成小时
+  }
+  var result = "" + parseInt(secondTime);
 
+  if (minuteTime > 0) {
+    if (result.length == 1) {
+      result = "0" + result;
+    }
+    if (parseInt(minuteTime).toString().length == 1) {
+      minuteTime = "0" + parseInt(minuteTime);
+    }
+    result = "" + minuteTime + ":" + result;
+  } else {
+    result = "00:" + result;
+  }
+  return result;
+}
 
 
+/**
+ *  获取大包数据进行绘制图表
+ */
+export function get_big_data(hex) {
+  let hexAry = []
+  for (let i = 0; i < hex.length; i += 2) {
+    hexAry.push(hex.substr(i, 2))
+  }
+  if (hex.substr(0, 6) != "555520") {
+    return false;
+  }
+  //当s1为 00时 数据有效
+  // let hex_str = hex.substr(hex.indexOf("555520"))
+  // let $s1 = hex_str.substr(8, 2);
+  let $s1 = hexAry[4]
+  if ($s1 !== "00") {
+    return false;
+  }
 
+  //专注度数据
+  let $att = parseInt(hexAry[6], 16)
+  //放松度数据
+  let $med = parseInt(hexAry[8], 16)
 
-
-
+  let idx = 0
+  let dataIndex = ['delta', 'theta', "low_alpha", "high_alpha", "low_beta", "high_beta", "low_gamma", "middle_gamma"]
+  let datas = []
+  hexAry.pop()
+  for (let i = 11; i < hexAry.length; i += 3) {
+    let num_1 = parseInt(hexAry[i], 16)
+    let num_2 = parseInt(hexAry[i + 1], 16)
+    let num_3 = parseInt(hexAry[i + 2], 16)
+    let show_value = num_1 + num_2 + num_3;
+    let basic_value = parseInt("0x" + hexAry[i] << 16 | "0x" + hexAry[i + 1] << 8 | "0x" + hexAry[i + 2], 16)
+    datas[dataIndex[idx]] = show_value
+    datas[`${dataIndex[idx]}_basic`] = basic_value
+    idx += 1;
+  }
+  datas['att'] = $att;
+  datas['med'] = $med;
+  return datas
+}