My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

queue.cpp 22KB

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