My Marlin configs for Fabrikator Mini and CTC i3 Pro B
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

cardreader.cpp 29KB

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