cmdqueue.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. #include <util/atomic.h>
  2. #include "cmdqueue.h"
  3. #include "cardreader.h"
  4. #include "ultralcd.h"
  5. #include "Prusa_farm.h"
  6. // Reserve BUFSIZE lines of length MAX_CMD_SIZE plus CMDBUFFER_RESERVE_FRONT.
  7. char cmdbuffer[BUFSIZE * (MAX_CMD_SIZE + 1) + CMDBUFFER_RESERVE_FRONT];
  8. // Head of the circular buffer, where to read.
  9. size_t bufindr = 0;
  10. // Tail of the buffer, where to write.
  11. static size_t bufindw = 0;
  12. // Number of lines in cmdbuffer.
  13. int buflen = 0;
  14. // Flag for processing the current command inside the main Arduino loop().
  15. // If a new command was pushed to the front of a command buffer while
  16. // processing another command, this replaces the command on the top.
  17. // Therefore don't remove the command from the queue in the loop() function.
  18. bool cmdbuffer_front_already_processed = false;
  19. // Used for temporarely preventing accidental adding of Serial commands to the queue.
  20. // For now only check_file and the fancheck pause use this.
  21. bool cmdqueue_serial_disabled = false;
  22. int serial_count = 0; //index of character read from serial line
  23. bool comment_mode = false;
  24. char *strchr_pointer; // just a pointer to find chars in the command string like X, Y, Z, E, etc
  25. ShortTimer serialTimeoutTimer;
  26. long gcode_N = 0;
  27. long gcode_LastN = 0;
  28. uint32_t sdpos_atomic = 0;
  29. // Pop the currently processed command from the queue.
  30. // It is expected, that there is at least one command in the queue.
  31. bool cmdqueue_pop_front()
  32. {
  33. if (buflen > 0) {
  34. #ifdef CMDBUFFER_DEBUG
  35. SERIAL_ECHOPGM("Dequeing ");
  36. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  37. SERIAL_ECHOLNPGM("");
  38. SERIAL_ECHOPGM("Old indices: buflen ");
  39. SERIAL_ECHO(buflen);
  40. SERIAL_ECHOPGM(", bufindr ");
  41. SERIAL_ECHO(bufindr);
  42. SERIAL_ECHOPGM(", bufindw ");
  43. SERIAL_ECHO(bufindw);
  44. SERIAL_ECHOPGM(", serial_count ");
  45. SERIAL_ECHO(serial_count);
  46. SERIAL_ECHOPGM(", bufsize ");
  47. SERIAL_ECHO(sizeof(cmdbuffer));
  48. SERIAL_ECHOLNPGM("");
  49. #endif /* CMDBUFFER_DEBUG */
  50. if (-- buflen == 0) {
  51. // Empty buffer.
  52. if (serial_count == 0)
  53. // No serial communication is pending. Reset both pointers to zero.
  54. bufindw = 0;
  55. bufindr = bufindw;
  56. } else {
  57. // There is at least one ready line in the buffer.
  58. // First skip the current command ID and iterate up to the end of the string.
  59. for (bufindr += CMDHDRSIZE; cmdbuffer[bufindr] != 0; ++ bufindr) ;
  60. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  61. for (++ bufindr; bufindr < sizeof(cmdbuffer) && cmdbuffer[bufindr] == 0; ++ bufindr) ;
  62. // If the end of the buffer was empty,
  63. if (bufindr == sizeof(cmdbuffer)) {
  64. // skip to the start and find the nonzero command.
  65. for (bufindr = 0; cmdbuffer[bufindr] == 0; ++ bufindr) ;
  66. }
  67. #ifdef CMDBUFFER_DEBUG
  68. SERIAL_ECHOPGM("New indices: buflen ");
  69. SERIAL_ECHO(buflen);
  70. SERIAL_ECHOPGM(", bufindr ");
  71. SERIAL_ECHO(bufindr);
  72. SERIAL_ECHOPGM(", bufindw ");
  73. SERIAL_ECHO(bufindw);
  74. SERIAL_ECHOPGM(", serial_count ");
  75. SERIAL_ECHO(serial_count);
  76. SERIAL_ECHOPGM(" new command on the top: ");
  77. SERIAL_ECHO(cmdbuffer+bufindr+CMDHDRSIZE);
  78. SERIAL_ECHOLNPGM("");
  79. #endif /* CMDBUFFER_DEBUG */
  80. }
  81. return true;
  82. }
  83. return false;
  84. }
  85. void cmdqueue_reset()
  86. {
  87. while (buflen)
  88. {
  89. // printf_P(PSTR("dumping: \"%s\" of type %u\n"), cmdbuffer+bufindr+CMDHDRSIZE, CMDBUFFER_CURRENT_TYPE);
  90. ClearToSend();
  91. cmdqueue_pop_front();
  92. }
  93. bufindr = 0;
  94. bufindw = 0;
  95. //commands are removed from command queue after process_command() function is finished
  96. //reseting command queue and enqueing new commands during some (usually long running) command processing would cause that new commands are immediately removed from queue (or damaged)
  97. //this will ensure that all new commands which are enqueued after cmdqueue reset, will be always executed
  98. cmdbuffer_front_already_processed = true;
  99. }
  100. // How long a string could be pushed to the front of the command queue?
  101. // If yes, adjust bufindr to the new position, where the new command could be enqued.
  102. // len_asked does not contain the zero terminator size.
  103. static bool cmdqueue_could_enqueue_front(size_t len_asked)
  104. {
  105. // MAX_CMD_SIZE has to accommodate the zero terminator.
  106. if (len_asked >= MAX_CMD_SIZE)
  107. return false;
  108. // Remove the currently processed command from the queue.
  109. if (! cmdbuffer_front_already_processed) {
  110. cmdqueue_pop_front();
  111. cmdbuffer_front_already_processed = true;
  112. }
  113. if (bufindr == bufindw && buflen > 0)
  114. // Full buffer.
  115. return false;
  116. // Adjust the end of the write buffer based on whether a partial line is in the receive buffer.
  117. int endw = (serial_count > 0) ? (bufindw + MAX_CMD_SIZE + 1) : bufindw;
  118. if (bufindw < bufindr) {
  119. int bufindr_new = bufindr - len_asked - (1 + CMDHDRSIZE);
  120. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  121. if (endw <= bufindr_new) {
  122. bufindr = bufindr_new;
  123. return true;
  124. }
  125. } else {
  126. // Otherwise the free space is split between the start and end.
  127. if (len_asked + (1 + CMDHDRSIZE) <= bufindr) {
  128. // Could fit at the start.
  129. bufindr -= len_asked + (1 + CMDHDRSIZE);
  130. return true;
  131. }
  132. int bufindr_new = sizeof(cmdbuffer) - len_asked - (1 + CMDHDRSIZE);
  133. if (endw <= bufindr_new) {
  134. memset(cmdbuffer, 0, bufindr);
  135. bufindr = bufindr_new;
  136. return true;
  137. }
  138. }
  139. return false;
  140. }
  141. // Could one enqueue a command of length len_asked into the buffer,
  142. // while leaving CMDBUFFER_RESERVE_FRONT at the start?
  143. // If yes, adjust bufindw to the new position, where the new command could be enqued.
  144. // len_asked does not contain the zero terminator size.
  145. // This function may update bufindw, therefore for the power panic to work, this function must be called
  146. // with the interrupts disabled!
  147. static bool __attribute__((noinline)) cmdqueue_could_enqueue_back(size_t len_asked)
  148. {
  149. // MAX_CMD_SIZE has to accommodate the zero terminator.
  150. if (len_asked >= MAX_CMD_SIZE)
  151. return false;
  152. if (bufindr == bufindw && buflen > 0)
  153. // Full buffer.
  154. return false;
  155. // If there is some data stored starting at bufindw, len_asked is certainly smaller than
  156. // the allocated data buffer. Try to reserve a new buffer and to move the already received
  157. // serial data.
  158. // How much memory to reserve for the commands pushed to the front?
  159. // End of the queue, when pushing to the end.
  160. size_t endw = bufindw + len_asked + (1 + CMDHDRSIZE);
  161. if (bufindw < bufindr)
  162. // Simple case. There is a contiguous space between the write buffer and the read buffer.
  163. return endw + CMDBUFFER_RESERVE_FRONT <= bufindr;
  164. // Otherwise the free space is split between the start and end.
  165. if (// Could one fit to the end, including the reserve?
  166. endw + CMDBUFFER_RESERVE_FRONT <= sizeof(cmdbuffer) ||
  167. // Could one fit to the end, and the reserve to the start?
  168. (endw <= sizeof(cmdbuffer) && CMDBUFFER_RESERVE_FRONT <= bufindr))
  169. return true;
  170. // Could one fit both to the start?
  171. if (len_asked + (1 + CMDHDRSIZE) + CMDBUFFER_RESERVE_FRONT <= bufindr) {
  172. // Mark the rest of the buffer as used.
  173. memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
  174. // and point to the start.
  175. // Be careful! The bufindw needs to be changed atomically for the power panic & filament panic to work.
  176. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { bufindw = 0; }
  177. return true;
  178. }
  179. return false;
  180. }
  181. #ifdef CMDBUFFER_DEBUG
  182. void cmdqueue_dump_to_serial_single_line(int nr, const char *p)
  183. {
  184. SERIAL_ECHOPGM("Entry nr: ");
  185. SERIAL_ECHO(nr);
  186. SERIAL_ECHOPGM(", type: ");
  187. int type = *p;
  188. SERIAL_ECHO(type);
  189. SERIAL_ECHOPGM(", size: ");
  190. unsigned int size = *(unsigned int*)(p + 1);
  191. SERIAL_ECHO(size);
  192. SERIAL_ECHOPGM(", cmd: ");
  193. SERIAL_ECHO(p + CMDHDRSIZE);
  194. SERIAL_ECHOLNPGM("");
  195. }
  196. void cmdqueue_dump_to_serial()
  197. {
  198. if (buflen == 0) {
  199. SERIAL_ECHOLNPGM("The command buffer is empty.");
  200. } else {
  201. SERIAL_ECHOPGM("Content of the buffer: entries ");
  202. SERIAL_ECHO(buflen);
  203. SERIAL_ECHOPGM(", indr ");
  204. SERIAL_ECHO(bufindr);
  205. SERIAL_ECHOPGM(", indw ");
  206. SERIAL_ECHO(bufindw);
  207. SERIAL_ECHOLNPGM("");
  208. int nr = 0;
  209. if (bufindr < bufindw) {
  210. for (const char *p = cmdbuffer + bufindr; p < cmdbuffer + bufindw; ++ nr) {
  211. cmdqueue_dump_to_serial_single_line(nr, p);
  212. // Skip the command.
  213. for (p += CMDHDRSIZE; *p != 0; ++ p);
  214. // Skip the gaps.
  215. for (++p; p < cmdbuffer + bufindw && *p == 0; ++ p);
  216. }
  217. } else {
  218. for (const char *p = cmdbuffer + bufindr; p < cmdbuffer + sizeof(cmdbuffer); ++ nr) {
  219. cmdqueue_dump_to_serial_single_line(nr, p);
  220. // Skip the command.
  221. for (p += CMDHDRSIZE; *p != 0; ++ p);
  222. // Skip the gaps.
  223. for (++p; p < cmdbuffer + sizeof(cmdbuffer) && *p == 0; ++ p);
  224. }
  225. for (const char *p = cmdbuffer; p < cmdbuffer + bufindw; ++ nr) {
  226. cmdqueue_dump_to_serial_single_line(nr, p);
  227. // Skip the command.
  228. for (p += CMDHDRSIZE; *p != 0; ++ p);
  229. // Skip the gaps.
  230. for (++p; p < cmdbuffer + bufindw && *p == 0; ++ p);
  231. }
  232. }
  233. SERIAL_ECHOLNPGM("End of the buffer.");
  234. }
  235. }
  236. #endif /* CMDBUFFER_DEBUG */
  237. //adds an command to the main command buffer
  238. //thats really done in a non-safe way.
  239. //needs overworking someday
  240. // Currently the maximum length of a command piped through this function is around 20 characters
  241. void enquecommand(const char *cmd, bool from_progmem)
  242. {
  243. size_t len = from_progmem ? strlen_P(cmd) : strlen(cmd);
  244. // Does cmd fit the queue while leaving sufficient space at the front for the chained commands?
  245. // If it fits, it may move bufindw, so it points to a contiguous buffer, which fits cmd.
  246. if (cmdqueue_could_enqueue_back(len)) {
  247. // This is dangerous if a mixing of serial and this happens
  248. // This may easily be tested: If serial_count > 0, we have a problem.
  249. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_UI;
  250. if (from_progmem)
  251. strcpy_P(cmdbuffer + bufindw + CMDHDRSIZE, cmd);
  252. else
  253. strcpy(cmdbuffer + bufindw + CMDHDRSIZE, cmd);
  254. SERIAL_ECHO_START;
  255. SERIAL_ECHORPGM(MSG_Enqueing);
  256. SERIAL_ECHO(cmdbuffer + bufindw + CMDHDRSIZE);
  257. SERIAL_ECHOLNPGM("\"");
  258. bufindw += len + (CMDHDRSIZE + 1);
  259. if (bufindw == sizeof(cmdbuffer))
  260. bufindw = 0;
  261. ++ buflen;
  262. #ifdef CMDBUFFER_DEBUG
  263. cmdqueue_dump_to_serial();
  264. #endif /* CMDBUFFER_DEBUG */
  265. } else {
  266. SERIAL_ERROR_START;
  267. SERIAL_ECHORPGM(MSG_Enqueing);
  268. if (from_progmem)
  269. SERIAL_PROTOCOLRPGM(cmd);
  270. else
  271. SERIAL_ECHO(cmd);
  272. SERIAL_ECHOLNPGM("\" failed: Buffer full!");
  273. #ifdef CMDBUFFER_DEBUG
  274. cmdqueue_dump_to_serial();
  275. #endif /* CMDBUFFER_DEBUG */
  276. }
  277. }
  278. bool cmd_buffer_empty()
  279. {
  280. return (buflen == 0);
  281. }
  282. void enquecommand_front(const char *cmd, bool from_progmem)
  283. {
  284. size_t len = from_progmem ? strlen_P(cmd) : strlen(cmd);
  285. // Does cmd fit the queue? This call shall move bufindr, so the command may be copied.
  286. if (cmdqueue_could_enqueue_front(len)) {
  287. cmdbuffer[bufindr] = CMDBUFFER_CURRENT_TYPE_UI;
  288. if (from_progmem)
  289. strcpy_P(cmdbuffer + bufindr + CMDHDRSIZE, cmd);
  290. else
  291. strcpy(cmdbuffer + bufindr + CMDHDRSIZE, cmd);
  292. ++ buflen;
  293. SERIAL_ECHO_START;
  294. SERIAL_ECHOPGM("Enqueing to the front: \"");
  295. SERIAL_ECHO(cmdbuffer + bufindr + CMDHDRSIZE);
  296. SERIAL_ECHOLNPGM("\"");
  297. #ifdef CMDBUFFER_DEBUG
  298. cmdqueue_dump_to_serial();
  299. #endif /* CMDBUFFER_DEBUG */
  300. } else {
  301. SERIAL_ERROR_START;
  302. SERIAL_ECHOPGM("Enqueing to the front: \"");
  303. if (from_progmem)
  304. SERIAL_PROTOCOLRPGM(cmd);
  305. else
  306. SERIAL_ECHO(cmd);
  307. SERIAL_ECHOLNPGM("\" failed: Buffer full!");
  308. #ifdef CMDBUFFER_DEBUG
  309. cmdqueue_dump_to_serial();
  310. #endif /* CMDBUFFER_DEBUG */
  311. }
  312. }
  313. // Mark the command at the top of the command queue as new.
  314. // Therefore it will not be removed from the queue.
  315. void repeatcommand_front()
  316. {
  317. cmdbuffer_front_already_processed = true;
  318. }
  319. void get_command()
  320. {
  321. // Test and reserve space for the new command string.
  322. if (! cmdqueue_could_enqueue_back(MAX_CMD_SIZE - 1))
  323. return;
  324. if (MYSERIAL.available() == RX_BUFFER_SIZE - 1) { //compare number of chars buffered in rx buffer with rx buffer size
  325. MYSERIAL.flush();
  326. SERIAL_ECHOLNPGM("Full RX Buffer"); //if buffer was full, there is danger that reading of last gcode will not be completed
  327. }
  328. // start of serial line processing loop
  329. while (((MYSERIAL.available() > 0 && !saved_printing) || (MYSERIAL.available() > 0 && isPrintPaused)) && !cmdqueue_serial_disabled) { //is print is saved (crash detection or filament detection), dont process data from serial line
  330. char serial_char = MYSERIAL.read();
  331. serialTimeoutTimer.start();
  332. if (serial_char < 0)
  333. // Ignore extended ASCII characters. These characters have no meaning in the G-code apart from the file names
  334. // and Marlin does not support such file names anyway.
  335. // Serial characters with a highest bit set to 1 are generated when the USB cable is unplugged, leading
  336. // to a hang-up of the print process from an SD card.
  337. continue;
  338. if(serial_char == '\n' ||
  339. serial_char == '\r' ||
  340. serial_count >= (MAX_CMD_SIZE - 1) )
  341. {
  342. if(!serial_count) { //if empty line
  343. comment_mode = false; //for new command
  344. return;
  345. }
  346. cmdbuffer[bufindw+serial_count+CMDHDRSIZE] = 0; //terminate string
  347. if(!comment_mode){
  348. gcode_N = 0;
  349. // Line numbers must be first in buffer
  350. if ((strstr_P(cmdbuffer+bufindw+CMDHDRSIZE, PSTR("PRUSA")) == NULL) &&
  351. (cmdbuffer[bufindw+CMDHDRSIZE] == 'N')) {
  352. // Line number met. When sending a G-code over a serial line, each line may be stamped with its index,
  353. // and Marlin tests, whether the successive lines are stamped with an increasing line number ID
  354. gcode_N = (strtol(cmdbuffer+bufindw+CMDHDRSIZE+1, NULL, 10));
  355. if(gcode_N != gcode_LastN+1 && (strstr_P(cmdbuffer+bufindw+CMDHDRSIZE, PSTR("M110")) == NULL) ) {
  356. // M110 - set current line number.
  357. // Line numbers not sent in succession.
  358. SERIAL_ERROR_START;
  359. SERIAL_ERRORRPGM(_n("Line Number is not Last Line Number+1, Last Line: "));////MSG_ERR_LINE_NO
  360. SERIAL_ERRORLN(gcode_LastN);
  361. //Serial.println(gcode_N);
  362. FlushSerialRequestResend();
  363. serial_count = 0;
  364. return;
  365. }
  366. if((strchr_pointer = strchr(cmdbuffer+bufindw+CMDHDRSIZE, '*')) != NULL)
  367. {
  368. byte checksum = 0;
  369. char *p = cmdbuffer+bufindw+CMDHDRSIZE;
  370. while (p != strchr_pointer)
  371. checksum = checksum^(*p++);
  372. if (code_value_short() != (int16_t)checksum) {
  373. SERIAL_ERROR_START;
  374. SERIAL_ERRORRPGM(_n("checksum mismatch, Last Line: "));////MSG_ERR_CHECKSUM_MISMATCH
  375. SERIAL_ERRORLN(gcode_LastN);
  376. FlushSerialRequestResend();
  377. serial_count = 0;
  378. return;
  379. }
  380. // If no errors, remove the checksum and continue parsing.
  381. *strchr_pointer = 0;
  382. }
  383. else
  384. {
  385. SERIAL_ERROR_START;
  386. SERIAL_ERRORRPGM(_n("No Checksum with line number, Last Line: "));////MSG_ERR_NO_CHECKSUM
  387. SERIAL_ERRORLN(gcode_LastN);
  388. FlushSerialRequestResend();
  389. serial_count = 0;
  390. return;
  391. }
  392. // Don't parse N again with code_seen('N')
  393. cmdbuffer[bufindw + CMDHDRSIZE] = '$';
  394. }
  395. // if we don't receive 'N' but still see '*'
  396. if ((cmdbuffer[bufindw + CMDHDRSIZE] != 'N') && (cmdbuffer[bufindw + CMDHDRSIZE] != '$') && (strchr(cmdbuffer+bufindw+CMDHDRSIZE, '*') != NULL))
  397. {
  398. SERIAL_ERROR_START;
  399. SERIAL_ERRORRPGM(_n("No Line Number with checksum, Last Line: "));////MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM
  400. SERIAL_ERRORLN(gcode_LastN);
  401. FlushSerialRequestResend();
  402. serial_count = 0;
  403. return;
  404. }
  405. // Handle KILL early, even when Stopped
  406. if(strcmp(cmdbuffer+bufindw+CMDHDRSIZE, "M112") == 0)
  407. kill(MSG_M112_KILL, 2);
  408. // Handle the USB timer
  409. if ((strchr_pointer = strchr(cmdbuffer+bufindw+CMDHDRSIZE, 'G')) != NULL) {
  410. if (!IS_SD_PRINTING) {
  411. usb_timer.start();
  412. }
  413. }
  414. if (Stopped == true) {
  415. // Stopped can be set either during error states (thermal error: cannot continue), or
  416. // when a printer-initiated action is processed. In such case the printer will send to
  417. // the host an action, but cannot know if the action has been processed while new
  418. // commands are being sent. In this situation we just drop the command while issuing
  419. // periodic "busy" messages in the main loop. Since we're not incrementing the received
  420. // line number, a request for resend will happen (if necessary), ensuring we don't skip
  421. // commands whenever Stopped is cleared and processing resumes.
  422. serial_count = 0;
  423. return;
  424. }
  425. // Command is complete: store the current line into buffer, move to the next line.
  426. // Store type of entry
  427. cmdbuffer[bufindw] = gcode_N ? CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR : CMDBUFFER_CURRENT_TYPE_USB;
  428. #ifdef CMDBUFFER_DEBUG
  429. SERIAL_ECHO_START;
  430. SERIAL_ECHOPGM("Storing a command line to buffer: ");
  431. SERIAL_ECHO(cmdbuffer+bufindw+CMDHDRSIZE);
  432. SERIAL_ECHOLNPGM("");
  433. #endif /* CMDBUFFER_DEBUG */
  434. // Store command itself
  435. bufindw += strlen(cmdbuffer+bufindw+CMDHDRSIZE) + (1 + CMDHDRSIZE);
  436. if (bufindw == sizeof(cmdbuffer))
  437. bufindw = 0;
  438. ++ buflen;
  439. // Update the processed gcode line
  440. gcode_LastN = gcode_N;
  441. #ifdef CMDBUFFER_DEBUG
  442. SERIAL_ECHOPGM("Number of commands in the buffer: ");
  443. SERIAL_ECHO(buflen);
  444. SERIAL_ECHOLNPGM("");
  445. #endif /* CMDBUFFER_DEBUG */
  446. } // end of 'not comment mode'
  447. serial_count = 0; //clear buffer
  448. // Don't call cmdqueue_could_enqueue_back if there are no characters waiting
  449. // in the queue, as this function will reserve the memory.
  450. if (MYSERIAL.available() == 0 || ! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  451. return;
  452. } // end of "end of line" processing
  453. else {
  454. // Not an "end of line" symbol. Store the new character into a buffer.
  455. if(serial_char == ';') comment_mode = true;
  456. if(!comment_mode) cmdbuffer[bufindw+CMDHDRSIZE+serial_count++] = serial_char;
  457. }
  458. } // end of serial line processing loop
  459. if (serial_count > 0 && serialTimeoutTimer.expired(farm_mode ? 800 : 2000)) {
  460. comment_mode = false;
  461. serial_count = 0;
  462. SERIAL_ECHOLNPGM("RX timeout");
  463. return;
  464. }
  465. #ifdef SDSUPPORT
  466. if(!card.sdprinting || !card.isFileOpen() || serial_count!=0){
  467. // If there is a half filled buffer from serial line, wait until return before
  468. // continuing with the serial line.
  469. return;
  470. }
  471. //'#' stops reading from SD to the buffer prematurely, so procedural macro calls are possible
  472. // if it occurs, stop_buffering is triggered and the buffer is ran dry.
  473. // this character _can_ occur in serial com, due to checksums. however, no checksums are used in SD printing
  474. static bool stop_buffering=false;
  475. if(buflen==0) stop_buffering=false;
  476. union {
  477. struct {
  478. char lo;
  479. char hi;
  480. } lohi;
  481. uint16_t value;
  482. } sd_count;
  483. sd_count.value = 0;
  484. // Reads whole lines from the SD card. Never leaves a half-filled line in the cmdbuffer.
  485. while( !card.eof() && !stop_buffering) {
  486. int16_t n=card.getFilteredGcodeChar();
  487. char serial_char = (char)n;
  488. if( serial_char == '\n'
  489. || serial_char == '\r'
  490. || ((serial_char == '#' || serial_char == ':') )
  491. || serial_count >= (MAX_CMD_SIZE - 1)
  492. || n==-1
  493. ){
  494. if(serial_char=='#')
  495. stop_buffering=true;
  496. if(!serial_count)
  497. {
  498. // This is either an empty line, or a line with just a comment.
  499. // Continue to the following line, and continue accumulating the number of bytes
  500. // read from the sdcard into sd_count,
  501. // so that the length of the already read empty lines and comments will be added
  502. // to the following non-empty line.
  503. return; // prevent cycling indefinitely - let manage_heaters do their job
  504. }
  505. // The new command buffer could be updated non-atomically, because it is not yet considered
  506. // to be inside the active queue.
  507. sd_count.value = card.get_sdpos() - sdpos_atomic;
  508. cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_SDCARD;
  509. cmdbuffer[bufindw+1] = sd_count.lohi.lo;
  510. cmdbuffer[bufindw+2] = sd_count.lohi.hi;
  511. cmdbuffer[bufindw+serial_count+CMDHDRSIZE] = 0; //terminate string
  512. // Calculate the length before disabling the interrupts.
  513. uint8_t len = strlen(cmdbuffer+bufindw+CMDHDRSIZE) + (1 + CMDHDRSIZE);
  514. // SERIAL_ECHOPGM("SD cmd(");
  515. // MYSERIAL.print(sd_count.value, DEC);
  516. // SERIAL_ECHOPGM(") ");
  517. // SERIAL_ECHOLN(cmdbuffer+bufindw+CMDHDRSIZE);
  518. // SERIAL_ECHOPGM("cmdbuffer:");
  519. // MYSERIAL.print(cmdbuffer);
  520. // SERIAL_ECHOPGM("buflen:");
  521. // MYSERIAL.print(buflen+1);
  522. sd_count.value = 0;
  523. cli();
  524. // This block locks the interrupts globally for 3.56 us,
  525. // which corresponds to a maximum repeat frequency of 280.70 kHz.
  526. // This blocking is safe in the context of a 10kHz stepper driver interrupt
  527. // or a 115200 Bd serial line receive interrupt, which will not trigger faster than 12kHz.
  528. ++ buflen;
  529. bufindw += len;
  530. sdpos_atomic = card.get_sdpos();
  531. if (bufindw == sizeof(cmdbuffer))
  532. bufindw = 0;
  533. sei();
  534. comment_mode = false; //for new command
  535. serial_count = 0; //clear buffer
  536. if(card.eof()) break;
  537. // The following line will reserve buffer space if available.
  538. if (! cmdqueue_could_enqueue_back(MAX_CMD_SIZE-1))
  539. return;
  540. }
  541. else
  542. {
  543. // there are no comments coming from the filtered file
  544. cmdbuffer[bufindw+CMDHDRSIZE+serial_count++] = serial_char;
  545. }
  546. }
  547. if(card.eof())
  548. {
  549. // file was fully buffered, but commands might still need to be planned!
  550. // do *not* clear sdprinting until all SD commands are consumed to ensure
  551. // SD state can be resumed from a saved printing state. sdprinting is only
  552. // cleared by printingHasFinished after peforming all remaining moves.
  553. if(!cmdqueue_calc_sd_length())
  554. {
  555. // queue is complete, but before we process EOF commands prevent
  556. // re-entry by disabling SD processing from any st_synchronize call
  557. card.closefile();
  558. SERIAL_PROTOCOLLNRPGM(_n("Done printing file"));////MSG_FILE_PRINTED
  559. stoptime=_millis();
  560. char time[30];
  561. unsigned long t=(stoptime-starttime-pause_time)/1000;
  562. pause_time = 0;
  563. int hours, minutes;
  564. minutes=(t/60)%60;
  565. hours=t/60/60;
  566. save_statistics(total_filament_used, t);
  567. sprintf_P(time, PSTR("%i hours %i minutes"),hours, minutes);
  568. SERIAL_ECHO_START;
  569. SERIAL_ECHOLN(time);
  570. lcd_setstatus(time);
  571. card.printingHasFinished();
  572. card.checkautostart(true);
  573. if (farm_mode)
  574. {
  575. prusa_statistics(6);
  576. lcd_commands_type = LcdCommands::FarmModeConfirm;
  577. }
  578. }
  579. }
  580. #endif //SDSUPPORT
  581. }
  582. uint16_t cmdqueue_calc_sd_length()
  583. {
  584. if (buflen == 0)
  585. return 0;
  586. union {
  587. struct {
  588. char lo;
  589. char hi;
  590. } lohi;
  591. uint16_t value;
  592. } sdlen_single;
  593. uint16_t sdlen = 0;
  594. for (size_t _buflen = buflen, _bufindr = bufindr;;) {
  595. if (cmdbuffer[_bufindr] == CMDBUFFER_CURRENT_TYPE_SDCARD) {
  596. sdlen_single.lohi.lo = cmdbuffer[_bufindr + 1];
  597. sdlen_single.lohi.hi = cmdbuffer[_bufindr + 2];
  598. sdlen += sdlen_single.value;
  599. }
  600. if (-- _buflen == 0)
  601. break;
  602. // First skip the current command ID and iterate up to the end of the string.
  603. for (_bufindr += CMDHDRSIZE; cmdbuffer[_bufindr] != 0; ++ _bufindr) ;
  604. // Second, skip the end of string null character and iterate until a nonzero command ID is found.
  605. for (++ _bufindr; _bufindr < sizeof(cmdbuffer) && cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  606. // If the end of the buffer was empty,
  607. if (_bufindr == sizeof(cmdbuffer)) {
  608. // skip to the start and find the nonzero command.
  609. for (_bufindr = 0; cmdbuffer[_bufindr] == 0; ++ _bufindr) ;
  610. }
  611. }
  612. return sdlen;
  613. }