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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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 <ctype.h>
  23. #include "cardreader.h"
  24. #include "ultralcd.h"
  25. #include "stepper.h"
  26. #include "language.h"
  27. #include "Marlin.h"
  28. #if ENABLED(SDSUPPORT)
  29. #define LONGEST_FILENAME (longFilename[0] ? longFilename : filename)
  30. CardReader::CardReader() {
  31. #if ENABLED(SDCARD_SORT_ALPHA)
  32. sort_count = 0;
  33. #if ENABLED(SDSORT_GCODE)
  34. sort_alpha = true;
  35. sort_folders = FOLDER_SORTING;
  36. //sort_reverse = false;
  37. #endif
  38. #endif
  39. sdprinting = cardOK = saving = logging = false;
  40. filesize = 0;
  41. sdpos = 0;
  42. workDirDepth = 0;
  43. file_subcall_ctr = 0;
  44. ZERO(workDirParents);
  45. autostart_stilltocheck = true; //the SD start is delayed, because otherwise the serial cannot answer fast enough to make contact with the host software.
  46. autostart_index = 0;
  47. //power to SD reader
  48. #if SDPOWER > -1
  49. OUT_WRITE(SDPOWER, HIGH);
  50. #endif // SDPOWER
  51. next_autostart_ms = millis() + 5000;
  52. }
  53. char *createFilename(char *buffer, const dir_t &p) { //buffer > 12characters
  54. char *pos = buffer;
  55. for (uint8_t i = 0; i < 11; i++) {
  56. if (p.name[i] == ' ') continue;
  57. if (i == 8) *pos++ = '.';
  58. *pos++ = p.name[i];
  59. }
  60. *pos++ = 0;
  61. return buffer;
  62. }
  63. /**
  64. * Dive into a folder and recurse depth-first to perform a pre-set operation lsAction:
  65. * LS_Count - Add +1 to nrFiles for every file within the parent
  66. * LS_GetFilename - Get the filename of the file indexed by nrFile_index
  67. * LS_SerialPrint - Print the full path and size of each file to serial output
  68. */
  69. uint16_t nrFile_index;
  70. void CardReader::lsDive(const char *prepend, SdFile parent, const char * const match/*=NULL*/) {
  71. dir_t p;
  72. uint8_t cnt = 0;
  73. // Read the next entry from a directory
  74. while (parent.readDir(p, longFilename) > 0) {
  75. // If the entry is a directory and the action is LS_SerialPrint
  76. if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) {
  77. // Get the short name for the item, which we know is a folder
  78. char lfilename[FILENAME_LENGTH];
  79. createFilename(lfilename, p);
  80. // Allocate enough stack space for the full path to a folder, trailing slash, and nul
  81. bool prepend_is_empty = (prepend[0] == '\0');
  82. int len = (prepend_is_empty ? 1 : strlen(prepend)) + strlen(lfilename) + 1 + 1;
  83. char path[len];
  84. // Append the FOLDERNAME12/ to the passed string.
  85. // It contains the full path to the "parent" argument.
  86. // We now have the full path to the item in this folder.
  87. strcpy(path, prepend_is_empty ? "/" : prepend); // root slash if prepend is empty
  88. strcat(path, lfilename); // FILENAME_LENGTH-1 characters maximum
  89. strcat(path, "/"); // 1 character
  90. // Serial.print(path);
  91. // Get a new directory object using the full path
  92. // and dive recursively into it.
  93. SdFile dir;
  94. if (!dir.open(parent, lfilename, O_READ)) {
  95. if (lsAction == LS_SerialPrint) {
  96. SERIAL_ECHO_START();
  97. SERIAL_ECHOPGM(MSG_SD_CANT_OPEN_SUBDIR);
  98. SERIAL_ECHOLN(lfilename);
  99. }
  100. }
  101. lsDive(path, dir);
  102. // close() is done automatically by destructor of SdFile
  103. }
  104. else {
  105. uint8_t pn0 = p.name[0];
  106. if (pn0 == DIR_NAME_FREE) break;
  107. if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue;
  108. if (longFilename[0] == '.') continue;
  109. if (!DIR_IS_FILE_OR_SUBDIR(&p) || (p.attributes & DIR_ATT_HIDDEN)) continue;
  110. filenameIsDir = DIR_IS_SUBDIR(&p);
  111. if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue;
  112. switch (lsAction) { // 1 based file count
  113. case LS_Count:
  114. nrFiles++;
  115. break;
  116. case LS_SerialPrint:
  117. createFilename(filename, p);
  118. SERIAL_PROTOCOL(prepend);
  119. SERIAL_PROTOCOL(filename);
  120. SERIAL_PROTOCOLCHAR(' ');
  121. SERIAL_PROTOCOLLN(p.fileSize);
  122. break;
  123. case LS_GetFilename:
  124. createFilename(filename, p);
  125. if (match != NULL) {
  126. if (strcasecmp(match, filename) == 0) return;
  127. }
  128. else if (cnt == nrFile_index) return; // 0 based index
  129. cnt++;
  130. break;
  131. }
  132. }
  133. } // while readDir
  134. }
  135. void CardReader::ls() {
  136. lsAction = LS_SerialPrint;
  137. root.rewind();
  138. lsDive("", root);
  139. }
  140. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  141. /**
  142. * Get a long pretty path based on a DOS 8.3 path
  143. */
  144. void CardReader::printLongPath(char *path) {
  145. lsAction = LS_GetFilename;
  146. int i, pathLen = strlen(path);
  147. // SERIAL_ECHOPGM("Full Path: "); SERIAL_ECHOLN(path);
  148. // Zero out slashes to make segments
  149. for (i = 0; i < pathLen; i++) if (path[i] == '/') path[i] = '\0';
  150. SdFile diveDir = root; // start from the root for segment 1
  151. for (i = 0; i < pathLen;) {
  152. if (path[i] == '\0') i++; // move past a single nul
  153. char *segment = &path[i]; // The segment after most slashes
  154. // If a segment is empty (extra-slash) then exit
  155. if (!*segment) break;
  156. // Go to the next segment
  157. while (path[++i]) { }
  158. // SERIAL_ECHOPGM("Looking for segment: "); SERIAL_ECHOLN(segment);
  159. // Find the item, setting the long filename
  160. diveDir.rewind();
  161. lsDive("", diveDir, segment);
  162. // Print /LongNamePart to serial output
  163. SERIAL_PROTOCOLCHAR('/');
  164. SERIAL_PROTOCOL(longFilename[0] ? longFilename : "???");
  165. // If the filename was printed then that's it
  166. if (!filenameIsDir) break;
  167. // SERIAL_ECHOPGM("Opening dir: "); SERIAL_ECHOLN(segment);
  168. // Open the sub-item as the new dive parent
  169. SdFile dir;
  170. if (!dir.open(diveDir, segment, O_READ)) {
  171. SERIAL_EOL();
  172. SERIAL_ECHO_START();
  173. SERIAL_ECHOPGM(MSG_SD_CANT_OPEN_SUBDIR);
  174. SERIAL_ECHO(segment);
  175. break;
  176. }
  177. diveDir.close();
  178. diveDir = dir;
  179. } // while i<pathLen
  180. SERIAL_EOL();
  181. }
  182. #endif // LONG_FILENAME_HOST_SUPPORT
  183. void CardReader::initsd() {
  184. cardOK = false;
  185. if (root.isOpen()) root.close();
  186. #ifndef SPI_SPEED
  187. #define SPI_SPEED SPI_FULL_SPEED
  188. #endif
  189. if (!card.init(SPI_SPEED, SDSS)
  190. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  191. && !card.init(SPI_SPEED, LCD_SDSS)
  192. #endif
  193. ) {
  194. //if (!card.init(SPI_HALF_SPEED,SDSS))
  195. SERIAL_ECHO_START();
  196. SERIAL_ECHOLNPGM(MSG_SD_INIT_FAIL);
  197. }
  198. else if (!volume.init(&card)) {
  199. SERIAL_ERROR_START();
  200. SERIAL_ERRORLNPGM(MSG_SD_VOL_INIT_FAIL);
  201. }
  202. else if (!root.openRoot(&volume)) {
  203. SERIAL_ERROR_START();
  204. SERIAL_ERRORLNPGM(MSG_SD_OPENROOT_FAIL);
  205. }
  206. else {
  207. cardOK = true;
  208. SERIAL_ECHO_START();
  209. SERIAL_ECHOLNPGM(MSG_SD_CARD_OK);
  210. }
  211. workDir = root;
  212. curDir = &root;
  213. #if ENABLED(SDCARD_SORT_ALPHA)
  214. presort();
  215. #endif
  216. /**
  217. if (!workDir.openRoot(&volume)) {
  218. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  219. }
  220. */
  221. }
  222. void CardReader::setroot() {
  223. /*if (!workDir.openRoot(&volume)) {
  224. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  225. }*/
  226. workDir = root;
  227. curDir = &workDir;
  228. #if ENABLED(SDCARD_SORT_ALPHA)
  229. presort();
  230. #endif
  231. }
  232. void CardReader::release() {
  233. sdprinting = false;
  234. cardOK = false;
  235. }
  236. void CardReader::openAndPrintFile(const char *name) {
  237. char cmd[4 + strlen(name) + 1]; // Room for "M23 ", filename, and null
  238. sprintf_P(cmd, PSTR("M23 %s"), name);
  239. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  240. enqueue_and_echo_command(cmd);
  241. enqueue_and_echo_commands_P(PSTR("M24"));
  242. }
  243. void CardReader::startFileprint() {
  244. if (cardOK) {
  245. sdprinting = true;
  246. #if ENABLED(SDCARD_SORT_ALPHA)
  247. flush_presort();
  248. #endif
  249. }
  250. }
  251. void CardReader::stopSDPrint() {
  252. sdprinting = false;
  253. if (isFileOpen()) file.close();
  254. }
  255. void CardReader::openLogFile(char* name) {
  256. logging = true;
  257. openFile(name, false);
  258. }
  259. void CardReader::getAbsFilename(char *t) {
  260. uint8_t cnt = 0;
  261. *t = '/'; t++; cnt++;
  262. for (uint8_t i = 0; i < workDirDepth; i++) {
  263. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  264. while (*t && cnt < MAXPATHNAMELENGTH) { t++; cnt++; } //crawl counter forward.
  265. }
  266. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH))
  267. file.getFilename(t);
  268. else
  269. t[0] = 0;
  270. }
  271. void CardReader::openFile(char* name, bool read, bool push_current/*=false*/) {
  272. if (!cardOK) return;
  273. uint8_t doing = 0;
  274. if (isFileOpen()) { //replacing current file by new file, or subfile call
  275. if (push_current) {
  276. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  277. SERIAL_ERROR_START();
  278. SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  279. SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  280. kill(PSTR(MSG_KILLED));
  281. return;
  282. }
  283. // Store current filename and position
  284. getAbsFilename(proc_filenames[file_subcall_ctr]);
  285. SERIAL_ECHO_START();
  286. SERIAL_ECHOPAIR("SUBROUTINE CALL target:\"", name);
  287. SERIAL_ECHOPAIR("\" parent:\"", proc_filenames[file_subcall_ctr]);
  288. SERIAL_ECHOLNPAIR("\" pos", sdpos);
  289. filespos[file_subcall_ctr] = sdpos;
  290. file_subcall_ctr++;
  291. }
  292. else {
  293. doing = 1;
  294. }
  295. }
  296. else { // Opening fresh file
  297. doing = 2;
  298. file_subcall_ctr = 0; // Reset procedure depth in case user cancels print while in procedure
  299. }
  300. if (doing) {
  301. SERIAL_ECHO_START();
  302. SERIAL_ECHOPGM("Now ");
  303. SERIAL_ECHO(doing == 1 ? "doing" : "fresh");
  304. SERIAL_ECHOLNPAIR(" file: ", name);
  305. }
  306. stopSDPrint();
  307. SdFile myDir;
  308. curDir = &root;
  309. char *fname = name;
  310. char *dirname_start, *dirname_end;
  311. if (name[0] == '/') {
  312. dirname_start = &name[1];
  313. while (dirname_start != NULL) {
  314. dirname_end = strchr(dirname_start, '/');
  315. //SERIAL_ECHOPGM("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  316. //SERIAL_ECHOPGM("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  317. if (dirname_end != NULL && dirname_end > dirname_start) {
  318. char subdirname[FILENAME_LENGTH];
  319. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  320. subdirname[dirname_end - dirname_start] = 0;
  321. SERIAL_ECHOLN(subdirname);
  322. if (!myDir.open(curDir, subdirname, O_READ)) {
  323. SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
  324. SERIAL_PROTOCOL(subdirname);
  325. SERIAL_PROTOCOLCHAR('.');
  326. return;
  327. }
  328. else {
  329. //SERIAL_ECHOLNPGM("dive ok");
  330. }
  331. curDir = &myDir;
  332. dirname_start = dirname_end + 1;
  333. }
  334. else { // the remainder after all /fsa/fdsa/ is the filename
  335. fname = dirname_start;
  336. //SERIAL_ECHOLNPGM("remainder");
  337. //SERIAL_ECHOLN(fname);
  338. break;
  339. }
  340. }
  341. }
  342. else { //relative path
  343. curDir = &workDir;
  344. }
  345. if (read) {
  346. if (file.open(curDir, fname, O_READ)) {
  347. filesize = file.fileSize();
  348. SERIAL_PROTOCOLPAIR(MSG_SD_FILE_OPENED, fname);
  349. SERIAL_PROTOCOLLNPAIR(MSG_SD_SIZE, filesize);
  350. sdpos = 0;
  351. SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED);
  352. getfilename(0, fname);
  353. lcd_setstatus(longFilename[0] ? longFilename : fname);
  354. }
  355. else {
  356. SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, fname);
  357. SERIAL_PROTOCOLCHAR('.');
  358. SERIAL_EOL();
  359. }
  360. }
  361. else { //write
  362. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  363. SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, fname);
  364. SERIAL_PROTOCOLCHAR('.');
  365. SERIAL_EOL();
  366. }
  367. else {
  368. saving = true;
  369. SERIAL_PROTOCOLLNPAIR(MSG_SD_WRITE_TO_FILE, name);
  370. lcd_setstatus(fname);
  371. }
  372. }
  373. }
  374. void CardReader::removeFile(char* name) {
  375. if (!cardOK) return;
  376. stopSDPrint();
  377. SdFile myDir;
  378. curDir = &root;
  379. char *fname = name;
  380. char *dirname_start, *dirname_end;
  381. if (name[0] == '/') {
  382. dirname_start = strchr(name, '/') + 1;
  383. while (dirname_start != NULL) {
  384. dirname_end = strchr(dirname_start, '/');
  385. //SERIAL_ECHOPGM("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  386. //SERIAL_ECHOPGM("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  387. if (dirname_end != NULL && dirname_end > dirname_start) {
  388. char subdirname[FILENAME_LENGTH];
  389. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  390. subdirname[dirname_end - dirname_start] = 0;
  391. SERIAL_ECHOLN(subdirname);
  392. if (!myDir.open(curDir, subdirname, O_READ)) {
  393. SERIAL_PROTOCOLPAIR("open failed, File: ", subdirname);
  394. SERIAL_PROTOCOLCHAR('.');
  395. SERIAL_EOL();
  396. return;
  397. }
  398. else {
  399. //SERIAL_ECHOLNPGM("dive ok");
  400. }
  401. curDir = &myDir;
  402. dirname_start = dirname_end + 1;
  403. }
  404. else { // the remainder after all /fsa/fdsa/ is the filename
  405. fname = dirname_start;
  406. //SERIAL_ECHOLNPGM("remainder");
  407. //SERIAL_ECHOLN(fname);
  408. break;
  409. }
  410. }
  411. }
  412. else { // relative path
  413. curDir = &workDir;
  414. }
  415. if (file.remove(curDir, fname)) {
  416. SERIAL_PROTOCOLPGM("File deleted:");
  417. SERIAL_PROTOCOLLN(fname);
  418. sdpos = 0;
  419. #if ENABLED(SDCARD_SORT_ALPHA)
  420. presort();
  421. #endif
  422. }
  423. else {
  424. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  425. SERIAL_PROTOCOL(fname);
  426. SERIAL_PROTOCOLCHAR('.');
  427. }
  428. }
  429. void CardReader::getStatus() {
  430. if (cardOK) {
  431. SERIAL_PROTOCOLPGM(MSG_SD_PRINTING_BYTE);
  432. SERIAL_PROTOCOL(sdpos);
  433. SERIAL_PROTOCOLCHAR('/');
  434. SERIAL_PROTOCOLLN(filesize);
  435. }
  436. else {
  437. SERIAL_PROTOCOLLNPGM(MSG_SD_NOT_PRINTING);
  438. }
  439. }
  440. void CardReader::write_command(char *buf) {
  441. char* begin = buf;
  442. char* npos = 0;
  443. char* end = buf + strlen(buf) - 1;
  444. file.writeError = false;
  445. if ((npos = strchr(buf, 'N')) != NULL) {
  446. begin = strchr(npos, ' ') + 1;
  447. end = strchr(npos, '*') - 1;
  448. }
  449. end[1] = '\r';
  450. end[2] = '\n';
  451. end[3] = '\0';
  452. file.write(begin);
  453. if (file.writeError) {
  454. SERIAL_ERROR_START();
  455. SERIAL_ERRORLNPGM(MSG_SD_ERR_WRITE_TO_FILE);
  456. }
  457. }
  458. void CardReader::checkautostart(bool force) {
  459. if (!force && (!autostart_stilltocheck || ELAPSED(millis(), next_autostart_ms)))
  460. return;
  461. autostart_stilltocheck = false;
  462. if (!cardOK) {
  463. initsd();
  464. if (!cardOK) return; // fail
  465. }
  466. char autoname[10];
  467. sprintf_P(autoname, PSTR("auto%i.g"), autostart_index);
  468. for (int8_t i = 0; i < (int8_t)strlen(autoname); i++) autoname[i] = tolower(autoname[i]);
  469. dir_t p;
  470. root.rewind();
  471. bool found = false;
  472. while (root.readDir(p, NULL) > 0) {
  473. for (int8_t i = (int8_t)strlen((char*)p.name); i--;) p.name[i] = tolower(p.name[i]);
  474. if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
  475. openAndPrintFile(autoname);
  476. found = true;
  477. }
  478. }
  479. if (!found)
  480. autostart_index = -1;
  481. else
  482. autostart_index++;
  483. }
  484. void CardReader::closefile(bool store_location) {
  485. file.sync();
  486. file.close();
  487. saving = logging = false;
  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. */
  496. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/) {
  497. #if ENABLED(SDSORT_CACHE_NAMES)
  498. if (match != NULL) {
  499. while (nr < sort_count) {
  500. if (strcasecmp(match, sortshort[nr]) == 0) break;
  501. nr++;
  502. }
  503. }
  504. if (nr < sort_count) {
  505. strcpy(filename, sortshort[nr]);
  506. strcpy(longFilename, sortnames[nr]);
  507. filenameIsDir = TEST(isDir[nr>>3], nr & 0x07);
  508. return;
  509. }
  510. #endif // SDSORT_CACHE_NAMES
  511. curDir = &workDir;
  512. lsAction = LS_GetFilename;
  513. nrFile_index = nr;
  514. curDir->rewind();
  515. lsDive("", *curDir, match);
  516. }
  517. uint16_t CardReader::getnrfilenames() {
  518. curDir = &workDir;
  519. lsAction = LS_Count;
  520. nrFiles = 0;
  521. curDir->rewind();
  522. lsDive("", *curDir);
  523. //SERIAL_ECHOLN(nrFiles);
  524. return nrFiles;
  525. }
  526. void CardReader::chdir(const char * relpath) {
  527. SdFile newfile;
  528. SdFile *parent = &root;
  529. if (workDir.isOpen()) parent = &workDir;
  530. if (!newfile.open(*parent, relpath, O_READ)) {
  531. SERIAL_ECHO_START();
  532. SERIAL_ECHOPGM(MSG_SD_CANT_ENTER_SUBDIR);
  533. SERIAL_ECHOLN(relpath);
  534. }
  535. else {
  536. if (workDirDepth < MAX_DIR_DEPTH)
  537. workDirParents[workDirDepth++] = *parent;
  538. workDir = newfile;
  539. #if ENABLED(SDCARD_SORT_ALPHA)
  540. presort();
  541. #endif
  542. }
  543. }
  544. void CardReader::updir() {
  545. if (workDirDepth > 0) {
  546. workDir = workDirParents[--workDirDepth];
  547. #if ENABLED(SDCARD_SORT_ALPHA)
  548. presort();
  549. #endif
  550. }
  551. }
  552. #if ENABLED(SDCARD_SORT_ALPHA)
  553. /**
  554. * Get the name of a file in the current directory by sort-index
  555. */
  556. void CardReader::getfilename_sorted(const uint16_t nr) {
  557. getfilename(
  558. #if ENABLED(SDSORT_GCODE)
  559. sort_alpha &&
  560. #endif
  561. (nr < sort_count) ? sort_order[nr] : nr
  562. );
  563. }
  564. /**
  565. * Read all the files and produce a sort key
  566. *
  567. * We can do this in 3 ways...
  568. * - Minimal RAM: Read two filenames at a time sorting along...
  569. * - Some RAM: Buffer the directory just for this sort
  570. * - Most RAM: Buffer the directory and return filenames from RAM
  571. */
  572. void CardReader::presort() {
  573. // Sorting may be turned off
  574. #if ENABLED(SDSORT_GCODE)
  575. if (!sort_alpha) return;
  576. #endif
  577. // Throw away old sort index
  578. flush_presort();
  579. // If there are files, sort up to the limit
  580. uint16_t fileCnt = getnrfilenames();
  581. if (fileCnt > 0) {
  582. // Never sort more than the max allowed
  583. // If you use folders to organize, 20 may be enough
  584. if (fileCnt > SDSORT_LIMIT) fileCnt = SDSORT_LIMIT;
  585. // Sort order is always needed. May be static or dynamic.
  586. #if ENABLED(SDSORT_DYNAMIC_RAM)
  587. sort_order = new uint8_t[fileCnt];
  588. #endif
  589. // Use RAM to store the entire directory during pre-sort.
  590. // SDSORT_LIMIT should be set to prevent over-allocation.
  591. #if ENABLED(SDSORT_USES_RAM)
  592. // If using dynamic ram for names, allocate on the heap.
  593. #if ENABLED(SDSORT_CACHE_NAMES)
  594. #if ENABLED(SDSORT_DYNAMIC_RAM)
  595. sortshort = new char*[fileCnt];
  596. sortnames = new char*[fileCnt];
  597. #endif
  598. #elif ENABLED(SDSORT_USES_STACK)
  599. char sortnames[fileCnt][LONG_FILENAME_LENGTH];
  600. #endif
  601. // Folder sorting needs 1 bit per entry for flags.
  602. #if HAS_FOLDER_SORTING
  603. #if ENABLED(SDSORT_DYNAMIC_RAM)
  604. isDir = new uint8_t[(fileCnt + 7) >> 3];
  605. #elif ENABLED(SDSORT_USES_STACK)
  606. uint8_t isDir[(fileCnt + 7) >> 3];
  607. #endif
  608. #endif
  609. #else // !SDSORT_USES_RAM
  610. // By default re-read the names from SD for every compare
  611. // retaining only two filenames at a time. This is very
  612. // slow but is safest and uses minimal RAM.
  613. char name1[LONG_FILENAME_LENGTH + 1];
  614. #endif
  615. if (fileCnt > 1) {
  616. // Init sort order.
  617. for (uint16_t i = 0; i < fileCnt; i++) {
  618. sort_order[i] = i;
  619. // If using RAM then read all filenames now.
  620. #if ENABLED(SDSORT_USES_RAM)
  621. getfilename(i);
  622. #if ENABLED(SDSORT_DYNAMIC_RAM)
  623. // Use dynamic method to copy long filename
  624. sortnames[i] = strdup(LONGEST_FILENAME);
  625. #if ENABLED(SDSORT_CACHE_NAMES)
  626. // When caching also store the short name, since
  627. // we're replacing the getfilename() behavior.
  628. sortshort[i] = strdup(filename);
  629. #endif
  630. #else
  631. // Copy filenames into the static array
  632. strcpy(sortnames[i], LONGEST_FILENAME);
  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. sortshort = new char*[1];
  719. sortshort[0] = strdup(filename); // malloc
  720. isDir = new uint8_t[1];
  721. #else
  722. strcpy(sortnames[0], LONGEST_FILENAME);
  723. strcpy(sortshort[0], filename);
  724. #endif
  725. isDir[0] = filenameIsDir ? 0x01 : 0x00;
  726. #endif
  727. }
  728. sort_count = fileCnt;
  729. }
  730. }
  731. void CardReader::flush_presort() {
  732. if (sort_count > 0) {
  733. #if ENABLED(SDSORT_DYNAMIC_RAM)
  734. delete sort_order;
  735. #if ENABLED(SDSORT_CACHE_NAMES)
  736. for (uint8_t i = 0; i < sort_count; ++i) {
  737. free(sortshort[i]); // strdup
  738. free(sortnames[i]); // strdup
  739. }
  740. delete sortshort;
  741. delete sortnames;
  742. #endif
  743. #endif
  744. sort_count = 0;
  745. }
  746. }
  747. #endif // SDCARD_SORT_ALPHA
  748. #if (ENABLED(SDCARD_SORT_ALPHA) && SDSORT_USES_RAM && SDSORT_CACHE_NAMES)
  749. // if true - don't need to access the SD card for file names
  750. uint16_t CardReader::get_num_Files() {return nrFiles;}
  751. #else
  752. uint16_t CardReader::get_num_Files() {return getnrfilenames(); }
  753. #endif
  754. void CardReader::printingHasFinished() {
  755. stepper.synchronize();
  756. file.close();
  757. if (file_subcall_ctr > 0) { // Heading up to a parent file that called current as a procedure.
  758. file_subcall_ctr--;
  759. openFile(proc_filenames[file_subcall_ctr], true, true);
  760. setIndex(filespos[file_subcall_ctr]);
  761. startFileprint();
  762. }
  763. else {
  764. sdprinting = false;
  765. if (SD_FINISHED_STEPPERRELEASE)
  766. enqueue_and_echo_commands_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  767. print_job_timer.stop();
  768. if (print_job_timer.duration() > 60)
  769. enqueue_and_echo_commands_P(PSTR("M31"));
  770. #if ENABLED(SDCARD_SORT_ALPHA)
  771. presort();
  772. #endif
  773. }
  774. }
  775. #endif // SDSUPPORT