Просмотр исходного кода

feature:增加OTA界面,壁纸界面

zeng.chen 8 месяцев назад
Родитель
Сommit
e1193ce66d

+ 2 - 1
app.json

@@ -17,7 +17,8 @@
     "pages/deviceConMode/index",
     "pages/connectBle/connectBle",
     "pages/deviceDetail/detail",
-    "pages/piano/wallpaper/wallpaper"
+    "pages/piano/wallpaper/wallpaper",
+    "pages/OTA/ota"
   ],
   "window": {
     "backgroundTextStyle": "light",

+ 7 - 3
devices/bluetooth/bt_cmd.js

@@ -142,7 +142,7 @@ class BtCmd {
         const minutes = now.getMinutes();
         const seconds = now.getSeconds();
 
-        // console.log(`setTime========${CmdRtc.setTime},${year},${_year},${month},${day},${hour},${minutes},${seconds}`);
+        console.log(`setTime========${year},${_year},${month},${day},${hour},${minutes},${seconds}`);
         // console.log(`setTime======== 2,    ${CmdRtc.setTime}`);
 
         let cmd = this._build(0x50, [year, _year, month, day, hour, minutes, seconds]);
@@ -273,8 +273,12 @@ class BtCmd {
         console.log(`${key}解析- [${result}]`);
     }
 
-    static _int2Hex(value) {
-        return value & 0xFF;
+    static _int2Hex(num) {
+        let hexStr = num >>> 0; // 将 num 转换为无符号 32 位整数
+        hexStr = hexStr.toString(16); // 转换为 16 进制字符串
+        let i = parseInt(hexStr, 16); // 将 16 进制字符串转换回整数
+        // console.log(`${hexStr}==${i}==${num}`);
+        return i;
     }
 
     static _int2HexString(value) {

+ 7 - 6
devices/bt_helper.js

@@ -99,7 +99,7 @@ class BtHelper {
             this.timer = null;
             this.bleManager.stopScan()
             var res = await this.bleManager.connectToDevice(data);
-            console.log('连接成功');
+            console.log(res ? '连接成功' : '连接失败');
             // this.setData({ connectedDeviceId: deviceId });
             if (res === false) {
                 console.log("连接失败")
@@ -134,9 +134,9 @@ class BtHelper {
             for (let i = 0; i < characteristics.length; i++) {
                 let charc = characteristics[i];
                 if (charc.properties.notify) {
+                    console.log('订阅数据:');
                     // 订阅的
                     this.bleManager.notifyCharacteristicValueChange(charc.uuid, (res) => {
-                        // console.log('收到数据:', BtParse.parseTLV);
                         BtParse.parseTLV(res);
                     })
                 }
@@ -259,12 +259,13 @@ class BtHelper {
         //     this.send(BtCmd.queryLowPower);
         //     this.send(BtCmd.queryCtrlStatus);
         // } else {
-        this.send(BtCmd.setDevTime());
+        // this.send(BtCmd.setDevTime());
         this.send(BtCmd.queryKwh());
         this.getSleep();
         this.getAlert();
         this.send(BtCmd.queryRGB());
         this.getVolume();
+        this.setVolume(8)
         this.getPauseSleep();
         // }
     }
@@ -315,14 +316,14 @@ class BtHelper {
     }
 
     async setVolume(volume) {
-        VolumeUtil.setVolume(volume, { hideVolumeView: true });
+        // VolumeUtil.setVolume(volume, { hideVolumeView: true });
 
-        const phoneMax = await VolumeUtil.getMaxVolume();
+        const phoneMax = 15;//await VolumeUtil.getMaxVolume();
         const result = Math.floor(CmdBase.volumeMax * volume / phoneMax);
 
         console.log(`phoneMax=${phoneMax}, deviceMax=${CmdBase.volumeMax}, setVolume=${volume}, result=${result}`);
 
-        this.send(BtCmd.setVolume({ volume: result }));
+        this.send(BtCmd.setVolume({ volume: 8 }));
     }
 
     async getVolume() {

+ 1 - 0
devices/cmd_key_event.js

@@ -122,6 +122,7 @@ class CmdEvent {
         this.deviceMode = null;
     }
 
+    static eventName = "cmdEventNotification"
     static wake({ wakeSwitch, wakeCycle, wakeHour, wakeMinutes }) {
         const event = new CmdEvent({ cmdEvent: EnumCmdEvent.wake });
         event.wakeSwitch = wakeSwitch;

BIN
images/common/icon_sel.png


Разница между файлами не показана из-за своего большого размера
+ 2 - 0
pages/connectBle/connectBle.js


+ 28 - 10
pages/deviceDetail/detail.js

@@ -2,7 +2,9 @@
 
 const BtHelper = require('../../devices/bt_helper');
 const { deviceVersion } = require('../../request/deviceListRequest')
+import { CmdEvent } from '../../devices/cmd_key_event';
 import EventManager from '../../utils/event_bus'
+import route_util from '../../utils/route_util';
 
 Page({
   data: {
@@ -14,12 +16,13 @@ Page({
     // 页面数据
     device: getApp().globalData.device,
     btHelper: null,
+    updateData: {},
   },
   checkOtaVersion(device) {
     let _this = this;
     deviceVersion(device.clienlType, device.connectType, device.version).then(res => {
       console.log(res);
-      let updateData = res.data;
+      let updateData = res.data ?? {};
       let hasNewVersion = updateData.isEnforcement === 1 || updateData.isEnforcement === 2;
       _this.setData({
         hasNew: hasNewVersion,
@@ -36,18 +39,22 @@ Page({
   },
 
   goToOta: function () {
-
-    wx.navigateTo({
-      url: '/pages/piano/wallpaper/wallpaper'
-    });
+    if (this.data.hasNew) {
+      let param = JSON.stringify(this.data.updateData) ?? {};
+      // wx.navigateTo({
+      //   url: '/pages/ota/ota' + "?param=" + param
+      // });
+      route_util.jumpParam('/pages/ota/ota', param)
+    }
   },
 
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function () {
-    let device = getApp().globalData.device;
-    if (!device.connect) {
+    let device = getApp().globalData.device ?? {};
+    let isConnect = device.state === 'online'
+    if (!isConnect) {
       // btHelper
       wx.showToast({
         title: '设备已经失去连接',
@@ -58,9 +65,20 @@ Page({
     const btHelper = BtHelper.getInstance();
     btHelper.getVersion()
 
-    this.data.btHelper = btHelper;
-    this.checkOtaVersion(device);
-    EventManager.addNotification(CmdEvent,)
+    EventManager.addNotification(CmdEvent.eventName, listenEvent, this)
+  },
+  listenEvent(event) {
+    let name = event.name;
+    console.log(event)
+    switch (name) {
+      case CmdEvent.version:
+        this.data.device.version = event.version;
+        this.checkOtaVersion(this.data.device);
+        break;
+    }
+  },
+  onUnload() {
+    EventManager.removeNotification(CmdEvent.eventName, listenEvent, this)
   },
 
 })

+ 18 - 7
pages/index/index.js

@@ -6,6 +6,7 @@ const {
 
 import timeUtil from '../../utils/time_util.js';
 import strings from '../../utils/strings.js';
+import route_util from '../../utils/route_util.js';
 
 Page({
   data: {
@@ -359,7 +360,11 @@ Page({
   },
 
   getchannelData(clientType) {
+<<<<<<< Updated upstream
     var that = this;
+=======
+    var that = this; Ï
+>>>>>>> Stashed changes
     if (that.data.deviceListIndex === null) {
       return;
     };
@@ -516,14 +521,20 @@ Page({
       }
       return;
     }
+    console.log(e)
     ///去蓝牙连接处理
-    that.addConnectBlueDevice({
-      deviceId: item.deviceId,
-      name: item.devName,
-      state: item.state,
-      clientType: item.ProdModel,
-      mac: item.mac,
-    });
+    if (item.state !== "online") {
+      that.addConnectBlueDevice({
+        deviceId: item.deviceId,
+        name: item.devName,
+        state: item.state,
+        clientType: item.ProdModel,
+        mac: item.mac,
+      });
+    } else {
+      route_util.jumpParam('/pages/deviceDetail/detail', JSON.stringify(item))
+    }
+
   },
 
   actionDevice(index) {

+ 239 - 0
pages/ota/ota.js

@@ -0,0 +1,239 @@
+// pages/OTA/ota.js
+Page({
+
+  /**
+   * 页面的初始数据
+   */
+  data: {
+    nvabarData: {
+      showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
+      title: '固件信息', //导航栏 中间的标题
+    },
+    device: getApp().globalData.device,
+    otaData: {},
+    btHelper: null,
+  },
+
+  startOtaTap() {
+    let connect = getApp().globalData.device.connect ?? false
+    if (!connect) {
+      wx.showToast({
+        title: '设备已经掉线了',
+      })
+      return;
+    }
+    let _this = this
+    wx.showModal({
+      title: '有新固件可升级',
+      content: _this.otaData.content ?? '提升体验,操作更流畅',
+      cancelText: '以后再说',
+      confirmText: '升级',
+      complete: (res) => {
+        if (res.cancel) {
+
+        }
+
+        if (res.confirm) {
+          _this.downloadFile(_this.otaData.url)
+        }
+      }
+    })
+    // const btHelper = BtHelper.getInstance();
+    // btHelper.ota(this.data.otaData.file_url)
+
+  },
+  downloadFile(url) {
+
+
+    urlPath = updateData.url ?? "";
+    content = updateData.content ?? "暂无更新";
+
+    var list = urlPath.split("/");
+    // let cachePath = await PathUtil.getDownloadPath(fileName: list.last ?? 'OTAUpgrade.OTA');
+    const fs = wx.getFileSystemManager();
+
+    // 构建本地文件路径
+    const localFilePath = list[list.length - 1];
+    let _this = this;
+    // 判断文件是否存在
+    fs.access(localFilePath, (err) => {
+      if (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);
+        wx.showToast({
+          title: '文件已存在,跳过下载',
+        });
+      }
+    });
+  },
+  readFile(localFilePath) {
+
+    if (!localFilePath) {
+      wx.showToast({
+        title: '下载文件为空',
+      });
+      return;
+    }
+    const fs = wx.getFileSystemManager();
+
+    fs.readFile({
+      filePath: localFilePath,
+      encoding: 'base64', // 可以选择 'utf8' 或 'base64'
+      success: (res) => {
+
+        // const btHelper = BtHelper.getInstance();
+        //   btHelper.ota(localFilePath);
+
+        // console.log('文件内容:', res.data);
+      },
+      fail: (err) => {
+        wx.showToast({
+          title: 'OTA文件下载失败',
+        });
+        console.error('文件读取失败:', err);
+      }
+    });
+  },
+  sendDataToBluetooth(data) {
+    const chunkSize = 20; // 每次发送的数据块大小
+    const chunks = [];
+
+    for (let i = 0; i < data.length; i += chunkSize) {
+      chunks.push(data.slice(i, i + chunkSize));
+    }
+
+    const sendNextChunk = (index) => {
+      if (index >= chunks.length) {
+        wx.showToast({
+          title: '文件发送完成',
+        });
+        return;
+      }
+
+      const chunk = chunks[index];
+
+      // wx.writeBLECharacteristicValue({
+      //   deviceId: deviceId,
+      //   serviceId: 'yourServiceId', // 替换为实际的服务ID
+      //   characteristicId: 'yourCharacteristicId', // 替换为实际的特征值ID
+      //   value: new Uint8Array(Buffer.from(chunk, 'base64')),
+      //   success: () => {
+      //     setTimeout(() => {
+      //       sendNextChunk(index + 1);
+      //     }, 100); // 延迟100毫秒发送下一个数据块
+      //   },
+      //   fail: (err) => {
+      //     wx.showToast({
+      //       title: '文件发送失败',
+      //     });
+      //     console.error('文件发送失败:', err);
+      //   }
+      // });
+    }
+  },
+  /**
+   * 生命周期函数--监听页面加载
+   */
+  onLoad(options) {
+    let otaData = JSON.parse(options.param)
+    this.setData({
+      otaData: otaData
+    })
+
+  },
+
+  /**
+   * 生命周期函数--监听页面初次渲染完成
+   */
+  onReady() {
+
+  },
+
+  /**
+   * 生命周期函数--监听页面显示
+   */
+  onShow() {
+
+  },
+
+  /**
+   * 生命周期函数--监听页面隐藏
+   */
+  onHide() {
+
+  },
+
+  /**
+   * 生命周期函数--监听页面卸载
+   */
+  onUnload() {
+
+  },
+
+  /**
+   * 页面相关事件处理函数--监听用户下拉动作
+   */
+  onPullDownRefresh() {
+
+  },
+
+  /**
+   * 页面上拉触底事件的处理函数
+   */
+  onReachBottom() {
+
+  },
+
+  /**
+   * 用户点击右上角分享
+   */
+  onShareAppMessage() {
+
+  }
+})

+ 5 - 0
pages/ota/ota.json

@@ -0,0 +1,5 @@
+{
+  "usingComponents": {
+    "nav-bar": "./../components/navbar/navbar"
+  }
+}

+ 17 - 0
pages/ota/ota.wxml

@@ -0,0 +1,17 @@
+<!-- pages/OTA/ota.wxml -->
+<view class="section">
+    <nav-bar bind:goBack="_goBack" nav-bgc-class="ex-nav-bgc-class" nav-title-class="ex-nav-title-class" ex-back-pre="ex-back-pre" navbar-data='{{nvabarData}}'></nav-bar>
+    <view class="item">
+        <text class="label">制造商</text>
+        <text class="arrow">{{device.man}}</text>
+    </view>
+    <view class="item">
+        <text class="label">产品型号</text>
+        <text class="arrow">{{device.clientType}}</text>
+    </view>
+    <view class="item">
+        <text class="label">MAC地址</text>
+        <text class="arrow">{{device.mac}}</text>
+    </view>
+    <view class="button main_color" bind:tap="startOtaTap">固件更新</view>
+</view>

+ 40 - 0
pages/ota/ota.wxss

@@ -0,0 +1,40 @@
+/* pages/OTA/ota.wxss */
+
+
+
+
+.item {
+	display: flex;
+	align-items: center;
+	border-bottom: 1px solid #e0e0e0;
+	justify-content: space-between;
+	margin-inline: 32rpx;
+	height: 120rpx;
+}
+
+
+.label {
+	font-size: 16px;
+	color: #333333;
+	margin-left: 32rpx;
+}
+
+.arrow {
+	width: 20px;
+	height: 20px;
+	margin-right: 16rpx;
+}
+
+.button {
+	margin-top: 128rpx;
+	display: flex;
+	justify-content: center;
+	align-items: center;
+	margin-inline: 64rpx;
+	font-size: 32rpx;
+	font-weight: Medium;
+	color: white;
+	text-align: center;
+	border-radius: 44rpx;
+	height: 88rpx;
+}

+ 11 - 1
pages/piano/wallpaper/wallpaper.js

@@ -5,8 +5,18 @@ Page({
    * 页面的初始数据
    */
   data: {
-    imageList: [],
+    topImg: "https://inews.gtimg.com/om_bt/OAVMydtx9BsJxf5i_thi4Oll9sR1px-Esmtv6UHSxoisEAA/641",
+    imageList: [
+      {
+        img:"https://inews.gtimg.com/om_bt/OAVMydtx9BsJxf5i_thi4Oll9sR1px-Esmtv6UHSxoisEAA/641",
+        imgId:""
+      }
+    ],
     selectIndex: 0,
+    nvabarData: {
+      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
+      title: '壁纸设置', //导航栏 中间的标题
+    },
   },
 
   /**

+ 2 - 2
pages/piano/wallpaper/wallpaper.wxml

@@ -2,8 +2,8 @@
 <view class="container">
     <nav-bar bind:goBack="_goBack" nav-bgc-class="ex-nav-bgc-class" nav-title-class="ex-nav-title-class" ex-back-pre="ex-back-pre" navbar-data='{{nvabarData}}'></nav-bar>
     <view class="img_section">
-        <image src="../../images/icon_arrow.png" class="select_img"></image>
-        <image src="../../images/icon_arrow.png" class="select_icon"></image>
+        <image src="{{topImg}}" class="select_img"></image>
+        <image src="../../images/common/icon_icon.png" class="select_icon"></image>
     </view>
     <view class="grid-container">
         <block wx:for="{{imageList}}" wx:key="index" wx:for-item="item" wx:for-index="index">

+ 2 - 0
pages/piano/wallpaper/wallpaper.wxss

@@ -4,6 +4,8 @@
     width: 100%;
     height: 400rpx;
     position: relative;
+    align-items: center;
+    justify-content: center;
 }
 
 .select_img {