Procházet zdrojové kódy

优化蓝牙连接流程8

chaooo před 1 rokem
rodič
revize
1097979998

+ 3 - 1
src/components/connection/index.vue

@@ -102,7 +102,9 @@ export default {
     // 选好教具
     chooseOK() {
       $this.popup_show = false;
-      $this.toy_item = game_store.getters.getToyItem();
+      $this.toy_item = ble_store.getters.getToyItem();
+      // 初始化教具连接的id
+      ble_store.setters.setCurrentToyId("00");
       if($this.toy_item && $this.toy_item.id > 0) {
         $this.setToyStatus(1);
         $this.$connection.sendToyConnection($this.toy_item);

+ 2 - 2
src/components/connection/toys/selection.vue

@@ -1,5 +1,5 @@
 <script>
-import game_store from "@/store/game";
+import ble_store from "@/store/bluetooth";
 import {game_devices} from "../../../requests/game";
 let $this;
 export default {
@@ -22,7 +22,7 @@ export default {
     //选择教具
     chooseToy($index) {
       $this.toy_action = $this.toy_list[$index].id;
-      game_store.setters.setToyItem($this.toy_list[$index]);
+      ble_store.setters.setToyItem($this.toy_list[$index]);
     },
     //  获取游戏设备教具
     getToyList() {

+ 2 - 2
src/pages/start/index.vue

@@ -335,7 +335,7 @@ export default {
         //游戏结束重置游戏模式
         // game_store.setters.setMode(0);
         //删除游戏得id
-        game_store.setters.removeToyHex();
+        // game_store.setters.removeToyHex();
 
         // 结束游戏在提交报告函数里
         $this.post_data();
@@ -396,7 +396,7 @@ export default {
       },500);
       setTimeout(()=>{
         // 获取教具类型 发送陀螺仪开关指令
-        let $toy_sn = game_store.getters.getToySn().toUpperCase();
+        let $toy_sn = ble_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.$connection.SendMotionOrder("01");

+ 34 - 15
src/store/bluetooth.js

@@ -3,49 +3,68 @@ const getters = {
     return wx.getStorageSync("ble_link_status")
   },
   getDeviceSn() {
-    return wx.getStorageSync('deviceSn')
+    return wx.getStorageSync('device_sn')
   },
   getDeviceId() {
-    return wx.getStorageSync('deviceId')
+    return wx.getStorageSync('device_id')
   },
   getServiceId() {
-    return wx.getStorageSync('serviceId')
+    return wx.getStorageSync('service_id')
   },
   getCharacteristicWriteId(){
-    return wx.getStorageSync('characteristicWriteId')
+    return wx.getStorageSync('characteristic_write_id')
   },
   getCharacteristicNotifyId(){
-    return wx.getStorageSync('characteristicNotifyId')
+    return wx.getStorageSync('characteristic_notify_id')
+  },
+  getToyItem() {
+    return wx.getStorageSync('toy_item')
+  },
+  getToySn() {
+    return wx.getStorageSync('toy_sn')
+  },
+  getCurrentToyId(){
+    return wx.getStorageSync('current_toy_id')
   },
 }
 
 const setters = {
   clearDeviceToy() {
-    wx.removeStorageSync('deviceId')
-    wx.removeStorageSync('deviceSn')
-    wx.removeStorageSync('serviceId')
+    wx.removeStorageSync('device_id')
+    wx.removeStorageSync('device_sn')
+    wx.removeStorageSync('service_id')
     wx.removeStorageSync('is_new')
-    wx.removeStorageSync('characteristicId')
+    wx.removeStorageSync('characteristic_write_id')
+    wx.removeStorageSync('characteristic_notify_id')
+    wx.setStorageSync('current_toy_id', '00')
   },
   setBluetoothLinkStatus($bool) {
     wx.setStorageSync("ble_link_status", $bool)
   },
   setDeviceSn(deviceSn) {
-    wx.setStorageSync('deviceSn', deviceSn)
+    wx.setStorageSync('device_sn', deviceSn)
   },
   setDeviceId(deviceId) {
-    wx.setStorageSync('deviceId', deviceId)
+    wx.setStorageSync('device_id', deviceId)
   },
   setServiceId(serviceId) {
-    wx.setStorageSync('serviceId', serviceId)
+    wx.setStorageSync('service_id', serviceId)
   },
   setCharacteristicWriteId(characteristicId){
-    wx.setStorageSync('characteristicWriteId', characteristicId)
+    wx.setStorageSync('characteristic_write_id', characteristicId)
   },
   setCharacteristicNotifyId(characteristicId){
-    wx.setStorageSync('characteristicNotifyId', characteristicId)
+    wx.setStorageSync('characteristic_notify_id', characteristicId)
+  },
+  setToyItem(toy_item) {
+    wx.setStorageSync('toy_item', toy_item)
+  },
+  setToySn(toy_sn) {
+    wx.setStorageSync('toy_sn', toy_sn)
+  },
+  setCurrentToyId(currentToyId){
+    wx.setStorageSync('current_toy_id', currentToyId)
   },
-
 }
 
 export default {

+ 0 - 24
src/store/game.js

@@ -3,15 +3,6 @@ const setters = {
   setGameStatus(status) {
     wx.setStorageSync('game_status', status)
   },
-  setToyItem(toy_item) {
-    wx.setStorageSync('toy_item', toy_item)
-  },
-  setToySn(toy_sn) {
-    wx.setStorageSync('toy_sn', toy_sn)
-  },
-  removeToyHex() {
-    wx.removeStorageSync('toy_hex')
-  },
   // 游戏模式: 1次数 2时间
   setMode(mode) {
     wx.setStorageSync('mode', mode)
@@ -41,9 +32,6 @@ const setters = {
   setGameAttMedDatas($param) {
     wx.setStorageSync('game_data', $param)
   },
-  // setIsNew($param) {
-  //   wx.setStorageSync('is_new', $param)
-  // },
   // 脑机LED灯
   setLED(bool) {
     wx.setStorageSync('led_status', bool)
@@ -54,17 +42,9 @@ const setters = {
 }
 
 const getters = {
-
-
   getGameStatus() {
     return wx.getStorageSync('game_status')
   },
-  getToyItem() {
-    return wx.getStorageSync('toy_item')
-  },
-  getToySn() {
-    return wx.getStorageSync('toy_sn')
-  },
   getMode() {
     return wx.getStorageSync('mode')
   },
@@ -95,10 +75,6 @@ const getters = {
   getGameAttMedDatas() {
     return wx.getStorageSync('game_data')
   },
-  // //记录游戏数据
-  // getIsNew() {
-  //   return wx.getStorageSync('is_new')
-  // },
   // 脑机LED灯
   getLED() {
     return wx.getStorageSync('led_status')

+ 51 - 183
src/utils/connection.js

@@ -3,13 +3,6 @@ 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 FlagOpenControl = false;
-
 function getDeviceWriteInfo() {
   let deviceId = ble_store.getters.getDeviceId();
   let serviceId = ble_store.getters.getServiceId();
@@ -17,26 +10,6 @@ function getDeviceWriteInfo() {
   let characteristicNotifyId = ble_store.getters.getCharacteristicNotifyId();
   return { deviceId, serviceId, characteristicWriteId, characteristicNotifyId};
 }
-// /**
-//  * 转移原始数据
-//  * @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进度字符串示例
@@ -55,21 +28,20 @@ function ab2hex(buffer) {
 /**
  * todo 解析hex
  * @param hexStr
- * @param byte_count
- * @param sublen
+ * @param count
+ * @param len
  * @returns {string}
- * @constructor
  */
-function doAnalysis(hexStr, byte_count, sublen = 6) {
+function doAnalysis(hexStr, count, len = 6) {
+  let $result = "";
   //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)
+  let $str = hexStr.substring(len);
+  let $data = $str.substring(0, count * 2);
+  for (let $i = 0; $i < $data.length; $i += 2) {
+    let $code = parseInt($data.substring($i, $i+2), 16)
+    $result += String.fromCharCode($code)
   }
-  return $_data;
+  return $result;
 }
 
 export default {
@@ -146,7 +118,7 @@ export default {
           }
         }
       },
-      fail(res) {
+      fail() {
         let deviceId = wx.getStorageSync('deviceId');
         //断开蓝牙连接
         wx.closeBLEConnection({
@@ -185,13 +157,14 @@ export default {
    * 连接教具(使用获取的ID)
    */
   sendConnectOneToOne(id) {
-    current_toy_id = id;
+    ble_store.setters.setCurrentToyId(id);
     this.WriteBufferInBle(`03 00 ${id} 01 0A`)
   },
   /**
    * 连接教具(使用下发的ID)
    */
   sendConnectOneToToy(id) {
+    ble_store.setters.setCurrentToyId(id);
     this.WriteBufferInBle(`03 00 ${id} 02 0A`)
   },
   /**
@@ -203,16 +176,6 @@ export default {
     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
@@ -230,23 +193,21 @@ export default {
     let $hexStr = `03 00 00 ${id} 34`;
     this.WriteBufferInBle($hexStr)
   },
+
   /**
    * 自动发送RF重连
    * @param  {Boolean} isOn    是否打开重连功能
-   * @param  {[type]}  timeOut 有效时间
-   * @return {[type]}          [description]
+   * @param timeOut 有效时间
    * AA CC 03 00 01 0a d0 21
    */
   sendAutoConnectRf(isOn, timeOut) {
     let onVal = isOn ? '01' : '00';
     let mTimeOut = timeOut.toString(16);
-
     if (mTimeOut.length === 1) {
-      mTimeOut = `0${mTimeOut}`
+      mTimeOut = `0${mTimeOut}`;
     }
-
     let $hexStr = `03 00 ${onVal} ${mTimeOut} d0`;
-    this.WriteBufferInBle($hexStr)
+    this.WriteBufferInBle($hexStr);
   },
     /**
    *  todo:开启脑控
@@ -259,16 +220,6 @@ export default {
     setTimeout(()=>{
       that.SendOrder('07');
     },500)
-    // let $intv = setInterval(() => {
-    //   if (FlagOpenControl) {
-    //     //设置打开脑控为false
-    //     FlagOpenControl = false;
-    //     clearInterval($intv)
-    //     wx.hideLoading()
-    //   } else {
-    //     that.SendOrder('07')
-    //   }
-    // }, 3000)
   },
   /**
    * 关闭脑控
@@ -282,13 +233,7 @@ export default {
     setTimeout(()=>{
       // 关闭脑控
       that.SendOrder('09');
-      //设置打开脑控为false
-      FlagOpenControl = false;
-      //清空当前数据
-      //control_close = false
-      connect_toy = false;
-      current_toy_id = "00";
-      //current_toy_UUID = "";
+      ble_store.setters.setCurrentToyId("00");
     },1000);
   },
   /**
@@ -329,23 +274,7 @@ export default {
       });
     }
   },
-  // /**
-  //  * 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征
-  //  */
-  // openNotify($this) {
-  //   let that = this;
-  //   let { deviceId, serviceId, characteristicNotifyId } = getDeviceWriteInfo();
-  //   wx.notifyBLECharacteristicValueChange({
-  //     deviceId: deviceId,
-  //     serviceId: serviceId,
-  //     characteristicId: characteristicNotifyId,
-  //     state: true,
-  //     success() {
-  //       that.notifyDatas($this);
-  //       console.log("正在监听特征值:", characteristicNotifyId);
-  //     }
-  //   });
-  // },
+
   /**
    * 监听脑机数据
    * @param $this
@@ -357,7 +286,25 @@ export default {
     wx.onBLECharacteristicValueChange((characteristic) => {
       let hexStr = ab2hex(characteristic.value);
       console.log("监听脑机数据:", hexStr);
-      let $game_status = game_store.getters.getGameStatus();
+      // 处理打开脑控的应答
+      if (hexStr.toUpperCase().indexOf("AADD07") >= 0) {
+        ble_store.setters.setBluetoothLinkStatus(true)
+      }
+      // 收到发送UUID的应答立马发送连接教具的指令
+      if (hexStr.toUpperCase().indexOf("AADD8E") >= 0) {
+        let $currentToyId = ble_store.getters.getCurrentToyId();
+        //发送教具连接(连接教具(使用下发的ID))
+        that.sendConnectOneToToy($currentToyId)
+      }
+      if (hexStr.toUpperCase().indexOf("AAEE87") >= 0) {
+        let $currentToyId = ble_store.getters.getCurrentToyId();
+        //获取教具电量
+        if ($currentToyId !== '80') {
+          that.SendOrder('87')
+        }
+      }
+      //let $game_status = game_store.getters.getGameStatus();
+      //let $currentToyId = ble_store.getters.getCurrentToyId();
       // 连接页面
       if($this && $this.$options.name){
         console.log("当前页面名称:", $this?$this.$options.name:"");
@@ -391,17 +338,17 @@ export default {
             console.log("一对多")
             // 发送一对一连接 03 00 ${$toy_id} 01 0A
             that.sendConnectOneToOne($toy_id);
-            current_toy_id = $toy_id;
+            ble_store.setters.setCurrentToyId($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)
@@ -419,45 +366,28 @@ export default {
         }
         // 获取教具名称
         if (hexStr.toUpperCase().indexOf("AADD87") >= 0) {
+          let $currentToyId = ble_store.getters.getCurrentToyId();
           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;
+          let toy_list_pre = {'00': "", '01': "SW", '02': "KL", '04': "SC", '05': "PP", '06': "SU", '09': "UF", '12': "JM", '13': "QM"}
+          let $sn = toy_list_pre[$currentToyId] + $number;
           $this.toy_sn = $sn;
           //保存教具sn
-          game_store.setters.setToySn($sn);
+          ble_store.setters.setToySn($sn);
           console.log("获取教具名称hexStr:",hexStr,",获取教具名称$sn",$sn);
         }
         // 获取教具电量
         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')
-          // }
         }
-        // // 读取教具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
+          //connect_toy = false
           wx.showModal({
             content: "教具已断开",
             success(res) {
@@ -487,9 +417,6 @@ export default {
             if($this.$options.name === "StartGames" && $this.device_bg){
               $this.analysisGameData(hexStr);
             }
-            // $this.hexStr = hexStr;
-            // let $data = that.get_big_data(hexStr);
-            // $this.do_datas($data);
           }
         }
 
@@ -511,63 +438,6 @@ export default {
 
       }
 
-      // 收到发送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("AAEE8A000000A5") >= 0) {
-      //   // 获取教具电量状态, 不直接发命令到教具, 获取的是缓存值
-      //   that.SendOrder("8a")
-      // }
-
-      //防止在首页 连接的时候重复 选择教具 产生了发送多个教具电量
-      // if(hexStr.toUpperCase().indexOf("AAEE8A000000FF76") >= 0){
-      //   that.connect_toy = false;
-      // }
-
-      // if (hexStr.toUpperCase().indexOf("AAEE07") >= 0) {
-      //   that.sendControl();
-      // }
-
-
-      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 (hexStr.substring(0, 6) === "5555e2") {
-      //   let _buffer =  doOriginBufferToData(hexStr)
-      //   if ($game_status === 1) {
-      //     wx.setStorageSync('origin_buffer', wx.getStorageSync('origin_buffer') + _buffer.join(',') + ",")
-      //   }
-      // }
-      // // 打开原始数据
-      // if (hexStr.toUpperCase().indexOf("AADD04") >= 0) {
-      //   // raw_data_open = true;
-      //   that.Send2BOrder(true)
-      //   //wx.setStorageSync('origin_buffer', "");
-      // }
-
     });
   },
 
@@ -599,7 +469,7 @@ export default {
           // connect_toy = false;
         } else {
           //关闭脑控
-          connect_toy = false;
+          // connect_toy = false;
           game_store.setters.setGameStatus(0);
           // 清空链接得设备 三值
           ble_store.setters.clearDeviceToy();
@@ -627,15 +497,15 @@ export default {
     let $connect_count = 0;
     let $rec = setInterval(() => {
       let $game_status = game_store.getters.getGameStatus();
-      if ($game_status == 1) {
+      if ($game_status === 1) {
         wx.createBLEConnection({
           deviceId: $deviceInfo.deviceId,
-          success(res) {
+          success() {
             clearInterval($rec)
             Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
             LogInDb(`${that.getNowTime()} 第${$connect_count}次重新连接成功`)
             let $system = wx.getSystemInfoSync()
-            if ($system.platform == 'ios') {
+            if ($system.platform === 'ios') {
               that.getBLEDeviceServices($deviceInfo.deviceId)
               that.notifyDatas($this)
             } else {
@@ -643,7 +513,6 @@ export default {
               that.watchBLEstatus($this);
             }
             // that.sendToyPower();
-
           },
           fail(res) {
             Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
@@ -676,7 +545,6 @@ export default {
     $this.device_bg = false;
     $this.connect_status = false;
 
-
     // 断开教具及蓝牙连接
     that.SendOrder("31");
     setTimeout(()=>{

+ 2 - 2
src/utils/game.js

@@ -88,8 +88,8 @@ function to_report() {
       game_store.remover.rmGameAttMedDatas()
       //游戏结束重置游戏模式
       game_store.setters.setMode(0)
-      //删除游戏得id
-      game_store.setters.removeToyHex()
+      // //删除游戏得id
+      // game_store.setters.removeToyHex()
       //删除隐藏时间
       game_store.remover.rmHideTime()
     }