My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

cardreader.cpp 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. lcd_setstatus(fname);
  359. }
  360. }
  361. }
  362. void CardReader::removeFile(char* name) {
  363. if (!cardOK) return;
  364. file.close();
  365. sdprinting = false;
  366. SdFile myDir;
  367. curDir = &root;
  368. char *fname = name;
  369. char *dirname_start, *dirname_end;
  370. if (name[0] == '/') {
  371. dirname_start = strchr(name, '/') + 1;
  372. while (dirname_start != NULL) {
  373. dirname_end = strchr(dirname_start, '/');
  374. //SERIAL_ECHOPGM("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  375. //SERIAL_ECHOPGM("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  376. if (dirname_end != NULL && dirname_end > dirname_start) {
  377. char subdirname[FILENAME_LENGTH];
  378. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  379. subdirname[dirname_end - dirname_start] = 0;
  380. SERIAL_ECHOLN(subdirname);
  381. if (!myDir.open(curDir, subdirname, O_READ)) {
  382. SERIAL_PROTOCOLPAIR("open failed, File: ", subdirname);
  383. SERIAL_PROTOCOLCHAR('.');
  384. return;
  385. }
  386. else {
  387. //SERIAL_ECHOLNPGM("dive ok");
  388. }
  389. curDir = &myDir;
  390. dirname_start = dirname_end + 1;
  391. }
  392. else { // the remainder after all /fsa/fdsa/ is the filename
  393. fname = dirname_start;
  394. //SERIAL_ECHOLNPGM("remainder");
  395. //SERIAL_ECHOLN(fname);
  396. break;
  397. }
  398. }
  399. }
  400. else { // relative path
  401. curDir = &workDir;
  402. }
  403. if (file.remove(curDir, fname)) {
  404. SERIAL_PROTOCOLPGM("File deleted:");
  405. SERIAL_PROTOCOLLN(fname);
  406. sdpos = 0;
  407. }
  408. else {
  409. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  410. SERIAL_PROTOCOL(fname);
  411. SERIAL_PROTOCOLCHAR('.');
  412. }
  413. }
  414. void CardReader::getStatus() {
  415. if (cardOK) {
  416. SERIAL_PROTOCOLPGM(MSG_SD_PRINTING_BYTE);
  417. SERIAL_PROTOCOL(sdpos);
  418. SERIAL_PROTOCOLCHAR('/');
  419. SERIAL_PROTOCOLLN(filesize);
  420. }
  421. else {
  422. SERIAL_PROTOCOLLNPGM(MSG_SD_NOT_PRINTING);
  423. }
  424. }
  425. void CardReader::write_command(char *buf) {
  426. char* begin = buf;
  427. char* npos = 0;
  428. char* end = buf + strlen(buf) - 1;
  429. file.writeError = false;
  430. if ((npos = strchr(buf, 'N')) != NULL) {
  431. begin = strchr(npos, ' ') + 1;
  432. end = strchr(npos, '*') - 1;
  433. }
  434. end[1] = '\r';
  435. end[2] = '\n';
  436. end[3] = '\0';
  437. file.write(begin);
  438. if (file.writeError) {
  439. SERIAL_ERROR_START;
  440. SERIAL_ERRORLNPGM(MSG_SD_ERR_WRITE_TO_FILE);
  441. }
  442. }
  443. void CardReader::checkautostart(bool force) {
  444. if (!force && (!autostart_stilltocheck || ELAPSED(millis(), next_autostart_ms)))
  445. return;
  446. autostart_stilltocheck = false;
  447. if (!cardOK) {
  448. initsd();
  449. if (!cardOK) return; // fail
  450. }
  451. char autoname[10];
  452. sprintf_P(autoname, PSTR("auto%i.g"), autostart_index);
  453. for (int8_t i = 0; i < (int8_t)strlen(autoname); i++) autoname[i] = tolower(autoname[i]);
  454. dir_t p;
  455. root.rewind();
  456. bool found = false;
  457. while (root.readDir(p, NULL) > 0) {
  458. for (int8_t i = 0; i < (int8_t)strlen((char*)p.name); i++) p.name[i] = tolower(p.name[i]);
  459. if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
  460. openAndPrintFile(autoname);
  461. found = true;
  462. }
  463. }
  464. if (!found)
  465. autostart_index = -1;
  466. else
  467. autostart_index++;
  468. }
  469. void CardReader::closefile(bool store_location) {
  470. file.sync();
  471. file.close();
  472. saving = logging = false;
  473. if (store_location) {
  474. //future: store printer state, filename and position for continuing a stopped print
  475. // so one can unplug the printer and continue printing the next day.
  476. }
  477. }
  478. /**
  479. * Get the name of a file in the current directory by index
  480. */
  481. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/) {
  482. curDir = &workDir;
  483. lsAction = LS_GetFilename;
  484. nrFiles = nr;
  485. curDir->rewind();
  486. lsDive("", *curDir, match);
  487. }
  488. uint16_t CardReader::getnrfilenames() {
  489. curDir = &workDir;
  490. lsAction = LS_Count;
  491. nrFiles = 0;
  492. curDir->rewind();
  493. lsDive("", *curDir);
  494. //SERIAL_ECHOLN(nrFiles);
  495. return nrFiles;
  496. }
  497. void CardReader::chdir(const char * relpath) {
  498. SdFile newfile;
  499. SdFile *parent = &root;
  500. if (workDir.isOpen()) parent = &workDir;
  501. if (!newfile.open(*parent, relpath, O_READ)) {
  502. SERIAL_ECHO_START;
  503. SERIAL_ECHOPGM(MSG_SD_CANT_ENTER_SUBDIR);
  504. SERIAL_ECHOLN(relpath);
  505. }
  506. else {
  507. if (workDirDepth < MAX_DIR_DEPTH)
  508. workDirParents[workDirDepth++] = *parent;
  509. workDir = newfile;
  510. }
  511. }
  512. void CardReader::updir() {
  513. if (workDirDepth > 0)
  514. workDir = workDirParents[--workDirDepth];
  515. }
  516. void CardReader::printingHasFinished() {
  517. stepper.synchronize();
  518. if (file_subcall_ctr > 0) { // Heading up to a parent file that called current as a procedure.
  519. file.close();
  520. file_subcall_ctr--;
  521. openFile(proc_filenames[file_subcall_ctr], true, true);
  522. setIndex(filespos[file_subcall_ctr]);
  523. startFileprint();
  524. }
  525. else {
  526. file.close();
  527. sdprinting = false;
  528. if (SD_FINISHED_STEPPERRELEASE)
  529. enqueue_and_echo_commands_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  530. thermalManager.autotempShutdown();
  531. }
  532. }
  533. #endif //SDSUPPORT