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

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