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

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