Selaa lähdekoodia

优化蓝牙连接流程5

chaooo 1 vuosi sitten
vanhempi
commit
79f54b589b

+ 4 - 7
src/components/connection/brains/connected.vue

@@ -3,12 +3,9 @@ export default {
   name: "connected",
   props: ['device_bg', 'device_power'],
   methods: {
-    /**
-     * 修改设备连接状态
-     * @param $status 设备状态 0为未连接,1:连接中,2:已连接 3:连接失败/断开连接
-     */
-    setDeviceStatus($status = 0) {
-      this.$emit("deviceStatus", $status);
+    // 断开脑机
+    cancelConnect() {
+      this.$emit("deviceStatus", 5);
     },
     /**
      * 打开教具选择
@@ -52,7 +49,7 @@ export default {
     <!--        按钮组合-->
     <van-row>
       <van-col span="9" offset="1">
-        <button class="cu-btn bg-red lg text-white" @click="setDeviceStatus(3)">
+        <button class="cu-btn bg-red lg text-white" @click="cancelConnect">
           <img src="https://img.shuimuai.com/m_duankainaohuan.png" class="cut_brain_icon" alt="">
           <text class="padding-lr cut_text">断开脑机</text>
         </button>

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

@@ -37,7 +37,7 @@ export default {
   methods:{
     /**
      * 修改设备连接状态
-     * @param $status 设备状态 0为未连接,1:连接中,2:已连接 3:连接失败
+     * @param $status 设备状态 0:为未连接,1:连接中,2:已连接 3:连接失败 5:取消连接
      */
     setDeviceStatus($status = 0) {
       $this.device_status = $status;
@@ -168,7 +168,7 @@ export default {
      */
     cancelConnect() {
       clearTimeout($this.bleFoundTimeOut);
-      $this.setDeviceStatus(3);
+      $this.setDeviceStatus(5);
     },
   },
 }

+ 54 - 55
src/components/connection/index.vue

@@ -6,7 +6,7 @@ import Connecting from "@/components/connection/brains/connecting";
 import Connected from "@/components/connection/brains/connected";
 import ToySelected from "@/components/connection/toys/selected";
 import ToySelection from "@/components/connection/toys/selection";
-import Toast from "../../../static/vant/toast/toast";
+
 let $this;
 export default {
   name: "ConnectionIndex",
@@ -19,7 +19,7 @@ export default {
   },
   data() {
     return {
-      // 设备状态 0为未连接,1:连接中,2:已连接 3:连接失败
+      // 设备状态 0:为未连接,1:连接中,2:已连接 3:连接失败 5:取消连接
       device_status: 0,
       // 教具选择弹框
       popup_show: false,
@@ -59,33 +59,28 @@ export default {
     },
     /**
      * 获取设备连接状态
-     * @param $status 设备状态 0为未连接,1:连接中,2:已连接 3:连接失败 4:取消連
+     * @param $status 设备状态 0:为未连接,1:连接中,2:已连接 3:连接失败 5:取消连
      */
     setDeviceStatus($status) {
-      $this.device_status = $status * 1;
       console.log("接收到设备连接状态:", $status);
       if ($status * 1 === 2) {
+        $this.device_status = 2;
         // 已连接
         let $checkServices = setInterval(() => {
           let $serviceId = ble_store.getters.getServiceId();
           if ($serviceId) {
             clearInterval($checkServices);
             // 监听数据
+            //$this.$connection.openNotify($this);
             $this.$connection.notifyDatas($this);
             $this.$connection.watchBLEstatus($this);
           }
         }, 1500);
       } else {
-        game_store.setters.setGameStatus(0);
-        // todo 清空链接的设备
-        $this.connect_toy = $status;
-        //$this.connect_show = false;
-        $this.device_bg = false;
-        $this.connect_status = false;
+        $this.device_status = 0;
         if ($status * 1 > 0) {
-          // 关闭脑机蓝牙连接
+          // 取消连接-关闭脑机蓝牙连接
           $this.$connection.closeConnection($this);
-
         }
       }
     },
@@ -177,54 +172,58 @@ export default {
 </script>
 
 <template>
-  <div id="device_container">
-    <view>
-      <text class="cuIcon-titles text-primary"></text>
-      <text class="">我的设备</text>
-    </view>
-    <div class="device padding">
-      <!-- 脑机模块 -->
-      <div v-if="connect_toy === 0">
-        <!-- 扫码连接 -->
-        <div v-if="device_status === 0" class="connect_box">
-          <ConnectionScan @scanStatus="getScanStatus"></ConnectionScan>
-        </div>
-        <template v-else>
-          <!-- 连接中 -->
-          <div v-if="device_status !== 2" class="connecting_box">
-            <Connecting :status="device_status" @deviceStatus="setDeviceStatus"></Connecting>
+  <div>
+    <div id="device_container">
+      <view>
+        <text class="cuIcon-titles text-primary"></text>
+        <text class="">我的设备</text>
+      </view>
+      <div class="device padding">
+        <!-- 脑机模块 -->
+        <div v-if="connect_toy === 0">
+          <!-- 扫码连接 -->
+          <div v-if="device_status === 0" class="connect_box">
+            <ConnectionScan @scanStatus="getScanStatus"></ConnectionScan>
           </div>
-          <!-- 已链接 -->
-          <div v-if="device_status === 2" class="connected_box">
-            <Connected :device_bg="device_bg" :device_power="device_power" @deviceStatus="setDeviceStatus" @openToys="openToyList"></Connected>
+          <template v-else>
+            <!-- 连接中 -->
+            <div v-if="device_status !== 2" class="connecting_box">
+              <Connecting :status="device_status" @deviceStatus="setDeviceStatus"></Connecting>
+            </div>
+            <!-- 已链接 -->
+            <div v-if="device_status === 2" class="connected_box">
+              <Connected :device_bg="device_bg" :device_power="device_power" @deviceStatus="setDeviceStatus" @openToys="openToyList"></Connected>
+            </div>
+          </template>
+        </div>
+        <!-- 教具模块 -->
+        <div v-else>
+          <div class="connecting_toy">
+            <ToySelected :connect_toy="connect_toy"
+                         :toy="toy_item"
+                         :toy_sn="toy_sn"
+                         :device_bg="device_bg"
+                         :device_power="device_power"
+                         :toy_power="toy_power"
+                         @openToys="openToyList"
+                         @deviceStatus="setDeviceStatus"
+                         @gameStart="gameStart"
+            ></ToySelected>
           </div>
-        </template>
-      </div>
-      <!-- 教具模块 -->
-      <div v-else>
-        <div class="connecting_toy">
-          <ToySelected :connect_toy="connect_toy"
-                       :toy="toy_item"
-                       :toy_sn="toy_sn"
-                       :device_bg="device_bg"
-                       :device_power="device_power"
-                       :toy_power="toy_power"
-                       @openToys="openToyList"
-                       @deviceStatus="setDeviceStatus"
-                       @gameStart="gameStart"
-          ></ToySelected>
         </div>
+        <!-- 选择教具 -->
+        <van-popup :show="popup_show" @close="closePopup" position="bottom" round closeable safe-area-inset-bottom>
+          <ToySelection></ToySelection>
+          <div class="padding">
+            <button class="cu-btn lg cu-btn-primary text-white text-center padding" @click="chooseOK">
+              选好了
+            </button>
+          </div>
+        </van-popup>
       </div>
-      <!-- 选择教具 -->
-      <van-popup :show="popup_show" @close="closePopup" position="bottom" round closeable safe-area-inset-bottom>
-        <ToySelection></ToySelection>
-        <div class="padding">
-          <button class="cu-btn lg cu-btn-primary text-white text-center padding" @click="chooseOK">
-            选好了
-          </button>
-        </div>
-      </van-popup>
     </div>
+    <van-toast id="van-toast"/>
+    <van-dialog id="van-dialog"/>
   </div>
 </template>
 

+ 1 - 1
src/components/connection/toys/selected.vue

@@ -31,7 +31,7 @@ export default {
   methods: {
     // 断开脑机
     cancelConnect() {
-      $this.$emit("deviceStatus", 3);
+      $this.$emit("deviceStatus", 5);
     },
     // 打开玩具下拉列表
     openToyList() {

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

@@ -178,7 +178,7 @@ 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;
+let att_charts, med_charts, $this;
 
 // 大脑图表初始化
 function initAttChart(canvas, width, height) {
@@ -549,6 +549,7 @@ export default {
       //判断是否隐藏 隐藏则不绘画
       let $hide_status = game_store.getters.getHideStatus();
       if (!$hide_status) {
+        //console.log("专注放松度:",$this.att_list, $this.med_list, $this.amp_list)
         //通过专注放松度 画图
         let $option = util.getLineOption($this.att_list, $this.med_list, $this.amp_list);
         att_charts.setOption($option);

+ 0 - 544
src/pages/user_center/firmware/index.vue

@@ -1,544 +0,0 @@
-<template>
-  <div id="firmwareContainer">
-    <div v-if="finished == false">
-      <p class="title">
-        {{ title }}
-      </p>
-      <div class="loading" v-if="update_state">
-        <van-steps :steps="steps" :active="step_active"/>
-        <div class="progress_container">
-          <van-progress :percentage="progress" v-if="step_active == 2"/>
-        </div>
-      </div>
-      <van-divider/>
-      <p class="subtitle">
-        更新相关准备
-      </p>
-      <div class="desc_container">
-        <p class="desc" v-for="(desc,index) in desc_list" :key="index">{{ desc }}</p>
-        <p class="desc" v-if="step_active>0">请将脑环保持供电
-          <van-icon name="checked" color="#07c160" v-if="hasUsb"/>
-          <van-icon name="clear" color="#ff2f4f" v-else/>
-        </p>
-      </div>
-
-      <button class="ready_button" @click="ReadyUpdate" v-if="update_state == false">准备好了</button>
-
-    </div>
-    <div v-else>
-      <div class="finished_container">
-        <van-icon name="checked" size="60px" color="#46D5A4"/>
-        <p class="finsihed_subtitle">升级完成</p>
-        <van-button
-          class="finished_button"
-          round color="#7078FF"
-          plain
-          custom-style="margin:200px auto 0px;"
-          @click="BackIndex"
-        >&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;返回&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
-        </van-button>
-      </div>
-    </div>
-    <!--    <p class="version_info">-->
-    <!--      当前版本:{{ software_version }}-->
-    <!--    </p>-->
-
-    <van-toast id="van-toast"/>
-  </div>
-</template>
-<script>
-import {EditFirmwareVersion, getDeviceBySn} from "../../../requests/game";
-import ble_store from "@/store/bluetooth";
-import Toast from "../../../../static/vant/toast/toast";
-
-var $this;
-var FileSystemManager = wx.getFileSystemManager();
-export default {
-  name: "firmwareContainer",
-  data() {
-    return {
-      brain_sn: "",
-      result: "",
-      updateImageSavePath: "",
-      software_version: "",
-      model: "",
-      //解密行数下标
-      dec_index: 0,
-      buffers: [],
-      payload_len: 0,
-      progress: "",
-      hasUsb: false,
-      title: "固件升级准备",
-      //更新状态
-      update_state: false,
-      desc_list: [
-        "1.保持智脑环开机状态,且电量保证50%,或保持充电;",
-        "2.保持手机电量充足,网络处于WIFI或畅通状态;",
-        "3.手机蓝牙开启状态;",
-        "4.升级固件时避免手机关机或智脑环关机;",
-        "5.固件升级中大概5-10分钟,中途不能退出水母星球,否则会导致升级失败"
-      ],
-      step_active: 0,
-      steps: [
-        {
-          text: "环境检查"
-        },
-        {
-          text: "下载固件"
-        },
-        {
-          text: "固件更新"
-        },
-        {
-          text: "更新完成"
-        },
-      ],
-      finished: false
-    }
-  },
-  watch: {
-    update_state($new, $old) {
-      if ($new == true) {
-        $this.title = "固件更新"
-      } else {
-        $this.title = "固件升级准备"
-      }
-    },
-    step_active($new, $old) {
-      //更新完成
-      if ($new == $this.steps.length - 1) {
-        //提交 脑环和版本到数据库
-        let firmware_info = JSON.parse(wx.getStorageSync("firmware_info"))
-        EditFirmwareVersion($this.brain_sn, firmware_info.version)
-        $this.finished = true;
-      }
-    }
-  },
-  methods: {
-    /**
-     * 扫码连接设备
-     * @constructor
-     */
-    ConnectBrain() {
-      // 判断新的标识值
-      // $this.brain_sn = $code;
-      //打开蓝牙设备
-      wx.getSystemInfo({
-        success(res) {
-          // 判断ios 和 安卓
-          if (res.platform == "ios") {
-            wx.openBluetoothAdapter({
-              //判断主机模式蓝牙是否打开
-              mode: "central",
-              success(res) {
-                //判断已经打开连接了
-                if (res["errMsg"] == "openBluetoothAdapter:ok") {
-                  // $this.startBluetoothDevicesDiscovery();
-                  wx.openBluetoothAdapter({
-                    //判断从机模式蓝牙是否打开
-                    mode: "peripheral",
-                    success(res) {
-                      if (res["errMsg"] == "openBluetoothAdapter:ok") {
-                        $this.startBluetoothDevicesDiscovery();
-                      }
-                    },
-                    fail(err) {
-                      let $msg =
-                        $this.$connection.connectionError(
-                          err["errCode"]
-                        );
-                      setTimeout(() => {
-                        Toast.fail({
-                          message: $msg,
-                        });
-                      }, 3000);
-                    },
-                  });
-                }
-              },
-              fail(err) {
-                let $msg = $this.$connection.connectionError(
-                  err["errCode"]
-                );
-                setTimeout(() => {
-                  Toast.fail({
-                    message: $msg,
-                  });
-                }, 3000);
-              },
-            });
-          } else {
-            // 安卓手机
-            wx.openBluetoothAdapter({
-              mode: "peripheral",
-              success(res) {
-                //判断已经打开连接了
-                if (res["errMsg"] == "openBluetoothAdapter:ok") {
-                  $this.startBluetoothDevicesDiscovery();
-                }
-              },
-              fail(err) {
-                let $msg = $this.$connection.connectionError(
-                  err["errCode"]
-                );
-                setTimeout(() => {
-                  Toast.fail({
-                    message: $msg,
-                  });
-                }, 3000);
-              },
-            });
-          }
-        },
-      });
-
-    },
-    /**
-     * 开始蓝牙被发现
-     */
-    startBluetoothDevicesDiscovery() {
-      wx.startBluetoothDevicesDiscovery({
-        allowDuplicatesKey: true,
-        success: (res) => {
-          //2021年10月21日15:07:57  通过sn 返回deviceId
-          getDeviceBySn($this.code).then((res) => {
-            let $data = res.data;
-            console.log($data.code);
-            $data = $data.data;
-            wx.getSystemInfo({
-              success(res) {
-                // 判断ios 和 安卓
-                if (res.platform == "ios") {
-                  $this.onBluetoothDeviceFound();
-                } else {
-                  if ($data.device_id) {
-                    console.log("finded");
-                    $this.device_finded = true;
-                    $this.createBLEConnection($data.device_id);
-                  } else {
-                    $this.device_finded = false;
-                    console.log("unfinded");
-                    $this.onBluetoothDeviceFound();
-                  }
-                }
-              },
-            });
-          });
-        },
-        fail(err) {
-          $this.change_device_status(3);
-        },
-      });
-    },
-    onBluetoothDeviceFound() {
-      try {
-        wx.onBluetoothDeviceFound((res) => {
-          res.devices.forEach((device) => {
-            if (!device.name && !device.localName) {
-              return;
-            }
-            if (device.localName && device.localName != "") {
-              device.name = device.localName;
-            }
-            if (device["name"].toUpperCase() == $this.brain_sn) {
-              console.log("搜索设备", device);
-              $this.createBLEConnection(device.deviceId);
-            }
-          });
-        });
-      } catch (e) {
-        console.log("打开蓝牙error", e);
-      }
-    },
-    /**
-     * 连接低功耗蓝牙设备
-     * @param deviceId
-     */
-    createBLEConnection(deviceId) {
-      wx.offBluetoothDeviceFound();
-      wx.stopBluetoothDevicesDiscovery();
-
-      wx.createBLEConnection({
-        deviceId: deviceId,
-        success: (res) => {
-          console.log(deviceId)
-          // 设置mtu单位大小
-          wx.setBLEMTU({
-            deviceId,
-            mtu: 250,
-            success(res) {
-              console.log("设置mtu成功", JSON.stringify(res));
-            },
-            fail(err) {
-              console.log(err)
-            }
-          })
-          ble_store.setters.setDeviceId(deviceId);
-          $this.$connection.getBLEDeviceServices(deviceId);
-          let $checkServices = setInterval(() => {
-            let $serviceId = ble_store.getters.getServiceId();
-            if ($serviceId) {
-              clearInterval($checkServices);
-              // $this.$connection.openNotify($this);
-              $this.$connection.notifyDatas($this);
-              $this.$connection.watchBLEstatus($this);
-            }
-            // setTimeout(() => {
-            //     $this.$connection.SendOrder("02");
-            //   }, 1000);
-          }, 1500);
-
-          //步骤加一
-          $this.step_active += 1;
-          $this.downloadUpateFile()
-
-          console.log("连接成功")
-        },
-        fail(err) {
-          console.log(err);
-        },
-      });
-    },
-    /**
-     * todo 下载更新文件
-     */
-    downloadUpateFile() {
-      let firmware_info = JSON.parse(wx.getStorageSync("firmware_info"))
-
-      wx.downloadFile({
-        url: firmware_info.url, //仅为示例,并非真实的资源
-        success(res) {
-          // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
-          if (res.statusCode === 200) {
-            // $this.AddContent("下载成功")
-            console.log(res)
-            //将临时文件保存到用户文件路径下
-            FileSystemManager.saveFile({
-              tempFilePath: res.tempFilePath,
-              filePath: `${wx.env.USER_DATA_PATH}/update.img`,
-              success(res) {
-                $this.updateImageSavePath = res.savedFilePath
-                $this.readUpdateFile()
-              }, fail(err) {
-                console.log(err)
-              }
-            })
-          }
-        }
-      })
-    },
-    /**
-     * todo 读取更新文件
-     */
-    readUpdateFile() {
-      FileSystemManager.readFile({
-        filePath: $this.updateImageSavePath,
-        success(res) {
-          console.log(res.data)
-        }
-      })
-      FileSystemManager.readFile({
-        filePath: $this.updateImageSavePath,
-        success(res) {
-          // $this.AddContent("读取文件成功")
-          let buffer_len = new Uint8Array(res.data).length
-          // 读取信息
-          for (let i = 0; i < buffer_len; i += 16) {
-            let buffer = new Uint8Array(res.data, i, 16);
-            if (i == 0) {
-              //读取第一行信息 并返回 文件解密下标
-              $this.dec_index = $this.getUpdateHeader0(buffer) / 10
-              console.log(`解密指定行:${$this.dec_index}`)
-            }
-            if (i == 1 * 16) {
-              let software_version = "";
-              for (let j = 0; j < buffer.length; j++) {
-                software_version += String.fromCharCode(buffer[j])
-              }
-              console.log(`软件版本:${$this.software_version}`)
-            }
-            if (i == 2 * 16) {
-              for (let j = 0; j < buffer.length; j++) {
-                $this.model += String.fromCharCode(buffer[j])
-              }
-              $this.model = $this.model.trim()
-              console.log(`模型:${$this.model}`)
-            }
-            //发送指定行的数据
-            if (i >= $this.dec_index * 16) {
-              $this.buffers = res.data
-              $this.step_active += 1;
-              //开始升级
-              $this.OpenBleUpdate();
-              break;
-            }
-          }
-        },
-        fail(err) {
-          console.log(err)
-        }
-      })
-    },
-    /**
-     * 获取第一行头部信息
-     * @param buffer 数据包
-     * @returns {number} 返回需要解密的位置信息
-     */
-    getUpdateHeader0(buffer) {
-      //验证升级标志
-      let update_tag = [88, 48, 57, 57]
-      let update_tag_count = update_tag.length
-      for (let i = 0; i < update_tag.length; i++) {
-        let _buffer = buffer[i].toString(16);
-        //验证升级标志
-        if (_buffer == update_tag[i]) {
-          update_tag_count -= 1;
-          if (update_tag_count == 0) {
-            // // $this.AddContent("验证升级标志成功")
-          }
-        }
-      }
-
-      //获取payload长度
-      let payload_len = ""
-      for (let i = 7; i > 3; i--) {
-        let _buffer = ('00' + buffer[i].toString(16)).substr(-2, 2);
-        //验证升级标志
-        payload_len += `${_buffer}`;
-      }
-      payload_len = parseInt(payload_len, 16);
-      $this.payload_len = payload_len;
-
-      //获取升级的offset
-      let update_offset = 0
-      for (let i = 15; i > 11; i--) {
-        let _buffer = buffer[i].toString(16);
-        //验证升级标志
-        update_offset += parseInt(_buffer);
-      }
-
-      //文件总长度
-      let file_total_size = payload_len + parseInt(update_offset, 16)
-      return update_offset;
-    },
-    /**
-     * 打开蓝牙升级通道
-     * @constructor
-     */
-    OpenBleUpdate() {
-      let buffer = new Uint8Array($this.buffers, 4, 4)
-      let $hexStr = [
-        '03',
-        '30'
-      ]
-      for (let i = 0; i < 11; i++) {
-        if (i < buffer.length) {
-          let $hex = ('00' + buffer[i].toString(16)).substr(-2, 2)
-          $hexStr.push($hex)
-        } else {
-          $hexStr.push('00')
-        }
-      }
-      $this.$connection.WriteBufferInBle($hexStr.join(' '), 16)
-    },
-    // todo 准备升级
-    ReadyUpdate() {
-      $this.update_state = true
-      this.ConnectBrain()
-      // this.downloadUpateFile();
-    },
-    BackIndex() {
-      wx.navigateBack();
-    }
-  },
-  mounted() {
-  },
-  created() {
-    $this = this;
-  },
-  onLoad(option) {
-    this.brain_sn = option.sn
-  }
-}
-</script>
-<style>
-.title {
-  font-size: 32px;
-  font-family: PingFang SC;
-  font-weight: bold;
-  color: #151515;
-  margin: 25px 0px;
-}
-
-#firmwareContainer {
-  padding: 0px 30px;
-}
-
-.subtitle {
-  font-size: 17px;
-  font-family: PingFang SC;
-  font-weight: 500;
-  color: #151515;
-}
-
-.desc_container {
-  margin: 20px 0px;
-}
-
-.desc {
-  font-size: 14px;
-  font-family: PingFang SC;
-  font-weight: 400;
-  color: #666666;
-  margin: 10px 0px;
-}
-
-.ready_button {
-  width: 250px;
-  height: 45px;
-  background: #7078FF;
-  border-radius: 23px;
-
-  font-size: 17px;
-  font-family: PingFang SC;
-  font-weight: bold;
-  color: #FFFFFF;
-
-  margin: 100px auto;
-}
-
-.progress_container {
-  margin: 10px 0px;
-}
-
-.finsihed_subtitle {
-  font-size: 17px;
-  font-family: PingFang SC;
-  font-weight: bold;
-  color: #151515;
-  text-align: center;
-  margin-top: 20px;
-}
-
-.finished_container {
-  display: flex;
-  flex-direction: column;
-  justify-content: center;
-  margin-top: 100px;
-}
-
-.finished_button {
-  text-align: center;
-}
-
-.version_info {
-  font-size: 13px;
-  font-family: PingFang SC;
-  font-weight: 400;
-  color: #B2B2B2;
-  text-align: center;
-  position: absolute;
-  bottom: 100px;
-  margin: 0px auto;
-}
-</style>

+ 0 - 12
src/pages/user_center/firmware/main.js

@@ -1,12 +0,0 @@
-import Vue from 'vue'
-import App from './index'
-
-// add this to handle exception
-Vue.config.errorHandler = function (err) {
-  if (console && console.error) {
-    console.error(err)
-  }
-}
-
-const app = new Vue(App)
-app.$mount()

+ 0 - 15
src/pages/user_center/firmware/main.json

@@ -1,15 +0,0 @@
-{
-  "usingComponents": {
-    "van-row": "../../../static/vant/row/index",
-    "van-col": "../../../static/vant/col/index",
-    "van-popup": "../../../static/vant/popup/index",
-    "van-cell": "../../../static/vant/cell/index",
-    "van-cell-group": "../../../static/vant/cell-group/index",
-    "van-icon": "../../../static/vant/icon/index",
-    "van-toast": "../../../static/vant/toast/index",
-    "van-divider": "../../../static/vant/divider/index",
-    "van-steps": "../../../static/vant/steps/index",
-    "van-progress": "../../../static/vant/progress/index",
-    "van-button": "../../../static/vant/button/index"
-  }
-}

+ 13 - 6
src/store/bluetooth.js

@@ -11,9 +11,12 @@ const getters = {
   getServiceId() {
     return wx.getStorageSync('serviceId')
   },
-  getCharacteristicId(){
-    return wx.getStorageSync('characteristicId')
-  }
+  getCharacteristicWriteId(){
+    return wx.getStorageSync('characteristicWriteId')
+  },
+  getCharacteristicNotifyId(){
+    return wx.getStorageSync('characteristicNotifyId')
+  },
 }
 
 const setters = {
@@ -36,9 +39,13 @@ const setters = {
   setServiceId(serviceId) {
     wx.setStorageSync('serviceId', serviceId)
   },
-  setCharacteristicId(characteristicId){
-    wx.setStorageSync('characteristicId', characteristicId)
-  }
+  setCharacteristicWriteId(characteristicId){
+    wx.setStorageSync('characteristicWriteId', characteristicId)
+  },
+  setCharacteristicNotifyId(characteristicId){
+    wx.setStorageSync('characteristicNotifyId', characteristicId)
+  },
+
 }
 
 export default {

+ 60 - 34
src/utils/connection.js

@@ -13,8 +13,9 @@ let FlagOpenControl = false;
 function getDeviceWriteInfo() {
   let deviceId = ble_store.getters.getDeviceId();
   let serviceId = ble_store.getters.getServiceId();
-  let characteristicId = ble_store.getters.getCharacteristicId();
-  return { deviceId, serviceId, characteristicId };
+  let characteristicWriteId = ble_store.getters.getCharacteristicWriteId();
+  let characteristicNotifyId = ble_store.getters.getCharacteristicNotifyId();
+  return { deviceId, serviceId, characteristicWriteId, characteristicNotifyId};
 }
 /**
  * 转移原始数据
@@ -121,11 +122,16 @@ export default {
           if (item.properties.write) {
             console.log("第" + (i + 1) + ",该特征值可写:" + item.uuid);
             if(item.uuid.indexOf("0002") !== -1){
-              ble_store.setters.setCharacteristicId(item.uuid);
+              ble_store.setters.setCharacteristicWriteId(item.uuid);
+              //打开数据帧 (打开大包数据)
+              that.SendOrder('ff');
             }
           }
           if (item.properties.notify || item.properties.indicate) {
             console.log("第" + (i + 1) + ",该特征值可监听:" + item.uuid);
+            if(item.uuid.indexOf("0003") !== -1){
+              ble_store.setters.setCharacteristicNotifyId(item.uuid);
+            }
             // 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征。
             wx.notifyBLECharacteristicValueChange({
               deviceId: deviceId,
@@ -134,7 +140,7 @@ export default {
               state: true,
               success() {
                 that.notifyDatas(null);
-                console.log("正在监听特征值:", item.uuid);
+                console.log("init正在监听特征值:", item.uuid);
               }
             });
           }
@@ -292,8 +298,8 @@ export default {
    * @constructor
    */
   WriteBufferInBle($hex, $buffer_len = 8) {
-    let { deviceId, serviceId, characteristicId } = getDeviceWriteInfo();
-    if (deviceId && serviceId && characteristicId) {
+    let { deviceId, serviceId, characteristicWriteId } = getDeviceWriteInfo();
+    if (deviceId && serviceId && characteristicWriteId) {
       let that = this;
       let $hex_header = "aa cc ";
       let $hex_sum = 0;
@@ -312,7 +318,7 @@ export default {
       wx.writeBLECharacteristicValue({
         deviceId: deviceId,
         serviceId: serviceId,
-        characteristicId: characteristicId,
+        characteristicId: characteristicWriteId,
         value: buffer,
         success: function (res) {
           console.log($hex + "写入成功,时间:" + that.getNowTime())
@@ -323,11 +329,26 @@ 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
-   * @param characteristicId
    */
   notifyDatas($this) {
     const that = this;
@@ -340,10 +361,6 @@ export default {
       // 连接页面
       if($this && $this.$options.name){
         console.log("当前页面名称:", $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.substring(8, 10), 16);
@@ -454,29 +471,28 @@ export default {
               }
             }
           })
-
-        }
-
-
-        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);
+        // 监听佩戴正确, 当s1为 00时 数据有效
+        if (hexStr.substring(0, 6) === "555520") {
+          $this.device_bg = (hexStr.substring(8, 10) === "00");
+          console.log("监听佩戴正确:", hexStr.substring(0, 10), $this.device_bg);
+          //游戏中模块
+          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.device_bg){
+              $this.analysisGameData(hexStr);
+            }
+            // $this.hexStr = hexStr;
+            // let $data = that.get_big_data(hexStr);
+            // $this.do_datas($data);
           }
-          // $this.hexStr = hexStr;
-          // let $data = that.get_big_data(hexStr);
-          // $this.do_datas($data);
         }
 
         //todo 接收脑机关机指令
@@ -626,7 +642,7 @@ export default {
               that.getBLEDeviceServices($deviceInfo.deviceId)
               that.notifyDatas($this)
             } else {
-              // that.openNotify($this)
+              //that.openNotify($this)
               that.watchBLEstatus($this);
             }
             // that.sendToyPower();
@@ -654,6 +670,16 @@ export default {
    */
   closeConnection($this) {
     const that = this;
+    // 关闭脑控
+    $this.$connection.SendOrder("09");
+    game_store.setters.setGameStatus(0);
+    // todo 清空链接的设备
+    $this.connect_toy = 0;
+    //$this.connect_show = false;
+    $this.device_bg = false;
+    $this.connect_status = false;
+
+
     // 断开教具及蓝牙连接
     that.SendOrder("31");
     setTimeout(()=>{

+ 1 - 12
src/utils/game.js

@@ -136,19 +136,8 @@ export function formatPlaySeconds(value) {
 export function get_big_data(hex) {
   let hexAry = []
   for (let i = 0; i < hex.length; i += 2) {
-    hexAry.push(hex.substr(i, 2))
+    hexAry.push(hex.substring(i, 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)
   //放松度数据