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 22KB

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