Browse Source

Merge remote-tracking branch 'origin/develop/3.2.4_黑胶' into develop/3.2.4_黑胶

332777428@qq.com 6 months ago
parent
commit
33f35fc1b6

+ 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('开始发送数据:', data);
+      let logData = new Uint8Array(buffer);
+      console.log('开始发送数据:', logData);
       wx.writeBLECharacteristicValue({
         deviceId: that.publicDevice.deviceId,
         serviceId: that.publicDevice.serviceId,

+ 22 - 45
devices/bluetooth/bt_cmd.js

@@ -180,13 +180,14 @@ class BtCmd {
         return this._build(CmdRgb.query, [0x00]);
     }
 
-    static stringToUint8Array(str) {
-        // 54 44 44 48 01 11 28 09 73 6d6172745f413246
-        // const encoder = new TextEncoder();
-        // const uint8Array = encoder.encode(str);
-        // return uint8Array;
+    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]
+        // 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)
+        return code
     }
 
     // 校验设备
@@ -248,7 +249,7 @@ class BtCmd {
     // 壁纸指令 
     static wallPaperData(value) {
         let uint8Array = new Uint8Array(value);
-        let cmd = this._build(CmdBase.wallPaperData, uint8Array);
+        let cmd = this._build(CmdBase.wallPaperData, uint8Array, true, false);
         return cmd;
     }
     // 背景图指令 1开始, 0结束
@@ -261,9 +262,15 @@ class BtCmd {
     // OTA指令 1开始, 0结束
     static otaCmd(value) {
         return this._build(CmdBase.heiJiaoOta, [value]);
-    } static otaData(value) {
+    }
+    // 发送OTA的URL
+    static otaUrl(value) {
         return this._build(CmdBase.heiJiaoOtaData, [value]);
     }
+    //暂时没用了
+    static otaData(value) {
+        return this._build(CmdBase.heiJiaoOta, [value], true, false);
+    }
     /// 获取设备型号指令
     static getClientType() {
         return this._build(0x31, [0x00]);
@@ -276,39 +283,9 @@ class BtCmd {
         return this._build(0x36, [0x00]);
     }
 
-    static _buildOther(data) {
-        const cmd = [];
-
-        // 固定头部
-        cmd.push(...this._header);
 
-        // 版本号
-        cmd.push(this._version);
-
-        // 命令类型
-        cmd.push(cmdType);
-
-        if (isWriteChildCmdLength) {
-            // 子命令长度
-            const childLength = this._int2Hex(otherCmd.length);
-            cmd.push(childLength);
-        }
-
-        // 其他命令
-        if (otherCmd.length > 0) {
-            for (const element of otherCmd) {
-                cmd.push(this._int2Hex(element));
-            }
-        }
-
-        // 命令长度(位置在版本号之后)
-        const length = cmd.length + 1;
-        const l = this._int2Hex(length);
-        cmd.splice(5, 0, l);
-        return cmd;
-    }
     // 生成命令(固定头部+版本号+命令总长度+命令类型+)
-    static _build(cmdType, otherCmd = [], isWriteChildCmdLength = true, isChangeOther = true) {
+    static _build(cmdType, otherCmd = [], isWriteChildCmdLength = true, isChangeHex = true) {
         const cmd = [];
 
         // 固定头部
@@ -328,12 +305,13 @@ class BtCmd {
 
         // 其他命令
         if (otherCmd.length > 0) {
-            if (isChangeOther) {
+            if (isChangeHex) {
                 for (const element of otherCmd) {
                     cmd.push(this._int2Hex(element));
                 }
             } else {
-                cmd.concat(otherCmd);
+                cmd.push(...otherCmd);
+                console.log(`打印其他命令:${cmd}`);
             }
         }
 
@@ -341,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;
     }
 
@@ -353,9 +332,7 @@ class BtCmd {
         }
 
         for (let i = 0; i < cmd.length; i++) {
-            var cmdStr = `${this._int2HexString(cmd[i])}`.padStart(2, "0");
-            cmdStr += ":"
-            result += cmdStr;
+            result += (`${this._int2HexString(cmd[i])}`.padStart(2, "0") + ":");
         }
         if (isSend) {
             mqttAddDebugCmd(`发送蓝牙指令:${cmd} \n ${result}`);
@@ -391,7 +368,7 @@ const CmdBase = {
     wallPaper: 0x78,
     wallPaperData: 0x79,
     heiJiaoOta: 0x074,
-    heiJiaoOtaData: 0x075,
+    heiJiaoOtaData: 0x75,
     heijiaoBackImg: 0x76,
     heijiaoBackImgData: 0x77,
     // 获取设备型号指令

File diff suppressed because it is too large
+ 510 - 535
devices/bluetooth/bt_parse.js


+ 9 - 5
devices/bt_helper.js

@@ -501,8 +501,8 @@ class BtHelper {
     var that = this;
     // console.log("校验设备:", BtCmd); // 输出: EarPhone Info
     that.sendNow(BtCmd.checkDevice());
-    //2.0有发这个,不知道是啥
-    that.send([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x26, 0x01, 0x01]);
+    //低电量提示语
+    // that.send([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x26, 0x01, 0x01]);
   }
 
   async getVersion() {
@@ -526,15 +526,15 @@ class BtHelper {
     // that.send(BtCmd.setDevTime());
 
     // that.send(BtCmd.queryKwh());
-    that.getSleep();
+    // that.getSleep();
     // that.getAlert();
     // that.send(BtCmd.queryRGB());
     // that.getVolume();
     // that.setVolume(8)
-    that.getPauseSleep();
+    // that.getPauseSleep();
 
     // that.send(BtCmd.getClientType());
-    that.send(BtCmd.getIsConnect());
+    // that.send(BtCmd.getIsConnect());
     // that.send(BtCmd.getMac());
 
     // }
@@ -770,6 +770,10 @@ class BtHelper {
   otaCmd(value) {
     this.send(BtCmd.otaCmd(value));
   }
+  // OTA的URL
+  otaUrl(value) {
+    this.send(BtCmd.otaUrl(value));
+  }
   otaData(value, callback) {
     BtHelper.sendCallBack(BtCmd.otaData(value), callback);
   }

+ 8 - 0
devices/cmd_key_event.js

@@ -47,6 +47,7 @@ const EnumCmdEvent = {
     authSleepStatus: 'authSleepStatus',
     btMac: 'btMac',
     otaCmd: 'otaCmd',
+    otaUrl: 'otaUrl',
     wallpaper: 'wallpaper'
 };
 
@@ -124,6 +125,7 @@ class CmdEvent {
         this.btMac = null;
         this.deviceMode = null;
         this.otaCmd = null;
+        this.otaUrl = null;
         this.heiJiaoKind = null;
         this.wallpaper = null;
     }
@@ -338,6 +340,12 @@ class CmdEvent {
         event.heiJiaoKind = kind;
         return event;
     }
+    static otaUrl({ value, kind }) {
+        const event = new CmdEvent({ cmdEvent: EnumCmdEvent.otaUrl });
+        event.otaUrl = value;
+        event.heiJiaoKind = kind;
+        return event;
+    }
     static wallpaper({ value, kind }) {
         const event = new CmdEvent({ cmdEvent: EnumCmdEvent.wallpaper });
         console.log("wallpaper:", value, kind)

+ 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",
@@ -225,18 +226,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);
@@ -467,10 +513,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;
@@ -485,6 +533,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,
+      // });
     }
   },
 
@@ -516,15 +574,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 妙播收音机"}
     }
   },
 
@@ -603,16 +661,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);
     };
@@ -622,6 +681,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;

+ 159 - 75
pages/ota/ota.js

@@ -1,6 +1,7 @@
 const { BtHelper } = require("../../devices/bt_helper");
 import { EnumCmdEvent, CmdEvent } from '../../devices/cmd_key_event';
 import EventManager from '../../utils/event_bus'
+import route_util from '../../utils/route_util';
 // pages/OTA/ota.js
 Page({
 
@@ -57,6 +58,12 @@ Page({
           buttonTips: "更新失败,再试一次"
         });
         break;
+      case 5:
+        this.setData({
+          otaStatus: 4,
+          buttonTips: "更新完成"
+        });
+        break;
       default:
         break;
     }
@@ -78,6 +85,9 @@ Page({
       })
       return;
     }
+    if (this.data.otaStatus != 1 || this.data.otaStatus != 4) {
+      return;
+    }
 
     let _this = this
     wx.showModal({
@@ -91,7 +101,9 @@ Page({
         }
 
         if (res.confirm) {
-          _this.startDownloadFile()
+          _this.sendOtaCmd(1)
+
+          // _this.startDownloadFile()
           // _this.downloadOtaFile(_this.data.otaData.url ?? "")
         }
       }
@@ -100,6 +112,40 @@ Page({
     // btHelper.ota(this.data.otaData.file_url)
 
   },
+  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);
+  },
+
+  // string转换为List<int>
+  string2ListInt(text) {
+    let code = Array.from(text).map(char => char.charCodeAt(0));
+    console.log("string转换为List<int>", code)
+    return code
+  },
+
+  // List<int>转换为string
+  listInt2String(data) {
+    return String.fromCharCode(...data);
+  },
+  // 读取文件废弃代码
   startDownloadFile() {
 
     var urlPath = this.data.otaData.url ?? "";
@@ -113,6 +159,8 @@ Page({
     console.log(list, localFilePath)
 
     let _this = this;
+    _this.setOtaStatus(2);
+
     let localPath = `${wx.env.USER_DATA_PATH}/` + localFilePath
     // 判断文件是否存在
     fs.access({
@@ -125,7 +173,7 @@ Page({
           _this.readFile(localPath);
 
         } else {
-
+          _this.downloadOtaFile(urlPath, localPath)
         }
       }, fail(err) {
         // 文件不存在或其他错误
@@ -149,41 +197,35 @@ Page({
           // 下载成功,保存文件路径
           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);
-          //   }
-          // });
+          fs.rename({
+            oldPath: filePath,
+            newPath: localPath,
+            success: () => {
+              wx.showToast({
+                title: '文件下载成功',
+              });
+              _this.readFile(localPath);
+            },
+            fail: (err) => {
+              _this.setOtaStatus(4);
+
+              wx.showToast({
+                title: '下载文件失败,检查下手机内存吧',
+              });
+              console.error('文件移动失败:', err);
+            }
+          });
         } else {
+          _this.setOtaStatus(4);
           wx.showToast({
             title: '文件下载失败',
           });
         }
       },
       fail: (err) => {
+        _this.setOtaStatus(4);
         wx.showToast({
           title: '文件下载失败',
         });
@@ -202,7 +244,6 @@ Page({
     wx.showLoading({
       title: '开始传输文件',
     })
-    this.setOtaStatus(2);
     const fs = wx.getFileSystemManager();
 
     let _this = this;
@@ -223,18 +264,20 @@ Page({
           title: 'OTA文件下载失败',
         });
         console.error('文件读取失败:', err);
+        _this.setOtaStatus(4);
       }
+
     });
   },
   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()
   },
 
@@ -244,10 +287,10 @@ Page({
 
     if (length === 0) {
       wx.showToast({
-        title: '图片裁剪失败',
+        title: '下载文件失败',
         icon: 'none'
       })
-      _this.endOta(2)
+      _this.sendOtaCmd(2)
       return;
     }
     _this.sendOtaData(this.data._chunks, 0)
@@ -256,7 +299,7 @@ Page({
     let _this = this
 
     if (index >= imageBuffer.length) {
-      _this.endOta(0)
+      _this.sendOtaCmd(0)
       return;
     }
     let chunkSize = 20;
@@ -265,23 +308,29 @@ Page({
     let total = imageBuffer.length
     let next = index + chunkSize;
     const chunk = imageBuffer.slice(index, next);
-    BtHelper.getInstance().wallPaperData(chunk, function (res) {
-      console.log("发送OTA数据:", next)
-      if (res) {
-        _this.updateProgress(next, total);
-
-        _this.sendOtaData(imageBuffer)
-      } else {
-        wx.showModal({
-          title: 'OTA升级失败了',
-          showCancel: false
-        })
-      }
-    })
+    // todo 改成设备wifi下载
+    // BtHelper.getInstance().wallPaperData(chunk, function (res) {
+    //   console.log("发送OTA数据:", next)
+    //   if (res) {
+    //     _this.updateProgress(next, total);
+
+    //     _this.sendOtaData(imageBuffer)
+    //   } else {
+    //     wx.showModal({
+    //       title: 'OTA升级失败了',
+    //       showCancel: false
+    //     })
+    //   }
+    // })
 
   },
-  endOta(value) {
+  sendOtaCmd(value) {
     BtHelper.getInstance().otaCmd(value)
+    if (value == 0) {
+      this.setOtaStatus(0);
+    } else {
+      this.setOtaStatus(4);
+    }
   },
 
   startProgress() {
@@ -308,48 +357,83 @@ Page({
       });
     }
   },
-  /**
-   * 生命周期函数--监听页面加载
-   */
-  onLoad(options) {
-    let param = JSON.parse(options.param)
-    console.log("OTA界面:", param)
-    let otaData = param.otaData
-    let device = param.device
-    this.setData({
-      otaData: otaData,
-      device: device,
-      isShowOta: device.clientType === 'MW-S2(BLE)' || device.clientType === 'MW-S2'
-    })
-
+  addNotification() {
     let _this = this;
     EventManager.addNotification(CmdEvent.eventName, function (event) {
       let name = event.cmdEvent;
-      console.log("OTA页0:", name, EnumCmdEvent.otaCmd, EnumCmdEvent.otaCmd === name)
+      console.log("OTA页0:", event)
+      let kind = event.heiJiaoKind;
 
       switch (name) {
         case EnumCmdEvent.otaCmd:
           let otaCmd = event.otaCmd;
-          let kind = event.heiJiaoKind;
           console.log("OTA页:", otaCmd, kind)
 
           if (otaCmd === 1 && kind == 1) {
             wx.hideLoading();
-            // 开始发送
-            _this.startSendOtaData()
-          } else if (otaCmd === 0 && kind == 1) {
-            // 发送结束
-            _this.endOta(0)
+            // 设备收到开启OTA的回复,发送url
+            _this.sendUrlData()
+          } else if (otaCmd === 2 && kind == 1) {
+            wx.hideLoading();
+            // 去设置wifi界面
+            _this.goToWifi()
+          }
+          else if (otaCmd === 0 && kind == 1) {
+            // 设备回收到url,OTA结束了
+            // _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: '等待设备升级中',
+              showCancel: false
+            })
           } else if (kind == 0) {
             wx.hideLoading()
             wx.showModal({
+              title: 'WIFI连接失败了',
+              showCancel: false
+            })
+          }
+          break;
+        case EnumCmdEvent.otaUrl:
+          let otaUrl = event.otaUrl;
+          if (otaUrl === 1) {
+            // 开始发送url
+            BtHelper.getInstance().wifiUrl(_this.string2ListInt(_this.data.otaData.url))
+          } else {
+            wx.hideLoading()
+            // wifi失败
+            wx.showModal({
               title: 'OTA升级失败了',
               showCancel: false
             })
           }
           break;
       }
-    }, this)
+    }, _this)
+  },
+  /**
+   * 生命周期函数--监听页面加载
+   */
+  onLoad(options) {
+    let param = JSON.parse(options.param)
+    console.log("OTA界面:", param)
+    let otaData = param.otaData
+    let device = param.device
+    this.setData({
+      otaData: otaData,
+      device: device,
+      isShowOta: device.clientType === 'MW-S2(BLE)' || device.clientType === 'MW-S2'
+    })
+    this.addNotification()
   },
   onUnload() {
     EventManager.removeNotification(CmdEvent.eventName, this)

+ 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>

+ 6 - 5
pages/piano/cropper/cropper.js

@@ -94,19 +94,19 @@ Page({
   imageDataToRGB565(rgbaData, width, height) {
     const pixelCount = width * height;
     // 十六进制字符串
-    // const hexString = "04 80 07 3c ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff";
     const hexString = "04 80 07 3c";
 
-
     // 将十六进制字符串转换为字节数组
-    const bytes = hexString.split(' ').map(byte => parseInt(byte, 10));
+    // const bytes = hexString.split(' ').map(byte => parseInt(byte, 10));
+    const bytes = ["04", "80", "07", "3c"];
+
     console.log(bytes);
 
     const outputData = new Uint8Array(pixelCount * 2 + bytes.length); // 文件头 + 每像素 4 字节 (RGB888 + Alpha)
 
     // 将字节数组写入 headerView
     bytes.forEach((byte, index) => {
-      outputData[index] = byte
+      outputData[index] = parseInt(byte, 16)
     });
 
     // 写入像素数据
@@ -238,6 +238,7 @@ Page({
     //   _this.startImage();
     // });
 
+    // 读取裁剪的jpg图片
     const fs = wx.getFileSystemManager();
     this.cropper.getImg((obj) => {
       wx.showLoading({
@@ -447,7 +448,7 @@ Page({
       _this.updateProgress(next, total);
 
       i++;
-    }, 5);
+    }, 30);
   },
   async delay(ms) {
     return new Promise(resolve => setTimeout(resolve, ms));

+ 0 - 38
pages/piano/wallpaper/wallpaper.js

@@ -36,44 +36,6 @@ Page({
   },
   footerTap() {
     route_util.jump("../cropper/cropper")
-    return;
-    const that = this;
-
-    wx.chooseMedia({
-      count: 1,
-      mediaType: ['image'],
-      sourceType: ['album'],
-      // camera: 'back',
-      success(res) {
-        // console.log(res.tempFiles[0].tempFilePath)
-        // console.log(res.tempFiles[0].size)
-        //重置图片角度、缩放、位置
-
-
-        // wx.getImageInfo({
-        //   src: res.tempFiles[0].tempFilePath,
-        //   success(res) {
-        //     console.log(res)
-        //     wx.cropImage({
-        //       src: res.path,// 图片路径
-        //       cropScale: '1:1', // 裁剪比例
-        //       success(res) {
-        //         console.log("裁剪后的图片", res)
-        //         that.setData({
-        //           showCropImg: true,
-        //           topImg: { "pic": res.tempFilePath }
-        //         })
-        //         that.convertImageToRGB565(res.tempFilePath)
-
-        //       },
-
-        //     })
-        //   }
-        // })
-
-      }
-    })
-
   },
 
   imageTap(e) {

+ 172 - 0
pages/setWifi/setWifi.js

@@ -0,0 +1,172 @@
+// pages/setWifi/setWifi.js
+const { BtHelper } = require("../../devices/bt_helper");
+
+Page({
+  data: {
+    wifiName: '',
+    wifiPassword: '',
+    _otaUrl: "",
+  },
+
+  getConnectedWifi: function () {
+    const that = this;
+    wx.getConnectedWifi({
+      success: function (res) {
+        const wifiName = res.wifi.SSID;
+        that.setData({
+          wifiName: wifiName
+        });
+      },
+      fail: function (err) {
+        console.error('获取Wi-Fi信息失败', err);
+        // wx.showToast({
+        //   title: '获取Wi-Fi信息失败',
+        //   icon: 'none'
+        // });
+
+      }
+    });
+  },
+
+  onWifiNameInput: function (e) {
+    this.setData({
+      wifiName: e.detail.value
+    });
+  },
+
+  onWifiPasswordInput: function (e) {
+    this.setData({
+      wifiPassword: e.detail.value
+    });
+  },
+  // string转换为List<int>
+  string2ListInt(text) {
+    let code = Array.from(text).map(char => char.charCodeAt(0));
+    console.log("string转换为List<int>", code)
+    return code
+  },
+  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)
+
+    console.log("发送wifi账号密码:", result.toString());
+    // _ble.send({ cmd: result });
+    BtHelper.getInstance().send(result)
+  },
+
+  onConfirm: function () {
+    const { wifiName, wifiPassword } = this.data;
+    if (!wifiName || !wifiPassword) {
+      wx.showToast({
+        title: '请输入完整的Wi-Fi信息',
+        icon: 'none'
+      });
+      return;
+    }
+    // 这里可以添加进一步的逻辑,比如连接Wi-Fi或保存信息
+    this.sendWiFiInfo(wifiName, wifiPassword);
+  },
+  addNotification() {
+    let _this = this;
+    EventManager.addNotification(CmdEvent.eventName, function (event) {
+      let name = event.cmdEvent;
+      console.log("OTA页0:", event)
+      let kind = event.heiJiaoKind;
+
+      switch (name) {
+        case EnumCmdEvent.otaCmd:
+          let otaCmd = event.otaCmd;
+          console.log("OTA页:", otaCmd, kind)
+
+          if (otaCmd === 1 && kind == 1) {
+            wx.hideLoading();
+            // 设备收到开启OTA的回复,发送url
+            _this.sendUrlData()
+          } else if (otaCmd === 2 && kind == 1) {
+            wx.hideLoading();
+            // 去设置wifi界面
+            _this.goToWifi()
+          }
+          else if (otaCmd === 0 && kind == 1) {
+            // 设备回收到url,OTA结束了
+            // _this.sendOtaCmd(0)
+            wx.hideLoading()
+            wx.showModal({
+              title: '等待设备升级中',
+              showCancel: false
+            })
+          } else if (kind == 0) {
+            wx.hideLoading()
+            wx.showModal({
+              title: 'WIFI连接失败了',
+              showCancel: false
+            })
+          }
+          break;
+        case EnumCmdEvent.otaUrl:
+          let otaUrl = event.otaUrl;
+          if (otaUrl === 1) {
+            // 开始发送url
+            BtHelper.getInstance().otaUrl(_this.string2ListInt(_this.data.otaData.url))
+          } else {
+            wx.hideLoading()
+            // wifi失败
+            wx.showModal({
+              title: 'OTA升级失败了',
+              showCancel: false
+            })
+          }
+          break;
+      }
+    }, _this)
+  },
+  onLoad: function (options) {
+    let param = options.param;
+    let url = JSON.parse(param).url ?? "";
+    this.data._otaUrl = url;
+    this.getConnectedWifi();
+    this.addNotification()
+  },
+  onUnload: function () {
+    EventManager.removeNotification(CmdEvent.eventName)
+  },
+});

+ 3 - 0
pages/setWifi/setWifi.json

@@ -0,0 +1,3 @@
+{
+  "usingComponents": {}
+}

+ 12 - 0
pages/setWifi/setWifi.wxml

@@ -0,0 +1,12 @@
+<!-- pages/setWifi/setWifi.wxml -->
+<view class="container">
+    <view class="input-group">
+        <label class="label">Wi-Fi 名称</label>
+        <input class="input" type="text" placeholder="请输入Wi-Fi名称" value="{{wifiName}}" bindinput="onWifiNameInput" />
+    </view>
+    <view class="input-group">
+        <label class="label">密码</label>
+        <input class="input" type="password" placeholder="请输入密码" value="{{wifiPassword}}" bindinput="onWifiPasswordInput" />
+    </view>
+    <button class="confirm-button" bindtap="onConfirm">确认</button>
+</view>

+ 30 - 0
pages/setWifi/setWifi.wxss

@@ -0,0 +1,30 @@
+/* pages/setWifi/setWifi.wxss */
+/* pages/setWifi/setWifi.wxss */
+.container {
+    padding: 20px;
+}
+
+.input-group {
+    margin-bottom: 15px;
+}
+
+.label {
+    display: block;
+    margin-bottom: 5px;
+}
+
+.input {
+    border: 1px solid #ccc;
+    padding: 10px;
+    width: 100%;
+    box-sizing: border-box;
+}
+
+.confirm-button {
+    background-color: #1aad19;
+    color: white;
+    padding: 10px;
+    border: none;
+    width: 100%;
+    border-radius: 5px;
+}