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 29KB

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