My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

cardreader.cpp 39KB

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