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.

queue.cpp 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. /**
  23. * queue.cpp - The G-code command queue
  24. */
  25. #include "queue.h"
  26. GCodeQueue queue;
  27. #include "gcode.h"
  28. #include "../lcd/marlinui.h"
  29. #include "../sd/cardreader.h"
  30. #include "../module/motion.h"
  31. #include "../module/planner.h"
  32. #include "../module/temperature.h"
  33. #include "../MarlinCore.h"
  34. #include "../core/bug_on.h"
  35. #if ENABLED(PRINTER_EVENT_LEDS)
  36. #include "../feature/leds/printer_event_leds.h"
  37. #endif
  38. #if HAS_ETHERNET
  39. #include "../feature/ethernet.h"
  40. #endif
  41. #if ENABLED(BINARY_FILE_TRANSFER)
  42. #include "../feature/binary_stream.h"
  43. #endif
  44. #if ENABLED(POWER_LOSS_RECOVERY)
  45. #include "../feature/powerloss.h"
  46. #endif
  47. #if ENABLED(GCODE_REPEAT_MARKERS)
  48. #include "../feature/repeat.h"
  49. #endif
  50. // Frequently used G-code strings
  51. PGMSTR(G28_STR, "G28");
  52. #if NO_TIMEOUTS > 0
  53. static millis_t last_command_time = 0;
  54. #endif
  55. GCodeQueue::SerialState GCodeQueue::serial_state[NUM_SERIAL] = { 0 };
  56. GCodeQueue::RingBuffer GCodeQueue::ring_buffer = { 0 };
  57. #if NO_TIMEOUTS > 0
  58. static millis_t last_command_time = 0;
  59. #endif
  60. /**
  61. * Serial command injection
  62. */
  63. /**
  64. * Next Injected PROGMEM Command pointer. (nullptr == empty)
  65. * Internal commands are enqueued ahead of serial / SD commands.
  66. */
  67. PGM_P GCodeQueue::injected_commands_P; // = nullptr
  68. /**
  69. * Injected SRAM Commands
  70. */
  71. char GCodeQueue::injected_commands[64]; // = { 0 }
  72. void GCodeQueue::RingBuffer::commit_command(bool skip_ok
  73. #if HAS_MULTI_SERIAL
  74. , serial_index_t serial_ind/*=-1*/
  75. #endif
  76. ) {
  77. commands[index_w].skip_ok = skip_ok;
  78. TERN_(HAS_MULTI_SERIAL, commands[index_w].port = serial_ind);
  79. TERN_(POWER_LOSS_RECOVERY, recovery.commit_sdpos(index_w));
  80. advance_pos(index_w, 1);
  81. }
  82. /**
  83. * Copy a command from RAM into the main command buffer.
  84. * Return true if the command was successfully added.
  85. * Return false for a full buffer, or if the 'command' is a comment.
  86. */
  87. bool GCodeQueue::RingBuffer::enqueue(const char* cmd, bool skip_ok/*=true*/
  88. #if HAS_MULTI_SERIAL
  89. , serial_index_t serial_ind/*=-1*/
  90. #endif
  91. ) {
  92. if (*cmd == ';' || length >= BUFSIZE) return false;
  93. strcpy(commands[index_w].buffer, cmd);
  94. commit_command(skip_ok
  95. #if HAS_MULTI_SERIAL
  96. , serial_ind
  97. #endif
  98. );
  99. return true;
  100. }
  101. /**
  102. * Enqueue with Serial Echo
  103. * Return true if the command was consumed
  104. */
  105. bool GCodeQueue::enqueue_one(const char* cmd) {
  106. //SERIAL_ECHOLNPAIR("enqueue_one(\"", cmd, "\")");
  107. if (*cmd == 0 || ISEOL(*cmd)) return true;
  108. if (ring_buffer.enqueue(cmd)) {
  109. SERIAL_ECHO_MSG(STR_ENQUEUEING, cmd, "\"");
  110. return true;
  111. }
  112. return false;
  113. }
  114. /**
  115. * Process the next "immediate" command from PROGMEM.
  116. * Return 'true' if any commands were processed.
  117. */
  118. bool GCodeQueue::process_injected_command_P() {
  119. if (!injected_commands_P) return false;
  120. char c;
  121. size_t i = 0;
  122. while ((c = pgm_read_byte(&injected_commands_P[i])) && c != '\n') i++;
  123. // Extract current command and move pointer to next command
  124. char cmd[i + 1];
  125. memcpy_P(cmd, injected_commands_P, i);
  126. cmd[i] = '\0';
  127. injected_commands_P = c ? injected_commands_P + i + 1 : nullptr;
  128. // Execute command if non-blank
  129. if (i) {
  130. parser.parse(cmd);
  131. gcode.process_parsed_command();
  132. }
  133. return true;
  134. }
  135. /**
  136. * Process the next "immediate" command from SRAM.
  137. * Return 'true' if any commands were processed.
  138. */
  139. bool GCodeQueue::process_injected_command() {
  140. if (injected_commands[0] == '\0') return false;
  141. char c;
  142. size_t i = 0;
  143. while ((c = injected_commands[i]) && c != '\n') i++;
  144. // Execute a non-blank command
  145. if (i) {
  146. injected_commands[i] = '\0';
  147. parser.parse(injected_commands);
  148. gcode.process_parsed_command();
  149. }
  150. // Copy the next command into place
  151. for (
  152. uint8_t d = 0, s = i + !!c; // dst, src
  153. (injected_commands[d] = injected_commands[s]); // copy, exit if 0
  154. d++, s++ // next dst, src
  155. );
  156. return true;
  157. }
  158. /**
  159. * Enqueue and return only when commands are actually enqueued.
  160. * Never call this from a G-code handler!
  161. */
  162. void GCodeQueue::enqueue_one_now(const char* cmd) { while (!enqueue_one(cmd)) idle(); }
  163. /**
  164. * Attempt to enqueue a single G-code command
  165. * and return 'true' if successful.
  166. */
  167. bool GCodeQueue::enqueue_one_P(PGM_P const pgcode) {
  168. size_t i = 0;
  169. PGM_P p = pgcode;
  170. char c;
  171. while ((c = pgm_read_byte(&p[i])) && c != '\n') i++;
  172. char cmd[i + 1];
  173. memcpy_P(cmd, p, i);
  174. cmd[i] = '\0';
  175. return ring_buffer.enqueue(cmd);
  176. }
  177. /**
  178. * Enqueue from program memory and return only when commands are actually enqueued
  179. * Never call this from a G-code handler!
  180. */
  181. void GCodeQueue::enqueue_now_P(PGM_P const pgcode) {
  182. size_t i = 0;
  183. PGM_P p = pgcode;
  184. for (;;) {
  185. char c;
  186. while ((c = pgm_read_byte(&p[i])) && c != '\n') i++;
  187. char cmd[i + 1];
  188. memcpy_P(cmd, p, i);
  189. cmd[i] = '\0';
  190. enqueue_one_now(cmd);
  191. if (!c) break;
  192. p += i + 1;
  193. }
  194. }
  195. /**
  196. * Send an "ok" message to the host, indicating
  197. * that a command was successfully processed.
  198. *
  199. * If ADVANCED_OK is enabled also include:
  200. * N<int> Line number of the command, if any
  201. * P<int> Planner space remaining
  202. * B<int> Block queue space remaining
  203. */
  204. void GCodeQueue::RingBuffer::ok_to_send() {
  205. #if NO_TIMEOUTS > 0
  206. // Start counting from the last command's execution
  207. last_command_time = millis();
  208. #endif
  209. CommandLine &command = commands[index_r];
  210. #if HAS_MULTI_SERIAL
  211. const serial_index_t serial_ind = command.port;
  212. if (serial_ind < 0) return;
  213. PORT_REDIRECT(SERIAL_PORTMASK(serial_ind)); // Reply to the serial port that sent the command
  214. #endif
  215. if (command.skip_ok) return;
  216. SERIAL_ECHOPGM(STR_OK);
  217. #if ENABLED(ADVANCED_OK)
  218. char* p = command.buffer;
  219. if (*p == 'N') {
  220. SERIAL_CHAR(' ', *p++);
  221. while (NUMERIC_SIGNED(*p))
  222. SERIAL_CHAR(*p++);
  223. }
  224. SERIAL_ECHOPAIR_P(SP_P_STR, planner.moves_free(),
  225. SP_B_STR, BUFSIZE - length);
  226. #endif
  227. SERIAL_EOL();
  228. }
  229. /**
  230. * Send a "Resend: nnn" message to the host to
  231. * indicate that a command needs to be re-sent.
  232. */
  233. void GCodeQueue::flush_and_request_resend() {
  234. const serial_index_t serial_ind = ring_buffer.command_port();
  235. #if HAS_MULTI_SERIAL
  236. if (serial_ind < 0) return; // Never mind. Command came from SD or Flash Drive
  237. PORT_REDIRECT(SERIAL_PORTMASK(serial_ind)); // Reply to the serial port that sent the command
  238. #endif
  239. SERIAL_FLUSH();
  240. SERIAL_ECHOPGM(STR_RESEND);
  241. SERIAL_ECHOLN(serial_state[serial_ind].last_N + 1);
  242. }
  243. // Multiserial already handle the dispatch to/from multiple port by itself
  244. inline bool serial_data_available(uint8_t index = SERIAL_ALL) {
  245. if (index == SERIAL_ALL) {
  246. for (index = 0; index < NUM_SERIAL; index++) {
  247. const int a = SERIAL_IMPL.available(index);
  248. #if BOTH(RX_BUFFER_MONITOR, RX_BUFFER_SIZE)
  249. if (a > RX_BUFFER_SIZE - 2) {
  250. PORT_REDIRECT(SERIAL_PORTMASK(index));
  251. SERIAL_ERROR_MSG("RX BUF overflow, increase RX_BUFFER_SIZE: ", a);
  252. }
  253. #endif
  254. if (a > 0) return true;
  255. }
  256. return false;
  257. }
  258. const int a = SERIAL_IMPL.available(index);
  259. #if BOTH(RX_BUFFER_MONITOR, RX_BUFFER_SIZE)
  260. if (a > RX_BUFFER_SIZE - 2) {
  261. PORT_REDIRECT(SERIAL_PORTMASK(index));
  262. SERIAL_ERROR_MSG("RX BUF overflow, increase RX_BUFFER_SIZE: ", a);
  263. }
  264. #endif
  265. return a > 0;
  266. }
  267. inline int read_serial(const uint8_t index) { return SERIAL_IMPL.read(index); }
  268. void GCodeQueue::gcode_line_error(PGM_P const err, const serial_index_t serial_ind) {
  269. PORT_REDIRECT(SERIAL_PORTMASK(serial_ind)); // Reply to the serial port that sent the command
  270. SERIAL_ERROR_START();
  271. SERIAL_ECHOPGM_P(err);
  272. SERIAL_ECHOLN(serial_state[serial_ind].last_N);
  273. while (read_serial(serial_ind) != -1) { /* nada */ } // Clear out the RX buffer. Why don't use flush here ?
  274. flush_and_request_resend();
  275. serial_state[serial_ind].count = 0;
  276. }
  277. FORCE_INLINE bool is_M29(const char * const cmd) { // matches "M29" & "M29 ", but not "M290", etc
  278. const char * const m29 = strstr_P(cmd, PSTR("M29"));
  279. return m29 && !NUMERIC(m29[3]);
  280. }
  281. #define PS_NORMAL 0
  282. #define PS_EOL 1
  283. #define PS_QUOTED 2
  284. #define PS_PAREN 3
  285. #define PS_ESC 4
  286. inline void process_stream_char(const char c, uint8_t &sis, char (&buff)[MAX_CMD_SIZE], int &ind) {
  287. if (sis == PS_EOL) return; // EOL comment or overflow
  288. #if ENABLED(PAREN_COMMENTS)
  289. else if (sis == PS_PAREN) { // Inline comment
  290. if (c == ')') sis = PS_NORMAL;
  291. return;
  292. }
  293. #endif
  294. else if (sis >= PS_ESC) // End escaped char
  295. sis -= PS_ESC;
  296. else if (c == '\\') { // Start escaped char
  297. sis += PS_ESC;
  298. if (sis == PS_ESC) return; // Keep if quoting
  299. }
  300. #if ENABLED(GCODE_QUOTED_STRINGS)
  301. else if (sis == PS_QUOTED) {
  302. if (c == '"') sis = PS_NORMAL; // End quoted string
  303. }
  304. else if (c == '"') // Start quoted string
  305. sis = PS_QUOTED;
  306. #endif
  307. else if (c == ';') { // Start end-of-line comment
  308. sis = PS_EOL;
  309. return;
  310. }
  311. #if ENABLED(PAREN_COMMENTS)
  312. else if (c == '(') { // Start inline comment
  313. sis = PS_PAREN;
  314. return;
  315. }
  316. #endif
  317. // Backspace erases previous characters
  318. if (c == 0x08) {
  319. if (ind) buff[--ind] = '\0';
  320. }
  321. else {
  322. buff[ind++] = c;
  323. if (ind >= MAX_CMD_SIZE - 1)
  324. sis = PS_EOL; // Skip the rest on overflow
  325. }
  326. }
  327. /**
  328. * Handle a line being completed. For an empty line
  329. * keep sensor readings going and watchdog alive.
  330. */
  331. inline bool process_line_done(uint8_t &sis, char (&buff)[MAX_CMD_SIZE], int &ind) {
  332. sis = PS_NORMAL; // "Normal" Serial Input State
  333. buff[ind] = '\0'; // Of course, I'm a Terminator.
  334. const bool is_empty = (ind == 0); // An empty line?
  335. if (is_empty)
  336. thermalManager.manage_heater(); // Keep sensors satisfied
  337. else
  338. ind = 0; // Start a new line
  339. return is_empty; // Inform the caller
  340. }
  341. /**
  342. * Get all commands waiting on the serial port and queue them.
  343. * Exit when the buffer is full or when no more characters are
  344. * left on the serial port.
  345. */
  346. void GCodeQueue::get_serial_commands() {
  347. #if ENABLED(BINARY_FILE_TRANSFER)
  348. if (card.flag.binary_mode) {
  349. /**
  350. * For binary stream file transfer, use serial_line_buffer as the working
  351. * receive buffer (which limits the packet size to MAX_CMD_SIZE).
  352. * The receive buffer also limits the packet size for reliable transmission.
  353. */
  354. binaryStream[card.transfer_port_index].receive(serial_state[card.transfer_port_index].line_buffer);
  355. return;
  356. }
  357. #endif
  358. // If the command buffer is empty for too long,
  359. // send "wait" to indicate Marlin is still waiting.
  360. #if NO_TIMEOUTS > 0
  361. const millis_t ms = millis();
  362. if (ring_buffer.empty() && !serial_data_available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  363. SERIAL_ECHOLNPGM(STR_WAIT);
  364. last_command_time = ms;
  365. }
  366. #endif
  367. // Loop while serial characters are incoming and the queue is not full
  368. for (bool hadData = true; hadData;) {
  369. // Unless a serial port has data, this will exit on next iteration
  370. hadData = false;
  371. LOOP_L_N(p, NUM_SERIAL) {
  372. // Check if the queue is full and exit if it is.
  373. if (ring_buffer.full()) return;
  374. // No data for this port ? Skip it
  375. if (!serial_data_available(p)) continue;
  376. // Ok, we have some data to process, let's make progress here
  377. hadData = true;
  378. const int c = read_serial(p);
  379. if (c < 0) {
  380. // This should never happen, let's log it
  381. PORT_REDIRECT(SERIAL_PORTMASK(p)); // Reply to the serial port that sent the command
  382. // Crash here to get more information why it failed
  383. BUG_ON("SP available but read -1");
  384. SERIAL_ERROR_MSG(STR_ERR_SERIAL_MISMATCH);
  385. SERIAL_FLUSH();
  386. continue;
  387. }
  388. const char serial_char = (char)c;
  389. SerialState &serial = serial_state[p];
  390. if (ISEOL(serial_char)) {
  391. // Reset our state, continue if the line was empty
  392. if (process_line_done(serial.input_state, serial.line_buffer, serial.count))
  393. continue;
  394. char* command = serial.line_buffer;
  395. while (*command == ' ') command++; // Skip leading spaces
  396. char *npos = (*command == 'N') ? command : nullptr; // Require the N parameter to start the line
  397. if (npos) {
  398. const bool M110 = !!strstr_P(command, PSTR("M110"));
  399. if (M110) {
  400. char* n2pos = strchr(command + 4, 'N');
  401. if (n2pos) npos = n2pos;
  402. }
  403. const long gcode_N = strtol(npos + 1, nullptr, 10);
  404. if (gcode_N != serial.last_N + 1 && !M110) {
  405. // In case of error on a serial port, don't prevent other serial port from making progress
  406. gcode_line_error(PSTR(STR_ERR_LINE_NO), p);
  407. break;
  408. }
  409. char *apos = strrchr(command, '*');
  410. if (apos) {
  411. uint8_t checksum = 0, count = uint8_t(apos - command);
  412. while (count) checksum ^= command[--count];
  413. if (strtol(apos + 1, nullptr, 10) != checksum) {
  414. // In case of error on a serial port, don't prevent other serial port from making progress
  415. gcode_line_error(PSTR(STR_ERR_CHECKSUM_MISMATCH), p);
  416. break;
  417. }
  418. }
  419. else {
  420. // In case of error on a serial port, don't prevent other serial port from making progress
  421. gcode_line_error(PSTR(STR_ERR_NO_CHECKSUM), p);
  422. break;
  423. }
  424. serial.last_N = gcode_N;
  425. }
  426. #if ENABLED(SDSUPPORT)
  427. // Pronterface "M29" and "M29 " has no line number
  428. else if (card.flag.saving && !is_M29(command)) {
  429. gcode_line_error(PSTR(STR_ERR_NO_CHECKSUM), p);
  430. break;
  431. }
  432. #endif
  433. //
  434. // Movement commands give an alert when the machine is stopped
  435. //
  436. if (IsStopped()) {
  437. char* gpos = strchr(command, 'G');
  438. if (gpos) {
  439. switch (strtol(gpos + 1, nullptr, 10)) {
  440. case 0: case 1:
  441. #if ENABLED(ARC_SUPPORT)
  442. case 2: case 3:
  443. #endif
  444. #if ENABLED(BEZIER_CURVE_SUPPORT)
  445. case 5:
  446. #endif
  447. PORT_REDIRECT(SERIAL_PORTMASK(p)); // Reply to the serial port that sent the command
  448. SERIAL_ECHOLNPGM(STR_ERR_STOPPED);
  449. LCD_MESSAGEPGM(MSG_STOPPED);
  450. break;
  451. }
  452. }
  453. }
  454. #if DISABLED(EMERGENCY_PARSER)
  455. // Process critical commands early
  456. if (command[0] == 'M') switch (command[3]) {
  457. case '8': if (command[2] == '0' && command[1] == '1') { wait_for_heatup = false; TERN_(HAS_LCD_MENU, wait_for_user = false); } break;
  458. case '2': if (command[2] == '1' && command[1] == '1') kill(M112_KILL_STR, nullptr, true); break;
  459. case '0': if (command[1] == '4' && command[2] == '1') quickstop_stepper(); break;
  460. }
  461. #endif
  462. #if NO_TIMEOUTS > 0
  463. last_command_time = ms;
  464. #endif
  465. // Add the command to the queue
  466. ring_buffer.enqueue(serial.line_buffer, false
  467. #if HAS_MULTI_SERIAL
  468. , p
  469. #endif
  470. );
  471. }
  472. else
  473. process_stream_char(serial_char, serial.input_state, serial.line_buffer, serial.count);
  474. } // NUM_SERIAL loop
  475. } // queue has space, serial has data
  476. }
  477. #if ENABLED(SDSUPPORT)
  478. /**
  479. * Get lines from the SD Card until the command buffer is full
  480. * or until the end of the file is reached. Because this method
  481. * always receives complete command-lines, they can go directly
  482. * into the main command queue.
  483. */
  484. inline void GCodeQueue::get_sdcard_commands() {
  485. static uint8_t sd_input_state = PS_NORMAL;
  486. if (!IS_SD_PRINTING()) return;
  487. int sd_count = 0;
  488. while (!ring_buffer.full() && !card.eof()) {
  489. const int16_t n = card.get();
  490. const bool card_eof = card.eof();
  491. if (n < 0 && !card_eof) { SERIAL_ERROR_MSG(STR_SD_ERR_READ); continue; }
  492. CommandLine &command = ring_buffer.commands[ring_buffer.index_w];
  493. const char sd_char = (char)n;
  494. const bool is_eol = ISEOL(sd_char);
  495. if (is_eol || card_eof) {
  496. // Reset stream state, terminate the buffer, and commit a non-empty command
  497. if (!is_eol && sd_count) ++sd_count; // End of file with no newline
  498. if (!process_line_done(sd_input_state, command.buffer, sd_count)) {
  499. // M808 L saves the sdpos of the next line. M808 loops to a new sdpos.
  500. TERN_(GCODE_REPEAT_MARKERS, repeat.early_parse_M808(command.buffer));
  501. // Put the new command into the buffer (no "ok" sent)
  502. ring_buffer.commit_command(true);
  503. // Prime Power-Loss Recovery for the NEXT commit_command
  504. TERN_(POWER_LOSS_RECOVERY, recovery.cmd_sdpos = card.getIndex());
  505. }
  506. if (card.eof()) card.fileHasFinished(); // Handle end of file reached
  507. }
  508. else
  509. process_stream_char(sd_char, sd_input_state, command.buffer, sd_count);
  510. }
  511. }
  512. #endif // SDSUPPORT
  513. /**
  514. * Add to the circular command queue the next command from:
  515. * - The command-injection queues (injected_commands_P, injected_commands)
  516. * - The active serial input (usually USB)
  517. * - The SD card file being actively printed
  518. */
  519. void GCodeQueue::get_available_commands() {
  520. if (ring_buffer.full()) return;
  521. get_serial_commands();
  522. TERN_(SDSUPPORT, get_sdcard_commands());
  523. }
  524. /**
  525. * Get the next command in the queue, optionally log it to SD, then dispatch it
  526. */
  527. void GCodeQueue::advance() {
  528. // Process immediate commands
  529. if (process_injected_command_P() || process_injected_command()) return;
  530. // Return if the G-code buffer is empty
  531. if (ring_buffer.empty()) return;
  532. #if ENABLED(SDSUPPORT)
  533. if (card.flag.saving) {
  534. char * const cmd = ring_buffer.peek_next_command_string();
  535. if (is_M29(cmd)) {
  536. // M29 closes the file
  537. card.closefile();
  538. SERIAL_ECHOLNPGM(STR_FILE_SAVED);
  539. #if !defined(__AVR__) || !defined(USBCON)
  540. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  541. SERIAL_ECHOLNPAIR("Dropped bytes: ", MYSERIAL0.dropped());
  542. #endif
  543. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  544. SERIAL_ECHOLNPAIR("Max RX Queue Size: ", MYSERIAL0.rxMaxEnqueued());
  545. #endif
  546. #endif
  547. ok_to_send();
  548. }
  549. else {
  550. // Write the string from the read buffer to SD
  551. card.write_command(cmd);
  552. if (card.flag.logging)
  553. gcode.process_next_command(); // The card is saving because it's logging
  554. else
  555. ok_to_send();
  556. }
  557. }
  558. else
  559. gcode.process_next_command();
  560. #else
  561. gcode.process_next_command();
  562. #endif // SDSUPPORT
  563. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  564. ring_buffer.advance_pos(ring_buffer.index_r, -1);
  565. }