Jelajahi Sumber

添加了游戏中脑环重连机制

智方网络_吖荣 3 tahun lalu
induk
melakukan
077b1d2615

+ 66 - 6
src/components/device/device.vue

@@ -149,8 +149,7 @@ import Toast from "../../../static/vant/toast/toast";
 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 {
@@ -206,7 +205,38 @@ export default {
       //当前发送的hex码
       current_hex: "",
       //判断是否已经连接教具
-      toy_connected: false
+      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: {
@@ -232,6 +262,15 @@ 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({
@@ -336,7 +375,15 @@ export default {
       let $hex = $this.toy_hex = $toy["hex"].substr($toy["hex"].length - 2, 2);
       //连接玩具
       $this.current_hex = `03 00 ${$hex} 00 0a`;
+
       bluetooth.sendConnectOneToMore($hex);
+
+      //设置5秒后是否已经连接
+      setTimeout(() => {
+        if ($this.toy_connected == false) {
+          $this.change_toy_connect_status(3);
+        }
+      }, 5000)
     },
     //修改玩具连接状态
     change_toy_connect_status($status = 0) {
@@ -359,6 +406,7 @@ export default {
         game_store.setters.clearDeviceToy();
         $this.connect_toy = $status;
         $this.connect_show = false;
+        $this.device_bg = false;
         wx.closeBLEConnection({
           deviceId: $this.device.deviceId,
           success(res) {
@@ -384,6 +432,7 @@ export default {
     //开始蓝牙被发现
     startBluetoothDevicesDiscovery() {
       wx.startBluetoothDevicesDiscovery({
+        services: ["0000fff0-0000-1000-8000-00805f9b34fb", "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"],
         allowDuplicatesKey: true,
         success: (res) => {
           //2021年10月21日15:07:57  通过sn 返回deviceId
@@ -403,8 +452,10 @@ export default {
                   }
                   if ($this.device.deviceId) {
                     console.log("finded")
+                    $this.device_finded = true
                     $this.createBLEConnection()
                   } else {
+                    $this.device_finded = false
                     console.log('unfinded')
                     $this.onBluetoothDeviceFound();
                   }
@@ -454,9 +505,6 @@ export default {
               $this.device = device;
               game_store.setters.setDeviceId(device.deviceId);
               $this.createBLEConnection();
-              //录入库
-              setDeviceInDb($this.code, device.deviceId)
-
             }
           });
         });
@@ -479,6 +527,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);

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

@@ -640,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;
@@ -695,8 +701,7 @@ export default {
     console.log("小程序被销毁");
     if (!$this.is_end) {
       //停止传输数据
-      bluetooth.sendControlClose();
-      wx.offBLECharacteristicValueChange();
+      // bluetooth.sendControlPause();
       //存储时间
       game_store.setters.setPlayedTime($this.played_time);
       //设置未结束游戏

+ 20 - 15
src/requests/game.js

@@ -46,32 +46,37 @@ export function gameList($params = {}) {
 
 //2021年10月21日15:08:57
 //获取设备
-export function getDeviceBySn($sn){
+export function getDeviceBySn($sn) {
   let $params = {
-    "access_token":wx.getStorageSync("token"),
-    "sn":$sn
+    "access_token": wx.getStorageSync("token"),
+    "sn": $sn
   }
-  return fly.post("equipment/equipment-search",$params)
+  return fly.post("equipment/equipment-search", $params)
 }
 
 //2021年10月22日11:11:03
 // 写入设备
-export function setDeviceInDb($sn,$deviceId){
-  let $params = {
-    "access_token":wx.getStorageSync("token"),
-    "sn":$sn,
-    "type":1,
-  }
+export function setDeviceInDb($this, $deviceId) {
+  let $params = $this.device_data;
+  $params["access_token"] = wx.getStorageSync("token")
   wx.getSystemInfo({
-    success(res){
-      $params['is_android'] = res.platform != "ios"
-      if (res.platform == "ios"){
+    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{
+      } else {
         $params['device_id'] = $deviceId;
       }
     }
   })
-  return fly.post("https://testadmin.shuimuai.com/equipment/factory",$params)
+  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')
   },

+ 123 - 24
src/utils/bluetooth.js

@@ -1,6 +1,7 @@
 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"
@@ -8,28 +9,28 @@ export default {
 
   // 打开大包数据
   sendOpenBigData() {
-    this.WriteBufferInBle("03 00 00 00 ff");
+    this.SendOrder('ff')
   },
   // 关闭大包数据
   sendCloseBigData() {
-    this.WriteBufferInBle("03 00 00 00 00");
+    this.SendOrder('00')
   },
   //获取当前连接的教具类型
   sendGetToyType() {
-    this.WriteBufferInBle("03 00 00 00 06");
+    this.SendOrder('06')
   },
   // 开启脑控
   sendControl() {
-    this.WriteBufferInBle("03 00 00 00 07");
+    this.SendOrder('07')
   },
   //暂停脑控
   sendControlPause() {
     //AA CC 03 00 00 00 09 F3
-    this.WriteBufferInBle("03 00 00 00 08");
+    this.SendOrder('08')
   },
   // 关闭脑控
   sendControlClose() {
-    this.WriteBufferInBle("03 00 00 00 09");
+    this.SendOrder('09')
   },
   //发送一对多连接
   sendConnectOneToMore(id) {
@@ -114,22 +115,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) {
@@ -138,18 +130,69 @@ 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);
-
 
+        } else {
+          //断开玩具连接
+          try {
+            $this.change_toy_connect_status(0);
+            //断开蓝牙连接
+            $this.change_device_status(0);
+          } catch (e) {
+            console.log("方法不存在");
+          }
         }
       }
     });
   },
 
+  //重新连接蓝牙
+  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;
@@ -208,6 +251,7 @@ export default {
               characteristicId: item.uuid,
               state: true,
             });
+            game_store.setters.setReadCid(item.uuid);
           }
         }
       },
@@ -217,7 +261,6 @@ export default {
     });
   },
 
-
   // ArrayBuffer转16进度字符串示例
   ab2hex(buffer) {
     var hexArr = Array.prototype.map.call(
@@ -233,9 +276,9 @@ export default {
     const that = this;
     wx.onBLECharacteristicValueChange((characteristic) => {
       let hexStr = that.ab2hex(characteristic.value);
-      if (hexStr.toUpperCase().indexOf("AADD") != -1) {
-        console.log(hexStr);
-      }
+      // if (hexStr.toUpperCase().indexOf("AADD") != -1) {
+      console.log(hexStr);
+      // }
       let $data = that.get_big_data(hexStr);
       let $game_status = game_store.getters.getGameStatus();
 
@@ -306,6 +349,51 @@ export default {
       }
 
 
+      //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)
+      }
+
+
       //  监听脑环电量
       let $power = that.get_device_elc(hexStr);
       if ($power) {
@@ -461,5 +549,16 @@ export default {
     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;