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

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