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

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