My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

queue.cpp 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 "../Marlin.h"
  31. #if HAS_COLOR_LEDS
  32. #include "../feature/leds/leds.h"
  33. #endif
  34. /**
  35. * GCode line number handling. Hosts may opt to include line numbers when
  36. * sending commands to Marlin, and lines will be checked for sequentiality.
  37. * M110 N<int> sets the current line number.
  38. */
  39. long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  40. /**
  41. * GCode Command Queue
  42. * A simple ring buffer of BUFSIZE command strings.
  43. *
  44. * Commands are copied into this buffer by the command injectors
  45. * (immediate, serial, sd card) and they are processed sequentially by
  46. * the main loop. The gcode.process_next_command method parses the next
  47. * command and hands off execution to individual handler functions.
  48. */
  49. uint8_t commands_in_queue = 0, // Count of commands in the queue
  50. cmd_queue_index_r = 0, // Ring buffer read position
  51. cmd_queue_index_w = 0; // Ring buffer write position
  52. char command_queue[BUFSIZE][MAX_CMD_SIZE];
  53. /**
  54. * Serial command injection
  55. */
  56. // Number of characters read in the current line of serial input
  57. static int serial_count = 0;
  58. bool send_ok[BUFSIZE];
  59. /**
  60. * Next Injected Command pointer. NULL if no commands are being injected.
  61. * Used by Marlin internally to ensure that commands initiated from within
  62. * are enqueued ahead of any pending serial or sd card commands.
  63. */
  64. static const char *injected_commands_P = NULL;
  65. void queue_setup() {
  66. // Send "ok" after commands by default
  67. for (uint8_t i = 0; i < COUNT(send_ok); i++) send_ok[i] = true;
  68. }
  69. /**
  70. * Clear the Marlin command queue
  71. */
  72. void clear_command_queue() {
  73. cmd_queue_index_r = cmd_queue_index_w;
  74. commands_in_queue = 0;
  75. }
  76. /**
  77. * Once a new command is in the ring buffer, call this to commit it
  78. */
  79. inline void _commit_command(bool say_ok) {
  80. send_ok[cmd_queue_index_w] = say_ok;
  81. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  82. commands_in_queue++;
  83. }
  84. /**
  85. * Copy a command from RAM into the main command buffer.
  86. * Return true if the command was successfully added.
  87. * Return false for a full buffer, or if the 'command' is a comment.
  88. */
  89. inline bool _enqueuecommand(const char* cmd, bool say_ok/*=false*/) {
  90. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  91. strcpy(command_queue[cmd_queue_index_w], cmd);
  92. _commit_command(say_ok);
  93. return true;
  94. }
  95. /**
  96. * Enqueue with Serial Echo
  97. */
  98. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  99. if (_enqueuecommand(cmd, say_ok)) {
  100. SERIAL_ECHO_START();
  101. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  102. SERIAL_CHAR('"');
  103. SERIAL_EOL();
  104. return true;
  105. }
  106. return false;
  107. }
  108. /**
  109. * Inject the next "immediate" command, when possible, onto the front of the queue.
  110. * Return true if any immediate commands remain to inject.
  111. */
  112. static bool drain_injected_commands_P() {
  113. if (injected_commands_P != NULL) {
  114. size_t i = 0;
  115. char c, cmd[30];
  116. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  117. cmd[sizeof(cmd) - 1] = '\0';
  118. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  119. cmd[i] = '\0';
  120. if (enqueue_and_echo_command(cmd)) // success?
  121. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  122. }
  123. return (injected_commands_P != NULL); // return whether any more remain
  124. }
  125. /**
  126. * Record one or many commands to run from program memory.
  127. * Aborts the current queue, if any.
  128. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  129. */
  130. void enqueue_and_echo_commands_P(const char * const pgcode) {
  131. injected_commands_P = pgcode;
  132. (void)drain_injected_commands_P(); // first command executed asap (when possible)
  133. }
  134. #if HAS_QUEUE_NOW
  135. /**
  136. * Enqueue and return only when commands are actually enqueued
  137. */
  138. void enqueue_and_echo_command_now(const char* cmd, bool say_ok/*=false*/) {
  139. while (!enqueue_and_echo_command(cmd, say_ok)) idle();
  140. }
  141. #if HAS_LCD_QUEUE_NOW
  142. /**
  143. * Enqueue from program memory and return only when commands are actually enqueued
  144. */
  145. void enqueue_and_echo_commands_P_now(const char * const pgcode) {
  146. enqueue_and_echo_commands_P(pgcode);
  147. while (drain_injected_commands_P()) idle();
  148. }
  149. #endif
  150. #endif
  151. /**
  152. * Send an "ok" message to the host, indicating
  153. * that a command was successfully processed.
  154. *
  155. * If ADVANCED_OK is enabled also include:
  156. * N<int> Line number of the command, if any
  157. * P<int> Planner space remaining
  158. * B<int> Block queue space remaining
  159. */
  160. void ok_to_send() {
  161. gcode.refresh_cmd_timeout();
  162. if (!send_ok[cmd_queue_index_r]) return;
  163. SERIAL_PROTOCOLPGM(MSG_OK);
  164. #if ENABLED(ADVANCED_OK)
  165. char* p = command_queue[cmd_queue_index_r];
  166. if (*p == 'N') {
  167. SERIAL_PROTOCOL(' ');
  168. SERIAL_ECHO(*p++);
  169. while (NUMERIC_SIGNED(*p))
  170. SERIAL_ECHO(*p++);
  171. }
  172. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  173. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  174. #endif
  175. SERIAL_EOL();
  176. }
  177. /**
  178. * Send a "Resend: nnn" message to the host to
  179. * indicate that a command needs to be re-sent.
  180. */
  181. void flush_and_request_resend() {
  182. //char command_queue[cmd_queue_index_r][100]="Resend:";
  183. MYSERIAL.flush();
  184. SERIAL_PROTOCOLPGM(MSG_RESEND);
  185. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  186. ok_to_send();
  187. }
  188. void gcode_line_error(const char* err, bool doFlush = true) {
  189. SERIAL_ERROR_START();
  190. serialprintPGM(err);
  191. SERIAL_ERRORLN(gcode_LastN);
  192. //Serial.println(gcode_N);
  193. if (doFlush) flush_and_request_resend();
  194. serial_count = 0;
  195. }
  196. /**
  197. * Get all commands waiting on the serial port and queue them.
  198. * Exit when the buffer is full or when no more characters are
  199. * left on the serial port.
  200. */
  201. inline void get_serial_commands() {
  202. static char serial_line_buffer[MAX_CMD_SIZE];
  203. static bool serial_comment_mode = false;
  204. // If the command buffer is empty for too long,
  205. // send "wait" to indicate Marlin is still waiting.
  206. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  207. static millis_t last_command_time = 0;
  208. const millis_t ms = millis();
  209. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  210. SERIAL_ECHOLNPGM(MSG_WAIT);
  211. last_command_time = ms;
  212. }
  213. #endif
  214. /**
  215. * Loop while serial characters are incoming and the queue is not full
  216. */
  217. int c;
  218. while (commands_in_queue < BUFSIZE && (c = MYSERIAL.read()) >= 0) {
  219. char serial_char = c;
  220. /**
  221. * If the character ends the line
  222. */
  223. if (serial_char == '\n' || serial_char == '\r') {
  224. serial_comment_mode = false; // end of line == end of comment
  225. if (!serial_count) continue; // Skip empty lines
  226. serial_line_buffer[serial_count] = 0; // Terminate string
  227. serial_count = 0; // Reset buffer
  228. char* command = serial_line_buffer;
  229. while (*command == ' ') command++; // Skip leading spaces
  230. char *npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  231. if (npos) {
  232. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  233. if (M110) {
  234. char* n2pos = strchr(command + 4, 'N');
  235. if (n2pos) npos = n2pos;
  236. }
  237. gcode_N = strtol(npos + 1, NULL, 10);
  238. if (gcode_N != gcode_LastN + 1 && !M110) {
  239. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  240. return;
  241. }
  242. char *apos = strrchr(command, '*');
  243. if (apos) {
  244. uint8_t checksum = 0, count = uint8_t(apos - command);
  245. while (count) checksum ^= command[--count];
  246. if (strtol(apos + 1, NULL, 10) != checksum) {
  247. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  248. return;
  249. }
  250. }
  251. else {
  252. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  253. return;
  254. }
  255. gcode_LastN = gcode_N;
  256. }
  257. // Movement commands alert when stopped
  258. if (IsStopped()) {
  259. char* gpos = strchr(command, 'G');
  260. if (gpos) {
  261. const int codenum = strtol(gpos + 1, NULL, 10);
  262. switch (codenum) {
  263. case 0:
  264. case 1:
  265. case 2:
  266. case 3:
  267. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  268. LCD_MESSAGEPGM(MSG_STOPPED);
  269. break;
  270. }
  271. }
  272. }
  273. #if DISABLED(EMERGENCY_PARSER)
  274. // If command was e-stop process now
  275. if (strcmp(command, "M108") == 0) {
  276. wait_for_heatup = false;
  277. #if ENABLED(ULTIPANEL)
  278. wait_for_user = false;
  279. #endif
  280. }
  281. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  282. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  283. #endif
  284. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  285. last_command_time = ms;
  286. #endif
  287. // Add the command to the queue
  288. _enqueuecommand(serial_line_buffer, true);
  289. }
  290. else if (serial_count >= MAX_CMD_SIZE - 1) {
  291. // Keep fetching, but ignore normal characters beyond the max length
  292. // The command will be injected when EOL is reached
  293. }
  294. else if (serial_char == '\\') { // Handle escapes
  295. // if we have one more character, copy it over
  296. if ((c = MYSERIAL.read()) >= 0 && !serial_comment_mode)
  297. serial_line_buffer[serial_count++] = serial_char;
  298. }
  299. else { // it's not a newline, carriage return or escape char
  300. if (serial_char == ';') serial_comment_mode = true;
  301. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  302. }
  303. } // queue has space, serial has data
  304. }
  305. #if ENABLED(SDSUPPORT)
  306. /**
  307. * Get commands from the SD Card until the command buffer is full
  308. * or until the end of the file is reached. The special character '#'
  309. * can also interrupt buffering.
  310. */
  311. inline void get_sdcard_commands() {
  312. static bool stop_buffering = false,
  313. sd_comment_mode = false;
  314. if (!IS_SD_PRINTING) return;
  315. /**
  316. * '#' stops reading from SD to the buffer prematurely, so procedural
  317. * macro calls are possible. If it occurs, stop_buffering is triggered
  318. * and the buffer is run dry; this character _can_ occur in serial com
  319. * due to checksums, however, no checksums are used in SD printing.
  320. */
  321. if (commands_in_queue == 0) stop_buffering = false;
  322. uint16_t sd_count = 0;
  323. bool card_eof = card.eof();
  324. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  325. const int16_t n = card.get();
  326. char sd_char = (char)n;
  327. card_eof = card.eof();
  328. if (card_eof || n == -1
  329. || sd_char == '\n' || sd_char == '\r'
  330. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  331. ) {
  332. if (card_eof) {
  333. card.printingHasFinished();
  334. if (card.sdprinting)
  335. sd_count = 0; // If a sub-file was printing, continue from call point
  336. else {
  337. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  338. #if ENABLED(PRINTER_EVENT_LEDS)
  339. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  340. leds.set_green();
  341. #if HAS_RESUME_CONTINUE
  342. enqueue_and_echo_commands_P(PSTR("M0")); // end of the queue!
  343. #else
  344. safe_delay(1000);
  345. #endif
  346. leds.set_off();
  347. #endif
  348. card.checkautostart(true);
  349. }
  350. }
  351. else if (n == -1) {
  352. SERIAL_ERROR_START();
  353. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  354. }
  355. if (sd_char == '#') stop_buffering = true;
  356. sd_comment_mode = false; // for new command
  357. if (!sd_count) continue; // skip empty lines (and comment lines)
  358. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  359. sd_count = 0; // clear sd line buffer
  360. _commit_command(false);
  361. }
  362. else if (sd_count >= MAX_CMD_SIZE - 1) {
  363. /**
  364. * Keep fetching, but ignore normal characters beyond the max length
  365. * The command will be injected when EOL is reached
  366. */
  367. }
  368. else {
  369. if (sd_char == ';') sd_comment_mode = true;
  370. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  371. }
  372. }
  373. }
  374. #endif // SDSUPPORT
  375. /**
  376. * Add to the circular command queue the next command from:
  377. * - The command-injection queue (injected_commands_P)
  378. * - The active serial input (usually USB)
  379. * - The SD card file being actively printed
  380. */
  381. void get_available_commands() {
  382. // if any immediate commands remain, don't get other commands yet
  383. if (drain_injected_commands_P()) return;
  384. get_serial_commands();
  385. #if ENABLED(SDSUPPORT)
  386. get_sdcard_commands();
  387. #endif
  388. }
  389. /**
  390. * Get the next command in the queue, optionally log it to SD, then dispatch it
  391. */
  392. void advance_command_queue() {
  393. if (!commands_in_queue) return;
  394. #if ENABLED(SDSUPPORT)
  395. if (card.saving) {
  396. char* command = command_queue[cmd_queue_index_r];
  397. if (strstr_P(command, PSTR("M29"))) {
  398. // M29 closes the file
  399. card.closefile();
  400. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  401. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  402. SERIAL_ECHOLNPAIR("Dropped bytes: ", customizedSerial.dropped());
  403. #endif
  404. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  405. SERIAL_ECHOLNPAIR("Max RX Queue Size: ", customizedSerial.rxMaxEnqueued());
  406. #endif
  407. ok_to_send();
  408. }
  409. else {
  410. // Write the string from the read buffer to SD
  411. card.write_command(command);
  412. if (card.logging)
  413. gcode.process_next_command(); // The card is saving because it's logging
  414. else
  415. ok_to_send();
  416. }
  417. }
  418. else
  419. gcode.process_next_command();
  420. #else
  421. gcode.process_next_command();
  422. #endif // SDSUPPORT
  423. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  424. if (commands_in_queue) {
  425. --commands_in_queue;
  426. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  427. }
  428. }