My Marlin configs for Fabrikator Mini and CTC i3 Pro B
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

cardreader.cpp 30KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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 "../inc/MarlinConfig.h"
  23. #if ENABLED(SDSUPPORT)
  24. #include "cardreader.h"
  25. #include "../Marlin.h"
  26. #include "../lcd/ultralcd.h"
  27. #include "../module/planner.h"
  28. #include "../module/printcounter.h"
  29. #include "../core/language.h"
  30. #include "../gcode/queue.h"
  31. #if ENABLED(POWER_LOSS_RECOVERY)
  32. #include "../feature/power_loss_recovery.h"
  33. #endif
  34. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  35. #include "../feature/pause.h"
  36. #endif
  37. #include <ctype.h>
  38. #define LONGEST_FILENAME (longFilename[0] ? longFilename : filename)
  39. CardReader::CardReader() {
  40. #if ENABLED(SDCARD_SORT_ALPHA)
  41. sort_count = 0;
  42. #if ENABLED(SDSORT_GCODE)
  43. sort_alpha = true;
  44. sort_folders = FOLDER_SORTING;
  45. //sort_reverse = false;
  46. #endif
  47. #endif
  48. sdprinting = cardOK = saving = logging = false;
  49. filesize = 0;
  50. sdpos = 0;
  51. file_subcall_ctr = 0;
  52. workDirDepth = 0;
  53. ZERO(workDirParents);
  54. // Disable autostart until card is initialized
  55. autostart_index = -1;
  56. //power to SD reader
  57. #if SDPOWER > -1
  58. OUT_WRITE(SDPOWER, HIGH);
  59. #endif
  60. }
  61. char *createFilename(char *buffer, const dir_t &p) { //buffer > 12characters
  62. char *pos = buffer;
  63. for (uint8_t i = 0; i < 11; i++) {
  64. if (p.name[i] == ' ') continue;
  65. if (i == 8) *pos++ = '.';
  66. *pos++ = p.name[i];
  67. }
  68. *pos++ = 0;
  69. return buffer;
  70. }
  71. /**
  72. * Dive into a folder and recurse depth-first to perform a pre-set operation lsAction:
  73. * LS_Count - Add +1 to nrFiles for every file within the parent
  74. * LS_GetFilename - Get the filename of the file indexed by nrFile_index
  75. * LS_SerialPrint - Print the full path and size of each file to serial output
  76. */
  77. uint16_t nrFile_index;
  78. void CardReader::lsDive(const char *prepend, SdFile parent, const char * const match/*=NULL*/
  79. #if NUM_SERIAL > 1
  80. , const int8_t port/*= -1*/
  81. #endif
  82. ) {
  83. dir_t p;
  84. uint8_t cnt = 0;
  85. // Read the next entry from a directory
  86. while (parent.readDir(p, longFilename) > 0) {
  87. // If the entry is a directory and the action is LS_SerialPrint
  88. if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) {
  89. // Get the short name for the item, which we know is a folder
  90. char lfilename[FILENAME_LENGTH];
  91. createFilename(lfilename, p);
  92. // Allocate enough stack space for the full path to a folder, trailing slash, and nul
  93. bool prepend_is_empty = (prepend[0] == '\0');
  94. int len = (prepend_is_empty ? 1 : strlen(prepend)) + strlen(lfilename) + 1 + 1;
  95. char path[len];
  96. // Append the FOLDERNAME12/ to the passed string.
  97. // It contains the full path to the "parent" argument.
  98. // We now have the full path to the item in this folder.
  99. strcpy(path, prepend_is_empty ? "/" : prepend); // root slash if prepend is empty
  100. strcat(path, lfilename); // FILENAME_LENGTH-1 characters maximum
  101. strcat(path, "/"); // 1 character
  102. // Serial.print(path);
  103. // Get a new directory object using the full path
  104. // and dive recursively into it.
  105. SdFile dir;
  106. if (!dir.open(parent, lfilename, O_READ)) {
  107. if (lsAction == LS_SerialPrint) {
  108. SERIAL_ECHO_START_P(port);
  109. SERIAL_ECHOPGM_P(port, MSG_SD_CANT_OPEN_SUBDIR);
  110. SERIAL_ECHOLN_P(port, lfilename);
  111. }
  112. }
  113. lsDive(path, dir
  114. #if NUM_SERIAL > 1
  115. , NULL, port
  116. #endif
  117. );
  118. // close() is done automatically by destructor of SdFile
  119. }
  120. else {
  121. uint8_t pn0 = p.name[0];
  122. if (pn0 == DIR_NAME_FREE) break;
  123. if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue;
  124. if (longFilename[0] == '.') continue;
  125. if (!DIR_IS_FILE_OR_SUBDIR(&p) || (p.attributes & DIR_ATT_HIDDEN)) continue;
  126. filenameIsDir = DIR_IS_SUBDIR(&p);
  127. if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue;
  128. switch (lsAction) { // 1 based file count
  129. case LS_Count:
  130. nrFiles++;
  131. break;
  132. case LS_SerialPrint:
  133. createFilename(filename, p);
  134. if (prepend) SERIAL_PROTOCOL_P(port, prepend);
  135. SERIAL_PROTOCOL_P(port, filename);
  136. SERIAL_PROTOCOLCHAR_P(port, ' ');
  137. SERIAL_PROTOCOLLN_P(port, p.fileSize);
  138. break;
  139. case LS_GetFilename:
  140. createFilename(filename, p);
  141. if (match != NULL) {
  142. if (strcasecmp(match, filename) == 0) return;
  143. }
  144. else if (cnt == nrFile_index) return; // 0 based index
  145. cnt++;
  146. break;
  147. }
  148. }
  149. } // while readDir
  150. }
  151. void CardReader::ls(
  152. #if NUM_SERIAL > 1
  153. const int8_t port
  154. #endif
  155. ) {
  156. lsAction = LS_SerialPrint;
  157. root.rewind();
  158. lsDive(NULL, root
  159. #if NUM_SERIAL > 1
  160. , NULL, port
  161. #endif
  162. );
  163. }
  164. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  165. /**
  166. * Get a long pretty path based on a DOS 8.3 path
  167. */
  168. void CardReader::printLongPath(char *path
  169. #if NUM_SERIAL > 1
  170. , const int8_t port/*= -1*/
  171. #endif
  172. ) {
  173. lsAction = LS_GetFilename;
  174. int i, pathLen = strlen(path);
  175. // SERIAL_ECHOPGM_P(port, "Full Path: "); SERIAL_ECHOLN_P(port, path);
  176. // Zero out slashes to make segments
  177. for (i = 0; i < pathLen; i++) if (path[i] == '/') path[i] = '\0';
  178. SdFile diveDir = root; // start from the root for segment 1
  179. for (i = 0; i < pathLen;) {
  180. if (path[i] == '\0') i++; // move past a single nul
  181. char *segment = &path[i]; // The segment after most slashes
  182. // If a segment is empty (extra-slash) then exit
  183. if (!*segment) break;
  184. // Go to the next segment
  185. while (path[++i]) { }
  186. // SERIAL_ECHOPGM_P(port, "Looking for segment: "); SERIAL_ECHOLN_P(port, segment);
  187. // Find the item, setting the long filename
  188. diveDir.rewind();
  189. lsDive(NULL, diveDir, segment
  190. #if NUM_SERIAL > 1
  191. , port
  192. #endif
  193. );
  194. // Print /LongNamePart to serial output
  195. SERIAL_PROTOCOLCHAR_P(port, '/');
  196. SERIAL_PROTOCOL_P(port, longFilename[0] ? longFilename : "???");
  197. // If the filename was printed then that's it
  198. if (!filenameIsDir) break;
  199. // SERIAL_ECHOPGM_P(port, "Opening dir: "); SERIAL_ECHOLN_P(port, segment);
  200. // Open the sub-item as the new dive parent
  201. SdFile dir;
  202. if (!dir.open(diveDir, segment, O_READ)) {
  203. SERIAL_EOL_P(port);
  204. SERIAL_ECHO_START_P(port);
  205. SERIAL_ECHOPGM_P(port, MSG_SD_CANT_OPEN_SUBDIR);
  206. SERIAL_ECHO_P(port, segment);
  207. break;
  208. }
  209. diveDir.close();
  210. diveDir = dir;
  211. } // while i<pathLen
  212. SERIAL_EOL_P(port);
  213. }
  214. #endif // LONG_FILENAME_HOST_SUPPORT
  215. /**
  216. * Echo the DOS 8.3 filename (and long filename, if any)
  217. */
  218. void CardReader::printFilename(
  219. #if NUM_SERIAL > 1
  220. const int8_t port/*= -1*/
  221. #endif
  222. ) {
  223. if (file.isOpen()) {
  224. char lfilename[FILENAME_LENGTH];
  225. file.getFilename(lfilename);
  226. SERIAL_ECHO_P(port, lfilename);
  227. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  228. getfilename(0, lfilename);
  229. if (longFilename[0]) {
  230. SERIAL_ECHO_P(port, ' ');
  231. SERIAL_ECHO_P(port, longFilename);
  232. }
  233. #endif
  234. }
  235. else
  236. SERIAL_ECHOPGM_P(port, "(no file)");
  237. SERIAL_EOL_P(port);
  238. }
  239. void CardReader::initsd() {
  240. cardOK = false;
  241. if (root.isOpen()) root.close();
  242. #ifndef SPI_SPEED
  243. #define SPI_SPEED SPI_FULL_SPEED
  244. #endif
  245. if (!card.init(SPI_SPEED, SDSS)
  246. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  247. && !card.init(SPI_SPEED, LCD_SDSS)
  248. #endif
  249. ) {
  250. //if (!card.init(SPI_HALF_SPEED,SDSS))
  251. SERIAL_ECHO_START();
  252. SERIAL_ECHOLNPGM(MSG_SD_INIT_FAIL);
  253. }
  254. else if (!volume.init(&card)) {
  255. SERIAL_ERROR_START();
  256. SERIAL_ERRORLNPGM(MSG_SD_VOL_INIT_FAIL);
  257. }
  258. else if (!root.openRoot(&volume)) {
  259. SERIAL_ERROR_START();
  260. SERIAL_ERRORLNPGM(MSG_SD_OPENROOT_FAIL);
  261. }
  262. else {
  263. cardOK = true;
  264. SERIAL_ECHO_START();
  265. SERIAL_ECHOLNPGM(MSG_SD_CARD_OK);
  266. }
  267. setroot();
  268. }
  269. void CardReader::setroot() {
  270. /*if (!workDir.openRoot(&volume)) {
  271. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  272. }*/
  273. workDir = root;
  274. curDir = &workDir;
  275. #if ENABLED(SDCARD_SORT_ALPHA)
  276. presort();
  277. #endif
  278. }
  279. void CardReader::release() {
  280. sdprinting = false;
  281. cardOK = false;
  282. }
  283. void CardReader::openAndPrintFile(const char *name) {
  284. char cmd[4 + strlen(name) + 1]; // Room for "M23 ", filename, and null
  285. sprintf_P(cmd, PSTR("M23 %s"), name);
  286. for (char *c = &cmd[4]; *c; c++) *c = tolower(*c);
  287. enqueue_and_echo_command_now(cmd);
  288. enqueue_and_echo_commands_P(PSTR("M24"));
  289. }
  290. void CardReader::startFileprint() {
  291. if (cardOK) {
  292. sdprinting = true;
  293. #if SD_RESORT
  294. flush_presort();
  295. #endif
  296. }
  297. }
  298. void CardReader::stopSDPrint(
  299. #if SD_RESORT
  300. const bool re_sort/*=false*/
  301. #endif
  302. ) {
  303. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  304. did_pause_print = 0;
  305. #endif
  306. sdprinting = false;
  307. if (isFileOpen()) file.close();
  308. #if SD_RESORT
  309. if (re_sort) presort();
  310. #endif
  311. }
  312. void CardReader::openLogFile(char* name) {
  313. logging = true;
  314. openFile(name, false);
  315. }
  316. void appendAtom(SdFile &file, char *& dst, uint8_t &cnt) {
  317. file.getFilename(dst);
  318. while (*dst && cnt < MAXPATHNAMELENGTH) { dst++; cnt++; }
  319. if (cnt < MAXPATHNAMELENGTH) { *dst = '/'; dst++; cnt++; }
  320. }
  321. void CardReader::getAbsFilename(char *t) {
  322. *t++ = '/'; // Root folder
  323. uint8_t cnt = 1;
  324. for (uint8_t i = 0; i < workDirDepth; i++) // Loop to current work dir
  325. appendAtom(workDirParents[i], t, cnt);
  326. if (cnt < MAXPATHNAMELENGTH - (FILENAME_LENGTH)) {
  327. appendAtom(file, t, cnt);
  328. --t;
  329. }
  330. *t = '\0';
  331. }
  332. void CardReader::openFile(char* name, const bool read, const bool subcall/*=false*/) {
  333. if (!cardOK) return;
  334. uint8_t doing = 0;
  335. if (isFileOpen()) { // Replacing current file or doing a subroutine
  336. if (subcall) {
  337. if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) {
  338. SERIAL_ERROR_START();
  339. SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  340. SERIAL_ERRORLN((int)SD_PROCEDURE_DEPTH);
  341. kill(PSTR(MSG_KILLED));
  342. return;
  343. }
  344. // Store current filename (based on workDirParents) and position
  345. getAbsFilename(proc_filenames[file_subcall_ctr]);
  346. filespos[file_subcall_ctr] = sdpos;
  347. SERIAL_ECHO_START();
  348. SERIAL_ECHOPAIR("SUBROUTINE CALL target:\"", name);
  349. SERIAL_ECHOPAIR("\" parent:\"", proc_filenames[file_subcall_ctr]);
  350. SERIAL_ECHOLNPAIR("\" pos", sdpos);
  351. file_subcall_ctr++;
  352. }
  353. else
  354. doing = 1;
  355. }
  356. else if (subcall) { // Returning from a subcall?
  357. SERIAL_ECHO_START();
  358. SERIAL_ECHOLNPGM("END SUBROUTINE");
  359. }
  360. else { // Opening fresh file
  361. doing = 2;
  362. file_subcall_ctr = 0; // Reset procedure depth in case user cancels print while in procedure
  363. }
  364. if (doing) {
  365. SERIAL_ECHO_START();
  366. SERIAL_ECHOPGM("Now ");
  367. serialprintPGM(doing == 1 ? PSTR("doing") : PSTR("fresh"));
  368. SERIAL_ECHOLNPAIR(" file: ", name);
  369. }
  370. stopSDPrint();
  371. SdFile myDir;
  372. curDir = &root;
  373. char *fname = name;
  374. char *dirname_start, *dirname_end;
  375. if (name[0] == '/') {
  376. dirname_start = &name[1];
  377. while (dirname_start != NULL) {
  378. dirname_end = strchr(dirname_start, '/');
  379. //SERIAL_ECHOPGM("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  380. //SERIAL_ECHOPGM("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  381. if (dirname_end != NULL && dirname_end > dirname_start) {
  382. char subdirname[FILENAME_LENGTH];
  383. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  384. subdirname[dirname_end - dirname_start] = '\0';
  385. if (!myDir.open(curDir, subdirname, O_READ)) {
  386. SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL);
  387. SERIAL_PROTOCOL(subdirname);
  388. SERIAL_PROTOCOLCHAR('.');
  389. return;
  390. }
  391. else {
  392. //SERIAL_ECHOLNPGM("dive ok");
  393. }
  394. curDir = &myDir;
  395. dirname_start = dirname_end + 1;
  396. }
  397. else { // the remainder after all /fsa/fdsa/ is the filename
  398. fname = dirname_start;
  399. //SERIAL_ECHOLNPGM("remainder");
  400. //SERIAL_ECHOLN(fname);
  401. break;
  402. }
  403. }
  404. }
  405. else
  406. curDir = &workDir; // Relative paths start in current directory
  407. if (read) {
  408. if (file.open(curDir, fname, O_READ)) {
  409. filesize = file.fileSize();
  410. sdpos = 0;
  411. SERIAL_PROTOCOLPAIR(MSG_SD_FILE_OPENED, fname);
  412. SERIAL_PROTOCOLLNPAIR(MSG_SD_SIZE, filesize);
  413. SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED);
  414. getfilename(0, fname);
  415. lcd_setstatus(longFilename[0] ? longFilename : fname);
  416. //if (longFilename[0]) {
  417. // SERIAL_PROTOCOLPAIR(MSG_SD_FILE_LONG_NAME, longFilename);
  418. //}
  419. }
  420. else {
  421. SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, fname);
  422. SERIAL_PROTOCOLCHAR('.');
  423. SERIAL_EOL();
  424. }
  425. }
  426. else { //write
  427. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) {
  428. SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, fname);
  429. SERIAL_PROTOCOLCHAR('.');
  430. SERIAL_EOL();
  431. }
  432. else {
  433. saving = true;
  434. SERIAL_PROTOCOLLNPAIR(MSG_SD_WRITE_TO_FILE, name);
  435. lcd_setstatus(fname);
  436. }
  437. }
  438. }
  439. void CardReader::removeFile(const char * const name) {
  440. if (!cardOK) return;
  441. stopSDPrint();
  442. SdFile myDir;
  443. curDir = &root;
  444. const char *fname = name;
  445. char *dirname_start, *dirname_end;
  446. if (name[0] == '/') {
  447. dirname_start = strchr(name, '/') + 1;
  448. while (dirname_start != NULL) {
  449. dirname_end = strchr(dirname_start, '/');
  450. //SERIAL_ECHOPGM("start:");SERIAL_ECHOLN((int)(dirname_start - name));
  451. //SERIAL_ECHOPGM("end :");SERIAL_ECHOLN((int)(dirname_end - name));
  452. if (dirname_end != NULL && dirname_end > dirname_start) {
  453. char subdirname[FILENAME_LENGTH];
  454. strncpy(subdirname, dirname_start, dirname_end - dirname_start);
  455. subdirname[dirname_end - dirname_start] = 0;
  456. SERIAL_ECHOLN(subdirname);
  457. if (!myDir.open(curDir, subdirname, O_READ)) {
  458. SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, subdirname);
  459. SERIAL_PROTOCOLCHAR('.');
  460. SERIAL_EOL();
  461. return;
  462. }
  463. curDir = &myDir;
  464. dirname_start = dirname_end + 1;
  465. }
  466. else {
  467. fname = dirname_start;
  468. break;
  469. }
  470. }
  471. }
  472. else // Relative paths are rooted in the current directory
  473. curDir = &workDir;
  474. if (file.remove(curDir, fname)) {
  475. SERIAL_PROTOCOLPGM("File deleted:");
  476. SERIAL_PROTOCOLLN(fname);
  477. sdpos = 0;
  478. #if ENABLED(SDCARD_SORT_ALPHA)
  479. presort();
  480. #endif
  481. }
  482. else {
  483. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  484. SERIAL_PROTOCOL(fname);
  485. SERIAL_PROTOCOLCHAR('.');
  486. }
  487. }
  488. void CardReader::getStatus(
  489. #if NUM_SERIAL > 1
  490. const int8_t port/*= -1*/
  491. #endif
  492. ) {
  493. if (cardOK && sdprinting) {
  494. SERIAL_PROTOCOLPGM_P(port, MSG_SD_PRINTING_BYTE);
  495. SERIAL_PROTOCOL_P(port, sdpos);
  496. SERIAL_PROTOCOLCHAR_P(port, '/');
  497. SERIAL_PROTOCOLLN_P(port, filesize);
  498. }
  499. else
  500. SERIAL_PROTOCOLLNPGM_P(port, MSG_SD_NOT_PRINTING);
  501. }
  502. void CardReader::write_command(char *buf) {
  503. char* begin = buf;
  504. char* npos = NULL;
  505. char* end = buf + strlen(buf) - 1;
  506. file.writeError = false;
  507. if ((npos = strchr(buf, 'N')) != NULL) {
  508. begin = strchr(npos, ' ') + 1;
  509. end = strchr(npos, '*') - 1;
  510. }
  511. end[1] = '\r';
  512. end[2] = '\n';
  513. end[3] = '\0';
  514. file.write(begin);
  515. if (file.writeError) {
  516. SERIAL_ERROR_START();
  517. SERIAL_ERRORLNPGM(MSG_SD_ERR_WRITE_TO_FILE);
  518. }
  519. }
  520. //
  521. // Run the next autostart file. Called:
  522. // - On boot after successful card init
  523. // - After finishing the previous autostart file
  524. // - From the LCD command to run the autostart file
  525. //
  526. void CardReader::checkautostart() {
  527. if (autostart_index < 0 || sdprinting) return;
  528. if (!cardOK) initsd();
  529. if (cardOK) {
  530. char autoname[10];
  531. sprintf_P(autoname, PSTR("auto%i.g"), autostart_index);
  532. dir_t p;
  533. root.rewind();
  534. while (root.readDir(p, NULL) > 0) {
  535. for (int8_t i = (int8_t)strlen((char*)p.name); i--;) p.name[i] = tolower(p.name[i]);
  536. if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) {
  537. openAndPrintFile(autoname);
  538. autostart_index++;
  539. return;
  540. }
  541. }
  542. }
  543. autostart_index = -1;
  544. }
  545. void CardReader::beginautostart() {
  546. autostart_index = 0;
  547. setroot();
  548. }
  549. void CardReader::closefile(const bool store_location) {
  550. file.sync();
  551. file.close();
  552. saving = logging = false;
  553. if (store_location) {
  554. //future: store printer state, filename and position for continuing a stopped print
  555. // so one can unplug the printer and continue printing the next day.
  556. }
  557. }
  558. /**
  559. * Get the name of a file in the current directory by index
  560. */
  561. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/) {
  562. #if ENABLED(SDSORT_CACHE_NAMES)
  563. if (match != NULL) {
  564. while (nr < sort_count) {
  565. if (strcasecmp(match, sortshort[nr]) == 0) break;
  566. nr++;
  567. }
  568. }
  569. if (nr < sort_count) {
  570. strcpy(filename, sortshort[nr]);
  571. strcpy(longFilename, sortnames[nr]);
  572. filenameIsDir = TEST(isDir[nr>>3], nr & 0x07);
  573. return;
  574. }
  575. #endif // SDSORT_CACHE_NAMES
  576. curDir = &workDir;
  577. lsAction = LS_GetFilename;
  578. nrFile_index = nr;
  579. curDir->rewind();
  580. lsDive(NULL, *curDir, match);
  581. }
  582. uint16_t CardReader::getnrfilenames() {
  583. curDir = &workDir;
  584. lsAction = LS_Count;
  585. nrFiles = 0;
  586. curDir->rewind();
  587. lsDive(NULL, *curDir);
  588. //SERIAL_ECHOLN(nrFiles);
  589. return nrFiles;
  590. }
  591. void CardReader::chdir(const char * relpath) {
  592. SdFile newDir;
  593. SdFile *parent = &root;
  594. if (workDir.isOpen()) parent = &workDir;
  595. if (!newDir.open(*parent, relpath, O_READ)) {
  596. SERIAL_ECHO_START();
  597. SERIAL_ECHOPGM(MSG_SD_CANT_ENTER_SUBDIR);
  598. SERIAL_ECHOLN(relpath);
  599. }
  600. else {
  601. workDir = newDir;
  602. if (workDirDepth < MAX_DIR_DEPTH)
  603. workDirParents[workDirDepth++] = workDir;
  604. #if ENABLED(SDCARD_SORT_ALPHA)
  605. presort();
  606. #endif
  607. }
  608. }
  609. int8_t CardReader::updir() {
  610. if (workDirDepth > 0) { // At least 1 dir has been saved
  611. workDir = --workDirDepth ? workDirParents[workDirDepth - 1] : root; // Use parent, or root if none
  612. #if ENABLED(SDCARD_SORT_ALPHA)
  613. presort();
  614. #endif
  615. }
  616. return workDirDepth;
  617. }
  618. #if ENABLED(SDCARD_SORT_ALPHA)
  619. /**
  620. * Get the name of a file in the current directory by sort-index
  621. */
  622. void CardReader::getfilename_sorted(const uint16_t nr) {
  623. getfilename(
  624. #if ENABLED(SDSORT_GCODE)
  625. sort_alpha &&
  626. #endif
  627. (nr < sort_count) ? sort_order[nr] : nr
  628. );
  629. }
  630. /**
  631. * Read all the files and produce a sort key
  632. *
  633. * We can do this in 3 ways...
  634. * - Minimal RAM: Read two filenames at a time sorting along...
  635. * - Some RAM: Buffer the directory just for this sort
  636. * - Most RAM: Buffer the directory and return filenames from RAM
  637. */
  638. void CardReader::presort() {
  639. // Throw away old sort index
  640. flush_presort();
  641. // Sorting may be turned off
  642. #if ENABLED(SDSORT_GCODE)
  643. if (!sort_alpha) return;
  644. #endif
  645. // If there are files, sort up to the limit
  646. uint16_t fileCnt = getnrfilenames();
  647. if (fileCnt > 0) {
  648. // Never sort more than the max allowed
  649. // If you use folders to organize, 20 may be enough
  650. if (fileCnt > SDSORT_LIMIT) fileCnt = SDSORT_LIMIT;
  651. // Sort order is always needed. May be static or dynamic.
  652. #if ENABLED(SDSORT_DYNAMIC_RAM)
  653. sort_order = new uint8_t[fileCnt];
  654. #endif
  655. // Use RAM to store the entire directory during pre-sort.
  656. // SDSORT_LIMIT should be set to prevent over-allocation.
  657. #if ENABLED(SDSORT_USES_RAM)
  658. // If using dynamic ram for names, allocate on the heap.
  659. #if ENABLED(SDSORT_CACHE_NAMES)
  660. #if ENABLED(SDSORT_DYNAMIC_RAM)
  661. sortshort = new char*[fileCnt];
  662. sortnames = new char*[fileCnt];
  663. #endif
  664. #elif ENABLED(SDSORT_USES_STACK)
  665. char sortnames[fileCnt][SORTED_LONGNAME_MAXLEN];
  666. #endif
  667. // Folder sorting needs 1 bit per entry for flags.
  668. #if HAS_FOLDER_SORTING
  669. #if ENABLED(SDSORT_DYNAMIC_RAM)
  670. isDir = new uint8_t[(fileCnt + 7) >> 3];
  671. #elif ENABLED(SDSORT_USES_STACK)
  672. uint8_t isDir[(fileCnt + 7) >> 3];
  673. #endif
  674. #endif
  675. #else // !SDSORT_USES_RAM
  676. // By default re-read the names from SD for every compare
  677. // retaining only two filenames at a time. This is very
  678. // slow but is safest and uses minimal RAM.
  679. char name1[LONG_FILENAME_LENGTH + 1];
  680. #endif
  681. if (fileCnt > 1) {
  682. // Init sort order.
  683. for (uint16_t i = 0; i < fileCnt; i++) {
  684. sort_order[i] = i;
  685. // If using RAM then read all filenames now.
  686. #if ENABLED(SDSORT_USES_RAM)
  687. getfilename(i);
  688. #if ENABLED(SDSORT_DYNAMIC_RAM)
  689. // Use dynamic method to copy long filename
  690. sortnames[i] = strdup(LONGEST_FILENAME);
  691. #if ENABLED(SDSORT_CACHE_NAMES)
  692. // When caching also store the short name, since
  693. // we're replacing the getfilename() behavior.
  694. sortshort[i] = strdup(filename);
  695. #endif
  696. #else
  697. // Copy filenames into the static array
  698. #if SORTED_LONGNAME_MAXLEN != LONG_FILENAME_LENGTH
  699. strncpy(sortnames[i], LONGEST_FILENAME, SORTED_LONGNAME_MAXLEN);
  700. sortnames[i][SORTED_LONGNAME_MAXLEN - 1] = '\0';
  701. #else
  702. strncpy(sortnames[i], LONGEST_FILENAME, SORTED_LONGNAME_MAXLEN);
  703. #endif
  704. #if ENABLED(SDSORT_CACHE_NAMES)
  705. strcpy(sortshort[i], filename);
  706. #endif
  707. #endif
  708. // char out[30];
  709. // sprintf_P(out, PSTR("---- %i %s %s"), i, filenameIsDir ? "D" : " ", sortnames[i]);
  710. // SERIAL_ECHOLN(out);
  711. #if HAS_FOLDER_SORTING
  712. const uint16_t bit = i & 0x07, ind = i >> 3;
  713. if (bit == 0) isDir[ind] = 0x00;
  714. if (filenameIsDir) isDir[ind] |= _BV(bit);
  715. #endif
  716. #endif
  717. }
  718. // Bubble Sort
  719. for (uint16_t i = fileCnt; --i;) {
  720. bool didSwap = false;
  721. for (uint16_t j = 0; j < i; ++j) {
  722. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  723. // Compare names from the array or just the two buffered names
  724. #if ENABLED(SDSORT_USES_RAM)
  725. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  726. #else
  727. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0)
  728. #endif
  729. #if HAS_FOLDER_SORTING
  730. #if ENABLED(SDSORT_USES_RAM)
  731. // Folder sorting needs an index and bit to test for folder-ness.
  732. const uint8_t ind1 = o1 >> 3, bit1 = o1 & 0x07,
  733. ind2 = o2 >> 3, bit2 = o2 & 0x07;
  734. #define _SORT_CMP_DIR(fs) \
  735. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  736. ? _SORT_CMP_NODIR() \
  737. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  738. #else
  739. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  740. #endif
  741. #endif
  742. // The most economical method reads names as-needed
  743. // throughout the loop. Slow if there are many.
  744. #if DISABLED(SDSORT_USES_RAM)
  745. getfilename(o1);
  746. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  747. #if HAS_FOLDER_SORTING
  748. bool dir1 = filenameIsDir;
  749. #endif
  750. getfilename(o2);
  751. char *name2 = LONGEST_FILENAME; // use the string in-place
  752. #endif // !SDSORT_USES_RAM
  753. // Sort the current pair according to settings.
  754. if (
  755. #if HAS_FOLDER_SORTING
  756. #if ENABLED(SDSORT_GCODE)
  757. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  758. #else
  759. _SORT_CMP_DIR(FOLDER_SORTING)
  760. #endif
  761. #else
  762. _SORT_CMP_NODIR()
  763. #endif
  764. ) {
  765. sort_order[j] = o2;
  766. sort_order[j + 1] = o1;
  767. didSwap = true;
  768. }
  769. }
  770. if (!didSwap) break;
  771. }
  772. // Using RAM but not keeping names around
  773. #if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_CACHE_NAMES)
  774. #if ENABLED(SDSORT_DYNAMIC_RAM)
  775. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  776. #if HAS_FOLDER_SORTING
  777. free(isDir);
  778. #endif
  779. #endif
  780. #endif
  781. }
  782. else {
  783. sort_order[0] = 0;
  784. #if ENABLED(SDSORT_USES_RAM) && ENABLED(SDSORT_CACHE_NAMES)
  785. getfilename(0);
  786. #if ENABLED(SDSORT_DYNAMIC_RAM)
  787. sortnames = new char*[1];
  788. sortnames[0] = strdup(LONGEST_FILENAME); // malloc
  789. #if ENABLED(SDSORT_CACHE_NAMES)
  790. sortshort = new char*[1];
  791. sortshort[0] = strdup(filename); // malloc
  792. #endif
  793. isDir = new uint8_t[1];
  794. #else
  795. #if SORTED_LONGNAME_MAXLEN != LONG_FILENAME_LENGTH
  796. strncpy(sortnames[0], LONGEST_FILENAME, SORTED_LONGNAME_MAXLEN);
  797. sortnames[0][SORTED_LONGNAME_MAXLEN - 1] = '\0';
  798. #else
  799. strncpy(sortnames[0], LONGEST_FILENAME, SORTED_LONGNAME_MAXLEN);
  800. #endif
  801. #if ENABLED(SDSORT_CACHE_NAMES)
  802. strcpy(sortshort[0], filename);
  803. #endif
  804. #endif
  805. isDir[0] = filenameIsDir ? 0x01 : 0x00;
  806. #endif
  807. }
  808. sort_count = fileCnt;
  809. }
  810. }
  811. void CardReader::flush_presort() {
  812. if (sort_count > 0) {
  813. #if ENABLED(SDSORT_DYNAMIC_RAM)
  814. delete sort_order;
  815. #if ENABLED(SDSORT_CACHE_NAMES)
  816. for (uint8_t i = 0; i < sort_count; ++i) {
  817. free(sortshort[i]); // strdup
  818. free(sortnames[i]); // strdup
  819. }
  820. delete sortshort;
  821. delete sortnames;
  822. #endif
  823. #endif
  824. sort_count = 0;
  825. }
  826. }
  827. #endif // SDCARD_SORT_ALPHA
  828. uint16_t CardReader::get_num_Files() {
  829. return
  830. #if ENABLED(SDCARD_SORT_ALPHA) && SDSORT_USES_RAM && SDSORT_CACHE_NAMES
  831. nrFiles // no need to access the SD card for filenames
  832. #else
  833. getnrfilenames()
  834. #endif
  835. ;
  836. }
  837. void CardReader::printingHasFinished() {
  838. planner.synchronize();
  839. file.close();
  840. if (file_subcall_ctr > 0) { // Heading up to a parent file that called current as a procedure.
  841. file_subcall_ctr--;
  842. openFile(proc_filenames[file_subcall_ctr], true, true);
  843. setIndex(filespos[file_subcall_ctr]);
  844. startFileprint();
  845. }
  846. else {
  847. sdprinting = false;
  848. #if ENABLED(POWER_LOSS_RECOVERY)
  849. openJobRecoveryFile(false);
  850. job_recovery_info.valid_head = job_recovery_info.valid_foot = 0;
  851. (void)saveJobRecoveryInfo();
  852. closeJobRecoveryFile();
  853. job_recovery_commands_count = 0;
  854. #endif
  855. #if ENABLED(SD_FINISHED_STEPPERRELEASE) && defined(SD_FINISHED_RELEASECOMMAND)
  856. planner.finish_and_disable();
  857. #endif
  858. print_job_timer.stop();
  859. if (print_job_timer.duration() > 60)
  860. enqueue_and_echo_commands_P(PSTR("M31"));
  861. #if ENABLED(SDCARD_SORT_ALPHA)
  862. presort();
  863. #endif
  864. #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY)
  865. progress_bar_percent = 0;
  866. #endif
  867. #if ENABLED(SD_REPRINT_LAST_SELECTED_FILE)
  868. lcd_reselect_last_file();
  869. #endif
  870. }
  871. }
  872. #if ENABLED(AUTO_REPORT_SD_STATUS)
  873. uint8_t CardReader::auto_report_sd_interval = 0;
  874. millis_t CardReader::next_sd_report_ms;
  875. #if NUM_SERIAL > 1
  876. int8_t CardReader::serialport;
  877. #endif
  878. void CardReader::auto_report_sd_status() {
  879. millis_t current_ms = millis();
  880. if (auto_report_sd_interval && ELAPSED(current_ms, next_sd_report_ms)) {
  881. next_sd_report_ms = current_ms + 1000UL * auto_report_sd_interval;
  882. getStatus(
  883. #if NUM_SERIAL > 1
  884. serialport
  885. #endif
  886. );
  887. }
  888. }
  889. #endif // AUTO_REPORT_SD_STATUS
  890. #if ENABLED(POWER_LOSS_RECOVERY)
  891. char job_recovery_file_name[4] = "bin";
  892. void CardReader::openJobRecoveryFile(const bool read) {
  893. if (!cardOK) return;
  894. if (jobRecoveryFile.isOpen()) return;
  895. if (!jobRecoveryFile.open(&root, job_recovery_file_name, read ? O_READ : O_CREAT | O_WRITE | O_TRUNC | O_SYNC)) {
  896. SERIAL_PROTOCOLPAIR(MSG_SD_OPEN_FILE_FAIL, job_recovery_file_name);
  897. SERIAL_PROTOCOLCHAR('.');
  898. SERIAL_EOL();
  899. }
  900. else
  901. SERIAL_PROTOCOLLNPAIR(MSG_SD_WRITE_TO_FILE, job_recovery_file_name);
  902. }
  903. void CardReader::closeJobRecoveryFile() { jobRecoveryFile.close(); }
  904. bool CardReader::jobRecoverFileExists() {
  905. return jobRecoveryFile.open(&root, job_recovery_file_name, O_READ);
  906. }
  907. int16_t CardReader::saveJobRecoveryInfo() {
  908. jobRecoveryFile.seekSet(0);
  909. const int16_t ret = jobRecoveryFile.write(&job_recovery_info, sizeof(job_recovery_info));
  910. if (ret == -1) SERIAL_PROTOCOLLNPGM("Power-loss file write failed.");
  911. return ret;
  912. }
  913. int16_t CardReader::loadJobRecoveryInfo() {
  914. return jobRecoveryFile.read(&job_recovery_info, sizeof(job_recovery_info));
  915. }
  916. void CardReader::removeJobRecoveryFile() {
  917. if (jobRecoveryFile.remove(&root, job_recovery_file_name))
  918. SERIAL_PROTOCOLLNPGM("Power-loss file deleted.");
  919. else
  920. SERIAL_PROTOCOLLNPGM("Power-loss file delete failed.");
  921. }
  922. #endif // POWER_LOSS_RECOVERY
  923. #endif // SDSUPPORT