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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. #include "../module/configuration_store.h"
  32. #if ENABLED(EMERGENCY_PARSER)
  33. #include "../feature/emergency_parser.h"
  34. #endif
  35. #if ENABLED(POWER_LOSS_RECOVERY)
  36. #include "../feature/power_loss_recovery.h"
  37. #endif
  38. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  39. #include "../feature/pause.h"
  40. #endif
  41. // public:
  42. card_flags_t CardReader::flag;
  43. char CardReader::filename[FILENAME_LENGTH], CardReader::longFilename[LONG_FILENAME_LENGTH];
  44. int8_t CardReader::autostart_index;
  45. #if ENABLED(BINARY_FILE_TRANSFER) && NUM_SERIAL > 1
  46. int8_t CardReader::transfer_port_index;
  47. #endif
  48. // private:
  49. SdFile CardReader::root, CardReader::workDir, CardReader::workDirParents[MAX_DIR_DEPTH];
  50. uint8_t CardReader::workDirDepth;
  51. #if ENABLED(SDCARD_SORT_ALPHA)
  52. uint16_t CardReader::sort_count;
  53. #if ENABLED(SDSORT_GCODE)
  54. bool CardReader::sort_alpha;
  55. int CardReader::sort_folders;
  56. //bool CardReader::sort_reverse;
  57. #endif
  58. #if ENABLED(SDSORT_DYNAMIC_RAM)
  59. uint8_t *CardReader::sort_order;
  60. #else
  61. uint8_t CardReader::sort_order[SDSORT_LIMIT];
  62. #endif
  63. #if ENABLED(SDSORT_USES_RAM)
  64. #if ENABLED(SDSORT_CACHE_NAMES)
  65. #if ENABLED(SDSORT_DYNAMIC_RAM)
  66. char **CardReader::sortshort, **CardReader::sortnames;
  67. #else
  68. char CardReader::sortshort[SDSORT_LIMIT][FILENAME_LENGTH];
  69. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  70. #endif
  71. #elif DISABLED(SDSORT_USES_STACK)
  72. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  73. #endif
  74. #if HAS_FOLDER_SORTING
  75. #if ENABLED(SDSORT_DYNAMIC_RAM)
  76. uint8_t *CardReader::isDir;
  77. #elif ENABLED(SDSORT_CACHE_NAMES) || DISABLED(SDSORT_USES_STACK)
  78. uint8_t CardReader::isDir[(SDSORT_LIMIT+7)>>3];
  79. #endif
  80. #endif
  81. #endif // SDSORT_USES_RAM
  82. #endif // SDCARD_SORT_ALPHA
  83. Sd2Card CardReader::sd2card;
  84. SdVolume CardReader::volume;
  85. SdFile CardReader::file;
  86. uint8_t CardReader::file_subcall_ctr;
  87. uint32_t CardReader::filespos[SD_PROCEDURE_DEPTH];
  88. char CardReader::proc_filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH];
  89. uint32_t CardReader::filesize, CardReader::sdpos;
  90. LsAction CardReader::lsAction; //stored for recursion.
  91. 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.
  92. char *CardReader::diveDirName;
  93. CardReader::CardReader() {
  94. #if ENABLED(SDCARD_SORT_ALPHA)
  95. sort_count = 0;
  96. #if ENABLED(SDSORT_GCODE)
  97. sort_alpha = true;
  98. sort_folders = FOLDER_SORTING;
  99. //sort_reverse = false;
  100. #endif
  101. #endif
  102. flag.sdprinting = flag.detected = flag.saving = flag.logging = false;
  103. filesize = sdpos = 0;
  104. file_subcall_ctr = 0;
  105. workDirDepth = 0;
  106. ZERO(workDirParents);
  107. // Disable autostart until card is initialized
  108. autostart_index = -1;
  109. #if PIN_EXISTS(SDPOWER)
  110. OUT_WRITE(SDPOWER_PIN, HIGH); // Power the SD reader
  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/*=nullptr*/) {
  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 != nullptr) {
  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(nullptr, 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(nullptr, 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. #if ENABLED(EEPROM_SETTINGS) && NONE(FLASH_EEPROM_EMULATION, SPI_EEPROM, I2C_EEPROM)
  285. settings.first_load();
  286. #endif
  287. }
  288. setroot();
  289. ui.refresh();
  290. }
  291. void CardReader::release() {
  292. stopSDPrint();
  293. flag.detected = false;
  294. }
  295. void CardReader::openAndPrintFile(const char *name) {
  296. char cmd[4 + strlen(name) + 1]; // Room for "M23 ", filename, and null
  297. sprintf_P(cmd, PSTR("M23 %s"), name);
  298. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  299. queue.enqueue_one_now(cmd);
  300. queue.enqueue_now_P(PSTR("M24"));
  301. }
  302. void CardReader::startFileprint() {
  303. if (isDetected()) {
  304. flag.sdprinting = true;
  305. #if SD_RESORT
  306. flush_presort();
  307. #endif
  308. }
  309. }
  310. void CardReader::stopSDPrint(
  311. #if SD_RESORT
  312. const bool re_sort/*=false*/
  313. #endif
  314. ) {
  315. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  316. did_pause_print = 0;
  317. #endif
  318. flag.sdprinting = flag.abort_sd_printing = false;
  319. if (isFileOpen()) file.close();
  320. #if SD_RESORT
  321. if (re_sort) presort();
  322. #endif
  323. }
  324. void CardReader::openLogFile(char * const path) {
  325. flag.logging = true;
  326. openFile(path, false);
  327. }
  328. void appendAtom(SdFile &file, char *& dst, uint8_t &cnt) {
  329. file.getFilename(dst);
  330. while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; }
  331. if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; }
  332. }
  333. void CardReader::getAbsFilename(char *t) {
  334. *t++ = '/'; // Root folder
  335. uint8_t cnt = 1;
  336. for (uint8_t i = 0; i < workDirDepth; i++) // Loop to current work dir
  337. appendAtom(workDirParents[i], t, cnt);
  338. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH) - 1) { // Leave room for filename and nul
  339. appendAtom(file, t, cnt);
  340. --t;
  341. }
  342. *t = '\0';
  343. }
  344. void CardReader::openFile(char * const path, const bool read, const bool subcall/*=false*/) {
  345. if (!isDetected()) return;
  346. uint8_t doing = 0;
  347. if (isFileOpen()) { // Replacing current file or doing a subroutine
  348. if (subcall) {
  349. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  350. SERIAL_ERROR_MSG("trying to call sub-gcode files with too many levels. MAX level is:" STRINGIFY(SD_PROCEDURE_DEPTH));
  351. kill();
  352. return;
  353. }
  354. // Store current filename (based on workDirParents) and position
  355. getAbsFilename(proc_filenames[file_subcall_ctr]);
  356. filespos[file_subcall_ctr] = sdpos;
  357. SERIAL_ECHO_START();
  358. SERIAL_ECHOLNPAIR("SUBROUTINE CALL target:\"", path, "\" parent:\"", proc_filenames[file_subcall_ctr], "\" pos", sdpos);
  359. file_subcall_ctr++;
  360. }
  361. else
  362. doing = 1;
  363. }
  364. else if (subcall) // Returning from a subcall?
  365. SERIAL_ECHO_MSG("END SUBROUTINE");
  366. else { // Opening fresh file
  367. doing = 2;
  368. file_subcall_ctr = 0; // Reset procedure depth in case user cancels print while in procedure
  369. }
  370. if (doing) {
  371. SERIAL_ECHO_START();
  372. SERIAL_ECHOPGM("Now ");
  373. serialprintPGM(doing == 1 ? PSTR("doing") : PSTR("fresh"));
  374. SERIAL_ECHOLNPAIR(" file: ", path);
  375. }
  376. stopSDPrint();
  377. SdFile *curDir;
  378. const char * const fname = diveToFile(curDir, path);
  379. if (!fname) return;
  380. if (read) {
  381. if (file.open(curDir, fname, O_READ)) {
  382. filesize = file.fileSize();
  383. sdpos = 0;
  384. SERIAL_ECHOLNPAIR(MSG_SD_FILE_OPENED, fname, MSG_SD_SIZE, filesize);
  385. SERIAL_ECHOLNPGM(MSG_SD_FILE_SELECTED);
  386. getfilename(0, fname);
  387. ui.set_status(longFilename[0] ? longFilename : fname);
  388. //if (longFilename[0]) {
  389. // SERIAL_ECHOPAIR(MSG_SD_FILE_LONG_NAME, longFilename);
  390. //}
  391. }
  392. else
  393. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, fname, ".");
  394. }
  395. else { //write
  396. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC))
  397. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, fname, ".");
  398. else {
  399. flag.saving = true;
  400. getfilename(0, fname);
  401. #if ENABLED(EMERGENCY_PARSER)
  402. emergency_parser.disable();
  403. #endif
  404. SERIAL_ECHOLNPAIR(MSG_SD_WRITE_TO_FILE, fname);
  405. ui.set_status(fname);
  406. }
  407. }
  408. }
  409. void CardReader::removeFile(const char * const name) {
  410. if (!isDetected()) return;
  411. //stopSDPrint();
  412. SdFile *curDir;
  413. const char * const fname = diveToFile(curDir, name);
  414. if (!fname) return;
  415. if (file.remove(curDir, fname)) {
  416. SERIAL_ECHOLNPAIR("File deleted:", fname);
  417. sdpos = 0;
  418. #if ENABLED(SDCARD_SORT_ALPHA)
  419. presort();
  420. #endif
  421. }
  422. else
  423. SERIAL_ECHOLNPAIR("Deletion failed, File: ", fname, ".");
  424. }
  425. void CardReader::report_status() {
  426. if (isPrinting()) {
  427. SERIAL_ECHOPGM(MSG_SD_PRINTING_BYTE);
  428. SERIAL_ECHO(sdpos);
  429. SERIAL_CHAR('/');
  430. SERIAL_ECHOLN(filesize);
  431. }
  432. else
  433. SERIAL_ECHOLNPGM(MSG_SD_NOT_PRINTING);
  434. }
  435. void CardReader::write_command(char *buf) {
  436. char* begin = buf;
  437. char* npos = nullptr;
  438. char* end = buf + strlen(buf) - 1;
  439. file.writeError = false;
  440. if ((npos = strchr(buf, 'N')) != nullptr) {
  441. begin = strchr(npos, ' ') + 1;
  442. end = strchr(npos, '*') - 1;
  443. }
  444. end[1] = '\r';
  445. end[2] = '\n';
  446. end[3] = '\0';
  447. file.write(begin);
  448. if (file.writeError) SERIAL_ERROR_MSG(MSG_SD_ERR_WRITE_TO_FILE);
  449. }
  450. //
  451. // Run the next autostart file. Called:
  452. // - On boot after successful card init
  453. // - After finishing the previous autostart file
  454. // - From the LCD command to run the autostart file
  455. //
  456. void CardReader::checkautostart() {
  457. if (autostart_index < 0 || flag.sdprinting) return;
  458. if (!isDetected()) initsd();
  459. #if ENABLED(EEPROM_SETTINGS) && NONE(FLASH_EEPROM_EMULATION, SPI_EEPROM, I2C_EEPROM)
  460. else settings.first_load();
  461. #endif
  462. if (isDetected()
  463. #if ENABLED(POWER_LOSS_RECOVERY)
  464. && !recovery.valid() // Don't run auto#.g when a resume file exists
  465. #endif
  466. ) {
  467. char autoname[8];
  468. sprintf_P(autoname, PSTR("auto%c.g"), autostart_index + '0');
  469. dir_t p;
  470. root.rewind();
  471. while (root.readDir(&p, nullptr) > 0) {
  472. for (int8_t i = (int8_t)strlen((char*)p.name); i--;) p.name[i] = tolower(p.name[i]);
  473. if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
  474. openAndPrintFile(autoname);
  475. autostart_index++;
  476. return;
  477. }
  478. }
  479. }
  480. autostart_index = -1;
  481. }
  482. void CardReader::beginautostart() {
  483. autostart_index = 0;
  484. setroot();
  485. }
  486. void CardReader::closefile(const bool store_location) {
  487. file.sync();
  488. file.close();
  489. flag.saving = flag.logging = false;
  490. sdpos = 0;
  491. #if ENABLED(EMERGENCY_PARSER)
  492. emergency_parser.enable();
  493. #endif
  494. if (store_location) {
  495. //future: store printer state, filename and position for continuing a stopped print
  496. // so one can unplug the printer and continue printing the next day.
  497. }
  498. }
  499. /**
  500. * Get the name of a file in the current directory by index
  501. * with optional name to match.
  502. */
  503. void CardReader::getfilename(uint16_t nr, const char * const match/*=nullptr*/) {
  504. #if ENABLED(SDSORT_CACHE_NAMES)
  505. if (match != nullptr) {
  506. while (nr < sort_count) {
  507. if (strcasecmp(match, sortshort[nr]) == 0) break;
  508. nr++;
  509. }
  510. }
  511. if (nr < sort_count) {
  512. strcpy(filename, sortshort[nr]);
  513. strcpy(longFilename, sortnames[nr]);
  514. flag.filenameIsDir = TEST(isDir[nr>>3], nr & 0x07);
  515. return;
  516. }
  517. #endif // SDSORT_CACHE_NAMES
  518. lsAction = LS_GetFilename;
  519. nrFile_index = nr;
  520. workDir.rewind();
  521. lsDive(nullptr, workDir, match);
  522. }
  523. uint16_t CardReader::getnrfilenames() {
  524. lsAction = LS_Count;
  525. nrFiles = 0;
  526. workDir.rewind();
  527. lsDive(nullptr, workDir);
  528. //SERIAL_ECHOLN(nrFiles);
  529. return nrFiles;
  530. }
  531. /**
  532. * Dive to the given DOS 8.3 file path, with optional echo of the dive paths.
  533. *
  534. * On exit, curDir contains an SdFile reference to the file's directory.
  535. *
  536. * Returns a pointer to the last segment (filename) of the given DOS 8.3 path.
  537. *
  538. * A nullptr result indicates an unrecoverable error.
  539. */
  540. const char* CardReader::diveToFile(SdFile*& curDir, const char * const path, const bool echo/*=false*/) {
  541. // Track both parent and subfolder
  542. static SdFile newDir1, newDir2;
  543. SdFile *sub = &newDir1, *startDir;
  544. const char *dirname_start = path;
  545. if (path[0] == '/') {
  546. curDir = &root;
  547. workDirDepth = 0;
  548. dirname_start++;
  549. }
  550. else
  551. curDir = &workDir;
  552. startDir = curDir;
  553. // Start dive
  554. while (dirname_start) {
  555. // Find next sub
  556. char * const dirname_end = strchr(dirname_start, '/');
  557. if (dirname_end <= dirname_start) break;
  558. // Set subDirName
  559. const uint8_t len = dirname_end - dirname_start;
  560. char dosSubdirname[len + 1];
  561. strncpy(dosSubdirname, dirname_start, len);
  562. dosSubdirname[len] = 0;
  563. if (echo) SERIAL_ECHOLN(dosSubdirname);
  564. // Open curDir
  565. if (!sub->open(curDir, dosSubdirname, O_READ)) {
  566. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, dosSubdirname, ".");
  567. return nullptr;
  568. }
  569. // Close curDir if not at starting-point
  570. if (curDir != startDir) curDir->close();
  571. // curDir now subDir
  572. curDir = sub;
  573. // Update workDirParents and workDirDepth
  574. if (workDirDepth < MAX_DIR_DEPTH) workDirParents[workDirDepth++] = *curDir;
  575. // Point sub pointer to unused newDir
  576. sub = (curDir != &newDir1) ? &newDir1 : &newDir2;
  577. // dirname_start point to next sub
  578. dirname_start = dirname_end + 1;
  579. }
  580. return dirname_start;
  581. }
  582. void CardReader::chdir(const char * relpath) {
  583. SdFile newDir;
  584. SdFile *parent = workDir.isOpen() ? &workDir : &root;
  585. if (newDir.open(parent, relpath, O_READ)) {
  586. workDir = newDir;
  587. if (workDirDepth < MAX_DIR_DEPTH)
  588. workDirParents[workDirDepth++] = workDir;
  589. #if ENABLED(SDCARD_SORT_ALPHA)
  590. presort();
  591. #endif
  592. }
  593. else {
  594. SERIAL_ECHO_START();
  595. SERIAL_ECHOLNPAIR(MSG_SD_CANT_ENTER_SUBDIR, relpath);
  596. }
  597. }
  598. int8_t CardReader::updir() {
  599. if (workDirDepth > 0) { // At least 1 dir has been saved
  600. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  601. #if ENABLED(SDCARD_SORT_ALPHA)
  602. presort();
  603. #endif
  604. }
  605. return workDirDepth;
  606. }
  607. void CardReader::setroot() {
  608. /*if (!workDir.openRoot(&volume)) {
  609. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  610. }*/
  611. workDir = root;
  612. #if ENABLED(SDCARD_SORT_ALPHA)
  613. presort();
  614. #endif
  615. }
  616. #if ENABLED(SDCARD_SORT_ALPHA)
  617. /**
  618. * Get the name of a file in the current directory by sort-index
  619. */
  620. void CardReader::getfilename_sorted(const uint16_t nr) {
  621. getfilename(
  622. #if ENABLED(SDSORT_GCODE)
  623. sort_alpha &&
  624. #endif
  625. (nr < sort_count) ? sort_order[nr] : nr
  626. );
  627. }
  628. #if ENABLED(SDSORT_USES_RAM)
  629. #if ENABLED(SDSORT_DYNAMIC_RAM)
  630. // Use dynamic method to copy long filename
  631. #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename()))
  632. #if ENABLED(SDSORT_CACHE_NAMES)
  633. // When caching also store the short name, since
  634. // we're replacing the getfilename() behavior.
  635. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename))
  636. #else
  637. #define SET_SORTSHORT(I) NOOP
  638. #endif
  639. #else
  640. // Copy filenames into the static array
  641. #define _SET_SORTNAME(I) strncpy(sortnames[I], longest_filename(), SORTED_LONGNAME_MAXLEN)
  642. #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH
  643. // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul
  644. #define SET_SORTNAME(I) _SET_SORTNAME(I)
  645. #else
  646. // Copy multiple name blocks. Add a nul for the longest case.
  647. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0)
  648. #endif
  649. #if ENABLED(SDSORT_CACHE_NAMES)
  650. #define SET_SORTSHORT(I) strcpy(sortshort[I], filename)
  651. #else
  652. #define SET_SORTSHORT(I) NOOP
  653. #endif
  654. #endif
  655. #endif
  656. /**
  657. * Read all the files and produce a sort key
  658. *
  659. * We can do this in 3 ways...
  660. * - Minimal RAM: Read two filenames at a time sorting along...
  661. * - Some RAM: Buffer the directory just for this sort
  662. * - Most RAM: Buffer the directory and return filenames from RAM
  663. */
  664. void CardReader::presort() {
  665. // Throw away old sort index
  666. flush_presort();
  667. // Sorting may be turned off
  668. #if ENABLED(SDSORT_GCODE)
  669. if (!sort_alpha) return;
  670. #endif
  671. // If there are files, sort up to the limit
  672. uint16_t fileCnt = getnrfilenames();
  673. if (fileCnt > 0) {
  674. // Never sort more than the max allowed
  675. // If you use folders to organize, 20 may be enough
  676. NOMORE(fileCnt, uint16_t(SDSORT_LIMIT));
  677. // Sort order is always needed. May be static or dynamic.
  678. #if ENABLED(SDSORT_DYNAMIC_RAM)
  679. sort_order = new uint8_t[fileCnt];
  680. #endif
  681. // Use RAM to store the entire directory during pre-sort.
  682. // SDSORT_LIMIT should be set to prevent over-allocation.
  683. #if ENABLED(SDSORT_USES_RAM)
  684. // If using dynamic ram for names, allocate on the heap.
  685. #if ENABLED(SDSORT_CACHE_NAMES)
  686. #if ENABLED(SDSORT_DYNAMIC_RAM)
  687. sortshort = new char*[fileCnt];
  688. sortnames = new char*[fileCnt];
  689. #endif
  690. #elif ENABLED(SDSORT_USES_STACK)
  691. char sortnames[fileCnt][SORTED_LONGNAME_STORAGE];
  692. #endif
  693. // Folder sorting needs 1 bit per entry for flags.
  694. #if HAS_FOLDER_SORTING
  695. #if ENABLED(SDSORT_DYNAMIC_RAM)
  696. isDir = new uint8_t[(fileCnt + 7) >> 3];
  697. #elif ENABLED(SDSORT_USES_STACK)
  698. uint8_t isDir[(fileCnt + 7) >> 3];
  699. #endif
  700. #endif
  701. #else // !SDSORT_USES_RAM
  702. // By default re-read the names from SD for every compare
  703. // retaining only two filenames at a time. This is very
  704. // slow but is safest and uses minimal RAM.
  705. char name1[LONG_FILENAME_LENGTH];
  706. #endif
  707. if (fileCnt > 1) {
  708. // Init sort order.
  709. for (uint16_t i = 0; i < fileCnt; i++) {
  710. sort_order[i] = (
  711. #if ENABLED(SDCARD_RATHERRECENTFIRST)
  712. fileCnt - 1 -
  713. #endif
  714. i);
  715. // If using RAM then read all filenames now.
  716. #if ENABLED(SDSORT_USES_RAM)
  717. getfilename(i);
  718. SET_SORTNAME(i);
  719. SET_SORTSHORT(i);
  720. // char out[30];
  721. // sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]);
  722. // SERIAL_ECHOLN(out);
  723. #if HAS_FOLDER_SORTING
  724. const uint16_t bit = i & 0x07, ind = i >> 3;
  725. if (bit == 0) isDir[ind] = 0x00;
  726. if (flag.filenameIsDir) isDir[ind] |= _BV(bit);
  727. #endif
  728. #endif
  729. }
  730. // Bubble Sort
  731. for (uint16_t i = fileCnt; --i;) {
  732. bool didSwap = false;
  733. for (uint16_t j = 0; j < i; ++j) {
  734. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  735. // Compare names from the array or just the two buffered names
  736. #if ENABLED(SDSORT_USES_RAM)
  737. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  738. #else
  739. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  740. #endif
  741. #if HAS_FOLDER_SORTING
  742. #if ENABLED(SDSORT_USES_RAM)
  743. // Folder sorting needs an index and bit to test for folder-ness.
  744. const uint8_t ind1 = o1 >> 3, bit1 = o1 & 0x07,
  745. ind2 = o2 >> 3, bit2 = o2 & 0x07;
  746. #define _SORT_CMP_DIR(fs) \
  747. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  748. ? _SORT_CMP_NODIR() \
  749. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  750. #else
  751. #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  752. #endif
  753. #endif
  754. // The most economical method reads names as-needed
  755. // throughout the loop. Slow if there are many.
  756. #if DISABLED(SDSORT_USES_RAM)
  757. getfilename(o1);
  758. strcpy(name1, longest_filename()); // save (or getfilename below will trounce it)
  759. #if HAS_FOLDER_SORTING
  760. bool dir1 = flag.filenameIsDir;
  761. #endif
  762. getfilename(o2);
  763. char *name2 = longest_filename(); // use the string in-place
  764. #endif // !SDSORT_USES_RAM
  765. // Sort the current pair according to settings.
  766. if (
  767. #if HAS_FOLDER_SORTING
  768. #if ENABLED(SDSORT_GCODE)
  769. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  770. #else
  771. _SORT_CMP_DIR(FOLDER_SORTING)
  772. #endif
  773. #else
  774. _SORT_CMP_NODIR()
  775. #endif
  776. ) {
  777. sort_order[j] = o2;
  778. sort_order[j + 1] = o1;
  779. didSwap = true;
  780. }
  781. }
  782. if (!didSwap) break;
  783. }
  784. // Using RAM but not keeping names around
  785. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  786. #if ENABLED(SDSORT_DYNAMIC_RAM)
  787. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  788. #if HAS_FOLDER_SORTING
  789. free(isDir);
  790. #endif
  791. #endif
  792. #endif
  793. }
  794. else {
  795. sort_order[0] = 0;
  796. #if BOTH(SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  797. #if ENABLED(SDSORT_DYNAMIC_RAM)
  798. sortnames = new char*[1];
  799. sortshort = new char*[1];
  800. isDir = new uint8_t[1];
  801. #endif
  802. getfilename(0);
  803. SET_SORTNAME(0);
  804. SET_SORTSHORT(0);
  805. isDir[0] = flag.filenameIsDir ? 0x01 : 0x00;
  806. #endif
  807. }
  808. sort_count = fileCnt;
  809. }
  810. }
  811. void CardReader::flush_presort() {
  812. if (sort_count > 0) {
  813. #if ENABLED(SDSORT_DYNAMIC_RAM)
  814. delete sort_order;
  815. #if ENABLED(SDSORT_CACHE_NAMES)
  816. for (uint8_t i = 0; i < sort_count; ++i) {
  817. free(sortshort[i]); // strdup
  818. free(sortnames[i]); // strdup
  819. }
  820. delete sortshort;
  821. delete sortnames;
  822. #endif
  823. #endif
  824. sort_count = 0;
  825. }
  826. }
  827. #endif // SDCARD_SORT_ALPHA
  828. uint16_t CardReader::get_num_Files() {
  829. return
  830. #if ENABLED(SDCARD_SORT_ALPHA) && SDSORT_USES_RAM && SDSORT_CACHE_NAMES
  831. nrFiles // no need to access the SD card for filenames
  832. #else
  833. getnrfilenames()
  834. #endif
  835. ;
  836. }
  837. void CardReader::printingHasFinished() {
  838. planner.synchronize();
  839. file.close();
  840. if (file_subcall_ctr > 0) { // Heading up to a parent file that called current as a procedure.
  841. file_subcall_ctr--;
  842. openFile(proc_filenames[file_subcall_ctr], true, true);
  843. setIndex(filespos[file_subcall_ctr]);
  844. startFileprint();
  845. }
  846. else {
  847. stopSDPrint();
  848. #if ENABLED(POWER_LOSS_RECOVERY)
  849. removeJobRecoveryFile();
  850. #endif
  851. #if ENABLED(SD_FINISHED_STEPPERRELEASE) && defined(SD_FINISHED_RELEASECOMMAND)
  852. planner.finish_and_disable();
  853. #endif
  854. print_job_timer.stop();
  855. queue.enqueue_now_P(print_job_timer.duration() > 60 ? PSTR("M31") : PSTR("M117"));
  856. #if ENABLED(SDCARD_SORT_ALPHA)
  857. presort();
  858. #endif
  859. #if ENABLED(LCD_SET_PROGRESS_MANUALLY)
  860. ui.set_progress_done();
  861. #endif
  862. #if ENABLED(SD_REPRINT_LAST_SELECTED_FILE)
  863. ui.reselect_last_file();
  864. #endif
  865. }
  866. }
  867. #if ENABLED(AUTO_REPORT_SD_STATUS)
  868. uint8_t CardReader::auto_report_sd_interval = 0;
  869. millis_t CardReader::next_sd_report_ms;
  870. #if NUM_SERIAL > 1
  871. int8_t CardReader::auto_report_port;
  872. #endif
  873. void CardReader::auto_report_sd_status() {
  874. millis_t current_ms = millis();
  875. if (auto_report_sd_interval && ELAPSED(current_ms, next_sd_report_ms)) {
  876. next_sd_report_ms = current_ms + 1000UL * auto_report_sd_interval;
  877. PORT_REDIRECT(auto_report_port);
  878. report_status();
  879. }
  880. }
  881. #endif // AUTO_REPORT_SD_STATUS
  882. #if ENABLED(POWER_LOSS_RECOVERY)
  883. constexpr char job_recovery_file_name[5] = "/PLR";
  884. bool CardReader::jobRecoverFileExists() {
  885. const bool exists = recovery.file.open(&root, job_recovery_file_name, O_READ);
  886. if (exists) recovery.file.close();
  887. return exists;
  888. }
  889. void CardReader::openJobRecoveryFile(const bool read) {
  890. if (!isDetected()) return;
  891. if (recovery.file.isOpen()) return;
  892. if (!recovery.file.open(&root, job_recovery_file_name, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC))
  893. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, job_recovery_file_name, ".");
  894. else if (!read)
  895. SERIAL_ECHOLNPAIR(MSG_SD_WRITE_TO_FILE, job_recovery_file_name);
  896. }
  897. // Removing the job recovery file currently requires closing
  898. // the file being printed, so during SD printing the file should
  899. // be zeroed and written instead of deleted.
  900. void CardReader::removeJobRecoveryFile() {
  901. if (jobRecoverFileExists()) {
  902. recovery.init();
  903. removeFile(job_recovery_file_name);
  904. #if ENABLED(DEBUG_POWER_LOSS_RECOVERY)
  905. SERIAL_ECHOPGM("Power-loss file delete");
  906. serialprintPGM(jobRecoverFileExists() ? PSTR(" failed.\n") : PSTR("d.\n"));
  907. #endif
  908. }
  909. }
  910. #endif // POWER_LOSS_RECOVERY
  911. #endif // SDSUPPORT