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

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