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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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_MSG(STR_SD_CANT_OPEN_SUBDIR, dosFilename);
  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_CHAR(' ');
  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(SD_SPI_SPEED, SDSS)
  308. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  309. && !sd2card.init(SD_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. #if ENABLED(POWER_LOSS_RECOVERY)
  363. recovery.check(); // Check for PLR file. (If not there then call autofile_begin)
  364. #elif DISABLED(NO_SD_AUTOSTART)
  365. autofile_begin(); // Look for auto0.g on the next loop
  366. #endif
  367. }
  368. }
  369. }
  370. else
  371. DEBUG_ECHOLNPGM("SD: No UI Detected.");
  372. }
  373. /**
  374. * "Release" the media by clearing the 'mounted' flag.
  375. * Used by M22, "Release Media", manage_media.
  376. */
  377. void CardReader::release() {
  378. // Card removed while printing? Abort!
  379. if (IS_SD_PRINTING())
  380. card.flag.abort_sd_printing = true;
  381. else
  382. endFilePrint();
  383. flag.mounted = false;
  384. flag.workDirIsRoot = true;
  385. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  386. nrFiles = 0;
  387. #endif
  388. }
  389. /**
  390. * Open a G-code file and set Marlin to start processing it.
  391. * Enqueues M23 and M24 commands to initiate a media print.
  392. */
  393. void CardReader::openAndPrintFile(const char *name) {
  394. char cmd[4 + strlen(name) + 1 + 3 + 1]; // Room for "M23 ", filename, "\n", "M24", and null
  395. sprintf_P(cmd, M23_STR, name);
  396. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  397. strcat_P(cmd, PSTR("\nM24"));
  398. queue.inject(cmd);
  399. }
  400. /**
  401. * Start or resume a media print by setting the sdprinting flag.
  402. * The file browser pre-sort is also purged to free up memory,
  403. * since you cannot browse files during active printing.
  404. * Used by M24 and anywhere Start / Resume applies.
  405. */
  406. void CardReader::startFileprint() {
  407. if (isMounted()) {
  408. flag.sdprinting = true;
  409. TERN_(SD_RESORT, flush_presort());
  410. }
  411. }
  412. //
  413. // Run tasks upon finishing or aborting a file print.
  414. //
  415. void CardReader::endFilePrint(TERN_(SD_RESORT, const bool re_sort/*=false*/)) {
  416. TERN_(ADVANCED_PAUSE_FEATURE, did_pause_print = 0);
  417. TERN_(DWIN_CREALITY_LCD, HMI_flag.print_finish = flag.sdprinting);
  418. flag.sdprinting = flag.abort_sd_printing = false;
  419. if (isFileOpen()) file.close();
  420. TERN_(SD_RESORT, if (re_sort) presort());
  421. }
  422. void CardReader::openLogFile(char * const path) {
  423. flag.logging = DISABLED(SDCARD_READONLY);
  424. IF_DISABLED(SDCARD_READONLY, openFileWrite(path));
  425. }
  426. //
  427. // Get the root-relative DOS path of the selected file
  428. //
  429. void CardReader::getAbsFilename(char *dst) {
  430. *dst++ = '/';
  431. uint8_t cnt = 1;
  432. auto appendAtom = [&](SdFile &file) {
  433. file.getDosName(dst);
  434. while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; }
  435. if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; }
  436. };
  437. LOOP_L_N(i, workDirDepth) // Loop down to current work dir
  438. appendAtom(workDirParents[i]);
  439. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH) - 1) { // Leave room for filename and nul
  440. appendAtom(file);
  441. --dst;
  442. }
  443. *dst = '\0';
  444. }
  445. void openFailed(const char * const fname) {
  446. SERIAL_ECHOLNPAIR(STR_SD_OPEN_FILE_FAIL, fname, ".");
  447. }
  448. void announceOpen(const uint8_t doing, const char * const path) {
  449. if (doing) {
  450. PORT_REDIRECT(SERIAL_ALL);
  451. SERIAL_ECHO_START();
  452. SERIAL_ECHOPGM("Now ");
  453. serialprintPGM(doing == 1 ? PSTR("doing") : PSTR("fresh"));
  454. SERIAL_ECHOLNPAIR(" file: ", path);
  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:", 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_MSG("SUBROUTINE CALL target:\"", path, "\" parent:\"", proc_filenames[file_subcall_ctr], "\" pos", sdpos);
  487. file_subcall_ctr++;
  488. break;
  489. case 2: // Resuming previous file after sub-procedure
  490. SERIAL_ECHO_MSG("END SUBROUTINE");
  491. break;
  492. #endif
  493. }
  494. endFilePrint();
  495. SdFile *diveDir;
  496. const char * const fname = diveToFile(true, diveDir, path);
  497. if (!fname) return;
  498. if (file.open(diveDir, fname, O_READ)) {
  499. filesize = file.fileSize();
  500. sdpos = 0;
  501. { // Don't remove this block, as the PORT_REDIRECT is a RAII
  502. PORT_REDIRECT(SERIAL_ALL);
  503. SERIAL_ECHOLNPAIR(STR_SD_FILE_OPENED, fname, STR_SD_SIZE, filesize);
  504. SERIAL_ECHOLNPGM(STR_SD_FILE_SELECTED);
  505. }
  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. DEBUG_ECHOLNPAIR("fileExists: ", path);
  547. // Dive to the file's directory and get the base name
  548. SdFile *diveDir = nullptr;
  549. const char * const fname = diveToFile(false, diveDir, path);
  550. if (!fname) return false;
  551. // Get the longname of the checked file
  552. //diveDir->rewind();
  553. //selectByName(*diveDir, fname);
  554. //diveDir->close();
  555. // Try to open the file and return the result
  556. SdFile tmpFile;
  557. const bool success = tmpFile.open(diveDir, fname, O_READ);
  558. if (success) tmpFile.close();
  559. return success;
  560. }
  561. //
  562. // Delete a file by name in the working directory
  563. //
  564. void CardReader::removeFile(const char * const name) {
  565. if (!isMounted()) return;
  566. //endFilePrint();
  567. SdFile *curDir;
  568. const char * const fname = diveToFile(false, curDir, name);
  569. if (!fname) return;
  570. #if ENABLED(SDCARD_READONLY)
  571. SERIAL_ECHOLNPAIR("Deletion failed (read-only), File: ", fname, ".");
  572. #else
  573. if (file.remove(curDir, fname)) {
  574. SERIAL_ECHOLNPAIR("File deleted:", fname);
  575. sdpos = 0;
  576. TERN_(SDCARD_SORT_ALPHA, presort());
  577. }
  578. else
  579. SERIAL_ECHOLNPAIR("Deletion failed, File: ", fname, ".");
  580. #endif
  581. }
  582. void CardReader::report_status() {
  583. if (isPrinting()) {
  584. SERIAL_ECHOPAIR(STR_SD_PRINTING_BYTE, sdpos);
  585. SERIAL_CHAR('/');
  586. SERIAL_ECHOLN(filesize);
  587. }
  588. else
  589. SERIAL_ECHOLNPGM(STR_SD_NOT_PRINTING);
  590. }
  591. void CardReader::write_command(char * const buf) {
  592. char* begin = buf;
  593. char* npos = nullptr;
  594. char* end = buf + strlen(buf) - 1;
  595. file.writeError = false;
  596. if ((npos = strchr(buf, 'N'))) {
  597. begin = strchr(npos, ' ') + 1;
  598. end = strchr(npos, '*') - 1;
  599. }
  600. end[1] = '\r';
  601. end[2] = '\n';
  602. end[3] = '\0';
  603. file.write(begin);
  604. if (file.writeError) SERIAL_ERROR_MSG(STR_SD_ERR_WRITE_TO_FILE);
  605. }
  606. #if DISABLED(NO_SD_AUTOSTART)
  607. /**
  608. * Run all the auto#.g files. Called:
  609. * - On boot after successful card init.
  610. * - From the LCD command to Run Auto Files
  611. */
  612. void CardReader::autofile_begin() {
  613. autofile_index = 1;
  614. (void)autofile_check();
  615. }
  616. /**
  617. * Run the next auto#.g file. Called:
  618. * - On boot after successful card init
  619. * - After finishing the previous auto#.g file
  620. * - From the LCD command to begin the auto#.g files
  621. *
  622. * Return 'true' if an auto file was started
  623. */
  624. bool CardReader::autofile_check() {
  625. if (!autofile_index) return false;
  626. if (!isMounted())
  627. mount();
  628. else if (ENABLED(SDCARD_EEPROM_EMULATION))
  629. settings.first_load();
  630. // Don't run auto#.g when a PLR file exists
  631. if (isMounted() && TERN1(POWER_LOSS_RECOVERY, !recovery.valid())) {
  632. char autoname[10];
  633. sprintf_P(autoname, PSTR("/auto%c.g"), '0' + autofile_index - 1);
  634. if (fileExists(autoname)) {
  635. cdroot();
  636. openAndPrintFile(autoname);
  637. autofile_index++;
  638. return true;
  639. }
  640. }
  641. autofile_cancel();
  642. return false;
  643. }
  644. #endif
  645. void CardReader::closefile(const bool store_location/*=false*/) {
  646. file.sync();
  647. file.close();
  648. flag.saving = flag.logging = false;
  649. sdpos = 0;
  650. TERN_(EMERGENCY_PARSER, emergency_parser.enable());
  651. if (store_location) {
  652. //future: store printer state, filename and position for continuing a stopped print
  653. // so one can unplug the printer and continue printing the next day.
  654. }
  655. }
  656. //
  657. // Get info for a file in the working directory by index
  658. //
  659. void CardReader::selectFileByIndex(const uint16_t nr) {
  660. #if ENABLED(SDSORT_CACHE_NAMES)
  661. if (nr < sort_count) {
  662. strcpy(filename, sortshort[nr]);
  663. strcpy(longFilename, sortnames[nr]);
  664. flag.filenameIsDir = IS_DIR(nr);
  665. return;
  666. }
  667. #endif
  668. workDir.rewind();
  669. selectByIndex(workDir, nr);
  670. }
  671. //
  672. // Get info for a file in the working directory by DOS name
  673. //
  674. void CardReader::selectFileByName(const char * const match) {
  675. #if ENABLED(SDSORT_CACHE_NAMES)
  676. for (uint16_t nr = 0; nr < sort_count; nr++)
  677. if (strcasecmp(match, sortshort[nr]) == 0) {
  678. strcpy(filename, sortshort[nr]);
  679. strcpy(longFilename, sortnames[nr]);
  680. flag.filenameIsDir = IS_DIR(nr);
  681. return;
  682. }
  683. #endif
  684. workDir.rewind();
  685. selectByName(workDir, match);
  686. }
  687. uint16_t CardReader::countFilesInWorkDir() {
  688. workDir.rewind();
  689. return countItems(workDir);
  690. }
  691. /**
  692. * Dive to the given DOS 8.3 file path, with optional echo of the dive paths.
  693. *
  694. * On exit:
  695. * - Your curDir pointer contains an SdFile reference to the file's directory.
  696. * - If update_cwd was 'true' the workDir now points to the file's directory.
  697. *
  698. * Returns a pointer to the last segment (filename) of the given DOS 8.3 path.
  699. *
  700. * A nullptr result indicates an unrecoverable error.
  701. */
  702. const char* CardReader::diveToFile(const bool update_cwd, SdFile*& diveDir, const char * const path, const bool echo/*=false*/) {
  703. // Track both parent and subfolder
  704. static SdFile newDir1, newDir2;
  705. SdFile *sub = &newDir1, *startDir;
  706. // Parsing the path string
  707. const char *item_name_adr = path;
  708. DEBUG_ECHOLNPAIR("diveToFile: path = '", path, "'");
  709. if (path[0] == '/') { // Starting at the root directory?
  710. diveDir = &root;
  711. item_name_adr++;
  712. DEBUG_ECHOLNPAIR("diveToFile: CWD to root: ", hex_address((void*)diveDir));
  713. if (update_cwd) workDirDepth = 0; // The cwd can be updated for the benefit of sub-programs
  714. }
  715. else
  716. diveDir = &workDir; // Dive from workDir (as set by the UI)
  717. startDir = diveDir;
  718. DEBUG_ECHOLNPAIR("diveToFile: startDir = ", hex_address((void*)startDir));
  719. while (item_name_adr) {
  720. // Find next subdirectory delimiter
  721. char * const name_end = strchr(item_name_adr, '/');
  722. // Last atom in the path? Item found.
  723. if (name_end <= item_name_adr) break;
  724. // Set subDirName
  725. const uint8_t len = name_end - item_name_adr;
  726. char dosSubdirname[len + 1];
  727. strncpy(dosSubdirname, item_name_adr, len);
  728. dosSubdirname[len] = 0;
  729. if (echo) SERIAL_ECHOLN(dosSubdirname);
  730. DEBUG_ECHOLNPAIR("diveToFile: sub = ", hex_address((void*)sub));
  731. // Open diveDir (closing first)
  732. sub->close();
  733. if (!sub->open(diveDir, dosSubdirname, O_READ)) {
  734. openFailed(dosSubdirname);
  735. item_name_adr = nullptr;
  736. break;
  737. }
  738. // Close diveDir if not at starting-point
  739. if (diveDir != startDir) {
  740. DEBUG_ECHOLNPAIR("diveToFile: closing diveDir: ", hex_address((void*)diveDir));
  741. diveDir->close();
  742. }
  743. // diveDir now subDir
  744. diveDir = sub;
  745. DEBUG_ECHOLNPAIR("diveToFile: diveDir = sub: ", hex_address((void*)diveDir));
  746. // Update workDirParents and workDirDepth
  747. if (update_cwd) {
  748. DEBUG_ECHOLNPAIR("diveToFile: update_cwd");
  749. if (workDirDepth < MAX_DIR_DEPTH)
  750. workDirParents[workDirDepth++] = *diveDir;
  751. }
  752. // Point sub at the other scratch object
  753. sub = (diveDir != &newDir1) ? &newDir1 : &newDir2;
  754. DEBUG_ECHOLNPAIR("diveToFile: swapping sub = ", hex_address((void*)sub));
  755. // Next path atom address
  756. item_name_adr = name_end + 1;
  757. }
  758. if (update_cwd) {
  759. workDir = *diveDir;
  760. DEBUG_ECHOLNPAIR("diveToFile: final workDir = ", hex_address((void*)diveDir));
  761. flag.workDirIsRoot = (workDirDepth == 0);
  762. TERN_(SDCARD_SORT_ALPHA, presort());
  763. }
  764. return item_name_adr;
  765. }
  766. void CardReader::cd(const char * relpath) {
  767. SdFile newDir;
  768. SdFile *parent = workDir.isOpen() ? &workDir : &root;
  769. if (newDir.open(parent, relpath, O_READ)) {
  770. workDir = newDir;
  771. flag.workDirIsRoot = false;
  772. if (workDirDepth < MAX_DIR_DEPTH)
  773. workDirParents[workDirDepth++] = workDir;
  774. TERN_(SDCARD_SORT_ALPHA, presort());
  775. }
  776. else
  777. SERIAL_ECHO_MSG(STR_SD_CANT_ENTER_SUBDIR, relpath);
  778. }
  779. int8_t CardReader::cdup() {
  780. if (workDirDepth > 0) { // At least 1 dir has been saved
  781. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  782. TERN_(SDCARD_SORT_ALPHA, presort());
  783. }
  784. if (!workDirDepth) flag.workDirIsRoot = true;
  785. return workDirDepth;
  786. }
  787. void CardReader::cdroot() {
  788. workDir = root;
  789. flag.workDirIsRoot = true;
  790. TERN_(SDCARD_SORT_ALPHA, presort());
  791. }
  792. #if ENABLED(SDCARD_SORT_ALPHA)
  793. /**
  794. * Get the name of a file in the working directory by sort-index
  795. */
  796. void CardReader::getfilename_sorted(const uint16_t nr) {
  797. selectFileByIndex(TERN1(SDSORT_GCODE, sort_alpha) && (nr < sort_count)
  798. ? sort_order[nr] : nr);
  799. }
  800. #if ENABLED(SDSORT_USES_RAM)
  801. #if ENABLED(SDSORT_DYNAMIC_RAM)
  802. // Use dynamic method to copy long filename
  803. #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename()))
  804. #if ENABLED(SDSORT_CACHE_NAMES)
  805. // When caching also store the short name, since
  806. // we're replacing the selectFileByIndex() behavior.
  807. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename))
  808. #else
  809. #define SET_SORTSHORT(I) NOOP
  810. #endif
  811. #else
  812. // Copy filenames into the static array
  813. #define _SET_SORTNAME(I) strncpy(sortnames[I], longest_filename(), SORTED_LONGNAME_MAXLEN)
  814. #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH
  815. // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul
  816. #define SET_SORTNAME(I) _SET_SORTNAME(I)
  817. #else
  818. // Copy multiple name blocks. Add a nul for the longest case.
  819. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0)
  820. #endif
  821. #if ENABLED(SDSORT_CACHE_NAMES)
  822. #define SET_SORTSHORT(I) strcpy(sortshort[I], filename)
  823. #else
  824. #define SET_SORTSHORT(I) NOOP
  825. #endif
  826. #endif
  827. #endif
  828. /**
  829. * Read all the files and produce a sort key
  830. *
  831. * We can do this in 3 ways...
  832. * - Minimal RAM: Read two filenames at a time sorting along...
  833. * - Some RAM: Buffer the directory just for this sort
  834. * - Most RAM: Buffer the directory and return filenames from RAM
  835. */
  836. void CardReader::presort() {
  837. // Throw away old sort index
  838. flush_presort();
  839. // Sorting may be turned off
  840. if (TERN0(SDSORT_GCODE, !sort_alpha)) return;
  841. // If there are files, sort up to the limit
  842. uint16_t fileCnt = countFilesInWorkDir();
  843. if (fileCnt > 0) {
  844. // Never sort more than the max allowed
  845. // If you use folders to organize, 20 may be enough
  846. NOMORE(fileCnt, uint16_t(SDSORT_LIMIT));
  847. // Sort order is always needed. May be static or dynamic.
  848. TERN_(SDSORT_DYNAMIC_RAM, sort_order = new uint8_t[fileCnt]);
  849. // Use RAM to store the entire directory during pre-sort.
  850. // SDSORT_LIMIT should be set to prevent over-allocation.
  851. #if ENABLED(SDSORT_USES_RAM)
  852. // If using dynamic ram for names, allocate on the heap.
  853. #if ENABLED(SDSORT_CACHE_NAMES)
  854. #if ENABLED(SDSORT_DYNAMIC_RAM)
  855. sortshort = new char*[fileCnt];
  856. sortnames = new char*[fileCnt];
  857. #endif
  858. #elif ENABLED(SDSORT_USES_STACK)
  859. char sortnames[fileCnt][SORTED_LONGNAME_STORAGE];
  860. #endif
  861. // Folder sorting needs 1 bit per entry for flags.
  862. #if HAS_FOLDER_SORTING
  863. #if ENABLED(SDSORT_DYNAMIC_RAM)
  864. isDir = new uint8_t[(fileCnt + 7) >> 3];
  865. #elif ENABLED(SDSORT_USES_STACK)
  866. uint8_t isDir[(fileCnt + 7) >> 3];
  867. #endif
  868. #endif
  869. #else // !SDSORT_USES_RAM
  870. // By default re-read the names from SD for every compare
  871. // retaining only two filenames at a time. This is very
  872. // slow but is safest and uses minimal RAM.
  873. char name1[LONG_FILENAME_LENGTH];
  874. #endif
  875. if (fileCnt > 1) {
  876. // Init sort order.
  877. for (uint16_t i = 0; i < fileCnt; i++) {
  878. sort_order[i] = i;
  879. // If using RAM then read all filenames now.
  880. #if ENABLED(SDSORT_USES_RAM)
  881. selectFileByIndex(i);
  882. SET_SORTNAME(i);
  883. SET_SORTSHORT(i);
  884. // char out[30];
  885. // sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]);
  886. // SERIAL_ECHOLN(out);
  887. #if HAS_FOLDER_SORTING
  888. const uint16_t bit = i & 0x07, ind = i >> 3;
  889. if (bit == 0) isDir[ind] = 0x00;
  890. if (flag.filenameIsDir) SBI(isDir[ind], bit);
  891. #endif
  892. #endif
  893. }
  894. // Bubble Sort
  895. for (uint16_t i = fileCnt; --i;) {
  896. bool didSwap = false;
  897. uint8_t o1 = sort_order[0];
  898. #if DISABLED(SDSORT_USES_RAM)
  899. selectFileByIndex(o1); // Pre-fetch the first entry and save it
  900. strcpy(name1, longest_filename()); // so the loop only needs one fetch
  901. TERN_(HAS_FOLDER_SORTING, bool dir1 = flag.filenameIsDir);
  902. #endif
  903. for (uint16_t j = 0; j < i; ++j) {
  904. const uint16_t o2 = sort_order[j + 1];
  905. // Compare names from the array or just the two buffered names
  906. #if ENABLED(SDSORT_USES_RAM)
  907. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  908. #else
  909. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  910. #endif
  911. #if HAS_FOLDER_SORTING
  912. #if ENABLED(SDSORT_USES_RAM)
  913. // Folder sorting needs an index and bit to test for folder-ness.
  914. #define _SORT_CMP_DIR(fs) (IS_DIR(o1) == IS_DIR(o2) ? _SORT_CMP_NODIR() : IS_DIR(fs > 0 ? o1 : o2))
  915. #else
  916. #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  917. #endif
  918. #endif
  919. // The most economical method reads names as-needed
  920. // throughout the loop. Slow if there are many.
  921. #if DISABLED(SDSORT_USES_RAM)
  922. selectFileByIndex(o2);
  923. const bool dir2 = flag.filenameIsDir;
  924. char * const name2 = longest_filename(); // use the string in-place
  925. #endif // !SDSORT_USES_RAM
  926. // Sort the current pair according to settings.
  927. if (
  928. #if HAS_FOLDER_SORTING
  929. #if ENABLED(SDSORT_GCODE)
  930. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  931. #else
  932. _SORT_CMP_DIR(FOLDER_SORTING)
  933. #endif
  934. #else
  935. _SORT_CMP_NODIR()
  936. #endif
  937. ) {
  938. // Reorder the index, indicate that sorting happened
  939. // Note that the next o1 will be the current o1. No new fetch needed.
  940. sort_order[j] = o2;
  941. sort_order[j + 1] = o1;
  942. didSwap = true;
  943. }
  944. else {
  945. // The next o1 is the current o2. No new fetch needed.
  946. o1 = o2;
  947. #if DISABLED(SDSORT_USES_RAM)
  948. TERN_(HAS_FOLDER_SORTING, dir1 = dir2);
  949. strcpy(name1, name2);
  950. #endif
  951. }
  952. }
  953. if (!didSwap) break;
  954. }
  955. // Using RAM but not keeping names around
  956. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  957. #if ENABLED(SDSORT_DYNAMIC_RAM)
  958. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  959. TERN_(HAS_FOLDER_SORTING, free(isDir));
  960. #endif
  961. #endif
  962. }
  963. else {
  964. sort_order[0] = 0;
  965. #if BOTH(SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  966. #if ENABLED(SDSORT_DYNAMIC_RAM)
  967. sortnames = new char*[1];
  968. sortshort = new char*[1];
  969. isDir = new uint8_t[1];
  970. #endif
  971. selectFileByIndex(0);
  972. SET_SORTNAME(0);
  973. SET_SORTSHORT(0);
  974. isDir[0] = flag.filenameIsDir;
  975. #endif
  976. }
  977. sort_count = fileCnt;
  978. }
  979. }
  980. void CardReader::flush_presort() {
  981. if (sort_count > 0) {
  982. #if ENABLED(SDSORT_DYNAMIC_RAM)
  983. delete sort_order;
  984. #if ENABLED(SDSORT_CACHE_NAMES)
  985. LOOP_L_N(i, sort_count) {
  986. free(sortshort[i]); // strdup
  987. free(sortnames[i]); // strdup
  988. }
  989. delete sortshort;
  990. delete sortnames;
  991. #endif
  992. #endif
  993. sort_count = 0;
  994. }
  995. }
  996. #endif // SDCARD_SORT_ALPHA
  997. uint16_t CardReader::get_num_Files() {
  998. if (!isMounted()) return 0;
  999. return (
  1000. #if ALL(SDCARD_SORT_ALPHA, SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  1001. nrFiles // no need to access the SD card for filenames
  1002. #else
  1003. countFilesInWorkDir()
  1004. #endif
  1005. );
  1006. }
  1007. //
  1008. // Return from procedure or close out the Print Job
  1009. //
  1010. void CardReader::fileHasFinished() {
  1011. planner.synchronize();
  1012. file.close();
  1013. #if HAS_MEDIA_SUBCALLS
  1014. if (file_subcall_ctr > 0) { // Resume calling file after closing procedure
  1015. file_subcall_ctr--;
  1016. openFileRead(proc_filenames[file_subcall_ctr], 2); // 2 = Returning from sub-procedure
  1017. setIndex(filespos[file_subcall_ctr]);
  1018. startFileprint();
  1019. return;
  1020. }
  1021. #endif
  1022. endFilePrint(TERN_(SD_RESORT, true));
  1023. marlin_state = MF_SD_COMPLETE;
  1024. }
  1025. #if ENABLED(AUTO_REPORT_SD_STATUS)
  1026. AutoReporter<CardReader::AutoReportSD> CardReader::auto_reporter;
  1027. #endif
  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. openFailed(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