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_module.cpp 64KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  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 "SPI_TFT.h"
  28. #include "../../marlinui.h"
  29. #include "../../../MarlinCore.h"
  30. #include "../../../module/temperature.h"
  31. #include "../../../gcode/queue.h"
  32. #include "../../../gcode/gcode.h"
  33. #include "../../../sd/cardreader.h"
  34. #include "../../../module/planner.h"
  35. #include "../../../module/servo.h"
  36. #include "../../../module/probe.h"
  37. #if DISABLED(EMERGENCY_PARSER)
  38. #include "../../../module/motion.h"
  39. #endif
  40. #if ENABLED(POWER_LOSS_RECOVERY)
  41. #include "../../../feature/powerloss.h"
  42. #endif
  43. #if ENABLED(PARK_HEAD_ON_PAUSE)
  44. #include "../../../feature/pause.h"
  45. #endif
  46. #define WIFI_SET() WRITE(WIFI_RESET_PIN, HIGH);
  47. #define WIFI_RESET() WRITE(WIFI_RESET_PIN, LOW);
  48. #define WIFI_IO1_SET() WRITE(WIFI_IO1_PIN, HIGH);
  49. #define WIFI_IO1_RESET() WRITE(WIFI_IO1_PIN, LOW);
  50. extern uint8_t Explore_Disk(char *path, uint8_t recu_level);
  51. extern uint8_t commands_in_queue;
  52. extern uint8_t sel_id;
  53. extern unsigned int getTickDiff(unsigned int curTick, unsigned int lastTick);
  54. volatile SZ_USART_FIFO WifiRxFifo;
  55. #define WAIT_ESP_TRANS_TIMEOUT_TICK 10500
  56. int cfg_cloud_flag = 0;
  57. extern PRINT_TIME print_time;
  58. char wifi_firm_ver[20] = { 0 };
  59. WIFI_GCODE_BUFFER espGcodeFifo;
  60. extern uint8_t pause_resum;
  61. uint8_t wifi_connect_flg = 0;
  62. extern volatile uint8_t get_temp_flag;
  63. #define WIFI_MODE 2
  64. #define WIFI_AP_MODE 3
  65. int upload_result = 0;
  66. uint32_t upload_time_sec = 0;
  67. uint32_t upload_size = 0;
  68. volatile WIFI_STATE wifi_link_state;
  69. WIFI_PARA wifiPara;
  70. IP_PARA ipPara;
  71. CLOUD_PARA cloud_para;
  72. char wifi_check_time = 0;
  73. extern uint8_t gCurDir[100];
  74. extern uint32_t wifi_loop_cycle;
  75. volatile TRANSFER_STATE esp_state;
  76. uint8_t left_to_send = 0;
  77. uint8_t left_to_save[96] = { 0 };
  78. volatile WIFI_DMA_RCV_FIFO wifiDmaRcvFifo;
  79. volatile WIFI_TRANS_ERROR wifiTransError;
  80. static bool need_ok_later = false;
  81. extern volatile WIFI_STATE wifi_link_state;
  82. extern WIFI_PARA wifiPara;
  83. extern IP_PARA ipPara;
  84. extern CLOUD_PARA cloud_para;
  85. extern bool once_flag, flash_preview_begin, default_preview_flg, gcode_preview_over;
  86. extern bool flash_dma_mode;
  87. uint32_t getWifiTick() { return millis(); }
  88. uint32_t getWifiTickDiff(int32_t lastTick, int32_t curTick) {
  89. return (lastTick <= curTick ? curTick - lastTick : 0xFFFFFFFF - lastTick + curTick) * TICK_CYCLE;
  90. }
  91. void wifi_delay(int n) {
  92. const uint32_t start = getWifiTick();
  93. while (getWifiTickDiff(start, getWifiTick()) < (uint32_t)n)
  94. watchdog_refresh();
  95. }
  96. void wifi_reset() {
  97. uint32_t start = getWifiTick();
  98. WIFI_RESET();
  99. while (getWifiTickDiff(start, getWifiTick()) < 500) { /* nada */ }
  100. WIFI_SET();
  101. }
  102. void mount_file_sys(uint8_t disk_type) {
  103. if (disk_type == FILE_SYS_SD) {
  104. TERN_(SDSUPPORT, card.mount());
  105. }
  106. else if (disk_type == FILE_SYS_USB) {
  107. }
  108. }
  109. static bool longName2DosName(const char *longName, char *dosName) {
  110. uint8_t i = FILENAME_LENGTH;
  111. while (i) dosName[--i] = '\0';
  112. while (*longName) {
  113. uint8_t c = *longName++;
  114. if (c == '.') { // For a dot...
  115. if (i == 0) return false;
  116. strcat_P(dosName, PSTR(".GCO"));
  117. return dosName[0] != '\0';
  118. }
  119. else {
  120. // Fail for illegal characters
  121. PGM_P p = PSTR("|<>^+=?/[];,*\"\\");
  122. while (uint8_t b = pgm_read_byte(p++)) if (b == c) return false;
  123. if (c < 0x21 || c == 0x7F) return false; // Check size, non-printable characters
  124. dosName[i++] = (c < 'a' || c > 'z') ? (c) : (c + ('A' - 'a')); // Uppercase required for 8.3 name
  125. }
  126. if (i >= 5) {
  127. strcat_P(dosName, PSTR("~1.GCO"));
  128. return dosName[0] != '\0';
  129. }
  130. }
  131. return dosName[0] != '\0'; // Return true if any name was set
  132. }
  133. #ifdef __STM32F1__
  134. #include <libmaple/timer.h>
  135. #include <libmaple/util.h>
  136. #include <libmaple/rcc.h>
  137. #include <boards.h>
  138. #include <wirish.h>
  139. #include <libmaple/dma.h>
  140. #include <libmaple/bitband.h>
  141. #include <libmaple/libmaple.h>
  142. #include <libmaple/gpio.h>
  143. #include <libmaple/usart.h>
  144. #include <libmaple/ring_buffer.h>
  145. void changeFlashMode(const bool dmaMode) {
  146. if (flash_dma_mode != dmaMode) {
  147. flash_dma_mode = dmaMode;
  148. if (!flash_dma_mode) {
  149. dma_disable(DMA1, DMA_CH5);
  150. dma_clear_isr_bits(DMA1, DMA_CH4);
  151. }
  152. }
  153. }
  154. static int storeRcvData(volatile uint8_t *bufToCpy, int32_t len) {
  155. unsigned char tmpW = wifiDmaRcvFifo.write_cur;
  156. if (len > UDISKBUFLEN) return 0;
  157. if (wifiDmaRcvFifo.state[tmpW] == udisk_buf_empty) {
  158. memcpy((unsigned char *) wifiDmaRcvFifo.bufferAddr[tmpW], (uint8_t *)bufToCpy, len);
  159. wifiDmaRcvFifo.state[tmpW] = udisk_buf_full;
  160. wifiDmaRcvFifo.write_cur = (tmpW + 1) % TRANS_RCV_FIFO_BLOCK_NUM;
  161. return 1;
  162. }
  163. return 0;
  164. }
  165. static void esp_dma_pre() {
  166. dma_channel_reg_map *channel_regs = dma_tube_regs(DMA1, DMA_CH5);
  167. CBI32(channel_regs->CCR, 0);
  168. channel_regs->CMAR = (uint32_t)WIFISERIAL.usart_device->rb->buf;
  169. channel_regs->CNDTR = 0x0000;
  170. channel_regs->CNDTR = UART_RX_BUFFER_SIZE;
  171. DMA1->regs->IFCR = 0xF0000;
  172. SBI32(channel_regs->CCR, 0);
  173. }
  174. static void dma_ch5_irq_handle() {
  175. uint8 status_bits = dma_get_isr_bits(DMA1, DMA_CH5);
  176. dma_clear_isr_bits(DMA1, DMA_CH5);
  177. if (status_bits & 0x8) {
  178. // DMA transmit Error
  179. }
  180. else if (status_bits & 0x2) {
  181. // DMA transmit complete
  182. if (esp_state == TRANSFER_IDLE)
  183. esp_state = TRANSFERRING;
  184. if (storeRcvData(WIFISERIAL.usart_device->rb->buf, UART_RX_BUFFER_SIZE)) {
  185. esp_dma_pre();
  186. if (wifiTransError.flag != 0x1)
  187. WIFI_IO1_RESET();
  188. }
  189. else {
  190. WIFI_IO1_SET();
  191. esp_state = TRANSFER_STORE;
  192. }
  193. }
  194. else if (status_bits & 0x4) {
  195. // DMA transmit half
  196. WIFI_IO1_SET();
  197. }
  198. }
  199. static void wifi_usart_dma_init() {
  200. dma_init(DMA1);
  201. uint32_t flags = ( DMA_MINC_MODE | DMA_TRNS_CMPLT | DMA_HALF_TRNS | DMA_TRNS_ERR);
  202. dma_xfer_size dma_bit_size = DMA_SIZE_8BITS;
  203. dma_setup_transfer(DMA1, DMA_CH5, &USART1_BASE->DR, dma_bit_size,
  204. (volatile void*)WIFISERIAL.usart_device->rb->buf, dma_bit_size, flags);// Transmit buffer DMA
  205. dma_set_priority(DMA1, DMA_CH5, DMA_PRIORITY_LOW);
  206. dma_attach_interrupt(DMA1, DMA_CH5, &dma_ch5_irq_handle);
  207. dma_clear_isr_bits(DMA1, DMA_CH5);
  208. dma_set_num_transfers(DMA1, DMA_CH5, UART_RX_BUFFER_SIZE);
  209. bb_peri_set_bit(&USART1_BASE->CR3, USART_CR3_DMAR_BIT, 1);
  210. dma_enable(DMA1, DMA_CH5); // enable transmit
  211. for (uint8_t i = 0; i < TRANS_RCV_FIFO_BLOCK_NUM; i++) {
  212. wifiDmaRcvFifo.bufferAddr[i] = &bmp_public_buf[1024 * i];
  213. wifiDmaRcvFifo.state[i] = udisk_buf_empty;
  214. }
  215. memset(wifiDmaRcvFifo.bufferAddr[0], 0, 1024 * TRANS_RCV_FIFO_BLOCK_NUM);
  216. wifiDmaRcvFifo.read_cur = 0;
  217. wifiDmaRcvFifo.write_cur = 0;
  218. }
  219. void esp_port_begin(uint8_t interrupt) {
  220. WifiRxFifo.uart_read_point = 0;
  221. WifiRxFifo.uart_write_point = 0;
  222. #if ENABLED(MKS_WIFI_MODULE)
  223. if (interrupt) {
  224. WIFISERIAL.end();
  225. for (uint16_t i = 0; i < 65535; i++) { /*nada*/ }
  226. WIFISERIAL.begin(WIFI_BAUDRATE);
  227. millis_t serial_connect_timeout = millis() + 1000UL;
  228. while (PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
  229. }
  230. else {
  231. WIFISERIAL.end();
  232. WIFISERIAL.usart_device->regs->CR1 &= ~USART_CR1_RXNEIE;
  233. WIFISERIAL.begin(WIFI_UPLOAD_BAUDRATE);
  234. wifi_usart_dma_init();
  235. }
  236. #endif
  237. }
  238. #else // !__STM32F1__
  239. DMA_HandleTypeDef wifiUsartDMArx;
  240. void changeFlashMode(const bool dmaMode) {
  241. if (flash_dma_mode != dmaMode) {
  242. flash_dma_mode = dmaMode;
  243. if (flash_dma_mode == 1) {
  244. }
  245. else {
  246. }
  247. }
  248. }
  249. #ifdef STM32F1xx
  250. HAL_StatusTypeDef HAL_DMA_PollForTransferCustomize(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout) {
  251. uint32_t temp;
  252. uint32_t tickstart = 0U;
  253. if (HAL_DMA_STATE_BUSY != hdma->State) { // No transfer ongoing
  254. hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER;
  255. __HAL_UNLOCK(hdma);
  256. return HAL_ERROR;
  257. }
  258. // Polling mode not supported in circular mode
  259. if (RESET != (hdma->Instance->CCR & DMA_CCR_CIRC)) {
  260. hdma->ErrorCode = HAL_DMA_ERROR_NOT_SUPPORTED;
  261. return HAL_ERROR;
  262. }
  263. // Get the level transfer complete flag
  264. temp = (CompleteLevel == HAL_DMA_FULL_TRANSFER
  265. ? __HAL_DMA_GET_TC_FLAG_INDEX(hdma) // Transfer Complete flag
  266. : __HAL_DMA_GET_HT_FLAG_INDEX(hdma) // Half Transfer Complete flag
  267. );
  268. // Get tick
  269. tickstart = HAL_GetTick();
  270. while (__HAL_DMA_GET_FLAG(hdma, temp) == RESET) {
  271. if ((__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)) != RESET)) {
  272. __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); // Clear the half transfer complete flag
  273. WIFI_IO1_SET();
  274. }
  275. if ((__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET)) {
  276. /**
  277. * When a DMA transfer error occurs
  278. * A hardware clear of its EN bits is performed
  279. * Clear all flags
  280. */
  281. hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << hdma->ChannelIndex);
  282. SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_TE); // Update error code
  283. hdma->State = HAL_DMA_STATE_READY; // Change the DMA state
  284. __HAL_UNLOCK(hdma); // Process Unlocked
  285. return HAL_ERROR;
  286. }
  287. // Check for the Timeout
  288. if (Timeout != HAL_MAX_DELAY && (!Timeout || (HAL_GetTick() - tickstart) > Timeout)) {
  289. SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_TIMEOUT); // Update error code
  290. hdma->State = HAL_DMA_STATE_READY; // Change the DMA state
  291. __HAL_UNLOCK(hdma); // Process Unlocked
  292. return HAL_ERROR;
  293. }
  294. }
  295. if (CompleteLevel == HAL_DMA_FULL_TRANSFER) {
  296. // Clear the transfer complete flag
  297. __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
  298. /* The selected Channelx EN bit is cleared (DMA is disabled and
  299. all transfers are complete) */
  300. hdma->State = HAL_DMA_STATE_READY;
  301. }
  302. else
  303. __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); // Clear the half transfer complete flag
  304. __HAL_UNLOCK(hdma); // Process unlocked
  305. return HAL_OK;
  306. }
  307. #else // !STM32F1xx
  308. typedef struct {
  309. __IO uint32_t ISR; //!< DMA interrupt status register
  310. __IO uint32_t Reserved0;
  311. __IO uint32_t IFCR; //!< DMA interrupt flag clear register
  312. } MYDMA_Base_Registers;
  313. HAL_StatusTypeDef HAL_DMA_PollForTransferCustomize(DMA_HandleTypeDef *hdma, HAL_DMA_LevelCompleteTypeDef CompleteLevel, uint32_t Timeout) {
  314. HAL_StatusTypeDef status = HAL_OK;
  315. uint32_t mask_cpltlevel;
  316. uint32_t tickstart = HAL_GetTick();
  317. uint32_t tmpisr;
  318. MYDMA_Base_Registers *regs; // Calculate DMA base and stream number
  319. if (HAL_DMA_STATE_BUSY != hdma->State) { // No transfer ongoing
  320. hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER;
  321. __HAL_UNLOCK(hdma);
  322. return HAL_ERROR;
  323. }
  324. // Polling mode not supported in circular mode and double buffering mode
  325. if ((hdma->Instance->CR & DMA_SxCR_CIRC) != RESET) {
  326. hdma->ErrorCode = HAL_DMA_ERROR_NOT_SUPPORTED;
  327. return HAL_ERROR;
  328. }
  329. // Get the level transfer complete flag
  330. mask_cpltlevel = (CompleteLevel == HAL_DMA_FULL_TRANSFER
  331. ? DMA_FLAG_TCIF0_4 << hdma->StreamIndex // Transfer Complete flag
  332. : DMA_FLAG_HTIF0_4 << hdma->StreamIndex // Half Transfer Complete flag
  333. );
  334. regs = (MYDMA_Base_Registers *)hdma->StreamBaseAddress;
  335. tmpisr = regs->ISR;
  336. while (((tmpisr & mask_cpltlevel) == RESET) && ((hdma->ErrorCode & HAL_DMA_ERROR_TE) == RESET)) {
  337. // Check for the Timeout (Not applicable in circular mode)
  338. if (Timeout != HAL_MAX_DELAY) {
  339. if (!Timeout || (HAL_GetTick() - tickstart) > Timeout) {
  340. hdma->ErrorCode = HAL_DMA_ERROR_TIMEOUT; // Update error code
  341. __HAL_UNLOCK(hdma); // Process Unlocked
  342. hdma->State = HAL_DMA_STATE_READY; // Change the DMA state
  343. return HAL_TIMEOUT;
  344. }
  345. }
  346. tmpisr = regs->ISR; // Get the ISR register value
  347. if ((tmpisr & (DMA_FLAG_HTIF0_4 << hdma->StreamIndex)) != RESET) {
  348. regs->IFCR = DMA_FLAG_HTIF0_4 << hdma->StreamIndex; // Clear the Direct Mode error flag
  349. WIFI_IO1_SET();
  350. }
  351. if ((tmpisr & (DMA_FLAG_TEIF0_4 << hdma->StreamIndex)) != RESET) {
  352. hdma->ErrorCode |= HAL_DMA_ERROR_TE; // Update error code
  353. regs->IFCR = DMA_FLAG_TEIF0_4 << hdma->StreamIndex; // Clear the transfer error flag
  354. }
  355. if ((tmpisr & (DMA_FLAG_FEIF0_4 << hdma->StreamIndex)) != RESET) {
  356. hdma->ErrorCode |= HAL_DMA_ERROR_FE; // Update error code
  357. regs->IFCR = DMA_FLAG_FEIF0_4 << hdma->StreamIndex; // Clear the FIFO error flag
  358. }
  359. if ((tmpisr & (DMA_FLAG_DMEIF0_4 << hdma->StreamIndex)) != RESET) {
  360. hdma->ErrorCode |= HAL_DMA_ERROR_DME; // Update error code
  361. regs->IFCR = DMA_FLAG_DMEIF0_4 << hdma->StreamIndex; // Clear the Direct Mode error flag
  362. }
  363. }
  364. if (hdma->ErrorCode != HAL_DMA_ERROR_NONE && (hdma->ErrorCode & HAL_DMA_ERROR_TE) != RESET) {
  365. HAL_DMA_Abort(hdma);
  366. regs->IFCR = (DMA_FLAG_HTIF0_4 | DMA_FLAG_TCIF0_4) << hdma->StreamIndex; // Clear the half transfer and transfer complete flags
  367. __HAL_UNLOCK(hdma); // Process Unlocked
  368. hdma->State= HAL_DMA_STATE_READY; // Change the DMA state
  369. return HAL_ERROR;
  370. }
  371. // Get the level transfer complete flag
  372. if (CompleteLevel == HAL_DMA_FULL_TRANSFER) {
  373. regs->IFCR = (DMA_FLAG_HTIF0_4 | DMA_FLAG_TCIF0_4) << hdma->StreamIndex; // Clear the half transfer and transfer complete flags
  374. __HAL_UNLOCK(hdma); // Process Unlocked
  375. hdma->State = HAL_DMA_STATE_READY;
  376. }
  377. else
  378. regs->IFCR = (DMA_FLAG_HTIF0_4) << hdma->StreamIndex; // Clear the half transfer and transfer complete flags
  379. return status;
  380. }
  381. #endif
  382. static void dmaTransmitBegin() {
  383. wifiUsartDMArx.Init.MemInc = DMA_MINC_ENABLE;
  384. if (HAL_DMA_Init((DMA_HandleTypeDef *)&wifiUsartDMArx) != HAL_OK)
  385. Error_Handler();
  386. if (HAL_DMA_Start(&wifiUsartDMArx, (uint32_t)&(USART1->DR), (uint32_t)WIFISERIAL.wifiRxBuf, UART_RX_BUFFER_SIZE))
  387. Error_Handler();
  388. USART1->CR1 |= USART_CR1_UE;
  389. SET_BIT(USART1->CR3, USART_CR3_DMAR);
  390. WIFI_IO1_RESET();
  391. }
  392. static int storeRcvData(volatile uint8_t *bufToCpy, int32_t len) {
  393. unsigned char tmpW = wifiDmaRcvFifo.write_cur;
  394. if (len > UDISKBUFLEN) return 0;
  395. if (wifiDmaRcvFifo.state[tmpW] == udisk_buf_empty) {
  396. const int timeOut = 2000; // millisecond
  397. dmaTransmitBegin();
  398. if (HAL_DMA_PollForTransferCustomize(&wifiUsartDMArx, HAL_DMA_FULL_TRANSFER, timeOut) == HAL_OK) {
  399. memcpy((unsigned char *) wifiDmaRcvFifo.bufferAddr[tmpW], (uint8_t *)bufToCpy, len);
  400. wifiDmaRcvFifo.state[tmpW] = udisk_buf_full;
  401. wifiDmaRcvFifo.write_cur = (tmpW + 1) % TRANS_RCV_FIFO_BLOCK_NUM;
  402. return 1;
  403. }
  404. }
  405. return 0;
  406. }
  407. static void wifi_usart_dma_init() {
  408. #ifdef STM32F1xx
  409. __HAL_RCC_DMA1_CLK_ENABLE();
  410. wifiUsartDMArx.Instance = DMA1_Channel5;
  411. #else
  412. __HAL_RCC_DMA2_CLK_ENABLE();
  413. wifiUsartDMArx.Instance = DMA2_Stream2;
  414. wifiUsartDMArx.Init.Channel = DMA_CHANNEL_4;
  415. #endif
  416. wifiUsartDMArx.Init.Direction = DMA_PERIPH_TO_MEMORY;
  417. wifiUsartDMArx.Init.PeriphInc = DMA_PINC_DISABLE;
  418. wifiUsartDMArx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
  419. wifiUsartDMArx.Init.MemDataAlignment = DMA_PDATAALIGN_BYTE;
  420. wifiUsartDMArx.Init.Mode = DMA_NORMAL;
  421. #ifdef STM32F4xx
  422. wifiUsartDMArx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
  423. #endif
  424. wifiUsartDMArx.Init.MemInc = DMA_MINC_ENABLE;
  425. if (HAL_DMA_Init((DMA_HandleTypeDef *)&wifiUsartDMArx) != HAL_OK)
  426. Error_Handler();
  427. if (HAL_DMA_Start(&wifiUsartDMArx, (uint32_t)&(USART1->DR), (uint32_t)WIFISERIAL.wifiRxBuf, UART_RX_BUFFER_SIZE))
  428. Error_Handler();
  429. USART1->CR1 |= USART_CR1_UE;
  430. SET_BIT(USART1->CR3, USART_CR3_DMAR); // Enable Rx DMA Request
  431. for (uint8_t i = 0; i < TRANS_RCV_FIFO_BLOCK_NUM; i++) {
  432. wifiDmaRcvFifo.bufferAddr[i] = &bmp_public_buf[1024 * i];
  433. wifiDmaRcvFifo.state[i] = udisk_buf_empty;
  434. }
  435. memset(wifiDmaRcvFifo.bufferAddr[0], 0, 1024 * TRANS_RCV_FIFO_BLOCK_NUM);
  436. wifiDmaRcvFifo.read_cur = 0;
  437. wifiDmaRcvFifo.write_cur = 0;
  438. }
  439. void esp_port_begin(uint8_t interrupt) {
  440. WifiRxFifo.uart_read_point = 0;
  441. WifiRxFifo.uart_write_point = 0;
  442. #if ENABLED(MKS_WIFI_MODULE)
  443. if (interrupt) {
  444. WIFISERIAL.end();
  445. for (uint16_t i = 0; i < 65535; i++) { /*nada*/ }
  446. WIFISERIAL.begin(WIFI_BAUDRATE);
  447. uint32_t serial_connect_timeout = millis() + 1000UL;
  448. while (PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
  449. }
  450. else {
  451. WIFISERIAL.end();
  452. USART1->CR1 &= ~USART_CR1_RXNEIE;
  453. WIFISERIAL.begin(WIFI_UPLOAD_BAUDRATE);
  454. wifi_usart_dma_init();
  455. }
  456. #endif
  457. }
  458. #endif // !__STM32F1__
  459. #if ENABLED(MKS_WIFI_MODULE)
  460. int raw_send_to_wifi(uint8_t *buf, int len) {
  461. if (buf == 0 || len <= 0) return 0;
  462. for (int i = 0; i < len; i++) WIFISERIAL.write(*(buf + i));
  463. return len;
  464. }
  465. #endif
  466. void wifi_ret_ack() {}
  467. uint8_t buf_to_wifi[256];
  468. int index_to_wifi = 0;
  469. int package_to_wifi(WIFI_RET_TYPE type, uint8_t *buf, int len) {
  470. uint8_t wifi_ret_head = 0xA5;
  471. uint8_t wifi_ret_tail = 0xFC;
  472. if (type == WIFI_PARA_SET) {
  473. int data_offset = 4,
  474. apLen = strlen((const char *)uiCfg.wifi_name),
  475. keyLen = strlen((const char *)uiCfg.wifi_key);
  476. ZERO(buf_to_wifi);
  477. index_to_wifi = 0;
  478. buf_to_wifi[data_offset] = gCfgItems.wifi_mode_sel;
  479. buf_to_wifi[data_offset + 1] = apLen;
  480. memcpy(&buf_to_wifi[data_offset + 2], (const char *)uiCfg.wifi_name, apLen);
  481. buf_to_wifi[data_offset + apLen + 2] = keyLen;
  482. memcpy(&buf_to_wifi[data_offset + apLen + 3], (const char *)uiCfg.wifi_key, keyLen);
  483. buf_to_wifi[data_offset + apLen + keyLen + 3] = wifi_ret_tail;
  484. index_to_wifi = apLen + keyLen + 3;
  485. buf_to_wifi[0] = wifi_ret_head;
  486. buf_to_wifi[1] = type;
  487. buf_to_wifi[2] = index_to_wifi & 0xFF;
  488. buf_to_wifi[3] = (index_to_wifi >> 8) & 0xFF;
  489. raw_send_to_wifi(buf_to_wifi, 5 + index_to_wifi);
  490. ZERO(buf_to_wifi);
  491. index_to_wifi = 0;
  492. }
  493. else if (type == WIFI_TRANS_INF) {
  494. if (len > (int)(sizeof(buf_to_wifi) - index_to_wifi - 5)) {
  495. ZERO(buf_to_wifi);
  496. index_to_wifi = 0;
  497. return 0;
  498. }
  499. if (len > 0) {
  500. memcpy(&buf_to_wifi[4 + index_to_wifi], buf, len);
  501. index_to_wifi += len;
  502. if (index_to_wifi < 1)
  503. return 0;
  504. if (buf_to_wifi[index_to_wifi + 3] == '\n') {
  505. // mask "wait" "busy" "X:"
  506. if ( ((buf_to_wifi[4] == 'w') && (buf_to_wifi[5] == 'a') && (buf_to_wifi[6] == 'i') && (buf_to_wifi[7] == 't'))
  507. || ((buf_to_wifi[4] == 'b') && (buf_to_wifi[5] == 'u') && (buf_to_wifi[6] == 's') && (buf_to_wifi[7] == 'y'))
  508. || ((buf_to_wifi[4] == 'X') && (buf_to_wifi[5] == ':'))
  509. ) {
  510. ZERO(buf_to_wifi);
  511. index_to_wifi = 0;
  512. return 0;
  513. }
  514. buf_to_wifi[0] = wifi_ret_head;
  515. buf_to_wifi[1] = type;
  516. buf_to_wifi[2] = index_to_wifi & 0xFF;
  517. buf_to_wifi[3] = (index_to_wifi >> 8) & 0xFF;
  518. buf_to_wifi[4 + index_to_wifi] = wifi_ret_tail;
  519. raw_send_to_wifi(buf_to_wifi, 5 + index_to_wifi);
  520. ZERO(buf_to_wifi);
  521. index_to_wifi = 0;
  522. }
  523. }
  524. }
  525. else if (type == WIFI_EXCEP_INF) {
  526. ZERO(buf_to_wifi);
  527. buf_to_wifi[0] = wifi_ret_head;
  528. buf_to_wifi[1] = type;
  529. buf_to_wifi[2] = 1;
  530. buf_to_wifi[3] = 0;
  531. buf_to_wifi[4] = *buf;
  532. buf_to_wifi[5] = wifi_ret_tail;
  533. raw_send_to_wifi(buf_to_wifi, 6);
  534. ZERO(buf_to_wifi);
  535. index_to_wifi = 0;
  536. }
  537. else if (type == WIFI_CLOUD_CFG) {
  538. int data_offset = 4;
  539. int urlLen = strlen((const char *)uiCfg.cloud_hostUrl);
  540. ZERO(buf_to_wifi);
  541. index_to_wifi = 0;
  542. buf_to_wifi[data_offset] = gCfgItems.cloud_enable ? 0x0A : 0x05;
  543. buf_to_wifi[data_offset + 1] = urlLen;
  544. memcpy(&buf_to_wifi[data_offset + 2], (const char *)uiCfg.cloud_hostUrl, urlLen);
  545. buf_to_wifi[data_offset + urlLen + 2] = uiCfg.cloud_port & 0xFF;
  546. buf_to_wifi[data_offset + urlLen + 3] = (uiCfg.cloud_port >> 8) & 0xFF;
  547. buf_to_wifi[data_offset + urlLen + 4] = wifi_ret_tail;
  548. index_to_wifi = urlLen + 4;
  549. buf_to_wifi[0] = wifi_ret_head;
  550. buf_to_wifi[1] = type;
  551. buf_to_wifi[2] = index_to_wifi & 0xFF;
  552. buf_to_wifi[3] = (index_to_wifi >> 8) & 0xFF;
  553. raw_send_to_wifi(buf_to_wifi, 5 + index_to_wifi);
  554. ZERO(buf_to_wifi);
  555. index_to_wifi = 0;
  556. }
  557. else if (type == WIFI_CLOUD_UNBIND) {
  558. ZERO(buf_to_wifi);
  559. buf_to_wifi[0] = wifi_ret_head;
  560. buf_to_wifi[1] = type;
  561. buf_to_wifi[2] = 0;
  562. buf_to_wifi[3] = 0;
  563. buf_to_wifi[4] = wifi_ret_tail;
  564. raw_send_to_wifi(buf_to_wifi, 5);
  565. ZERO(buf_to_wifi);
  566. index_to_wifi = 0;
  567. }
  568. return 1;
  569. }
  570. #define SEND_OK_TO_WIFI send_to_wifi((uint8_t *)"ok\r\n", strlen("ok\r\n"))
  571. int send_to_wifi(uint8_t *buf, int len) { return package_to_wifi(WIFI_TRANS_INF, buf, len); }
  572. void set_cur_file_sys(int fileType) { gCfgItems.fileSysType = fileType; }
  573. void get_file_list(char *path) {
  574. if (!path) return;
  575. if (gCfgItems.fileSysType == FILE_SYS_SD) {
  576. TERN_(SDSUPPORT, card.mount());
  577. }
  578. else if (gCfgItems.fileSysType == FILE_SYS_USB) {
  579. // udisk
  580. }
  581. Explore_Disk(path, 0);
  582. }
  583. char wait_ip_back_flag = 0;
  584. typedef struct {
  585. int write_index;
  586. uint8_t saveFileName[30];
  587. uint8_t fileTransfer;
  588. uint32_t fileLen;
  589. uint32_t tick_begin;
  590. uint32_t tick_end;
  591. } FILE_WRITER;
  592. FILE_WRITER file_writer;
  593. int32_t lastFragment = 0;
  594. char saveFilePath[50];
  595. static SdFile upload_file, *upload_curDir;
  596. static filepos_t pos;
  597. int write_to_file(char *buf, int len) {
  598. int i;
  599. int res = 0;
  600. for (i = 0; i < len; i++) {
  601. public_buf[file_writer.write_index++] = buf[i];
  602. if (file_writer.write_index >= 512) {
  603. res = upload_file.write(public_buf, file_writer.write_index);
  604. if (res == -1) {
  605. upload_file.close();
  606. const char * const fname = card.diveToFile(false, upload_curDir, saveFilePath);
  607. if (upload_file.open(upload_curDir, fname, O_WRITE)) {
  608. upload_file.setpos(&pos);
  609. res = upload_file.write(public_buf, file_writer.write_index);
  610. }
  611. }
  612. if (res == -1) return -1;
  613. upload_file.getpos(&pos);
  614. file_writer.write_index = 0;
  615. }
  616. }
  617. if (res == -1) {
  618. ZERO(public_buf);
  619. file_writer.write_index = 0;
  620. return -1;
  621. }
  622. return 0;
  623. }
  624. #define ESP_PROTOC_HEAD (uint8_t)0xA5
  625. #define ESP_PROTOC_TAIL (uint8_t)0xFC
  626. #define ESP_TYPE_NET (uint8_t)0x0
  627. #define ESP_TYPE_GCODE (uint8_t)0x1
  628. #define ESP_TYPE_FILE_FIRST (uint8_t)0x2
  629. #define ESP_TYPE_FILE_FRAGMENT (uint8_t)0x3
  630. #define ESP_TYPE_WIFI_LIST (uint8_t)0x4
  631. uint8_t esp_msg_buf[UART_RX_BUFFER_SIZE] = { 0 };
  632. uint16_t esp_msg_index = 0;
  633. typedef struct {
  634. uint8_t head;
  635. uint8_t type;
  636. uint16_t dataLen;
  637. uint8_t *data;
  638. uint8_t tail;
  639. } ESP_PROTOC_FRAME;
  640. static int cut_msg_head(uint8_t *msg, uint16_t msgLen, uint16_t cutLen) {
  641. if (msgLen < cutLen) return 0;
  642. else if (msgLen == cutLen) {
  643. memset(msg, 0, msgLen);
  644. return 0;
  645. }
  646. for (int i = 0; i < (msgLen - cutLen); i++)
  647. msg[i] = msg[cutLen + i];
  648. memset(&msg[msgLen - cutLen], 0, cutLen);
  649. return msgLen - cutLen;
  650. }
  651. uint8_t Explore_Disk(char *path , uint8_t recu_level) {
  652. char tmp[200];
  653. char Fstream[200];
  654. if (!path) return 0;
  655. const uint8_t fileCnt = card.get_num_Files();
  656. for (uint8_t i = 0; i < fileCnt; i++) {
  657. card.getfilename_sorted(SD_ORDER(i, fileCnt));
  658. ZERO(tmp);
  659. strcpy(tmp, card.filename);
  660. ZERO(Fstream);
  661. strcpy(Fstream, tmp);
  662. if (card.flag.filenameIsDir && recu_level <= 10)
  663. strcat_P(Fstream, PSTR(".DIR"));
  664. strcat_P(Fstream, PSTR("\r\n"));
  665. send_to_wifi((uint8_t*)Fstream, strlen(Fstream));
  666. }
  667. return fileCnt;
  668. }
  669. static void wifi_gcode_exec(uint8_t *cmd_line) {
  670. int8_t tempBuf[100] = { 0 };
  671. uint8_t *tmpStr = 0;
  672. int cmd_value;
  673. volatile int print_rate;
  674. if (strchr((char *)cmd_line, '\n') && (strchr((char *)cmd_line, 'G') || strchr((char *)cmd_line, 'M') || strchr((char *)cmd_line, 'T'))) {
  675. tmpStr = (uint8_t *)strchr((char *)cmd_line, '\n');
  676. if (tmpStr) *tmpStr = '\0';
  677. tmpStr = (uint8_t *)strchr((char *)cmd_line, '\r');
  678. if (tmpStr) *tmpStr = '\0';
  679. tmpStr = (uint8_t *)strchr((char *)cmd_line, '*');
  680. if (tmpStr) *tmpStr = '\0';
  681. tmpStr = (uint8_t *)strchr((char *)cmd_line, 'M');
  682. if (tmpStr) {
  683. cmd_value = atoi((char *)(tmpStr + 1));
  684. tmpStr = (uint8_t *)strchr((char *)tmpStr, ' ');
  685. switch (cmd_value) {
  686. case 20: // M20: Print SD / µdisk file
  687. file_writer.fileTransfer = 0;
  688. if (uiCfg.print_state == IDLE) {
  689. int index = 0;
  690. if (tmpStr == 0) {
  691. gCfgItems.fileSysType = FILE_SYS_SD;
  692. send_to_wifi((uint8_t *)(STR_BEGIN_FILE_LIST "\r\n"), strlen(STR_BEGIN_FILE_LIST "\r\n"));
  693. get_file_list((char *)"0:/");
  694. send_to_wifi((uint8_t *)(STR_END_FILE_LIST "\r\n"), strlen(STR_END_FILE_LIST "\r\n"));
  695. SEND_OK_TO_WIFI;
  696. break;
  697. }
  698. while (tmpStr[index] == ' ') index++;
  699. if (gCfgItems.wifi_type == ESP_WIFI) {
  700. char *path = (char *)tempBuf;
  701. if (strlen((char *)&tmpStr[index]) < 80) {
  702. send_to_wifi((uint8_t *)(STR_BEGIN_FILE_LIST "\r\n"), strlen(STR_BEGIN_FILE_LIST "\r\n"));
  703. if (strncmp((char *)&tmpStr[index], "1:", 2) == 0)
  704. gCfgItems.fileSysType = FILE_SYS_SD;
  705. else if (strncmp((char *)&tmpStr[index], "0:", 2) == 0)
  706. gCfgItems.fileSysType = FILE_SYS_USB;
  707. strcpy((char *)path, (char *)&tmpStr[index]);
  708. get_file_list(path);
  709. send_to_wifi((uint8_t *)(STR_END_FILE_LIST "\r\n"), strlen(STR_END_FILE_LIST "\r\n"));
  710. }
  711. SEND_OK_TO_WIFI;
  712. }
  713. }
  714. break;
  715. case 21: SEND_OK_TO_WIFI; break; // Init SD card
  716. case 23:
  717. // Select the file
  718. if (uiCfg.print_state == IDLE) {
  719. int index = 0;
  720. while (tmpStr[index] == ' ') index++;
  721. if (strstr_P((char *)&tmpStr[index], PSTR(".g")) || strstr_P((char *)&tmpStr[index], PSTR(".G"))) {
  722. if (strlen((char *)&tmpStr[index]) < 80) {
  723. ZERO(list_file.file_name[sel_id]);
  724. ZERO(list_file.long_name[sel_id]);
  725. uint8_t has_path_selected = 0;
  726. if (gCfgItems.wifi_type == ESP_WIFI) {
  727. if (strncmp_P((char *)&tmpStr[index], PSTR("1:"), 2) == 0) {
  728. gCfgItems.fileSysType = FILE_SYS_SD;
  729. has_path_selected = 1;
  730. }
  731. else if (strncmp_P((char *)&tmpStr[index], PSTR("0:"), 2) == 0) {
  732. gCfgItems.fileSysType = FILE_SYS_USB;
  733. has_path_selected = 1;
  734. }
  735. else if (tmpStr[index] != '/')
  736. strcat_P((char *)list_file.file_name[sel_id], PSTR("/"));
  737. if (file_writer.fileTransfer == 1) {
  738. char dosName[FILENAME_LENGTH];
  739. uint8_t fileName[sizeof(list_file.file_name[sel_id])];
  740. fileName[0] = '\0';
  741. if (has_path_selected == 1) {
  742. strcat((char *)fileName, (char *)&tmpStr[index + 3]);
  743. strcat_P((char *)list_file.file_name[sel_id], PSTR("/"));
  744. }
  745. else strcat((char *)fileName, (char *)&tmpStr[index]);
  746. if (!longName2DosName((const char *)fileName, dosName))
  747. strcpy_P(list_file.file_name[sel_id], PSTR("notValid"));
  748. strcat((char *)list_file.file_name[sel_id], dosName);
  749. strcat((char *)list_file.long_name[sel_id], dosName);
  750. }
  751. else {
  752. strcat((char *)list_file.file_name[sel_id], (char *)&tmpStr[index]);
  753. strcat((char *)list_file.long_name[sel_id], (char *)&tmpStr[index]);
  754. }
  755. }
  756. else
  757. strcpy(list_file.file_name[sel_id], (char *)&tmpStr[index]);
  758. char *cur_name=strrchr(list_file.file_name[sel_id],'/');
  759. card.openFileRead(cur_name);
  760. if (card.isFileOpen())
  761. send_to_wifi((uint8_t *)"File selected\r\n", strlen("File selected\r\n"));
  762. else {
  763. send_to_wifi((uint8_t *)"file.open failed\r\n", strlen("file.open failed\r\n"));
  764. strcpy_P(list_file.file_name[sel_id], PSTR("notValid"));
  765. }
  766. SEND_OK_TO_WIFI;
  767. }
  768. }
  769. }
  770. break;
  771. case 24:
  772. if (strcmp_P(list_file.file_name[sel_id], PSTR("notValid")) != 0) {
  773. if (uiCfg.print_state == IDLE) {
  774. clear_cur_ui();
  775. reset_print_time();
  776. start_print_time();
  777. preview_gcode_prehandle(list_file.file_name[sel_id]);
  778. uiCfg.print_state = WORKING;
  779. lv_draw_printing();
  780. #if ENABLED(SDSUPPORT)
  781. if (!gcode_preview_over) {
  782. char *cur_name = strrchr(list_file.file_name[sel_id], '/');
  783. SdFile file;
  784. SdFile *curDir;
  785. card.abortFilePrintNow();
  786. const char * const fname = card.diveToFile(false, curDir, cur_name);
  787. if (!fname) return;
  788. if (file.open(curDir, fname, O_READ)) {
  789. gCfgItems.curFilesize = file.fileSize();
  790. file.close();
  791. update_spi_flash();
  792. }
  793. card.openFileRead(cur_name);
  794. if (card.isFileOpen()) {
  795. //saved_feedrate_percentage = feedrate_percentage;
  796. feedrate_percentage = 100;
  797. #if HAS_EXTRUDERS
  798. planner.flow_percentage[0] = 100;
  799. planner.e_factor[0] = planner.flow_percentage[0] * 0.01f;
  800. #endif
  801. #if HAS_MULTI_EXTRUDER
  802. planner.flow_percentage[1] = 100;
  803. planner.e_factor[1] = planner.flow_percentage[1] * 0.01f;
  804. #endif
  805. card.startOrResumeFilePrinting();
  806. TERN_(POWER_LOSS_RECOVERY, recovery.prepare());
  807. once_flag = false;
  808. }
  809. }
  810. #endif
  811. }
  812. else if (uiCfg.print_state == PAUSED) {
  813. uiCfg.print_state = RESUMING;
  814. clear_cur_ui();
  815. start_print_time();
  816. if (gCfgItems.from_flash_pic)
  817. flash_preview_begin = true;
  818. else
  819. default_preview_flg = true;
  820. lv_draw_printing();
  821. }
  822. else if (uiCfg.print_state == REPRINTING) {
  823. uiCfg.print_state = REPRINTED;
  824. clear_cur_ui();
  825. start_print_time();
  826. if (gCfgItems.from_flash_pic)
  827. flash_preview_begin = true;
  828. else
  829. default_preview_flg = true;
  830. lv_draw_printing();
  831. }
  832. }
  833. SEND_OK_TO_WIFI;
  834. break;
  835. case 25:
  836. // Pause print file
  837. if (uiCfg.print_state == WORKING) {
  838. stop_print_time();
  839. clear_cur_ui();
  840. #if ENABLED(SDSUPPORT)
  841. card.pauseSDPrint();
  842. uiCfg.print_state = PAUSING;
  843. #endif
  844. if (gCfgItems.from_flash_pic)
  845. flash_preview_begin = true;
  846. else
  847. default_preview_flg = true;
  848. lv_draw_printing();
  849. SEND_OK_TO_WIFI;
  850. }
  851. break;
  852. case 26:
  853. // Stop print file
  854. if ((uiCfg.print_state == WORKING) || (uiCfg.print_state == PAUSED) || (uiCfg.print_state == REPRINTING)) {
  855. stop_print_time();
  856. clear_cur_ui();
  857. #if ENABLED(SDSUPPORT)
  858. uiCfg.print_state = IDLE;
  859. card.abortFilePrintSoon();
  860. #endif
  861. lv_draw_ready_print();
  862. SEND_OK_TO_WIFI;
  863. }
  864. break;
  865. case 27:
  866. // Report print rate
  867. if ((uiCfg.print_state == WORKING) || (uiCfg.print_state == PAUSED)|| (uiCfg.print_state == REPRINTING)) {
  868. print_rate = uiCfg.totalSend;
  869. ZERO(tempBuf);
  870. sprintf_P((char *)tempBuf, PSTR("M27 %d\r\n"), print_rate);
  871. send_to_wifi((uint8_t *)tempBuf, strlen((char *)tempBuf));
  872. }
  873. break;
  874. case 28:
  875. // Begin to transfer file to filesys
  876. if (uiCfg.print_state == IDLE) {
  877. int index = 0;
  878. while (tmpStr[index] == ' ') index++;
  879. if (strstr_P((char *)&tmpStr[index], PSTR(".g")) || strstr_P((char *)&tmpStr[index], PSTR(".G"))) {
  880. strcpy((char *)file_writer.saveFileName, (char *)&tmpStr[index]);
  881. if (gCfgItems.fileSysType == FILE_SYS_SD) {
  882. ZERO(tempBuf);
  883. sprintf_P((char *)tempBuf, PSTR("%s"), file_writer.saveFileName);
  884. }
  885. else if (gCfgItems.fileSysType == FILE_SYS_USB) {
  886. ZERO(tempBuf);
  887. sprintf_P((char *)tempBuf, PSTR("%s"), (char *)file_writer.saveFileName);
  888. }
  889. mount_file_sys(gCfgItems.fileSysType);
  890. #if ENABLED(SDSUPPORT)
  891. char *cur_name = strrchr(list_file.file_name[sel_id], '/');
  892. card.openFileWrite(cur_name);
  893. if (card.isFileOpen()) {
  894. ZERO(file_writer.saveFileName);
  895. strcpy((char *)file_writer.saveFileName, (char *)&tmpStr[index]);
  896. ZERO(tempBuf);
  897. sprintf_P((char *)tempBuf, PSTR("Writing to file: %s\r\n"), (char *)file_writer.saveFileName);
  898. wifi_ret_ack();
  899. send_to_wifi((uint8_t *)tempBuf, strlen((char *)tempBuf));
  900. wifi_link_state = WIFI_WAIT_TRANS_START;
  901. }
  902. else {
  903. wifi_link_state = WIFI_CONNECTED;
  904. clear_cur_ui();
  905. lv_draw_dialog(DIALOG_TRANSFER_NO_DEVICE);
  906. }
  907. #endif
  908. }
  909. }
  910. break;
  911. case 105:
  912. case 991:
  913. ZERO(tempBuf);
  914. if (cmd_value == 105) {
  915. SEND_OK_TO_WIFI;
  916. char *outBuf = (char *)tempBuf;
  917. char tbuf[34];
  918. sprintf_P(tbuf, PSTR("%d /%d"), thermalManager.wholeDegHotend(0), thermalManager.degTargetHotend(0));
  919. const int tlen = strlen(tbuf);
  920. sprintf_P(outBuf, PSTR("T:%s"), tbuf);
  921. outBuf += 2 + tlen;
  922. strcpy_P(outBuf, PSTR(" B:"));
  923. outBuf += 3;
  924. #if HAS_HEATED_BED
  925. sprintf_P(outBuf, PSTR("%d /%d"), thermalManager.wholeDegBed(), thermalManager.degTargetBed());
  926. #else
  927. strcpy_P(outBuf, PSTR("0 /0"));
  928. #endif
  929. outBuf += 4;
  930. strcat_P(outBuf, PSTR(" T0:"));
  931. strcat(outBuf, tbuf);
  932. outBuf += 4 + tlen;
  933. strcat_P(outBuf, PSTR(" T1:"));
  934. outBuf += 4;
  935. #if HAS_MULTI_HOTEND
  936. sprintf_P(outBuf, PSTR("%d /%d"), thermalManager.wholeDegHotend(1), thermalManager.degTargetHotend(1));
  937. #else
  938. strcpy_P(outBuf, PSTR("0 /0"));
  939. #endif
  940. outBuf += 4;
  941. strcat_P(outBuf, PSTR(" @:0 B@:0\r\n"));
  942. }
  943. else {
  944. sprintf_P((char *)tempBuf, PSTR("T:%d /%d B:%d /%d T0:%d /%d T1:%d /%d @:0 B@:0\r\n"),
  945. thermalManager.wholeDegHotend(0), thermalManager.degTargetHotend(0),
  946. TERN0(HAS_HEATED_BED, thermalManager.wholeDegBed()),
  947. TERN0(HAS_HEATED_BED, thermalManager.degTargetBed()),
  948. thermalManager.wholeDegHotend(0), thermalManager.degTargetHotend(0),
  949. TERN0(HAS_MULTI_HOTEND, thermalManager.wholeDegHotend(1)),
  950. TERN0(HAS_MULTI_HOTEND, thermalManager.degTargetHotend(1))
  951. );
  952. }
  953. send_to_wifi((uint8_t *)tempBuf, strlen((char *)tempBuf));
  954. queue.enqueue_one(F("M105"));
  955. break;
  956. case 992:
  957. if ((uiCfg.print_state == WORKING) || (uiCfg.print_state == PAUSED)) {
  958. ZERO(tempBuf);
  959. sprintf_P((char *)tempBuf, PSTR("M992 %d%d:%d%d:%d%d\r\n"), print_time.hours/10, print_time.hours%10, print_time.minutes/10, print_time.minutes%10, print_time.seconds/10, print_time.seconds%10);
  960. wifi_ret_ack();
  961. send_to_wifi((uint8_t *)tempBuf, strlen((char *)tempBuf));
  962. }
  963. break;
  964. case 994:
  965. if ((uiCfg.print_state == WORKING) || (uiCfg.print_state == PAUSED)) {
  966. ZERO(tempBuf);
  967. if (strlen((char *)list_file.file_name[sel_id]) > (100 - 1)) return;
  968. sprintf_P((char *)tempBuf, PSTR("M994 %s;%d\n"), list_file.file_name[sel_id], (int)gCfgItems.curFilesize);
  969. wifi_ret_ack();
  970. send_to_wifi((uint8_t *)tempBuf, strlen((char *)tempBuf));
  971. }
  972. break;
  973. case 997:
  974. if (uiCfg.print_state == IDLE) {
  975. wifi_ret_ack();
  976. send_to_wifi((uint8_t *)"M997 IDLE\r\n", strlen("M997 IDLE\r\n"));
  977. }
  978. else if (uiCfg.print_state == WORKING) {
  979. wifi_ret_ack();
  980. send_to_wifi((uint8_t *)"M997 PRINTING\r\n", strlen("M997 PRINTING\r\n"));
  981. }
  982. else if (uiCfg.print_state == PAUSED) {
  983. wifi_ret_ack();
  984. send_to_wifi((uint8_t *)"M997 PAUSE\r\n", strlen("M997 PAUSE\r\n"));
  985. }
  986. else if (uiCfg.print_state == REPRINTING) {
  987. wifi_ret_ack();
  988. send_to_wifi((uint8_t *)"M997 PAUSE\r\n", strlen("M997 PAUSE\r\n"));
  989. }
  990. if (!uiCfg.command_send) get_wifi_list_command_send();
  991. break;
  992. case 998:
  993. if (uiCfg.print_state == IDLE) {
  994. const int v = atoi((char *)tmpStr);
  995. if (v == 0 || v == 1) set_cur_file_sys(v);
  996. wifi_ret_ack();
  997. }
  998. break;
  999. case 115:
  1000. ZERO(tempBuf);
  1001. SEND_OK_TO_WIFI;
  1002. send_to_wifi((uint8_t *)"FIRMWARE_NAME:Robin_nano\r\n", strlen("FIRMWARE_NAME:Robin_nano\r\n"));
  1003. break;
  1004. default:
  1005. strcat_P((char *)cmd_line, PSTR("\n"));
  1006. if (espGcodeFifo.wait_tick > 5) {
  1007. const uint32_t left = espGcodeFifo.r > espGcodeFifo.w
  1008. ? espGcodeFifo.r - espGcodeFifo.w - 1
  1009. : WIFI_GCODE_BUFFER_SIZE + espGcodeFifo.r - espGcodeFifo.w - 1;
  1010. if (left >= strlen((const char *)cmd_line)) {
  1011. for (uint32_t index = 0; index < strlen((const char *)cmd_line); index++) {
  1012. espGcodeFifo.Buffer[espGcodeFifo.w] = cmd_line[index] ;
  1013. espGcodeFifo.w = (espGcodeFifo.w + 1) % WIFI_GCODE_BUFFER_SIZE;
  1014. }
  1015. if (left - WIFI_GCODE_BUFFER_LEAST_SIZE >= strlen((const char *)cmd_line))
  1016. SEND_OK_TO_WIFI;
  1017. else
  1018. need_ok_later = true;
  1019. }
  1020. }
  1021. break;
  1022. }
  1023. }
  1024. else {
  1025. strcat_P((char *)cmd_line, PSTR("\n"));
  1026. if (espGcodeFifo.wait_tick > 5) {
  1027. const uint32_t left_g = espGcodeFifo.r > espGcodeFifo.w
  1028. ? espGcodeFifo.r - espGcodeFifo.w - 1
  1029. : WIFI_GCODE_BUFFER_SIZE + espGcodeFifo.r - espGcodeFifo.w - 1;
  1030. if (left_g >= strlen((const char *)cmd_line)) {
  1031. for (uint32_t index = 0; index < strlen((const char *)cmd_line); index++) {
  1032. espGcodeFifo.Buffer[espGcodeFifo.w] = cmd_line[index] ;
  1033. espGcodeFifo.w = (espGcodeFifo.w + 1) % WIFI_GCODE_BUFFER_SIZE;
  1034. }
  1035. if (left_g - WIFI_GCODE_BUFFER_LEAST_SIZE >= strlen((const char *)cmd_line))
  1036. SEND_OK_TO_WIFI;
  1037. else
  1038. need_ok_later = true;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. }
  1044. static int32_t charAtArray(const uint8_t *_array, uint32_t _arrayLen, uint8_t _char) {
  1045. for (uint32_t i = 0; i < _arrayLen; i++)
  1046. if (*(_array + i) == _char) return i;
  1047. return -1;
  1048. }
  1049. void get_wifi_list_command_send() {
  1050. uint8_t cmd_wifi_list[] = { 0xA5, 0x07, 0x00, 0x00, 0xFC };
  1051. raw_send_to_wifi(cmd_wifi_list, COUNT(cmd_wifi_list));
  1052. }
  1053. static void net_msg_handle(uint8_t * msg, uint16_t msgLen) {
  1054. int wifiNameLen, wifiKeyLen, hostLen, id_len, ver_len;
  1055. if (msgLen <= 0) return;
  1056. // IP address
  1057. sprintf_P(ipPara.ip_addr, PSTR("%d.%d.%d.%d"), msg[0], msg[1], msg[2], msg[3]);
  1058. // port connect state
  1059. switch (msg[6]) {
  1060. case 0x0A: wifi_link_state = WIFI_CONNECTED; break;
  1061. case 0x0E: wifi_link_state = WIFI_EXCEPTION; break;
  1062. default: wifi_link_state = WIFI_NOT_CONFIG; break;
  1063. }
  1064. // mode
  1065. wifiPara.mode = msg[7];
  1066. // WiFi name
  1067. wifiNameLen = msg[8];
  1068. wifiKeyLen = msg[9 + wifiNameLen];
  1069. if (wifiNameLen < 32) {
  1070. ZERO(wifiPara.ap_name);
  1071. memcpy(wifiPara.ap_name, &msg[9], wifiNameLen);
  1072. memset(&wifi_list.wifiConnectedName, 0, sizeof(wifi_list.wifiConnectedName));
  1073. memcpy(&wifi_list.wifiConnectedName, &msg[9], wifiNameLen);
  1074. // WiFi key
  1075. if (wifiKeyLen < 64) {
  1076. ZERO(wifiPara.keyCode);
  1077. memcpy(wifiPara.keyCode, &msg[10 + wifiNameLen], wifiKeyLen);
  1078. }
  1079. }
  1080. cloud_para.state =msg[10 + wifiNameLen + wifiKeyLen];
  1081. hostLen = msg[11 + wifiNameLen + wifiKeyLen];
  1082. if (cloud_para.state) {
  1083. if (hostLen < 96) {
  1084. ZERO(cloud_para.hostUrl);
  1085. memcpy(cloud_para.hostUrl, &msg[12 + wifiNameLen + wifiKeyLen], hostLen);
  1086. }
  1087. cloud_para.port = msg[12 + wifiNameLen + wifiKeyLen + hostLen] + (msg[13 + wifiNameLen + wifiKeyLen + hostLen] << 8);
  1088. }
  1089. // ID
  1090. id_len = msg[14 + wifiNameLen + wifiKeyLen + hostLen];
  1091. if (id_len == 20) {
  1092. ZERO(cloud_para.id);
  1093. memcpy(cloud_para.id, (const char *)&msg[15 + wifiNameLen + wifiKeyLen + hostLen], id_len);
  1094. }
  1095. ver_len = msg[15 + wifiNameLen + wifiKeyLen + hostLen + id_len];
  1096. if (ver_len < 20) {
  1097. ZERO(wifi_firm_ver);
  1098. memcpy(wifi_firm_ver, (const char *)&msg[16 + wifiNameLen + wifiKeyLen + hostLen + id_len], ver_len);
  1099. }
  1100. if (uiCfg.configWifi) {
  1101. if ((wifiPara.mode != gCfgItems.wifi_mode_sel)
  1102. || (strncmp(wifiPara.ap_name, (const char *)uiCfg.wifi_name, 32) != 0)
  1103. || (strncmp(wifiPara.keyCode, (const char *)uiCfg.wifi_key, 64) != 0)) {
  1104. package_to_wifi(WIFI_PARA_SET, (uint8_t *)0, 0);
  1105. }
  1106. else uiCfg.configWifi = false;
  1107. }
  1108. if (cfg_cloud_flag == 1) {
  1109. if (((cloud_para.state >> 4) != (char)gCfgItems.cloud_enable)
  1110. || (strncmp(cloud_para.hostUrl, (const char *)uiCfg.cloud_hostUrl, 96) != 0)
  1111. || (cloud_para.port != uiCfg.cloud_port)
  1112. ) package_to_wifi(WIFI_CLOUD_CFG, (uint8_t *)0, 0);
  1113. else
  1114. cfg_cloud_flag = 0;
  1115. }
  1116. }
  1117. static void wifi_list_msg_handle(uint8_t * msg, uint16_t msgLen) {
  1118. int wifiNameLen,wifiMsgIdex = 1;
  1119. int8_t wifi_name_is_same = 0;
  1120. int8_t i, j;
  1121. int8_t wifi_name_num = 0;
  1122. uint8_t *str = 0;
  1123. int8_t valid_name_num;
  1124. if (msgLen <= 0) return;
  1125. if (disp_state == KEYBOARD_UI) return;
  1126. wifi_list.getNameNum = msg[0];
  1127. if (wifi_list.getNameNum < 20) {
  1128. uiCfg.command_send = true;
  1129. ZERO(wifi_list.wifiName);
  1130. wifi_name_num = wifi_list.getNameNum;
  1131. valid_name_num = 0;
  1132. str = wifi_list.wifiName[0];
  1133. if (wifi_list.getNameNum > 0) wifi_list.currentWifipage = 1;
  1134. for (i = 0; i < wifi_list.getNameNum; i++) {
  1135. wifiNameLen = msg[wifiMsgIdex++];
  1136. if (wifiNameLen < 32) {
  1137. memset(str, 0, WIFI_NAME_BUFFER_SIZE);
  1138. memcpy(str, &msg[wifiMsgIdex], wifiNameLen);
  1139. for (j = 0; j < valid_name_num; j++) {
  1140. if (strcmp((const char *)str, (const char *)wifi_list.wifiName[j]) == 0) {
  1141. wifi_name_is_same = 1;
  1142. break;
  1143. }
  1144. }
  1145. if (wifi_name_is_same != 1 && str[0] > 0x80)
  1146. wifi_name_is_same = 1;
  1147. if (wifi_name_is_same == 1) {
  1148. wifi_name_is_same = 0;
  1149. wifiMsgIdex += wifiNameLen;
  1150. wifiMsgIdex += 1;
  1151. wifi_name_num--;
  1152. //i--;
  1153. continue;
  1154. }
  1155. if (i < WIFI_TOTAL_NUMBER - 1)
  1156. str = wifi_list.wifiName[++valid_name_num];
  1157. }
  1158. wifiMsgIdex += wifiNameLen;
  1159. wifi_list.RSSI[i] = msg[wifiMsgIdex++];
  1160. }
  1161. wifi_list.getNameNum = wifi_name_num;
  1162. wifi_list.getPage = wifi_list.getNameNum / NUMBER_OF_PAGE + ((wifi_list.getNameNum % NUMBER_OF_PAGE) != 0);
  1163. wifi_list.nameIndex = 0;
  1164. if (disp_state == WIFI_LIST_UI) disp_wifi_list();
  1165. }
  1166. }
  1167. static void gcode_msg_handle(uint8_t * msg, uint16_t msgLen) {
  1168. uint8_t gcodeBuf[100] = { 0 };
  1169. char *index_s, *index_e;
  1170. if (msgLen <= 0) return;
  1171. index_s = (char *)msg;
  1172. index_e = (char *)strchr((char *)msg, '\n');
  1173. if (*msg == 'N') {
  1174. index_s = (char *)strchr((char *)msg, ' ');
  1175. while (*index_s == ' ') index_s++;
  1176. }
  1177. while ((index_e != 0) && ((int)index_s < (int)index_e)) {
  1178. if ((int)(index_e - index_s) < (int)sizeof(gcodeBuf)) {
  1179. ZERO(gcodeBuf);
  1180. memcpy(gcodeBuf, index_s, index_e - index_s + 1);
  1181. wifi_gcode_exec(gcodeBuf);
  1182. }
  1183. while ((*index_e == '\r') || (*index_e == '\n')) index_e++;
  1184. index_s = index_e;
  1185. index_e = (char *)strchr(index_s, '\n');
  1186. }
  1187. }
  1188. void utf8_2_unicode(uint8_t *source, uint8_t Len) {
  1189. uint8_t i = 0, char_i = 0, char_byte_num = 0;
  1190. uint16_t u16_h, u16_m, u16_l, u16_value;
  1191. uint8_t FileName_unicode[30];
  1192. ZERO(FileName_unicode);
  1193. for (;;) {
  1194. char_byte_num = source[i] & 0xF0;
  1195. if (source[i] < 0x80) { // ASCII -- 1 byte
  1196. FileName_unicode[char_i++] = source[i++];
  1197. }
  1198. else if (char_byte_num == 0xC0 || char_byte_num == 0xD0) { // -- 2 byte
  1199. u16_h = (((uint16_t)source[i] << 8) & 0x1F00) >> 2;
  1200. u16_l = ((uint16_t)source[i + 1] & 0x003F);
  1201. u16_value = (u16_h | u16_l);
  1202. FileName_unicode[char_i] = (uint8_t)((u16_value & 0xFF00) >> 8);
  1203. FileName_unicode[char_i + 1] = (uint8_t)(u16_value & 0x00FF);
  1204. i += 2;
  1205. char_i += 2;
  1206. }
  1207. else if (char_byte_num == 0xE0) { // -- 3 byte
  1208. u16_h = (((uint16_t)source[i] << 8) & 0x0F00) << 4;
  1209. u16_m = (((uint16_t)source[i + 1] << 8) & 0x3F00) >> 2;
  1210. u16_l = ((uint16_t)source[i + 2] & 0x003F);
  1211. u16_value = (u16_h | u16_m | u16_l);
  1212. FileName_unicode[char_i] = (uint8_t)((u16_value & 0xFF00) >> 8);
  1213. FileName_unicode[char_i + 1] = (uint8_t)(u16_value & 0x00FF);
  1214. i += 3;
  1215. char_i += 2;
  1216. }
  1217. else if (char_byte_num == 0xF0) { // -- 4 byte
  1218. i += 4;
  1219. //char_i += 3;
  1220. }
  1221. else
  1222. break;
  1223. if (i >= Len || i >= 255) break;
  1224. }
  1225. COPY(source, FileName_unicode);
  1226. }
  1227. static void file_first_msg_handle(uint8_t * msg, uint16_t msgLen) {
  1228. uint8_t fileNameLen = *msg;
  1229. if (msgLen != fileNameLen + 5) return;
  1230. file_writer.fileLen = *((uint32_t *)(msg + 1));
  1231. ZERO(file_writer.saveFileName);
  1232. memcpy(file_writer.saveFileName, msg + 5, fileNameLen);
  1233. utf8_2_unicode(file_writer.saveFileName, fileNameLen);
  1234. ZERO(public_buf);
  1235. if (strlen((const char *)file_writer.saveFileName) > sizeof(saveFilePath))
  1236. return;
  1237. ZERO(saveFilePath);
  1238. if (gCfgItems.fileSysType == FILE_SYS_SD) {
  1239. TERN_(SDSUPPORT, card.mount());
  1240. }
  1241. else if (gCfgItems.fileSysType == FILE_SYS_USB) {
  1242. // nothing
  1243. }
  1244. file_writer.write_index = 0;
  1245. lastFragment = -1;
  1246. wifiTransError.flag = 0;
  1247. wifiTransError.start_tick = 0;
  1248. wifiTransError.now_tick = 0;
  1249. TERN_(SDSUPPORT, card.closefile());
  1250. wifi_delay(1000);
  1251. #if ENABLED(SDSUPPORT)
  1252. char dosName[FILENAME_LENGTH];
  1253. if (!longName2DosName((const char *)file_writer.saveFileName, dosName)) {
  1254. clear_cur_ui();
  1255. upload_result = 2;
  1256. wifiTransError.flag = 1;
  1257. wifiTransError.start_tick = getWifiTick();
  1258. lv_draw_dialog(DIALOG_TYPE_UPLOAD_FILE);
  1259. return;
  1260. }
  1261. strcpy((char *)saveFilePath, dosName);
  1262. card.cdroot();
  1263. upload_file.close();
  1264. const char * const fname = card.diveToFile(false, upload_curDir, saveFilePath);
  1265. if (!upload_file.open(upload_curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  1266. clear_cur_ui();
  1267. upload_result = 2;
  1268. wifiTransError.flag = 1;
  1269. wifiTransError.start_tick = getWifiTick();
  1270. lv_draw_dialog(DIALOG_TYPE_UPLOAD_FILE);
  1271. return;
  1272. }
  1273. #endif // SDSUPPORT
  1274. wifi_link_state = WIFI_TRANS_FILE;
  1275. upload_result = 1;
  1276. clear_cur_ui();
  1277. lv_draw_dialog(DIALOG_TYPE_UPLOAD_FILE);
  1278. lv_task_handler();
  1279. file_writer.tick_begin = getWifiTick();
  1280. file_writer.fileTransfer = 1;
  1281. }
  1282. #define FRAG_MASK ~_BV32(31)
  1283. static void file_fragment_msg_handle(uint8_t * msg, uint16_t msgLen) {
  1284. uint32_t frag = *((uint32_t *)msg);
  1285. if ((frag & FRAG_MASK) != (uint32_t)(lastFragment + 1)) {
  1286. ZERO(public_buf);
  1287. file_writer.write_index = 0;
  1288. wifi_link_state = WIFI_CONNECTED;
  1289. upload_result = 2;
  1290. }
  1291. else {
  1292. if (write_to_file((char *)msg + 4, msgLen - 4) < 0) {
  1293. ZERO(public_buf);
  1294. file_writer.write_index = 0;
  1295. wifi_link_state = WIFI_CONNECTED;
  1296. upload_result = 2;
  1297. return;
  1298. }
  1299. lastFragment = frag;
  1300. if ((frag & (~FRAG_MASK)) != 0) {
  1301. wifiDmaRcvFifo.receiveEspData = false;
  1302. int res = upload_file.write(public_buf, file_writer.write_index);
  1303. if (res == -1) {
  1304. upload_file.close();
  1305. const char * const fname = card.diveToFile(false, upload_curDir, saveFilePath);
  1306. if (upload_file.open(upload_curDir, fname, O_WRITE)) {
  1307. upload_file.setpos(&pos);
  1308. res = upload_file.write(public_buf, file_writer.write_index);
  1309. }
  1310. }
  1311. upload_file.close();
  1312. SdFile file, *curDir;
  1313. const char * const fname = card.diveToFile(false, curDir, saveFilePath);
  1314. if (file.open(curDir, fname, O_RDWR)) {
  1315. gCfgItems.curFilesize = file.fileSize();
  1316. file.close();
  1317. }
  1318. else {
  1319. ZERO(public_buf);
  1320. file_writer.write_index = 0;
  1321. wifi_link_state = WIFI_CONNECTED;
  1322. upload_result = 2;
  1323. return;
  1324. }
  1325. ZERO(public_buf);
  1326. file_writer.write_index = 0;
  1327. file_writer.tick_end = getWifiTick();
  1328. upload_time_sec = getWifiTickDiff(file_writer.tick_begin, file_writer.tick_end) / 1000;
  1329. upload_size = gCfgItems.curFilesize;
  1330. wifi_link_state = WIFI_CONNECTED;
  1331. upload_result = 3;
  1332. }
  1333. }
  1334. }
  1335. void esp_data_parser(char *cmdRxBuf, int len) {
  1336. int32_t head_pos, tail_pos;
  1337. uint16_t cpyLen;
  1338. int16_t leftLen = len;
  1339. bool loop_again = false;
  1340. ESP_PROTOC_FRAME esp_frame;
  1341. while (leftLen > 0 || loop_again) {
  1342. loop_again = false;
  1343. if (esp_msg_index != 0) {
  1344. head_pos = 0;
  1345. cpyLen = (leftLen < (int16_t)((sizeof(esp_msg_buf) - esp_msg_index)) ? leftLen : sizeof(esp_msg_buf) - esp_msg_index);
  1346. memcpy(&esp_msg_buf[esp_msg_index], cmdRxBuf + len - leftLen, cpyLen);
  1347. esp_msg_index += cpyLen;
  1348. leftLen = leftLen - cpyLen;
  1349. tail_pos = charAtArray(esp_msg_buf, esp_msg_index, ESP_PROTOC_TAIL);
  1350. if (tail_pos == -1) {
  1351. if (esp_msg_index >= sizeof(esp_msg_buf)) {
  1352. ZERO(esp_msg_buf);
  1353. esp_msg_index = 0;
  1354. }
  1355. return;
  1356. }
  1357. }
  1358. else {
  1359. head_pos = charAtArray((uint8_t const *)&cmdRxBuf[len - leftLen], leftLen, ESP_PROTOC_HEAD);
  1360. if (head_pos == -1) return;
  1361. ZERO(esp_msg_buf);
  1362. memcpy(esp_msg_buf, &cmdRxBuf[len - leftLen + head_pos], leftLen - head_pos);
  1363. esp_msg_index = leftLen - head_pos;
  1364. leftLen = 0;
  1365. head_pos = 0;
  1366. tail_pos = charAtArray(esp_msg_buf, esp_msg_index, ESP_PROTOC_TAIL);
  1367. if (tail_pos == -1) {
  1368. if (esp_msg_index >= sizeof(esp_msg_buf)) {
  1369. ZERO(esp_msg_buf);
  1370. esp_msg_index = 0;
  1371. }
  1372. return;
  1373. }
  1374. }
  1375. esp_frame.type = esp_msg_buf[1];
  1376. if ( esp_frame.type != ESP_TYPE_NET
  1377. && esp_frame.type != ESP_TYPE_GCODE
  1378. && esp_frame.type != ESP_TYPE_FILE_FIRST
  1379. && esp_frame.type != ESP_TYPE_FILE_FRAGMENT
  1380. && esp_frame.type != ESP_TYPE_WIFI_LIST
  1381. ) {
  1382. ZERO(esp_msg_buf);
  1383. esp_msg_index = 0;
  1384. return;
  1385. }
  1386. esp_frame.dataLen = esp_msg_buf[2] + (esp_msg_buf[3] << 8);
  1387. if ((int)(4 + esp_frame.dataLen) > (int)(sizeof(esp_msg_buf))) {
  1388. ZERO(esp_msg_buf);
  1389. esp_msg_index = 0;
  1390. return;
  1391. }
  1392. if (esp_msg_buf[4 + esp_frame.dataLen] != ESP_PROTOC_TAIL) {
  1393. if (esp_msg_index >= sizeof(esp_msg_buf)) {
  1394. ZERO(esp_msg_buf);
  1395. esp_msg_index = 0;
  1396. }
  1397. return;
  1398. }
  1399. esp_frame.data = &esp_msg_buf[4];
  1400. switch (esp_frame.type) {
  1401. case ESP_TYPE_NET:
  1402. net_msg_handle(esp_frame.data, esp_frame.dataLen);
  1403. break;
  1404. case ESP_TYPE_GCODE:
  1405. gcode_msg_handle(esp_frame.data, esp_frame.dataLen);
  1406. break;
  1407. case ESP_TYPE_FILE_FIRST:
  1408. file_first_msg_handle(esp_frame.data, esp_frame.dataLen);
  1409. break;
  1410. case ESP_TYPE_FILE_FRAGMENT:
  1411. file_fragment_msg_handle(esp_frame.data, esp_frame.dataLen);
  1412. break;
  1413. case ESP_TYPE_WIFI_LIST:
  1414. wifi_list_msg_handle(esp_frame.data, esp_frame.dataLen);
  1415. break;
  1416. default: break;
  1417. }
  1418. esp_msg_index = cut_msg_head(esp_msg_buf, esp_msg_index, esp_frame.dataLen + 5);
  1419. if (esp_msg_index > 0) {
  1420. if (charAtArray(esp_msg_buf, esp_msg_index, ESP_PROTOC_HEAD) == -1) {
  1421. ZERO(esp_msg_buf);
  1422. esp_msg_index = 0;
  1423. return;
  1424. }
  1425. if ((charAtArray(esp_msg_buf, esp_msg_index, ESP_PROTOC_HEAD) != -1) && (charAtArray(esp_msg_buf, esp_msg_index, ESP_PROTOC_TAIL) != -1))
  1426. loop_again = true;
  1427. }
  1428. }
  1429. }
  1430. int32_t tick_net_time1, tick_net_time2;
  1431. int32_t readWifiFifo(uint8_t *retBuf, uint32_t bufLen) {
  1432. unsigned char tmpR = wifiDmaRcvFifo.read_cur;
  1433. if (bufLen >= UDISKBUFLEN && wifiDmaRcvFifo.state[tmpR] == udisk_buf_full) {
  1434. memcpy(retBuf, (unsigned char *)wifiDmaRcvFifo.bufferAddr[tmpR], UDISKBUFLEN);
  1435. wifiDmaRcvFifo.state[tmpR] = udisk_buf_empty;
  1436. wifiDmaRcvFifo.read_cur = (tmpR + 1) % TRANS_RCV_FIFO_BLOCK_NUM;
  1437. return UDISKBUFLEN;
  1438. }
  1439. return 0;
  1440. }
  1441. void stopEspTransfer() {
  1442. if (wifi_link_state == WIFI_TRANS_FILE)
  1443. wifi_link_state = WIFI_CONNECTED;
  1444. TERN_(SDSUPPORT, card.closefile());
  1445. if (upload_result != 3) {
  1446. wifiTransError.flag = 1;
  1447. wifiTransError.start_tick = getWifiTick();
  1448. card.removeFile((const char *)saveFilePath);
  1449. }
  1450. wifi_delay(200);
  1451. WIFI_IO1_SET();
  1452. // disable dma
  1453. #ifdef __STM32F1__
  1454. dma_clear_isr_bits(DMA1, DMA_CH5);
  1455. bb_peri_set_bit(&USART1_BASE->CR3, USART_CR3_DMAR_BIT, 0);
  1456. dma_disable(DMA1, DMA_CH5);
  1457. #else
  1458. // First, abort any running dma
  1459. HAL_DMA_Abort(&wifiUsartDMArx);
  1460. // DeInit objects
  1461. HAL_DMA_DeInit(&wifiUsartDMArx);
  1462. #endif
  1463. wifi_delay(200);
  1464. changeFlashMode(true); // Set SPI flash to use DMA mode
  1465. esp_port_begin(1);
  1466. wifi_delay(200);
  1467. W25QXX.init(SPI_QUARTER_SPEED);
  1468. TERN_(HAS_TFT_LVGL_UI_SPI, SPI_TFT.spi_init(SPI_FULL_SPEED));
  1469. TERN_(HAS_SERVOS, servo_init());
  1470. TERN_(HAS_Z_SERVO_PROBE, probe.servo_probe_init());
  1471. if (wifiTransError.flag != 0x1) WIFI_IO1_RESET();
  1472. }
  1473. void wifi_rcv_handle() {
  1474. int32_t len = 0;
  1475. uint8_t ucStr[(UART_RX_BUFFER_SIZE) + 1] = {0};
  1476. int8_t getDataF = 0;
  1477. if (wifi_link_state == WIFI_TRANS_FILE) {
  1478. #if 0
  1479. if (WIFISERIAL.available() == UART_RX_BUFFER_SIZE) {
  1480. for (uint16_t i=0;i<UART_RX_BUFFER_SIZE;i++) {
  1481. ucStr[i] = WIFISERIAL.read();
  1482. len++;
  1483. }
  1484. }
  1485. #else
  1486. #ifndef __STM32F1__
  1487. if (wifiDmaRcvFifo.receiveEspData) storeRcvData(WIFISERIAL.wifiRxBuf, UART_RX_BUFFER_SIZE);
  1488. #endif
  1489. len = readWifiFifo(ucStr, UART_RX_BUFFER_SIZE);
  1490. #endif
  1491. if (len > 0) {
  1492. esp_data_parser((char *)ucStr, len);
  1493. if (wifi_link_state == WIFI_CONNECTED) {
  1494. clear_cur_ui();
  1495. lv_draw_dialog(DIALOG_TYPE_UPLOAD_FILE);
  1496. stopEspTransfer();
  1497. }
  1498. getDataF = 1;
  1499. }
  1500. #ifdef __STM32F1__
  1501. if (esp_state == TRANSFER_STORE) {
  1502. if (storeRcvData(WIFISERIAL.wifiRxBuf, UART_RX_BUFFER_SIZE)) {
  1503. esp_state = TRANSFERRING;
  1504. esp_dma_pre();
  1505. if (wifiTransError.flag != 0x1) WIFI_IO1_RESET();
  1506. }
  1507. else WIFI_IO1_SET();
  1508. }
  1509. #endif
  1510. }
  1511. else {
  1512. len = readWifiBuf((int8_t *)ucStr, UART_RX_BUFFER_SIZE);
  1513. if (len > 0) {
  1514. esp_data_parser((char *)ucStr, len);
  1515. if (wifi_link_state == WIFI_TRANS_FILE) {
  1516. changeFlashMode(false); // Set SPI flash to use non-DMA mode
  1517. wifi_delay(10);
  1518. esp_port_begin(0);
  1519. wifi_delay(10);
  1520. tick_net_time1 = 0;
  1521. #ifndef __STM32F1__
  1522. wifiDmaRcvFifo.receiveEspData = true;
  1523. return;
  1524. #endif
  1525. }
  1526. if (wifiTransError.flag != 0x1) WIFI_IO1_RESET();
  1527. getDataF = 1;
  1528. }
  1529. if (need_ok_later && !queue.ring_buffer.full()) {
  1530. need_ok_later = false;
  1531. send_to_wifi((uint8_t *)"ok\r\n", strlen("ok\r\n"));
  1532. }
  1533. }
  1534. if (getDataF == 1)
  1535. tick_net_time1 = getWifiTick();
  1536. else {
  1537. tick_net_time2 = getWifiTick();
  1538. if (wifi_link_state == WIFI_TRANS_FILE) {
  1539. if (tick_net_time1 && getWifiTickDiff(tick_net_time1, tick_net_time2) > 8000) {
  1540. wifi_link_state = WIFI_CONNECTED;
  1541. upload_result = 2;
  1542. clear_cur_ui();
  1543. stopEspTransfer();
  1544. lv_draw_dialog(DIALOG_TYPE_UPLOAD_FILE);
  1545. }
  1546. }
  1547. if (tick_net_time1 && getWifiTickDiff(tick_net_time1, tick_net_time2) > 10000)
  1548. wifi_link_state = WIFI_NOT_CONFIG;
  1549. if (tick_net_time1 && getWifiTickDiff(tick_net_time1, tick_net_time2) > 120000) {
  1550. wifi_link_state = WIFI_NOT_CONFIG;
  1551. wifi_reset();
  1552. tick_net_time1 = getWifiTick();
  1553. }
  1554. }
  1555. if (wifiTransError.flag == 0x1) {
  1556. wifiTransError.now_tick = getWifiTick();
  1557. if (getWifiTickDiff(wifiTransError.start_tick, wifiTransError.now_tick) > WAIT_ESP_TRANS_TIMEOUT_TICK) {
  1558. wifiTransError.flag = 0;
  1559. WIFI_IO1_RESET();
  1560. }
  1561. }
  1562. }
  1563. void wifi_looping() {
  1564. do {
  1565. wifi_rcv_handle();
  1566. watchdog_refresh();
  1567. } while (wifi_link_state == WIFI_TRANS_FILE);
  1568. }
  1569. void mks_esp_wifi_init() {
  1570. wifi_link_state = WIFI_NOT_CONFIG;
  1571. SET_OUTPUT(WIFI_RESET_PIN);
  1572. WIFI_SET();
  1573. SET_OUTPUT(WIFI_IO1_PIN);
  1574. SET_INPUT_PULLUP(WIFI_IO0_PIN);
  1575. WIFI_IO1_SET();
  1576. esp_state = TRANSFER_IDLE;
  1577. esp_port_begin(1);
  1578. watchdog_refresh();
  1579. wifi_reset();
  1580. #if 0
  1581. if (update_flag == 0) {
  1582. res = f_open(&esp_upload.uploadFile, ESP_WEB_FIRMWARE_FILE, FA_OPEN_EXISTING | FA_READ);
  1583. if (res == FR_OK) {
  1584. f_close(&esp_upload.uploadFile);
  1585. wifi_delay(2000);
  1586. if (usartFifoAvailable((SZ_USART_FIFO *)&WifiRxFifo) < 20) return;
  1587. clear_cur_ui();
  1588. draw_dialog(DIALOG_TYPE_UPDATE_ESP_FIRMWARE);
  1589. if (wifi_upload(1) >= 0) {
  1590. f_unlink("1:/MKS_WIFI_CUR");
  1591. f_rename(ESP_WEB_FIRMWARE_FILE,"/MKS_WIFI_CUR");
  1592. }
  1593. draw_return_ui();
  1594. update_flag = 1;
  1595. }
  1596. }
  1597. if (update_flag == 0) {
  1598. res = f_open(&esp_upload.uploadFile, ESP_WEB_FILE, FA_OPEN_EXISTING | FA_READ);
  1599. if (res == FR_OK) {
  1600. f_close(&esp_upload.uploadFile);
  1601. wifi_delay(2000);
  1602. if (usartFifoAvailable((SZ_USART_FIFO *)&WifiRxFifo) < 20) return;
  1603. clear_cur_ui();
  1604. draw_dialog(DIALOG_TYPE_UPDATE_ESP_DATA);
  1605. if (wifi_upload(2) >= 0) {
  1606. f_unlink("1:/MKS_WEB_CONTROL_CUR");
  1607. f_rename(ESP_WEB_FILE,"/MKS_WEB_CONTROL_CUR");
  1608. }
  1609. draw_return_ui();
  1610. }
  1611. }
  1612. #endif
  1613. wifiPara.decodeType = WIFI_DECODE_TYPE;
  1614. wifiPara.baud = 115200;
  1615. wifi_link_state = WIFI_NOT_CONFIG;
  1616. }
  1617. void mks_wifi_firmware_update() {
  1618. watchdog_refresh();
  1619. card.openFileRead((char *)ESP_FIRMWARE_FILE);
  1620. if (card.isFileOpen()) {
  1621. card.closefile();
  1622. wifi_delay(2000);
  1623. watchdog_refresh();
  1624. if (usartFifoAvailable((SZ_USART_FIFO *)&WifiRxFifo) < 20) return;
  1625. clear_cur_ui();
  1626. lv_draw_dialog(DIALOG_TYPE_UPDATE_ESP_FIRMWARE);
  1627. lv_task_handler();
  1628. watchdog_refresh();
  1629. if (wifi_upload(0) >= 0) {
  1630. card.removeFile((char *)ESP_FIRMWARE_FILE_RENAME);
  1631. SdFile file, *curDir;
  1632. const char * const fname = card.diveToFile(false, curDir, ESP_FIRMWARE_FILE);
  1633. if (file.open(curDir, fname, O_READ)) {
  1634. file.rename(curDir, (char *)ESP_FIRMWARE_FILE_RENAME);
  1635. file.close();
  1636. }
  1637. }
  1638. clear_cur_ui();
  1639. }
  1640. }
  1641. void get_wifi_commands() {
  1642. static char wifi_line_buffer[MAX_CMD_SIZE];
  1643. static bool wifi_comment_mode = false;
  1644. static int wifi_read_count = 0;
  1645. if (espGcodeFifo.wait_tick > 5) {
  1646. while (!queue.ring_buffer.full() && (espGcodeFifo.r != espGcodeFifo.w)) {
  1647. espGcodeFifo.wait_tick = 0;
  1648. char wifi_char = espGcodeFifo.Buffer[espGcodeFifo.r];
  1649. espGcodeFifo.r = (espGcodeFifo.r + 1) % WIFI_GCODE_BUFFER_SIZE;
  1650. /**
  1651. * If the character ends the line
  1652. */
  1653. if (wifi_char == '\n' || wifi_char == '\r') {
  1654. wifi_comment_mode = false; // end of line == end of comment
  1655. if (!wifi_read_count) continue; // skip empty lines
  1656. wifi_line_buffer[wifi_read_count] = 0; // terminate string
  1657. wifi_read_count = 0; //reset buffer
  1658. char* command = wifi_line_buffer;
  1659. while (*command == ' ') command++; // skip any leading spaces
  1660. // Movement commands alert when stopped
  1661. if (IsStopped()) {
  1662. char* gpos = strchr(command, 'G');
  1663. if (gpos) {
  1664. switch (strtol(gpos + 1, nullptr, 10)) {
  1665. case 0 ... 1:
  1666. TERN_(ARC_SUPPORT, case 2 ... 3:)
  1667. TERN_(BEZIER_CURVE_SUPPORT, case 5:)
  1668. SERIAL_ECHOLNPGM(STR_ERR_STOPPED);
  1669. LCD_MESSAGE(MSG_STOPPED);
  1670. break;
  1671. }
  1672. }
  1673. }
  1674. #if DISABLED(EMERGENCY_PARSER)
  1675. // Process critical commands early
  1676. if (strcmp_P(command, PSTR("M108")) == 0) {
  1677. wait_for_heatup = false;
  1678. TERN_(HAS_MARLINUI_MENU, wait_for_user = false);
  1679. }
  1680. if (strcmp_P(command, PSTR("M112")) == 0) kill(FPSTR(M112_KILL_STR), nullptr, true);
  1681. if (strcmp_P(command, PSTR("M410")) == 0) quickstop_stepper();
  1682. #endif
  1683. // Add the command to the queue
  1684. queue.enqueue_one(wifi_line_buffer);
  1685. }
  1686. else if (wifi_read_count >= MAX_CMD_SIZE - 1) {
  1687. }
  1688. else { // it's not a newline, carriage return or escape char
  1689. if (wifi_char == ';') wifi_comment_mode = true;
  1690. if (!wifi_comment_mode) wifi_line_buffer[wifi_read_count++] = wifi_char;
  1691. }
  1692. }
  1693. } // queue has space, serial has data
  1694. else
  1695. espGcodeFifo.wait_tick++;
  1696. }
  1697. int readWifiBuf(int8_t *buf, int32_t len) {
  1698. int i = 0;
  1699. while (i < len && WIFISERIAL.available())
  1700. buf[i++] = WIFISERIAL.read();
  1701. return i;
  1702. }
  1703. int usartFifoAvailable(SZ_USART_FIFO *fifo) { return WIFISERIAL.available(); }
  1704. #endif // HAS_TFT_LVGL_UI && MKS_WIFI_MODULE