My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

cardreader.cpp 37KB

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