My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

queue.cpp 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 <http://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/ultralcd.h"
  29. #include "../sd/cardreader.h"
  30. #include "../module/planner.h"
  31. #include "../module/temperature.h"
  32. #include "../MarlinCore.h"
  33. #if ENABLED(PRINTER_EVENT_LEDS)
  34. #include "../feature/leds/printer_event_leds.h"
  35. #endif
  36. #if ENABLED(BINARY_FILE_TRANSFER)
  37. #include "../feature/binary_protocol.h"
  38. #endif
  39. #if ENABLED(POWER_LOSS_RECOVERY)
  40. #include "../feature/power_loss_recovery.h"
  41. #endif
  42. /**
  43. * GCode line number handling. Hosts may opt to include line numbers when
  44. * sending commands to Marlin, and lines will be checked for sequentiality.
  45. * M110 N<int> sets the current line number.
  46. */
  47. long gcode_N, GCodeQueue::last_N, GCodeQueue::stopped_N = 0;
  48. /**
  49. * GCode Command Queue
  50. * A simple ring buffer of BUFSIZE command strings.
  51. *
  52. * Commands are copied into this buffer by the command injectors
  53. * (immediate, serial, sd card) and they are processed sequentially by
  54. * the main loop. The gcode.process_next_command method parses the next
  55. * command and hands off execution to individual handler functions.
  56. */
  57. uint8_t GCodeQueue::length = 0, // Count of commands in the queue
  58. GCodeQueue::index_r = 0, // Ring buffer read position
  59. GCodeQueue::index_w = 0; // Ring buffer write position
  60. char GCodeQueue::command_buffer[BUFSIZE][MAX_CMD_SIZE];
  61. /*
  62. * The port that the command was received on
  63. */
  64. #if NUM_SERIAL > 1
  65. int16_t GCodeQueue::port[BUFSIZE];
  66. #endif
  67. /**
  68. * Serial command injection
  69. */
  70. // Number of characters read in the current line of serial input
  71. static int serial_count[NUM_SERIAL] = { 0 };
  72. bool send_ok[BUFSIZE];
  73. /**
  74. * Next Injected Command pointer. nullptr if no commands are being injected.
  75. * Used by Marlin internally to ensure that commands initiated from within
  76. * are enqueued ahead of any pending serial or sd card commands.
  77. */
  78. static PGM_P injected_commands_P = nullptr;
  79. GCodeQueue::GCodeQueue() {
  80. // Send "ok" after commands by default
  81. for (uint8_t i = 0; i < COUNT(send_ok); i++) send_ok[i] = true;
  82. }
  83. /**
  84. * Check whether there are any commands yet to be executed
  85. */
  86. bool GCodeQueue::has_commands_queued() {
  87. return queue.length || injected_commands_P;
  88. }
  89. /**
  90. * Clear the Marlin command queue
  91. */
  92. void GCodeQueue::clear() {
  93. index_r = index_w = length = 0;
  94. }
  95. /**
  96. * Once a new command is in the ring buffer, call this to commit it
  97. */
  98. void GCodeQueue::_commit_command(bool say_ok
  99. #if NUM_SERIAL > 1
  100. , int16_t p/*=-1*/
  101. #endif
  102. ) {
  103. send_ok[index_w] = say_ok;
  104. #if NUM_SERIAL > 1
  105. port[index_w] = p;
  106. #endif
  107. #if ENABLED(POWER_LOSS_RECOVERY)
  108. recovery.commit_sdpos(index_w);
  109. #endif
  110. if (++index_w >= BUFSIZE) index_w = 0;
  111. length++;
  112. }
  113. /**
  114. * Copy a command from RAM into the main command buffer.
  115. * Return true if the command was successfully added.
  116. * Return false for a full buffer, or if the 'command' is a comment.
  117. */
  118. bool GCodeQueue::_enqueue(const char* cmd, bool say_ok/*=false*/
  119. #if NUM_SERIAL > 1
  120. , int16_t pn/*=-1*/
  121. #endif
  122. ) {
  123. if (*cmd == ';' || length >= BUFSIZE) return false;
  124. strcpy(command_buffer[index_w], cmd);
  125. _commit_command(say_ok
  126. #if NUM_SERIAL > 1
  127. , pn
  128. #endif
  129. );
  130. return true;
  131. }
  132. /**
  133. * Enqueue with Serial Echo
  134. * Return true if the command was consumed
  135. */
  136. bool GCodeQueue::enqueue_one(const char* cmd) {
  137. //SERIAL_ECHOPGM("enqueue_one(\"");
  138. //SERIAL_ECHO(cmd);
  139. //SERIAL_ECHOPGM("\") \n");
  140. if (*cmd == 0 || *cmd == '\n' || *cmd == '\r') return true;
  141. if (_enqueue(cmd)) {
  142. SERIAL_ECHO_MSG(MSG_ENQUEUEING, cmd, "\"");
  143. return true;
  144. }
  145. return false;
  146. }
  147. /**
  148. * Process the next "immediate" command.
  149. * Return 'true' if any commands were processed,
  150. * or remain to process.
  151. */
  152. bool GCodeQueue::process_injected_command() {
  153. if (injected_commands_P == nullptr) return false;
  154. char c;
  155. size_t i = 0;
  156. while ((c = pgm_read_byte(&injected_commands_P[i])) && c != '\n') i++;
  157. // Extract current command and move pointer to next command
  158. char cmd[i + 1];
  159. memcpy_P(cmd, injected_commands_P, i);
  160. cmd[i] = '\0';
  161. injected_commands_P = c ? injected_commands_P + i + 1 : nullptr;
  162. // Execute command if non-blank
  163. if (i) {
  164. parser.parse(cmd);
  165. gcode.process_parsed_command();
  166. }
  167. return true;
  168. }
  169. /**
  170. * Enqueue one or many commands to run from program memory.
  171. * Do not inject a comment or use leading spaces!
  172. * Aborts the current queue, if any.
  173. * Note: process_injected_command() will be called to drain any commands afterwards
  174. */
  175. void GCodeQueue::inject_P(PGM_P const pgcode) { injected_commands_P = pgcode; }
  176. /**
  177. * Enqueue and return only when commands are actually enqueued.
  178. * Never call this from a G-code handler!
  179. */
  180. void GCodeQueue::enqueue_one_now(const char* cmd) { while (!enqueue_one(cmd)) idle(); }
  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::ok_to_send() {
  209. #if NUM_SERIAL > 1
  210. const int16_t pn = port[index_r];
  211. if (pn < 0) return;
  212. PORT_REDIRECT(pn); // Reply to the serial port that sent the command
  213. #endif
  214. if (!send_ok[index_r]) return;
  215. SERIAL_ECHOPGM(MSG_OK);
  216. #if ENABLED(ADVANCED_OK)
  217. char* p = command_buffer[index_r];
  218. if (*p == 'N') {
  219. SERIAL_ECHO(' ');
  220. SERIAL_ECHO(*p++);
  221. while (NUMERIC_SIGNED(*p))
  222. SERIAL_ECHO(*p++);
  223. }
  224. SERIAL_ECHOPAIR_P(SP_P_STR, int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  225. SERIAL_ECHOPAIR(" B", 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. #if NUM_SERIAL > 1
  235. const int16_t pn = port[index_r];
  236. if (pn < 0) return;
  237. PORT_REDIRECT(pn); // Reply to the serial port that sent the command
  238. #endif
  239. SERIAL_FLUSH();
  240. SERIAL_ECHOPGM(MSG_RESEND);
  241. SERIAL_ECHOLN(last_N + 1);
  242. ok_to_send();
  243. }
  244. inline bool serial_data_available() {
  245. return false
  246. || MYSERIAL0.available()
  247. #if NUM_SERIAL > 1
  248. || MYSERIAL1.available()
  249. #endif
  250. ;
  251. }
  252. inline int read_serial(const uint8_t index) {
  253. switch (index) {
  254. case 0: return MYSERIAL0.read();
  255. #if NUM_SERIAL > 1
  256. case 1: return MYSERIAL1.read();
  257. #endif
  258. default: return -1;
  259. }
  260. }
  261. void GCodeQueue::gcode_line_error(PGM_P const err, const int8_t pn) {
  262. PORT_REDIRECT(pn); // Reply to the serial port that sent the command
  263. SERIAL_ERROR_START();
  264. serialprintPGM(err);
  265. SERIAL_ECHOLN(last_N);
  266. while (read_serial(pn) != -1); // Clear out the RX buffer
  267. flush_and_request_resend();
  268. serial_count[pn] = 0;
  269. }
  270. FORCE_INLINE bool is_M29(const char * const cmd) { // matches "M29" & "M29 ", but not "M290", etc
  271. const char * const m29 = strstr_P(cmd, PSTR("M29"));
  272. return m29 && !NUMERIC(m29[3]);
  273. }
  274. #define PS_NORMAL 0
  275. #define PS_EOL 1
  276. #define PS_QUOTED 2
  277. #define PS_PAREN 3
  278. #define PS_ESC 4
  279. inline void process_stream_char(const char c, uint8_t &sis, char (&buff)[MAX_CMD_SIZE], int &ind) {
  280. if (sis == PS_EOL) return; // EOL comment or overflow
  281. #if ENABLED(PAREN_COMMENTS)
  282. else if (sis == PS_PAREN) { // Inline comment
  283. if (c == ')') sis = PS_NORMAL;
  284. return;
  285. }
  286. #endif
  287. else if (sis >= PS_ESC) // End escaped char
  288. sis -= PS_ESC;
  289. else if (c == '\\') { // Start escaped char
  290. sis += PS_ESC;
  291. if (sis == PS_ESC) return; // Keep if quoting
  292. }
  293. #if ENABLED(GCODE_QUOTED_STRINGS)
  294. else if (sis == PS_QUOTED) {
  295. if (c == '"') sis = PS_NORMAL; // End quoted string
  296. }
  297. else if (c == '"') // Start quoted string
  298. sis = PS_QUOTED;
  299. #endif
  300. else if (c == ';') { // Start end-of-line comment
  301. sis = PS_EOL;
  302. return;
  303. }
  304. #if ENABLED(PAREN_COMMENTS)
  305. else if (c == '(') { // Start inline comment
  306. sis = PS_PAREN;
  307. return;
  308. }
  309. #endif
  310. buff[ind++] = c;
  311. if (ind >= MAX_CMD_SIZE - 1)
  312. sis = PS_EOL; // Skip the rest on overflow
  313. }
  314. inline bool process_line_done(uint8_t &sis, char (&buff)[MAX_CMD_SIZE], int &ind) {
  315. sis = PS_NORMAL;
  316. if (!ind) { thermalManager.manage_heater(); return true; }
  317. buff[ind] = 0;
  318. ind = 0;
  319. return false;
  320. }
  321. /**
  322. * Get all commands waiting on the serial port and queue them.
  323. * Exit when the buffer is full or when no more characters are
  324. * left on the serial port.
  325. */
  326. void GCodeQueue::get_serial_commands() {
  327. static char serial_line_buffer[NUM_SERIAL][MAX_CMD_SIZE];
  328. static uint8_t serial_input_state[NUM_SERIAL] = { 0 };
  329. #if ENABLED(BINARY_FILE_TRANSFER)
  330. if (card.flag.binary_mode) {
  331. /**
  332. * For binary stream file transfer, use serial_line_buffer as the working
  333. * receive buffer (which limits the packet size to MAX_CMD_SIZE).
  334. * The receive buffer also limits the packet size for reliable transmission.
  335. */
  336. binaryStream[card.transfer_port_index].receive(serial_line_buffer[card.transfer_port_index]);
  337. return;
  338. }
  339. #endif
  340. // If the command buffer is empty for too long,
  341. // send "wait" to indicate Marlin is still waiting.
  342. #if NO_TIMEOUTS > 0
  343. static millis_t last_command_time = 0;
  344. const millis_t ms = millis();
  345. if (length == 0 && !serial_data_available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  346. SERIAL_ECHOLNPGM(MSG_WAIT);
  347. last_command_time = ms;
  348. }
  349. #endif
  350. /**
  351. * Loop while serial characters are incoming and the queue is not full
  352. */
  353. while (length < BUFSIZE && serial_data_available()) {
  354. for (uint8_t i = 0; i < NUM_SERIAL; ++i) {
  355. const int c = read_serial(i);
  356. if (c < 0) continue;
  357. const char serial_char = c;
  358. if (serial_char == '\n' || serial_char == '\r') {
  359. process_line_done(serial_input_state[i], serial_line_buffer[i], serial_count[i]);
  360. char* command = serial_line_buffer[i];
  361. while (*command == ' ') command++; // Skip leading spaces
  362. char *npos = (*command == 'N') ? command : nullptr; // Require the N parameter to start the line
  363. if (npos) {
  364. bool M110 = strstr_P(command, PSTR("M110")) != nullptr;
  365. if (M110) {
  366. char* n2pos = strchr(command + 4, 'N');
  367. if (n2pos) npos = n2pos;
  368. }
  369. gcode_N = strtol(npos + 1, nullptr, 10);
  370. if (gcode_N != last_N + 1 && !M110)
  371. return gcode_line_error(PSTR(MSG_ERR_LINE_NO), i);
  372. char *apos = strrchr(command, '*');
  373. if (apos) {
  374. uint8_t checksum = 0, count = uint8_t(apos - command);
  375. while (count) checksum ^= command[--count];
  376. if (strtol(apos + 1, nullptr, 10) != checksum)
  377. return gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH), i);
  378. }
  379. else
  380. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM), i);
  381. last_N = gcode_N;
  382. }
  383. #if ENABLED(SDSUPPORT)
  384. // Pronterface "M29" and "M29 " has no line number
  385. else if (card.flag.saving && !is_M29(command))
  386. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM), i);
  387. #endif
  388. //
  389. // Movement commands give an alert when the machine is stopped
  390. //
  391. if (IsStopped()) {
  392. char* gpos = strchr(command, 'G');
  393. if (gpos) {
  394. switch (strtol(gpos + 1, nullptr, 10)) {
  395. case 0: case 1:
  396. #if ENABLED(ARC_SUPPORT)
  397. case 2: case 3:
  398. #endif
  399. #if ENABLED(BEZIER_CURVE_SUPPORT)
  400. case 5:
  401. #endif
  402. SERIAL_ECHOLNPGM(MSG_ERR_STOPPED);
  403. LCD_MESSAGEPGM(MSG_STOPPED);
  404. break;
  405. }
  406. }
  407. }
  408. #if DISABLED(EMERGENCY_PARSER)
  409. // Process critical commands early
  410. if (strcmp(command, "M108") == 0) {
  411. wait_for_heatup = false;
  412. #if HAS_LCD_MENU
  413. wait_for_user = false;
  414. #endif
  415. }
  416. if (strcmp(command, "M112") == 0) kill(M112_KILL_STR, nullptr, true);
  417. if (strcmp(command, "M410") == 0) quickstop_stepper();
  418. #endif
  419. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  420. last_command_time = ms;
  421. #endif
  422. // Add the command to the queue
  423. _enqueue(serial_line_buffer[i], true
  424. #if NUM_SERIAL > 1
  425. , i
  426. #endif
  427. );
  428. }
  429. else
  430. process_stream_char(serial_char, serial_input_state[i], serial_line_buffer[i], serial_count[i]);
  431. } // for NUM_SERIAL
  432. } // queue has space, serial has data
  433. }
  434. #if ENABLED(SDSUPPORT)
  435. /**
  436. * Get commands from the SD Card until the command buffer is full
  437. * or until the end of the file is reached. The special character '#'
  438. * can also interrupt buffering.
  439. */
  440. inline void GCodeQueue::get_sdcard_commands() {
  441. static uint8_t sd_input_state = PS_NORMAL;
  442. if (!IS_SD_PRINTING()) return;
  443. int sd_count = 0;
  444. bool card_eof = card.eof();
  445. while (length < BUFSIZE && !card_eof) {
  446. const int16_t n = card.get();
  447. card_eof = card.eof();
  448. const char sd_char = (char)n;
  449. if (card_eof || n < 0 || sd_char == '\n' || sd_char == '\r') {
  450. if (card_eof) {
  451. card.printingHasFinished();
  452. if (IS_SD_PRINTING())
  453. sd_count = 0; // If a sub-file was printing, continue from call point
  454. else {
  455. SERIAL_ECHOLNPGM(MSG_FILE_PRINTED);
  456. #if ENABLED(PRINTER_EVENT_LEDS)
  457. printerEventLEDs.onPrintCompleted();
  458. #if HAS_RESUME_CONTINUE
  459. inject_P(PSTR("M0 Q S"
  460. #if HAS_LCD_MENU
  461. "1800"
  462. #else
  463. "60"
  464. #endif
  465. ));
  466. #endif
  467. #endif // PRINTER_EVENT_LEDS
  468. }
  469. }
  470. else if (n < 0)
  471. SERIAL_ERROR_MSG(MSG_SD_ERR_READ);
  472. process_line_done(sd_input_state, command_buffer[index_w], sd_count);
  473. _commit_command(false);
  474. #if ENABLED(POWER_LOSS_RECOVERY)
  475. recovery.cmd_sdpos = card.getIndex(); // Prime for the next _commit_command
  476. #endif
  477. }
  478. else
  479. process_stream_char(sd_char, sd_input_state, command_buffer[index_w], sd_count);
  480. }
  481. }
  482. #endif // SDSUPPORT
  483. /**
  484. * Add to the circular command queue the next command from:
  485. * - The command-injection queue (injected_commands_P)
  486. * - The active serial input (usually USB)
  487. * - The SD card file being actively printed
  488. */
  489. void GCodeQueue::get_available_commands() {
  490. get_serial_commands();
  491. #if ENABLED(SDSUPPORT)
  492. get_sdcard_commands();
  493. #endif
  494. }
  495. /**
  496. * Get the next command in the queue, optionally log it to SD, then dispatch it
  497. */
  498. void GCodeQueue::advance() {
  499. // Process immediate commands
  500. if (process_injected_command()) return;
  501. // Return if the G-code buffer is empty
  502. if (!length) return;
  503. #if ENABLED(SDSUPPORT)
  504. if (card.flag.saving) {
  505. char* command = command_buffer[index_r];
  506. if (is_M29(command)) {
  507. // M29 closes the file
  508. card.closefile();
  509. SERIAL_ECHOLNPGM(MSG_FILE_SAVED);
  510. #if !defined(__AVR__) || !defined(USBCON)
  511. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  512. SERIAL_ECHOLNPAIR("Dropped bytes: ", MYSERIAL0.dropped());
  513. #endif
  514. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  515. SERIAL_ECHOLNPAIR("Max RX Queue Size: ", MYSERIAL0.rxMaxEnqueued());
  516. #endif
  517. #endif // !defined(__AVR__) || !defined(USBCON)
  518. ok_to_send();
  519. }
  520. else {
  521. // Write the string from the read buffer to SD
  522. card.write_command(command);
  523. if (card.flag.logging)
  524. gcode.process_next_command(); // The card is saving because it's logging
  525. else
  526. ok_to_send();
  527. }
  528. }
  529. else
  530. gcode.process_next_command();
  531. #else
  532. gcode.process_next_command();
  533. #endif // SDSUPPORT
  534. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  535. if (length) {
  536. --length;
  537. if (++index_r >= BUFSIZE) index_r = 0;
  538. }
  539. }