My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cardreader.cpp 31KB

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