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

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