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

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