cardreader.cpp 26 KB

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