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

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