My Marlin configs for Fabrikator Mini and CTC i3 Pro B
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

queue.cpp 27KB

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