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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. #include "Marlin.h"
  2. #include "cardreader.h"
  3. #include "ultralcd.h"
  4. #include "stepper.h"
  5. #include "temperature.h"
  6. #include "language.h"
  7. #ifdef SDSUPPORT
  8. CardReader::CardReader() {
  9. filesize = 0;
  10. sdpos = 0;
  11. sdprinting = false;
  12. cardOK = false;
  13. saving = false;
  14. logging = false;
  15. workDirDepth = 0;
  16. file_subcall_ctr = 0;
  17. memset(workDirParents, 0, sizeof(workDirParents));
  18. autostart_stilltocheck = true; //the SD start is delayed, because otherwise the serial cannot answer fast enough to make contact with the host software.
  19. autostart_index = 0;
  20. //power to SD reader
  21. #if SDPOWER > -1
  22. OUT_WRITE(SDPOWER, HIGH);
  23. #endif //SDPOWER
  24. next_autostart_ms = millis() + 5000;
  25. }
  26. char *createFilename(char *buffer, const dir_t &p) { //buffer > 12characters
  27. char *pos = buffer;
  28. for (uint8_t i = 0; i < 11; i++) {
  29. if (p.name[i] == ' ') continue;
  30. if (i == 8) *pos++ = '.';
  31. *pos++ = p.name[i];
  32. }
  33. *pos++ = 0;
  34. return buffer;
  35. }
  36. /**
  37. * Dive into a folder and recurse depth-first to perform a pre-set operation lsAction:
  38. * LS_Count - Add +1 to nrFiles for every file within the parent
  39. * LS_GetFilename - Get the filename of the file indexed by nrFiles
  40. * LS_SerialPrint - Print the full path of each file to serial output
  41. */
  42. void CardReader::lsDive(const char *prepend, SdFile parent, const char * const match/*=NULL*/) {
  43. dir_t p;
  44. uint8_t cnt = 0;
  45. // Read the next entry from a directory
  46. while (parent.readDir(p, longFilename) > 0) {
  47. // If the entry is a directory and the action is LS_SerialPrint
  48. if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) {
  49. // Get the short name for the item, which we know is a folder
  50. char lfilename[FILENAME_LENGTH];
  51. createFilename(lfilename, p);
  52. // Allocate enough stack space for the full path to a folder, trailing slash, and nul
  53. boolean prepend_is_empty = (prepend[0] == '\0');
  54. int len = strlen(prepend) + (prepend_is_empty ? 1 : 0) + strlen(lfilename) + 1;
  55. char path[len];
  56. // Append the FOLDERNAME12/ to the passed string.
  57. // It contains the full path to the "parent" argument.
  58. // We now have the full path to the item in this folder.
  59. if (prepend_is_empty) {
  60. path[0] = '/'; // a root slash if prepend is empty
  61. path[1] = '\0';
  62. }
  63. else
  64. path[0] = '\0';
  65. strcat(path, prepend); // 1 character minimum
  66. strcat(path, lfilename); // FILENAME_LENGTH-1 characters maximum
  67. strcat(path, "/"); // 1 character
  68. // Serial.print(path);
  69. // Get a new directory object using the full path
  70. // and dive recursively into it.
  71. SdFile dir;
  72. if (!dir.open(parent, lfilename, O_READ)) {
  73. if (lsAction == LS_SerialPrint) {
  74. SERIAL_ECHO_START;
  75. SERIAL_ECHOLN(MSG_SD_CANT_OPEN_SUBDIR);
  76. SERIAL_ECHOLN(lfilename);
  77. }
  78. }
  79. lsDive(path, dir);
  80. // close() is done automatically by destructor of SdFile
  81. }
  82. else {
  83. char pn0 = p.name[0];
  84. if (pn0 == DIR_NAME_FREE) break;
  85. if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue;
  86. if (longFilename[0] == '.') continue;
  87. if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;
  88. filenameIsDir = DIR_IS_SUBDIR(&p);
  89. if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue;
  90. switch (lsAction) {
  91. case LS_Count:
  92. nrFiles++;
  93. break;
  94. case LS_SerialPrint:
  95. createFilename(filename, p);
  96. SERIAL_PROTOCOL(prepend);
  97. SERIAL_PROTOCOLLN(filename);
  98. break;
  99. case LS_GetFilename:
  100. createFilename(filename, p);
  101. if (match != NULL) {
  102. if (strcasecmp(match, filename) == 0) return;
  103. }
  104. else if (cnt == nrFiles) return;
  105. cnt++;
  106. break;
  107. }
  108. }
  109. } // while readDir
  110. }
  111. void CardReader::ls() {
  112. lsAction = LS_SerialPrint;
  113. root.rewind();
  114. lsDive("", root);
  115. }
  116. #ifdef LONG_FILENAME_HOST_SUPPORT
  117. /**
  118. * Get a long pretty path based on a DOS 8.3 path
  119. */
  120. void CardReader::printLongPath(char *path) {
  121. lsAction = LS_GetFilename;
  122. int i, pathLen = strlen(path);
  123. // SERIAL_ECHOPGM("Full Path: "); SERIAL_ECHOLN(path);
  124. // Zero out slashes to make segments
  125. for (i = 0; i < pathLen; i++) if (path[i] == '/') path[i] = '\0';
  126. SdFile diveDir = root; // start from the root for segment 1
  127. for (i = 0; i < pathLen;) {
  128. if (path[i] == '\0') i++; // move past a single nul
  129. char *segment = &path[i]; // The segment after most slashes
  130. // If a segment is empty (extra-slash) then exit
  131. if (!*segment) break;
  132. // Go to the next segment
  133. while (path[++i]) { }
  134. // SERIAL_ECHOPGM("Looking for segment: "); SERIAL_ECHOLN(segment);
  135. // Find the item, setting the long filename
  136. diveDir.rewind();
  137. lsDive("", diveDir, segment);
  138. // Print /LongNamePart to serial output
  139. SERIAL_PROTOCOLCHAR('/');
  140. SERIAL_PROTOCOL(longFilename[0] ? longFilename : "???");
  141. // If the filename was printed then that's it
  142. if (!filenameIsDir) break;
  143. // SERIAL_ECHOPGM("Opening dir: "); SERIAL_ECHOLN(segment);
  144. // Open the sub-item as the new dive parent
  145. SdFile dir;
  146. if (!dir.open(diveDir, segment, O_READ)) {
  147. SERIAL_EOL;
  148. SERIAL_ECHO_START;
  149. SERIAL_ECHOPGM(MSG_SD_CANT_OPEN_SUBDIR);
  150. SERIAL_ECHO(segment);
  151. break;
  152. }
  153. diveDir.close();
  154. diveDir = dir;
  155. } // while i<pathLen
  156. SERIAL_EOL;
  157. }
  158. #endif // LONG_FILENAME_HOST_SUPPORT
  159. void CardReader::initsd() {
  160. cardOK = false;
  161. if (root.isOpen()) root.close();
  162. #ifdef SDSLOW
  163. #define SPI_SPEED SPI_HALF_SPEED
  164. #else
  165. #define SPI_SPEED SPI_FULL_SPEED
  166. #endif
  167. if (!card.init(SPI_SPEED,SDSS)
  168. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  169. && !card.init(SPI_SPEED, LCD_SDSS)
  170. #endif
  171. ) {
  172. //if (!card.init(SPI_HALF_SPEED,SDSS))
  173. SERIAL_ECHO_START;
  174. SERIAL_ECHOLNPGM(MSG_SD_INIT_FAIL);
  175. }
  176. else if (!volume.init(&card)) {
  177. SERIAL_ERROR_START;
  178. SERIAL_ERRORLNPGM(MSG_SD_VOL_INIT_FAIL);
  179. }
  180. else if (!root.openRoot(&volume)) {
  181. SERIAL_ERROR_START;
  182. SERIAL_ERRORLNPGM(MSG_SD_OPENROOT_FAIL);
  183. }
  184. else {
  185. cardOK = true;
  186. SERIAL_ECHO_START;
  187. SERIAL_ECHOLNPGM(MSG_SD_CARD_OK);
  188. }
  189. workDir = root;
  190. curDir = &root;
  191. /*
  192. if (!workDir.openRoot(&volume)) {
  193. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  194. }
  195. */
  196. }
  197. void CardReader::setroot() {
  198. /*if (!workDir.openRoot(&volume)) {
  199. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  200. }*/
  201. workDir = root;
  202. curDir = &workDir;
  203. }
  204. void CardReader::release() {
  205. sdprinting = false;
  206. cardOK = false;
  207. }
  208. void CardReader::startFileprint() {
  209. if (cardOK) {
  210. sdprinting = true;
  211. }
  212. }
  213. void CardReader::pauseSDPrint() {
  214. if (sdprinting) sdprinting = false;
  215. }
  216. void CardReader::openLogFile(char* name) {
  217. logging = true;
  218. openFile(name, false);
  219. }
  220. void CardReader::getAbsFilename(char *t) {
  221. uint8_t cnt = 0;
  222. *t = '/'; t++; cnt++;
  223. for (uint8_t i = 0; i < workDirDepth; i++) {
  224. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  225. while(*t && cnt < MAXPATHNAMELENGTH) { t++; cnt++; } //crawl counter forward.
  226. }
  227. if (cnt < MAXPATHNAMELENGTH - FILENAME_LENGTH)
  228. file.getFilename(t);
  229. else
  230. t[0] = 0;
  231. }
  232. void CardReader::openFile(char* name, bool read, bool replace_current/*=true*/) {
  233. if (!cardOK) return;
  234. if (file.isOpen()) { //replacing current file by new file, or subfile call
  235. if (!replace_current) {
  236. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  237. SERIAL_ERROR_START;
  238. SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  239. SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  240. kill(PSTR(MSG_KILLED));
  241. return;
  242. }
  243. SERIAL_ECHO_START;
  244. SERIAL_ECHOPGM("SUBROUTINE CALL target:\"");
  245. SERIAL_ECHO(name);
  246. SERIAL_ECHOPGM("\" parent:\"");
  247. //store current filename and position
  248. getAbsFilename(filenames[file_subcall_ctr]);
  249. SERIAL_ECHO(filenames[file_subcall_ctr]);
  250. SERIAL_ECHOPGM("\" pos");
  251. SERIAL_ECHOLN(sdpos);
  252. filespos[file_subcall_ctr] = sdpos;
  253. file_subcall_ctr++;
  254. }
  255. else {
  256. SERIAL_ECHO_START;
  257. SERIAL_ECHOPGM("Now doing file: ");
  258. SERIAL_ECHOLN(name);
  259. }
  260. file.close();
  261. }
  262. else { //opening fresh file
  263. file_subcall_ctr = 0; //resetting procedure depth in case user cancels print while in procedure
  264. SERIAL_ECHO_START;
  265. SERIAL_ECHOPGM("Now fresh file: ");
  266. SERIAL_ECHOLN(name);
  267. }
  268. sdprinting = false;
  269. SdFile myDir;
  270. curDir = &root;
  271. char *fname = name;
  272. char *dirname_start, *dirname_end;
  273. if (name[0] == '/') {
  274. dirname_start = &name[1];
  275. while (dirname_start > 0) {
  276. dirname_end = strchr(dirname_start, '/');
  277. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  278. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  279. if (dirname_end > 0 && dirname_end > dirname_start) {
  280. char subdirname[FILENAME_LENGTH];
  281. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  282. subdirname[dirname_end - dirname_start] = 0;
  283. SERIAL_ECHOLN(subdirname);
  284. if (!myDir.open(curDir, subdirname, O_READ)) {
  285. SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
  286. SERIAL_PROTOCOL(subdirname);
  287. SERIAL_PROTOCOLCHAR('.');
  288. return;
  289. }
  290. else {
  291. //SERIAL_ECHOLN("dive ok");
  292. }
  293. curDir = &myDir;
  294. dirname_start = dirname_end + 1;
  295. }
  296. else { // the remainder after all /fsa/fdsa/ is the filename
  297. fname = dirname_start;
  298. //SERIAL_ECHOLN("remainder");
  299. //SERIAL_ECHOLN(fname);
  300. break;
  301. }
  302. }
  303. }
  304. else { //relative path
  305. curDir = &workDir;
  306. }
  307. if (read) {
  308. if (file.open(curDir, fname, O_READ)) {
  309. filesize = file.fileSize();
  310. SERIAL_PROTOCOLPGM(MSG_SD_FILE_OPENED);
  311. SERIAL_PROTOCOL(fname);
  312. SERIAL_PROTOCOLPGM(MSG_SD_SIZE);
  313. SERIAL_PROTOCOLLN(filesize);
  314. sdpos = 0;
  315. SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED);
  316. getfilename(0, fname);
  317. lcd_setstatus(longFilename[0] ? longFilename : fname);
  318. }
  319. else {
  320. SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
  321. SERIAL_PROTOCOL(fname);
  322. SERIAL_PROTOCOLPGM(".\n");
  323. }
  324. }
  325. else { //write
  326. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  327. SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
  328. SERIAL_PROTOCOL(fname);
  329. SERIAL_PROTOCOLPGM(".\n");
  330. }
  331. else {
  332. saving = true;
  333. SERIAL_PROTOCOLPGM(MSG_SD_WRITE_TO_FILE);
  334. SERIAL_PROTOCOLLN(name);
  335. lcd_setstatus(fname);
  336. }
  337. }
  338. }
  339. void CardReader::removeFile(char* name) {
  340. if (!cardOK) return;
  341. file.close();
  342. sdprinting = false;
  343. SdFile myDir;
  344. curDir = &root;
  345. char *fname = name;
  346. char *dirname_start, *dirname_end;
  347. if (name[0] == '/') {
  348. dirname_start = strchr(name, '/') + 1;
  349. while (dirname_start > 0) {
  350. dirname_end = strchr(dirname_start, '/');
  351. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  352. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  353. if (dirname_end > 0 && dirname_end > dirname_start) {
  354. char subdirname[FILENAME_LENGTH];
  355. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  356. subdirname[dirname_end - dirname_start] = 0;
  357. SERIAL_ECHOLN(subdirname);
  358. if (!myDir.open(curDir, subdirname, O_READ)) {
  359. SERIAL_PROTOCOLPGM("open failed, File: ");
  360. SERIAL_PROTOCOL(subdirname);
  361. SERIAL_PROTOCOLCHAR('.');
  362. return;
  363. }
  364. else {
  365. //SERIAL_ECHOLN("dive ok");
  366. }
  367. curDir = &myDir;
  368. dirname_start = dirname_end + 1;
  369. }
  370. else { // the remainder after all /fsa/fdsa/ is the filename
  371. fname = dirname_start;
  372. //SERIAL_ECHOLN("remainder");
  373. //SERIAL_ECHOLN(fname);
  374. break;
  375. }
  376. }
  377. }
  378. else { // relative path
  379. curDir = &workDir;
  380. }
  381. if (file.remove(curDir, fname)) {
  382. SERIAL_PROTOCOLPGM("File deleted:");
  383. SERIAL_PROTOCOLLN(fname);
  384. sdpos = 0;
  385. }
  386. else {
  387. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  388. SERIAL_PROTOCOL(fname);
  389. SERIAL_PROTOCOLCHAR('.');
  390. }
  391. }
  392. void CardReader::getStatus() {
  393. if (cardOK) {
  394. SERIAL_PROTOCOLPGM(MSG_SD_PRINTING_BYTE);
  395. SERIAL_PROTOCOL(sdpos);
  396. SERIAL_PROTOCOLCHAR('/');
  397. SERIAL_PROTOCOLLN(filesize);
  398. }
  399. else {
  400. SERIAL_PROTOCOLLNPGM(MSG_SD_NOT_PRINTING);
  401. }
  402. }
  403. void CardReader::write_command(char *buf) {
  404. char* begin = buf;
  405. char* npos = 0;
  406. char* end = buf + strlen(buf) - 1;
  407. file.writeError = false;
  408. if ((npos = strchr(buf, 'N')) != NULL) {
  409. begin = strchr(npos, ' ') + 1;
  410. end = strchr(npos, '*') - 1;
  411. }
  412. end[1] = '\r';
  413. end[2] = '\n';
  414. end[3] = '\0';
  415. file.write(begin);
  416. if (file.writeError) {
  417. SERIAL_ERROR_START;
  418. SERIAL_ERRORLNPGM(MSG_SD_ERR_WRITE_TO_FILE);
  419. }
  420. }
  421. void CardReader::checkautostart(bool force) {
  422. if (!force && (!autostart_stilltocheck || next_autostart_ms < millis()))
  423. return;
  424. autostart_stilltocheck = false;
  425. if (!cardOK) {
  426. initsd();
  427. if (!cardOK) return; // fail
  428. }
  429. char autoname[10];
  430. sprintf_P(autoname, PSTR("auto%i.g"), autostart_index);
  431. for (int8_t i = 0; i < (int8_t)strlen(autoname); i++) autoname[i] = tolower(autoname[i]);
  432. dir_t p;
  433. root.rewind();
  434. bool found = false;
  435. while (root.readDir(p, NULL) > 0) {
  436. for (int8_t i = 0; i < (int8_t)strlen((char*)p.name); i++) p.name[i] = tolower(p.name[i]);
  437. if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
  438. char cmd[4 + (FILENAME_LENGTH + 1) * MAX_DIR_DEPTH + 2];
  439. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  440. enqueuecommand(cmd);
  441. enqueuecommands_P(PSTR("M24"));
  442. found = true;
  443. }
  444. }
  445. if (!found)
  446. autostart_index = -1;
  447. else
  448. autostart_index++;
  449. }
  450. void CardReader::closefile(bool store_location) {
  451. file.sync();
  452. file.close();
  453. saving = logging = false;
  454. if (store_location) {
  455. //future: store printer state, filename and position for continuing a stopped print
  456. // so one can unplug the printer and continue printing the next day.
  457. }
  458. }
  459. /**
  460. * Get the name of a file in the current directory by index
  461. */
  462. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/) {
  463. curDir = &workDir;
  464. lsAction = LS_GetFilename;
  465. nrFiles = nr;
  466. curDir->rewind();
  467. lsDive("", *curDir, match);
  468. }
  469. uint16_t CardReader::getnrfilenames() {
  470. curDir = &workDir;
  471. lsAction = LS_Count;
  472. nrFiles = 0;
  473. curDir->rewind();
  474. lsDive("", *curDir);
  475. //SERIAL_ECHOLN(nrFiles);
  476. return nrFiles;
  477. }
  478. void CardReader::chdir(const char * relpath) {
  479. SdFile newfile;
  480. SdFile *parent = &root;
  481. if (workDir.isOpen()) parent = &workDir;
  482. if (!newfile.open(*parent, relpath, O_READ)) {
  483. SERIAL_ECHO_START;
  484. SERIAL_ECHOPGM(MSG_SD_CANT_ENTER_SUBDIR);
  485. SERIAL_ECHOLN(relpath);
  486. }
  487. else {
  488. if (workDirDepth < MAX_DIR_DEPTH) {
  489. ++workDirDepth;
  490. for (int d = workDirDepth; d--;) workDirParents[d + 1] = workDirParents[d];
  491. workDirParents[0] = *parent;
  492. }
  493. workDir = newfile;
  494. }
  495. }
  496. void CardReader::updir() {
  497. if (workDirDepth > 0) {
  498. --workDirDepth;
  499. workDir = workDirParents[0];
  500. for (uint16_t d = 0; d < workDirDepth; d++)
  501. workDirParents[d] = workDirParents[d+1];
  502. }
  503. }
  504. void CardReader::printingHasFinished() {
  505. st_synchronize();
  506. if (file_subcall_ctr > 0) { // Heading up to a parent file that called current as a procedure.
  507. file.close();
  508. file_subcall_ctr--;
  509. openFile(filenames[file_subcall_ctr], true, true);
  510. setIndex(filespos[file_subcall_ctr]);
  511. startFileprint();
  512. }
  513. else {
  514. file.close();
  515. sdprinting = false;
  516. if (SD_FINISHED_STEPPERRELEASE) {
  517. //finishAndDisableSteppers();
  518. enqueuecommands_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  519. }
  520. autotempShutdown();
  521. }
  522. }
  523. #endif //SDSUPPORT