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

cardreader.cpp 33KB

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