chaooo пре 1 година
родитељ
комит
1adcd65e52

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

@@ -1,4 +1,5 @@
 <script>
+import ble_store from "@/store/bluetooth";
 import game_store from "@/store/game";
 import Dialog from "../../../../static/vant/dialog/dialog";
 import Toast from "../../../../static/vant/toast/toast";
@@ -12,7 +13,7 @@ export default {
       // 设备状态 0为未连接,1:连接中,2:已连接 3:连接失败
       device_status: 0,
       // 脑机sn码
-      code: "jellyfish1234",
+      code: "AI00000000",
       bleFoundTimeOut: undefined
     }
   },
@@ -20,7 +21,7 @@ export default {
     $this = this;
   },
   mounted() {
-    $this.code = game_store.getters.getDeviceSn();
+    $this.code = ble_store.getters.getDeviceSn();
   },
   watch: {
     'status': {
@@ -107,7 +108,7 @@ export default {
       try {
         // 监听搜索到新设备的事件
         wx.onBluetoothDeviceFound((res) => {
-          $this.code = game_store.getters.getDeviceSn();
+          $this.code = ble_store.getters.getDeviceSn();
           res.devices.forEach((device) => {
             if (!device.name && !device.localName) { return; }
             if (device.localName && device.localName !== "") {
@@ -148,15 +149,14 @@ export default {
               console.log("设置mtu成功", JSON.stringify(res));
             }
           })
-          // 记录日志
-          WechatLog.info("脑机蓝牙连接成功:", $this.code);
-
           $this.$bluetooth.current_device_sn = $this.code;
-          game_store.setters.setDeviceId(deviceId);
+          ble_store.setters.setDeviceId(deviceId);
           // 获取蓝牙设备服务
-          $this.$bluetooth.getBLEDeviceServices(deviceId);
+          $this.$connection.getBLEDeviceServices(deviceId);
           //成功连接脑机蓝牙
           $this.setDeviceStatus(2);
+          // 记录日志
+          WechatLog.info("脑机蓝牙连接成功:", $this.code);
         },
         fail(err) {
           console.log(err);

+ 9 - 26
src/components/connection/brains/scan.vue

@@ -1,5 +1,5 @@
 <script>
-import game_store from "@/store/game";
+import ble_store from "@/store/bluetooth";
 import Dialog from "../../../../static/vant/dialog/dialog";
 import Toast from "../../../../static/vant/toast/toast";
 
@@ -14,8 +14,6 @@ export default {
      * 扫描二维码连接脑机
      */
     openScan() {
-      // 打开蓝牙扫描 重置游戏状态
-      game_store.setters.setGameStatus(0);
       // 微信异步获取系统信息
       wx.getSystemInfoAsync({
         success(res) {
@@ -70,36 +68,21 @@ export default {
         // barCode:一维码, qrCode:二维码
         scanType: ["barCode", "qrCode"],
         success: (scan) => {
+          console.log(scan.result)
           if (scan.result) {
             let url = decodeURIComponent(scan.result);
             let $code = "";
-            // 二维码
             if (scan.scanType === "QR_CODE") {
-              if (url.indexOf("AI") !== -1) {
-                $code = url.substr(url.indexOf("AI"));
-              } else if (url.toUpperCase().indexOf("JELLYFISH")) {
-                $code = url.substr(url.toUpperCase().indexOf("JELLYFISH"));
-              }
+              // 二维码
+              $code = url.substring(url.indexOf("AI"));
             } else {
               // 一维码
               $code = scan.result.toUpperCase();
             }
-            game_store.setters.setDeviceSn($code);
-            // 判断是新还是旧
-            game_store.setters.setIsNew($code.indexOf("AI") !== -1);
+            ble_store.setters.setDeviceSn($code);
             console.log("扫码得到头环SN码:", $code);
-            // 标识值
-            // $this.code = $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();
-            this.openSystemBluetooth();
+            // 检查微信蓝牙权限
+            this.openWechatBluetooth();
           }
         },
         fail(err) {
@@ -113,9 +96,9 @@ export default {
       });
     },
     /**
-     * 检查系统蓝牙权限
+     * 检查微信蓝牙权限
      */
-    openSystemBluetooth: function () {
+    openWechatBluetooth: function () {
       // 获取系统信息
       wx.getSystemInfo({
         success(res) {

+ 20 - 12
src/components/connection/index.vue

@@ -1,4 +1,5 @@
 <script>
+import ble_store from "@/store/bluetooth";
 import game_store from "@/store/game";
 import ConnectionScan from "@/components/connection/brains/scan";
 import Connecting from "@/components/connection/brains/connecting";
@@ -76,7 +77,7 @@ export default {
       console.log("接收到设备连接状态:", $status);
       if ($status * 1 === 2) {
         let $checkServices = setInterval(() => {
-          let $serviceId = game_store.getters.getServiceId();
+          let $serviceId = ble_store.getters.getServiceId();
           if ($serviceId) {
             clearInterval($checkServices);
             // 监听数据
@@ -100,7 +101,7 @@ export default {
           // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
           wx.stopBluetoothDevicesDiscovery();
           $this.$bluetooth.SendOrder("09");
-          let deviceId = game_store.getters.getDeviceId();
+          let deviceId = ble_store.getters.getDeviceId();
           //断开蓝牙连接
           wx.closeBLEConnection({
             deviceId: deviceId,
@@ -145,15 +146,16 @@ export default {
       $this.toy_item = game_store.getters.getToyItem();
       if($this.toy_item && $this.toy_item.id > 0) {
         $this.setToyStatus(1);
-        let $hex = ($this.toy_hex = $this.toy_item["hex"].substr($this.toy_item["hex"].length - 2, 2));
-        if ($hex === "80") {
-          wx.setStorageSync("report_mode", 2)
-        } else {
-          wx.setStorageSync("report_mode", 1)
-        }
-        console.log("连接教具:", `03 00 ${$hex} 00 0a`, JSON.stringify($this.toy_item));
-        // 连接教具: 03 00 ${$hex} 00 0a
-        $this.$bluetooth.sendConnectOneToMore($hex);
+        $this.$connection.sendToyConnection($this.toy_item);
+        // let $hex = ($this.toy_hex = $this.toy_item["hex"].substr($this.toy_item["hex"].length - 2, 2));
+        // if ($hex === "80") {
+        //   wx.setStorageSync("report_mode", 2)
+        // } else {
+        //   wx.setStorageSync("report_mode", 1)
+        // }
+        // console.log("连接教具:", `03 00 ${$hex} 00 0a`, JSON.stringify($this.toy_item));
+        // // 连接教具: 03 00 ${$hex} 00 0a
+        // $this.$bluetooth.sendConnectOneToMore($hex);
         //2022-5-25 09:07:59 设置10秒后是否已经连接
         setTimeout(() => {
           if ($this.toy_connected === false) {
@@ -175,13 +177,19 @@ export default {
     },
   },
   onShow() {
+    // 未连接蓝牙状态
+    if($this.device_status*1 === 0){
+      // 打开蓝牙扫描 重置游戏状态
+      game_store.setters.setGameStatus(0);
+    }
     //判断是否游戏中
     let $game_status = game_store.getters.getGameStatus();
     // 游戏过程中关闭脑机状态
     let $game_close_status = game_store.getters.getGameCloseStatus();
 
     if ($game_status === 3) {
-      let $ble_status = wx.getStorageSync("ble_link_status");
+      // getBluetoothLinkStatus
+      let $ble_status = ble_store.getters.getBluetoothLinkStatus();
       if ($ble_status === false) {
         //断开蓝牙连接
         $this.setDeviceStatus(0);

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

@@ -63,7 +63,7 @@ export default {
         <van-row gutter="14" class="toy_list_content">
           <van-col v-for="(toy, index) in toy_list" :key="index" class="text-center">
             <div v-if="toy" class="toy_item flex flex-direction justify-center align-center" @click="chooseToy(index)"
-              :class=" toy_action == toy.id ? 'toy_item_action_bg' : 'toy_item_normal_bg'">
+              :class=" toy_action === toy.id ? 'toy_item_action_bg' : 'toy_item_normal_bg'">
               <img :src="toy.img" alt="" class="toy_img"/>
               <text class="toy_text padding-top">{{ toy.name }}</text>
             </div>

+ 2 - 0
src/main.js

@@ -2,6 +2,7 @@ import Vue from 'vue'
 import App from './App'
 import Fly from 'flyio/dist/npm/wx'
 import store from '@/store/index'
+import connection from "@/utils/connection";
 import bluetooth from "@/utils/bluetooth";
 
 
@@ -17,6 +18,7 @@ fly.config.headers = {
 
 Vue.prototype.$fly = fly
 Vue.prototype.$store = store
+Vue.prototype.$connection = connection
 Vue.prototype.$bluetooth = bluetooth
 Vue.config.productionTip = false
 App.mpType = 'app'

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

@@ -63,9 +63,9 @@ export default {
     }
   },
   onLoad() {
-    // if (process.env.NODE_ENV == "development") {
-    //   wx.setStorageSync('token', "WxN3rgbWyVpjyBhi4uT6mZmwajZ3dFlm");
-    // }
+    if (process.env.NODE_ENV == "development") {
+      wx.setStorageSync('token', "WxN3rgbWyVpjyBhi4uT6mZmwajZ3dFlm");
+    }
     if (game_store.getters.getGameStatus() * 1 === 1) {
       Dialog.alert({
         title: "系统提示",

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

@@ -42,7 +42,7 @@
             <text class="text-default">脑机电量</text>
           </div>
         </van-col>
-        <van-col span="8" v-if="is_new">
+        <van-col span="8">
           <div class="flex flex-direction align-center justify-center">
             <view class="elc_power_container">
               <img src="https://img.shuimuai.com/web/dianchi_3.png" alt="" :style="{ width: toy_power + '%' }" class="device_elc" />
@@ -281,7 +281,6 @@ export default {
       device_voltage: 0,
 
       toy_UUID: "",
-      is_new: false,
 
 
       save_index: [
@@ -602,7 +601,7 @@ export default {
     $this.executed = false;
     $this.deviceId = "";
     $this.toy_UUID = "";
-    $this.deviceId = game_store.getters.getDeviceId();
+    $this.deviceId = ble_store.getters.getDeviceId();
     // setTimeout(() => {
     $this.game_status = game_store.getters.getGameStatus();
     // }, 1000)
@@ -616,8 +615,6 @@ export default {
       //打开蓝牙监听
       $this.$bluetooth.watchBLEstatus($this);
     }
-
-    $this.is_new = game_store.getters.getIsNew()
   },
   created() {
     $this = this;

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

@@ -48,6 +48,7 @@
 </template>
 <script>
 import {getDeviceBySn, EditFirmwareVersion} from "../../../requests/game";
+import ble_store from "@/store/bluetooth";
 import game_store from "@/store/game";
 import Toast from "../../../../static/vant/toast/toast";
 
@@ -273,10 +274,10 @@ export default {
               console.log(err)
             }
           })
-          game_store.setters.setDeviceId(deviceId);
+          ble_store.setters.setDeviceId(deviceId);
           $this.$bluetooth.getBLEDeviceServices(deviceId);
           let $checkServices = setInterval(() => {
-            let $serviceId = game_store.getters.getServiceId();
+            let $serviceId = ble_store.getters.getServiceId();
             if ($serviceId) {
               clearInterval($checkServices);
               $this.$bluetooth.openNotify($this);

+ 25 - 1
src/store/bluetooth.js

@@ -1,13 +1,37 @@
 const getters = {
   getBluetoothLinkStatus() {
     return wx.getStorageSync("ble_link_status")
+  },
+  getDeviceSn() {
+    return wx.getStorageSync('deviceSn')
+  },
+  getDeviceId() {
+    return wx.getStorageSync('deviceId')
+  },
+  getServiceId() {
+    return wx.getStorageSync('serviceId')
+  },
+  getCharacteristicId(){
+    return wx.getStorageSync('characteristicId')
   }
 }
 
 const setters = {
   setBluetoothLinkStatus($bool) {
-    wx.setStorageSync('ble_link_status', $bool)
+    wx.setStorageSync("ble_link_status", $bool)
   },
+  setDeviceSn(deviceSn) {
+    wx.setStorageSync('deviceSn', deviceSn)
+  },
+  setDeviceId(deviceId) {
+    wx.setStorageSync('deviceId', deviceId)
+  },
+  setServiceId(serviceId) {
+    wx.setStorageSync('serviceId', serviceId)
+  },
+  setCharacteristicId(characteristicId){
+    wx.setStorageSync('characteristicId', characteristicId)
+  }
 }
 
 export default {

+ 11 - 25
src/store/game.js

@@ -7,15 +7,8 @@ const setters = {
     // wx.removeStorageSync('characteristicId')
   },
   //setter模块
-  setDeviceId(deviceId) {
-    wx.setStorageSync('deviceId', deviceId)
-  },
-  setDeviceSn(deviceSn) {
-    wx.setStorageSync('deviceSn', deviceSn)
-  },
-  setServiceId(serviceId) {
-    wx.setStorageSync('serviceId', serviceId)
-  },
+
+
   // 游戏状态: 0未开始 1游戏中 3游戏结束
   setGameStatus(status) {
     wx.setStorageSync('game_status', status)
@@ -58,9 +51,9 @@ const setters = {
   setGameAttMedDatas($param) {
     wx.setStorageSync('game_data', $param)
   },
-  setIsNew($param) {
-    wx.setStorageSync('is_new', $param)
-  },
+  // setIsNew($param) {
+  //   wx.setStorageSync('is_new', $param)
+  // },
   // 脑机LED灯
   setLED(bool) {
     wx.setStorageSync('led_status', bool)
@@ -71,15 +64,8 @@ const setters = {
 }
 
 const getters = {
-  getDeviceId() {
-    return wx.getStorageSync('deviceId')
-  },
-  getDeviceSn() {
-    return wx.getStorageSync('deviceSn')
-  },
-  getServiceId() {
-    return wx.getStorageSync('serviceId')
-  },
+
+
   getGameStatus() {
     return wx.getStorageSync('game_status')
   },
@@ -119,10 +105,10 @@ const getters = {
   getGameAttMedDatas() {
     return wx.getStorageSync('game_data')
   },
-  //记录游戏数据
-  getIsNew() {
-    return wx.getStorageSync('is_new')
-  },
+  // //记录游戏数据
+  // getIsNew() {
+  //   return wx.getStorageSync('is_new')
+  // },
   // 脑机LED灯
   getLED() {
     return wx.getStorageSync('led_status')

+ 116 - 113
src/utils/bluetooth.js

@@ -28,7 +28,7 @@ var logTime = "";
 
 var current_hex = "";
 
-var is_new = game_store.getters.getIsNew();
+//var is_new = game_store.getters.getIsNew();
 
 //2021年11月10日14:59:38
 // 0为旧 1为新
@@ -49,9 +49,9 @@ var charateristics = [
 
 function getServicesAndCharateristc() {
   //获取当前设备名称
-  // let $brainSn = game_store.getters.getDeviceSn();
-  let $deviceId = game_store.getters.getDeviceId();
-  let $serviceId = game_store.getters.getServiceId();
+  // let $brainSn = ble_store.getters.getDeviceSn();
+  let $deviceId = ble_store.getters.getDeviceId();
+  let $serviceId = ble_store.getters.getServiceId();
   let $index = services.indexOf($serviceId.toUpperCase())
   // let $index = $brainSn.toUpperCase().indexOf("JELLYFISH") != -1 ? 0 : 1;
   return {
@@ -136,27 +136,31 @@ export default {
       that.SendOrder('09');
       //清空当前数据
       that.clearLocalDatas();
+      //设置打开脑控为false
+      FlagOpenControl = false;
+      //清空当前数据
+      that.clearLocalDatas()
     },1000);
     // setTimeout(()=>{
     //   // 断开教具及蓝牙连接
     //   that.SendOrder("31");
     // },1500);
     // 兼容二代脑机,不能退出循环
-    if (!is_new) {
-      control_close = false;
-      control_close_intv = setInterval(() => {
-        if (!control_close) {
-          //如果是jellyfish则发送00教具
-            that.sendConnectOneToMore('00')
-        } else {
-          //设置打开脑控为false
-          FlagOpenControl = false;
-          clearInterval(control_close_intv)
-          //清空当前数据
-          that.clearLocalDatas()
-        }
-      }, 2000)
-    }
+    // if (!is_new) {
+    //   control_close = false;
+    //   control_close_intv = setInterval(() => {
+    //     if (!control_close) {
+    //       //如果是jellyfish则发送00教具
+    //         that.sendConnectOneToMore('00')
+    //     } else {
+    //       //设置打开脑控为false
+    //       FlagOpenControl = false;
+    //       clearInterval(control_close_intv)
+    //       //清空当前数据
+    //       that.clearLocalDatas()
+    //     }
+    //   }, 2000)
+    // }
   },
   /**
    *  todo:发送一对多连接
@@ -177,7 +181,7 @@ export default {
    */
   sendToyPower() {
     let that = this;
-    if (is_new) {
+    // if (is_new) {
       let $connect_false_count = 0;
       let toy_intv = setInterval(() => {
         let $game_status = game_store.getters.getGameStatus();
@@ -189,9 +193,9 @@ export default {
           }
         }
       }, 5000)
-    } else {
-      console.log("旧脑机不支持获取教具电量")
-    }
+    // } else {
+    //   console.log("旧脑机不支持获取教具电量")
+    // }
   },
 
   /**
@@ -338,84 +342,83 @@ export default {
 
   },
 
-  /**
-   * todo 获取蓝牙设备服务
-   * @param deviceId
-   */
-  getBLEDeviceServices(deviceId) {
-    const that = 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);
-            that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
-            game_store.setters.setServiceId(res.services[i].uuid)
-            is_new = game_store.getters.getIsNew()
-            return;
-          }
-        }
-      },
-      fail(res) {
-        let deviceId = wx.getStorageSync('deviceId');
-        //断开蓝牙连接
-        wx.closeBLEConnection({
-          deviceId: deviceId
-        });
-      },
-    });
-  },
-
-  /**
-   * todo 获取蓝牙设备某个服务中所有特征值
-   */
-  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];
-          let writeState = null;
-          if (serviceId.indexOf("0001") != -1) {
-            writeState = item.properties.write && item.uuid.indexOf("0002") != -1;
-          } else {
-            writeState = item.properties.write;
-          }
-          if (writeState) {
-            // if (item.properties.write) {
-            $this.deviceId = deviceId;
-            $this.serviceId = serviceId;
-            $this.cid = item.uuid;
-            //打开数据帧
-            $this.sendOpenBigData();
-          }
-
-          if (item.properties.notify || item.properties.indicate) {
-            wx.notifyBLECharacteristicValueChange({
-              deviceId,
-              serviceId,
-              characteristicId: item.uuid,
-              state: true,
-            });
-          }
-        }
-      },
-      fail(res) {
-        let deviceId = wx.getStorageSync('deviceId');
-        //断开蓝牙连接
-        wx.closeBLEConnection({
-          deviceId: deviceId
-        });
-      },
-    });
-  },
+  // /**
+  //  * todo 获取蓝牙设备服务
+  //  * @param deviceId
+  //  */
+  // getBLEDeviceServices(deviceId) {
+  //   const that = this;
+  //   wx.getBLEDeviceServices({
+  //     deviceId,
+  //     success: (res) => {
+  //       console.log("获取蓝牙设备服务service:\n", JSON.stringify(res.services));
+  //       for (let i = 0; i < res.services.length; i++) {
+  //         console.log("第" + (i + 1) + "个UUID:" + res.services[i].uuid + "\n");
+  //         if (res.services[i].uuid.indexOf('6E') !== -1 || res.services[i].uuid.indexOf('0000FFF0') !== -1) {
+  //           console.log("notifyServicesId:" + res.services[i].uuid);
+  //           that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
+  //           game_store.setters.setServiceId(res.services[i].uuid);
+  //           return;
+  //         }
+  //       }
+  //     },
+  //     fail(res) {
+  //       let deviceId = wx.getStorageSync('deviceId');
+  //       //断开蓝牙连接
+  //       wx.closeBLEConnection({
+  //         deviceId: deviceId
+  //       });
+  //     },
+  //   });
+  // },
+
+  // /**
+  //  * todo 获取蓝牙设备某个服务中所有特征值
+  //  */
+  // 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];
+  //         let writeState = null;
+  //         if (serviceId.indexOf("0001") != -1) {
+  //           writeState = item.properties.write && item.uuid.indexOf("0002") != -1;
+  //         } else {
+  //           writeState = item.properties.write;
+  //         }
+  //         if (writeState) {
+  //           // if (item.properties.write) {
+  //           $this.deviceId = deviceId;
+  //           $this.serviceId = serviceId;
+  //           $this.cid = item.uuid;
+  //           //打开数据帧
+  //           $this.sendOpenBigData();
+  //         }
+  //
+  //         if (item.properties.notify || item.properties.indicate) {
+  //           wx.notifyBLECharacteristicValueChange({
+  //             deviceId,
+  //             serviceId,
+  //             characteristicId: item.uuid,
+  //             state: true,
+  //           });
+  //         }
+  //       }
+  //     },
+  //     fail(res) {
+  //       let deviceId = wx.getStorageSync('deviceId');
+  //       //断开蓝牙连接
+  //       wx.closeBLEConnection({
+  //         deviceId: deviceId
+  //       });
+  //     },
+  //   });
+  // },
   // 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征。
   openNotify($this) {
     let that = this;
@@ -454,7 +457,7 @@ export default {
    */
   notifyDatas($this) {
     const that = this;
-    let DeviceId = game_store.getters.getDeviceId();
+    let DeviceId = ble_store.getters.getDeviceId();
     // 监听蓝牙低功耗设备的特征值变化事件
     wx.onBLECharacteristicValueChange((characteristic) => {
       // 获取脑机信号值
@@ -512,9 +515,9 @@ export default {
       if (hexStr.toUpperCase().indexOf("AADD0A") != -1) {
         //没连接上教具
         if (hexStr.toUpperCase().indexOf("AADD0A0000") != -1) {
-          if (is_new) {
+          //if (is_new) {
             $this.connect_toy = 3;
-          }
+          //}
           return false;
         }
         let $mHexStrIndex = hexStr.toUpperCase().indexOf("AADD0A");
@@ -524,18 +527,18 @@ export default {
         console.log("教具", $toy_id)
         // 连接上教具
         if (new RegExp("00").test($hex_index) == true) {
-          if (is_new) {
+          //if (is_new) {
             that.sendConnectOneToOne($toy_id)
             $this.current_hex = `03 00 ${$toy_id} 01 0A`
             console.log("一对多")
-          } else {
-            $this.current_hex = "";
-            wx.showToast({
-              title: "已连接到" + $this.toy_item.name
-            });
-            $this.toy_connected = true;
-            $this.connect_toy = 2;
-          }
+          // } else {
+          //   $this.current_hex = "";
+          //   wx.showToast({
+          //     title: "已连接到" + $this.toy_item.name
+          //   });
+          //   $this.toy_connected = true;
+          //   $this.connect_toy = 2;
+          // }
         }
         if (new RegExp("01").test($hex_index) == true) {
           console.log("一对一")

+ 139 - 0
src/utils/connection.js

@@ -0,0 +1,139 @@
+import ble_store from "../store/bluetooth";
+
+export default {
+  /**
+   * 获取蓝牙设备服务
+   * @param deviceId 脑机mac
+   */
+  getBLEDeviceServices(deviceId) {
+    const that = this;
+    wx.getBLEDeviceServices({
+      deviceId,
+      success: (res) => {
+        console.log("获取蓝牙设备服务service:\n", JSON.stringify(res.services));
+        for (let i = 0; i < res.services.length; i++) {
+          console.log("第" + (i + 1) + "个UUID:" + res.services[i].uuid + "\n");
+          if (res.services[i].uuid.indexOf('6E') !== -1 || res.services[i].uuid.indexOf('0000FFF0') !== -1) {
+            // 获取蓝牙设备某个服务中所有特征值
+            that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
+            ble_store.setters.setServiceId(res.services[i].uuid);
+            console.log("脑机deviceId(mac)", deviceId, "notifyServicesId:" + res.services[i].uuid);
+            return;
+          }
+        }
+      },
+      fail(res) {
+        let deviceId = wx.getStorageSync('deviceId');
+        //断开蓝牙连接
+        wx.closeBLEConnection({
+          deviceId: deviceId
+        });
+      },
+    });
+  },
+
+  /**
+   * 获取蓝牙设备某个服务中所有特征值
+   */
+  getBLEDeviceCharacteristics(deviceId, serviceId) {
+    wx.getBLEDeviceCharacteristics({
+      deviceId,
+      serviceId,
+      success: (res) => {
+        console.log("获取服务", serviceId, "的特征值:\n", JSON.stringify(res));
+        for (let i = 0; i < res.characteristics.length; i++) {
+          let item = res.characteristics[i]
+          if (item.properties.read) {
+            console.log("第" + (i + 1) + ",该特征值可读:" + item.uuid);
+          }
+          if (item.properties.write) {
+            console.log("第" + (i + 1) + ",该特征值可写:" + item.uuid);
+            if(item.uuid.indexOf("0002") !== -1){
+              ble_store.setters.setCharacteristicId(item.uuid);
+            }
+          }
+          if (item.properties.notify || item.properties.indicate) {
+            console.log("第" + (i + 1) + ",该特征值可监听:" + item.uuid);
+            // 必须先启用 wx.notifyBLECharacteristicValueChange 才能监听到设备 onBLECharacteristicValueChange 的事件
+            wx.notifyBLECharacteristicValueChange({
+              deviceId,
+              serviceId,
+              characteristicId: item.uuid,
+              state: true,
+            });
+          }
+        }
+      },
+      fail(res) {
+        let deviceId = wx.getStorageSync('deviceId');
+        //断开蓝牙连接
+        wx.closeBLEConnection({
+          deviceId: deviceId
+        });
+      },
+    });
+  },
+
+  /**
+   * 脑机连接教具
+   */
+  sendToyConnection(toyItem) {
+    if(toyItem && toyItem["hex"]) {
+      let $hex = $this.toy_item["hex"].substr($this.toy_item["hex"].length - 2, 2);
+      if ($hex === "80") {
+        wx.setStorageSync("report_mode", 2)
+      } else {
+        wx.setStorageSync("report_mode", 1)
+      }
+      console.log("连接教具:", `03 00 ${$hex} 00 0A`, JSON.stringify($this.toy_item));
+      // 连接教具: 03 00 ${$hex} 00 0a
+      $this.$bluetooth.sendConnectOneToMore($hex);
+    }
+  },
+  /**
+   *  发送一对多连接
+   */
+  sendConnectOneToMore(id) {
+    this.WriteBufferInBle(`03 00 ${id} 00 0A`);
+  },
+  /**
+   * todo 写入buffer
+   * @param $hex
+   * @param $buffer_len
+   * @constructor
+   */
+  WriteBufferInBle($hex, $buffer_len = 8) {
+    let deviceId = ble_store.getters.getDeviceId();
+    let serviceId = ble_store.getters.getServiceId();
+    let characteristicId = ble_store.getters.getCharacteristicId()
+    if (deviceId && serviceId && characteristicId) {
+      let that = this;
+      let $hex_header = "aa cc ";
+      let $hex_sum = 0;
+      let $hex_ary = $hex.split(" ");
+      $hex_ary.forEach(($val, $index) => {
+        $hex_sum += parseInt($val, 16);
+      })
+      let $checksum = ($hex_sum ^ parseInt("ffffffff", 16)) & parseInt("ff", 16);
+      $hex = $hex_header + $hex + " " + ("00" + $checksum.toString(16)).substr(-2, 2);
+      let buffer = new ArrayBuffer($buffer_len);
+      let dataView = new DataView(buffer);
+      $hex_ary = $hex.split(" ");
+      $hex_ary.forEach(($val, $index) => {
+        dataView.setUint8($index, parseInt($val, 16))
+      })
+      wx.writeBLECharacteristicValue({
+        deviceId: deviceId,
+        serviceId: serviceId,
+        characteristicId: characteristicId,
+        value: buffer,
+        success: function (res) {
+          console.log($hex + "写入成功,时间:" + that.getNowTime())
+        },
+        fail: function (err) {
+          console.log($hex + "写入失败", err);
+        },
+      });
+    }
+  },
+};