Преглед изворни кода

feature:新增OTA的wifi界面,修改OTA的URL指令

zeng.chen пре 6 месеци
родитељ
комит
fa7d4d46ed

+ 58 - 25
devices/ble_manager.js

@@ -51,6 +51,30 @@ class bleManager {
         getCurrentPages()[0].closeBlueResetOffline(false, true);
       }
     })
+    if (that.isAvailable) {
+      return;
+    }
+    wx.openBluetoothAdapter({
+      success: function (res) {
+        that.isAvailable = res.available;
+      },
+      fail: function (res) {
+        that.isAvailable = res.available;
+        console.log("打开蓝牙成功2", res);
+        // wx.showModal({
+        //   title: '提示',
+        //   content: '请检查手机蓝牙是否打开',
+        //   showCancel: false,
+        //   success: function (res) { }
+        // });
+
+        // that.doStartScaning = false;
+        // that.requestBlueTime = that.getCurrentMills();
+        // if (boolean != null) {
+        //   boolean(false);
+        // }
+      }
+    })
   }
 
   ///监听搜索设备列表
@@ -284,12 +308,14 @@ class bleManager {
     const connectBleRoot = route_constant.connectBleRoot;
     var lastPageRoute = route_util.getLastPageRoute();
     if (lastPageRoute != indexRoot && lastPageRoute != connectBleRoot) {
+      console.log("搜索蓝牙设备失败,请返回首页0");
       return;
     }
 
     ///蓝牙连接 做限制
     if (lastPageRoute == indexRoot) {
       if (that.doStartScaning == true) {
+        console.log("搜索蓝牙设备失败,请返回首页1");
         return;
       }
     }
@@ -311,36 +337,40 @@ class bleManager {
       that.doStartScaning = false;
       return;
     }
-
-    wx.openBluetoothAdapter({
-      success: function (res) {
-        wx.stopBluetoothDevicesDiscovery({
-          success: (res) => {
-            that.search(connectWillDevice, boolean, callBackConnect);
-          },
-          fail: (err) => {
-            that.doStartScaning = false;
-            that.requestBlueTime = that.getCurrentMills();
-            if (boolean != null) {
-              boolean(false);
-            }
-          }
-        });
+    wx.stopBluetoothDevicesDiscovery({
+      success: (res) => {
+        console.log("停止搜索设备0", res);
+        that.search(connectWillDevice, boolean, callBackConnect);
       },
-      fail: function (res) {
-        // wx.showModal({
-        //   title: '提示',
-        //   content: '请检查手机蓝牙是否打开',
-        //   showCancel: false,
-        //   success: function (res) {}
-        // });
+      fail: (err) => {
+        console.log("停止搜索设备1", err);
         that.doStartScaning = false;
         that.requestBlueTime = that.getCurrentMills();
         if (boolean != null) {
           boolean(false);
         }
       }
-    })
+    });
+
+    // wx.openBluetoothAdapter({
+    //   success: function (res) {
+
+    //   },
+    //   fail: function (res) {
+    //     console.log("打开蓝牙成功2", res);
+    //     // wx.showModal({
+    //     //   title: '提示',
+    //     //   content: '请检查手机蓝牙是否打开',
+    //     //   showCancel: false,
+    //     //   success: function (res) { }
+    //     // });
+    //     that.doStartScaning = false;
+    //     that.requestBlueTime = that.getCurrentMills();
+    //     if (boolean != null) {
+    //       boolean(false);
+    //     }
+    //   }
+    // })
   }
 
   search(connectWillDevice, boolean, callBackConnect) {
@@ -348,6 +378,7 @@ class bleManager {
     wx.startBluetoothDevicesDiscovery({
       allowDuplicatesKey: true,
       success: function (res) {
+        console.log("开始搜索设备", res);
         that.getConnectedDevices();
 
         that.doStartScaning = false;
@@ -360,6 +391,8 @@ class bleManager {
         that.compareList = [];
       },
       fail(err) {
+        console.log("开始搜索设备失败", res);
+
         that.doStartScaning = false;
         that.requestBlueTime = that.getCurrentMills();
         if (boolean != null) {
@@ -471,8 +504,8 @@ class bleManager {
         dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
       });
       // }
-
-      console.log('开始发送数据:', buffer);
+      let logData = new Uint8Array(buffer);
+      console.log('开始发送数据:', logData);
       wx.writeBLECharacteristicValue({
         deviceId: that.publicDevice.deviceId,
         serviceId: that.publicDevice.serviceId,

+ 10 - 7
devices/bluetooth/bt_cmd.js

@@ -183,6 +183,7 @@ class BtCmd {
     static stringToUint8Array(text) {
         // return [0x73, 0x6d, 0x61, 0x72, 0x74, 0x5f, 0x41, 0x32, 0x46]
         // return [115, 109, 97, 114, 116, 95, 65, 50, 70]
+        // return [115, 109, 97, 114, 116, 95, 65, 50, 70]
         // 73 6D 61 72 74 5F 41 32 46
         let code = Array.from(text).map(char => char.charCodeAt(0));
         console.log("stringToUint8Array", code)
@@ -262,12 +263,13 @@ class BtCmd {
     static otaCmd(value) {
         return this._build(CmdBase.heiJiaoOta, [value]);
     }
-    //
-    static wifiUrl(value) {
-        return this._build(CmdBase.heiJiaoOta, [value]);
+    // 发送OTA的URL
+    static otaUrl(value) {
+        return this._build(CmdBase.heiJiaoOtaData, [value]);
     }
+    //暂时没用了
     static otaData(value) {
-        return this._build(CmdBase.heiJiaoOtaData, [value], true, false);
+        return this._build(CmdBase.heiJiaoOta, [value], true, false);
     }
     /// 获取设备型号指令
     static getClientType() {
@@ -287,7 +289,7 @@ class BtCmd {
         const cmd = [];
 
         // 固定头部
-        cmd.concat(this._header);
+        cmd.push(...this._header);
 
         // 版本号
         cmd.push(this._version);
@@ -308,7 +310,7 @@ class BtCmd {
                     cmd.push(this._int2Hex(element));
                 }
             } else {
-                cmd.concat(otherCmd);
+                cmd.push(...otherCmd);
                 console.log(`打印其他命令:${cmd}`);
             }
         }
@@ -317,6 +319,7 @@ class BtCmd {
         const length = cmd.length + 1;
         const l = this._int2Hex(length);
         cmd.splice(5, 0, l);
+        // console.log(`打印cmd:${cmd}`);
         return cmd;
     }
 
@@ -365,7 +368,7 @@ const CmdBase = {
     wallPaper: 0x78,
     wallPaperData: 0x79,
     heiJiaoOta: 0x074,
-    heiJiaoOtaData: 0x075,
+    heiJiaoOtaData: 0x75,
     heijiaoBackImg: 0x76,
     heijiaoBackImgData: 0x77,
     // 获取设备型号指令

+ 3 - 3
devices/bt_helper.js

@@ -770,9 +770,9 @@ class BtHelper {
   otaCmd(value) {
     this.send(BtCmd.otaCmd(value));
   }
-  // OTA指令
-  wifiUrl(value) {
-    this.send(BtCmd.otaCmd(value));
+  // OTA的URL
+  otaUrl(value) {
+    this.send(BtCmd.otaUrl(value));
   }
   otaData(value, callback) {
     BtHelper.sendCallBack(BtCmd.otaData(value), callback);

+ 2 - 2
pages/deviceDetail/detail.js

@@ -108,11 +108,11 @@ Page({
     this.setData({
       device: device,
       powerOpen: (device.pauseSleep ?? -1) > 0,
-      isShowWallpaper: device.clientType === '猫王妙播黑胶音箱(BLE)' || device.clientType === 'MW-S2'
+      isShowWallpaper: device.clientType === 'MW-S2'
     })
 
     const btHelper = BtHelper.getInstance();
-    let isShowOta = device.clientType === '猫王妙播黑胶音箱(BLE)' || device.clientType === 'MW-S2'
+    let isShowOta = device.clientType === 'MW-S2'
     if (isShowOta) {
       btHelper.getVersion()
     }

+ 3 - 3
pages/deviceList/deviceList.js

@@ -23,7 +23,7 @@ Page({
     }
 
     ///数据请求
-    dRequest.deviceList({unShowLoad:true}).then((res) => {
+    dRequest.deviceList({ unShowLoad: true }).then((res) => {
       if (res) {
         that.setDeviceList(res, true);
       }
@@ -54,11 +54,11 @@ Page({
         store.setStore("classifyProducts", res);
         app.globalData.classifyProducts = devices;
       }
-
+      console.log(devices);
       that.setData({
         deviceList: devices
       });
-    } catch (e) {}
+    } catch (e) { }
   },
 
   deviceTap(e) {

+ 78 - 16
pages/index/index.js

@@ -36,11 +36,11 @@ Page({
     isLogin: false,
     greeting: "",
     bannerList: [{
-        "pic": "https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20241028142233669038262.png"
-      },
-      {
-        "pic": "https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20240823145816541223911.png"
-      }
+      "pic": "https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20241028142233669038262.png"
+    },
+    {
+      "pic": "https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20240823145816541223911.png"
+    }
     ],
     autoplay: true,
     interval: 3000, // 切换时间间隔
@@ -74,6 +74,7 @@ Page({
     deviceMacId: null,
     deviceListSelect: null,
     deviceList: [],
+    _willConnectBle: true,
     // deviceList: [{
     //   "connectType": 3,
     //   "devName": "猫王小王子OTR-X",
@@ -224,18 +225,23 @@ Page({
     let hasBle = that.data.deviceList.find(item => {
       return item.connectType == 1;
     })
-    console.log("hasBle:", hasBle)
     if (hasBle) {
       ///监听蓝牙设备
       BtHelper.getInstance().initBluetoothAdapter();
       BtHelper.getInstance().getBluetoothDevices();
-      BtHelper.getInstance().startScan(null, null, null);
       var isFirst = true;
+      console.log("开始监听蓝牙设备");
       ///再秒再对比一次
       that.stopIntervalId1();
+      let count = 0;
       that.data.intervalId1 = setInterval(async function () {
         isFirst = false;
         that.compareList();
+        if (count > 3) {
+          that.stopIntervalId1();
+        } else {
+          count++;
+        }
       }, isFirst ? 6 * 1000 : 12 * 1000);
     }
 
@@ -244,13 +250,53 @@ Page({
   /// 对比蓝牙数据
   compareList() {
     var that = this;
+    if (that.data.deviceList.length == 1) {
+      let device = that.data.deviceList[0];
+      if (device.state === 'online') {
+        return;
+      }
+      getApp().getBluetoothStatus();
+      that.data._willConnectBle = true;
+      return;
+    }
     lexin_scan.compareList(function (list) {
       that.updateDeviceList(list, false, false);
     }, function (item) {
       that.addBlueDevice(item);
     });
   },
+  getBluetoothStatusCallck(v) {
+    var that = this;
+    if (!that.data._willConnectBle) {
+      // true 走下面
+      return;
+    }
+    if (v) {
+      let device = that.data.deviceList[0];
+      console.log("开始连接设备0", device);
+      if (device.state === 'online' || device.connectType != 1) {
+        return;
+      }
+      // });
+      BtHelper.getInstance().connect(device, function (isConnected, d) {
+        if (isConnected) {
+          d.connectType = 1;
+          d.state = 'online';
+          d.imageUrl = device.img;
+          that.addBlueDevice(d);
+        }
+      });
 
+    } else {
+      // wx.showModal({
+      //   title: '温馨提示',
+      //   content: '请检查手机蓝牙是否打开',
+      //   showCancel: false,
+      //   success: function (res) { }
+      // });
+    }
+    that.data._willConnectBle = false;
+  },
   // 回调
   mqttCallback(type, option) {
     // console.log("gadsfadsfadsfa==888===" + type);
@@ -265,7 +311,7 @@ Page({
       case "connect":
         lexin_subscribe.subscribeAllDevice();
         break;
-        ///再走有在线
+      ///再走有在线
       case "message_onoffline":
         lexin_connect.searchOnlineDevice(payloads, function (list) {
           that.updateDeviceList(list, false, false);
@@ -460,10 +506,12 @@ Page({
 
     var deviceList = that.getDeviceList();
     var deviceListSelect = that.getDeviceListSelect();
-    if (deviceListSelect === null || deviceList.length <= deviceListSelect) {
+
+    if (deviceList.length > 1 && (deviceListSelect === null || deviceList.length <= deviceListSelect)) {
+      // 2个设备才判断,1个直接删除
       return;
     };
-
+    deviceListSelect = deviceListSelect ?? 0
     ///有设备在线被选中,则让它不被选择
     if (deviceList[deviceListSelect].connectType == 3) {
       var deviceMacId = that.data.deviceMacId;
@@ -478,6 +526,16 @@ Page({
           indexPage: indexPage == 1 ? 0 : indexPage,
         });
       };
+    } else {
+      // console.log("退出登录,断开连接", deviceList);
+      // BtHelper.getInstance().disconnect(deviceList[deviceListSelect]);
+      // var indexPage = that.data.indexPage;
+      // that.setData({
+      //   deviceMacId: null,
+      //   actionIndex: null,
+      //   deviceListSelect: null,
+      //   indexPage: indexPage == 1 ? 0 : indexPage,
+      // });
     }
   },
 
@@ -509,15 +567,15 @@ Page({
     if (index === deviceListSelect) {
       route_util.jumpParam('/pages/deviceDetail/detail', JSON.stringify(device))
     } else if (device.state === "offline") {
-      console.log("去连接蓝牙")
-    } else {
-      // {"connectType":1,"deviceId":"E4:9F:80:09:40:EC","name":"E4:9F:80:09:40:EC","state":"online","ProdModel":"MW-SR1(4G_WIFI)","devName":"猫王音响x阿基米德 SR1 妙播收音机"}
+      console.log("去连接蓝牙", device)
       device.name = device.devName;
       BtHelper.getInstance().connect(device, function (isConnected, d) {
         if (isConnected) {
           that.addBlueDevice(d);
         }
       });
+    } else {
+      // {"connectType":1,"deviceId":"E4:9F:80:09:40:EC","name":"E4:9F:80:09:40:EC","state":"online","ProdModel":"MW-SR1(4G_WIFI)","devName":"猫王音响x阿基米德 SR1 妙播收音机"}
     }
   },
 
@@ -596,16 +654,17 @@ Page({
     if (onlyCancel) {
       return;
     }
-
     var deviceList = that.getDeviceList();
     var deviceListSelect = that.getDeviceListSelect();
-    if (deviceListSelect === null || deviceList.length <= deviceListSelect) {
+
+    if (deviceList.length > 1 && (deviceListSelect === null || deviceList.length <= deviceListSelect)) {
+      // 2个设备才判断,1个直接删除
       return;
     };
 
     ///是否删除的当前播放这个
     var isCurrentIndex = false;
-    var deviceListSelect = that.getDeviceListSelect();
+    deviceListSelect = deviceListSelect ?? 0;
     if (deviceListSelect != null && deviceList.length > deviceListSelect) {
       isCurrentIndex = (deviceListSelect == index);
     };
@@ -615,6 +674,9 @@ Page({
     deviceList = deviceList.filter((item, i) => {
       return deviceId !== item.deviceId;
     });
+    console.log("断开蓝牙连接", deviceId)
+
+    BtHelper.getInstance().disconnect({ "deviceId": deviceId });
 
     store.setStore("deviceList", deviceList);
     var indexPage = that.data.indexPage;

+ 51 - 64
pages/ota/ota.js

@@ -1,6 +1,7 @@
 const { BtHelper } = require("../../devices/bt_helper");
 import { EnumCmdEvent, CmdEvent } from '../../devices/cmd_key_event';
-import EventManager, { addNotification } from '../../utils/event_bus'
+import EventManager from '../../utils/event_bus'
+import route_util from '../../utils/route_util';
 // pages/OTA/ota.js
 Page({
 
@@ -100,7 +101,9 @@ Page({
         }
 
         if (res.confirm) {
-          _this.startDownloadFile()
+          _this.sendOtaCmd(1)
+
+          // _this.startDownloadFile()
           // _this.downloadOtaFile(_this.data.otaData.url ?? "")
         }
       }
@@ -109,54 +112,23 @@ Page({
     // btHelper.ota(this.data.otaData.file_url)
 
   },
-  sendWiFiInfo(wifiName, pwd) {
-    // [0x22, (wifiList.length + pwdList.length + 6), 0x33, (wifiList.length), (wifiList), 0x44, (pwdList)];
-
-    if (!wifiName || !pwd) {
-      wx.showToast({
-        title: '请输入正确的账号密码',
-      })
-      wx.hideLoading()
-      return;
-    }
-
-    let result = [];
-
-    // 字母*6 +
-    let wifiList = this.string2ListInt(wifiName);
-
-    // 数字*3 +
-    let pwdList = this.string2ListInt(pwd);
-
-    // 16进制
-    result.push(0x22);
-    result.push(this.int2Hex(wifiList.length + pwdList.length + 6));
-
-    // 账号
-    result.push(0x33);
-    result.push(this.int2Hex(wifiList.length));
-
-    let p = result[3] + 4;
-    let j = 0;
-    for (let i = 4; i < p; i++) {
-      result.splice(i, 0, wifiList[j++]);
-    }
-
-    // 密码
-    result.splice(p, 0, 0x44);
-    result.splice(++p, 0, this.int2Hex(pwdList.length));
-    p++;
-    j = 0;
-    // for (let i = p; i < p + pwdList.length; i++) {
-    //   result.splice(i, 0, pwdList[j++]);
-    // }
-    // result.push(...pwdList);
-    result.concat(pwdList)
-
-    console.log("发送wifi账号密码:", result.toString());
-    // _ble.send({ cmd: result });
-    const btHelper = BtHelper.getInstance();
-    btHelper.otaData(result)
+  goToWifi() {
+    route_util.jump("pages/setWifi/setWifi")
+  },
+  sendUrlData() {
+    let url = this.data.otaData.url ?? ""
+    let codeUrl = this.string2ListInt(url)
+    BtHelper.getInstance().otaUrl(codeUrl);
+    wx.showModal({
+      title: '发送成功',
+      content: '开始升级OTA,请等待设备升级成功',
+      showCancel: false,
+      success: (res) => {
+        if (res.confirm) {
+          route_util.goBack()
+        }
+      }
+    })
   },
   int2Hex(num) {
     return parseInt(num, 16);
@@ -173,6 +145,7 @@ Page({
   listInt2String(data) {
     return String.fromCharCode(...data);
   },
+  // 读取文件废弃代码
   startDownloadFile() {
 
     var urlPath = this.data.otaData.url ?? "";
@@ -297,14 +270,14 @@ Page({
     });
   },
   startSend(data) {
-    const chunkSize = 20; // 每次发送的数据块大小
-    const chunks = [];
-    for (let i = 0; i < data.length; i += chunkSize) {
-      chunks.push(data.slice(i, i + chunkSize));
-    }
+    // const chunkSize = 20; // 每次发送的数据块大小
+    // const chunks = [];
+    // for (let i = 0; i < data.length; i += chunkSize) {
+    //   chunks.push(data.slice(i, i + chunkSize));
+    // }
 
-    this.data._chunks = chunks;
-    this.endOta(1)
+    // this.data._chunks = chunks;
+    this.sendOtaCmd(1)
     // this.startSendOtaData()
   },
 
@@ -317,7 +290,7 @@ Page({
         title: '下载文件失败',
         icon: 'none'
       })
-      _this.endOta(2)
+      _this.sendOtaCmd(2)
       return;
     }
     _this.sendOtaData(this.data._chunks, 0)
@@ -326,7 +299,7 @@ Page({
     let _this = this
 
     if (index >= imageBuffer.length) {
-      _this.endOta(0)
+      _this.sendOtaCmd(0)
       return;
     }
     let chunkSize = 20;
@@ -351,7 +324,7 @@ Page({
     // })
 
   },
-  endOta(value) {
+  sendOtaCmd(value) {
     BtHelper.getInstance().otaCmd(value)
     if (value == 0) {
       this.setOtaStatus(0);
@@ -398,11 +371,25 @@ Page({
 
           if (otaCmd === 1 && kind == 1) {
             wx.hideLoading();
-            // 设备收到开启OTA的回复,开始发送wifi信息
-            _this.sendWiFiInfo()
-          } else if (otaCmd === 0 && kind == 1) {
+            // 设备收到开启OTA的回复,发送url
+            _this.sendUrlData()
+          } else if (otaCmd === 2 && kind == 1) {
+            wx.hideLoading();
+            // 去设置wifi界面
+            _this.goToWifi()
+          }
+          else if (otaCmd === 0 && kind == 1) {
             // 设备回收到url,OTA结束了
-            // _this.endOta(0)
+            // _this.sendOtaCmd(0)
+            var pages = getCurrentPages();
+            var length = pages.length;
+            var currentPage = pages[length - 1];
+            if (currentPage.route == 'pages/setWifi/setWifi') {
+              wx.navigateBack({
+                delta: 1
+              })
+            }
+
             wx.hideLoading()
             wx.showModal({
               title: '等待设备升级中',

+ 1 - 2
pages/ota/ota.wxml

@@ -27,7 +27,6 @@
                 {{progressPercent}}%
             </view>
         </view>
-        <view class="pro_tips">升级过程中请勿离开当前页面
-建议保持设备电量20%已上进行升级操作</view>
+        <view class="pro_tips">升级过程中请勿离开当前页面</view>
     </view>
 </view>