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

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