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

cardreader.cpp 33KB

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