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

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