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

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