My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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_STORAGE];
  69. #endif
  70. #elif DISABLED(SDSORT_USES_STACK)
  71. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  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/*=nullptr*/) {
  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 != nullptr) {
  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(nullptr, 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(nullptr, 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. queue.enqueue_one_now(cmd);
  297. queue.enqueue_now_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 = nullptr;
  435. char* end = buf + strlen(buf) - 1;
  436. file.writeError = false;
  437. if ((npos = strchr(buf, 'N')) != nullptr) {
  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, nullptr) > 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/*=nullptr*/) {
  498. #if ENABLED(SDSORT_CACHE_NAMES)
  499. if (match != nullptr) {
  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(nullptr, workDir, match);
  516. }
  517. uint16_t CardReader::getnrfilenames() {
  518. lsAction = LS_Count;
  519. nrFiles = 0;
  520. workDir.rewind();
  521. lsDive(nullptr, 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 nullptr 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. if (path[0] == '/') {
  540. curDir = &root;
  541. workDirDepth = 0;
  542. dirname_start++;
  543. }
  544. else
  545. curDir = &workDir;
  546. startDir = curDir;
  547. // Start dive
  548. while (dirname_start) {
  549. // Find next sub
  550. char * const dirname_end = strchr(dirname_start, '/');
  551. if (dirname_end <= dirname_start) break;
  552. // Set subDirName
  553. const uint8_t len = dirname_end - dirname_start;
  554. char dosSubdirname[len + 1];
  555. strncpy(dosSubdirname, dirname_start, len);
  556. dosSubdirname[len] = 0;
  557. if (echo) SERIAL_ECHOLN(dosSubdirname);
  558. // Open curDir
  559. if (!sub->open(curDir, dosSubdirname, O_READ)) {
  560. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, dosSubdirname, ".");
  561. return nullptr;
  562. }
  563. // Close curDir if not at starting-point
  564. if (curDir != startDir) curDir->close();
  565. // curDir now subDir
  566. curDir = sub;
  567. // Update workDirParents and workDirDepth
  568. if (workDirDepth < MAX_DIR_DEPTH) workDirParents[workDirDepth++] = *curDir;
  569. // Point sub pointer to unused newDir
  570. sub = (curDir != &newDir1) ? &newDir1 : &newDir2;
  571. // dirname_start point to next sub
  572. dirname_start = dirname_end + 1;
  573. }
  574. return dirname_start;
  575. }
  576. void CardReader::chdir(const char * relpath) {
  577. SdFile newDir;
  578. SdFile *parent = workDir.isOpen() ? &workDir : &root;
  579. if (newDir.open(parent, relpath, O_READ)) {
  580. workDir = newDir;
  581. if (workDirDepth < MAX_DIR_DEPTH)
  582. workDirParents[workDirDepth++] = workDir;
  583. #if ENABLED(SDCARD_SORT_ALPHA)
  584. presort();
  585. #endif
  586. }
  587. else {
  588. SERIAL_ECHO_START();
  589. SERIAL_ECHOLNPAIR(MSG_SD_CANT_ENTER_SUBDIR, relpath);
  590. }
  591. }
  592. int8_t CardReader::updir() {
  593. if (workDirDepth > 0) { // At least 1 dir has been saved
  594. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  595. #if ENABLED(SDCARD_SORT_ALPHA)
  596. presort();
  597. #endif
  598. }
  599. return workDirDepth;
  600. }
  601. void CardReader::setroot() {
  602. /*if (!workDir.openRoot(&volume)) {
  603. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  604. }*/
  605. workDir = root;
  606. #if ENABLED(SDCARD_SORT_ALPHA)
  607. presort();
  608. #endif
  609. }
  610. #if ENABLED(SDCARD_SORT_ALPHA)
  611. /**
  612. * Get the name of a file in the current directory by sort-index
  613. */
  614. void CardReader::getfilename_sorted(const uint16_t nr) {
  615. getfilename(
  616. #if ENABLED(SDSORT_GCODE)
  617. sort_alpha &&
  618. #endif
  619. (nr < sort_count) ? sort_order[nr] : nr
  620. );
  621. }
  622. #if ENABLED(SDSORT_USES_RAM)
  623. #if ENABLED(SDSORT_DYNAMIC_RAM)
  624. // Use dynamic method to copy long filename
  625. #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename()))
  626. #if ENABLED(SDSORT_CACHE_NAMES)
  627. // When caching also store the short name, since
  628. // we're replacing the getfilename() behavior.
  629. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename))
  630. #else
  631. #define SET_SORTSHORT(I) NOOP
  632. #endif
  633. #else
  634. // Copy filenames into the static array
  635. #define _SET_SORTNAME(I) strncpy(sortnames[I], longest_filename(), SORTED_LONGNAME_MAXLEN)
  636. #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH
  637. // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul
  638. #define SET_SORTNAME(I) _SET_SORTNAME(I)
  639. #else
  640. // Copy multiple name blocks. Add a nul for the longest case.
  641. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0)
  642. #endif
  643. #if ENABLED(SDSORT_CACHE_NAMES)
  644. #define SET_SORTSHORT(I) strcpy(sortshort[I], filename)
  645. #else
  646. #define SET_SORTSHORT(I) NOOP
  647. #endif
  648. #endif
  649. #endif
  650. /**
  651. * Read all the files and produce a sort key
  652. *
  653. * We can do this in 3 ways...
  654. * - Minimal RAM: Read two filenames at a time sorting along...
  655. * - Some RAM: Buffer the directory just for this sort
  656. * - Most RAM: Buffer the directory and return filenames from RAM
  657. */
  658. void CardReader::presort() {
  659. // Throw away old sort index
  660. flush_presort();
  661. // Sorting may be turned off
  662. #if ENABLED(SDSORT_GCODE)
  663. if (!sort_alpha) return;
  664. #endif
  665. // If there are files, sort up to the limit
  666. uint16_t fileCnt = getnrfilenames();
  667. if (fileCnt > 0) {
  668. // Never sort more than the max allowed
  669. // If you use folders to organize, 20 may be enough
  670. NOMORE(fileCnt, uint16_t(SDSORT_LIMIT));
  671. // Sort order is always needed. May be static or dynamic.
  672. #if ENABLED(SDSORT_DYNAMIC_RAM)
  673. sort_order = new uint8_t[fileCnt];
  674. #endif
  675. // Use RAM to store the entire directory during pre-sort.
  676. // SDSORT_LIMIT should be set to prevent over-allocation.
  677. #if ENABLED(SDSORT_USES_RAM)
  678. // If using dynamic ram for names, allocate on the heap.
  679. #if ENABLED(SDSORT_CACHE_NAMES)
  680. #if ENABLED(SDSORT_DYNAMIC_RAM)
  681. sortshort = new char*[fileCnt];
  682. sortnames = new char*[fileCnt];
  683. #endif
  684. #elif ENABLED(SDSORT_USES_STACK)
  685. char sortnames[fileCnt][SORTED_LONGNAME_STORAGE];
  686. #endif
  687. // Folder sorting needs 1 bit per entry for flags.
  688. #if HAS_FOLDER_SORTING
  689. #if ENABLED(SDSORT_DYNAMIC_RAM)
  690. isDir = new uint8_t[(fileCnt + 7) >> 3];
  691. #elif ENABLED(SDSORT_USES_STACK)
  692. uint8_t isDir[(fileCnt + 7) >> 3];
  693. #endif
  694. #endif
  695. #else // !SDSORT_USES_RAM
  696. // By default re-read the names from SD for every compare
  697. // retaining only two filenames at a time. This is very
  698. // slow but is safest and uses minimal RAM.
  699. char name1[LONG_FILENAME_LENGTH];
  700. #endif
  701. if (fileCnt > 1) {
  702. // Init sort order.
  703. for (uint16_t i = 0; i < fileCnt; i++) {
  704. sort_order[i] = (
  705. #if ENABLED(SDCARD_RATHERRECENTFIRST)
  706. fileCnt - 1 -
  707. #endif
  708. i);
  709. // If using RAM then read all filenames now.
  710. #if ENABLED(SDSORT_USES_RAM)
  711. getfilename(i);
  712. SET_SORTNAME(i);
  713. SET_SORTSHORT(i);
  714. // char out[30];
  715. // sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]);
  716. // SERIAL_ECHOLN(out);
  717. #if HAS_FOLDER_SORTING
  718. const uint16_t bit = i & 0x07, ind = i >> 3;
  719. if (bit == 0) isDir[ind] = 0x00;
  720. if (flag.filenameIsDir) isDir[ind] |= _BV(bit);
  721. #endif
  722. #endif
  723. }
  724. // Bubble Sort
  725. for (uint16_t i = fileCnt; --i;) {
  726. bool didSwap = false;
  727. for (uint16_t j = 0; j < i; ++j) {
  728. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  729. // Compare names from the array or just the two buffered names
  730. #if ENABLED(SDSORT_USES_RAM)
  731. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  732. #else
  733. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  734. #endif
  735. #if HAS_FOLDER_SORTING
  736. #if ENABLED(SDSORT_USES_RAM)
  737. // Folder sorting needs an index and bit to test for folder-ness.
  738. const uint8_t ind1 = o1 >> 3, bit1 = o1 & 0x07,
  739. ind2 = o2 >> 3, bit2 = o2 & 0x07;
  740. #define _SORT_CMP_DIR(fs) \
  741. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  742. ? _SORT_CMP_NODIR() \
  743. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  744. #else
  745. #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  746. #endif
  747. #endif
  748. // The most economical method reads names as-needed
  749. // throughout the loop. Slow if there are many.
  750. #if DISABLED(SDSORT_USES_RAM)
  751. getfilename(o1);
  752. strcpy(name1, longest_filename()); // save (or getfilename below will trounce it)
  753. #if HAS_FOLDER_SORTING
  754. bool dir1 = flag.filenameIsDir;
  755. #endif
  756. getfilename(o2);
  757. char *name2 = longest_filename(); // use the string in-place
  758. #endif // !SDSORT_USES_RAM
  759. // Sort the current pair according to settings.
  760. if (
  761. #if HAS_FOLDER_SORTING
  762. #if ENABLED(SDSORT_GCODE)
  763. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  764. #else
  765. _SORT_CMP_DIR(FOLDER_SORTING)
  766. #endif
  767. #else
  768. _SORT_CMP_NODIR()
  769. #endif
  770. ) {
  771. sort_order[j] = o2;
  772. sort_order[j + 1] = o1;
  773. didSwap = true;
  774. }
  775. }
  776. if (!didSwap) break;
  777. }
  778. // Using RAM but not keeping names around
  779. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  780. #if ENABLED(SDSORT_DYNAMIC_RAM)
  781. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  782. #if HAS_FOLDER_SORTING
  783. free(isDir);
  784. #endif
  785. #endif
  786. #endif
  787. }
  788. else {
  789. sort_order[0] = 0;
  790. #if BOTH(SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  791. #if ENABLED(SDSORT_DYNAMIC_RAM)
  792. sortnames = new char*[1];
  793. sortshort = new char*[1];
  794. isDir = new uint8_t[1];
  795. #endif
  796. getfilename(0);
  797. SET_SORTNAME(0);
  798. SET_SORTSHORT(0);
  799. isDir[0] = flag.filenameIsDir ? 0x01 : 0x00;
  800. #endif
  801. }
  802. sort_count = fileCnt;
  803. }
  804. }
  805. void CardReader::flush_presort() {
  806. if (sort_count > 0) {
  807. #if ENABLED(SDSORT_DYNAMIC_RAM)
  808. delete sort_order;
  809. #if ENABLED(SDSORT_CACHE_NAMES)
  810. for (uint8_t i = 0; i < sort_count; ++i) {
  811. free(sortshort[i]); // strdup
  812. free(sortnames[i]); // strdup
  813. }
  814. delete sortshort;
  815. delete sortnames;
  816. #endif
  817. #endif
  818. sort_count = 0;
  819. }
  820. }
  821. #endif // SDCARD_SORT_ALPHA
  822. uint16_t CardReader::get_num_Files() {
  823. return
  824. #if ENABLED(SDCARD_SORT_ALPHA) && SDSORT_USES_RAM && SDSORT_CACHE_NAMES
  825. nrFiles // no need to access the SD card for filenames
  826. #else
  827. getnrfilenames()
  828. #endif
  829. ;
  830. }
  831. void CardReader::printingHasFinished() {
  832. planner.synchronize();
  833. file.close();
  834. if (file_subcall_ctr > 0) { // Heading up to a parent file that called current as a procedure.
  835. file_subcall_ctr--;
  836. openFile(proc_filenames[file_subcall_ctr], true, true);
  837. setIndex(filespos[file_subcall_ctr]);
  838. startFileprint();
  839. }
  840. else {
  841. stopSDPrint();
  842. #if ENABLED(POWER_LOSS_RECOVERY)
  843. removeJobRecoveryFile();
  844. #endif
  845. #if ENABLED(SD_FINISHED_STEPPERRELEASE) && defined(SD_FINISHED_RELEASECOMMAND)
  846. planner.finish_and_disable();
  847. #endif
  848. print_job_timer.stop();
  849. if (print_job_timer.duration() > 60) queue.inject_P(PSTR("M31"));
  850. #if ENABLED(SDCARD_SORT_ALPHA)
  851. presort();
  852. #endif
  853. #if EITHER(ULTRA_LCD, EXTENSIBLE_UI) && ENABLED(LCD_SET_PROGRESS_MANUALLY)
  854. ui.progress_bar_percent = 0;
  855. #endif
  856. ui.reset_status();
  857. #if ENABLED(SD_REPRINT_LAST_SELECTED_FILE)
  858. ui.reselect_last_file();
  859. #endif
  860. }
  861. }
  862. #if ENABLED(AUTO_REPORT_SD_STATUS)
  863. uint8_t CardReader::auto_report_sd_interval = 0;
  864. millis_t CardReader::next_sd_report_ms;
  865. #if NUM_SERIAL > 1
  866. int8_t CardReader::auto_report_port;
  867. #endif
  868. void CardReader::auto_report_sd_status() {
  869. millis_t current_ms = millis();
  870. if (auto_report_sd_interval && ELAPSED(current_ms, next_sd_report_ms)) {
  871. next_sd_report_ms = current_ms + 1000UL * auto_report_sd_interval;
  872. PORT_REDIRECT(auto_report_port);
  873. report_status();
  874. }
  875. }
  876. #endif // AUTO_REPORT_SD_STATUS
  877. #if ENABLED(POWER_LOSS_RECOVERY)
  878. constexpr char job_recovery_file_name[5] = "/PLR";
  879. bool CardReader::jobRecoverFileExists() {
  880. const bool exists = recovery.file.open(&root, job_recovery_file_name, O_READ);
  881. if (exists) recovery.file.close();
  882. return exists;
  883. }
  884. void CardReader::openJobRecoveryFile(const bool read) {
  885. if (!isDetected()) return;
  886. if (recovery.file.isOpen()) return;
  887. if (!recovery.file.open(&root, job_recovery_file_name, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC))
  888. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, job_recovery_file_name, ".");
  889. else if (!read)
  890. SERIAL_ECHOLNPAIR(MSG_SD_WRITE_TO_FILE, job_recovery_file_name);
  891. }
  892. // Removing the job recovery file currently requires closing
  893. // the file being printed, so during SD printing the file should
  894. // be zeroed and written instead of deleted.
  895. void CardReader::removeJobRecoveryFile() {
  896. if (jobRecoverFileExists()) {
  897. recovery.init();
  898. removeFile(job_recovery_file_name);
  899. #if ENABLED(DEBUG_POWER_LOSS_RECOVERY)
  900. SERIAL_ECHOPGM("Power-loss file delete");
  901. serialprintPGM(jobRecoverFileExists() ? PSTR(" failed.\n") : PSTR("d.\n"));
  902. #endif
  903. }
  904. }
  905. #endif // POWER_LOSS_RECOVERY
  906. #endif // SDSUPPORT