cmdqueue.cpp 27 KB

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