ota.js 13 KB

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