ota.js 11 KB

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