ota.js 12 KB

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