My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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