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

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