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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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.mounted = 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.getDosName(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::mount() {
  264. flag.mounted = 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.mounted = 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.mounted = 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 (isMounted()) {
  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.getDosName(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 (!isMounted()) 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 (!isMounted()) 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 (!isMounted()) mount();
  459. #if ENABLED(EEPROM_SETTINGS) && NONE(FLASH_EEPROM_EMULATION, SPI_EEPROM, I2C_EEPROM)
  460. else settings.first_load();
  461. #endif
  462. if (isMounted()
  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::countFilesInWorkDir() {
  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. flag.workDirIsRoot = false;
  588. if (workDirDepth < MAX_DIR_DEPTH)
  589. workDirParents[workDirDepth++] = workDir;
  590. #if ENABLED(SDCARD_SORT_ALPHA)
  591. presort();
  592. #endif
  593. }
  594. else {
  595. SERIAL_ECHO_START();
  596. SERIAL_ECHOLNPAIR(MSG_SD_CANT_ENTER_SUBDIR, relpath);
  597. }
  598. }
  599. int8_t CardReader::updir() {
  600. if (workDirDepth > 0) { // At least 1 dir has been saved
  601. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  602. #if ENABLED(SDCARD_SORT_ALPHA)
  603. presort();
  604. #endif
  605. }
  606. if (!workDirDepth) flag.workDirIsRoot = true;
  607. return workDirDepth;
  608. }
  609. void CardReader::setroot() {
  610. workDir = root;
  611. flag.workDirIsRoot = true;
  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 = countFilesInWorkDir();
  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. countFilesInWorkDir()
  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. bool CardReader::jobRecoverFileExists() {
  884. const bool exists = recovery.file.open(&root, recovery.filename, O_READ);
  885. if (exists) recovery.file.close();
  886. return exists;
  887. }
  888. void CardReader::openJobRecoveryFile(const bool read) {
  889. if (!isMounted()) return;
  890. if (recovery.file.isOpen()) return;
  891. if (!recovery.file.open(&root, recovery.filename, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC))
  892. SERIAL_ECHOLNPAIR(MSG_SD_OPEN_FILE_FAIL, recovery.filename, ".");
  893. else if (!read)
  894. SERIAL_ECHOLNPAIR(MSG_SD_WRITE_TO_FILE, recovery.filename);
  895. }
  896. // Removing the job recovery file currently requires closing
  897. // the file being printed, so during SD printing the file should
  898. // be zeroed and written instead of deleted.
  899. void CardReader::removeJobRecoveryFile() {
  900. if (jobRecoverFileExists()) {
  901. recovery.init();
  902. removeFile(recovery.filename);
  903. #if ENABLED(DEBUG_POWER_LOSS_RECOVERY)
  904. SERIAL_ECHOPGM("Power-loss file delete");
  905. serialprintPGM(jobRecoverFileExists() ? PSTR(" failed.\n") : PSTR("d.\n"));
  906. #endif
  907. }
  908. }
  909. #endif // POWER_LOSS_RECOVERY
  910. #endif // SDSUPPORT