cardreader.cpp 28 KB

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