My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

cardreader.cpp 26KB

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