Browse Source

体验版C端小程序
调整了 蓝牙链接的顺序 兼容了新旧脑环
依旧关闭了教具重连
修复了 在游戏中脑环断开后,点结束游戏 会重复跳出报告 的bug
修复了 偶发的 点击开始游戏后 教具白灯常亮没打开脑控的 bug
修复了 偶发的 脑环与小程序重连后 小程序页面会卡死的 bug

叶振荣 3 years ago
parent
commit
be3024cd6e
4 changed files with 287 additions and 196 deletions
  1. 5 5
      src/components/device/device.vue
  2. 1 4
      src/pages/start/index.vue
  3. 27 20
      src/store/game.js
  4. 254 167
      src/utils/bluetooth.js

+ 5 - 5
src/components/device/device.vue

@@ -262,6 +262,7 @@ export default {
             // 判断新的标识值
             $this.code = $code[1].toUpperCase();
             console.log("头环码", $code);
+            game_store.setters.setDeviceSn($this.code)
             //设备信息
             $this.device_data.product_qrcode = url;
             $this.device_data.sn = $this.code
@@ -507,7 +508,6 @@ export default {
             if (device["name"].toUpperCase() == $this.code) {
               $this.stopBluetoothDevicesDiscovery();
               $this.device = device;
-              game_store.setters.setDeviceId(device.deviceId);
               $this.createBLEConnection();
             }
           });
