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

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