ota.js 13 KB

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