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

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