ota.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. const { BtHelper } = require("../../devices/bt_helper");
  2. import { EnumCmdEvent, CmdEvent } from '../../devices/cmd_key_event';
  3. import EventManager from '../../utils/event_bus'
  4. import route_util from '../../utils/route_util';
  5. import route_constant from '../../utils/route_constant.js';
  6. import { BtCmd } from '../../devices/bluetooth/bt_cmd.js';
  7. import strings from '../../utils/strings.js';
  8. const {
  9. deviceVersion
  10. } = require('../../request/deviceListRequest')
  11. // pages/OTA/ota.js
  12. Page({
  13. /**
  14. * 页面的初始数据
  15. */
  16. data: {
  17. navbarData: {
  18. showCapsule: 1, //
  19. title: '固件信息',
  20. },
  21. device: {},
  22. _otaData: {},
  23. hasNewVersion: false,
  24. progress: 0, // 进度条初始值
  25. otaStatus: 0,
  26. buttonTips: "固件更新",
  27. _chunks: [],
  28. progressPercent: 0,
  29. progress: 0,
  30. progressTextLeft: "0%",
  31. _timer: null,
  32. },
  33. checkOtaVersion(device) {
  34. let _this = this;
  35. device.clientType = "MW-S2"
  36. _this.setData({
  37. device: device,
  38. })
  39. deviceVersion(device.clientType, device.connectType, device.version ?? "1.0.0").then(res => {
  40. console.log("OTA2:", res);
  41. let updateData = res ?? {};
  42. let hasNewVersion = updateData.isEnforcement === 1 || updateData.isEnforcement === 2;
  43. updateData.hasNewVersion = hasNewVersion;
  44. _this.data._otaData = updateData;
  45. _this.setData({
  46. hasNewVersion: hasNewVersion
  47. });
  48. })
  49. },
  50. setOtaStatus(status) {
  51. switch (status) {
  52. case 0:
  53. this.setData({
  54. otaStatus: 0,
  55. buttonTips: "固件更新"
  56. });
  57. break;
  58. case 1:
  59. this.setData({
  60. otaStatus: 1,
  61. buttonTips: "下载升级包"
  62. });
  63. break;
  64. case 2:
  65. this.setData({
  66. otaStatus: 2,
  67. buttonTips: "开始更新"
  68. });
  69. break;
  70. case 3:
  71. this.setData({
  72. otaStatus: 3,
  73. buttonTips: "更新中..."
  74. });
  75. break;
  76. case 4:
  77. this.setData({
  78. otaStatus: 4,
  79. buttonTips: "更新失败,再试一次"
  80. });
  81. break;
  82. case 5:
  83. this.setData({
  84. otaStatus: 4,
  85. buttonTips: "更新完成"
  86. });
  87. break;
  88. default:
  89. break;
  90. }
  91. },
  92. startOtaTap() {
  93. // this.goToWifi()
  94. // return;
  95. let online = this.data.device.state === "online"
  96. if (!online) {
  97. wx.showToast({
  98. title: '设备已经掉线了',
  99. })
  100. return;
  101. }
  102. let hasNewVersion = this.data._otaData.hasNewVersion ?? false
  103. if (!hasNewVersion) {
  104. wx.showToast({
  105. title: '当前已是最新版本',
  106. })
  107. return;
  108. }
  109. if (this.data.otaStatus != 0) {
  110. console.log("没有可升级的固件2")
  111. return;
  112. }
  113. let _this = this
  114. wx.showModal({
  115. title: '有新固件可升级',
  116. content: _this.data._otaData.content ?? '提升体验,操作更流畅',
  117. cancelText: '以后再说',
  118. confirmText: '升级',
  119. complete: (res) => {
  120. if (res.cancel) {
  121. }
  122. if (res.confirm) {
  123. wx.showLoading({
  124. title: '升级设备中,请稍后',
  125. })
  126. _this.sendOtaCmd(1)
  127. // _this.startDownloadFile()
  128. // _this.downloadOtaFile(_this.data._otaData.url ?? "")
  129. }
  130. }
  131. })
  132. // const btHelper = BtHelper.getInstance();
  133. // btHelper.ota(this.data._otaData.file_url)
  134. },
  135. goToWifi() {
  136. route_util.jump(route_constant.setWifi)
  137. },
  138. sendUrlData() {
  139. let url = this.data._otaData.url ?? ""
  140. let codeUrl = BtCmd.stringToUint8Array(url)
  141. BtHelper.getInstance().otaUrl(codeUrl);
  142. },
  143. // 读取文件废弃代码
  144. startDownloadFile() {
  145. var urlPath = this.data._otaData.url ?? "";
  146. var list = urlPath.split("/");
  147. // let cachePath = await PathUtil.getDownloadPath(fileName: list.last ?? 'OTAUpgrade.OTA');
  148. const fs = wx.getFileSystemManager();
  149. // 构建本地文件路径
  150. var localFilePath = list[list.length - 1];
  151. console.log(list, localFilePath)
  152. let _this = this;
  153. _this.setOtaStatus(2);
  154. let localPath = `${wx.env.USER_DATA_PATH}/` + localFilePath
  155. // 判断文件是否存在
  156. fs.access({
  157. path: localPath,
  158. success(res) {
  159. console.log('文件已存在:', res);
  160. if (res) {
  161. // 有文件
  162. _this.readFile(localPath);
  163. } else {
  164. _this.downloadOtaFile(urlPath, localPath)
  165. }
  166. }, fail(err) {
  167. // 文件不存在或其他错误
  168. console.log(err)
  169. // 文件不存在,开始下载
  170. _this.downloadOtaFile(urlPath, localPath)
  171. }
  172. }
  173. );
  174. },
  175. downloadOtaFile(urlPath, localPath) {
  176. let _this = this;
  177. // const fs = wx.getFileSystemManager();
  178. wx.downloadFile({
  179. url: urlPath, // 下载资源的URL
  180. success: (res) => {
  181. console.log('文件下载成功2', res);
  182. if (res.statusCode === 200) {
  183. // 下载成功,保存文件路径
  184. const filePath = res.tempFilePath;
  185. // _this.readFile(filePath);
  186. // 将下载的文件移动到本地路径
  187. fs.rename({
  188. oldPath: filePath,
  189. newPath: localPath,
  190. success: () => {
  191. wx.showToast({
  192. title: '文件下载成功',
  193. });
  194. _this.readFile(localPath);
  195. },
  196. fail: (err) => {
  197. _this.setOtaStatus(4);
  198. wx.showToast({
  199. title: '下载文件失败,检查下手机内存吧',
  200. });
  201. console.error('文件移动失败:', err);
  202. }
  203. });
  204. } else {
  205. _this.setOtaStatus(4);
  206. wx.showToast({
  207. title: '文件下载失败',
  208. });
  209. }
  210. },
  211. fail: (err) => {
  212. _this.setOtaStatus(4);
  213. wx.showToast({
  214. title: '文件下载失败',
  215. });
  216. console.error('下载文件失败:', err);
  217. }
  218. });
  219. },
  220. readFile(localFilePath) {
  221. if (!localFilePath) {
  222. wx.showToast({
  223. title: '下载文件为空',
  224. });
  225. return;
  226. }
  227. wx.showLoading({
  228. title: '开始传输文件',
  229. })
  230. const fs = wx.getFileSystemManager();
  231. let _this = this;
  232. fs.readFile({
  233. filePath: localFilePath,
  234. encoding: 'base64', // 可以选择 'utf8' 或 'base64'
  235. success: (res) => {
  236. // const btHelper = BtHelper.getInstance();
  237. // btHelper.ota(localFilePath);
  238. console.log('文件内容:', res.data.length);
  239. _this.startSend(res.data);
  240. },
  241. fail: (err) => {
  242. wx.showToast({
  243. title: 'OTA文件下载失败',
  244. });
  245. console.error('文件读取失败:', err);
  246. _this.setOtaStatus(4);
  247. }
  248. });
  249. },
  250. startSend(data) {
  251. // const chunkSize = 20; // 每次发送的数据块大小
  252. // const chunks = [];
  253. // for (let i = 0; i < data.length; i += chunkSize) {
  254. // chunks.push(data.slice(i, i + chunkSize));
  255. // }
  256. // this.data._chunks = chunks;
  257. this.sendOtaCmd(1)
  258. // this.startSendOtaData()
  259. },
  260. startSendOtaData() {
  261. let _this = this
  262. let length = this.data._chunks.length
  263. if (length === 0) {
  264. wx.showToast({
  265. title: '下载文件失败',
  266. icon: 'none'
  267. })
  268. _this.sendOtaCmd(2)
  269. return;
  270. }
  271. _this.sendOtaData(this.data._chunks, 0)
  272. // }
  273. }, sendOtaData(imageBuffer, index) {
  274. let _this = this
  275. if (index >= imageBuffer.length) {
  276. _this.sendOtaCmd(0)
  277. return;
  278. }
  279. let chunkSize = 20;
  280. let total = imageBuffer.length
  281. let next = index + chunkSize;
  282. const chunk = imageBuffer.slice(index, next);
  283. // todo 改成设备wifi下载
  284. // BtHelper.getInstance().wallPaperData(chunk, function (res) {
  285. // console.log("发送OTA数据:", next)
  286. // if (res) {
  287. // _this.updateProgress(next, total);
  288. // _this.sendOtaData(imageBuffer)
  289. // } else {
  290. // wx.showModal({
  291. // title: 'OTA升级失败了',
  292. // showCancel: false
  293. // })
  294. // }
  295. // })
  296. },
  297. sendOtaCmd(value) {
  298. BtHelper.getInstance().otaCmd(value)
  299. if (value == 0) {
  300. this.setOtaStatus(0);
  301. } else {
  302. // this.setOtaStatus(4);
  303. }
  304. },
  305. startProgress() {
  306. this.setData({
  307. progress: 0,
  308. showProgress: true
  309. })
  310. },
  311. updateProgress(chunk, total) {
  312. let progress = chunk / total * 100;
  313. let _this = this
  314. if (progress >= 100) {
  315. _this.setData({
  316. progress: 0,
  317. showProgress: false,
  318. // showCropImg: false
  319. });
  320. wx.showToast({
  321. title: '图片上传成功',
  322. })
  323. } else {
  324. _this.setData({
  325. progress: progress,
  326. });
  327. }
  328. },
  329. otaSuccess() {
  330. var pages = getCurrentPages();
  331. var length = pages.length;
  332. var currentPage = pages[length - 1];
  333. console.log("currentPage==", currentPage.route)
  334. if (currentPage.route == "pages/setWifi/setWifi") {
  335. console.log("currentPage==222", currentPage.route)
  336. currentPage.wifiPageSuccess()
  337. }
  338. wx.hideLoading();
  339. // 流程成功
  340. wx.showModal({
  341. title: '设备开始升级中,请等待',
  342. showCancel: false,
  343. success: function (res) {
  344. if (res.confirm) {
  345. route_util.goBackHomePage();
  346. }
  347. }
  348. })
  349. },
  350. otaFailure() {
  351. wx.hideLoading();
  352. // 流程失败
  353. wx.showModal({
  354. title: '设备升级失败了',
  355. showCancel: false,
  356. success: function (res) {
  357. if (res.confirm) {
  358. //
  359. }
  360. }
  361. })
  362. },
  363. addNotification() {
  364. let _this = this;
  365. EventManager.addNotification(CmdEvent.eventName, function (event) {
  366. let name = event.cmdEvent;
  367. let kind = event.heiJiaoKind;
  368. // 74,1,1是wifi连接成功,74,0 2连接wifi失败/没有wifi。
  369. // 发送url给你后,你回:74 0 1是流程成功,74 0 3是流程失败。
  370. let otaCmd = event.otaCmd;
  371. console.log("OTA页:", otaCmd, kind, name)
  372. switch (name) {
  373. case EnumCmdEvent.otaCmd:
  374. if (otaCmd === 1 && kind == 1) {
  375. wx.showLoading({
  376. title: '正在下载ota文件...',
  377. mask: true
  378. });
  379. // 设备收到开启OTA的回复,发送url
  380. _this.sendUrlData()
  381. } else if (otaCmd === 0 && kind == 2) {
  382. wx.hideLoading();
  383. // 去设置wifi界面
  384. _this.goToWifi()
  385. } else if (otaCmd === 0 && kind == 3) {
  386. _this.otaFailure()
  387. } else if (otaCmd === 0 && kind == 1) {
  388. _this.otaSuccess()
  389. }
  390. else if (kind == 0) {
  391. }
  392. break;
  393. case EnumCmdEvent.otaUrl:
  394. // 小程序发:0x75, 0
  395. if (otaCmd === 1 && kind == 1) {
  396. // _this.sendOtaCmd(0)
  397. _this.otaSuccess()
  398. // BtHelper.getInstance().otaUrl(BtCmd.stringToUint8Array(_this.data._otaData.url))
  399. } else if (otaCmd === 0 && kind == 3) {
  400. wx.showModal({
  401. title: 'OTA升级失败,请重启设备再试试吧',
  402. showCancel: false,
  403. success: function (res) {
  404. if (res.confirm) {
  405. console.log('用户点击确定')
  406. }
  407. }
  408. })
  409. } else {
  410. _this.otaFailure()
  411. }
  412. break;
  413. case EnumCmdEvent.otaWifi:
  414. //0x76
  415. wx.hideLoading()
  416. // 0x76, 发送wifi成功
  417. if (otaCmd === 1 && kind == 1) {
  418. wx.showLoading({
  419. title: 'wifi连接成功,正在下载ota文件...',
  420. mask: true
  421. });
  422. _this.sendUrlData()
  423. } else if (otaCmd === 0 && kind == 3) {
  424. wx.showModal({
  425. title: 'OTA升级失败,请重启设备再试试吧',
  426. showCancel: false,
  427. success: function (res) {
  428. if (res.confirm) {
  429. console.log('用户点击确定')
  430. }
  431. }
  432. })
  433. } else {
  434. // wifi失败
  435. _this.otaFailure()
  436. }
  437. break;
  438. case EnumCmdEvent.onoffline:
  439. let state = event.commonValue
  440. if (event.deviceId === _this.data.device.deviceId) {
  441. _this.data.device.state = state
  442. }
  443. wx.hideLoading()
  444. break;
  445. case EnumCmdEvent.version:
  446. _this.data.device.version = event.version;
  447. console.log("OTA1:", event.version)
  448. _this.checkOtaVersion(_this.data.device);
  449. break;
  450. }
  451. }, _this)
  452. },
  453. /**
  454. * 生命周期函数--监听页面加载
  455. */
  456. onLoad(options) {
  457. let param = JSON.parse(options.param)
  458. console.log("OTA界面:", param)
  459. // let otaData = param.otaData
  460. let device = param.device
  461. device.mac = strings.isEmpty(device.mac) ? device.deviceId : device.mac
  462. this.setData({
  463. device: device,
  464. isShowOta: device.clientType === 'MW-S2'
  465. })
  466. const btHelper = BtHelper.getInstance();
  467. let isShowOta = device.clientType === 'MW-S2'
  468. if (isShowOta) {
  469. btHelper.getVersion()
  470. }
  471. this.addNotification()
  472. },
  473. onUnload() {
  474. console.log("移除OTA通知")
  475. EventManager.removeNotification(CmdEvent.eventName, this)
  476. },
  477. })