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

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