My Marlin configs for Fabrikator Mini and CTC i3 Pro B
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

cardreader.cpp 33KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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 "../gcode/queue.h"
  30. #include "../module/configuration_store.h"
  31. #if ENABLED(EMERGENCY_PARSER)
  32. #include "../feature/e_parser.h"
  33. #endif
  34. #if ENABLED(POWER_LOSS_RECOVERY)
  35. #include "../feature/powerloss.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(BINARY_FILE_TRANSFER) && NUM_SERIAL > 1
  45. int8_t CardReader::transfer_port_index;
  46. #endif
  47. // private:
  48. SdFile CardReader::root, CardReader::workDir, CardReader::workDirParents[MAX_DIR_DEPTH];
  49. uint8_t CardReader::workDirDepth;
  50. #if ENABLED(SDCARD_SORT_ALPHA)
  51. uint16_t CardReader::sort_count;
  52. #if ENABLED(SDSORT_GCODE)
  53. bool CardReader::sort_alpha;
  54. int CardReader::sort_folders;
  55. //bool CardReader::sort_reverse;
  56. #endif
  57. #if ENABLED(SDSORT_DYNAMIC_RAM)
  58. uint8_t *CardReader::sort_order;
  59. #else
  60. uint8_t CardReader::sort_order[SDSORT_LIMIT];
  61. #endif
  62. #if ENABLED(SDSORT_USES_RAM)
  63. #if ENABLED(SDSORT_CACHE_NAMES)
  64. uint16_t CardReader::nrFiles; // Cached total file count
  65. #if ENABLED(SDSORT_DYNAMIC_RAM)
  66. char **CardReader::sortshort, **CardReader::sortnames;
  67. #else
  68. char CardReader::sortshort[SDSORT_LIMIT][FILENAME_LENGTH];
  69. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  70. #endif
  71. #elif DISABLED(SDSORT_USES_STACK)
  72. char CardReader::sortnames[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
  73. #endif
  74. #if HAS_FOLDER_SORTING
  75. #if ENABLED(SDSORT_DYNAMIC_RAM)
  76. uint8_t *CardReader::isDir;
  77. #elif ENABLED(SDSORT_CACHE_NAMES) || DISABLED(SDSORT_USES_STACK)
  78. uint8_t CardReader::isDir[(SDSORT_LIMIT+7)>>3];
  79. #endif
  80. #define IS_DIR(n) TEST(isDir[(n) >> 3], (n) & 0x07)
  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. CardReader::CardReader() {
  92. #if ENABLED(SDCARD_SORT_ALPHA)
  93. sort_count = 0;
  94. #if ENABLED(SDSORT_GCODE)
  95. sort_alpha = true;
  96. sort_folders = FOLDER_SORTING;
  97. //sort_reverse = false;
  98. #endif
  99. #endif
  100. flag.sdprinting = flag.mounted = flag.saving = flag.logging = false;
  101. filesize = sdpos = 0;
  102. file_subcall_ctr = 0;
  103. workDirDepth = 0;
  104. ZERO(workDirParents);
  105. // Disable autostart until card is initialized
  106. autostart_index = -1;
  107. #if PIN_EXISTS(SDPOWER)
  108. OUT_WRITE(SDPOWER_PIN, HIGH); // Power the SD reader
  109. #endif
  110. }
  111. //
  112. // Get a DOS 8.3 filename in its useful form
  113. //
  114. char *createFilename(char * const buffer, const dir_t &p) {
  115. char *pos = buffer;
  116. LOOP_L_N(i, 11) {
  117. if (p.name[i] == ' ') continue;
  118. if (i == 8) *pos++ = '.';
  119. *pos++ = p.name[i];
  120. }
  121. *pos++ = 0;
  122. return buffer;
  123. }
  124. //
  125. // Return 'true' if the item is a folder or G-code file
  126. //
  127. bool CardReader::is_dir_or_gcode(const dir_t &p) {
  128. //uint8_t pn0 = p.name[0];
  129. if ( (p.attributes & DIR_ATT_HIDDEN) // Hidden by attribute
  130. // When readDir() > 0 these must be false:
  131. //|| 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. ) 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(STR_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(STR_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(STR_SD_INIT_FAIL);
  297. else if (!volume.init(&sd2card))
  298. SERIAL_ERROR_MSG(STR_SD_VOL_INIT_FAIL);
  299. else if (!root.openRoot(&volume))
  300. SERIAL_ERROR_MSG(STR_SD_OPENROOT_FAIL);
  301. else {
  302. flag.mounted = true;
  303. SERIAL_ECHO_MSG(STR_SD_CARD_OK);
  304. }
  305. cdroot();
  306. ui.refresh();
  307. }
  308. /**
  309. * Handle SD card events
  310. */
  311. #if MB(FYSETC_CHEETAH, FYSETC_AIO_II)
  312. #include "../module/stepper.h"
  313. #endif
  314. void CardReader::manage_media() {
  315. static uint8_t prev_stat = TERN(INIT_SDCARD_ON_BOOT, 2, 0);
  316. uint8_t stat = uint8_t(IS_SD_INSERTED());
  317. if (stat != prev_stat && ui.detected()) {
  318. uint8_t old_stat = prev_stat;
  319. prev_stat = stat; // Change now to prevent re-entry
  320. if (stat) { // Media Inserted
  321. safe_delay(500); // Some boards need a delay to get settled
  322. mount(); // Try to mount the media
  323. #if MB(FYSETC_CHEETAH, FYSETC_AIO_II)
  324. reset_stepper_drivers(); // Workaround for Cheetah bug
  325. #endif
  326. if (!isMounted()) stat = 0; // Not mounted?
  327. }
  328. else {
  329. #if PIN_EXISTS(SD_DETECT)
  330. release(); // Card is released
  331. #endif
  332. }
  333. ui.media_changed(old_stat, stat); // Update the UI
  334. if (stat) {
  335. TERN_(SDCARD_EEPROM_EMULATION, settings.first_load());
  336. if (old_stat == 2) // First mount?
  337. TERN(POWER_LOSS_RECOVERY,
  338. recovery.check(), // Check for PLR file. (If not there it will beginautostart)
  339. beginautostart() // Look for auto0.g on the next loop
  340. );
  341. }
  342. }
  343. }
  344. void CardReader::release() {
  345. endFilePrint();
  346. flag.mounted = false;
  347. }
  348. void CardReader::openAndPrintFile(const char *name) {
  349. char cmd[4 + strlen(name) + 1]; // Room for "M23 ", filename, and null
  350. extern const char M23_STR[];
  351. sprintf_P(cmd, M23_STR, name);
  352. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  353. queue.enqueue_one_now(cmd);
  354. queue.enqueue_now_P(M24_STR);
  355. }
  356. void CardReader::startFileprint() {
  357. if (isMounted()) {
  358. flag.sdprinting = true;
  359. TERN_(SD_RESORT, flush_presort());
  360. }
  361. }
  362. void CardReader::endFilePrint(TERN_(SD_RESORT, const bool re_sort/*=false*/)) {
  363. TERN_(ADVANCED_PAUSE_FEATURE, did_pause_print = 0);
  364. flag.sdprinting = flag.abort_sd_printing = false;
  365. if (isFileOpen()) file.close();
  366. TERN_(SD_RESORT, if (re_sort) presort());
  367. }
  368. void CardReader::openLogFile(char * const path) {
  369. flag.logging = DISABLED(SDCARD_READONLY);
  370. TERN(SDCARD_READONLY,,openFileWrite(path));
  371. }
  372. //
  373. // Get the root-relative DOS path of the selected file
  374. //
  375. void CardReader::getAbsFilename(char *dst) {
  376. *dst++ = '/';
  377. uint8_t cnt = 1;
  378. auto appendAtom = [&](SdFile &file) {
  379. file.getDosName(dst);
  380. while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; }
  381. if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; }
  382. };
  383. LOOP_L_N(i, workDirDepth) // Loop down to current work dir
  384. appendAtom(workDirParents[i]);
  385. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH) - 1) { // Leave room for filename and nul
  386. appendAtom(file);
  387. --dst;
  388. }
  389. *dst = '\0';
  390. }
  391. void openFailed(const char * const fname) {
  392. SERIAL_ECHOLNPAIR(STR_SD_OPEN_FILE_FAIL, fname, ".");
  393. }
  394. void announceOpen(const uint8_t doing, const char * const path) {
  395. if (doing) {
  396. PORT_REDIRECT(SERIAL_BOTH);
  397. SERIAL_ECHO_START();
  398. SERIAL_ECHOPGM("Now ");
  399. serialprintPGM(doing == 1 ? PSTR("doing") : PSTR("fresh"));
  400. SERIAL_ECHOLNPAIR(" file: ", path);
  401. PORT_RESTORE();
  402. }
  403. }
  404. //
  405. // Open a file by DOS path for read
  406. // The 'subcall_type' flag indicates...
  407. // - 0 : Standard open from host or user interface.
  408. // - 1 : (file open) Opening a new sub-procedure.
  409. // - 1 : (no file open) Opening a macro (M98).
  410. // - 2 : Resuming from a sub-procedure
  411. //
  412. void CardReader::openFileRead(char * const path, const uint8_t subcall_type/*=0*/) {
  413. if (!isMounted()) return;
  414. switch (subcall_type) {
  415. case 0: // Starting a new print. "Now fresh file: ..."
  416. announceOpen(2, path);
  417. file_subcall_ctr = 0;
  418. break;
  419. case 1: // Starting a sub-procedure
  420. // With no file is open it's a simple macro. "Now doing file: ..."
  421. if (!isFileOpen()) { announceOpen(1, path); break; }
  422. // Too deep? The firmware has to bail.
  423. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  424. SERIAL_ERROR_MSG("Exceeded max SUBROUTINE depth:" STRINGIFY(SD_PROCEDURE_DEPTH));
  425. kill(GET_TEXT(MSG_KILL_SUBCALL_OVERFLOW));
  426. return;
  427. }
  428. // Store current filename (based on workDirParents) and position
  429. getAbsFilename(proc_filenames[file_subcall_ctr]);
  430. filespos[file_subcall_ctr] = sdpos;
  431. // For sub-procedures say 'SUBROUTINE CALL target: "..." parent: "..." pos12345'
  432. SERIAL_ECHO_START();
  433. SERIAL_ECHOLNPAIR("SUBROUTINE CALL target:\"", path, "\" parent:\"", proc_filenames[file_subcall_ctr], "\" pos", sdpos);
  434. file_subcall_ctr++;
  435. break;
  436. case 2: // Resuming previous file after sub-procedure
  437. SERIAL_ECHO_MSG("END SUBROUTINE");
  438. break;
  439. }
  440. endFilePrint();
  441. SdFile *curDir;
  442. const char * const fname = diveToFile(true, curDir, path);
  443. if (!fname) return;
  444. if (file.open(curDir, fname, O_READ)) {
  445. filesize = file.fileSize();
  446. sdpos = 0;
  447. PORT_REDIRECT(SERIAL_BOTH);
  448. SERIAL_ECHOLNPAIR(STR_SD_FILE_OPENED, fname, STR_SD_SIZE, filesize);
  449. SERIAL_ECHOLNPGM(STR_SD_FILE_SELECTED);
  450. PORT_RESTORE();
  451. selectFileByName(fname);
  452. ui.set_status(longFilename[0] ? longFilename : fname);
  453. }
  454. else
  455. openFailed(fname);
  456. }
  457. inline void echo_write_to_file(const char * const fname) {
  458. SERIAL_ECHOLNPAIR(STR_SD_WRITE_TO_FILE, fname);
  459. }
  460. //
  461. // Open a file by DOS path for write
  462. //
  463. void CardReader::openFileWrite(char * const path) {
  464. if (!isMounted()) return;
  465. announceOpen(2, path);
  466. file_subcall_ctr = 0;
  467. endFilePrint();
  468. SdFile *curDir;
  469. const char * const fname = diveToFile(false, curDir, path);
  470. if (!fname) return;
  471. #if ENABLED(SDCARD_READONLY)
  472. openFailed(fname);
  473. #else
  474. if (file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  475. flag.saving = true;
  476. selectFileByName(fname);
  477. TERN_(EMERGENCY_PARSER, emergency_parser.disable());
  478. echo_write_to_file(fname);
  479. ui.set_status(fname);
  480. }
  481. else
  482. openFailed(fname);
  483. #endif
  484. }
  485. //
  486. // Delete a file by name in the working directory
  487. //
  488. void CardReader::removeFile(const char * const name) {
  489. if (!isMounted()) return;
  490. //endFilePrint();
  491. SdFile *curDir;
  492. const char * const fname = diveToFile(false, curDir, name);
  493. if (!fname) return;
  494. #if ENABLED(SDCARD_READONLY)
  495. SERIAL_ECHOLNPAIR("Deletion failed (read-only), File: ", fname, ".");
  496. #else
  497. if (file.remove(curDir, fname)) {
  498. SERIAL_ECHOLNPAIR("File deleted:", fname);
  499. sdpos = 0;
  500. TERN_(SDCARD_SORT_ALPHA, presort());
  501. }
  502. else
  503. SERIAL_ECHOLNPAIR("Deletion failed, File: ", fname, ".");
  504. #endif
  505. }
  506. void CardReader::report_status() {
  507. if (isPrinting()) {
  508. SERIAL_ECHOPGM(STR_SD_PRINTING_BYTE);
  509. SERIAL_ECHO(sdpos);
  510. SERIAL_CHAR('/');
  511. SERIAL_ECHOLN(filesize);
  512. }
  513. else
  514. SERIAL_ECHOLNPGM(STR_SD_NOT_PRINTING);
  515. }
  516. void CardReader::write_command(char * const buf) {
  517. char* begin = buf;
  518. char* npos = nullptr;
  519. char* end = buf + strlen(buf) - 1;
  520. file.writeError = false;
  521. if ((npos = strchr(buf, 'N')) != nullptr) {
  522. begin = strchr(npos, ' ') + 1;
  523. end = strchr(npos, '*') - 1;
  524. }
  525. end[1] = '\r';
  526. end[2] = '\n';
  527. end[3] = '\0';
  528. file.write(begin);
  529. if (file.writeError) SERIAL_ERROR_MSG(STR_SD_ERR_WRITE_TO_FILE);
  530. }
  531. //
  532. // Run the next autostart file. Called:
  533. // - On boot after successful card init
  534. // - After finishing the previous autostart file
  535. // - From the LCD command to run the autostart file
  536. //
  537. void CardReader::checkautostart() {
  538. if (autostart_index < 0 || flag.sdprinting) return;
  539. if (!isMounted()) mount();
  540. TERN_(SDCARD_EEPROM_EMULATION, else settings.first_load());
  541. // Don't run auto#.g when a PLR file exists
  542. if (isMounted() && TERN1(POWER_LOSS_RECOVERY, !recovery.valid())) {
  543. char autoname[8];
  544. sprintf_P(autoname, PSTR("auto%c.g"), autostart_index + '0');
  545. dir_t p;
  546. root.rewind();
  547. while (root.readDir(&p, nullptr) > 0) {
  548. for (int8_t i = (int8_t)strlen((char*)p.name); i--;) p.name[i] = tolower(p.name[i]);
  549. if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
  550. openAndPrintFile(autoname);
  551. autostart_index++;
  552. return;
  553. }
  554. }
  555. }
  556. autostart_index = -1;
  557. }
  558. void CardReader::beginautostart() {
  559. autostart_index = 0;
  560. cdroot();
  561. }
  562. void CardReader::closefile(const bool store_location) {
  563. file.sync();
  564. file.close();
  565. flag.saving = flag.logging = false;
  566. sdpos = 0;
  567. TERN_(EMERGENCY_PARSER, emergency_parser.enable());
  568. if (store_location) {
  569. //future: store printer state, filename and position for continuing a stopped print
  570. // so one can unplug the printer and continue printing the next day.
  571. }
  572. }
  573. //
  574. // Get info for a file in the working directory by index
  575. //
  576. void CardReader::selectFileByIndex(const uint16_t nr) {
  577. #if ENABLED(SDSORT_CACHE_NAMES)
  578. if (nr < sort_count) {
  579. strcpy(filename, sortshort[nr]);
  580. strcpy(longFilename, sortnames[nr]);
  581. flag.filenameIsDir = IS_DIR(nr);
  582. return;
  583. }
  584. #endif
  585. workDir.rewind();
  586. selectByIndex(workDir, nr);
  587. }
  588. //
  589. // Get info for a file in the working directory by DOS name
  590. //
  591. void CardReader::selectFileByName(const char * const match) {
  592. #if ENABLED(SDSORT_CACHE_NAMES)
  593. for (uint16_t nr = 0; nr < sort_count; nr++)
  594. if (strcasecmp(match, sortshort[nr]) == 0) {
  595. strcpy(filename, sortshort[nr]);
  596. strcpy(longFilename, sortnames[nr]);
  597. flag.filenameIsDir = IS_DIR(nr);
  598. return;
  599. }
  600. #endif
  601. workDir.rewind();
  602. selectByName(workDir, match);
  603. }
  604. uint16_t CardReader::countFilesInWorkDir() {
  605. workDir.rewind();
  606. return countItems(workDir);
  607. }
  608. /**
  609. * Dive to the given DOS 8.3 file path, with optional echo of the dive paths.
  610. *
  611. * On exit, curDir contains an SdFile reference to the file's directory.
  612. *
  613. * Returns a pointer to the last segment (filename) of the given DOS 8.3 path.
  614. *
  615. * A nullptr result indicates an unrecoverable error.
  616. */
  617. const char* CardReader::diveToFile(const bool update_cwd, SdFile*& curDir, const char * const path, const bool echo/*=false*/) {
  618. // Track both parent and subfolder
  619. static SdFile newDir1, newDir2;
  620. SdFile *sub = &newDir1, *startDir;
  621. // Parsing the path string
  622. const char *item_name_adr = path;
  623. if (path[0] == '/') { // Starting at the root directory?
  624. curDir = &root;
  625. if (update_cwd) workDirDepth = 0; // The cwd can be updated for the benefit of sub-programs
  626. item_name_adr++;
  627. }
  628. else
  629. curDir = &workDir; // Dive from workDir (as set by the UI)
  630. startDir = curDir;
  631. while (item_name_adr) {
  632. // Find next subdirectory delimiter
  633. char * const name_end = strchr(item_name_adr, '/');
  634. // Last atom in the path? Item found.
  635. if (name_end <= item_name_adr) break;
  636. // Set subDirName
  637. const uint8_t len = name_end - item_name_adr;
  638. char dosSubdirname[len + 1];
  639. strncpy(dosSubdirname, item_name_adr, len);
  640. dosSubdirname[len] = 0;
  641. if (echo) SERIAL_ECHOLN(dosSubdirname);
  642. // Open curDir
  643. if (!sub->open(curDir, dosSubdirname, O_READ)) {
  644. SERIAL_ECHOLNPAIR(STR_SD_OPEN_FILE_FAIL, dosSubdirname, ".");
  645. return nullptr;
  646. }
  647. // Close curDir if not at starting-point
  648. if (curDir != startDir) curDir->close();
  649. // curDir now subDir
  650. curDir = sub;
  651. // Update workDirParents, workDirDepth, and workDir
  652. if (update_cwd) {
  653. if (workDirDepth < MAX_DIR_DEPTH) workDirParents[workDirDepth++] = *curDir;
  654. workDir = *curDir;
  655. }
  656. // Point sub at the other scratch object
  657. sub = (curDir != &newDir1) ? &newDir1 : &newDir2;
  658. // Next path atom address
  659. item_name_adr = name_end + 1;
  660. }
  661. return item_name_adr;
  662. }
  663. void CardReader::cd(const char * relpath) {
  664. SdFile newDir;
  665. SdFile *parent = workDir.isOpen() ? &workDir : &root;
  666. if (newDir.open(parent, relpath, O_READ)) {
  667. workDir = newDir;
  668. flag.workDirIsRoot = false;
  669. if (workDirDepth < MAX_DIR_DEPTH)
  670. workDirParents[workDirDepth++] = workDir;
  671. TERN_(SDCARD_SORT_ALPHA, presort());
  672. }
  673. else {
  674. SERIAL_ECHO_START();
  675. SERIAL_ECHOLNPAIR(STR_SD_CANT_ENTER_SUBDIR, relpath);
  676. }
  677. }
  678. int8_t CardReader::cdup() {
  679. if (workDirDepth > 0) { // At least 1 dir has been saved
  680. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  681. TERN_(SDCARD_SORT_ALPHA, presort());
  682. }
  683. if (!workDirDepth) flag.workDirIsRoot = true;
  684. return workDirDepth;
  685. }
  686. void CardReader::cdroot() {
  687. workDir = root;
  688. flag.workDirIsRoot = true;
  689. TERN_(SDCARD_SORT_ALPHA, presort());
  690. }
  691. #if ENABLED(SDCARD_SORT_ALPHA)
  692. /**
  693. * Get the name of a file in the working directory by sort-index
  694. */
  695. void CardReader::getfilename_sorted(const uint16_t nr) {
  696. selectFileByIndex(TERN1(SDSORT_GCODE, sort_alpha) && (nr < sort_count)
  697. ? sort_order[nr] : nr);
  698. }
  699. #if ENABLED(SDSORT_USES_RAM)
  700. #if ENABLED(SDSORT_DYNAMIC_RAM)
  701. // Use dynamic method to copy long filename
  702. #define SET_SORTNAME(I) (sortnames[I] = strdup(longest_filename()))
  703. #if ENABLED(SDSORT_CACHE_NAMES)
  704. // When caching also store the short name, since
  705. // we're replacing the selectFileByIndex() behavior.
  706. #define SET_SORTSHORT(I) (sortshort[I] = strdup(filename))
  707. #else
  708. #define SET_SORTSHORT(I) NOOP
  709. #endif
  710. #else
  711. // Copy filenames into the static array
  712. #define _SET_SORTNAME(I) strncpy(sortnames[I], longest_filename(), SORTED_LONGNAME_MAXLEN)
  713. #if SORTED_LONGNAME_MAXLEN == LONG_FILENAME_LENGTH
  714. // Short name sorting always use LONG_FILENAME_LENGTH with no trailing nul
  715. #define SET_SORTNAME(I) _SET_SORTNAME(I)
  716. #else
  717. // Copy multiple name blocks. Add a nul for the longest case.
  718. #define SET_SORTNAME(I) do{ _SET_SORTNAME(I); sortnames[I][SORTED_LONGNAME_MAXLEN] = '\0'; }while(0)
  719. #endif
  720. #if ENABLED(SDSORT_CACHE_NAMES)
  721. #define SET_SORTSHORT(I) strcpy(sortshort[I], filename)
  722. #else
  723. #define SET_SORTSHORT(I) NOOP
  724. #endif
  725. #endif
  726. #endif
  727. /**
  728. * Read all the files and produce a sort key
  729. *
  730. * We can do this in 3 ways...
  731. * - Minimal RAM: Read two filenames at a time sorting along...
  732. * - Some RAM: Buffer the directory just for this sort
  733. * - Most RAM: Buffer the directory and return filenames from RAM
  734. */
  735. void CardReader::presort() {
  736. // Throw away old sort index
  737. flush_presort();
  738. // Sorting may be turned off
  739. if (TERN0(SDSORT_GCODE, !sort_alpha)) return;
  740. // If there are files, sort up to the limit
  741. uint16_t fileCnt = countFilesInWorkDir();
  742. if (fileCnt > 0) {
  743. // Never sort more than the max allowed
  744. // If you use folders to organize, 20 may be enough
  745. NOMORE(fileCnt, uint16_t(SDSORT_LIMIT));
  746. // Sort order is always needed. May be static or dynamic.
  747. TERN_(SDSORT_DYNAMIC_RAM, sort_order = new uint8_t[fileCnt]);
  748. // Use RAM to store the entire directory during pre-sort.
  749. // SDSORT_LIMIT should be set to prevent over-allocation.
  750. #if ENABLED(SDSORT_USES_RAM)
  751. // If using dynamic ram for names, allocate on the heap.
  752. #if ENABLED(SDSORT_CACHE_NAMES)
  753. #if ENABLED(SDSORT_DYNAMIC_RAM)
  754. sortshort = new char*[fileCnt];
  755. sortnames = new char*[fileCnt];
  756. #endif
  757. #elif ENABLED(SDSORT_USES_STACK)
  758. char sortnames[fileCnt][SORTED_LONGNAME_STORAGE];
  759. #endif
  760. // Folder sorting needs 1 bit per entry for flags.
  761. #if HAS_FOLDER_SORTING
  762. #if ENABLED(SDSORT_DYNAMIC_RAM)
  763. isDir = new uint8_t[(fileCnt + 7) >> 3];
  764. #elif ENABLED(SDSORT_USES_STACK)
  765. uint8_t isDir[(fileCnt + 7) >> 3];
  766. #endif
  767. #endif
  768. #else // !SDSORT_USES_RAM
  769. // By default re-read the names from SD for every compare
  770. // retaining only two filenames at a time. This is very
  771. // slow but is safest and uses minimal RAM.
  772. char name1[LONG_FILENAME_LENGTH];
  773. #endif
  774. if (fileCnt > 1) {
  775. // Init sort order.
  776. for (uint16_t i = 0; i < fileCnt; i++) {
  777. sort_order[i] = SD_ORDER(i, fileCnt);
  778. // If using RAM then read all filenames now.
  779. #if ENABLED(SDSORT_USES_RAM)
  780. selectFileByIndex(i);
  781. SET_SORTNAME(i);
  782. SET_SORTSHORT(i);
  783. // char out[30];
  784. // sprintf_P(out, PSTR("---- %i %s %s"), i, flag.filenameIsDir ? "D" : " ", sortnames[i]);
  785. // SERIAL_ECHOLN(out);
  786. #if HAS_FOLDER_SORTING
  787. const uint16_t bit = i & 0x07, ind = i >> 3;
  788. if (bit == 0) isDir[ind] = 0x00;
  789. if (flag.filenameIsDir) isDir[ind] |= _BV(bit);
  790. #endif
  791. #endif
  792. }
  793. // Bubble Sort
  794. for (uint16_t i = fileCnt; --i;) {
  795. bool didSwap = false;
  796. uint8_t o1 = sort_order[0];
  797. #if DISABLED(SDSORT_USES_RAM)
  798. selectFileByIndex(o1); // Pre-fetch the first entry and save it
  799. strcpy(name1, longest_filename()); // so the loop only needs one fetch
  800. TERN_(HAS_FOLDER_SORTING, bool dir1 = flag.filenameIsDir);
  801. #endif
  802. for (uint16_t j = 0; j < i; ++j) {
  803. const uint16_t o2 = sort_order[j + 1];
  804. // Compare names from the array or just the two buffered names
  805. #if ENABLED(SDSORT_USES_RAM)
  806. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  807. #else
  808. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  809. #endif
  810. #if HAS_FOLDER_SORTING
  811. #if ENABLED(SDSORT_USES_RAM)
  812. // Folder sorting needs an index and bit to test for folder-ness.
  813. #define _SORT_CMP_DIR(fs) IS_DIR(o1) == IS_DIR(o2) ? _SORT_CMP_NODIR() : IS_DIR(fs > 0 ? o1 : o2)
  814. #else
  815. #define _SORT_CMP_DIR(fs) ((dir1 == flag.filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  816. #endif
  817. #endif
  818. // The most economical method reads names as-needed
  819. // throughout the loop. Slow if there are many.
  820. #if DISABLED(SDSORT_USES_RAM)
  821. selectFileByIndex(o2);
  822. const bool dir2 = flag.filenameIsDir;
  823. char * const name2 = longest_filename(); // use the string in-place
  824. #endif // !SDSORT_USES_RAM
  825. // Sort the current pair according to settings.
  826. if (
  827. #if HAS_FOLDER_SORTING
  828. #if ENABLED(SDSORT_GCODE)
  829. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  830. #else
  831. _SORT_CMP_DIR(FOLDER_SORTING)
  832. #endif
  833. #else
  834. _SORT_CMP_NODIR()
  835. #endif
  836. ) {
  837. // Reorder the index, indicate that sorting happened
  838. // Note that the next o1 will be the current o1. No new fetch needed.
  839. sort_order[j] = o2;
  840. sort_order[j + 1] = o1;
  841. didSwap = true;
  842. }
  843. else {
  844. // The next o1 is the current o2. No new fetch needed.
  845. o1 = o2;
  846. #if DISABLED(SDSORT_USES_RAM)
  847. TERN_(HAS_FOLDER_SORTING, dir1 = dir2);
  848. strcpy(name1, name2);
  849. #endif
  850. }
  851. }
  852. if (!didSwap) break;
  853. }
  854. // Using RAM but not keeping names around
  855. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  856. #if ENABLED(SDSORT_DYNAMIC_RAM)
  857. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  858. TERN_(HAS_FOLDER_SORTING, free(isDir));
  859. #endif
  860. #endif
  861. }
  862. else {
  863. sort_order[0] = 0;
  864. #if BOTH(SDSORT_USES_RAM, SDSORT_CACHE_NAMES)
  865. #if ENABLED(SDSORT_DYNAMIC_RAM)
  866. sortnames = new char*[1];
  867. sortshort = new char*[1];
  868. isDir = new uint8_t[1];
  869. #endif
  870. selectFileByIndex(0);
  871. SET_SORTNAME(0);
  872. SET_SORTSHORT(0);
  873. isDir[0] = flag.filenameIsDir;
  874. #endif
  875. }
  876. sort_count = fileCnt;
  877. }
  878. }
  879. void CardReader::flush_presort() {
  880. if (sort_count > 0) {
  881. #if ENABLED(SDSORT_DYNAMIC_RAM)
  882. delete sort_order;
  883. #if ENABLED(SDSORT_CACHE_NAMES)
  884. LOOP_L_N(i, sort_count) {
  885. free(sortshort[i]); // strdup
  886. free(sortnames[i]); // strdup
  887. }
  888. delete sortshort;
  889. delete sortnames;
  890. #endif
  891. #endif
  892. sort_count = 0;
  893. }
  894. }
  895. #endif // SDCARD_SORT_ALPHA
  896. uint16_t CardReader::get_num_Files() {
  897. return
  898. #if ENABLED(SDCARD_SORT_ALPHA) && SDSORT_USES_RAM && SDSORT_CACHE_NAMES
  899. nrFiles // no need to access the SD card for filenames
  900. #else
  901. countFilesInWorkDir()
  902. #endif
  903. ;
  904. }
  905. //
  906. // Return from procedure or close out the Print Job
  907. //
  908. void CardReader::fileHasFinished() {
  909. planner.synchronize();
  910. file.close();
  911. if (file_subcall_ctr > 0) { // Resume calling file after closing procedure
  912. file_subcall_ctr--;
  913. openFileRead(proc_filenames[file_subcall_ctr], 2); // 2 = Returning from sub-procedure
  914. setIndex(filespos[file_subcall_ctr]);
  915. startFileprint();
  916. }
  917. else {
  918. endFilePrint();
  919. TERN_(SDCARD_SORT_ALPHA, presort());
  920. marlin_state = MF_SD_COMPLETE;
  921. }
  922. }
  923. #if ENABLED(AUTO_REPORT_SD_STATUS)
  924. uint8_t CardReader::auto_report_sd_interval = 0;
  925. millis_t CardReader::next_sd_report_ms;
  926. #if NUM_SERIAL > 1
  927. int8_t CardReader::auto_report_port;
  928. #endif
  929. void CardReader::auto_report_sd_status() {
  930. millis_t current_ms = millis();
  931. if (auto_report_sd_interval && ELAPSED(current_ms, next_sd_report_ms)) {
  932. next_sd_report_ms = current_ms + 1000UL * auto_report_sd_interval;
  933. PORT_REDIRECT(auto_report_port);
  934. report_status();
  935. }
  936. }
  937. #endif // AUTO_REPORT_SD_STATUS
  938. #if ENABLED(POWER_LOSS_RECOVERY)
  939. bool CardReader::jobRecoverFileExists() {
  940. const bool exists = recovery.file.open(&root, recovery.filename, O_READ);
  941. if (exists) recovery.file.close();
  942. return exists;
  943. }
  944. void CardReader::openJobRecoveryFile(const bool read) {
  945. if (!isMounted()) return;
  946. if (recovery.file.isOpen()) return;
  947. if (!recovery.file.open(&root, recovery.filename, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC))
  948. SERIAL_ECHOLNPAIR(STR_SD_OPEN_FILE_FAIL, recovery.filename, ".");
  949. else if (!read)
  950. echo_write_to_file(recovery.filename);
  951. }
  952. // Removing the job recovery file currently requires closing
  953. // the file being printed, so during SD printing the file should
  954. // be zeroed and written instead of deleted.
  955. void CardReader::removeJobRecoveryFile() {
  956. if (jobRecoverFileExists()) {
  957. recovery.init();
  958. removeFile(recovery.filename);
  959. #if ENABLED(DEBUG_POWER_LOSS_RECOVERY)
  960. SERIAL_ECHOPGM("Power-loss file delete");
  961. serialprintPGM(jobRecoverFileExists() ? PSTR(" failed.\n") : PSTR("d.\n"));
  962. #endif
  963. }
  964. }
  965. #endif // POWER_LOSS_RECOVERY
  966. #endif // SDSUPPORT