@@ -526,19 +526,19 @@ export default {
         deviceId: $this.device.deviceId,
         success: (res) => {
           console.log("成功连接");
+          game_store.setters.setDeviceId($this.device.deviceId);
+
           //成功连接脑环蓝牙
           $this.change_device_status(2);
+          bluetooth.openNotify($this)
           bluetooth.watch_bluetooth_status($this);
-          bluetooth.getBLEDeviceServices($this.device.deviceId);
-          bluetooth.watchingDevice($this);
-
 
           //录入库
           //读取信息逐个写入
           if (!$this.device_finded) {
             setTimeout(() => {
               bluetooth.SendOrder("02")
-              // setDeviceInDb($this,device.deviceId)
+              setDeviceInDb($this, $this.device.deviceId)
             }, 3000)
           }
 

+ 1 - 4
src/pages/start/index.vue

@@ -619,11 +619,10 @@ export default {
     }
   },
   mounted() {
+    $this.executed = false;
     $this.deviceId = "";
     $this.toy_UUID = "";
     $this.deviceId = game_store.getters.getDeviceId();
-    $this._serviceId = game_store.getters.getServiceId();
-    $this._characteristicId = game_store.getters.getCharacterId();
     // setTimeout(() => {
     $this.game_status = game_store.getters.getGameStatus();
     // }, 1000)
@@ -697,8 +696,6 @@ export default {
   onUnload() {
     console.log("小程序被销毁");
     if (!$this.is_end) {
-      //停止传输数据
-      // bluetooth.sendControlPause();
       //存储时间
       game_store.setters.setPlayedTime($this.played_time);
       //设置未结束游戏

+ 27 - 20
src/store/game.js

@@ -1,22 +1,26 @@
 const setters = {
   clearDeviceToy() {
     wx.removeStorageSync('deviceId')
-    wx.removeStorageSync('serviceId')
-    wx.removeStorageSync('characteristicId')
+    wx.removeStorageSync('deviceSn')
+    // wx.removeStorageSync('serviceId')
+    // wx.removeStorageSync('characteristicId')
   },
   //setter模块
   setDeviceId(deviceId) {
     wx.setStorageSync('deviceId', deviceId)
   },
-  setServiceId(serviceId) {
-    wx.setStorageSync('serviceId', serviceId)
-  },
-  setCid(characteristicId) {
-    wx.setStorageSync('characteristicId', characteristicId)
-  },
-  setReadCid(value) {
-    wx.setStorageSync('read_characteristicId', value)
-  },
+  setDeviceSn(deviceSn) {
+    wx.setStorageSync('deviceSn', deviceSn)
+  },
+  // setServiceId(serviceId) {
+  //   wx.setStorageSync('serviceId', serviceId)
+  // },
+  // setCid(characteristicId) {
+  //   wx.setStorageSync('characteristicId', characteristicId)
+  // },
+  // setReadCid(value) {
+  //   wx.setStorageSync('read_characteristicId', value)
+  // },
   setGameStatus(status) {
     wx.setStorageSync('game_status', status)
   },
@@ -66,15 +70,18 @@ const getters = {
   getDeviceId() {
     return wx.getStorageSync('deviceId')
   },
-  getServiceId() {
-    return wx.getStorageSync('serviceId')
-  },
-  getCharacterId() {
-    return wx.getStorageSync('characteristicId')
-  },
-  getReadCharacterId() {
-    return wx.getStorageSync('read_characteristicId')
-  },
+  getDeviceSn() {
+    return wx.getStorageSync('deviceSn')
+  },
+  // getServiceId() {
+  //   return wx.getStorageSync('serviceId')
+  // },
+  // getCharacterId() {
+  //   return wx.getStorageSync('characteristicId')
+  // },
+  // getReadCharacterId() {
+  //   return wx.getStorageSync('read_characteristicId')
+  // },
   getGameStatus() {
     return wx.getStorageSync('game_status')
   },

+ 254 - 167
src/utils/bluetooth.js

@@ -6,13 +6,48 @@ import {setDeviceInDb} from "../requests/game";
 var $ff = "ff";
 var $8f = "ffffffff"
 var control_close = false
-
+//记录当前脑环的mac地址
 var current_device_mac = "";
-
-var connect_toy = false;
+//记录教具连接状态
+var connect_toy = true;
+//记录教具连接的id
 var current_toy_id = "00";
+//记录教具的UUID
 var current_toy_UUID = "";
 
+//标记是否打开脑控
+var FlagOpenControl = false;
+
+
+//2021年11月10日14:59:38
+// 0为旧 1为新
+var services = [
+  "6e400001-b5a3-f393-e0a9-e50e24dcca9e",
+  "0000fff0-0000-1000-8000-00805f9b34fb"
+]
+var charateristics = [
+  {
+    notify: "6e400003-b5a3-f393-e0a9-e50e24dcca9e",
+    write: "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
+  },
+  {
+    notify: "0000fff1-0000-1000-8000-00805f9b34fb",
+    write: "0000fff2-0000-1000-8000-00805f9b34fb"
+  },
+]
+
+function getServicesAndCharateristc() {
+  //获取当前设备名称
+  let $brainSn = game_store.getters.getDeviceSn();
+  let $deviceId = game_store.getters.getDeviceId();
+  let $index = $brainSn.toUpperCase().indexOf("JELLYFISH") != -1 ? 0 : 1;
+  return {
+    deviceId:$deviceId,
+    service:services[$index],
+    charateristic:charateristics[$index]
+  }
+}
+
 export default {
   //变量
   connect_toy, control_close, current_toy_id, current_toy_UUID,
@@ -31,20 +66,25 @@ export default {
   },
   // 开启脑控
   sendControl() {
-    this.SendOrder('07')
-  },
-  //暂停脑控
-  sendControlPause() {
-    //AA CC 03 00 00 00 09 F3
-    this.SendOrder('08')
+    let that = this;
+    let $SendControlIntv = setInterval(() => {
+      if (FlagOpenControl) {
+        clearInterval($SendControlIntv)
+      } else {
+        that.SendOrder('07')
+      }
+    }, 1000);
   },
   // 关闭脑控
   sendControlClose() {
     let that = this
+    control_close = false;
     let $intv = setInterval(() => {
       if (!control_close) {
         that.SendOrder('09')
       } else {
+        //设置打开脑控为false
+        FlagOpenControl = false;
         clearInterval($intv)
         //清空当前数据
         that.clearLocalDatas()
@@ -64,27 +104,23 @@ export default {
   //获取教具电量
   sendToyPower_CheckReconected() {
     let that = this;
-    let $connect_false_count = 0;
-    let $game_status = game_store.getters.getGameStatus();
-    if ($game_status == 1) {
-      let toy_intv = setInterval(() => {
-        if (connect_toy) {
-          that.SendOrder('8a')
-          connect_toy = false
-          $connect_false_count = 0
-        } else {
-          $connect_false_count += 1;
-          console.log("循环数:" + $connect_false_count)
-          if ($connect_false_count == 2) {
-            //调用重连教具
-            connect_toy = false;
-            that.ReconnectToy()
-            clearInterval(toy_intv)
-          }
-        }
 
-      }, 3000)
-    }
+    let toy_intv = setInterval(() => {
+      let $game_status = game_store.getters.getGameStatus();
+      if ($game_status == 1) {
+        // if (!connect_toy) {
+        //   wx.showToast({
+        //     title: `教具已断开`
+        //   })
+        //   //调用重连教具
+        //   that.SendOrder("09")
+        //   that.ReconnectToy()
+        //   clearInterval(toy_intv)
+        // } else {
+        that.SendOrder('8a')
+        // }
+      }
+    }, 3000)
   },
 
   //  获取大包数据 进行绘制图表
@@ -181,9 +217,22 @@ export default {
               that.reconnect(res.deviceId, $this)
             }
           });
+          control_close = true
           // game_store.setters.setGameStatus(0);
           // 结束状态更改为1
-
+        } else {
+          game_store.setters.setGameStatus(0);
+          // 清空链接得设备 三值
+          game_store.setters.clearDeviceToy();
+          $this.connect_toy = 0;
+          $this.connect_show = false;
+          $this.device_bg = false;
+          $this.change_toy_connect_status(0);
+          $this.device_status = 0;
+          $this.device = {}
+          $this.toy_UUID = "";
+          $this.$forceUpdate();
+          wx.closeBluetoothAdapter();
         }
       }
     });
@@ -192,109 +241,119 @@ export default {
   //重新连接蓝牙
   reconnect($deviceId, $this) {
     let that = this;
-    let $serviceId = game_store.getters.getServiceId();
-    let $characteristicId = game_store.getters.getReadCharacterId();
+    let $deviceInfo = getServicesAndCharateristc();
     //重连的次数
     let $connect_count = 0;
     let $rec = setInterval(() => {
       $connect_count += 1;
-      wx.createBLEConnection({
-        deviceId: $deviceId,
-        success(res) {
-          Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
-          wx.notifyBLECharacteristicValueChange({
-            deviceId: $deviceId,
-            serviceId: $serviceId,
-            characteristicId: $characteristicId,
-            state: true,
-            success(res) {
-              console.log("重新连接SUCCESS,log", res)
-              that.watchingDevice($this)
-            }, fail(res) {
-              console.log("重新失败,log", res)
-            }
-          })
-          that.watchingDevice($this)
+      let $game_status = game_store.getters.getGameStatus();
+      if ($game_status == 1) {
+        wx.createBLEConnection({
+          deviceId: $deviceInfo.deviceId,
+          success(res) {
+            Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
+            that.openNotify($this)
+            clearInterval($rec)
+          },
+          fail(res) {
+            Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
+            game_store.setters.setGameCloseStatus(1);
+          }
+        })
+        if ($connect_count >= 3) {
+          $this.game_finished();
           clearInterval($rec)
-        },
-        fail(res) {
-          Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
-          game_store.setters.setGameCloseStatus(1);
         }
-      })
-      if ($connect_count == 3) {
-        $this.game_finished();
+      } else {
+        clearInterval($rec)
       }
 
-    }, 5000)
 
-  },
+    }, 5000)
 
-  //获取蓝牙设备服务
-  getBLEDeviceServices(deviceId) {
-    const $this = this;
-    current_device_mac = deviceId
-    wx.getBLEDeviceServices({
-      deviceId,
-      success: (res) => {
-        for (let i = 0; i < res.services.length; i++) {
-          console.log("serviceItem:" + res.services[i].uuid);
-          if (res.services[i].uuid.indexOf('6E') != -1 || res.services[i].uuid.indexOf('0000FFF0') != -1) {
-            console.log("SelectedServiceItem:" + res.services[i].uuid);
-            $this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
-            return;
-          }
-        }
-      },
-      fail(res) {
-        console.log("连接蓝牙成功,获取服务失败");
-      },
-    });
   },
 
-  //获取蓝牙设备某个服务中所有特征值
-  getBLEDeviceCharacteristics(deviceId, serviceId) {
-    console.log(deviceId, serviceId);
-    const $this = this;
-    wx.getBLEDeviceCharacteristics({
-      deviceId,
-      serviceId,
-      success: (res) => {
-        console.log("getBLEDeviceCharacteristics success", res.characteristics);
-        for (let i = 0; i < res.characteristics.length; i++) {
-          let item = res.characteristics[i];
-          if (item.properties.read) {
-            wx.readBLECharacteristicValue({
-              deviceId,
-              serviceId,
-              characteristicId: item.uuid,
-            });
-          }
-          if (item.properties.write) {
-            $this.deviceId = deviceId;
-            $this.serviceId = serviceId;
-            $this.cid = item.uuid;
-            game_store.setters.setDeviceId(deviceId);
-            game_store.setters.setServiceId(serviceId);
-            game_store.setters.setCid(item.uuid);
-            //打开数据帧
-            $this.sendOpenBigData();
-          }
-
-          if (item.properties.notify || item.properties.indicate) {
-            wx.notifyBLECharacteristicValueChange({
-              deviceId,
-              serviceId,
-              characteristicId: item.uuid,
-              state: true,
-            });
-            game_store.setters.setReadCid(item.uuid);
-          }
-        }
-      },
-      fail(res) {
-        console.error("getBLEDeviceCharacteristics", res);
-      },
+  // //获取蓝牙设备服务
+  // getBLEDeviceServices(deviceId) {
+  //   const $this = this;
+  //   current_device_mac = deviceId
+  //   wx.getBLEDeviceServices({
+  //     deviceId,
+  //     success: (res) => {
+  //       for (let i = 0; i < res.services.length; i++) {
+  //         console.log("serviceItem:" + res.services[i].uuid);
+  //         if (res.services[i].uuid.indexOf('6E') != -1 || res.services[i].uuid.indexOf('0000FFF0') != -1) {
+  //           console.log("SelectedServiceItem:" + res.services[i].uuid);
+  //           $this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
+  //           return;
+  //         }
+  //       }
+  //     },
+  //     fail(res) {
+  //       console.log("连接蓝牙成功,获取服务失败");
+  //     },
+  //   });
+  // },
+  //
+  // //获取蓝牙设备某个服务中所有特征值
+  // getBLEDeviceCharacteristics(deviceId, serviceId) {
+  //   console.log(deviceId, serviceId);
+  //   const $this = this;
+  //   wx.getBLEDeviceCharacteristics({
+  //     deviceId,
+  //     serviceId,
+  //     success: (res) => {
+  //       console.log("getBLEDeviceCharacteristics success", res.characteristics);
+  //       for (let i = 0; i < res.characteristics.length; i++) {
+  //         let item = res.characteristics[i];
+  //         if (item.properties.read) {
+  //           wx.readBLECharacteristicValue({
+  //             deviceId,
+  //             serviceId,
+  //             characteristicId: item.uuid,
+  //           });
+  //         }
+  //         if (item.properties.write) {
+  //           $this.deviceId = deviceId;
+  //           $this.serviceId = serviceId;
+  //           $this.cid = item.uuid;
+  //           game_store.setters.setDeviceId(deviceId);
+  //           game_store.setters.setServiceId(serviceId);
+  //           game_store.setters.setCid(item.uuid);
+  //           //打开数据帧
+  //           $this.sendOpenBigData();
+  //         }
+  //
+  //         if (item.properties.notify || item.properties.indicate) {
+  //           wx.notifyBLECharacteristicValueChange({
+  //             deviceId,
+  //             serviceId,
+  //             characteristicId: item.uuid,
+  //             state: true,
+  //           });
+  //           game_store.setters.setReadCid(item.uuid);
+  //         }
+  //       }
+  //     },
+  //     fail(res) {
+  //       console.error("getBLEDeviceCharacteristics", res);
+  //     },
+  //   });
+  // },
+
+  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.watchingDevice($this)
+        that.sendOpenBigData();
+      }
     });
   },
 
@@ -328,26 +387,37 @@ export default {
           $this.change_toy_connect_status(3);
           return false;
         }
-        let $hexAry = $this.current_hex.split(" ")
-        // 03 00 01 00 0a
-        //      [2] [3]
+        let $hex_index = hexStr.substr(hexStr.length - 4, 2)
+        let $toy_id = hexStr.substr(8, 2)
+        console.log("连接", $hex_index)
+        console.log("玩具", $toy_id)
         // 连接上教具
-        if (new RegExp("00").test($hexAry[2]) == false) {
-          if (new RegExp("00").test($hexAry[3]) == true) {
-            that.sendConnectOneToOne($hexAry[2])
-            $this.current_hex = `03 00 $hexAry[2] 01 0A`
-            console.log("一对多")
-          } else {
-            console.log("一对一")
-            $this.current_hex = "";
-            wx.showToast({
-              title: "已连接到" + $this.toy_item.name
-            });
-            $this.toy_connected = true;
-            $this.change_toy_connect_status(2);
-            //连接成功后 获取一次教具电量信息
-            that.SendOrder('8a')
-          }
+        if (new RegExp("00").test($hex_index) == true) {
+          that.sendConnectOneToOne($toy_id)
+          $this.current_hex = `03 00 ${$toy_id} 01 0A`
+          console.log("一对多")
+        }
+        if (new RegExp("01").test($hex_index) == true) {
+          console.log("一对一")
+          $this.current_hex = "";
+          wx.showToast({
+            title: "已连接到" + $this.toy_item.name
+          });
+          $this.toy_connected = true;
+          $this.change_toy_connect_status(2);
+          //连接成功后 获取一次教具电量信息
+          that.SendOrder('8a')
+        }
+
+        if (new RegExp("02").test($hex_index) == true) {
+          //发送教具连接
+          connect_toy = true
+          wx.hideLoading()
+          wx.showToast({
+            title: "教具重连成功"
+          })
+          that.sendControl()
+          that.sendToyPower_CheckReconected();
         }
       }
 
@@ -362,7 +432,12 @@ export default {
         console.log("电压:" + $voltage / 10)
         $this.toy_power = $power;
         //连接上教具的标识
-        connect_toy = true;
+        if ($power != 0) {
+          connect_toy = true;
+        }
+        if (hexStr.toUpperCase().indexOf("FF") != -1) {
+          connect_toy = false;
+        }
         if (current_toy_UUID == "") {
           //获取教具UUID
           that.SendOrder('84')
@@ -445,12 +520,12 @@ export default {
         //发送教具连接
         that.WriteBufferInBle(`03 00 ${current_toy_id} 02 0A`)
       }
-      if (hexStr.toUpperCase().indexOf("AADD0A02") != -1) {
-        //发送教具连接
-        connect_toy = true
-        wx.showToast({
-          title: "教具重连成功"
-        })
+
+
+      // 2021年11月10日14:34:26
+      // 处理打开脑控的应答
+      if (hexStr.toUpperCase().indexOf("AADD07") != -1) {
+        FlagOpenControl = true;
       }
 
 
@@ -557,9 +632,7 @@ export default {
   },
   //写入buffer
   WriteBufferInBle($hex, $buffer_len = 8) {
-    let $device_id = game_store.getters.getDeviceId();
-    let $service_id = game_store.getters.getServiceId()
-    let $charateristic = game_store.getters.getCharacterId();
+    let $deviceInfo = getServicesAndCharateristc();
     let $hex_header = "aa cc ";
     // let $hex = "03 00 01 00 0a";
 
@@ -580,9 +653,9 @@ export default {
     })
 
     wx.writeBLECharacteristicValue({
-      deviceId: $device_id,
-      serviceId: $service_id,
-      characteristicId: $charateristic,
+      deviceId: $deviceInfo.deviceId,
+      serviceId: $deviceInfo.service,
+      characteristicId: $deviceInfo.charateristic.write,
       value: buffer,
       success: function (res) {
         console.log($hex + ',写入成功')
@@ -628,6 +701,7 @@ export default {
 
   //重连教具
   ReconnectToy() {
+    let $game_status = game_store.getters.getGameStatus();
     let that = this;
     try {
       //发送UUID
@@ -648,20 +722,33 @@ export default {
       sum = sum.substr(0, sum.length - 1);
       let $hexStr = `03 ff ${sum} 8e`;
       let loop_count = "";
-      // let connect_toy_intv = setInterval(() => {
-      //   if (connect_toy == false) {
-      //     if (loop_count == 3) {
-      //       wx.showToast("教具已无法连接")
-      //       clearInterval(connect_toy_intv)
-      //     }
-      //     loop_count += 1;
-          that.WriteBufferInBle($hexStr, 16)
-      //   } else {
-      //     loop_count = 0;
-      //     clearInterval(connect_toy_intv)
-      //   }
-      //
-      // }, 3000)
+      if ($game_status == 1) {
+        wx.showLoading({
+          title: "重新连接教具中"
+        })
+      }
+      let connect_toy_intv = setInterval(() => {
+        if ($game_status == 1) {
+
+          if (connect_toy == false) {
+            if (loop_count == 3) {
+              wx.hideLoading()
+              wx.showToast("教具已无法连接")
+              clearInterval(connect_toy_intv)
+            }
+            loop_count += 1;
+            that.WriteBufferInBle($hexStr, 16)
+          } else {
+            wx.hideLoading()
+            loop_count = 0;
+            clearInterval(connect_toy_intv)
+          }
+        } else {
+          wx.hideLoading()
+          clearInterval(connect_toy_intv)
+        }
+      }, 3000)
+
 
     } catch (e) {
       console.log("ReconnectToy:", e)