My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

queue.cpp 27KB

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