Browse Source

feature:修改OTA的流程

zeng.chen 7 tháng trước cách đây
mục cha
commit
d903472529

+ 8 - 2
devices/ble_manager.js

@@ -459,7 +459,7 @@ class bleManager {
   }
 
   // 发送数据到指定设备
-  async sendData(data) {
+  async sendData(data, callback) {
     var that = this
     return new Promise((resolve, reject) => {
       var buffer = null;
@@ -483,9 +483,15 @@ class bleManager {
         value: buffer,
         success: (res) => {
           // console.log('数据发送成功:');
+          if (callback) {
+            callback(true)
+          }
           resolve(res);
         },
         fail: (err) => {
+          if (callback) {
+            callback(false)
+          }
           console.error('数据发送失败:', err);
           reject(new Error('数据发送失败'));
         }
@@ -585,7 +591,7 @@ class bleManager {
     });
   }
 
-  connect() {}
+  connect() { }
 
   // 发现特征值 read / write
   discoverCharacteristics(deviceId, serviceId) {

+ 19 - 3
devices/bluetooth/bt_parse.js

@@ -488,9 +488,9 @@ class BtParse {
                 break;
 
             case CmdBase.heiJiaoOta:
-                // [84, 68, 68, 72, 1, 10, 54, 2, 0, 1] 
+                // [54:44:44:48:01:0A:74:01:01:00]
                 {
-                    let kind = cmd[8]
+                    let kind = cmd[9]
                     EventManager.fire(CmdEvent.otaCmd({ value: value, kind: kind }));
 
                 }
@@ -499,12 +499,28 @@ class BtParse {
             case CmdBase.heijiaoBackImg:
                 // [84, 68, 68, 72, 1, 10, 54, 2, 0, 1] 
                 {
-                    let kind = cmd[8]
+                    let kind = cmd[9]
                     EventManager.fire(CmdEvent.otaCmd({ value: value, kind: kind }));
 
                 }
 
                 break;
+            case CmdBase.wallPaper:
+                // [54:44:44:48:01:0A:78:01:01:00]
+                {
+                    let kind = cmd[9]
+                    EventManager.fire(CmdEvent.wallpaper({ value: value, kind: kind }));
+                }
+
+                break;
+            case CmdBase.wallPaperData:
+                // [54:44:44:48:01:0A:78:01:01:00]
+                {
+                    // let kind = cmd[8]
+                    // EventManager.fire(CmdEvent.wallPaperData({ value: value, kind: kind }));
+                }
+
+                break;
             default:
                 console.log("接收到语音:", cmd);
                 // _receiveRecordData(cmd);

+ 11 - 14
devices/bt_helper.js

@@ -472,8 +472,8 @@ class BtHelper {
     // QueueManager.instance.addTask({ task: cmd });
   }
 
-  static sendData(value) {
-    BtHelper.getInstance().send(BtCmd.otaData(value));
+  static sendCallBack(cmd, callback) {
+    BtHelper.getInstance().bleManager.sendData(cmd, callback)
   }
 
   // onLoad: function () {
@@ -741,32 +741,29 @@ class BtHelper {
 
   /* 黑胶音箱的指令 */
   // 壁纸指令 1开始, 0结束
-  static wallPaper(value) {
+  wallPaper(value) {
     var that = this;
     that.send(BtCmd.wallPaper(value));
   }
   // 壁纸指令 
-  static wallPaperData(value) {
-    var that = this;
-    that.send(BtCmd.wallPaperData(value));
+  wallPaperData(value, callback) {
+    BtHelper.sendCallBack(BtCmd.wallPaperData(value), callback);
   }
   // 背景图指令
-  static backgroudImg(value) {
+  backgroudImg(value) {
     var that = this;
     that.send(BtCmd.backgroudImg(value));
   } // 背景图指令
-  static backgroudImgData(value) {
+  backgroudImgData(value) {
     var that = this;
     that.send(BtCmd.backgroudImgData(value));
   }
   // OTA指令
-  static otaCmd(value) {
-    var that = this;
-    that.send(BtCmd.otaCmd(value));
+  otaCmd(value) {
+    this.send(BtCmd.otaCmd(value));
   }
-  static otaData(value) {
-    var that = this;
-    that.send(BtCmd.otaData(value));
+  otaData(value, callback) {
+    BtHelper.sendCallBack(BtCmd.wallPaperData(value), callback);
   }
 
   async closeBle() {

+ 8 - 7
devices/cmd_key_event.js

@@ -74,7 +74,7 @@ const EnumSupplier = {
 // 设备操作类
 class CmdEvent {
     constructor({ cmdEvent }) {
-//    this.cmdEvent =  EnumCmdEvent.value
+        //    this.cmdEvent =  EnumCmdEvent.value
         this.cmdEvent = cmdEvent;
         this.channelId = 1;
         this.wakeSwitch = null;
@@ -227,7 +227,7 @@ class CmdEvent {
     static pauseSleep({ pauseSleep }) {
         const event = new CmdEvent({ cmdEvent: EnumCmdEvent.authSleepStatus });
         event.pauseSleep = pauseSleep;
-                console.log("pauseSleep:", pauseSleep)
+        console.log("pauseSleep:", pauseSleep)
 
         return event;
     }
@@ -316,7 +316,7 @@ class CmdEvent {
 
     static version({ version }) {
         const event = new CmdEvent({ cmdEvent: EnumCmdEvent.version });
-        console.log('版本号:', version, {version});
+        console.log('版本号:', version, { version });
         event.version = version;
         return event;
     }
@@ -332,16 +332,17 @@ class CmdEvent {
         event.clientType = clientType;
         return event;
     }
-    static otaCmd({ value, Kind }) {
+    static otaCmd({ value, kind }) {
         const event = new CmdEvent({ cmdEvent: EnumCmdEvent.otaCmd });
         event.otaCmd = value;
-        event.heiJiaoKind = Kind;
+        event.heiJiaoKind = kind;
         return event;
     }
-    static wallpaper({ value, Kind }) {
+    static wallpaper({ value, kind }) {
         const event = new CmdEvent({ cmdEvent: EnumCmdEvent.wallpaper });
+        console.log("wallpaper:", value, kind)
         event.wallpaper = value;
-        event.heiJiaoKind = Kind;
+        event.heiJiaoKind = kind;
         return event;
     }
 

+ 9 - 6
pages/deviceDetail/detail.js

@@ -29,10 +29,11 @@ Page({
   },
   checkOtaVersion(device) {
     let _this = this;
-    console.log("OTA1:", device);
-    deviceVersion(device.clientType, device.connectType, device.version).then(res => {
+    device.clientType = "MW-S2"
+    deviceVersion(device.clientType, device.connectType, device.version ?? "1.0.0").then(res => {
       console.log("OTA2:", res);
-      let updateData = res.data ?? {};
+      let updateData = res ?? {};
+
       let hasNewVersion = updateData.isEnforcement === 1 || updateData.isEnforcement === 2;
       updateData.hasNewVersion = hasNewVersion;
       _this.setData({
@@ -115,14 +116,16 @@ Page({
     const btHelper = BtHelper.getInstance();
     let isShowOta = device.clientType === 'MW-S2(BLE)' || device.clientType === 'MW-S2'
     if (isShowOta) {
-      btHelper.getVersion()
+      // btHelper.getVersion()
     }
-    btHelper.getPauseSleep()
+    // btHelper.getPauseSleep()
+
+    this.checkOtaVersion(device)
 
     let _this = this;
     EventManager.addNotification(CmdEvent.eventName, function (event) {
       let name = event.cmdEvent;
-      console.log("详情页:", name, event)
+      // console.log("详情页:", name, event)
       switch (name) {
         case EnumCmdEvent.version:
           _this.data.device.version = event.version;

+ 174 - 131
pages/ota/ota.js

@@ -49,7 +49,6 @@ Page({
           otaStatus: 3,
           buttonTips: "更新中..."
         });
-        this.startProgress();
         break;
 
       case 4:
@@ -64,8 +63,8 @@ Page({
 
   },
   startOtaTap() {
-    let connect = getApp().globalData.device.connect ?? false
-    if (!connect) {
+    let online = this.data.device.state === "online"
+    if (!online) {
       wx.showToast({
         title: '设备已经掉线了',
       })
@@ -83,7 +82,7 @@ Page({
     let _this = this
     wx.showModal({
       title: '有新固件可升级',
-      content: _this.otaData.content ?? '提升体验,操作更流畅',
+      content: _this.data.otaData.content ?? '提升体验,操作更流畅',
       cancelText: '以后再说',
       confirmText: '升级',
       complete: (res) => {
@@ -92,7 +91,8 @@ Page({
         }
 
         if (res.confirm) {
-          _this.downloadFile(_this.otaData.url)
+          _this.startDownloadFile()
+          // _this.downloadOtaFile(_this.data.otaData.url ?? "")
         }
       }
     })
@@ -100,73 +100,94 @@ Page({
     // btHelper.ota(this.data.otaData.file_url)
 
   },
-  downloadFile(url) {
+  startDownloadFile() {
 
-    urlPath = updateData.url ?? "";
-    content = updateData.content ?? "暂无更新";
+    var urlPath = this.data.otaData.url ?? "";
 
     var list = urlPath.split("/");
     // let cachePath = await PathUtil.getDownloadPath(fileName: list.last ?? 'OTAUpgrade.OTA');
     const fs = wx.getFileSystemManager();
 
     // 构建本地文件路径
-    const localFilePath = list[list.length - 1];
+    var localFilePath = list[list.length - 1];
+    console.log(list, localFilePath)
+
     let _this = this;
+    let localPath = `${wx.env.USER_DATA_PATH}/` + localFilePath
     // 判断文件是否存在
-    fs.access(localFilePath, (err) => {
-      if (err) {
+    fs.access({
+      path: localPath,
+      success(res) {
+        console.log('文件已存在:', res);
+
+        if (res) {
+          // 有文件
+          _this.readFile(localPath);
+
+        } else {
+
+        }
+      }, fail(err) {
+        // 文件不存在或其他错误
+        console.log(err)
         // 文件不存在,开始下载
-        wx.downloadFile({
-          url: url, // 下载资源的URL
-          success: (res) => {
-            if (res.statusCode === 200) {
-              // 下载成功,保存文件路径
-              const filePath = res.tempFilePath;
-
-              // 将下载的文件移动到本地路径
-              fs.rename({
-                oldPath: filePath,
-                newPath: localFilePath,
-                success: () => {
-
-                  // this.setData({
-                  //   localFilePath: localFilePath
-                  // });
-
-                  // 调用 OTA 更新方法
-                  // const btHelper = BtHelper.getInstance();
-                  // btHelper.ota(localFilePath);
-
-                  wx.showToast({
-                    title: '文件下载成功',
-                  });
-                  _this.readFile(localFilePath);
-                },
-                fail: (err) => {
-                  wx.showToast({
-                    title: '文件移动失败',
-                  });
-                  console.error('文件移动失败:', err);
-                }
-              });
-            } else {
-              wx.showToast({
-                title: '文件下载失败',
-              });
-            }
-          },
-          fail: (err) => {
-            wx.showToast({
-              title: '文件下载失败',
-            });
-            console.error('下载文件失败:', err);
-          }
-        });
-      } else {
-        _this.readFile(localFilePath);
+        _this.downloadOtaFile(urlPath, localPath)
+      }
+    }
+    );
+  },
+  downloadOtaFile(urlPath, localPath) {
+    let _this = this;
+    // const fs = wx.getFileSystemManager();
+
+    wx.downloadFile({
+      url: urlPath, // 下载资源的URL
+      success: (res) => {
+        console.log('文件下载成功2', res);
+
+        if (res.statusCode === 200) {
+          // 下载成功,保存文件路径
+          const filePath = res.tempFilePath;
+          // _this.readFile(filePath);
+          _this.readFile(filePath);
+
+          // 将下载的文件移动到本地路径
+          // fs.rename({
+          //   oldPath: filePath,
+          //   newPath: localPath,
+          //   success: () => {
+
+          //     // this.setData({
+          //     //   localFilePath: localFilePath
+          //     // });
+
+          //     // 调用 OTA 更新方法
+          //     // const btHelper = BtHelper.getInstance();
+          //     // btHelper.ota(localFilePath);
+
+          //     wx.showToast({
+          //       title: '文件下载成功',
+          //     });
+          //     _this.readFile(localPath);
+          //   },
+          //   fail: (err) => {
+          //     wx.showToast({
+          //       title: '下载文件失败,检查下手机内存吧',
+          //     });
+          //     console.error('文件移动失败:', err);
+          //   }
+          // });
+        } else {
+          wx.showToast({
+            title: '文件下载失败',
+          });
+        }
+      },
+      fail: (err) => {
         wx.showToast({
-          title: '文件已存在,跳过下载',
+          title: '文件下载失败',
         });
+        console.error('下载文件失败:', err);
       }
     });
   },
@@ -178,6 +199,9 @@ Page({
       });
       return;
     }
+    wx.showLoading({
+      title: '开始传输文件',
+    })
     this.setOtaStatus(2);
     const fs = wx.getFileSystemManager();
 
@@ -190,8 +214,9 @@ Page({
         // const btHelper = BtHelper.getInstance();
         //   btHelper.ota(localFilePath);
 
-        // console.log('文件内容:', res.data);
-        _this.startSend();
+        console.log('文件内容:', res.data.length);
+
+        _this.startSend(res.data);
       },
       fail: (err) => {
         wx.showToast({
@@ -201,88 +226,96 @@ Page({
       }
     });
   },
-  startSend() {
+  startSend(data) {
     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;
-    const btHelper = BtHelper.getInstance();
-    btHelper.otaCmd(1)
-  },
-  sendOtaData() {
-    const btHelper = BtHelper.getInstance();
-    this.data._chunks.forEach(element => {
-      btHelper.otaData(element)
-    });
-    this.startProgress()
-  },
-  endEnd() {
-    const btHelper = BtHelper.getInstance();
-    btHelper.otaCmd(0)
+    this.endOta(1)
+    // this.startSendOtaData()
   },
 
-  updateProgress(newProgress) {
-    this.setData({
-      progress: newProgress,
-    });
-  },
+  startSendOtaData() {
+    let _this = this
+    let length = this.data._chunks.length
 
-  // 示例:模拟进度更新
-  simulateProgressUpdate() {
-    let currentProgress = 0;
-    const interval = setInterval(() => {
-      if (currentProgress >= 100) {
-        clearInterval(interval);
-        wx.showToast({
-          title: '升级完成',
-        });
+    if (length === 0) {
+      wx.showToast({
+        title: '图片裁剪失败',
+        icon: 'none'
+      })
+      _this.endOta(2)
+      return;
+    }
+    _this.sendOtaData(this.data._chunks, 0)
+    // }
+  }, sendOtaData(imageBuffer, index) {
+    let _this = this
+
+    if (index >= imageBuffer.length) {
+      _this.endOta(0)
+      return;
+    }
+    let chunkSize = 20;
+
+
+    let total = imageBuffer.length
+    let next = index + chunkSize;
+    const chunk = imageBuffer.slice(index, next);
+    BtHelper.getInstance().wallPaperData(chunk, function (res) {
+      console.log("发送图片数据:", next)
+      if (res) {
+        _this.updateProgress(next, total);
+
+        _this.sendOtaData(imageBuffer)
       } else {
-        currentProgress += 10;
-        this.updateProgress(currentProgress);
-      }
-    }, 500);
-  },
-  startProgress: function () {
-    const _this = this;
-    let progress = 0;
-    // 定时器,每100毫秒执行一次
-    _this._timer = setInterval(function () {
-      if (progress >= 100) {
-        clearInterval(_this._timer); // 停止定时器
-        _this.setData({
-          progress: 0,
-          progressPercent: 0,
-          showProgress: false,
-        });
-        _this.data.otaData.hasNewVersion = false;
-        _this.setOtaStatus(0)
-        wx.showToast({
-          title: '数据上传成功',
+        wx.showModal({
+          title: 'OTA升级失败了',
+          showCancel: false
         })
-      } else {
-        progress += 1; // 每次增加1%
-        let ptl = (progress / 2) + "%"
-        _this.setData({
-          progress: progress,
-          progressPercent: progress,
-          progressTextLeft:ptl  // 文字位置跟随进度     
-        });
       }
-    }, 100);
+    })
+
+  },
+  endOta(value) {
+    BtHelper.getInstance().otaCmd(value)
+  },
+
+  startProgress() {
+    this.setData({
+      progress: 0,
+      showProgress: true
+    })
+  },
+  updateProgress(chunk, total) {
+    let progress = chunk / total * 100;
+    let _this = this
+    if (progress >= 100) {
+      _this.setData({
+        progress: 0,
+        showProgress: false,
+        // showCropImg: false
+      });
+      wx.showToast({
+        title: '图片上传成功',
+      })
+    } else {
+      _this.setData({
+        progress: progress,
+      });
+    }
   },
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad(options) {
     let param = JSON.parse(options.param)
-    console.log(param)
+    console.log("OTA界面:", param)
     let otaData = param.otaData
     let device = param.device
-    device.clientType = device.clientType ?? device.ProdModel
     this.setData({
       otaData: otaData,
       device: device,
@@ -291,25 +324,35 @@ Page({
 
     let _this = this;
     EventManager.addNotification(CmdEvent.eventName, function (event) {
-      let name = event.name;
-      console.log("OTA页:", event)
+      let name = event.cmdEvent;
+      console.log("OTA页0:", name, EnumCmdEvent.otaCmd, EnumCmdEvent.otaCmd === name)
+
       switch (name) {
         case EnumCmdEvent.otaCmd:
           let otaCmd = event.otaCmd;
-          let kind = event.kind;
+          let kind = event.heiJiaoKind;
+          console.log("OTA页:", otaCmd, kind)
+
           if (otaCmd === 1 && kind == 1) {
+            wx.hideLoading();
             // 开始发送
-            _this.sendOtaData()
+            _this.startSendOtaData()
           } else if (otaCmd === 0 && kind == 1) {
             // 发送结束
-            _this.endEnd()
+            _this.endOta(0)
+          } else if (kind == 0) {
+            wx.hideLoading()
+            wx.showModal({
+              title: 'OTA升级失败了',
+              showCancel: false
+            })
           }
           break;
       }
     }, this)
-
-
-
+  },
+  onUnload() {
+    EventManager.removeNotification(CmdEvent.eventName, this)
   },
 
 })