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 37KB

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