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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2019 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. #include "gcode.h"
  27. #include "../lcd/ultralcd.h"
  28. #include "../sd/cardreader.h"
  29. #include "../module/planner.h"
  30. #include "../module/temperature.h"
  31. #include "../Marlin.h"
  32. #if ENABLED(PRINTER_EVENT_LEDS)
  33. #include "../feature/leds/printer_event_leds.h"
  34. #endif
  35. /**
  36. * GCode line number handling. Hosts may opt to include line numbers when
  37. * sending commands to Marlin, and lines will be checked for sequentiality.
  38. * M110 N<int> sets the current line number.
  39. */
  40. long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  41. /**
  42. * GCode Command Queue
  43. * A simple ring buffer of BUFSIZE command strings.
  44. *
  45. * Commands are copied into this buffer by the command injectors
  46. * (immediate, serial, sd card) and they are processed sequentially by
  47. * the main loop. The gcode.process_next_command method parses the next
  48. * command and hands off execution to individual handler functions.
  49. */
  50. uint8_t commands_in_queue = 0, // Count of commands in the queue
  51. cmd_queue_index_r = 0, // Ring buffer read position
  52. cmd_queue_index_w = 0; // Ring buffer write position
  53. char command_queue[BUFSIZE][MAX_CMD_SIZE];
  54. /*
  55. * The port that the command was received on
  56. */
  57. #if NUM_SERIAL > 1
  58. int16_t command_queue_port[BUFSIZE];
  59. #endif
  60. /**
  61. * Serial command injection
  62. */
  63. // Number of characters read in the current line of serial input
  64. static int serial_count[NUM_SERIAL] = { 0 };
  65. bool send_ok[BUFSIZE];
  66. /**
  67. * Next Injected Command pointer. NULL if no commands are being injected.
  68. * Used by Marlin internally to ensure that commands initiated from within
  69. * are enqueued ahead of any pending serial or sd card commands.
  70. */
  71. static PGM_P injected_commands_P = NULL;
  72. void queue_setup() {
  73. // Send "ok" after commands by default
  74. for (uint8_t i = 0; i < COUNT(send_ok); i++) send_ok[i] = true;
  75. }
  76. /**
  77. * Clear the Marlin command queue
  78. */
  79. void clear_command_queue() {
  80. cmd_queue_index_r = cmd_queue_index_w = commands_in_queue = 0;
  81. }
  82. /**
  83. * Once a new command is in the ring buffer, call this to commit it
  84. */
  85. inline void _commit_command(bool say_ok
  86. #if NUM_SERIAL > 1
  87. , int16_t port = -1
  88. #endif
  89. ) {
  90. send_ok[cmd_queue_index_w] = say_ok;
  91. #if NUM_SERIAL > 1
  92. command_queue_port[cmd_queue_index_w] = port;
  93. #endif
  94. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  95. commands_in_queue++;
  96. }
  97. /**
  98. * Copy a command from RAM into the main command buffer.
  99. * Return true if the command was successfully added.
  100. * Return false for a full buffer, or if the 'command' is a comment.
  101. */
  102. inline bool _enqueuecommand(const char* cmd, bool say_ok=false
  103. #if NUM_SERIAL > 1
  104. , int16_t port = -1
  105. #endif
  106. ) {
  107. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  108. strcpy(command_queue[cmd_queue_index_w], cmd);
  109. _commit_command(say_ok
  110. #if NUM_SERIAL > 1
  111. , port
  112. #endif
  113. );
  114. return true;
  115. }
  116. /**
  117. * Enqueue with Serial Echo
  118. */
  119. bool enqueue_and_echo_command(const char* cmd) {
  120. //SERIAL_ECHOPGM("enqueue_and_echo_command(\"");
  121. //SERIAL_ECHO(cmd);
  122. //SERIAL_ECHOPGM("\") \n");
  123. if (*cmd == 0 || *cmd == '\n' || *cmd == '\r') {
  124. //SERIAL_ECHOLNPGM("Null command found... Did not queue!");
  125. return true;
  126. }
  127. if (_enqueuecommand(cmd)) {
  128. SERIAL_ECHO_START();
  129. SERIAL_ECHOLNPAIR(MSG_ENQUEUEING, cmd, "\"");
  130. return true;
  131. }
  132. return false;
  133. }
  134. /**
  135. * Inject the next "immediate" command, when possible, onto the front of the queue.
  136. * Return true if any immediate commands remain to inject.
  137. */
  138. static bool drain_injected_commands_P() {
  139. if (injected_commands_P != NULL) {
  140. size_t i = 0;
  141. char c, cmd[60];
  142. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  143. cmd[sizeof(cmd) - 1] = '\0';
  144. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  145. cmd[i] = '\0';
  146. if (enqueue_and_echo_command(cmd)) // success?
  147. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  148. }
  149. return (injected_commands_P != NULL); // return whether any more remain
  150. }
  151. /**
  152. * Record one or many commands to run from program memory.
  153. * Aborts the current queue, if any.
  154. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  155. */
  156. void enqueue_and_echo_commands_P(PGM_P const pgcode) {
  157. injected_commands_P = pgcode;
  158. (void)drain_injected_commands_P(); // first command executed asap (when possible)
  159. }
  160. #if HAS_QUEUE_NOW
  161. /**
  162. * Enqueue and return only when commands are actually enqueued.
  163. * Never call this from a G-code handler!
  164. */
  165. void enqueue_and_echo_command_now(const char* cmd) {
  166. while (!enqueue_and_echo_command(cmd)) idle();
  167. }
  168. #if HAS_LCD_QUEUE_NOW
  169. /**
  170. * Enqueue from program memory and return only when commands are actually enqueued
  171. * Never call this from a G-code handler!
  172. */
  173. void enqueue_and_echo_commands_now_P(PGM_P const pgcode) {
  174. enqueue_and_echo_commands_P(pgcode);
  175. while (drain_injected_commands_P()) idle();
  176. }
  177. #endif
  178. #endif
  179. /**
  180. * Send an "ok" message to the host, indicating
  181. * that a command was successfully processed.
  182. *
  183. * If ADVANCED_OK is enabled also include:
  184. * N<int> Line number of the command, if any
  185. * P<int> Planner space remaining
  186. * B<int> Block queue space remaining
  187. */
  188. void ok_to_send() {
  189. #if NUM_SERIAL > 1
  190. const int16_t port = command_queue_port[cmd_queue_index_r];
  191. if (port < 0) return;
  192. PORT_REDIRECT(port);
  193. #endif
  194. if (!send_ok[cmd_queue_index_r]) return;
  195. SERIAL_ECHOPGM(MSG_OK);
  196. #if ENABLED(ADVANCED_OK)
  197. char* p = command_queue[cmd_queue_index_r];
  198. if (*p == 'N') {
  199. SERIAL_ECHO(' ');
  200. SERIAL_ECHO(*p++);
  201. while (NUMERIC_SIGNED(*p))
  202. SERIAL_ECHO(*p++);
  203. }
  204. SERIAL_ECHOPGM(" P"); SERIAL_ECHO(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  205. SERIAL_ECHOPGM(" B"); SERIAL_ECHO(BUFSIZE - commands_in_queue);
  206. #endif
  207. SERIAL_EOL();
  208. }
  209. /**
  210. * Send a "Resend: nnn" message to the host to
  211. * indicate that a command needs to be re-sent.
  212. */
  213. void flush_and_request_resend() {
  214. #if NUM_SERIAL > 1
  215. const int16_t port = command_queue_port[cmd_queue_index_r];
  216. if (port < 0) return;
  217. PORT_REDIRECT(port);
  218. #endif
  219. SERIAL_FLUSH();
  220. SERIAL_ECHOPGM(MSG_RESEND);
  221. SERIAL_ECHOLN(gcode_LastN + 1);
  222. ok_to_send();
  223. }
  224. inline bool serial_data_available() {
  225. return false
  226. || MYSERIAL0.available()
  227. #if NUM_SERIAL > 1
  228. || MYSERIAL1.available()
  229. #endif
  230. ;
  231. }
  232. inline int read_serial(const uint8_t index) {
  233. switch (index) {
  234. case 0: return MYSERIAL0.read();
  235. #if NUM_SERIAL > 1
  236. case 1: return MYSERIAL1.read();
  237. #endif
  238. default: return -1;
  239. }
  240. }
  241. void gcode_line_error(PGM_P const err, const int8_t port) {
  242. PORT_REDIRECT(port);
  243. SERIAL_ERROR_START();
  244. serialprintPGM(err);
  245. SERIAL_ECHOLN(gcode_LastN);
  246. while (read_serial(port) != -1); // clear out the RX buffer
  247. flush_and_request_resend();
  248. serial_count[port] = 0;
  249. }
  250. #if ENABLED(BINARY_FILE_TRANSFER)
  251. inline bool serial_data_available(const uint8_t index) {
  252. switch (index) {
  253. case 0: return MYSERIAL0.available();
  254. #if NUM_SERIAL > 1
  255. case 1: return MYSERIAL1.available();
  256. #endif
  257. default: return false;
  258. }
  259. }
  260. class BinaryStream {
  261. public:
  262. enum class StreamState : uint8_t {
  263. STREAM_RESET,
  264. PACKET_RESET,
  265. STREAM_HEADER,
  266. PACKET_HEADER,
  267. PACKET_DATA,
  268. PACKET_VALIDATE,
  269. PACKET_RESEND,
  270. PACKET_FLUSHRX,
  271. PACKET_TIMEOUT,
  272. STREAM_COMPLETE,
  273. STREAM_FAILED,
  274. };
  275. #pragma pack(push, 1)
  276. struct StreamHeader {
  277. uint16_t token;
  278. uint32_t filesize;
  279. };
  280. union {
  281. uint8_t stream_header_bytes[sizeof(StreamHeader)];
  282. StreamHeader stream_header;
  283. };
  284. struct Packet {
  285. struct Header {
  286. uint32_t id;
  287. uint16_t size, checksum;
  288. };
  289. union {
  290. uint8_t header_bytes[sizeof(Header)];
  291. Header header;
  292. };
  293. uint32_t bytes_received;
  294. uint16_t checksum;
  295. millis_t timeout;
  296. } packet{};
  297. #pragma pack(pop)
  298. void packet_reset() {
  299. packet.header.id = 0;
  300. packet.header.size = 0;
  301. packet.header.checksum = 0;
  302. packet.bytes_received = 0;
  303. packet.checksum = 0x53A2;
  304. packet.timeout = millis() + STREAM_MAX_WAIT;
  305. }
  306. void stream_reset() {
  307. packets_received = 0;
  308. bytes_received = 0;
  309. packet_retries = 0;
  310. buffer_next_index = 0;
  311. stream_header.token = 0;
  312. stream_header.filesize = 0;
  313. }
  314. uint32_t checksum(uint32_t seed, uint8_t value) {
  315. return ((seed ^ value) ^ (seed << 8)) & 0xFFFF;
  316. }
  317. // read the next byte from the data stream keeping track of
  318. // whether the stream times out from data starvation
  319. // takes the data variable by reference in order to return status
  320. bool stream_read(uint8_t& data) {
  321. if (ELAPSED(millis(), packet.timeout)) {
  322. stream_state = StreamState::PACKET_TIMEOUT;
  323. return false;
  324. }
  325. if (!serial_data_available(card.transfer_port_index)) return false;
  326. data = read_serial(card.transfer_port_index);
  327. packet.timeout = millis() + STREAM_MAX_WAIT;
  328. return true;
  329. }
  330. template<const size_t buffer_size>
  331. void receive(char (&buffer)[buffer_size]) {
  332. uint8_t data = 0;
  333. millis_t transfer_timeout = millis() + RX_TIMESLICE;
  334. #if ENABLED(SDSUPPORT)
  335. PORT_REDIRECT(card.transfer_port_index);
  336. #endif
  337. while (PENDING(millis(), transfer_timeout)) {
  338. switch (stream_state) {
  339. case StreamState::STREAM_RESET:
  340. stream_reset();
  341. case StreamState::PACKET_RESET:
  342. packet_reset();
  343. stream_state = StreamState::PACKET_HEADER;
  344. break;
  345. case StreamState::STREAM_HEADER: // The filename could also be in this packet, rather than handling it in the gcode
  346. for (size_t i = 0; i < sizeof(stream_header); ++i)
  347. stream_header_bytes[i] = buffer[i];
  348. if (stream_header.token == 0x1234) {
  349. stream_state = StreamState::PACKET_RESET;
  350. bytes_received = 0;
  351. time_stream_start = millis();
  352. // confirm active stream and the maximum block size supported
  353. SERIAL_ECHO_START();
  354. SERIAL_ECHOLNPAIR("Datastream initialized (", stream_header.filesize, " bytes expected)");
  355. SERIAL_ECHOLNPAIR("so", buffer_size);
  356. }
  357. else {
  358. SERIAL_ECHO_MSG("Datastream init error (invalid token)");
  359. stream_state = StreamState::STREAM_FAILED;
  360. }
  361. buffer_next_index = 0;
  362. break;
  363. case StreamState::PACKET_HEADER:
  364. if (!stream_read(data)) break;
  365. packet.header_bytes[packet.bytes_received++] = data;
  366. if (packet.bytes_received == sizeof(Packet::Header)) {
  367. if (packet.header.id == packets_received) {
  368. buffer_next_index = 0;
  369. packet.bytes_received = 0;
  370. stream_state = StreamState::PACKET_DATA;
  371. }
  372. else {
  373. SERIAL_ECHO_MSG("Datastream packet out of order");
  374. stream_state = StreamState::PACKET_FLUSHRX;
  375. }
  376. }
  377. break;
  378. case StreamState::PACKET_DATA:
  379. if (!stream_read(data)) break;
  380. if (buffer_next_index < buffer_size)
  381. buffer[buffer_next_index] = data;
  382. else {
  383. SERIAL_ECHO_MSG("Datastream packet data buffer overrun");
  384. stream_state = StreamState::STREAM_FAILED;
  385. break;
  386. }
  387. packet.checksum = checksum(packet.checksum, data);
  388. packet.bytes_received++;
  389. buffer_next_index++;
  390. if (packet.bytes_received == packet.header.size)
  391. stream_state = StreamState::PACKET_VALIDATE;
  392. break;
  393. case StreamState::PACKET_VALIDATE:
  394. if (packet.header.checksum == packet.checksum) {
  395. packet_retries = 0;
  396. packets_received++;
  397. bytes_received += packet.header.size;
  398. if (packet.header.id == 0) // id 0 is always the stream descriptor
  399. stream_state = StreamState::STREAM_HEADER; // defer packet confirmation to STREAM_HEADER state
  400. else {
  401. if (bytes_received < stream_header.filesize) {
  402. stream_state = StreamState::PACKET_RESET; // reset and receive next packet
  403. SERIAL_ECHOLNPAIR("ok", packet.header.id); // transmit confirm packet received and valid token
  404. }
  405. else
  406. stream_state = StreamState::STREAM_COMPLETE; // no more data required
  407. if (card.write(buffer, buffer_next_index) < 0) {
  408. stream_state = StreamState::STREAM_FAILED;
  409. SERIAL_ECHO_MSG("SDCard IO Error");
  410. break;
  411. };
  412. }
  413. }
  414. else {
  415. SERIAL_ECHO_START();
  416. SERIAL_ECHOLNPAIR("Block(", packet.header.id, ") Corrupt");
  417. stream_state = StreamState::PACKET_FLUSHRX;
  418. }
  419. break;
  420. case StreamState::PACKET_RESEND:
  421. if (packet_retries < MAX_RETRIES) {
  422. packet_retries++;
  423. stream_state = StreamState::PACKET_RESET;
  424. SERIAL_ECHO_START();
  425. SERIAL_ECHOLNPAIR("Resend request ", int(packet_retries));
  426. SERIAL_ECHOLNPAIR("rs", packet.header.id); // transmit resend packet token
  427. }
  428. else {
  429. stream_state = StreamState::STREAM_FAILED;
  430. }
  431. break;
  432. case StreamState::PACKET_FLUSHRX:
  433. if (ELAPSED(millis(), packet.timeout)) {
  434. stream_state = StreamState::PACKET_RESEND;
  435. break;
  436. }
  437. if (!serial_data_available(card.transfer_port_index)) break;
  438. read_serial(card.transfer_port_index); // throw away data
  439. packet.timeout = millis() + STREAM_MAX_WAIT;
  440. break;
  441. case StreamState::PACKET_TIMEOUT:
  442. SERIAL_ECHO_START();
  443. SERIAL_ECHOLNPGM("Datastream timeout");
  444. stream_state = StreamState::PACKET_RESEND;
  445. break;
  446. case StreamState::STREAM_COMPLETE:
  447. stream_state = StreamState::STREAM_RESET;
  448. card.flag.binary_mode = false;
  449. SERIAL_ECHO_START();
  450. SERIAL_ECHO(card.filename);
  451. SERIAL_ECHOLNPAIR(" transfer completed @ ", ((bytes_received / (millis() - time_stream_start) * 1000) / 1024), "KiB/s");
  452. SERIAL_ECHOLNPGM("sc"); // transmit stream complete token
  453. card.closefile();
  454. return;
  455. case StreamState::STREAM_FAILED:
  456. stream_state = StreamState::STREAM_RESET;
  457. card.flag.binary_mode = false;
  458. card.closefile();
  459. card.removeFile(card.filename);
  460. SERIAL_ECHO_START();
  461. SERIAL_ECHOLNPGM("File transfer failed");
  462. SERIAL_ECHOLNPGM("sf"); // transmit stream failed token
  463. return;
  464. }
  465. }
  466. }
  467. static const uint16_t STREAM_MAX_WAIT = 500, RX_TIMESLICE = 20, MAX_RETRIES = 3;
  468. uint8_t packet_retries;
  469. uint16_t buffer_next_index;
  470. uint32_t packets_received, bytes_received;
  471. millis_t time_stream_start;
  472. StreamState stream_state = StreamState::STREAM_RESET;
  473. } binaryStream{};
  474. #endif // BINARY_FILE_TRANSFER
  475. FORCE_INLINE bool is_M29(const char * const cmd) { // matches "M29" & "M29 ", but not "M290", etc
  476. const char * const m29 = strstr_P(cmd, PSTR("M29"));
  477. return m29 && !NUMERIC(m29[3]);
  478. }
  479. /**
  480. * Get all commands waiting on the serial port and queue them.
  481. * Exit when the buffer is full or when no more characters are
  482. * left on the serial port.
  483. */
  484. inline void get_serial_commands() {
  485. static char serial_line_buffer[NUM_SERIAL][MAX_CMD_SIZE];
  486. static bool serial_comment_mode[NUM_SERIAL] = { false }
  487. #if ENABLED(PAREN_COMMENTS)
  488. , serial_comment_paren_mode[NUM_SERIAL] = { false }
  489. #endif
  490. ;
  491. #if ENABLED(BINARY_FILE_TRANSFER)
  492. if (card.flag.saving && card.flag.binary_mode) {
  493. /**
  494. * For binary stream file transfer, use serial_line_buffer as the working
  495. * receive buffer (which limits the packet size to MAX_CMD_SIZE).
  496. * The receive buffer also limits the packet size for reliable transmission.
  497. */
  498. binaryStream.receive(serial_line_buffer[card.transfer_port_index]);
  499. return;
  500. }
  501. #endif
  502. // If the command buffer is empty for too long,
  503. // send "wait" to indicate Marlin is still waiting.
  504. #if NO_TIMEOUTS > 0
  505. static millis_t last_command_time = 0;
  506. const millis_t ms = millis();
  507. if (commands_in_queue == 0 && !serial_data_available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  508. SERIAL_ECHOLNPGM(MSG_WAIT);
  509. last_command_time = ms;
  510. }
  511. #endif
  512. /**
  513. * Loop while serial characters are incoming and the queue is not full
  514. */
  515. while (commands_in_queue < BUFSIZE && serial_data_available()) {
  516. for (uint8_t i = 0; i < NUM_SERIAL; ++i) {
  517. int c;
  518. if ((c = read_serial(i)) < 0) continue;
  519. char serial_char = c;
  520. /**
  521. * If the character ends the line
  522. */
  523. if (serial_char == '\n' || serial_char == '\r') {
  524. // Start with comment mode off
  525. serial_comment_mode[i] = false;
  526. #if ENABLED(PAREN_COMMENTS)
  527. serial_comment_paren_mode[i] = false;
  528. #endif
  529. // Skip empty lines and comments
  530. if (!serial_count[i]) { thermalManager.manage_heater(); continue; }
  531. serial_line_buffer[i][serial_count[i]] = 0; // Terminate string
  532. serial_count[i] = 0; // Reset buffer
  533. char* command = serial_line_buffer[i];
  534. while (*command == ' ') command++; // Skip leading spaces
  535. char *npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  536. if (npos) {
  537. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  538. if (M110) {
  539. char* n2pos = strchr(command + 4, 'N');
  540. if (n2pos) npos = n2pos;
  541. }
  542. gcode_N = strtol(npos + 1, NULL, 10);
  543. if (gcode_N != gcode_LastN + 1 && !M110)
  544. return gcode_line_error(PSTR(MSG_ERR_LINE_NO), i);
  545. char *apos = strrchr(command, '*');
  546. if (apos) {
  547. uint8_t checksum = 0, count = uint8_t(apos - command);
  548. while (count) checksum ^= command[--count];
  549. if (strtol(apos + 1, NULL, 10) != checksum)
  550. return gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH), i);
  551. }
  552. else
  553. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM), i);
  554. gcode_LastN = gcode_N;
  555. }
  556. #if ENABLED(SDSUPPORT)
  557. // Pronterface "M29" and "M29 " has no line number
  558. else if (card.flag.saving && !is_M29(command))
  559. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM), i);
  560. #endif
  561. // Movement commands alert when stopped
  562. if (IsStopped()) {
  563. char* gpos = strchr(command, 'G');
  564. if (gpos) {
  565. switch (strtol(gpos + 1, NULL, 10)) {
  566. case 0:
  567. case 1:
  568. #if ENABLED(ARC_SUPPORT)
  569. case 2:
  570. case 3:
  571. #endif
  572. #if ENABLED(BEZIER_CURVE_SUPPORT)
  573. case 5:
  574. #endif
  575. SERIAL_ECHOLNPGM(MSG_ERR_STOPPED);
  576. LCD_MESSAGEPGM(MSG_STOPPED);
  577. break;
  578. }
  579. }
  580. }
  581. #if DISABLED(EMERGENCY_PARSER)
  582. // Process critical commands early
  583. if (strcmp(command, "M108") == 0) {
  584. wait_for_heatup = false;
  585. #if HAS_LCD_MENU
  586. wait_for_user = false;
  587. #endif
  588. }
  589. if (strcmp(command, "M112") == 0) kill();
  590. if (strcmp(command, "M410") == 0) quickstop_stepper();
  591. #endif
  592. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  593. last_command_time = ms;
  594. #endif
  595. // Add the command to the queue
  596. _enqueuecommand(serial_line_buffer[i], true
  597. #if NUM_SERIAL > 1
  598. , i
  599. #endif
  600. );
  601. }
  602. else if (serial_count[i] >= MAX_CMD_SIZE - 1) {
  603. // Keep fetching, but ignore normal characters beyond the max length
  604. // The command will be injected when EOL is reached
  605. }
  606. else if (serial_char == '\\') { // Handle escapes
  607. // if we have one more character, copy it over
  608. if ((c = read_serial(i)) >= 0 && !serial_comment_mode[i]
  609. #if ENABLED(PAREN_COMMENTS)
  610. && !serial_comment_paren_mode[i]
  611. #endif
  612. )
  613. serial_line_buffer[i][serial_count[i]++] = (char)c;
  614. }
  615. else { // it's not a newline, carriage return or escape char
  616. if (serial_char == ';') serial_comment_mode[i] = true;
  617. #if ENABLED(PAREN_COMMENTS)
  618. else if (serial_char == '(') serial_comment_paren_mode[i] = true;
  619. else if (serial_char == ')') serial_comment_paren_mode[i] = false;
  620. #endif
  621. else if (!serial_comment_mode[i]
  622. #if ENABLED(PAREN_COMMENTS)
  623. && ! serial_comment_paren_mode[i]
  624. #endif
  625. ) serial_line_buffer[i][serial_count[i]++] = serial_char;
  626. }
  627. } // for NUM_SERIAL
  628. } // queue has space, serial has data
  629. }
  630. #if ENABLED(SDSUPPORT)
  631. /**
  632. * Get commands from the SD Card until the command buffer is full
  633. * or until the end of the file is reached. The special character '#'
  634. * can also interrupt buffering.
  635. */
  636. inline void get_sdcard_commands() {
  637. static bool stop_buffering = false,
  638. sd_comment_mode = false
  639. #if ENABLED(PAREN_COMMENTS)
  640. , sd_comment_paren_mode = false
  641. #endif
  642. ;
  643. if (!IS_SD_PRINTING()) return;
  644. /**
  645. * '#' stops reading from SD to the buffer prematurely, so procedural
  646. * macro calls are possible. If it occurs, stop_buffering is triggered
  647. * and the buffer is run dry; this character _can_ occur in serial com
  648. * due to checksums, however, no checksums are used in SD printing.
  649. */
  650. if (commands_in_queue == 0) stop_buffering = false;
  651. uint16_t sd_count = 0;
  652. bool card_eof = card.eof();
  653. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  654. const int16_t n = card.get();
  655. char sd_char = (char)n;
  656. card_eof = card.eof();
  657. if (card_eof || n == -1
  658. || sd_char == '\n' || sd_char == '\r'
  659. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode
  660. #if ENABLED(PAREN_COMMENTS)
  661. && !sd_comment_paren_mode
  662. #endif
  663. )
  664. ) {
  665. if (card_eof) {
  666. card.printingHasFinished();
  667. if (IS_SD_PRINTING())
  668. sd_count = 0; // If a sub-file was printing, continue from call point
  669. else {
  670. SERIAL_ECHOLNPGM(MSG_FILE_PRINTED);
  671. #if ENABLED(PRINTER_EVENT_LEDS)
  672. printerEventLEDs.onPrintCompleted();
  673. #if HAS_RESUME_CONTINUE
  674. enqueue_and_echo_commands_P(PSTR("M0 S"
  675. #if HAS_LCD_MENU
  676. "1800"
  677. #else
  678. "60"
  679. #endif
  680. ));
  681. #endif
  682. #endif // PRINTER_EVENT_LEDS
  683. }
  684. }
  685. else if (n == -1)
  686. SERIAL_ERROR_MSG(MSG_SD_ERR_READ);
  687. if (sd_char == '#') stop_buffering = true;
  688. sd_comment_mode = false; // for new command
  689. #if ENABLED(PAREN_COMMENTS)
  690. sd_comment_paren_mode = false;
  691. #endif
  692. // Skip empty lines and comments
  693. if (!sd_count) { thermalManager.manage_heater(); continue; }
  694. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  695. sd_count = 0; // clear sd line buffer
  696. _commit_command(false);
  697. }
  698. else if (sd_count >= MAX_CMD_SIZE - 1) {
  699. /**
  700. * Keep fetching, but ignore normal characters beyond the max length
  701. * The command will be injected when EOL is reached
  702. */
  703. }
  704. else {
  705. if (sd_char == ';') sd_comment_mode = true;
  706. #if ENABLED(PAREN_COMMENTS)
  707. else if (sd_char == '(') sd_comment_paren_mode = true;
  708. else if (sd_char == ')') sd_comment_paren_mode = false;
  709. #endif
  710. else if (!sd_comment_mode
  711. #if ENABLED(PAREN_COMMENTS)
  712. && ! sd_comment_paren_mode
  713. #endif
  714. ) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  715. }
  716. }
  717. }
  718. #endif // SDSUPPORT
  719. /**
  720. * Add to the circular command queue the next command from:
  721. * - The command-injection queue (injected_commands_P)
  722. * - The active serial input (usually USB)
  723. * - The SD card file being actively printed
  724. */
  725. void get_available_commands() {
  726. // if any immediate commands remain, don't get other commands yet
  727. if (drain_injected_commands_P()) return;
  728. get_serial_commands();
  729. #if ENABLED(SDSUPPORT)
  730. get_sdcard_commands();
  731. #endif
  732. }
  733. /**
  734. * Get the next command in the queue, optionally log it to SD, then dispatch it
  735. */
  736. void advance_command_queue() {
  737. if (!commands_in_queue) return;
  738. #if ENABLED(SDSUPPORT)
  739. if (card.flag.saving) {
  740. char* command = command_queue[cmd_queue_index_r];
  741. if (is_M29(command)) {
  742. // M29 closes the file
  743. card.closefile();
  744. SERIAL_ECHOLNPGM(MSG_FILE_SAVED);
  745. #if !defined(__AVR__) || !defined(USBCON)
  746. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  747. SERIAL_ECHOLNPAIR("Dropped bytes: ", MYSERIAL0.dropped());
  748. #endif
  749. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  750. SERIAL_ECHOLNPAIR("Max RX Queue Size: ", MYSERIAL0.rxMaxEnqueued());
  751. #endif
  752. #endif // !defined(__AVR__) || !defined(USBCON)
  753. ok_to_send();
  754. }
  755. else {
  756. // Write the string from the read buffer to SD
  757. card.write_command(command);
  758. if (card.flag.logging)
  759. gcode.process_next_command(); // The card is saving because it's logging
  760. else
  761. ok_to_send();
  762. }
  763. }
  764. else
  765. gcode.process_next_command();
  766. #else
  767. gcode.process_next_command();
  768. #endif // SDSUPPORT
  769. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  770. if (commands_in_queue) {
  771. --commands_in_queue;
  772. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  773. }
  774. }