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

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