My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wifi_upload.cpp 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #include "../../../inc/MarlinConfigPre.h"
  23. #if BOTH(HAS_TFT_LVGL_UI, MKS_WIFI_MODULE)
  24. #include "draw_ui.h"
  25. #include "wifi_module.h"
  26. #include "wifi_upload.h"
  27. #include "../../../MarlinCore.h"
  28. #include "../../../sd/cardreader.h"
  29. #define WIFI_SET() WRITE(WIFI_RESET_PIN, HIGH);
  30. #define WIFI_RESET() WRITE(WIFI_RESET_PIN, LOW);
  31. #define WIFI_IO1_SET() WRITE(WIFI_IO1_PIN, HIGH);
  32. #define WIFI_IO1_RESET() WRITE(WIFI_IO1_PIN, LOW);
  33. extern SZ_USART_FIFO WifiRxFifo;
  34. extern int readUsartFifo(SZ_USART_FIFO *fifo, int8_t *buf, int32_t len);
  35. extern int writeUsartFifo(SZ_USART_FIFO * fifo, int8_t * buf, int32_t len);
  36. void esp_port_begin(uint8_t interrupt);
  37. void wifi_delay(int n);
  38. #define ARRAY_SIZE(a) sizeof(a) / sizeof((a)[0])
  39. //typedef signed char bool;
  40. // ESP8266 command codes
  41. const uint8_t ESP_FLASH_BEGIN = 0x02;
  42. const uint8_t ESP_FLASH_DATA = 0x03;
  43. const uint8_t ESP_FLASH_END = 0x04;
  44. const uint8_t ESP_MEM_BEGIN = 0x05;
  45. const uint8_t ESP_MEM_END = 0x06;
  46. const uint8_t ESP_MEM_DATA = 0x07;
  47. const uint8_t ESP_SYNC = 0x08;
  48. const uint8_t ESP_WRITE_REG = 0x09;
  49. const uint8_t ESP_READ_REG = 0x0A;
  50. // MAC address storage locations
  51. const uint32_t ESP_OTP_MAC0 = 0x3FF00050;
  52. const uint32_t ESP_OTP_MAC1 = 0x3FF00054;
  53. const uint32_t ESP_OTP_MAC2 = 0x3FF00058;
  54. const uint32_t ESP_OTP_MAC3 = 0x3FF0005C;
  55. const size_t EspFlashBlockSize = 0x0400; // 1K byte blocks
  56. const uint8_t ESP_IMAGE_MAGIC = 0xE9;
  57. const uint8_t ESP_CHECKSUM_MAGIC = 0xEF;
  58. const uint32_t ESP_ERASE_CHIP_ADDR = 0x40004984; // &SPIEraseChip
  59. const uint32_t ESP_SEND_PACKET_ADDR = 0x40003C80; // &send_packet
  60. const uint32_t ESP_SPI_READ_ADDR = 0x40004B1C; // &SPIRead
  61. const uint32_t ESP_UNKNOWN_ADDR = 0x40001121; // not used
  62. const uint32_t ESP_USER_DATA_RAM_ADDR = 0x3FFE8000; // &user data ram
  63. const uint32_t ESP_IRAM_ADDR = 0x40100000; // instruction RAM
  64. const uint32_t ESP_FLASH_ADDR = 0x40200000; // address of start of Flash
  65. UPLOAD_STRUCT esp_upload;
  66. static const unsigned int retriesPerReset = 3;
  67. static const uint32_t connectAttemptInterval = 50;
  68. static const unsigned int percentToReportIncrement = 5; // how often we report % complete
  69. static const uint32_t defaultTimeout = 500;
  70. static const uint32_t eraseTimeout = 15000;
  71. static const uint32_t blockWriteTimeout = 200;
  72. static const uint32_t blockWriteInterval = 15; // 15ms is long enough, 10ms is mostly too short
  73. static SdFile update_file, *update_curDir;
  74. // Messages corresponding to result codes, should make sense when followed by " error"
  75. const char *resultMessages[] = {
  76. "no",
  77. "timeout",
  78. "comm write",
  79. "connect",
  80. "bad reply",
  81. "file read",
  82. "empty file",
  83. "response header",
  84. "slip frame",
  85. "slip state",
  86. "slip data"
  87. };
  88. // A note on baud rates.
  89. // The ESP8266 supports 921600, 460800, 230400, 115200, 74880 and some lower baud rates.
  90. // 921600b is not reliable because even though it sometimes succeeds in connecting, we get a bad response during uploading after a few blocks.
  91. // Probably our UART ISR cannot receive bytes fast enough, perhaps because of the latency of the system tick ISR.
  92. // 460800b doesn't always manage to connect, but if it does then uploading appears to be reliable.
  93. // 230400b always manages to connect.
  94. static const uint32_t uploadBaudRates[] = { 460800, 230400, 115200, 74880 };
  95. signed char IsReady() {
  96. return esp_upload.state == upload_idle;
  97. }
  98. void uploadPort_write(const uint8_t *buf, const size_t len) {
  99. for (size_t i = 0; i < len; i++)
  100. WIFISERIAL.write(*(buf + i));
  101. }
  102. char uploadPort_read() {
  103. uint8_t retChar;
  104. retChar = WIFISERIAL.read();
  105. return _MAX(retChar, 0);
  106. }
  107. int uploadPort_available() {
  108. return usartFifoAvailable(&WifiRxFifo);
  109. }
  110. void uploadPort_begin() {
  111. esp_port_begin(1);
  112. }
  113. void uploadPort_close() {
  114. //WIFI_COM.end();
  115. //WIFI_COM.begin(115200, true);
  116. esp_port_begin(0);
  117. }
  118. void flushInput() {
  119. while (uploadPort_available() != 0) {
  120. (void)uploadPort_read();
  121. //IWDG_ReloadCounter();
  122. }
  123. }
  124. // Extract 1-4 bytes of a value in little-endian order from a buffer beginning at a specified offset
  125. uint32_t getData(unsigned byteCnt, const uint8_t *buf, int ofst) {
  126. uint32_t val = 0;
  127. if (buf && byteCnt) {
  128. unsigned int shiftCnt = 0;
  129. NOMORE(byteCnt, 4U);
  130. do {
  131. val |= (uint32_t)buf[ofst++] << shiftCnt;
  132. shiftCnt += 8;
  133. } while (--byteCnt);
  134. }
  135. return val;
  136. }
  137. // Put 1-4 bytes of a value in little-endian order into a buffer beginning at a specified offset.
  138. void putData(uint32_t val, unsigned byteCnt, uint8_t *buf, int ofst) {
  139. if (buf && byteCnt) {
  140. NOMORE(byteCnt, 4U);
  141. do {
  142. buf[ofst++] = (uint8_t)(val & 0xFF);
  143. val >>= 8;
  144. } while (--byteCnt);
  145. }
  146. }
  147. // Read a byte optionally performing SLIP decoding. The return values are:
  148. //
  149. // 2 - an escaped byte was read successfully
  150. // 1 - a non-escaped byte was read successfully
  151. // 0 - no data was available
  152. // -1 - the value 0xC0 was encountered (shouldn't happen)
  153. // -2 - a SLIP escape byte was found but the following byte wasn't available
  154. // -3 - a SLIP escape byte was followed by an invalid byte
  155. int ReadByte(uint8_t *data, signed char slipDecode) {
  156. if (uploadPort_available() == 0) return 0;
  157. // At least one byte is available
  158. *data = uploadPort_read();
  159. if (!slipDecode) return 1;
  160. if (*data == 0xC0) return -1; // This shouldn't happen
  161. if (*data != 0xDB) return 1; // If not the SLIP escape, we're done
  162. // SLIP escape, check availability of subsequent byte
  163. if (uploadPort_available() == 0) return -2;
  164. // process the escaped byte
  165. *data = uploadPort_read();
  166. if (*data == 0xDC) { *data = 0xC0; return 2; }
  167. if (*data == 0xDD) { *data = 0xDB; return 2; }
  168. return -3; // invalid
  169. }
  170. // When we write a sync packet, there must be no gaps between most of the characters.
  171. // So use this function, which does a block write to the UART buffer in the latest CoreNG.
  172. void _writePacketRaw(const uint8_t *buf, size_t len) {
  173. uploadPort_write(buf, len);
  174. }
  175. // Write a byte to the serial port optionally SLIP encoding. Return the number of bytes actually written.
  176. void WriteByteRaw(uint8_t b) {
  177. uploadPort_write((const uint8_t *)&b, 1);
  178. }
  179. // Write a byte to the serial port optionally SLIP encoding. Return the number of bytes actually written.
  180. void WriteByteSlip(const uint8_t b) {
  181. if (b == 0xC0) {
  182. WriteByteRaw(0xDB);
  183. WriteByteRaw(0xDC);
  184. }
  185. else if (b == 0xDB) {
  186. WriteByteRaw(0xDB);
  187. WriteByteRaw(0xDD);
  188. }
  189. else
  190. uploadPort_write((const uint8_t *)&b, 1);
  191. }
  192. // Wait for a data packet to be returned. If the body of the packet is
  193. // non-zero length, return an allocated buffer indirectly containing the
  194. // data and return the data length. Note that if the pointer for returning
  195. // the data buffer is nullptr, the response is expected to be two bytes of zero.
  196. //
  197. // If an error occurs, return a negative value. Otherwise, return the number
  198. // of bytes in the response (or zero if the response was not the standard "two bytes of zero").
  199. EspUploadResult readPacket(uint8_t op, uint32_t *valp, size_t *bodyLen, uint32_t msTimeout) {
  200. typedef enum {
  201. begin = 0,
  202. header,
  203. body,
  204. end,
  205. done
  206. } PacketState;
  207. uint8_t resp, opRet;
  208. const size_t headerLength = 8;
  209. uint32_t startTime = getWifiTick();
  210. uint8_t hdr[headerLength];
  211. uint16_t hdrIdx = 0;
  212. uint16_t bodyIdx = 0;
  213. uint8_t respBuf[2];
  214. // wait for the response
  215. uint16_t needBytes = 1;
  216. PacketState state = begin;
  217. *bodyLen = 0;
  218. while (state != done) {
  219. uint8_t c;
  220. EspUploadResult stat;
  221. //IWDG_ReloadCounter();
  222. hal.watchdog_refresh();
  223. if (getWifiTickDiff(startTime, getWifiTick()) > msTimeout)
  224. return timeout;
  225. if (uploadPort_available() < needBytes) {
  226. // insufficient data available
  227. // preferably, return to Spin() here
  228. continue;
  229. }
  230. // sufficient bytes have been received for the current state, process them
  231. switch (state) {
  232. case begin: // expecting frame start
  233. c = uploadPort_read();
  234. if (c != (uint8_t)0xC0) break;
  235. state = header;
  236. needBytes = 2;
  237. break;
  238. case end: // expecting frame end
  239. c = uploadPort_read();
  240. if (c != (uint8_t)0xC0) return slipFrame;
  241. state = done;
  242. break;
  243. case header: // reading an 8-byte header
  244. case body: { // reading the response body
  245. int rslt;
  246. // retrieve a byte with SLIP decoding
  247. rslt = ReadByte(&c, 1);
  248. if (rslt != 1 && rslt != 2) {
  249. // some error occurred
  250. stat = (rslt == 0 || rslt == -2) ? slipData : slipFrame;
  251. return stat;
  252. }
  253. else if (state == header) {
  254. // store the header byte
  255. hdr[hdrIdx++] = c;
  256. if (hdrIdx >= headerLength) {
  257. // get the body length, prepare a buffer for it
  258. *bodyLen = (uint16_t)getData(2, hdr, 2);
  259. // extract the value, if requested
  260. if (valp)
  261. *valp = getData(4, hdr, 4);
  262. if (*bodyLen != 0)
  263. state = body;
  264. else {
  265. needBytes = 1;
  266. state = end;
  267. }
  268. }
  269. }
  270. else {
  271. // Store the response body byte, check for completion
  272. if (bodyIdx < ARRAY_SIZE(respBuf))
  273. respBuf[bodyIdx] = c;
  274. if (++bodyIdx >= *bodyLen) {
  275. needBytes = 1;
  276. state = end;
  277. }
  278. }
  279. } break;
  280. default: return slipState; // this shouldn't happen
  281. }
  282. }
  283. // Extract elements from the header
  284. resp = (uint8_t)getData(1, hdr, 0);
  285. opRet = (uint8_t)getData(1, hdr, 1);
  286. // Sync packets often provoke a response with a zero opcode instead of ESP_SYNC
  287. if (resp != 0x01 || opRet != op) return respHeader;
  288. return success;
  289. }
  290. // Send a block of data performing SLIP encoding of the content.
  291. void _writePacket(const uint8_t *data, size_t len) {
  292. unsigned char outBuf[2048] = {0};
  293. unsigned int outIndex = 0;
  294. while (len != 0) {
  295. if (*data == 0xC0) {
  296. outBuf[outIndex++] = 0xDB;
  297. outBuf[outIndex++] = 0xDC;
  298. }
  299. else if (*data == 0xDB) {
  300. outBuf[outIndex++] = 0xDB;
  301. outBuf[outIndex++] = 0xDD;
  302. }
  303. else {
  304. outBuf[outIndex++] = *data;
  305. }
  306. data++;
  307. --len;
  308. }
  309. uploadPort_write((const uint8_t *)outBuf, outIndex);
  310. }
  311. // Send a packet to the serial port while performing SLIP framing. The packet data comprises a header and an optional data block.
  312. // A SLIP packet begins and ends with 0xC0. The data encapsulated has the bytes
  313. // 0xC0 and 0xDB replaced by the two-byte sequences {0xDB, 0xDC} and {0xDB, 0xDD} respectively.
  314. void writePacket(const uint8_t *hdr, size_t hdrLen, const uint8_t *data, size_t dataLen) {
  315. WriteByteRaw(0xC0); // send the packet start character
  316. _writePacket(hdr, hdrLen); // send the header
  317. _writePacket(data, dataLen); // send the data block
  318. WriteByteRaw(0xC0); // send the packet end character
  319. }
  320. // Send a packet to the serial port while performing SLIP framing. The packet data comprises a header and an optional data block.
  321. // This is like writePacket except that it does a fast block write for both the header and the main data with no SLIP encoding. Used to send sync commands.
  322. void writePacketRaw(const uint8_t *hdr, size_t hdrLen, const uint8_t *data, size_t dataLen) {
  323. WriteByteRaw(0xC0); // send the packet start character
  324. _writePacketRaw(hdr, hdrLen); // send the header
  325. _writePacketRaw(data, dataLen); // send the data block in raw mode
  326. WriteByteRaw(0xC0); // send the packet end character
  327. }
  328. // Send a command to the attached device together with the supplied data, if any.
  329. // The data is supplied via a list of one or more segments.
  330. void sendCommand(uint8_t op, uint32_t checkVal, const uint8_t *data, size_t dataLen) {
  331. // populate the header
  332. uint8_t hdr[8];
  333. putData(0, 1, hdr, 0);
  334. putData(op, 1, hdr, 1);
  335. putData(dataLen, 2, hdr, 2);
  336. putData(checkVal, 4, hdr, 4);
  337. // send the packet
  338. if (op == ESP_SYNC)
  339. writePacketRaw(hdr, sizeof(hdr), data, dataLen);
  340. else
  341. writePacket(hdr, sizeof(hdr), data, dataLen);
  342. }
  343. // Send a command to the attached device together with the supplied data, if any, and get the response
  344. EspUploadResult doCommand(uint8_t op, const uint8_t *data, size_t dataLen, uint32_t checkVal, uint32_t *valp, uint32_t msTimeout) {
  345. size_t bodyLen;
  346. EspUploadResult stat;
  347. sendCommand(op, checkVal, data, dataLen);
  348. stat = readPacket(op, valp, &bodyLen, msTimeout);
  349. if (stat == success && bodyLen != 2)
  350. stat = badReply;
  351. return stat;
  352. }
  353. // Send a synchronising packet to the serial port in an attempt to induce
  354. // the ESP8266 to auto-baud lock on the baud rate.
  355. EspUploadResult Sync(uint16_t timeout) {
  356. uint8_t buf[36];
  357. EspUploadResult stat;
  358. int i;
  359. // compose the data for the sync attempt
  360. memset(buf, 0x55, sizeof(buf));
  361. buf[0] = 0x07;
  362. buf[1] = 0x07;
  363. buf[2] = 0x12;
  364. buf[3] = 0x20;
  365. stat = doCommand(ESP_SYNC, buf, sizeof(buf), 0, 0, timeout);
  366. // If we got a response other than sync, discard it and wait for a sync response. This happens at higher baud rates.
  367. for (i = 0; i < 10 && stat == respHeader; ++i) {
  368. size_t bodyLen;
  369. stat = readPacket(ESP_SYNC, 0, &bodyLen, timeout);
  370. }
  371. if (stat == success) {
  372. // Read and discard additional replies
  373. for (;;) {
  374. size_t bodyLen;
  375. EspUploadResult rc = readPacket(ESP_SYNC, 0, &bodyLen, defaultTimeout);
  376. hal.watchdog_refresh();
  377. if (rc != success || bodyLen != 2) break;
  378. }
  379. }
  380. // DEBUG
  381. //else printf("stat=%d\n", (int)stat);
  382. return stat;
  383. }
  384. // Send a command to the device to begin the Flash process.
  385. EspUploadResult flashBegin(uint32_t addr, uint32_t size) {
  386. // determine the number of blocks represented by the size
  387. uint32_t blkCnt;
  388. uint8_t buf[16];
  389. uint32_t timeout;
  390. blkCnt = (size + EspFlashBlockSize - 1) / EspFlashBlockSize;
  391. // ensure that the address is on a block boundary
  392. addr &= ~(EspFlashBlockSize - 1);
  393. // begin the Flash process
  394. putData(size, 4, buf, 0);
  395. putData(blkCnt, 4, buf, 4);
  396. putData(EspFlashBlockSize, 4, buf, 8);
  397. putData(addr, 4, buf, 12);
  398. timeout = (size != 0) ? eraseTimeout : defaultTimeout;
  399. return doCommand(ESP_FLASH_BEGIN, buf, sizeof(buf), 0, 0, timeout);
  400. }
  401. // Send a command to the device to terminate the Flash process
  402. EspUploadResult flashFinish(signed char reboot) {
  403. uint8_t buf[4];
  404. putData(reboot ? 0 : 1, 4, buf, 0);
  405. return doCommand(ESP_FLASH_END, buf, sizeof(buf), 0, 0, defaultTimeout);
  406. }
  407. // Compute the checksum of a block of data
  408. uint16_t checksum(const uint8_t *data, uint16_t dataLen, uint16_t cksum) {
  409. if (data) while (dataLen--) cksum ^= (uint16_t)*data++;
  410. return cksum;
  411. }
  412. EspUploadResult flashWriteBlock(uint16_t flashParmVal, uint16_t flashParmMask) {
  413. const uint32_t blkSize = EspFlashBlockSize;
  414. int i;
  415. // Allocate a data buffer for the combined header and block data
  416. const uint16_t hdrOfst = 0;
  417. const uint16_t dataOfst = 16;
  418. const uint16_t blkBufSize = dataOfst + blkSize;
  419. uint32_t blkBuf32[blkBufSize/4];
  420. uint8_t * const blkBuf = (uint8_t*)(blkBuf32);
  421. uint32_t cnt;
  422. uint16_t cksum;
  423. EspUploadResult stat;
  424. // Prepare the header for the block
  425. putData(blkSize, 4, blkBuf, hdrOfst + 0);
  426. putData(esp_upload.uploadBlockNumber, 4, blkBuf, hdrOfst + 4);
  427. putData(0, 4, blkBuf, hdrOfst + 8);
  428. putData(0, 4, blkBuf, hdrOfst + 12);
  429. // Get the data for the block
  430. cnt = update_file.read(blkBuf + dataOfst, blkSize); //->Read(reinterpret_cast<char *>(blkBuf + dataOfst), blkSize);
  431. if (cnt != blkSize) {
  432. if (update_file.curPosition() == esp_upload.fileSize) {
  433. // partial last block, fill the remainder
  434. memset(blkBuf + dataOfst + cnt, 0xFF, blkSize - cnt);
  435. }
  436. else
  437. return fileRead;
  438. }
  439. // Patch the flash parameters into the first block if it is loaded at address 0
  440. if (esp_upload.uploadBlockNumber == 0 && esp_upload.uploadAddress == 0 && blkBuf[dataOfst] == ESP_IMAGE_MAGIC && flashParmMask != 0) {
  441. // update the Flash parameters
  442. uint32_t flashParm = getData(2, blkBuf + dataOfst + 2, 0) & ~(uint32_t)flashParmMask;
  443. putData(flashParm | flashParmVal, 2, blkBuf + dataOfst + 2, 0);
  444. }
  445. // Calculate the block checksum
  446. cksum = checksum(blkBuf + dataOfst, blkSize, ESP_CHECKSUM_MAGIC);
  447. for (i = 0; i < 3; i++)
  448. if ((stat = doCommand(ESP_FLASH_DATA, blkBuf, blkBufSize, cksum, 0, blockWriteTimeout)) == success)
  449. break;
  450. return stat;
  451. }
  452. void upload_spin() {
  453. switch (esp_upload.state) {
  454. case resetting:
  455. if (esp_upload.connectAttemptNumber == 9) {
  456. esp_upload.uploadResult = connected;
  457. esp_upload.state = done;
  458. }
  459. else {
  460. uploadPort_begin();
  461. wifi_delay(2000);
  462. flushInput();
  463. esp_upload.lastAttemptTime = esp_upload.lastResetTime = getWifiTick();
  464. esp_upload.state = connecting;
  465. }
  466. break;
  467. case connecting:
  468. if ((getWifiTickDiff(esp_upload.lastAttemptTime, getWifiTick()) >= connectAttemptInterval) && (getWifiTickDiff(esp_upload.lastResetTime, getWifiTick()) >= 500)) {
  469. EspUploadResult res = Sync(5000);
  470. esp_upload.lastAttemptTime = getWifiTick();
  471. if (res == success)
  472. esp_upload.state = erasing;
  473. else {
  474. esp_upload.connectAttemptNumber++;
  475. if (esp_upload.connectAttemptNumber % retriesPerReset == 0)
  476. esp_upload.state = resetting;
  477. }
  478. }
  479. break;
  480. case erasing:
  481. if (getWifiTickDiff(esp_upload.lastAttemptTime, getWifiTick()) >= blockWriteInterval) {
  482. uint32_t eraseSize;
  483. const uint32_t sectorsPerBlock = 16;
  484. const uint32_t sectorSize = 4096;
  485. const uint32_t numSectors = (esp_upload.fileSize + sectorSize - 1)/sectorSize;
  486. const uint32_t startSector = esp_upload.uploadAddress/sectorSize;
  487. uint32_t headSectors = sectorsPerBlock - (startSector % sectorsPerBlock);
  488. NOMORE(headSectors, numSectors);
  489. eraseSize = (numSectors < 2 * headSectors)
  490. ? (numSectors + 1) / 2 * sectorSize
  491. : (numSectors - headSectors) * sectorSize;
  492. esp_upload.uploadResult = flashBegin(esp_upload.uploadAddress, eraseSize);
  493. if (esp_upload.uploadResult == success) {
  494. esp_upload.uploadBlockNumber = 0;
  495. esp_upload.uploadNextPercentToReport = percentToReportIncrement;
  496. esp_upload.lastAttemptTime = getWifiTick();
  497. esp_upload.state = uploading;
  498. }
  499. else
  500. esp_upload.state = done;
  501. }
  502. break;
  503. case uploading:
  504. // The ESP needs several milliseconds to recover from one packet before it will accept another
  505. if (getWifiTickDiff(esp_upload.lastAttemptTime, getWifiTick()) >= 15) {
  506. unsigned int percentComplete;
  507. const uint32_t blkCnt = (esp_upload.fileSize + EspFlashBlockSize - 1) / EspFlashBlockSize;
  508. if (esp_upload.uploadBlockNumber < blkCnt) {
  509. esp_upload.uploadResult = flashWriteBlock(0, 0);
  510. esp_upload.lastAttemptTime = getWifiTick();
  511. if (esp_upload.uploadResult != success)
  512. esp_upload.state = done;
  513. percentComplete = (100 * esp_upload.uploadBlockNumber)/blkCnt;
  514. ++esp_upload.uploadBlockNumber;
  515. if (percentComplete >= esp_upload.uploadNextPercentToReport)
  516. esp_upload.uploadNextPercentToReport += percentToReportIncrement;
  517. }
  518. else
  519. esp_upload.state = done;
  520. }
  521. break;
  522. case done:
  523. update_file.close();
  524. esp_upload.state = upload_idle;
  525. break;
  526. default: break;
  527. }
  528. }
  529. // Try to upload the given file at the given address
  530. void SendUpdateFile(const char *file, uint32_t address) {
  531. const char * const fname = card.diveToFile(false, update_curDir, ESP_FIRMWARE_FILE);
  532. if (!update_file.open(update_curDir, fname, O_READ)) return;
  533. esp_upload.fileSize = update_file.fileSize();
  534. if (esp_upload.fileSize == 0) {
  535. update_file.close();
  536. return;
  537. }
  538. esp_upload.uploadAddress = address;
  539. esp_upload.connectAttemptNumber = 0;
  540. esp_upload.state = resetting;
  541. }
  542. static const uint32_t FirmwareAddress = 0x00000000, WebFilesAddress = 0x00100000;
  543. void ResetWiFiForUpload(int begin_or_end) {
  544. //#if 0
  545. uint32_t start = getWifiTick();
  546. if (begin_or_end == 0) {
  547. SET_OUTPUT(WIFI_IO0_PIN);
  548. WRITE(WIFI_IO0_PIN, LOW);
  549. }
  550. else
  551. SET_INPUT_PULLUP(WIFI_IO0_PIN);
  552. WIFI_RESET();
  553. while (getWifiTickDiff(start, getWifiTick()) < 500) { /* nada */ }
  554. WIFI_SET();
  555. //#endif
  556. }
  557. int32_t wifi_upload(int type) {
  558. esp_upload.retriesPerBaudRate = 9;
  559. ResetWiFiForUpload(0);
  560. switch (type) {
  561. case 0: SendUpdateFile(ESP_FIRMWARE_FILE, FirmwareAddress); break;
  562. case 1: SendUpdateFile(ESP_WEB_FIRMWARE_FILE, FirmwareAddress); break;
  563. case 2: SendUpdateFile(ESP_WEB_FILE, WebFilesAddress); break;
  564. default: return -1;
  565. }
  566. while (esp_upload.state != upload_idle) {
  567. upload_spin();
  568. hal.watchdog_refresh();
  569. }
  570. ResetWiFiForUpload(1);
  571. return esp_upload.uploadResult == success ? 0 : -1;
  572. }
  573. #endif // HAS_TFT_LVGL_UI && MKS_WIFI_MODULE