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.

cardreader.cpp 32KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. #include "../inc/MarlinConfig.h"
  23. #if ENABLED(SDSUPPORT)
  24. #include "cardreader.h"
  25. #include "../Marlin.h"
  26. #include "../lcd/ultralcd.h"
  27. #include "../module/planner.h"
  28. #include "../module/printcounter.h"
  29. #include "../core/language.h"
  30. #include "../gcode/queue.h"
  31. #include "../module/configuration_store.h"
  32. #if ENABLED(EMERGENCY_PARSER)
  33. #include "../feature/emergency_parser.h"
  34. #endif
  35. #if ENABLED(POWER_LOSS_RECOVERY)
  36. #include "../feature/power_loss_recovery.h"
  37. #endif
  38. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  39. #include "../feature/pause.h"
  40. #endif
  41. // public:
  42. card_flags_t CardReader::flag;
  43. char CardReader::filename[FILENAME_LENGTH], CardReader::longFilename[LONG_FILENAME_LENGTH];
  44. int8_t CardReader::autostart_index;
  45. #if ENABLED(BINARY_FILE_TRANSFER) && NUM_SERIAL > 1
  46. int8_t CardReader::transfer_port_index;
  47. #endif
  48. // private:
  49. SdFile CardReader::root, CardReader::workDir, CardReader::workDirParents[MAX_DIR_DEPTH];
  50. uint8_t CardReader::workDirDepth;
  51. #if ENABLED(SDCARD_SORT_ALPHA)
  52. uint16_t CardReader::sort_count;
  53. #if ENABLED(SDSORT_GCODE)
  54. bool CardReader::sort_alpha;
  55. int CardReader::sort_folders;
  56. //bool CardReader::sort_reverse;
  57. #endif
  58. #if ENABLED(SDSORT_DYNAMIC_RAM)
  59. uint8_t *CardReader::sort_order;
  60. #else
  61. uint8_t CardReader::sort_order[SDSORT_LIMIT];
  62. #endif
  63. #if ENABLED(SDSORT_USES_RAM)
  64. #if ENABLED(SDSORT_CACHE_NAMES)
  65. uint16_t CardReader::nrFiles; // Cached total file count
  66. #if ENABLED(SDSORT_DYNAMIC_RAM)
  67. char **CardReader::sortshort, **CardReader::sortnames;
  68. #else
  69. char CardReader::sortshort[SDSORT_LIMIT][FILENAME_LENGTH];
  70. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  71. #endif
  72. #elif DISABLED(SDSORT_USES_STACK)
  73. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  74. #endif
  75. #if HAS_FOLDER_SORTING
  76. #if ENABLED(SDSORT_DYNAMIC_RAM)
  77. uint8_t *CardReader::isDir;
  78. #elif ENABLED(SDSORT_CACHE_NAMES) || DISABLED(SDSORT_USES_STACK)
  79. uint8_t CardReader::isDir[(SDSORT_LIMIT+7)>>3];
  80. #endif
  81. #define IS_DIR(n) TEST(isDir[(n) >> 3], (n) & 0x07)
  82. #endif
  83. #endif // SDSORT_USES_RAM
  84. #endif // SDCARD_SORT_ALPHA
  85. Sd2Card CardReader::sd2card;
  86. SdVolume CardReader::volume;
  87. SdFile CardReader::file;
  88. uint8_t CardReader::file_subcall_ctr;
  89. uint32_t CardReader::filespos[SD_PROCEDURE_DEPTH];
  90. char CardReader::proc_filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH];
  91. uint32_t CardReader::filesize, CardReader::sdpos;
  92. CardReader::CardReader() {
  93. #if ENABLED(SDCARD_SORT_ALPHA)
  94. sort_count = 0;
  95. #if ENABLED(SDSORT_GCODE)
  96. sort_alpha = true;
  97. sort_folders = FOLDER_SORTING;
  98. //sort_reverse = false;
  99. #endif
  100. #endif
  101. flag.sdprinting = flag.mounted = flag.saving = flag.logging = false;
  102. filesize = sdpos = 0;
  103. file_subcall_ctr = 0;
  104. workDirDepth = 0;
  105. ZERO(workDirParents);
  106. // Disable autostart until card is initialized
  107. autostart_index = -1;
  108. #if PIN_EXISTS(SDPOWER)
  109. OUT_WRITE(SDPOWER_PIN, HIGH); // Power the SD reader
  110. #endif
  111. }
  112. //
  113. // Get a DOS 8.3 filename in its useful form
  114. //
  115. char *createFilename(char * const buffer, const dir_t &p) {
  116. char *pos = buffer;
  117. for (uint8_t i = 0; i < 11; i++) {
  118. if (p.name[i] == ' ') continue;
  119. if (i == 8) *pos++ = '.';
  120. *pos++ = p.name[i];
  121. }
  122. *pos++ = 0;
  123. return buffer;
  124. }
  125. //
  126. // Return 'true' if the item is a folder or G-code file
  127. //
  128. bool CardReader::is_dir_or_gcode(const dir_t &p) {
  129. uint8_t pn0 = p.name[0];
  130. if ( pn0 == DIR_NAME_FREE || pn0 == DIR_NAME_DELETED // Clear or Deleted entry
  131. || pn0 == '.' || longFilename[0] == '.' // Hidden file
  132. || !DIR_IS_FILE_OR_SUBDIR(&p) // Not a File or Directory
  133. || (p.attributes & DIR_ATT_HIDDEN) // Hidden by attribute
  134. ) return false;
  135. flag.filenameIsDir = DIR_IS_SUBDIR(&p); // We know it's a File or Folder
  136. return (
  137. flag.filenameIsDir // All Directories are ok
  138. || (p.name[8] == 'G' && p.name[9] != '~') // Non-backup *.G* files are accepted
  139. );
  140. }
  141. //
  142. // Get the number of (compliant) items in the folder
  143. //
  144. int CardReader::countItems(SdFile dir) {
  145. dir_t p;
  146. int c = 0;
  147. while (dir.readDir(&p, longFilename) > 0)
  148. c += is_dir_or_gcode(p);
  149. #if ENABLED(SDCARD_SORT_ALPHA) && SDSORT_USES_RAM && SDSORT_CACHE_NAMES
  150. nrFiles = c;
  151. #endif
  152. return c;
  153. }
  154. //
  155. // Get file/folder info for an item by index
  156. //
  157. void CardReader::selectByIndex(SdFile dir, const uint8_t index) {
  158. dir_t p;
  159. for (uint8_t cnt = 0; dir.readDir(&p, longFilename) > 0;) {
  160. if (is_dir_or_gcode(p)) {
  161. if (cnt == index) {
  162. createFilename(filename, p);
  163. return; // 0 based index
  164. }
  165. cnt++;
  166. }
  167. }
  168. }
  169. //
  170. // Get file/folder info for an item by name
  171. //
  172. void CardReader::selectByName(SdFile dir, const char * const match) {
  173. dir_t p;
  174. for (uint8_t cnt = 0; dir.readDir(&p, longFilename) > 0; cnt++) {
  175. if (is_dir_or_gcode(p)) {
  176. createFilename(filename, p);
  177. if (strcasecmp(match, filename) == 0) return;
  178. }
  179. }
  180. }
  181. //
  182. // Recursive method to list all files within a folder
  183. //
  184. void CardReader::printListing(SdFile parent, const char * const prepend/*=nullptr*/) {
  185. dir_t p;
  186. while (parent.readDir(&p, longFilename) > 0) {
  187. if (DIR_IS_SUBDIR(&p)) {
  188. // Get the short name for the item, which we know is a folder
  189. char dosFilename[FILENAME_LENGTH];
  190. createFilename(dosFilename, p);
  191. // Allocate enough stack space for the full path to a folder, trailing slash, and nul
  192. const bool prepend_is_empty = (!prepend || prepend[0] == '\0');
  193. const int len = (prepend_is_empty ? 1 : strlen(prepend)) + strlen(dosFilename) + 1 + 1;
  194. char path[len];
  195. // Append the FOLDERNAME12/ to the passed string.
  196. // It contains the full path to the "parent" argument.
  197. // We now have the full path to the item in this folder.
  198. strcpy(path, prepend_is_empty ? "/" : prepend); // root slash if prepend is empty
  199. strcat(path, dosFilename); // FILENAME_LENGTH characters maximum
  200. strcat(path, "/"); // 1 character
  201. // Serial.print(path);
  202. // Get a new directory object using the full path
  203. // and dive recursively into it.
  204. SdFile child;
  205. if (!child.open(&parent, dosFilename, O_READ)) {
  206. SERIAL_ECHO_START();
  207. SERIAL_ECHOLNPAIR(MSG_SD_CANT_OPEN_SUBDIR, dosFilename);
  208. }
  209. printListing(child, path);
  210. // close() is done automatically by destructor of SdFile
  211. }
  212. else if (is_dir_or_gcode(p)) {
  213. createFilename(filename, p);
  214. if (prepend) SERIAL_ECHO(prepend);
  215. SERIAL_ECHO(filename);
  216. SERIAL_CHAR(' ');
  217. SERIAL_ECHOLN(p.fileSize);
  218. }
  219. }
  220. }
  221. //
  222. // List all files on the SD card
  223. //
  224. void CardReader::ls() {
  225. root.rewind();
  226. printListing(root);
  227. }
  228. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  229. //
  230. // Get a long pretty path based on a DOS 8.3 path
  231. //
  232. void CardReader::printLongPath(char * const path) {
  233. int i, pathLen = strlen(path);
  234. // SERIAL_ECHOPGM("Full Path: "); SERIAL_ECHOLN(path);
  235. // Zero out slashes to make segments
  236. for (i = 0; i < pathLen; i++) if (path[i] == '/') path[i] = '\0';
  237. SdFile diveDir = root; // start from the root for segment 1
  238. for (i = 0; i < pathLen;) {
  239. if (path[i] == '\0') i++; // move past a single nul
  240. char *segment = &path[i]; // The segment after most slashes
  241. // If a segment is empty (extra-slash) then exit
  242. if (!*segment) break;
  243. // Go to the next segment
  244. while (path[++i]) { }
  245. // SERIAL_ECHOPGM("Looking for segment: "); SERIAL_ECHOLN(segment);
  246. // Find the item, setting the long filename
  247. diveDir.rewind();
  248. selectByName(diveDir, segment);
  249. // Print /LongNamePart to serial output
  250. SERIAL_CHAR('/');
  251. SERIAL_ECHO(longFilename[0] ? longFilename : "???");
  252. // If the filename was printed then that's it
  253. if (!flag.filenameIsDir) break;
  254. // SERIAL_ECHOPGM("Opening dir: "); SERIAL_ECHOLN(segment);
  255. // Open the sub-item as the new dive parent
  256. SdFile dir;
  257. if (!dir.open(&diveDir, segment, O_READ)) {
  258. SERIAL_EOL();
  259. SERIAL_ECHO_START();
  260. SERIAL_ECHOPAIR(MSG_SD_CANT_OPEN_SUBDIR, segment);
  261. break;
  262. }
  263. diveDir.close();
  264. diveDir = dir;
  265. } // while i<pathLen
  266. SERIAL_EOL();
  267. }
  268. #endif // LONG_FILENAME_HOST_SUPPORT
  269. //
  270. // Echo the DOS 8.3 filename (and long filename, if any)
  271. //
  272. void CardReader::printFilename() {
  273. if (file.isOpen()) {
  274. char dosFilename[FILENAME_LENGTH];
  275. file.getDosName(dosFilename);
  276. SERIAL_ECHO(dosFilename);
  277. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  278. selectFileByName(dosFilename);
  279. if (longFilename[0]) {
  280. SERIAL_ECHO(' ');
  281. SERIAL_ECHO(longFilename);
  282. }
  283. #endif
  284. }
  285. else
  286. SERIAL_ECHOPGM("(no file)");
  287. SERIAL_EOL();
  288. }
  289. void CardReader::mount() {
  290. flag.mounted = false;
  291. if (root.isOpen()) root.close();
  292. if (!sd2card.init(SPI_SPEED, SDSS)
  293. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  294. && !sd2card.init(SPI_SPEED, LCD_SDSS)
  295. #endif
  296. ) SERIAL_ECHO_MSG(MSG_SD_INIT_FAIL);
  297. else if (!volume.init(&sd2card))
  298. SERIAL_ERROR_MSG(MSG_SD_VOL_INIT_FAIL);
  299. else if (!root.openRoot(&volume))
  300. SERIAL_ERROR_MSG(MSG_SD_OPENROOT_FAIL);
  301. else {
  302. flag.mounted = true;
  303. SERIAL_ECHO_MSG(MSG_SD_CARD_OK);
  304. #if ENABLED(EEPROM_SETTINGS) && NONE(FLASH_EEPROM_EMULATION, SPI_EEPROM, I2C_EEPROM)
  305. settings.first_load();
  306. #endif
  307. }
  308. cdroot();
  309. ui.refresh();
  310. }
  311. void CardReader::release() {
  312. stopSDPrint();
  313. flag.mounted = false;
  314. }
  315. void CardReader::openAndPrintFile(const char *name) {
  316. char cmd[4 + strlen(name) + 1]; // Room for "M23 ", filename, and null
  317. extern const char M23_STR[];
  318. sprintf_P(cmd, M23_STR, name);
  319. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  320. queue.enqueue_one_now(cmd);
  321. queue.enqueue_now_P(M24_STR);
  322. }
  323. void CardReader::startFileprint() {
  324. if (isMounted()) {
  325. flag.sdprinting = true;
  326. #if SD_RESORT
  327. flush_presort();
  328. #endif
  329. }
  330. }
  331. void CardReader::stopSDPrint(
  332. #if SD_RESORT
  333. const bool re_sort/*=false*/
  334. #endif
  335. ) {
  336. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  337. did_pause_print = 0;
  338. #endif
  339. flag.sdprinting = flag.abort_sd_printing = false;
  340. if (isFileOpen()) file.close();
  341. #if SD_RESORT
  342. if (re_sort) presort();
  343. #endif
  344. }
  345. void CardReader::openLogFile(char * const path) {
  346. flag.logging = true;
  347. openFileWrite(path);
  348. }
  349. //
  350. // Get the root-relative DOS path of the selected file
  351. //
  352. void CardReader::getAbsFilename(char *dst) {
  353. *dst++ = '/';
  354. uint8_t cnt = 1;
  355. auto appendAtom = [&](SdFile &file) {
  356. file.getDosName(dst);
  357. while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; }
  358. if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; }
  359. };
  360. for (uint8_t i = 0; i < workDirDepth; i++) // Loop down to current work dir
  361. appendAtom(workDirParents[i]);
  362. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH) - 1) { // Leave room for filename and nul
  363. appendAtom(file);
  364. --dst;
  365. }
  366. *dst = '\0';
  367. }
  368. void openFailed(const char * const fname) {
  369. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, fname, ".");
  370. }
  371. void announceOpen(const uint8_t doing, const char * const path) {
  372. if (doing) {
  373. SERIAL_ECHO_START();
  374. SERIAL_ECHOPGM("Now ");
  375. serialprintPGM(doing == 1 ? PSTR("doing") : PSTR("fresh"));
  376. SERIAL_ECHOLNPAIR(" file: ", path);
  377. }
  378. }
  379. //
  380. // Open a file by DOS path for read
  381. // The 'subcall_type' flag indicates...
  382. // - 0 : Standard open from host or user interface.
  383. // - 1 : (file open) Opening a new sub-procedure.
  384. // - 1 : (no file open) Opening a macro (M98).
  385. // - 2 : Resuming from a sub-procedure
  386. //
  387. void CardReader::openFileRead(char * const path, const uint8_t subcall_type/*=0*/) {
  388. if (!isMounted()) return;
  389. switch (subcall_type) {
  390. case 0: // Starting a new print. "Now fresh file: ..."
  391. announceOpen(2, path);
  392. file_subcall_ctr = 0;
  393. break;
  394. case 1: // Starting a sub-procedure
  395. // With no file is open it's a simple macro. "Now doing file: ..."
  396. if (!isFileOpen()) { announceOpen(1, path); break; }
  397. // Too deep? The firmware has to bail.
  398. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  399. SERIAL_ERROR_MSG("trying to call sub-gcode files with too many levels. MAX level is:" STRINGIFY(SD_PROCEDURE_DEPTH));
  400. kill();
  401. return;
  402. }
  403. // Store current filename (based on workDirParents) and position
  404. getAbsFilename(proc_filenames[file_subcall_ctr]);
  405. filespos[file_subcall_ctr] = sdpos;
  406. // For sub-procedures say 'SUBROUTINE CALL target: "..." parent: "..." pos12345'
  407. SERIAL_ECHO_START();
  408. SERIAL_ECHOLNPAIR("SUBROUTINE CALL target:\"", path, "\" parent:\"", proc_filenames[file_subcall_ctr], "\" pos", sdpos);
  409. file_subcall_ctr++;
  410. break;
  411. case 2: // Resuming previous file after sub-procedure
  412. SERIAL_ECHO_MSG("END SUBROUTINE");
  413. break;
  414. }
  415. stopSDPrint();
  416. SdFile *curDir;
  417. const char * const fname = diveToFile(curDir, path);
  418. if (!fname) return;
  419. if (file.open(curDir, fname, O_READ)) {
  420. filesize = file.fileSize();
  421. sdpos = 0;
  422. SERIAL_ECHOLNPAIR(MSG_SD_FILE_OPENED, fname, MSG_SD_SIZE, filesize);
  423. SERIAL_ECHOLNPGM(MSG_SD_FILE_SELECTED);
  424. selectFileByName(fname);
  425. ui.set_status(longFilename[0] ? longFilename : fname);
  426. }
  427. else
  428. openFailed(fname);
  429. }
  430. //
  431. // Open a file by DOS path for write
  432. //
  433. void CardReader::openFileWrite(char * const path) {
  434. if (!isMounted()) return;
  435. announceOpen(2, path);
  436. file_subcall_ctr = 0;
  437. stopSDPrint();
  438. SdFile *curDir;
  439. const char * const fname = diveToFile(curDir, path);
  440. if (!fname) return;
  441. if (file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  442. flag.saving = true;
  443. selectFileByName(fname);
  444. #if ENABLED(EMERGENCY_PARSER)
  445. emergency_parser.disable();
  446. #endif
  447. SERIAL_ECHOLNPAIR(MSG_SD_WRITE_TO_FILE, fname);
  448. ui.set_status(fname);
  449. }
  450. else
  451. openFailed(fname);
  452. }
  453. //
  454. // Delete a file by name in the working directory
  455. //
  456. void CardReader::removeFile(const char * const name) {
  457. if (!isMounted()) return;
  458. //stopSDPrint();
  459. SdFile *curDir;
  460. const char * const fname = diveToFile(curDir, name);
  461. if (!fname) return;
  462. if (file.remove(curDir, fname)) {
  463. SERIAL_ECHOLNPAIR("File deleted:", fname);
  464. sdpos = 0;
  465. #if ENABLED(SDCARD_SORT_ALPHA)
  466. presort();
  467. #endif
  468. }
  469. else
  470. SERIAL_ECHOLNPAIR("Deletion failed, File: ", fname, ".");
  471. }
  472. void CardReader::report_status() {
  473. if (isPrinting()) {
  474. SERIAL_ECHOPGM(MSG_SD_PRINTING_BYTE);
  475. SERIAL_ECHO(sdpos);
  476. SERIAL_CHAR('/');
  477. SERIAL_ECHOLN(filesize);
  478. }
  479. else
  480. SERIAL_ECHOLNPGM(MSG_SD_NOT_PRINTING);
  481. }
  482. void CardReader::write_command(char * const buf) {
  483. char* begin = buf;
  484. char* npos = nullptr;
  485. char* end = buf + strlen(buf) - 1;
  486. file.writeError = false;
  487. if ((npos = strchr(buf, 'N')) != nullptr) {
  488. begin = strchr(npos, ' ') + 1;
  489. end = strchr(npos, '*') - 1;
  490. }
  491. end[1] = '\r';
  492. end[2] = '\n';
  493. end[3] = '\0';
  494. file.write(begin);
  495. if (file.writeError) SERIAL_ERROR_MSG(MSG_SD_ERR_WRITE_TO_FILE);
  496. }
  497. //
  498. // Run the next autostart file. Called:
  499. // - On boot after successful card init
  500. // - After finishing the previous autostart file
  501. // - From the LCD command to run the autostart file
  502. //
  503. void CardReader::checkautostart() {
  504. if (autostart_index < 0 || flag.sdprinting) return;
  505. if (!isMounted()) mount();
  506. #if ENABLED(EEPROM_SETTINGS) && NONE(FLASH_EEPROM_EMULATION, SPI_EEPROM, I2C_EEPROM)
  507. else settings.first_load();
  508. #endif
  509. if (isMounted()
  510. #if ENABLED(POWER_LOSS_RECOVERY)
  511. && !recovery.valid() // Don't run auto#.g when a resume file exists
  512. #endif
  513. ) {
  514. char autoname[8];
  515. sprintf_P(autoname, PSTR("auto%c.g"), autostart_index + '0');
  516. dir_t p;
  517. root.rewind();
  518. while (root.readDir(&p, nullptr) > 0) {
  519. for (int8_t i = (int8_t)strlen((char*)p.name); i--;) p.name[i] = tolower(p.name[i]);
  520. if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
  521. openAndPrintFile(autoname);
  522. autostart_index++;
  523. return;
  524. }
  525. }
  526. }
  527. autostart_index = -1;
  528. }
  529. void CardReader::beginautostart() {
  530. autostart_index = 0;
  531. cdroot();
  532. }
  533. void CardReader::closefile(const bool store_location) {
  534. file.sync();
  535. file.close();
  536. flag.saving = flag.logging = false;
  537. sdpos = 0;
  538. #if ENABLED(EMERGENCY_PARSER)
  539. emergency_parser.enable();
  540. #endif
  541. if (store_location) {
  542. //future: store printer state, filename and position for continuing a stopped print
  543. // so one can unplug the printer and continue printing the next day.
  544. }
  545. }
  546. //
  547. // Get info for a file in the working directory by index
  548. //
  549. void CardReader::selectFileByIndex(const uint16_t nr) {
  550. #if ENABLED(SDSORT_CACHE_NAMES)
  551. if (nr < sort_count) {
  552. strcpy(filename, sortshort[nr]);
  553. strcpy(longFilename, sortnames[nr]);
  554. flag.filenameIsDir = IS_DIR(nr);
  555. return;
  556. }
  557. #endif
  558. workDir.rewind();
  559. selectByIndex(workDir, nr);
  560. }
  561. //
  562. // Get info for a file in the working directory by DOS name
  563. //
  564. void CardReader::selectFileByName(const char * const match) {
  565. #if ENABLED(SDSORT_CACHE_NAMES)
  566. for (int nr = 0; nr < sort_count; nr++)
  567. if (strcasecmp(match, sortshort[nr]) == 0) {
  568. strcpy(filename, sortshort[nr]);
  569. strcpy(longFilename, sortnames[nr]);
  570. flag.filenameIsDir = IS_DIR(nr);
  571. return;
  572. }
  573. #endif
  574. workDir.rewind();
  575. selectByName(workDir, match);
  576. }
  577. uint16_t CardReader::countFilesInWorkDir() {
  578. workDir.rewind();
  579. return countItems(workDir);
  580. }
  581. /**
  582. * Dive to the given DOS 8.3 file path, with optional echo of the dive paths.
  583. *
  584. * On exit, curDir contains an SdFile reference to the file's directory.
  585. *
  586. * Returns a pointer to the last segment (filename) of the given DOS 8.3 path.
  587. *
  588. * A nullptr result indicates an unrecoverable error.
  589. */
  590. const char* CardReader::diveToFile(SdFile*& curDir, const char * const path, const bool echo/*=false*/) {
  591. // Track both parent and subfolder
  592. static SdFile newDir1, newDir2;
  593. SdFile *sub = &newDir1, *startDir;
  594. const char *item_name_adr = path;
  595. if (path[0] == '/') {
  596. curDir = &root;
  597. workDirDepth = 0;
  598. item_name_adr++;
  599. }
  600. else
  601. curDir = &workDir;
  602. startDir = curDir;
  603. // Start dive
  604. while (item_name_adr) {
  605. // Find next sub
  606. char * const name_end = strchr(item_name_adr, '/');
  607. if (name_end <= item_name_adr) break;
  608. // Set subDirName
  609. const uint8_t len = name_end - item_name_adr;
  610. char dosSubdirname[len + 1];
  611. strncpy(dosSubdirname, item_name_adr, len);
  612. dosSubdirname[len] = 0;
  613. if (echo) SERIAL_ECHOLN(dosSubdirname);
  614. // Open curDir
  615. if (!sub->open(curDir, dosSubdirname, O_READ)) {
  616. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, dosSubdirname, ".");
  617. return nullptr;
  618. }
  619. // Close curDir if not at starting-point
  620. if (curDir != startDir) curDir->close();
  621. // curDir now subDir
  622. curDir = sub;
  623. // Update workDirParents and workDirDepth
  624. if (workDirDepth < MAX_DIR_DEPTH) workDirParents[workDirDepth++] = *curDir;
  625. // Point sub pointer to unused newDir
  626. sub = (curDir != &newDir1) ? &newDir1 : &newDir2;
  627. // item_name_adr point to next sub
  628. item_name_adr = name_end + 1;
  629. }
  630. return item_name_adr;
  631. }
  632. void CardReader::cd(const char * relpath) {
  633. SdFile newDir;
  634. SdFile *parent = workDir.isOpen() ? &workDir : &root;
  635. if (newDir.open(parent, relpath, O_READ)) {
  636. workDir = newDir;
  637. flag.workDirIsRoot = false;
  638. if (workDirDepth < MAX_DIR_DEPTH)
  639. workDirParents[workDirDepth++] = workDir;
  640. #if ENABLED(SDCARD_SORT_ALPHA)
  641. presort();
  642. #endif
  643. }
  644. else {
  645. SERIAL_ECHO_START();
  646. SERIAL_ECHOLNPAIR(MSG_SD_CANT_ENTER_SUBDIR, relpath);
  647. }
  648. }
  649. int8_t CardReader::cdup() {
  650. if (workDirDepth > 0) { // At least 1 dir has been saved
  651. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  652. #if ENABLED(SDCARD_SORT_ALPHA)
  653. presort();
  654. #endif
  655. }
  656. if (!workDirDepth) flag.workDirIsRoot = true;
  657. return workDirDepth;
  658. }
  659. void CardReader::cdroot() {
  660. workDir = root;
  661. flag.workDirIsRoot = true;
  662. #if ENABLED(SDCARD_SORT_ALPHA)
  663. presort();
  664. #endif
  665. }
  666. #if ENABLED(SDCARD_SORT_ALPHA)
  667. /**
  668. * Get the name of a file in the working directory by sort-index
  669. */
  670. void CardReader::getfilename_sorted(const uint16_t nr) {
  671. selectFileByIndex(
  672. #if ENABLED(SDSORT_GCODE)
  673. sort_alpha &&
  674. #endif
  675. (nr < sort_count) ? sort_order[nr] : nr
  676. );
  677. }
  678. #if ENABLED(SDSORT_USES_RAM)
  679. #if ENABLED(SDSORT_DYNAMIC_RAM)
  680. // Use dynamic method to copy long filename
  681. #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename()))
  682. #if ENABLED(SDSORT_CACHE_NAMES)
  683. // When caching also store the short name, since
  684. // we're replacing the selectFileByIndex() behavior.
  685. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename))
  686. #else
  687. #define SET_SORTSHORT(I) NOOP
  688. #endif
  689. #else
  690. // Copy filenames into the static array
  691. #define _SET_SORTNAME(I) strncpy(sortnames[I], longest_filename(), SORTED_LONGNAME_MAXLEN)
  692. #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH
  693. // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul
  694. #define SET_SORTNAME(I) _SET_SORTNAME(I)
  695. #else
  696. // Copy multiple name blocks. Add a nul for the longest case.
  697. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0)
  698. #endif
  699. #if ENABLED(SDSORT_CACHE_NAMES)
  700. #define SET_SORTSHORT(I) strcpy(sortshort[I], filename)
  701. #else
  702. #define SET_SORTSHORT(I) NOOP
  703. #endif
  704. #endif
  705. #endif
  706. /**
  707. * Read all the files and produce a sort key
  708. *
  709. * We can do this in 3 ways...
  710. * - Minimal RAM: Read two filenames at a time sorting along...
  711. * - Some RAM: Buffer the directory just for this sort
  712. * - Most RAM: Buffer the directory and return filenames from RAM
  713. */
  714. void CardReader::presort() {
  715. // Throw away old sort index
  716. flush_presort();
  717. // Sorting may be turned off
  718. #if ENABLED(SDSORT_GCODE)
  719. if (!sort_alpha) return;
  720. #endif
  721. // If there are files, sort up to the limit
  722. uint16_t fileCnt = countFilesInWorkDir();
  723. if (fileCnt > 0) {
  724. // Never sort more than the max allowed
  725. // If you use folders to organize, 20 may be enough
  726. NOMORE(fileCnt, uint16_t(SDSORT_LIMIT));
  727. // Sort order is always needed. May be static or dynamic.
  728. #if ENABLED(SDSORT_DYNAMIC_RAM)
  729. sort_order = new uint8_t[fileCnt];
  730. #endif
  731. // Use RAM to store the entire directory during pre-sort.
  732. // SDSORT_LIMIT should be set to prevent over-allocation.
  733. #if ENABLED(SDSORT_USES_RAM)
  734. // If using dynamic ram for names, allocate on the heap.
  735. #if ENABLED(SDSORT_CACHE_NAMES)
  736. #if ENABLED(SDSORT_DYNAMIC_RAM)
  737. sortshort = new char*[fileCnt];
  738. sortnames = new char*[fileCnt];
  739. #endif
  740. #elif ENABLED(SDSORT_USES_STACK)
  741. char sortnames[fileCnt][SORTED_LONGNAME_STORAGE];
  742. #endif
  743. // Folder sorting needs 1 bit per entry for flags.
  744. #if HAS_FOLDER_SORTING
  745. #if ENABLED(SDSORT_DYNAMIC_RAM)
  746. isDir = new uint8_t[(fileCnt + 7) >> 3];
  747. #elif ENABLED(SDSORT_USES_STACK)
  748. uint8_t isDir[(fileCnt + 7) >> 3];
  749. #endif
  750. #endif
  751. #else // !SDSORT_USES_RAM
  752. // By default re-read the names from SD for every compare
  753. // retaining only two filenames at a time. This is very
  754. // slow but is safest and uses minimal RAM.
  755. char name1[LONG_FILENAME_LENGTH];
  756. #endif
  757. if (fileCnt > 1) {
  758. // Init sort order.
  759. for (uint16_t i = 0; i < fileCnt; i++) {
  760. sort_order[i] = (
  761. #if ENABLED(SDCARD_RATHERRECENTFIRST)
  762. fileCnt - 1 -
  763. #endif
  764. i);
  765. // If using RAM then read all filenames now.
  766. #if ENABLED(SDSORT_USES_RAM)
  767. selectFileByIndex(i);
  768. SET_SORTNAME(i);
  769. SET_SORTSHORT(i);
  770. // char out[30];
  771. // sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]);
  772. // SERIAL_ECHOLN(out);
  773. #if HAS_FOLDER_SORTING
  774. const uint16_t bit = i & 0x07, ind = i >> 3;
  775. if (bit == 0) isDir[ind] = 0x00;
  776. if (flag.filenameIsDir) isDir[ind] |= _BV(bit);
  777. #endif
  778. #endif
  779. }
  780. // Bubble Sort
  781. for (uint16_t i = fileCnt; --i;) {
  782. bool didSwap = false;
  783. uint8_t o1 = sort_order[0];
  784. #if DISABLED(SDSORT_USES_RAM)
  785. selectFileByIndex(o1); // Pre-fetch the first entry and save it
  786. strcpy(name1, longest_filename()); // so the loop only needs one fetch
  787. #if HAS_FOLDER_SORTING
  788. bool dir1 = flag.filenameIsDir;
  789. #endif
  790. #endif
  791. for (uint16_t j = 0; j < i; ++j) {
  792. const uint16_t o2 = sort_order[j + 1];
  793. // Compare names from the array or just the two buffered names
  794. #if ENABLED(SDSORT_USES_RAM)
  795. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  796. #else
  797. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  798. #endif
  799. #if HAS_FOLDER_SORTING
  800. #if ENABLED(SDSORT_USES_RAM)
  801. // Folder sorting needs an index and bit to test for folder-ness.
  802. #define _SORT_CMP_DIR(fs) IS_DIR(o1) == IS_DIR(o2) ? _SORT_CMP_NODIR() : IS_DIR(fs > 0 ? o1 : o2)
  803. #else
  804. #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  805. #endif
  806. #endif
  807. // The most economical method reads names as-needed
  808. // throughout the loop. Slow if there are many.
  809. #if DISABLED(SDSORT_USES_RAM)
  810. selectFileByIndex(o2);
  811. const bool dir2 = flag.filenameIsDir;
  812. char * const name2 = longest_filename(); // use the string in-place
  813. #endif // !SDSORT_USES_RAM
  814. // Sort the current pair according to settings.
  815. if (
  816. #if HAS_FOLDER_SORTING
  817. #if ENABLED(SDSORT_GCODE)
  818. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  819. #else
  820. _SORT_CMP_DIR(FOLDER_SORTING)
  821. #endif
  822. #else
  823. _SORT_CMP_NODIR()
  824. #endif
  825. ) {
  826. // Reorder the index, indicate that sorting happened
  827. // Note that the next o1 will be the current o1. No new fetch needed.
  828. sort_order[j] = o2;
  829. sort_order[j + 1] = o1;
  830. didSwap = true;
  831. }
  832. else {
  833. // The next o1 is the current o2. No new fetch needed.
  834. o1 = o2;
  835. #if DISABLED(SDSORT_USES_RAM)
  836. #if HAS_FOLDER_SORTING
  837. dir1 = dir2;
  838. #endif
  839. strcpy(name1, name2);
  840. #endif
  841. }
  842. }
  843. if (!didSwap) break;
  844. }
  845. // Using RAM but not keeping names around
  846. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  847. #if ENABLED(SDSORT_DYNAMIC_RAM)
  848. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  849. #if HAS_FOLDER_SORTING
  850. free(isDir);
  851. #endif
  852. #endif
  853. #endif
  854. }
  855. else {
  856. sort_order[0] = 0;
  857. #if BOTH(SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  858. #if ENABLED(SDSORT_DYNAMIC_RAM)
  859. sortnames = new char*[1];
  860. sortshort = new char*[1];
  861. isDir = new uint8_t[1];
  862. #endif
  863. selectFileByIndex(0);
  864. SET_SORTNAME(0);
  865. SET_SORTSHORT(0);
  866. isDir[0] = flag.filenameIsDir;
  867. #endif
  868. }
  869. sort_count = fileCnt;
  870. }
  871. }
  872. void CardReader::flush_presort() {
  873. if (sort_count > 0) {
  874. #if ENABLED(SDSORT_DYNAMIC_RAM)
  875. delete sort_order;
  876. #if ENABLED(SDSORT_CACHE_NAMES)
  877. for (uint8_t i = 0; i < sort_count; ++i) {
  878. free(sortshort[i]); // strdup
  879. free(sortnames[i]); // strdup
  880. }
  881. delete sortshort;
  882. delete sortnames;
  883. #endif
  884. #endif
  885. sort_count = 0;
  886. }
  887. }
  888. #endif // SDCARD_SORT_ALPHA
  889. uint16_t CardReader::get_num_Files() {
  890. return
  891. #if ENABLED(SDCARD_SORT_ALPHA) && SDSORT_USES_RAM && SDSORT_CACHE_NAMES
  892. nrFiles // no need to access the SD card for filenames
  893. #else
  894. countFilesInWorkDir()
  895. #endif
  896. ;
  897. }
  898. //
  899. // Return from procedure or close out the Print Job
  900. //
  901. void CardReader::printingHasFinished() {
  902. planner.synchronize();
  903. file.close();
  904. if (file_subcall_ctr > 0) { // Resume calling file after closing procedure
  905. file_subcall_ctr--;
  906. openFileRead(proc_filenames[file_subcall_ctr], 2); // 2 = Returning from sub-procedure
  907. setIndex(filespos[file_subcall_ctr]);
  908. startFileprint();
  909. }
  910. else {
  911. stopSDPrint();
  912. #if ENABLED(POWER_LOSS_RECOVERY)
  913. removeJobRecoveryFile();
  914. #endif
  915. #if ENABLED(SD_FINISHED_STEPPERRELEASE) && defined(SD_FINISHED_RELEASECOMMAND)
  916. planner.finish_and_disable();
  917. #endif
  918. print_job_timer.stop();
  919. queue.enqueue_now_P(print_job_timer.duration() > 60 ? PSTR("M31") : PSTR("M117"));
  920. #if ENABLED(SDCARD_SORT_ALPHA)
  921. presort();
  922. #endif
  923. #if ENABLED(LCD_SET_PROGRESS_MANUALLY)
  924. ui.set_progress_done();
  925. #endif
  926. #if ENABLED(SD_REPRINT_LAST_SELECTED_FILE)
  927. ui.reselect_last_file();
  928. #endif
  929. }
  930. }
  931. #if ENABLED(AUTO_REPORT_SD_STATUS)
  932. uint8_t CardReader::auto_report_sd_interval = 0;
  933. millis_t CardReader::next_sd_report_ms;
  934. #if NUM_SERIAL > 1
  935. int8_t CardReader::auto_report_port;
  936. #endif
  937. void CardReader::auto_report_sd_status() {
  938. millis_t current_ms = millis();
  939. if (auto_report_sd_interval && ELAPSED(current_ms, next_sd_report_ms)) {
  940. next_sd_report_ms = current_ms + 1000UL * auto_report_sd_interval;
  941. PORT_REDIRECT(auto_report_port);
  942. report_status();
  943. }
  944. }
  945. #endif // AUTO_REPORT_SD_STATUS
  946. #if ENABLED(POWER_LOSS_RECOVERY)
  947. bool CardReader::jobRecoverFileExists() {
  948. const bool exists = recovery.file.open(&root, recovery.filename, O_READ);
  949. if (exists) recovery.file.close();
  950. return exists;
  951. }
  952. void CardReader::openJobRecoveryFile(const bool read) {
  953. if (!isMounted()) return;
  954. if (recovery.file.isOpen()) return;
  955. if (!recovery.file.open(&root, recovery.filename, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC))
  956. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, recovery.filename, ".");
  957. else if (!read)
  958. SERIAL_ECHOLNPAIR(MSG_SD_WRITE_TO_FILE, recovery.filename);
  959. }
  960. // Removing the job recovery file currently requires closing
  961. // the file being printed, so during SD printing the file should
  962. // be zeroed and written instead of deleted.
  963. void CardReader::removeJobRecoveryFile() {
  964. if (jobRecoverFileExists()) {
  965. recovery.init();
  966. removeFile(recovery.filename);
  967. #if ENABLED(DEBUG_POWER_LOSS_RECOVERY)
  968. SERIAL_ECHOPGM("Power-loss file delete");
  969. serialprintPGM(jobRecoverFileExists() ? PSTR(" failed.\n") : PSTR("d.\n"));
  970. #endif
  971. }
  972. }
  973. #endif // POWER_LOSS_RECOVERY
  974. #endif // SDSUPPORT