Procházet zdrojové kódy

10/28 新赛季改图至11月

Foystor před 3 roky
rodič
revize
a52112b01e

+ 5 - 0
config/dev.env.js

@@ -3,6 +3,11 @@ var prodEnv = require('./prod.env')
 
 module.exports = merge(prodEnv, {
   NODE_ENV: '"development"',
+<<<<<<< HEAD
   // REQUEST_URI: "'https://api.shuimuai.com/'"
   REQUEST_URI: "'https://testapi.shuimuai.com/'"
+=======
+  REQUEST_URI: "'https://testapi.shuimuai.com/'"
+  // REQUEST_URI: "'https://testapi.shuimuai.com/'"
+>>>>>>> e6e65e8acc06ca9c724e9a0df47929887f5bf0c0
 })

+ 1 - 1
src/App.vue

@@ -8,7 +8,7 @@ export default {
   //外发
   onShow(options){
       let query = options.query.other
-      console.log('进入小程序了',options)
+      // console.log('进入小程序了',options)
       // 有无参数
       if(query){
         console.log('外发给你')

+ 2 - 2
src/components/banner.vue

@@ -71,7 +71,7 @@ export default {
     },
     getBanners() {
       getBannerList().then((res) => {
-        console.log("活动列表ID:", res);
+        // console.log("活动列表ID:", res);
         let $res = res.data;
         let $activities = $res.data;
         let $new_act = $activities.pop();
@@ -90,7 +90,7 @@ export default {
     //   getJointBanner().then((res) => {
     //     console.log("banner活动", res.data.data)
     //     let $banner_img = res.data.data
-        
+
     //     $this.banners[0].src = $banner_img[0].img
     //     $this.banners[2].src = $banner_img[1].img
     //   });

+ 3 - 3
src/components/device/connected.vue

@@ -72,9 +72,9 @@ export default {
 }
 
 .device_elc {
-  height: 10 rpx;
-  border-radius: 5 rpx;
-  bottom: 3 rpx;
+  height: 5px;
+  border-radius: 2.5px;
+  bottom: 1.5px;
 }
 
 </style>

+ 142 - 32
src/components/device/device.vue

@@ -42,11 +42,12 @@
         <div class="connecting_toy">
           <toy_connecting
             :connect_toy="connect_toy"
-            :deviceId="_deviceId"
+            :deviceId="device.deviceId"
             :toy_id="toy_action"
             :toy="toy_item"
             :device_bg="device_bg"
             :device_power="device_power"
+            :toy_power="toy_power"
             @open_choose_toy="open_choose_toy"
             @change_toy_connect_status="change_toy_connect_status"
             @change_status="change_device_status"
@@ -113,9 +114,13 @@
         </button>
       </div>
     </van-popup>
-    <van-toast id="van-toast" />
-    <van-dialog id="van-dialog" />
+    <van-toast id="van-toast"/>
+    <van-dialog id="van-dialog"/>
 
+    <view style="width: 100%;height: 300px;">
+      <view>脑环Mac:{{ device.deviceId }}</view>
+      <view>教具UUID:{{ toy_UUID }}</view>
+    </view>
     <!--    <van-popup-->
     <!--      :show="start_show"-->
     <!--      :closeable="false"-->
@@ -141,11 +146,10 @@ import toy_connecting from "@/components/device/toy/connecting";
 import gameIng from "@/pages/start/index";
 //获取个人信息
 import Toast from "../../../static/vant/toast/toast";
-import { game_devices } from "../../requests/game";
+import {game_devices, getDeviceBySn, setDeviceInDb} from "../../requests/game";
 import game_store from "@/store/game";
 import bluetooth from "@/utils/bluetooth";
-import ble_store from "../../store/bluetooth";
-import Dialog from "../../../static/vant/dialog/dialog";
+import {getNowDate} from "../../utils";
 
 let $this;
 export default {
@@ -180,16 +184,59 @@ export default {
       connect_toy: 0,
       code: "jellyfish1234",
       device: {},
-      _deviceId: "",
+      deviceId: "",
       _device_index: false,
       toy_id: 0,
+      toy_hex: "",
 
       // 电量
       device_power: 0,
+      //教具电量
+      toy_power: 0,
+      //教具名称
+      toy_sn: "",
+      //UUID
+      toy_UUID: "",
 
       //  开始游戏模块
       start_show: false,
       game_status: 0,
+
+      //当前发送的hex码
+      current_hex: "",
+      //判断是否已经连接教具
+      toy_connected: false,
+
+      device_finded: false,
+
+      device_data: {
+        //产品编码
+        sn: "",
+        //产品名称
+        product_name: "",
+        //产品型号       :"",
+        product_model: "",
+        //产品二维码
+        product_qrcode: "",
+        //生产年月日       :"",
+        production_date: "",
+        //制造工厂
+        manufacturing_plan: "",
+        //硬件版本       :"",
+        hardware_version: "",
+        //软件版本
+        software_version: "",
+        //蓝牙地址  mac_address
+        device_id: "",
+        //蓝牙PC地址
+        pc_device_id: "",
+        //ios蓝牙地址
+        ios_device_id: "",
+        //设备类型 1脑环 2玩具
+        type: "",
+        //UUID
+        UUID: "",
+      },
     };
   },
   methods: {
@@ -202,13 +249,9 @@ export default {
     },
     //扫描连接蓝牙
     scan_to_bluetooth() {
-      // console.log("在扫码时是否存在deviceId?:", this._deviceId);
       wx.scanCode({
         onlyFromCamera: true,
         success: (res) => {
-          wx.vibrateShort({
-            type: "heavy",
-          });
 
           let $data = res;
           if ($data.result) {
@@ -219,6 +262,16 @@ export default {
             // 判断新的标识值
             $this.code = $code[1].toUpperCase();
             console.log("头环码", $code);
+            //设备信息
+            $this.device_data.product_qrcode = url;
+            $this.device_data.sn = $this.code
+            //产品名称、制造工厂
+            $this.device_data.product_name = "水母智脑环";
+            $this.device_data.manufacturing_plan = "深圳水母智脑科技有限公司"
+            // 设备类型
+            $this.device_data.type = 1
+            $this.device_data.production_date = getNowDate()
+
             //打开蓝牙设备
             wx.getSystemInfo({
               success(res) {
@@ -303,8 +356,8 @@ export default {
     open_choose_toy() {
       // $this.choose_toy_window.show = false;
       $this.choose_toy_window.show = true;
-
-      bluetooth.sendEnd();
+      $this.toy_connected = false
+      bluetooth.sendControlClose();
     },
     // 选好玩具
     choose_ok() {
@@ -319,10 +372,18 @@ export default {
         }
       });
       $this.toy_id = $toy.id;
-      let $hex = $toy["hex"].substr($toy["hex"].length - 2, 2);
+      let $hex = $this.toy_hex = $toy["hex"].substr($toy["hex"].length - 2, 2);
       //连接玩具
+      $this.current_hex = `03 00 ${$hex} 00 0a`;
 
-      bluetooth.sendConnect($hex);
+      bluetooth.sendConnectOneToMore($hex);
+
+      //设置5秒后是否已经连接
+      setTimeout(() => {
+        if ($this.toy_connected == false) {
+          $this.change_toy_connect_status(3);
+        }
+      }, 5000)
     },
     //修改玩具连接状态
     change_toy_connect_status($status = 0) {
@@ -340,21 +401,33 @@ export default {
       //当脑环断开
       if ($status == 0) {
         game_store.setters.setGameStatus(0);
-        // bluetooth.shutdownSendControl();
         // 清空链接得设备 三值
         game_store.setters.clearDeviceToy();
         $this.connect_toy = $status;
         $this.connect_show = false;
-        $this._deviceId = "";
+        $this.device_bg = false;
+
+        bluetooth.SendOrder("09")
+
+        $this.change_toy_connect_status(0);
+        //断开蓝牙连接
         wx.closeBLEConnection({
-          deviceId: $this._deviceId,
+          deviceId: $this.device.deviceId,
           success(res) {
             Toast.success({
               message: "已成功断开",
             });
+            wx.closeBluetoothAdapter();
+          },
+          fail(res) {
+            console.log("断开连接error:", res)
           },
+          complete(res) {
+            $this.device = {}
+            $this.toy_UUID = "";
+            $this.$forceUpdate();
+          }
         });
-        wx.closeBluetoothAdapter();
       } else if ($status == 2) {
         $this.connect_show = true;
       }
@@ -363,10 +436,40 @@ export default {
     //开始蓝牙被发现
     startBluetoothDevicesDiscovery() {
       wx.startBluetoothDevicesDiscovery({
+        services: ["0000fff0-0000-1000-8000-00805f9b34fb", "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"],
         allowDuplicatesKey: true,
         success: (res) => {
-          $this.onBluetoothDeviceFound();
-          $this.change_device_status(1);
+          //2021年10月21日15:07:57  通过sn 返回deviceId
+          getDeviceBySn($this.code).then((res) => {
+            let $data = res.data;
+            console.log($data)
+            $this.change_device_status(1);
+            if ($data.code == 0) {
+              $data = $data.data;
+              wx.getSystemInfo({
+                success(res) {
+                  // 判断ios 和 安卓
+                  if (res.platform == "ios") {
+                    $this.device.deviceId = $data.ios_device_id;
+                  } else {
+                    $this.device.deviceId = $data.device_id;
+                  }
+                  if ($this.device.deviceId) {
+                    console.log("finded")
+                    $this.device_finded = true
+                    $this.createBLEConnection()
+                  } else {
+                    $this.device_finded = false
+                    console.log('unfinded')
+                    $this.onBluetoothDeviceFound();
+                  }
+                }
+              });
+            } else {
+              $this.onBluetoothDeviceFound();
+            }
+          })
+
         },
         fail(err) {
           $this.change_device_status(3);
@@ -375,16 +478,10 @@ export default {
     },
     //打开蓝牙搜索
     onBluetoothDeviceFound() {
-      // console.log(
-      //   "打开蓝牙搜索 device_status",
-      //   $this.device_status,
-      //   "是否有id _deviceId",
-      //   $this._deviceId
-      // );
       try {
         // 5秒后判断 这5秒在搜索设备,搜索到就赋值给_deviceId
         setTimeout(() => {
-          if (!$this._deviceId) {
+          if (!$this.device.deviceId) {
             wx.stopBluetoothDevicesDiscovery();
             $this.change_device_status(0);
             Toast.fail("未连接到设备");
@@ -411,8 +508,6 @@ export default {
               $this.stopBluetoothDevicesDiscovery();
               $this.device = device;
               game_store.setters.setDeviceId(device.deviceId);
-              $this._deviceId = device.deviceId;
-
               $this.createBLEConnection();
             }
           });
@@ -436,6 +531,18 @@ export default {
           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)
+            }, 3000)
+          }
+
+
         },
         fail(err) {
           console.log(err);
@@ -494,6 +601,8 @@ export default {
       //   //断开蓝牙连接
       //   $this.change_device_status(0);
       // }
+      $this.toy_UUID = "";
+      $this.$forceUpdate();
       // 状态为1的时候重置为1 小乌龟
       if ($game_close_status == 1) {
         // 重置默认条件
@@ -501,8 +610,9 @@ export default {
         $this.connect_show = false;
         $this.device_status = 0;
         bluetooth.watch_bluetooth_status($this);
-        $this._deviceId = "";
-
+        $this.device.deviceId = "";
+        $this.toy_UUID = "";
+        $this.$forceUpdate();
         // 清空链接的设备
         game_store.setters.clearDeviceToy();
 

+ 3 - 2
src/components/device/toy/connecting.vue

@@ -94,7 +94,7 @@
               {{ toy['name'] }}
             </template>
             <template v-if="connect_toy == 2 || connect_toy == 4">
-              已连接
+              {{ toy['name'] }}({{toy_power}}%)
             </template>
           </text>
         </div>
@@ -297,6 +297,7 @@ export default {
     "toy",
     "device_bg",
     "device_power",
+    "toy_power",
   ],
   data() {
     return {
@@ -328,7 +329,7 @@ export default {
       $this.pay_type = $event;
       let $params = {
         type: $event,
-        device_id: $this.toy_id, 
+        device_id: $this.toy_id,
         access_token: wx.getStorageSync("token"),
       };
       gameStart($params).then(

+ 24 - 22
src/pages/index/index.vue

@@ -71,8 +71,8 @@
         </van-row>
       </div>
     </div>
-    <van-toast id="van-toast" />
-    <van-dialog id="van-dialog" />
+    <van-toast id="van-toast"/>
+    <van-dialog id="van-dialog"/>
     <!--     <button class="cu-btn lg cu-btn-primary text-white text-center margin-tb" @click="auth_msg">获取消息授权-->
     <!--    </button>-->
   </div>
@@ -86,10 +86,10 @@ import personal_container from "@/components/index/personal";
 import device_container from "@/components/device/device";
 import Toast from "../../../static/vant/toast/toast";
 import Dialog from "../../../static/vant/dialog/dialog";
-import { userDetail, setUserLogin } from "../../requests/user";
+import {userDetail, setUserLogin} from "../../requests/user";
 import user_store from "../../store/index";
 import game_store from "../../store/game";
-import game_util, { post_data } from "../../utils/game";
+import game_util, {post_data} from "../../utils/game";
 
 var $this;
 export default {
@@ -111,7 +111,8 @@ export default {
     };
   },
   methods: {
-    get_init_data() {},
+    get_init_data() {
+    },
     //切换到扫码
     change_status($status) {
       this.login_status = $status;
@@ -172,21 +173,21 @@ export default {
     });
   },
   onShow() {
-    if(wx.getStorageSync("is_other_first") == false){
-       wx.setStorageSync("is_other", false);
-    } else{
-       wx.setStorageSync("is_other", true);
+    if (wx.getStorageSync("is_other_first") == false) {
+      wx.setStorageSync("is_other", false);
+    } else {
+      wx.setStorageSync("is_other", true);
     }
-    
-    wx.getStorageInfo({
-      success(res) {
-        console.log("当前存储的数据", res.keys);
-        let $keys = res.keys;
-        $keys.forEach(($val, $index) => {
-          console.log($val, wx.getStorageSync($val));
-        });
-      },
-    });
+
+    // wx.getStorageInfo({
+    //   success(res) {
+    //     console.log("当前存储的数据", res.keys);
+    //     let $keys = res.keys;
+    //     $keys.forEach(($val, $index) => {
+    //       console.log($val, wx.getStorageSync($val));
+    //     });
+    //   },
+    // });
     userDetail().then((res) => {
       let $data = res.data;
       //判断如果是第一次登录就 弹出领取体验卡
@@ -194,10 +195,11 @@ export default {
       user_store.setters.set_userinfo($this.userinfo);
     });
   },
-  onHide() {},
+  onHide() {
+  },
   onLoad($option) {
     if (process.env.NODE_ENV == "development") {
-      // wx.setStorageSync("token", "ZbNv-hpdpmxk895iqUrEwe4kCJjEWCJD");
+      wx.setStorageSync("token", "ogsti72oUSkbPl4OL7gl9woLTxR6fk4V");
     }
 
     if (game_store.getters.getGameStatus() == 1) {
@@ -220,7 +222,7 @@ export default {
       // });
       // 存在token时候录入
       setUserLogin().then((res) => {
-        console.log("录入", res);
+        // console.log("录入", res);
       });
     }
   },

+ 73 - 53
src/pages/start/index.vue

@@ -1,5 +1,9 @@
 <template>
   <div id="playing_container">
+    <view style="width: 100%;height: 100px;color: white">
+      <view>脑环Mac:{{ deviceId }}</view>
+      <view>教具UUID:{{ toy_UUID }}</view>
+    </view>
     <!--    计费面板模块-->
     <div class="game_panel padding-top-sm">
       <van-row gutter="16">
@@ -42,8 +46,7 @@
     <div class="game_status padding-tb">
       <van-row>
         <van-col
-          span="10"
-          offset="2"
+          span="8"
         >
           <div
             class="flex flex-direction align-center justify-center"
@@ -68,7 +71,7 @@
             <text class="text-default">未正确佩戴</text>
           </div>
         </van-col>
-        <van-col span="10">
+        <van-col span="8">
           <div class="flex flex-direction align-center justify-center">
             <view class="elc_power_container">
               <img
@@ -82,16 +85,21 @@
             <text class="text-default">设备电量</text>
           </div>
         </van-col>
-        <!-- <van-col span="2">
+
+        <van-col span="8">
           <div class="flex flex-direction align-center justify-center">
-            <view>
-              <text>-{{ rssi }}dbm</text>
-            </view>
-            <view>
-              <text class="text-default">信号强度</text>
+            <view class="elc_power_container">
+              <img
+                src="https://img.shuimuai.com/web/dianchi_3.png"
+                alt=""
+                :style="{ width: toy_power + '%' }"
+                class="device_elc"
+              />
             </view>
+            <text class="text-default">{{ toy_power }}%</text>
+            <text class="text-default">教具电量</text>
           </div>
-        </van-col> -->
+        </van-col>
       </van-row>
     </div>
 
@@ -285,7 +293,7 @@ export default {
 
       user_info: {},
       //设备值
-      _deviceId: "",
+      deviceId: "",
       _serviceId: "",
       _characteristicId: "",
 
@@ -344,49 +352,50 @@ export default {
       //  蓝牙信号强度
       rssi: 0,
       game_status: 0,
+      toy_power: 0,
+      toy_UUID: "",
     };
   },
   methods: {
     //游戏结束方法
-    game_finished() {  
-        if (!$this.executed){
-          bluetooth.sendEnd();
-
-          $this.$emit("closePop", true);
-          //取消监听低功耗蓝牙设备
-          wx.offBLECharacteristicValueChange();
-          //设置游戏状态为 停止游戏
-          game_store.getters.getGameStatus() == 0
-            ? game_store.setters.setGameStatus(0)
-            : game_store.setters.setGameStatus(3);
-          //游戏结束重置游戏时间
-          wx.removeStorageSync("play_time");
-          //删除游戏专注数据
-          game_store.remover.rmGameAttMedDatas();
-          //删除隐藏时间
-          game_store.remover.rmHideTime();
-          //游戏结束重置游戏模式
-          // game_store.setters.setMode(0);
-          //删除游戏得id
-          game_store.setters.removeToyHex();
-
-          // 结束游戏在提交报告函数里
-          $this.post_data();
-
-          $this.game_over();
-
-          
-          Toast.loading({
-              forbidClick: true,
-              mask: true,
-              message: "正在生成报告...",
-              duration: 2000,
-              onClose() {
-                $this.to_report();
-              }
-          });
-        }
-        $this.executed = true;
+    game_finished() {
+      if (!$this.executed) {
+        bluetooth.sendControlClose();
+
+        $this.$emit("closePop", true);
+
+        //设置游戏状态为 停止游戏
+        game_store.getters.getGameStatus() == 0
+          ? game_store.setters.setGameStatus(0)
+          : game_store.setters.setGameStatus(3);
+        //游戏结束重置游戏时间
+        wx.removeStorageSync("play_time");
+        //删除游戏专注数据
+        game_store.remover.rmGameAttMedDatas();
+        //删除隐藏时间
+        game_store.remover.rmHideTime();
+        //游戏结束重置游戏模式
+        // game_store.setters.setMode(0);
+        //删除游戏得id
+        game_store.setters.removeToyHex();
+
+        // 结束游戏在提交报告函数里
+        $this.post_data();
+
+        $this.game_over();
+
+
+        Toast.loading({
+          forbidClick: true,
+          mask: true,
+          message: "正在生成报告...",
+          duration: 2000,
+          onClose() {
+            $this.to_report();
+          }
+        });
+      }
+      $this.executed = true;
     },
     to_report() {
       mpvue.redirectTo({
@@ -407,6 +416,10 @@ export default {
 
       bluetooth.watchingDevice($this);
       bluetooth.sendControl();
+
+      setTimeout(() => {
+        bluetooth.SendOrder("8a")
+      }, 1000)
     },
 
     // ArrayBuffer转16进度字符串示例
@@ -609,7 +622,9 @@ export default {
     }
   },
   mounted() {
-    $this._deviceId = game_store.getters.getDeviceId();
+    $this.deviceId = "";
+    $this.toy_UUID = "";
+    $this.deviceId = game_store.getters.getDeviceId();
     $this._serviceId = game_store.getters.getServiceId();
     $this._characteristicId = game_store.getters.getCharacterId();
     // setTimeout(() => {
@@ -625,6 +640,12 @@ export default {
       //打开蓝牙监听
       bluetooth.watch_bluetooth_status($this);
     }
+
+    // const $sendSmPack = setInterval(()=>{
+    //   if ($this.game_status == 1){
+    //     bluetooth.SendOrder("04")
+    //   }
+    // },1500)
   },
   created() {
     $this = this;
@@ -680,8 +701,7 @@ export default {
     console.log("小程序被销毁");
     if (!$this.is_end) {
       //停止传输数据
-      bluetooth.sendEnd();
-      wx.offBLECharacteristicValueChange();
+      // bluetooth.sendControlPause();
       //存储时间
       game_store.setters.setPlayedTime($this.played_time);
       //设置未结束游戏

+ 37 - 0
src/requests/game.js

@@ -43,3 +43,40 @@ export function gameList($params = {}) {
   $params["access_token"] = wx.getStorageSync("token");
   return fly.post("game/game-list", $params);
 }
+
+//2021年10月21日15:08:57
+//获取设备
+export function getDeviceBySn($sn) {
+  let $params = {
+    "access_token": wx.getStorageSync("token"),
+    "sn": $sn
+  }
+  return fly.post("equipment/equipment-search", $params)
+}
+
+//2021年10月22日11:11:03
+// 写入设备
+export function setDeviceInDb($this, $deviceId) {
+  let $params = $this.device_data;
+  $params["access_token"] = wx.getStorageSync("token")
+  wx.getSystemInfo({
+    success(res) {
+      switch (res.platform) {
+        case "android":
+        default:
+          $params['is_android'] = 0;
+          break;
+        case "ios":
+          $params['is_android'] = 2;
+          break;
+      }
+      if (res.platform == "ios") {
+        $params['ios_device_id'] = $deviceId
+      } else {
+        $params['device_id'] = $deviceId;
+      }
+    }
+  })
+  return fly.post("https://testadmin.shuimuai.com/equipment/factory", $params)
+}
+

+ 7 - 1
src/store/game.js

@@ -14,6 +14,9 @@ const setters = {
   setCid(characteristicId) {
     wx.setStorageSync('characteristicId', characteristicId)
   },
+  setReadCid(value) {
+    wx.setStorageSync('read_characteristicId', value)
+  },
   setGameStatus(status) {
     wx.setStorageSync('game_status', status)
   },
@@ -69,13 +72,16 @@ const getters = {
   getCharacterId() {
     return wx.getStorageSync('characteristicId')
   },
+  getReadCharacterId() {
+    return wx.getStorageSync('read_characteristicId')
+  },
   getGameStatus() {
     return wx.getStorageSync('game_status')
   },
   getGameCloseStatus() {
     return wx.getStorageSync('game_close_status')
   },
-  
+
   getToyList() {
     return wx.getStorageSync('toy_list')
   },

+ 239 - 79
src/utils/bluetooth.js

@@ -1,27 +1,66 @@
 import game_store from "../store/game";
 import ble_store from "../store/bluetooth";
 import Notify from "../../static/vant/notify/notify";
+import {setDeviceInDb} from "../requests/game";
 
 var $ff = "ff";
 var $8f = "ffffffff"
+var control_close = false
+var connect_toy = true;
+
 export default {
 
-  // 发送开启脑电数据包指令
-  sendOpen() {
-    this.WriteBufferInBle("03 00 00 00 ff");
+  // 打开大包数据
+  sendOpenBigData() {
+    this.SendOrder('ff')
+  },
+  // 关闭大包数据
+  sendCloseBigData() {
+    this.SendOrder('00')
   },
-  // 发送开启教具脑控指令
+  //获取当前连接的教具类型
+  sendGetToyType() {
+    this.SendOrder('06')
+  },
+  // 开启脑控
   sendControl() {
-    this.WriteBufferInBle("03 00 00 00 07");
+    this.SendOrder('07')
   },
-  //发送断开玩具的指令
-  sendEnd() {
+  //暂停脑控
+  sendControlPause() {
     //AA CC 03 00 00 00 09 F3
-    this.WriteBufferInBle("03 00 00 00 09");
+    this.SendOrder('08')
+  },
+  // 关闭脑控
+  sendControlClose() {
+    let that = this
+    let $intv = setInterval(() => {
+      if (!control_close) {
+        that.SendOrder('09')
+      } else {
+        clearInterval($intv)
+        control_close = false
+      }
+    }, 1000)
+  },
+  //发送一对多连接
+  sendConnectOneToMore(id) {
+    this.WriteBufferInBle(`03 00 ${id} 00 0A`);
   },
-  // 发送停止发送脑电数据包指令
-  sendPause() {
-    this.WriteBufferInBle("03 00 00 00 08");
+  //发送一对一连接
+  sendConnectOneToOne(id) {
+    this.WriteBufferInBle(`03 00 ${id} 01 0A`)
+  },
+
+  //获取教具电量
+  sendToyPower() {
+    let that = this;
+    let toy_intv = setInterval(() => {
+      if (connect_toy) {
+        that.SendOrder('8a')
+        connect_toy = false
+      }
+    }, 3000)
   },
 
   //  获取大包数据 进行绘制图表
@@ -76,16 +115,6 @@ export default {
     let $high_beta_2 = hex.substr(hex.indexOf("0418") + 36, 2);
     let $high_beta_3 = hex.substr(hex.indexOf("0418") + 38, 2);
     let $high_beta = parseInt($high_beta_1 + $high_beta_2 + $high_beta_3, 16);
-    console.log(
-      "att: " + $att,
-      "med: " + $med,
-      "delta: " + $delta,
-      "theta: " + $theta,
-      "low_alpha: " + $low_alpha,
-      "high_alpha: " + $high_alpha,
-      "low_beta: " + $low_beta,
-      "high_beta: " + $high_beta,
-    );
     let $max_num = 30000;
     return {
       att: $att,
@@ -108,22 +137,13 @@ export default {
   },
 
   //  监听蓝牙连接状态
-  watch_bluetooth_status($that) {
+  watch_bluetooth_status($this) {
     let that = this;
     // 微信自身监听低功耗蓝牙连接状态的改变事件
     wx.onBLEConnectionStateChange((res) => {
       // 该方法回调中可以用于处理连接意外断开等异常情况
       ble_store.setters.setBluetoothLinkStatus(res.connected);
       if (res.connected == false) {
-        //断开玩具连接
-        try {
-          $that.change_toy_connect_status(0);
-          //断开蓝牙连接
-          $that.change_device_status(0);
-        } catch (e) {
-          console.log("方法不存在");
-        }
-
         //判断游戏是否游戏中
         let $game_status = game_store.getters.getGameStatus();
         if ($game_status == 1) {
@@ -132,18 +152,60 @@ export default {
           Notify({
             type: 'danger',
             duration: 0,
-            message: '智脑环已断开连接,请重新扫码智脑环'
+            message: '智脑环已断开连接,正在尝试重新连接',
+            onOpened() {
+              that.reconnect(res.deviceId, $this)
+            }
           });
           // game_store.setters.setGameStatus(0);
           // 结束状态更改为1
-          game_store.setters.setGameCloseStatus(1);
-
 
         }
       }
     });
   },
 
+  //重新连接蓝牙
+  reconnect($deviceId, $this) {
+    let that = this;
+    let $serviceId = game_store.getters.getServiceId();
+    let $characteristicId = game_store.getters.getReadCharacterId();
+    //重连的次数
+    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)
+          clearInterval($rec)
+        },
+        fail(res) {
+          Notify({type: 'danger', message: `第${$connect_count}次重新连接失败`});
+          game_store.setters.setGameCloseStatus(1);
+        }
+      })
+      if ($connect_count == 3) {
+        $this.game_finished();
+      }
+
+    }, 5000)
+
+  },
+
   //获取蓝牙设备服务
   getBLEDeviceServices(deviceId) {
     const $this = this;
@@ -192,10 +254,7 @@ export default {
             game_store.setters.setServiceId(serviceId);
             game_store.setters.setCid(item.uuid);
             //打开数据帧
-            $this.sendOpen();
-            // $this.sendPause(deviceId, serviceId, item.uuid)
-            //获取玩具的值
-            // bluetooth.sendConnect($this.toy_hex, deviceId, serviceId, item.uuid)
+            $this.sendOpenBigData();
           }
 
           if (item.properties.notify || item.properties.indicate) {
@@ -205,6 +264,7 @@ export default {
               characteristicId: item.uuid,
               state: true,
             });
+            game_store.setters.setReadCid(item.uuid);
           }
         }
       },
@@ -214,16 +274,6 @@ export default {
     });
   },
 
-
-  // 发送连接玩具指令
-  sendConnect($hex) {
-    //获取最后两个字节
-    this.WriteBufferInBle("03 00 " + $hex + " 00 0a");
-  },
-  //  获取当前连接得玩具
-  getConnectedToy() {
-    this.WriteBufferInBle("03 00 00 00 06");
-  },
   // ArrayBuffer转16进度字符串示例
   ab2hex(buffer) {
     var hexArr = Array.prototype.map.call(
@@ -234,45 +284,66 @@ export default {
     );
     return hexArr.join("");
   },
-  //断开发送数据
-  shutdownSendControl() {
-    this.WriteBufferInBle("03 00 00 00 0a");
-  },
 
-  // 监听脑环是否带正
+
+  // 监听脑环数据
   watchingDevice($this) {
     const that = this;
     wx.onBLECharacteristicValueChange((characteristic) => {
       let hexStr = that.ab2hex(characteristic.value);
+      // if (hexStr.toUpperCase().indexOf("AADD") != -1) {
       console.log(hexStr);
+      // }
       let $data = that.get_big_data(hexStr);
-      // wx.getBLEDeviceRSSI({
-      //   deviceId: characteristic.deviceId,
-      //   success(res) {
-      //     $this.rssi = Math.abs(res["RSSI"]);
-      //   },
-      // });
-
-      //监听连接教具
-      if (hexStr.substr(0, 8).toLowerCase() == "aadd0a00") {
-        if ($this.toy_item["hex"]) {
-          let $hex = $this.toy_item["hex"].substr($this.toy_item["hex"].length - 2, 2);
-          if (hexStr.substr(8, 2) == $hex) {
+      let $game_status = game_store.getters.getGameStatus();
+
+      // 2021年10月20日17:18:13 判断教具 连接
+      if (hexStr.toUpperCase().indexOf("AADD0A") != -1) {
+        //没连接上教具
+        if (hexStr.toUpperCase().indexOf("AADD0A0000") != -1) {
+          $this.change_toy_connect_status(3);
+          return false;
+        }
+        let $hexAry = $this.current_hex.split(" ")
+        // 03 00 01 00 0a
+        //      [2] [3]
+        // 连接上教具
+        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);
-          } else if (hexStr.substr(8, 2) == "00") {
-            $this.change_toy_connect_status(3);
+            //连接成功后 获取一次教具电量信息
+            that.SendOrder('8a')
           }
         }
       }
 
-      //暂停脑控,切断教具连接
-      if (hexStr.substr(0, 8).toLowerCase() == "aadd0900") {
-        this.shutdownSendControl();
-      }
 
+      //2021年10月21日16:30:07
+      // 获取教具电量
+      if (hexStr.toUpperCase().indexOf("AADD8A") != -1) {//接收教具电量状态
+        let $_hexStr = hexStr.substr(6);
+        let $power = parseInt($_hexStr.substr(0, 2), 16)
+        let $voltage = parseInt($_hexStr.substr(2, 2), 16)
+        console.log("电量:" + $power)
+        console.log("电压:" + $voltage / 10)
+        $this.toy_power = $power;
+        //连接上教具的标识
+        connect_toy = true;
+
+        //2021年10月25日09:16:06
+        //获取教具UUID
+        that.SendOrder('84')
+      }
 
       //监听佩戴正确
       if (hexStr.substr(0, 6) == "555520") {
@@ -283,6 +354,67 @@ export default {
         $this.device_bg = $s1 == "00";
       }
 
+      // 2021年10月25日09:15:50
+      // 收到一次UUID就发送一次获取教具的电量
+      // 读取教具UUID
+      if (hexStr.toUpperCase().indexOf("AADD84") != -1) {//接收UUID 5个字节
+        let $_hexStr = hexStr.substr(6);
+        let $datas = $_hexStr.substr(0, 10);
+        if ($datas != "0000000000") {
+          $this.toy_UUID = $datas;
+        }
+      }
+
+
+      //2021年10月26日11:09:01
+      // 量产结束读取数据
+      if (hexStr.toUpperCase().indexOf("AADD02") != -1) {
+        //脑环型号
+        let $ring_type = hexStr.substr(10).substr(0, hexStr.substr(10).length - 2);
+        for (let $i = 0; $i < $ring_type.length; $i += 2) {
+          let $code = parseInt($ring_type.substr($i, 2), 16)
+          $this.device_data.product_model += String.fromCharCode($code)
+        }
+        that.SendOrder("01")
+
+      }
+      if (hexStr.toUpperCase().indexOf("AADD01") != -1) {
+        let _UUID = ""
+        let $_str4 = hexStr.substr(6);
+        let $UUID = $_str4.substr(0, $_str4.length - 2);
+        for (let $i = 0; $i < $UUID.length; $i += 8) {
+          let $code = $UUID.substr($i, 8);
+          _UUID += `${$code}-`
+        }
+        _UUID = _UUID.substr(0, _UUID.length - 1)
+        $this.device_data.UUID = _UUID
+        that.SendOrder("03")
+      }
+      if (hexStr.toUpperCase().indexOf("AADD03") != -1) {
+        let $_data = that.DoAnalysis(hexStr, 12);
+        $this.device_data.software_version = $_data.substr(0, 4)
+        // $this.device_data.software_date = $_data.substr(4)
+        that.SendOrder("8d")
+      }
+      if (hexStr.toUpperCase().indexOf("AADD8D") != -1) {
+        let $_str5 = hexStr.substr(10);
+        let $version_date = $_str5.substr(0, $_str5.length - 2);
+        let $_data = "";
+        for (let $i = 0; $i < $version_date.length; $i += 2) {
+          let $code = parseInt($version_date.substr($i, 2), 16)
+          $_data += String.fromCharCode($code)
+        }
+        let $version_data = $_data.substr(0, 2).split('')
+        $this.device_data.hardware_version = `${$version_data[0]}.${$version_data[1]}`
+
+        setDeviceInDb($this, $this.device.deviceId)
+      }
+
+      if (hexStr.toUpperCase().indexOf("AADD09") != -1) {
+        control_close = true;
+      }
+
+
       //  监听脑环电量
       let $power = that.get_device_elc(hexStr);
       if ($power) {
@@ -301,7 +433,6 @@ export default {
       }
 
       //游戏中模块
-      let $game_status = game_store.getters.getGameStatus();
       if ($game_status == 1 && $data) {
         try {
           if ($this.played_time > 0) {
@@ -310,14 +441,15 @@ export default {
             game_store.setters.setPlayedTime($this.played_time)
             $this.played_time_text = that.formatPlaySeconds($this.played_time);
             $this.do_datas($data);
-            // if ($this.played_time_text.indexOf(":00") != -1 || $this.played_time_text.indexOf(":30") != -1) {
-            //   $this.post_data();
-            // }
+            if ($this.played_time % 10 == 0) {
+              //读取教具电量
+              that.SendOrder('8a')
+            }
           }
           if ($this.played_time == 0) {
             $this.post_data();
             //判断是否隐藏 隐藏则不绘画
-            that.shutdownSendControl();
+            that.sendControlClose();
             let $hide_status = game_store.getters.getHideStatus();
             if (!$hide_status) {
               $this.game_finished();
@@ -385,7 +517,7 @@ export default {
     return $errmsg;
   },
   //写入buffer
-  WriteBufferInBle($hex) {
+  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();
@@ -401,7 +533,7 @@ export default {
     let $checksum = ($hex_sum ^ parseInt($8f, 16)) & parseInt($ff, 16);
 
     $hex = $hex_header + $hex + " " + $checksum.toString(16);
-    let buffer = new ArrayBuffer(8);
+    let buffer = new ArrayBuffer($buffer_len);
     let dataView = new DataView(buffer);
     $hex_ary = $hex.split(" ");
     $hex_ary.forEach(($val, $index) => {
@@ -421,5 +553,33 @@ export default {
         console.log(err);
       },
     });
-  }
+  },
+  //写入指令
+  SendOrder(id) {
+    let $hexStr = `03 00 00 00 ${id}`;
+    this.WriteBufferInBle($hexStr)
+  },
+  Send16Order(val, id) {
+    let $str = val;
+    let $str_ary = $str.split('');
+    $str = "";
+    $str_ary.forEach(($val, $index) => {
+      $str += $val.charCodeAt().toString(16) + " "
+    });
+    $str = $str.substr(0, $str.length - 1)
+    let $hexStr = "03 ff " + $str + ` ${id}`;
+    this.WriteBufferInBle($hexStr, 16)
+  },
+//解析
+  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;
+  },
 };

+ 9 - 0
src/utils/index.js

@@ -2,7 +2,16 @@ function formatNumber(n) {
   const str = n.toString();
   return str[1] ? str : `0${str}`;
 }
+export function getNowDate() {
 
+  var date = new Date();
+  const year = date.getFullYear();
+  const month = date.getMonth() + 1;
+  const day = date.getDate();
+
+
+  return `${year}${month}${day}`;
+}
 export function formatTime(date) {
   if (date.length <= 11) {
     date = date * 1000;