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

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