Pārlūkot izejas kodu

微信实时日志埋点

chaooo 1 gadu atpakaļ
vecāks
revīzija
14792fbfd7

+ 14 - 13
src/components/connection/brains/connecting.vue

@@ -2,7 +2,7 @@
 import ble_store from "@/store/bluetooth";
 import Dialog from "../../../../static/vant/dialog/dialog";
 import Toast from "../../../../static/vant/toast/toast";
-import WechatLog from "@/utils/wechat_log";
+import {LOG_DEBUG, LOG_WECHAT} from "../../../utils/log";
 
 let $this;
 export default {
@@ -21,7 +21,7 @@ export default {
     $this = this;
     // 不断获取教具电量
     let connect_interval = setInterval(() => {
-      console.log("created监听到父级扫码状态", $this.status);
+      LOG_DEBUG("created监听到父级扫码状态", $this.status);
       if ($this.status*1 === 1) {
         $this.device_status = 1;
         $this.getBluetoothState();
@@ -32,7 +32,7 @@ export default {
   // watch: {
   //   'status': {
   //     handler: function($status) {
-  //       console.log("监听到父级扫码状态",$status);
+  //       LOG_DEBUG("监听到父级扫码状态",$status);
   //       if ($status*1 === 1) {
   //         $this.device_status = 1;
   //         $this.getBluetoothState();
@@ -51,10 +51,9 @@ export default {
     },
     /**
      * 获取蓝牙状态
-     *
      */
     getBluetoothState() {
-      WechatLog.info(process.env.NODE_ENV, "开始连接手机蓝牙");
+      LOG_WECHAT("开始搜索手机蓝牙");
       // 获取本机蓝牙适配器状态
       wx.getBluetoothAdapterState({
         success: function(res) {
@@ -72,7 +71,7 @@ export default {
             });
           } else {
             // 打印相关信息
-            console.log(res["errMsg"])
+            LOG_DEBUG(res["errMsg"])
             setTimeout(() => {
               Toast.fail({
                 message: res["errMsg"],
@@ -82,7 +81,7 @@ export default {
         },
         fail: function (err) {
           // 打印相关信息
-          console.log(err["errMsg"])
+          LOG_DEBUG(err["errMsg"])
           setTimeout(() => {
             Toast.fail({
               message: err["errMsg"],
@@ -128,12 +127,12 @@ export default {
               $this.bLEConnection(device.deviceId);
               //$this.device_data.deviceId = device.deviceId;
               clearTimeout($this.bleFoundTimeOut);
-              console.log("连接低功耗蓝牙设备:", JSON.stringify(device));
+              LOG_DEBUG("连接低功耗蓝牙设备:", JSON.stringify(device));
             }
           });
         });
       } catch (e) {
-        console.log("打开蓝牙error", e);
+        LOG_DEBUG("打开蓝牙error", e);
         $this.setDeviceStatus(3);
       }
     },
@@ -141,6 +140,9 @@ export default {
      * 连接低功耗蓝牙设备
      */
     bLEConnection(deviceId) {
+      $this.code = ble_store.getters.getDeviceSn();
+      // 记录日志
+      LOG_WECHAT("开始连接脑机蓝牙:", $this.code);
       // 移除搜索到新设备的事件的全部监听函数
       wx.offBluetoothDeviceFound();
       // 停止搜寻附近的蓝牙外围设备
@@ -154,7 +156,7 @@ export default {
             deviceId,
             mtu: 250,
             success(res) {
-              console.log("设置mtu成功", JSON.stringify(res));
+              LOG_DEBUG("设置mtu成功", JSON.stringify(res));
             }
           })
           ble_store.setters.setDeviceId(deviceId);
@@ -163,13 +165,12 @@ export default {
           //成功连接脑机蓝牙
           $this.setDeviceStatus(2);
           // 记录日志
-          $this.code = ble_store.getters.getDeviceSn();
-          WechatLog.info(process.env.NODE_ENV, "脑机蓝牙连接成功:", $this.code);
+          LOG_WECHAT("脑机蓝牙连接成功:", $this.code);
         },
         fail(err) {
           //连接脑机蓝牙失败
           $this.setDeviceStatus(3);
-          console.log(err);
+          LOG_DEBUG(err);
         },
       });
     },

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

@@ -2,7 +2,7 @@
 import ble_store from "@/store/bluetooth";
 import Dialog from "../../../../static/vant/dialog/dialog";
 import Toast from "../../../../static/vant/toast/toast";
-import WechatLog from "@/utils/wechat_log";
+import {LOG_DEBUG, LOG_WECHAT} from "../../../utils/log";
 
 let $this;
 export default {
@@ -69,7 +69,7 @@ export default {
         // barCode:一维码, qrCode:二维码
         scanType: ["barCode", "qrCode"],
         success: (scan) => {
-          console.log(scan.result)
+          LOG_DEBUG(scan.result)
           if (scan.result) {
             let url = decodeURIComponent(scan.result);
             let $code = "";
@@ -97,16 +97,14 @@ export default {
               });
             } else {
               ble_store.setters.setDeviceSn($code);
-              WechatLog.info(process.env.NODE_ENV, "扫码得到头环SN码:", $code);
-              console.log("扫码得到头环SN码:", $code);
+              LOG_WECHAT("扫码得到头环SN码:", $code);
               // 检查微信蓝牙权限
               this.openWechatBluetooth();
             }
           }
         },
         fail(err) {
-          console.log("扫码错误", JSON.stringify(err));
-          WechatLog.error(process.env.NODE_ENV, "扫码错误", JSON.stringify(err));
+          LOG_DEBUG("扫码错误", JSON.stringify(err));
         },
       });
     },
@@ -117,7 +115,6 @@ export default {
       // 获取系统信息
       wx.getSystemInfo({
         success(res) {
-          WechatLog.info(process.env.NODE_ENV, "获取手机系统信息:", JSON.stringify(res));
           // 判断ios
           if (res.platform === "ios") {
             // 初始化蓝牙模块。iOS上开启主机central/从机peripheral(外围设备)模式时需分别调用一次,并指定对应的 mode

+ 5 - 4
src/components/connection/index.vue

@@ -6,6 +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 {LOG_DEBUG} from "../../utils/log";
 
 let $this;
 export default {
@@ -48,7 +49,7 @@ export default {
   // watch: {
   //   'connect_toy': {
   //     handler: function($status) {
-  //       console.log("监听connect_toy状态变化",$status);
+  //       LOG_DEBUG("监听connect_toy状态变化",$status);
   //     }, immediate: true
   //   }
   // },
@@ -59,7 +60,7 @@ export default {
     getScanStatus($status) {
       // 扫码成功连接中1,失败未连接0
       $this.device_status = $status * 1;
-      console.log("接收到设备扫码连接状态:", $status);
+      LOG_DEBUG("接收到设备扫码连接状态:", $status);
     },
     /**
      * 获取设备连接状态
@@ -68,7 +69,7 @@ export default {
     setDeviceStatus($status) {
       // 重置教具连接状态
       $this.connect_toy = 0;
-      console.log("接收到设备连接状态:", $status);
+      LOG_DEBUG("接收到设备连接状态:", $status);
       if ($status * 1 === 2) {
         $this.device_status = 2;
         // 已连接
@@ -98,7 +99,7 @@ export default {
       this.toy_sn = "教具";
       if ($this.device_status*1 === 2) {
         // 关闭脑控
-        this.$connection.SendOrder("09");
+        this.$connection.SendOrder("09", "关闭脑控");
       }
     },
     // 关闭窗口

+ 9 - 10
src/pages/games/start/index.vue

@@ -174,9 +174,8 @@ import Toast from "../../../../static/vant/toast/toast";
 import {gameAddLine, gameEnd} from "../../../requests/game";
 import mpvueEcharts from "mpvue-echarts";
 import echarts from "../../../../static/echarts.min";
-import {LogInDb} from "@/requests/log";
-import WechatLog from '@/utils/wechat_log'
 import {formatPlaySeconds, get_big_data} from "../../../utils/game";
+import {LOG_DEBUG, LOG_WECHAT} from "../../../utils/log";
 
 let att_charts, med_charts, $this, $timeout;
 
@@ -305,7 +304,8 @@ export default {
     //游戏结束方法
     game_finished() {
       if (!$this.executed) {
-        LogInDb(`${$this.$connection.getNowTime()} 游戏结束`)
+        LOG_DEBUG("正在结束游戏");
+        let $code = ble_store.getters.getDeviceSn();
         // 关闭脑控
         $this.$connection.sendControlClose();
 
@@ -338,8 +338,7 @@ export default {
         // })
 
         $this.game_over();
-
-        WechatLog.info(process.env.NODE_ENV, "结束训练,game_record_id:", game_store.getters.getGameRecordId());
+        LOG_WECHAT($code, "结束训练record_id:", game_store.getters.getGameRecordId());
 
         Toast.loading({
           forbidClick: true,
@@ -361,13 +360,13 @@ export default {
           $this.attList = [];
           $this.medList = [];
           $this.ampList = [];
-          LogInDb(`${$this.$connection.getNowTime()} 生成报告`)
+          LOG_DEBUG("生成报告成功")
         },
       });
     },
     // 开始游戏
     start_game() {
-      LogInDb(`${$this.$connection.getNowTime()} 开始游戏`)
+      LOG_DEBUG("开始游戏")
       wx.setKeepScreenOn({
         keepScreenOn: true,
       });
@@ -376,7 +375,7 @@ export default {
       setTimeout(()=>{
         // 获取LED灯状态并设置
         let led_status = game_store.getters.getLED();
-        console.log("开始游戏获取LED灯状态", led_status)
+        LOG_DEBUG("开始游戏获取LED灯状态", led_status)
         if(led_status){
           $this.$connection.SendLedOrder("01");
         }else{
@@ -542,7 +541,7 @@ export default {
       //判断是否隐藏 隐藏则不绘画
       let $hide_status = game_store.getters.getHideStatus();
       if (!$hide_status) {
-        //console.log("专注放松度:",$this.att_list, $this.med_list, $this.amp_list)
+        //LOG_DEBUG("专注放松度:",$this.att_list, $this.med_list, $this.amp_list)
         if (att_charts) {
           //通过专注放松度 画图
           let $option = util.getLineOption($this.att_list, $this.med_list, $this.amp_list);
@@ -671,7 +670,7 @@ export default {
   },
   // 页面卸载时候触发的生命周期
   onUnload() {
-    console.log("训练页面被卸载!");
+    LOG_DEBUG("训练页面被卸载!");
     if (!$this.is_end) {
       //存储时间
       game_store.setters.setPlayedTime($this.played_time);

+ 0 - 25
src/requests/log.js

@@ -1,25 +0,0 @@
-import fly from "./main";
-
-
-/**
- * 记录操作进数据库
- * @param {*} content 操作内容
- */
-export function LogInDb(content) {
-  let userinfo = wx.getStorageSync("userinfo")
-  let user_id = userinfo['user_id'];
-  let access_token = wx.getStorageSync("token")
-  let params = {
-    access_token,
-    user_id,
-    content
-  }
-  console.log("记录日志:", JSON.stringify(params));
-  // fly.post("log/add-log", params).then((res) => {
-  //   if (res.data.code == 0) {
-  //     return res.data.data;
-  //   } else {
-  //     return false;
-  //   }
-  // })
-}

+ 70 - 62
src/utils/connection.js

@@ -2,7 +2,7 @@ import ble_store from "../store/bluetooth";
 import game_store from "../store/game";
 import Toast from "../../static/vant/toast/toast";
 import Notify from "../../static/vant/notify/notify";
-import WechatLog from "../utils/wechat_log";
+import {LOG_DEBUG, LOG_WECHAT, LOG_WECHAT_ERROR} from "./log";
 
 function getDeviceWriteInfo() {
   let deviceId = ble_store.getters.getDeviceId();
@@ -20,7 +20,6 @@ function isJELLYFISH() {
   return $code.indexOf("JELLYFISH") >= 0;
 }
 
-
 /**
  *  ArrayBuffer转16进度字符串示例
  * @param buffer
@@ -64,14 +63,14 @@ export default {
     wx.getBLEDeviceServices({
       deviceId,
       success: (res) => {
-        console.log("获取蓝牙设备服务service:\n", JSON.stringify(res.services));
+       LOG_DEBUG("获取蓝牙设备服务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");
+         LOG_DEBUG("第" + (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);
+           LOG_DEBUG("脑机deviceId(mac)", deviceId, "notifyServicesId:" + res.services[i].uuid);
             return;
           }
         }
@@ -95,22 +94,22 @@ export default {
       deviceId,
       serviceId,
       success: (res) => {
-        console.log("获取服务", serviceId, "的特征值:\n", JSON.stringify(res));
+       LOG_DEBUG("获取服务", 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);
+           LOG_DEBUG("第" + (i + 1) + ",该特征值可读:" + item.uuid);
           }
           if (item.properties.write) {
-            console.log("第" + (i + 1) + ",该特征值可写:" + item.uuid);
+           LOG_DEBUG("第" + (i + 1) + ",该特征值可写:" + item.uuid);
             if(item.uuid.indexOf("0002") !== -1){
               ble_store.setters.setCharacteristicWriteId(item.uuid);
               //打开数据帧 (打开大包数据)
-              that.SendOrder('ff');
+              that.SendOrder("ff", "打开数据帧");
             }
           }
           if (item.properties.notify || item.properties.indicate) {
-            console.log("第" + (i + 1) + ",该特征值可监听:" + item.uuid);
+           LOG_DEBUG("第" + (i + 1) + ",该特征值可监听:" + item.uuid);
             if(item.uuid.indexOf("0003") !== -1){
               ble_store.setters.setCharacteristicNotifyId(item.uuid);
             }
@@ -122,7 +121,7 @@ export default {
               state: true,
               success() {
                 that.notifyDatas(null);
-                console.log("init正在监听特征值:", item.uuid);
+               LOG_DEBUG("init正在监听特征值:", item.uuid);
               }
             });
           }
@@ -150,7 +149,7 @@ export default {
       } else {
         wx.setStorageSync("report_mode", 1)
       }
-      console.log("连接教具(获取连接ID):", `03 00 ${$hex} 00 0A`, JSON.stringify(toyItem));
+      LOG_DEBUG("连接教具(获取连接ID):", `03 00 ${$hex} 00 0A`, JSON.stringify(toyItem));
       // 连接教具: 03 00 ${$hex} 00 0a
       that.sendConnectOneToMore($hex);
     }
@@ -160,7 +159,7 @@ export default {
    *  连接教具(获取连接ID)
    */
   sendConnectOneToMore(id) {
-    this.WriteBufferInBle(`03 00 ${id} 00 0A`);
+    this.WriteBufferInBle(`03 00 ${id} 00 0A`, "一对多教具连接");
   },
   /**
    * 发送一对一连接
@@ -168,23 +167,24 @@ export default {
    */
   sendConnectOneToOne(id) {
     ble_store.setters.setCurrentToyId(id);
-    this.WriteBufferInBle(`03 00 ${id} 01 0A`)
+    this.WriteBufferInBle(`03 00 ${id} 01 0A`, "连接教具(使用获取的ID)")
   },
   /**
    * 连接教具(使用下发的ID)
    */
   sendConnectOneToToy(id) {
     ble_store.setters.setCurrentToyId(id);
-    this.WriteBufferInBle(`03 00 ${id} 02 0A`)
+    this.WriteBufferInBle(`03 00 ${id} 02 0A`, "连接教具(使用下发的ID)")
   },
   /**
    * 写入8位指令
    * @param id 末尾id
+   * @param $comments
    * @constructor
    */
-  SendOrder(id) {
+  SendOrder(id, $comments = "") {
     let $hexStr = `03 00 00 00 ${id}`;
-    this.WriteBufferInBle($hexStr)
+    this.WriteBufferInBle($hexStr, $comments)
   },
   /**
    * 打开或关闭LED灯 AA CC 03 00 00 ctrl EC CKS
@@ -192,7 +192,7 @@ export default {
    */
   SendLedOrder(id) {
     let $hexStr = `03 00 00 ${id} ec`;
-    this.WriteBufferInBle($hexStr)
+    this.WriteBufferInBle($hexStr, "控制脑机LED灯")
   },
 
   /**
@@ -201,7 +201,7 @@ export default {
    */
   SendMotionOrder(id) {
     let $hexStr = `03 00 00 ${id} 34`;
-    this.WriteBufferInBle($hexStr)
+    this.WriteBufferInBle($hexStr, "设置教具为无运动状态")
   },
 
   /**
@@ -217,7 +217,7 @@ export default {
       mTimeOut = `0${mTimeOut}`;
     }
     let $hexStr = `03 00 ${onVal} ${mTimeOut} d0`;
-    this.WriteBufferInBle($hexStr);
+    this.WriteBufferInBle($hexStr, "RF重连");
   },
   /**
    * 开启脑控
@@ -228,7 +228,7 @@ export default {
       title: "正在启动"
     })
     setTimeout(()=>{
-      that.SendOrder('07');
+      that.SendOrder("07", "开启脑控");
     },500)
   },
   /**
@@ -242,7 +242,7 @@ export default {
     },500);
     setTimeout(()=>{
       // 关闭脑控
-      that.SendOrder('09');
+      that.SendOrder("09", "关闭脑控");
       ble_store.setters.setCurrentToyId("00");
     },1000);
     //如果是一代脑机则发送00教具
@@ -256,10 +256,12 @@ export default {
    * todo 写入buffer
    * @param $hex
    * @param $buffer_len
+   * @param $comments
    * @constructor
    */
-  WriteBufferInBle($hex, $buffer_len = 8) {
+  WriteBufferInBle($hex, $comments = "", $buffer_len = 8) {
     let { deviceId, serviceId, characteristicWriteId } = getDeviceWriteInfo();
+    let $code = ble_store.getters.getDeviceSn();
     if (deviceId && serviceId && characteristicWriteId) {
       let that = this;
       let $hex_header = "aa cc ";
@@ -282,11 +284,10 @@ export default {
         characteristicId: characteristicWriteId,
         value: buffer,
         success: function (res) {
-          WechatLog.info(process.env.NODE_ENV, "写入指令失败:",$hex, that.getNowTime());
+          LOG_WECHAT($code, "写入指令:", $hex, $comments);
         },
         fail: function (err) {
-          console.log("写入指令失败:", $hex, err);
-          WechatLog.error(process.env.NODE_ENV, "写入指令失败:", $hex, err);
+          LOG_WECHAT_ERROR($code, "写入指令失败:", $hex, $comments, JSON.stringify(err));
         },
       });
     }
@@ -302,31 +303,36 @@ export default {
     // 监听蓝牙低功耗设备的特征值变化事件
     wx.onBLECharacteristicValueChange((characteristic) => {
       let hexStr = ab2hex(characteristic.value);
-      console.log("监听脑机数据:", hexStr);
+      let $code = ble_store.getters.getDeviceSn();
+      let $comments = "";
       // 处理打开脑控的应答
       if (hexStr.toUpperCase().indexOf("AADD07") >= 0) {
-        ble_store.setters.setBluetoothLinkStatus(true)
+        ble_store.setters.setBluetoothLinkStatus(true);
+        $comments = "打开脑控的应答";
       }
       // 收到发送UUID的应答立马发送连接教具的指令
       if (hexStr.toUpperCase().indexOf("AADD8E") >= 0) {
         let $currentToyId = ble_store.getters.getCurrentToyId();
         //发送教具连接(连接教具(使用下发的ID))
-        that.sendConnectOneToToy($currentToyId)
+        that.sendConnectOneToToy($currentToyId);
+        $comments = "连接教具(使用下发的ID)的应答";
       }
       if (hexStr.toUpperCase().indexOf("AAEE87") >= 0) {
         let $currentToyId = ble_store.getters.getCurrentToyId();
-        //获取教具电量
+        //获取教具设备编号
         if ($currentToyId !== '80') {
-          that.SendOrder('87')
+          that.SendOrder('87', "获取教具编号")
         }
+        $comments = "获取教具编号异常";
       }
       //let $game_status = game_store.getters.getGameStatus();
       //let $currentToyId = ble_store.getters.getCurrentToyId();
       // 连接页面
       if($this && $this.$options.name){
-        console.log("当前页面名称:", $this?$this.$options.name:"");
+        LOG_DEBUG("当前页面名称:", $this?$this.$options.name:"");
         // 监听脑机电量
         if (hexStr.substring(0, 8) === "55550203") {
+          $comments = "监听脑机电量";
           let $power = parseInt(hexStr.substring(8, 10), 16);
           // let $voltage = parseInt(hexStr.substring(10, 12), 16);
           // // 监听是否插入USB
@@ -340,6 +346,7 @@ export default {
         }
         // 判断教具连接
         if (hexStr.toUpperCase().indexOf("AADD0A") >= 0) {
+          $comments = "连接教具的应答";
           //没连接上教具
           if (hexStr.toUpperCase().indexOf("AADD0A0000") >= 0) {
             if(!isJELLYFISH()){
@@ -350,8 +357,7 @@ export default {
           let $baseIndex = hexStr.toUpperCase().indexOf("AADD0A");
           let $hex_index = hexStr.substring($baseIndex + 28, 30)
           let $toy_id = hexStr.substring($baseIndex + 8, 10)
-          console.log("连接", $hex_index)
-          console.log("教具", $toy_id)
+          LOG_DEBUG("连接HEX:", $hex_index, "教具ID:", $toy_id)
           // 连接上教具
           if (new RegExp("00").test($hex_index) === true) {
             if (isJELLYFISH()){
@@ -361,7 +367,7 @@ export default {
                 wx.showToast({title: "已连接到" + $this.toy_item.name });
               }
             } else {
-              console.log("一对多")
+             LOG_DEBUG("一对多")
               // 发送一对一连接 03 00 ${$toy_id} 01 0A
               that.sendConnectOneToOne($toy_id);
               ble_store.setters.setCurrentToyId($toy_id);
@@ -369,7 +375,7 @@ export default {
             }
           }
           if (new RegExp("01").test($hex_index) === true) {
-            console.log("一对一")
+            LOG_DEBUG("一对一")
             if($this.toy_item && $this.toy_item.name){
               wx.showToast({title: "已连接到" + $this.toy_item.name });
             }
@@ -379,7 +385,7 @@ export default {
             if ($toy_id !== "80") {
               // 获取一次教具名称
               setTimeout(() => {
-                that.SendOrder('87')
+                that.SendOrder('87', "获取教具编号")
               }, 3000)
               // 不断获取教具电量
               let toy_interval = setInterval(() => {
@@ -387,7 +393,7 @@ export default {
                 if($game_status !== 1){
                   clearInterval(toy_interval);
                 } else{
-                  that.SendOrder('8a');
+                  that.SendOrder('8a', "获取教具电量");
                 }
               }, 10000);
             }
@@ -404,7 +410,8 @@ export default {
           $this.toy_sn = $sn;
           //保存教具sn
           ble_store.setters.setToySn($sn);
-          console.log("获取教具名称hexStr:",hexStr,",获取教具名称$sn",$sn);
+          LOG_DEBUG("获取教具名称hexStr:", hexStr, ",获取教具名称$sn", $sn);
+          $comments = "获取教具名称";
         }
         // 获取教具电量
         if (hexStr.toUpperCase().indexOf("AADD8A") >= 0) {//接收教具电量状态
@@ -413,6 +420,7 @@ export default {
           if ($power > 0) {
             $this.toy_power = $power
           }
+          $comments = "获取教具电量的应答";
         }
         // 教具断链(连续多次到教具的命令没有响应)
         if (hexStr.toUpperCase().indexOf("AAEE70") >= 0) {
@@ -429,12 +437,15 @@ export default {
               }
             }
           })
+          $comments = "连续多次到教具的命令没有响应";
         }
 
-        // 监听佩戴正确, 当s1为 00时 数据有效
+        // 监听数据
         if (hexStr.substring(0, 6) === "555520") {
+          $comments = "监听数据";
+          // 监听佩戴正确, 当s1为 00时 数据有效
           $this.device_bg = (hexStr.substring(8, 10) === "00");
-          console.log("监听佩戴正确:", hexStr.substring(0, 10), $this.device_bg);
+          LOG_DEBUG("监听佩戴正确:", hexStr.substring(0, 10), $this.device_bg);
           //游戏中模块
           let $game_status = game_store.getters.getGameStatus();
           if ($game_status === 1) {
@@ -463,8 +474,17 @@ export default {
               }, 2000)
             }
           });
+          $comments = "脑环关机的应答";
         }
       }
+      // 日志DEBUG: 脑机电量 || 教具电量 || 数据
+      let logFlag = (hexStr.substring(0, 8) === "55550203") || (hexStr.toUpperCase().indexOf("AADD8A") >= 0) || (hexStr.substring(0, 6) === "555520");
+      if (logFlag) {
+        LOG_DEBUG($code, "电量及数据应答:", hexStr, $comments);
+      } else {
+        // 日志-推送到微信
+        LOG_WECHAT($code, "指令应答:", hexStr, $comments);
+      }
     });
   },
 
@@ -478,7 +498,7 @@ export default {
     wx.onBLEConnectionStateChange((res) => {
       // 该方法回调中可以用于处理连接意外断开等异常情况
       ble_store.setters.setBluetoothLinkStatus(res.connected);
-      console.log(`${that.getNowTime()} 监听脑机是否断连:`, res.connected);
+     LOG_DEBUG("监听脑机连接状态:", res.connected);
       if (res.connected === false) {
         //判断游戏是否游戏中
         let $game_status = game_store.getters.getGameStatus();
@@ -525,12 +545,13 @@ export default {
     let $rec = setInterval(() => {
       let $game_status = game_store.getters.getGameStatus();
       if ($game_status === 1) {
+        let $code = ble_store.getters.getDeviceSn();
         wx.createBLEConnection({
           deviceId: $deviceInfo.deviceId,
           success() {
             clearInterval($rec)
             Notify({type: 'success', message: `第${$connect_count}次重新连接成功`});
-            LogInDb(`${that.getNowTime()} 第${$connect_count}次重新连接成功`)
+            LOG_WECHAT($code, `第${$connect_count}次重新连接成功`);
             let $system = wx.getSystemInfoSync()
             if ($system.platform === 'ios') {
               that.getBLEDeviceServices($deviceInfo.deviceId)
@@ -563,8 +584,9 @@ export default {
    */
   closeConnection($this) {
     const that = this;
+    let $code = ble_store.getters.getDeviceSn();
     // 关闭脑控
-    $this.$connection.SendOrder("09");
+    that.SendOrder("09", "关闭脑控");
     game_store.setters.setGameStatus(0);
     // todo 清空链接的设备
     $this.connect_toy = 0;
@@ -573,9 +595,9 @@ export default {
     //$this.connect_status = false;
 
     // 断开教具及蓝牙连接
-    that.SendOrder("31");
+    that.SendOrder("31", "断开教具及蓝牙连接");
     setTimeout(()=>{
-      that.SendOrder("09");
+      that.SendOrder("09", "关闭脑控");
       // 移除搜索到新设备的事件的全部监听函数
       wx.offBluetoothDeviceFound();
       // 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
@@ -591,10 +613,10 @@ export default {
           });
           ble_store.setters.clearDeviceToy();
           wx.closeBluetoothAdapter();
-          console.log("断开蓝牙连接成功", deviceId);
+          LOG_WECHAT($code, "断开蓝牙连接成功", deviceId);
         },
         fail(err) {
-          console.log("断开蓝牙连接"+deviceId+"失败error:", err);
+          LOG_WECHAT_ERROR($code, "断开蓝牙连接"+deviceId+"失败error:", JSON.stringify(err));
         },
         complete() {
           //$this.device = {};
@@ -608,20 +630,6 @@ export default {
       });
     },500);
   },
-  /**
-   * 获取当前时间
-   */
-  getNowTime() {
-    const date = new Date();
-    const year = date.getFullYear();
-    const month = date.getMonth() + 1;
-    const day = date.getDate();
-    const hour = date.getHours();
-    const minutes = date.getMinutes();
-    const seconds = date.getSeconds();
-    const millSeconds = date.getMilliseconds();
-    return `${year}/${month}/${day} ${hour}:${minutes}:${seconds}.${millSeconds}`;
-  },
   connectionError(errCode) {
     if (errCode === 10000) {
       return "未初始化蓝牙适配器";

+ 59 - 0
src/utils/log.js

@@ -0,0 +1,59 @@
+import WechatLog from "@/utils/wechat_log";
+import fly from "@/requests/main";
+/**
+ * 获取当前时间
+ */
+function getNowTime(){
+  const date = new Date();
+  const year = date.getFullYear();
+  const month = date.getMonth() + 1;
+  const day = date.getDate();
+  const hour = date.getHours();
+  const minutes = date.getMinutes();
+  const seconds = date.getSeconds();
+  const millSeconds = date.getMilliseconds().toString().padStart(3,"0");
+  return `${year}/${month}/${day} ${hour}:${minutes}:${seconds} ${millSeconds}`;
+}
+
+/**
+ * 日志封装
+ */
+export function LOG_DEBUG() {
+  console.log("%cLOG_DEBUG", "color:green;", getNowTime(), ...arguments);
+}
+export function LOG_WECHAT() {
+  console.log("%cLOG_WECHAT", "color:yellow;", getNowTime(), ...arguments);
+  // 当前环境(正式/测试)
+  const mode = process.env.NODE_ENV;
+  if (process.env.NODE_ENV === "production"){
+    WechatLog.info("线上版", getNowTime(), ...arguments);
+  } else {
+    WechatLog.info("体验版", getNowTime(), ...arguments);
+  }
+}
+export function LOG_WECHAT_ERROR() {
+  console.log("%cLOG_WECHAT", "color:red;", getNowTime(), ...arguments);
+  // 当前环境(正式/测试)
+  const mode = process.env.NODE_ENV;
+  if (process.env.NODE_ENV === "production"){
+    WechatLog.error("线上版", getNowTime(), ...arguments);
+  } else {
+    WechatLog.warn("体验版", getNowTime(), ...arguments);
+  }
+}
+export function LOG_DB() {
+  console.log("%cLOG_DB", "color:red;", getNowTime(), ...arguments);
+  const args = [...arguments];
+  const content = getNowTime() + " " + args.join(" ");
+  const userinfo = wx.getStorageSync("userinfo")
+  const user_id = userinfo['user_id'];
+  const access_token = wx.getStorageSync("token")
+  let params = {
+    access_token,
+    user_id,
+    content
+  };
+  fly.post("log/add-log", params).then((res) => {
+    console.log("日志推送数据库:", JSON.stringify(res));
+  });
+}

+ 3 - 0
src/utils/wechat_log.js

@@ -1,3 +1,6 @@
+/**
+ * 调用微信实时日志相关接口。打日志的接口是wx.getRealtimeLogManager
+ */
 const wechat_log = wx.getRealtimeLogManager ? wx.getRealtimeLogManager() : null;
 module.exports = {
   debug() {