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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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 nrFiles
  67. * LS_SerialPrint - Print the full path and size of each file to serial output
  68. */
  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) {
  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 == nrFiles) return;
  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. workDir = root;
  211. curDir = &root;
  212. #if ENABLED(SDCARD_SORT_ALPHA)
  213. presort();
  214. #endif
  215. /**
  216. if (!workDir.openRoot(&volume)) {
  217. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  218. }
  219. */
  220. }
  221. void CardReader::setroot() {
  222. /*if (!workDir.openRoot(&volume)) {
  223. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  224. }*/
  225. workDir = root;
  226. curDir = &workDir;
  227. #if ENABLED(SDCARD_SORT_ALPHA)
  228. presort();
  229. #endif
  230. }
  231. void CardReader::release() {
  232. sdprinting = false;
  233. cardOK = false;
  234. }
  235. void CardReader::openAndPrintFile(const char *name) {
  236. char cmd[4 + strlen(name) + 1]; // Room for "M23 ", filename, and null
  237. sprintf_P(cmd, PSTR("M23 %s"), name);
  238. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  239. enqueue_and_echo_command(cmd);
  240. enqueue_and_echo_commands_P(PSTR("M24"));
  241. }
  242. void CardReader::startFileprint() {
  243. if (cardOK) {
  244. sdprinting = true;
  245. #if ENABLED(SDCARD_SORT_ALPHA)
  246. flush_presort();
  247. #endif
  248. }
  249. }
  250. void CardReader::stopSDPrint() {
  251. sdprinting = false;
  252. if (isFileOpen()) file.close();
  253. }
  254. void CardReader::openLogFile(char* name) {
  255. logging = true;
  256. openFile(name, false);
  257. }
  258. void CardReader::getAbsFilename(char *t) {
  259. uint8_t cnt = 0;
  260. *t = '/'; t++; cnt++;
  261. for (uint8_t i = 0; i < workDirDepth; i++) {
  262. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  263. while (*t && cnt < MAXPATHNAMELENGTH) { t++; cnt++; } //crawl counter forward.
  264. }
  265. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH))
  266. file.getFilename(t);
  267. else
  268. t[0] = 0;
  269. }
  270. void CardReader::openFile(char* name, bool read, bool push_current/*=false*/) {
  271. if (!cardOK) return;
  272. uint8_t doing = 0;
  273. if (isFileOpen()) { //replacing current file by new file, or subfile call
  274. if (push_current) {
  275. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  276. SERIAL_ERROR_START();
  277. SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  278. SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  279. kill(PSTR(MSG_KILLED));
  280. return;
  281. }
  282. // Store current filename and position
  283. getAbsFilename(proc_filenames[file_subcall_ctr]);
  284. SERIAL_ECHO_START();
  285. SERIAL_ECHOPAIR("SUBROUTINE CALL target:\"", name);
  286. SERIAL_ECHOPAIR("\" parent:\"", proc_filenames[file_subcall_ctr]);
  287. SERIAL_ECHOLNPAIR("\" pos", sdpos);
  288. filespos[file_subcall_ctr] = sdpos;
  289. file_subcall_ctr++;
  290. }
  291. else {
  292. doing = 1;
  293. }
  294. }
  295. else { // Opening fresh file
  296. doing = 2;
  297. file_subcall_ctr = 0; // Reset procedure depth in case user cancels print while in procedure
  298. }
  299. if (doing) {
  300. SERIAL_ECHO_START();
  301. SERIAL_ECHOPGM("Now ");
  302. SERIAL_ECHO(doing == 1 ? "doing" : "fresh");
  303. SERIAL_ECHOLNPAIR(" file: ", name);
  304. }
  305. stopSDPrint();
  306. SdFile myDir;
  307. curDir = &root;
  308. char *fname = name;
  309. char *dirname_start, *dirname_end;
  310. if (name[0] == '/') {
  311. dirname_start = &name[1];
  312. while (dirname_start != NULL) {
  313. dirname_end = strchr(dirname_start, '/');
  314. //SERIAL_ECHOPGM("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  315. //SERIAL_ECHOPGM("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  316. if (dirname_end != NULL && dirname_end > dirname_start) {
  317. char subdirname[FILENAME_LENGTH];
  318. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  319. subdirname[dirname_end - dirname_start] = 0;
  320. SERIAL_ECHOLN(subdirname);
  321. if (!myDir.open(curDir, subdirname, O_READ)) {
  322. SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
  323. SERIAL_PROTOCOL(subdirname);
  324. SERIAL_PROTOCOLCHAR('.');
  325. return;
  326. }
  327. else {
  328. //SERIAL_ECHOLNPGM("dive ok");
  329. }
  330. curDir = &myDir;
  331. dirname_start = dirname_end + 1;
  332. }
  333. else { // the remainder after all /fsa/fdsa/ is the filename
  334. fname = dirname_start;
  335. //SERIAL_ECHOLNPGM("remainder");
  336. //SERIAL_ECHOLN(fname);
  337. break;
  338. }
  339. }
  340. }
  341. else { //relative path
  342. curDir = &workDir;
  343. }
  344. if (read) {
  345. if (file.open(curDir, fname, O_READ)) {
  346. filesize = file.fileSize();
  347. SERIAL_PROTOCOLPAIR(MSG_SD_FILE_OPENED, fname);
  348. SERIAL_PROTOCOLLNPAIR(MSG_SD_SIZE, filesize);
  349. sdpos = 0;
  350. SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED);
  351. getfilename(0, fname);
  352. lcd_setstatus(longFilename[0] ? longFilename : fname);
  353. }
  354. else {
  355. SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, fname);
  356. SERIAL_PROTOCOLCHAR('.');
  357. SERIAL_EOL();
  358. }
  359. }
  360. else { //write
  361. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  362. SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, fname);
  363. SERIAL_PROTOCOLCHAR('.');
  364. SERIAL_EOL();
  365. }
  366. else {
  367. saving = true;
  368. SERIAL_PROTOCOLLNPAIR(MSG_SD_WRITE_TO_FILE, name);
  369. lcd_setstatus(fname);
  370. }
  371. }
  372. }
  373. void CardReader::removeFile(char* name) {
  374. if (!cardOK) return;
  375. stopSDPrint();
  376. SdFile myDir;
  377. curDir = &root;
  378. char *fname = name;
  379. char *dirname_start, *dirname_end;
  380. if (name[0] == '/') {
  381. dirname_start = strchr(name, '/') + 1;
  382. while (dirname_start != NULL) {
  383. dirname_end = strchr(dirname_start, '/');
  384. //SERIAL_ECHOPGM("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  385. //SERIAL_ECHOPGM("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  386. if (dirname_end != NULL && dirname_end > dirname_start) {
  387. char subdirname[FILENAME_LENGTH];
  388. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  389. subdirname[dirname_end - dirname_start] = 0;
  390. SERIAL_ECHOLN(subdirname);
  391. if (!myDir.open(curDir, subdirname, O_READ)) {
  392. SERIAL_PROTOCOLPAIR("open failed, File: ", subdirname);
  393. SERIAL_PROTOCOLCHAR('.');
  394. SERIAL_EOL();
  395. return;
  396. }
  397. else {
  398. //SERIAL_ECHOLNPGM("dive ok");
  399. }
  400. curDir = &myDir;
  401. dirname_start = dirname_end + 1;
  402. }
  403. else { // the remainder after all /fsa/fdsa/ is the filename
  404. fname = dirname_start;
  405. //SERIAL_ECHOLNPGM("remainder");
  406. //SERIAL_ECHOLN(fname);
  407. break;
  408. }
  409. }
  410. }
  411. else { // relative path
  412. curDir = &workDir;
  413. }
  414. if (file.remove(curDir, fname)) {
  415. SERIAL_PROTOCOLPGM("File deleted:");
  416. SERIAL_PROTOCOLLN(fname);
  417. sdpos = 0;
  418. #if ENABLED(SDCARD_SORT_ALPHA)
  419. presort();
  420. #endif
  421. }
  422. else {
  423. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  424. SERIAL_PROTOCOL(fname);
  425. SERIAL_PROTOCOLCHAR('.');
  426. }
  427. }
  428. void CardReader::getStatus() {
  429. if (cardOK) {
  430. SERIAL_PROTOCOLPGM(MSG_SD_PRINTING_BYTE);
  431. SERIAL_PROTOCOL(sdpos);
  432. SERIAL_PROTOCOLCHAR('/');
  433. SERIAL_PROTOCOLLN(filesize);
  434. }
  435. else {
  436. SERIAL_PROTOCOLLNPGM(MSG_SD_NOT_PRINTING);
  437. }
  438. }
  439. void CardReader::write_command(char *buf) {
  440. char* begin = buf;
  441. char* npos = 0;
  442. char* end = buf + strlen(buf) - 1;
  443. file.writeError = false;
  444. if ((npos = strchr(buf, 'N')) != NULL) {
  445. begin = strchr(npos, ' ') + 1;
  446. end = strchr(npos, '*') - 1;
  447. }
  448. end[1] = '\r';
  449. end[2] = '\n';
  450. end[3] = '\0';
  451. file.write(begin);
  452. if (file.writeError) {
  453. SERIAL_ERROR_START();
  454. SERIAL_ERRORLNPGM(MSG_SD_ERR_WRITE_TO_FILE);
  455. }
  456. }
  457. void CardReader::checkautostart(bool force) {
  458. if (!force && (!autostart_stilltocheck || ELAPSED(millis(), next_autostart_ms)))
  459. return;
  460. autostart_stilltocheck = false;
  461. if (!cardOK) {
  462. initsd();
  463. if (!cardOK) return; // fail
  464. }
  465. char autoname[10];
  466. sprintf_P(autoname, PSTR("auto%i.g"), autostart_index);
  467. for (int8_t i = 0; i < (int8_t)strlen(autoname); i++) autoname[i] = tolower(autoname[i]);
  468. dir_t p;
  469. root.rewind();
  470. bool found = false;
  471. while (root.readDir(p, NULL) > 0) {
  472. for (int8_t i = (int8_t)strlen((char*)p.name); i--;) p.name[i] = tolower(p.name[i]);
  473. if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
  474. openAndPrintFile(autoname);
  475. found = true;
  476. }
  477. }
  478. if (!found)
  479. autostart_index = -1;
  480. else
  481. autostart_index++;
  482. }
  483. void CardReader::closefile(bool store_location) {
  484. file.sync();
  485. file.close();
  486. saving = logging = false;
  487. if (store_location) {
  488. //future: store printer state, filename and position for continuing a stopped print
  489. // so one can unplug the printer and continue printing the next day.
  490. }
  491. }
  492. /**
  493. * Get the name of a file in the current directory by index
  494. */
  495. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/) {
  496. #if ENABLED(SDSORT_CACHE_NAMES)
  497. if (match != NULL) {
  498. while (nr < sort_count) {
  499. if (strcasecmp(match, sortshort[nr]) == 0) break;
  500. nr++;
  501. }
  502. }
  503. if (nr < sort_count) {
  504. strcpy(filename, sortshort[nr]);
  505. strcpy(longFilename, sortnames[nr]);
  506. filenameIsDir = TEST(isDir[nr>>3], nr & 0x07);
  507. return;
  508. }
  509. #endif // SDSORT_CACHE_NAMES
  510. curDir = &workDir;
  511. lsAction = LS_GetFilename;
  512. nrFiles = nr;
  513. curDir->rewind();
  514. lsDive("", *curDir, match);
  515. }
  516. uint16_t CardReader::getnrfilenames() {
  517. curDir = &workDir;
  518. lsAction = LS_Count;
  519. nrFiles = 0;
  520. curDir->rewind();
  521. lsDive("", *curDir);
  522. //SERIAL_ECHOLN(nrFiles);
  523. return nrFiles;
  524. }
  525. void CardReader::chdir(const char * relpath) {
  526. SdFile newfile;
  527. SdFile *parent = &root;
  528. if (workDir.isOpen()) parent = &workDir;
  529. if (!newfile.open(*parent, relpath, O_READ)) {
  530. SERIAL_ECHO_START();
  531. SERIAL_ECHOPGM(MSG_SD_CANT_ENTER_SUBDIR);
  532. SERIAL_ECHOLN(relpath);
  533. }
  534. else {
  535. if (workDirDepth < MAX_DIR_DEPTH)
  536. workDirParents[workDirDepth++] = *parent;
  537. workDir = newfile;
  538. #if ENABLED(SDCARD_SORT_ALPHA)
  539. presort();
  540. #endif
  541. }
  542. }
  543. void CardReader::updir() {
  544. if (workDirDepth > 0) {
  545. workDir = workDirParents[--workDirDepth];
  546. #if ENABLED(SDCARD_SORT_ALPHA)
  547. presort();
  548. #endif
  549. }
  550. }
  551. #if ENABLED(SDCARD_SORT_ALPHA)
  552. /**
  553. * Get the name of a file in the current directory by sort-index
  554. */
  555. void CardReader::getfilename_sorted(const uint16_t nr) {
  556. getfilename(
  557. #if ENABLED(SDSORT_GCODE)
  558. sort_alpha &&
  559. #endif
  560. (nr < sort_count) ? sort_order[nr] : nr
  561. );
  562. }
  563. /**
  564. * Read all the files and produce a sort key
  565. *
  566. * We can do this in 3 ways...
  567. * - Minimal RAM: Read two filenames at a time sorting along...
  568. * - Some RAM: Buffer the directory just for this sort
  569. * - Most RAM: Buffer the directory and return filenames from RAM
  570. */
  571. void CardReader::presort() {
  572. // Sorting may be turned off
  573. #if ENABLED(SDSORT_GCODE)
  574. if (!sort_alpha) return;
  575. #endif
  576. // Throw away old sort index
  577. flush_presort();
  578. // If there are files, sort up to the limit
  579. uint16_t fileCnt = getnrfilenames();
  580. if (fileCnt > 0) {
  581. // Never sort more than the max allowed
  582. // If you use folders to organize, 20 may be enough
  583. if (fileCnt > SDSORT_LIMIT) fileCnt = SDSORT_LIMIT;
  584. // Sort order is always needed. May be static or dynamic.
  585. #if ENABLED(SDSORT_DYNAMIC_RAM)
  586. sort_order = new uint8_t[fileCnt];
  587. #endif
  588. // Use RAM to store the entire directory during pre-sort.
  589. // SDSORT_LIMIT should be set to prevent over-allocation.
  590. #if ENABLED(SDSORT_USES_RAM)
  591. // If using dynamic ram for names, allocate on the heap.
  592. #if ENABLED(SDSORT_CACHE_NAMES)
  593. #if ENABLED(SDSORT_DYNAMIC_RAM)
  594. sortshort = new char*[fileCnt];
  595. sortnames = new char*[fileCnt];
  596. #endif
  597. #elif ENABLED(SDSORT_USES_STACK)
  598. char sortnames[fileCnt][LONG_FILENAME_LENGTH];
  599. #endif
  600. // Folder sorting needs 1 bit per entry for flags.
  601. #if HAS_FOLDER_SORTING
  602. #if ENABLED(SDSORT_DYNAMIC_RAM)
  603. isDir = new uint8_t[(fileCnt + 7) >> 3];
  604. #elif ENABLED(SDSORT_USES_STACK)
  605. uint8_t isDir[(fileCnt + 7) >> 3];
  606. #endif
  607. #endif
  608. #else // !SDSORT_USES_RAM
  609. // By default re-read the names from SD for every compare
  610. // retaining only two filenames at a time. This is very
  611. // slow but is safest and uses minimal RAM.
  612. char name1[LONG_FILENAME_LENGTH + 1];
  613. #endif
  614. if (fileCnt > 1) {
  615. // Init sort order.
  616. for (uint16_t i = 0; i < fileCnt; i++) {
  617. sort_order[i] = i;
  618. // If using RAM then read all filenames now.
  619. #if ENABLED(SDSORT_USES_RAM)
  620. getfilename(i);
  621. #if ENABLED(SDSORT_DYNAMIC_RAM)
  622. // Use dynamic method to copy long filename
  623. sortnames[i] = strdup(LONGEST_FILENAME);
  624. #if ENABLED(SDSORT_CACHE_NAMES)
  625. // When caching also store the short name, since
  626. // we're replacing the getfilename() behavior.
  627. sortshort[i] = strdup(filename);
  628. #endif
  629. #else
  630. // Copy filenames into the static array
  631. strcpy(sortnames[i], LONGEST_FILENAME);
  632. #if ENABLED(SDSORT_CACHE_NAMES)
  633. strcpy(sortshort[i], filename);
  634. #endif
  635. #endif
  636. // char out[30];
  637. // sprintf_P(out, PSTR("---- %i %s %s"), i, filenameIsDir ? "D" : " ", sortnames[i]);
  638. // SERIAL_ECHOLN(out);
  639. #if HAS_FOLDER_SORTING
  640. const uint16_t bit = i & 0x07, ind = i >> 3;
  641. if (bit == 0) isDir[ind] = 0x00;
  642. if (filenameIsDir) isDir[ind] |= _BV(bit);
  643. #endif
  644. #endif
  645. }
  646. // Bubble Sort
  647. for (uint16_t i = fileCnt; --i;) {
  648. bool didSwap = false;
  649. for (uint16_t j = 0; j < i; ++j) {
  650. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  651. // Compare names from the array or just the two buffered names
  652. #if ENABLED(SDSORT_USES_RAM)
  653. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  654. #else
  655. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  656. #endif
  657. #if HAS_FOLDER_SORTING
  658. #if ENABLED(SDSORT_USES_RAM)
  659. // Folder sorting needs an index and bit to test for folder-ness.
  660. const uint8_t ind1 = o1 >> 3, bit1 = o1 & 0x07,
  661. ind2 = o2 >> 3, bit2 = o2 & 0x07;
  662. #define _SORT_CMP_DIR(fs) \
  663. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  664. ? _SORT_CMP_NODIR() \
  665. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  666. #else
  667. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  668. #endif
  669. #endif
  670. // The most economical method reads names as-needed
  671. // throughout the loop. Slow if there are many.
  672. #if DISABLED(SDSORT_USES_RAM)
  673. getfilename(o1);
  674. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  675. #if HAS_FOLDER_SORTING
  676. bool dir1 = filenameIsDir;
  677. #endif
  678. getfilename(o2);
  679. char *name2 = LONGEST_FILENAME; // use the string in-place
  680. #endif // !SDSORT_USES_RAM
  681. // Sort the current pair according to settings.
  682. if (
  683. #if HAS_FOLDER_SORTING
  684. #if ENABLED(SDSORT_GCODE)
  685. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  686. #else
  687. _SORT_CMP_DIR(FOLDER_SORTING)
  688. #endif
  689. #else
  690. _SORT_CMP_NODIR()
  691. #endif
  692. ) {
  693. sort_order[j] = o2;
  694. sort_order[j + 1] = o1;
  695. didSwap = true;
  696. }
  697. }
  698. if (!didSwap) break;
  699. }
  700. // Using RAM but not keeping names around
  701. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  702. #if ENABLED(SDSORT_DYNAMIC_RAM)
  703. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  704. #if HAS_FOLDER_SORTING
  705. free(isDir);
  706. #endif
  707. #endif
  708. #endif
  709. }
  710. else {
  711. sort_order[0] = 0;
  712. #if ENABLED(SDSORT_USES_RAM) && ENABLED(SDSORT_CACHE_NAMES)
  713. getfilename(0);
  714. #if ENABLED(SDSORT_DYNAMIC_RAM)
  715. sortnames = new char*[1];
  716. sortnames[0] = strdup(LONGEST_FILENAME); // malloc
  717. sortshort = new char*[1];
  718. sortshort[0] = strdup(filename); // malloc
  719. isDir = new uint8_t[1];
  720. #else
  721. strcpy(sortnames[0], LONGEST_FILENAME);
  722. strcpy(sortshort[0], filename);
  723. #endif
  724. isDir[0] = filenameIsDir ? 0x01 : 0x00;
  725. #endif
  726. }
  727. sort_count = fileCnt;
  728. }
  729. }
  730. void CardReader::flush_presort() {
  731. if (sort_count > 0) {
  732. #if ENABLED(SDSORT_DYNAMIC_RAM)
  733. delete sort_order;
  734. #if ENABLED(SDSORT_CACHE_NAMES)
  735. for (uint8_t i = 0; i < sort_count; ++i) {
  736. free(sortshort[i]); // strdup
  737. free(sortnames[i]); // strdup
  738. }
  739. delete sortshort;
  740. delete sortnames;
  741. #endif
  742. #endif
  743. sort_count = 0;
  744. }
  745. }
  746. #endif // SDCARD_SORT_ALPHA
  747. void CardReader::printingHasFinished() {
  748. stepper.synchronize();
  749. file.close();
  750. if (file_subcall_ctr > 0) { // Heading up to a parent file that called current as a procedure.
  751. file_subcall_ctr--;
  752. openFile(proc_filenames[file_subcall_ctr], true, true);
  753. setIndex(filespos[file_subcall_ctr]);
  754. startFileprint();
  755. }
  756. else {
  757. sdprinting = false;
  758. if (SD_FINISHED_STEPPERRELEASE)
  759. enqueue_and_echo_commands_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  760. print_job_timer.stop();
  761. if (print_job_timer.duration() > 60)
  762. enqueue_and_echo_commands_P(PSTR("M31"));
  763. #if ENABLED(SDCARD_SORT_ALPHA)
  764. presort();
  765. #endif
  766. }
  767. }
  768. #endif // SDSUPPORT