cardreader.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. #include "Marlin.h"
  2. #include "cmdqueue.h"
  3. #include "cardreader.h"
  4. #include "ultralcd.h"
  5. #include "stepper.h"
  6. #include "temperature.h"
  7. #include "language.h"
  8. #ifdef SDSUPPORT
  9. #define LONGEST_FILENAME (longFilename[0] ? longFilename : filename)
  10. CardReader::CardReader()
  11. {
  12. #ifdef SDCARD_SORT_ALPHA
  13. sort_count = 0;
  14. #endif
  15. filesize = 0;
  16. sdpos = 0;
  17. sdprinting = false;
  18. cardOK = false;
  19. saving = false;
  20. logging = false;
  21. autostart_atmillis=0;
  22. workDirDepth = 0;
  23. file_subcall_ctr=0;
  24. memset(workDirParents, 0, sizeof(workDirParents));
  25. presort_flag = false;
  26. autostart_stilltocheck=true; //the SD start is delayed, because otherwise the serial cannot answer fast enough to make contact with the host software.
  27. lastnr=0;
  28. //power to SD reader
  29. #if SDPOWER > -1
  30. SET_OUTPUT(SDPOWER);
  31. WRITE(SDPOWER,HIGH);
  32. #endif //SDPOWER
  33. autostart_atmillis=_millis()+5000;
  34. }
  35. char *createFilename(char *buffer,const dir_t &p) //buffer>12characters
  36. {
  37. char *pos=buffer;
  38. for (uint8_t i = 0; i < 11; i++)
  39. {
  40. if (p.name[i] == ' ')continue;
  41. if (i == 8)
  42. {
  43. *pos++='.';
  44. }
  45. *pos++=p.name[i];
  46. }
  47. *pos++=0;
  48. return buffer;
  49. }
  50. /**
  51. +* Dive into a folder and recurse depth-first to perform a pre-set operation lsAction:
  52. +* LS_Count - Add +1 to nrFiles for every file within the parent
  53. +* LS_GetFilename - Get the filename of the file indexed by nrFiles
  54. +* LS_SerialPrint - Print the full path and size of each file to serial output
  55. +* LS_SerialPrint_LFN - Print the full path, long filename and size of each file to serial output
  56. +*/
  57. void CardReader::lsDive(const char *prepend, SdFile parent, const char * const match/*=NULL*/) {
  58. static uint8_t recursionCnt = 0;
  59. // RAII incrementer for the recursionCnt
  60. class _incrementer
  61. {
  62. public:
  63. _incrementer() {recursionCnt++;}
  64. ~_incrementer() {recursionCnt--;}
  65. } recursionCntIncrementer;
  66. dir_t p;
  67. uint8_t cnt = 0;
  68. // Read the next entry from a directory
  69. for (position = parent.curPosition(); parent.readDir(p, longFilename) > 0; position = parent.curPosition()) {
  70. if (recursionCnt > MAX_DIR_DEPTH)
  71. return;
  72. uint8_t pn0 = p.name[0];
  73. if (pn0 == DIR_NAME_FREE) break;
  74. if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue;
  75. if (longFilename[0] == '.') continue;
  76. if (!DIR_IS_FILE_OR_SUBDIR(&p) || (p.attributes & DIR_ATT_HIDDEN)) continue;
  77. else if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) { // If the entry is a directory and the action is LS_SerialPrint
  78. // Get the short name for the item, which we know is a folder
  79. char lfilename[FILENAME_LENGTH];
  80. createFilename(lfilename, p);
  81. // Allocate enough stack space for the full path to a folder, trailing slash, and nul
  82. bool prepend_is_empty = (prepend[0] == '\0');
  83. int len = (prepend_is_empty ? 1 : strlen(prepend)) + strlen(lfilename) + 1 + 1;
  84. char path[len];
  85. // Append the FOLDERNAME12/ to the passed string.
  86. // It contains the full path to the "parent" argument.
  87. // We now have the full path to the item in this folder.
  88. strcpy(path, prepend_is_empty ? "/" : prepend); // root slash if prepend is empty
  89. strcat(path, lfilename); // FILENAME_LENGTH-1 characters maximum
  90. strcat(path, "/"); // 1 character
  91. // Serial.print(path);
  92. // Get a new directory object using the full path
  93. // and dive recursively into it.
  94. if (lsAction == LS_SerialPrint_LFN)
  95. printf_P(PSTR("DIR_ENTER: %s \"%s\"\n"), path, longFilename[0] ? longFilename : lfilename);
  96. SdFile dir;
  97. if (!dir.open(parent, lfilename, O_READ)) {
  98. if (lsAction == LS_SerialPrint || lsAction == LS_SerialPrint_LFN) {
  99. //SERIAL_ECHO_START();
  100. //SERIAL_ECHOPGM(_i("Cannot open subdir"));////MSG_SD_CANT_OPEN_SUBDIR
  101. //SERIAL_ECHOLN(lfilename);
  102. }
  103. }
  104. lsDive(path, dir);
  105. // close() is done automatically by destructor of SdFile
  106. if (lsAction == LS_SerialPrint_LFN)
  107. puts_P(PSTR("DIR_EXIT"));
  108. }
  109. else {
  110. filenameIsDir = DIR_IS_SUBDIR(&p);
  111. if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue;
  112. switch (lsAction) {
  113. case LS_Count:
  114. nrFiles++;
  115. break;
  116. case LS_SerialPrint_LFN:
  117. case LS_SerialPrint:
  118. createFilename(filename, p);
  119. SERIAL_PROTOCOL(prepend);
  120. SERIAL_PROTOCOL(filename);
  121. MYSERIAL.write(' ');
  122. SERIAL_PROTOCOL(p.fileSize);
  123. if (lsAction == LS_SerialPrint_LFN)
  124. printf_P(PSTR(" \"%s\""), LONGEST_FILENAME);
  125. SERIAL_PROTOCOLLN();
  126. manage_heater();
  127. break;
  128. case LS_GetFilename:
  129. //SERIAL_ECHOPGM("File: ");
  130. createFilename(filename, p);
  131. // cluster = parent.curCluster();
  132. // position = parent.curPosition();
  133. /*MYSERIAL.println(filename);
  134. SERIAL_ECHOPGM("Write date: ");
  135. writeDate = p.lastWriteDate;
  136. MYSERIAL.println(writeDate);
  137. writeTime = p.lastWriteTime;
  138. SERIAL_ECHOPGM("Creation date: ");
  139. MYSERIAL.println(p.creationDate);
  140. SERIAL_ECHOPGM("Access date: ");
  141. MYSERIAL.println(p.lastAccessDate);
  142. SERIAL_ECHOLNPGM("");*/
  143. crmodDate = p.lastWriteDate;
  144. crmodTime = p.lastWriteTime;
  145. // There are scenarios when simple modification time is not enough (on MS Windows)
  146. // For example - extract an old g-code from an archive onto the SD card.
  147. // In such case the creation time is current time (which is correct), but the modification time
  148. // stays the same - i.e. old.
  149. // Therefore let's pick the most recent timestamp from both creation and modification timestamps
  150. if( crmodDate < p.creationDate || ( crmodDate == p.creationDate && crmodTime < p.creationTime ) ){
  151. crmodDate = p.creationDate;
  152. crmodTime = p.creationTime;
  153. }
  154. //writeDate = p.lastAccessDate;
  155. if (match != NULL) {
  156. if (strcasecmp(match, filename) == 0) return;
  157. }
  158. else if (cnt == nrFiles) return;
  159. cnt++;
  160. break;
  161. }
  162. }
  163. } // while readDir
  164. }
  165. void CardReader::ls(bool printLFN)
  166. {
  167. lsAction = printLFN ? LS_SerialPrint_LFN : LS_SerialPrint;
  168. //if(lsAction==LS_Count)
  169. //nrFiles=0;
  170. root.rewind();
  171. lsDive("",root);
  172. }
  173. void CardReader::initsd()
  174. {
  175. cardOK = false;
  176. if(root.isOpen())
  177. root.close();
  178. #ifdef SDSLOW
  179. if (!card.init(SPI_HALF_SPEED,SDSS)
  180. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  181. && !card.init(SPI_HALF_SPEED,LCD_SDSS)
  182. #endif
  183. )
  184. #else
  185. if (!card.init(SPI_FULL_SPEED,SDSS)
  186. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  187. && !card.init(SPI_FULL_SPEED,LCD_SDSS)
  188. #endif
  189. )
  190. #endif
  191. {
  192. //if (!card.init(SPI_HALF_SPEED,SDSS))
  193. SERIAL_ECHO_START;
  194. SERIAL_ECHOLNRPGM(_n("SD init fail"));////MSG_SD_INIT_FAIL
  195. }
  196. else if (!volume.init(&card))
  197. {
  198. SERIAL_ERROR_START;
  199. SERIAL_ERRORLNRPGM(_n("volume.init failed"));////MSG_SD_VOL_INIT_FAIL
  200. }
  201. else if (!root.openRoot(&volume))
  202. {
  203. SERIAL_ERROR_START;
  204. SERIAL_ERRORLNRPGM(_n("openRoot failed"));////MSG_SD_OPENROOT_FAIL
  205. }
  206. else
  207. {
  208. cardOK = true;
  209. SERIAL_ECHO_START;
  210. SERIAL_ECHOLNRPGM(_n("SD card ok"));////MSG_SD_CARD_OK
  211. }
  212. workDir=root;
  213. curDir=&root;
  214. workDirDepth = 0;
  215. #ifdef SDCARD_SORT_ALPHA
  216. presort();
  217. #endif
  218. /*
  219. if(!workDir.openRoot(&volume))
  220. {
  221. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  222. }
  223. */
  224. }
  225. void CardReader::setroot(bool doPresort)
  226. {
  227. workDir=root;
  228. workDirDepth = 0;
  229. curDir=&workDir;
  230. #ifdef SDCARD_SORT_ALPHA
  231. if (doPresort)
  232. presort();
  233. else
  234. presort_flag = true;
  235. #endif
  236. }
  237. void CardReader::release()
  238. {
  239. sdprinting = false;
  240. cardOK = false;
  241. SERIAL_ECHO_START;
  242. SERIAL_ECHOLNRPGM(_n("SD card released"));////MSG_SD_CARD_RELEASED
  243. }
  244. void CardReader::startFileprint()
  245. {
  246. if(cardOK)
  247. {
  248. sdprinting = true;
  249. Stopped = false;
  250. #ifdef SDCARD_SORT_ALPHA
  251. //flush_presort();
  252. #endif
  253. }
  254. }
  255. void CardReader::openLogFile(const char* name)
  256. {
  257. logging = true;
  258. openFileWrite(name);
  259. }
  260. void CardReader::getDirName(char* name, uint8_t level)
  261. {
  262. workDirParents[level].getFilename(name);
  263. }
  264. uint16_t CardReader::getWorkDirDepth() {
  265. return workDirDepth;
  266. }
  267. void CardReader::getAbsFilename(char *t)
  268. {
  269. uint8_t cnt=0;
  270. *t='/';t++;cnt++;
  271. for(uint8_t i=0;i<workDirDepth;i++)
  272. {
  273. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  274. while(*t!=0 && cnt< MAXPATHNAMELENGTH)
  275. {t++;cnt++;} //crawl counter forward.
  276. }
  277. if(cnt<MAXPATHNAMELENGTH-13)
  278. file.getFilename(t);
  279. else
  280. t[0]=0;
  281. }
  282. void CardReader::printAbsFilenameFast()
  283. {
  284. SERIAL_PROTOCOL('/');
  285. for (uint8_t i = 0; i < getWorkDirDepth(); i++)
  286. {
  287. SERIAL_PROTOCOL(dir_names[i]);
  288. SERIAL_PROTOCOL('/');
  289. }
  290. SERIAL_PROTOCOL(LONGEST_FILENAME);
  291. }
  292. /**
  293. * @brief Dive into subfolder
  294. *
  295. * Method sets curDir to point to root, in case fileName is null.
  296. * Method sets curDir to point to workDir, in case fileName path is relative
  297. * (doesn't start with '/')
  298. * Method sets curDir to point to dir, which is specified by absolute path
  299. * specified by fileName. In such case fileName is updated so it points to
  300. * file name without the path.
  301. *
  302. * @param[in,out] fileName
  303. * expects file name including path
  304. * in case of absolute path, file name without path is returned
  305. */
  306. bool CardReader::diveSubfolder (const char *&fileName)
  307. {
  308. curDir=&root;
  309. if (!fileName)
  310. return 1;
  311. const char *dirname_start, *dirname_end;
  312. if (fileName[0] == '/') // absolute path
  313. {
  314. setroot(false);
  315. dirname_start = fileName + 1;
  316. while (*dirname_start)
  317. {
  318. dirname_end = strchr(dirname_start, '/');
  319. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
  320. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name));
  321. if (dirname_end && dirname_end > dirname_start)
  322. {
  323. const size_t maxLen = 12;
  324. char subdirname[maxLen+1];
  325. const size_t len = ((static_cast<size_t>(dirname_end-dirname_start))>maxLen) ? maxLen : (dirname_end-dirname_start);
  326. strncpy(subdirname, dirname_start, len);
  327. subdirname[len] = 0;
  328. if (!chdir(subdirname, false))
  329. return 0;
  330. curDir = &workDir;
  331. dirname_start = dirname_end + 1;
  332. }
  333. else // the reminder after all /fsa/fdsa/ is the filename
  334. {
  335. fileName = dirname_start;
  336. //SERIAL_ECHOLN("remaider");
  337. //SERIAL_ECHOLN(fname);
  338. break;
  339. }
  340. }
  341. }
  342. else //relative path
  343. {
  344. curDir = &workDir;
  345. }
  346. return 1;
  347. }
  348. static const char ofKill[] PROGMEM = "trying to call sub-gcode files with too many levels.";
  349. static const char ofSubroutineCallTgt[] PROGMEM = "SUBROUTINE CALL target:\"";
  350. static const char ofParent[] PROGMEM = "\" parent:\"";
  351. static const char ofPos[] PROGMEM = "\" pos";
  352. static const char ofNowDoingFile[] PROGMEM = "Now doing file: ";
  353. static const char ofNowFreshFile[] PROGMEM = "Now fresh file: ";
  354. static const char ofFileOpened[] PROGMEM = "File opened: ";
  355. static const char ofSize[] PROGMEM = " Size: ";
  356. static const char ofFileSelected[] PROGMEM = "File selected";
  357. static const char ofSDPrinting[] PROGMEM = "SD-PRINTING";
  358. static const char ofWritingToFile[] PROGMEM = "Writing to file: ";
  359. void CardReader::openFileReadFilteredGcode(const char* name, bool replace_current/* = false*/){
  360. if(!cardOK)
  361. return;
  362. if(file.isOpen()){ //replacing current file by new file, or subfile call
  363. if(!replace_current){
  364. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1){
  365. // SERIAL_ERROR_START;
  366. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  367. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  368. kill(ofKill, 1);
  369. return;
  370. }
  371. SERIAL_ECHO_START;
  372. SERIAL_ECHORPGM(ofSubroutineCallTgt);
  373. SERIAL_ECHO(name);
  374. SERIAL_ECHORPGM(ofParent);
  375. //store current filename and position
  376. getAbsFilename(filenames[file_subcall_ctr]);
  377. SERIAL_ECHO(filenames[file_subcall_ctr]);
  378. SERIAL_ECHORPGM(ofPos);
  379. SERIAL_ECHOLN(sdpos);
  380. filespos[file_subcall_ctr]=sdpos;
  381. file_subcall_ctr++;
  382. } else {
  383. SERIAL_ECHO_START;
  384. SERIAL_ECHORPGM(ofNowDoingFile);
  385. SERIAL_ECHOLN(name);
  386. }
  387. file.close();
  388. } else { //opening fresh file
  389. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  390. SERIAL_ECHO_START;
  391. SERIAL_ECHORPGM(ofNowFreshFile);
  392. SERIAL_ECHOLN(name);
  393. }
  394. sdprinting = false;
  395. const char *fname=name;
  396. if (!diveSubfolder(fname))
  397. return;
  398. if (file.openFilteredGcode(curDir, fname)) {
  399. getfilename(0, fname);
  400. filesize = file.fileSize();
  401. SERIAL_PROTOCOLRPGM(ofFileOpened);////MSG_SD_FILE_OPENED
  402. printAbsFilenameFast();
  403. SERIAL_PROTOCOLRPGM(ofSize);////MSG_SD_SIZE
  404. SERIAL_PROTOCOLLN(filesize);
  405. sdpos = 0;
  406. SERIAL_PROTOCOLLNRPGM(ofFileSelected);////MSG_SD_FILE_SELECTED
  407. lcd_setstatuspgm(ofFileSelected);
  408. scrollstuff = 0;
  409. } else {
  410. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  411. SERIAL_PROTOCOL(fname);
  412. SERIAL_PROTOCOLLN('.');
  413. }
  414. }
  415. void CardReader::openFileWrite(const char* name)
  416. {
  417. if(!cardOK)
  418. return;
  419. if(file.isOpen()){ //replacing current file by new file, or subfile call
  420. #if 0
  421. // I doubt chained files support is necessary for file saving:
  422. // Intentionally disabled because it takes a lot of code size while being not used
  423. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1){
  424. // SERIAL_ERROR_START;
  425. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  426. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  427. kill(ofKill, 1);
  428. return;
  429. }
  430. SERIAL_ECHO_START;
  431. SERIAL_ECHORPGM(ofSubroutineCallTgt);
  432. SERIAL_ECHO(name);
  433. SERIAL_ECHORPGM(ofParent);
  434. //store current filename and position
  435. getAbsFilename(filenames[file_subcall_ctr]);
  436. SERIAL_ECHO(filenames[file_subcall_ctr]);
  437. SERIAL_ECHORPGM(ofPos);
  438. SERIAL_ECHOLN(sdpos);
  439. filespos[file_subcall_ctr]=sdpos;
  440. file_subcall_ctr++;
  441. file.close();
  442. #else
  443. SERIAL_ECHOLNPGM("File already opened");
  444. #endif
  445. } else { //opening fresh file
  446. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  447. SERIAL_ECHO_START;
  448. SERIAL_ECHORPGM(ofNowFreshFile);
  449. SERIAL_ECHOLN(name);
  450. }
  451. sdprinting = false;
  452. const char *fname=name;
  453. if (!diveSubfolder(fname))
  454. return;
  455. //write
  456. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)){
  457. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  458. SERIAL_PROTOCOL(fname);
  459. SERIAL_PROTOCOLLN('.');
  460. } else {
  461. saving = true;
  462. getfilename(0, fname);
  463. SERIAL_PROTOCOLRPGM(ofWritingToFile);////MSG_SD_WRITE_TO_FILE
  464. printAbsFilenameFast();
  465. SERIAL_PROTOCOLLN();
  466. SERIAL_PROTOCOLLNRPGM(ofFileSelected);////MSG_SD_FILE_SELECTED
  467. lcd_setstatuspgm(ofFileSelected);
  468. scrollstuff = 0;
  469. }
  470. }
  471. void CardReader::removeFile(const char* name)
  472. {
  473. if(!cardOK) return;
  474. file.close();
  475. sdprinting = false;
  476. const char *fname=name;
  477. if (!diveSubfolder(fname))
  478. return;
  479. if (file.remove(curDir, fname))
  480. {
  481. SERIAL_PROTOCOLPGM("File deleted:");
  482. SERIAL_PROTOCOLLN(fname);
  483. sdpos = 0;
  484. #ifdef SDCARD_SORT_ALPHA
  485. presort();
  486. #endif
  487. }
  488. else
  489. {
  490. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  491. SERIAL_PROTOCOL(fname);
  492. SERIAL_PROTOCOLLN('.');
  493. }
  494. }
  495. uint32_t CardReader::getFileSize()
  496. {
  497. return filesize;
  498. }
  499. void CardReader::getStatus(bool arg_P)
  500. {
  501. if (isPrintPaused)
  502. {
  503. if (saved_printing && (saved_printing_type == PRINTING_TYPE_SD))
  504. SERIAL_PROTOCOLLNPGM("SD print paused");
  505. else
  506. SERIAL_PROTOCOLLNPGM("Print saved");
  507. }
  508. else if (sdprinting)
  509. {
  510. if (arg_P)
  511. {
  512. printAbsFilenameFast();
  513. SERIAL_PROTOCOLLN();
  514. }
  515. else
  516. SERIAL_PROTOCOLLN(LONGEST_FILENAME);
  517. SERIAL_PROTOCOLRPGM(_N("SD printing byte "));////MSG_SD_PRINTING_BYTE
  518. SERIAL_PROTOCOL(sdpos);
  519. SERIAL_PROTOCOL('/');
  520. SERIAL_PROTOCOLLN(filesize);
  521. uint16_t time = ( _millis() - starttime ) / 60000U;
  522. SERIAL_PROTOCOL(itostr2(time/60));
  523. SERIAL_PROTOCOL(':');
  524. SERIAL_PROTOCOLLN(itostr2(time%60));
  525. }
  526. else
  527. SERIAL_PROTOCOLLNPGM("Not SD printing");
  528. }
  529. void CardReader::write_command(char *buf)
  530. {
  531. char* begin = buf;
  532. char* npos = 0;
  533. char* end = buf + strlen(buf) - 1;
  534. file.writeError = false;
  535. if((npos = strchr(buf, 'N')) != NULL)
  536. {
  537. begin = strchr(npos, ' ') + 1;
  538. end = strchr(npos, '*') - 1;
  539. }
  540. end[1] = '\r';
  541. end[2] = '\n';
  542. end[3] = '\0';
  543. file.write(begin);
  544. if (file.writeError)
  545. {
  546. SERIAL_ERROR_START;
  547. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  548. }
  549. }
  550. #define CHUNK_SIZE 64
  551. void CardReader::write_command_no_newline(char *buf)
  552. {
  553. file.write(buf, CHUNK_SIZE);
  554. if (file.writeError)
  555. {
  556. SERIAL_ERROR_START;
  557. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  558. SERIAL_PROTOCOLLNPGM("An error while writing to the SD Card.");
  559. }
  560. }
  561. void CardReader::checkautostart(bool force)
  562. {
  563. if(!force)
  564. {
  565. if(!autostart_stilltocheck)
  566. return;
  567. if(autostart_atmillis<_millis())
  568. return;
  569. }
  570. autostart_stilltocheck=false;
  571. if(!cardOK)
  572. {
  573. initsd();
  574. if(!cardOK) //fail
  575. return;
  576. }
  577. char autoname[30];
  578. sprintf_P(autoname, PSTR("auto%i.g"), lastnr);
  579. for(int8_t i=0;i<(int8_t)strlen(autoname);i++)
  580. autoname[i]=tolower(autoname[i]);
  581. dir_t p;
  582. root.rewind();
  583. bool found=false;
  584. while (root.readDir(p, NULL) > 0)
  585. {
  586. for(int8_t i=0;i<(int8_t)strlen((char*)p.name);i++)
  587. p.name[i]=tolower(p.name[i]);
  588. //Serial.print((char*)p.name);
  589. //Serial.print(" ");
  590. //Serial.println(autoname);
  591. if(p.name[9]!='~') //skip safety copies
  592. if(strncmp((char*)p.name,autoname,5)==0)
  593. {
  594. char cmd[30];
  595. // M23: Select SD file
  596. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  597. enquecommand(cmd);
  598. // M24: Start/resume SD print
  599. enquecommand_P(PSTR("M24"));
  600. found=true;
  601. }
  602. }
  603. if(!found)
  604. lastnr=-1;
  605. else
  606. lastnr++;
  607. }
  608. void CardReader::closefile(bool store_location)
  609. {
  610. file.sync();
  611. file.close();
  612. saving = false;
  613. logging = false;
  614. if(store_location)
  615. {
  616. //future: store printer state, filename and position for continuing a stopped print
  617. // so one can unplug the printer and continue printing the next day.
  618. }
  619. }
  620. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/)
  621. {
  622. curDir=&workDir;
  623. lsAction=LS_GetFilename;
  624. nrFiles=nr;
  625. curDir->rewind();
  626. lsDive("",*curDir,match);
  627. }
  628. void CardReader::getfilename_simple(uint32_t position, const char * const match/*=NULL*/)
  629. {
  630. curDir = &workDir;
  631. lsAction = LS_GetFilename;
  632. nrFiles = 0;
  633. curDir->seekSet(position);
  634. lsDive("", *curDir, match);
  635. }
  636. void CardReader::getfilename_next(uint32_t position, const char * const match/*=NULL*/)
  637. {
  638. curDir = &workDir;
  639. lsAction = LS_GetFilename;
  640. nrFiles = 1;
  641. curDir->seekSet(position);
  642. lsDive("", *curDir, match);
  643. }
  644. uint16_t CardReader::getnrfilenames()
  645. {
  646. curDir=&workDir;
  647. lsAction=LS_Count;
  648. nrFiles=0;
  649. curDir->rewind();
  650. lsDive("",*curDir);
  651. //SERIAL_ECHOLN(nrFiles);
  652. return nrFiles;
  653. }
  654. bool CardReader::chdir(const char * relpath, bool doPresort)
  655. {
  656. SdFile newfile;
  657. SdFile *parent=&root;
  658. if(workDir.isOpen())
  659. parent=&workDir;
  660. if(!newfile.open(*parent,relpath, O_READ) || ((workDirDepth + 1) >= MAX_DIR_DEPTH))
  661. {
  662. SERIAL_ECHO_START;
  663. SERIAL_ECHORPGM(_n("Cannot enter subdir: "));////MSG_SD_CANT_ENTER_SUBDIR
  664. SERIAL_ECHOLN(relpath);
  665. return 0;
  666. }
  667. else
  668. {
  669. strcpy(dir_names[workDirDepth], relpath);
  670. puts(relpath);
  671. if (workDirDepth < MAX_DIR_DEPTH) {
  672. for (int d = ++workDirDepth; d--;)
  673. workDirParents[d+1] = workDirParents[d];
  674. workDirParents[0]=*parent;
  675. }
  676. workDir=newfile;
  677. #ifdef SDCARD_SORT_ALPHA
  678. if (doPresort)
  679. presort();
  680. else
  681. presort_flag = true;
  682. #endif
  683. return 1;
  684. }
  685. }
  686. void CardReader::updir()
  687. {
  688. if(workDirDepth > 0)
  689. {
  690. --workDirDepth;
  691. workDir = workDirParents[0];
  692. for (unsigned int d = 0; d < workDirDepth; d++)
  693. {
  694. workDirParents[d] = workDirParents[d+1];
  695. }
  696. #ifdef SDCARD_SORT_ALPHA
  697. presort();
  698. #endif
  699. }
  700. }
  701. #ifdef SDCARD_SORT_ALPHA
  702. /**
  703. * Get the name of a file in the current directory by sort-index
  704. */
  705. void CardReader::getfilename_sorted(const uint16_t nr, uint8_t sdSort) {
  706. if (nr < sort_count)
  707. getfilename_simple(sort_positions[(sdSort == SD_SORT_ALPHA) ? (sort_count - nr - 1) : nr]);
  708. else
  709. getfilename(nr);
  710. }
  711. /**
  712. * Read all the files and produce a sort key
  713. *
  714. * We can do this in 3 ways...
  715. * - Minimal RAM: Read two filenames at a time sorting along...
  716. * - Some RAM: Buffer the directory just for this sort
  717. * - Most RAM: Buffer the directory and return filenames from RAM
  718. */
  719. void CardReader::presort() {
  720. if (farm_mode || IS_SD_INSERTED == false) return; //sorting is not used in farm mode
  721. uint8_t sdSort = eeprom_read_byte((uint8_t*)EEPROM_SD_SORT);
  722. if (sdSort == SD_SORT_NONE) return; //sd sort is turned off
  723. KEEPALIVE_STATE(IN_HANDLER);
  724. // Throw away old sort index
  725. flush_presort();
  726. // If there are files, sort up to the limit
  727. uint16_t fileCnt = getnrfilenames();
  728. if (fileCnt > 0) {
  729. // Never sort more than the max allowed
  730. // If you use folders to organize, 20 may be enough
  731. if (fileCnt > SDSORT_LIMIT) {
  732. lcd_show_fullscreen_message_and_wait_P(_i("Some files will not be sorted. Max. No. of files in 1 folder for sorting is 100."));////MSG_FILE_CNT c=20 r=6
  733. fileCnt = SDSORT_LIMIT;
  734. }
  735. // By default re-read the names from SD for every compare
  736. // retaining only two filenames at a time. This is very
  737. // slow but is safest and uses minimal RAM.
  738. char name1[LONG_FILENAME_LENGTH];
  739. uint16_t crmod_time_bckp;
  740. uint16_t crmod_date_bckp;
  741. #if HAS_FOLDER_SORTING
  742. uint16_t dirCnt = 0;
  743. #endif
  744. if (fileCnt > 1) {
  745. // Init sort order.
  746. uint8_t sort_order[fileCnt];
  747. for (uint16_t i = 0; i < fileCnt; i++) {
  748. if (!IS_SD_INSERTED) return;
  749. manage_heater();
  750. if (i == 0)
  751. getfilename(0);
  752. else
  753. getfilename_next(position);
  754. sort_order[i] = i;
  755. sort_positions[i] = position;
  756. #if HAS_FOLDER_SORTING
  757. if (filenameIsDir) dirCnt++;
  758. #endif
  759. }
  760. #ifdef QUICKSORT
  761. quicksort(0, fileCnt - 1);
  762. #elif defined(SHELLSORT)
  763. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  764. #define _SORT_CMP_TIME_NODIR() (((crmod_date_bckp == crmodDate) && (crmod_time_bckp < crmodTime)) || (crmod_date_bckp < crmodDate))
  765. #if HAS_FOLDER_SORTING
  766. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  767. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  768. #endif
  769. for (uint8_t runs = 0; runs < 2; runs++)
  770. {
  771. //run=0: sorts all files and moves folders to the beginning
  772. //run=1: assumes all folders are at the beginning of the list and sorts them
  773. uint16_t sortCountFiles = 0;
  774. if (runs == 0)
  775. {
  776. sortCountFiles = fileCnt;
  777. }
  778. #if HAS_FOLDER_SORTING
  779. else
  780. {
  781. sortCountFiles = dirCnt;
  782. }
  783. #endif
  784. uint16_t counter = 0;
  785. uint16_t total = 0;
  786. for (uint16_t i = sortCountFiles/2; i > 0; i /= 2) total += sortCountFiles - i; //total runs for progress bar
  787. menu_progressbar_init(total, (runs == 0)?_i("Sorting files"):_i("Sorting folders"));
  788. for (uint16_t gap = sortCountFiles/2; gap > 0; gap /= 2)
  789. {
  790. for (uint16_t i = gap; i < sortCountFiles; i++)
  791. {
  792. if (!IS_SD_INSERTED) return;
  793. menu_progressbar_update(counter);
  794. counter++;
  795. manage_heater();
  796. uint8_t orderBckp = sort_order[i];
  797. getfilename_simple(sort_positions[orderBckp]);
  798. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  799. crmod_date_bckp = crmodDate;
  800. crmod_time_bckp = crmodTime;
  801. #if HAS_FOLDER_SORTING
  802. bool dir1 = filenameIsDir;
  803. #endif
  804. uint16_t j = i;
  805. getfilename_simple(sort_positions[sort_order[j - gap]]);
  806. char *name2 = LONGEST_FILENAME; // use the string in-place
  807. #if HAS_FOLDER_SORTING
  808. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_DIR(FOLDER_SORTING):_SORT_CMP_DIR(FOLDER_SORTING)))
  809. #else
  810. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_NODIR():_SORT_CMP_NODIR()))
  811. #endif
  812. {
  813. sort_order[j] = sort_order[j - gap];
  814. j -= gap;
  815. #ifdef SORTING_DUMP
  816. for (uint16_t z = 0; z < sortCountFiles; z++)
  817. {
  818. printf_P(PSTR("%2u "), sort_order[z]);
  819. }
  820. printf_P(PSTR("i%2d j%2d gap%2d orderBckp%2d\n"), i, j, gap, orderBckp);
  821. #endif
  822. if (j < gap) break;
  823. getfilename_simple(sort_positions[sort_order[j - gap]]);
  824. name2 = LONGEST_FILENAME; // use the string in-place
  825. }
  826. sort_order[j] = orderBckp;
  827. }
  828. }
  829. }
  830. #else //Bubble Sort
  831. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  832. #define _SORT_CMP_TIME_NODIR() (((crmod_date_bckp == crmodDate) && (crmod_time_bckp > crmodTime)) || (crmod_date_bckp > crmodDate))
  833. #if HAS_FOLDER_SORTING
  834. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  835. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  836. #endif
  837. uint16_t counter = 0;
  838. menu_progressbar_init(0.5*(fileCnt - 1)*(fileCnt), _i("Sorting files"));
  839. for (uint16_t i = fileCnt; --i;) {
  840. if (!IS_SD_INSERTED) return;
  841. bool didSwap = false;
  842. menu_progressbar_update(counter);
  843. counter++;
  844. for (uint16_t j = 0; j < i; ++j) {
  845. if (!IS_SD_INSERTED) return;
  846. #ifdef SORTING_DUMP
  847. for (uint16_t z = 0; z < fileCnt; z++)
  848. {
  849. printf_P(PSTR("%2u "), sort_order[z]);
  850. }
  851. MYSERIAL.println();
  852. #endif
  853. manage_heater();
  854. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  855. counter++;
  856. getfilename_simple(sort_positions[o1]);
  857. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  858. crmod_date_bckp = crmodDate;
  859. crmod_time_bckp = crmodTime;
  860. #if HAS_FOLDER_SORTING
  861. bool dir1 = filenameIsDir;
  862. #endif
  863. getfilename_simple(sort_positions[o2]);
  864. char *name2 = LONGEST_FILENAME; // use the string in-place
  865. // Sort the current pair according to settings.
  866. if (
  867. #if HAS_FOLDER_SORTING
  868. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_DIR(FOLDER_SORTING))
  869. #else
  870. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_NODIR())
  871. #endif
  872. )
  873. {
  874. #ifdef SORTING_DUMP
  875. puts_P(PSTR("swap"));
  876. #endif
  877. sort_order[j] = o2;
  878. sort_order[j + 1] = o1;
  879. didSwap = true;
  880. }
  881. }
  882. if (!didSwap) break;
  883. } //end of bubble sort loop
  884. #endif
  885. #ifdef SORTING_DUMP
  886. for (uint16_t z = 0; z < fileCnt; z++)
  887. printf_P(PSTR("%2u "), sort_order[z]);
  888. SERIAL_PROTOCOLLN();
  889. #endif
  890. uint8_t sort_order_reverse_index[fileCnt];
  891. for (uint8_t i = 0; i < fileCnt; i++)
  892. sort_order_reverse_index[sort_order[i]] = i;
  893. for (uint8_t i = 0; i < fileCnt; i++)
  894. {
  895. if (sort_order_reverse_index[i] != i)
  896. {
  897. uint32_t el = sort_positions[i];
  898. uint8_t idx = sort_order_reverse_index[i];
  899. while (idx != i)
  900. {
  901. uint32_t el1 = sort_positions[idx];
  902. uint8_t idx1 = sort_order_reverse_index[idx];
  903. sort_order_reverse_index[idx] = idx;
  904. sort_positions[idx] = el;
  905. idx = idx1;
  906. el = el1;
  907. }
  908. sort_order_reverse_index[idx] = idx;
  909. sort_positions[idx] = el;
  910. }
  911. }
  912. menu_progressbar_finish();
  913. }
  914. else {
  915. getfilename(0);
  916. sort_positions[0] = position;
  917. }
  918. sort_count = fileCnt;
  919. }
  920. lcd_update(2);
  921. KEEPALIVE_STATE(NOT_BUSY);
  922. lcd_timeoutToStatus.start();
  923. }
  924. void CardReader::flush_presort() {
  925. if (sort_count > 0) {
  926. sort_count = 0;
  927. }
  928. }
  929. #endif // SDCARD_SORT_ALPHA
  930. void CardReader::printingHasFinished()
  931. {
  932. st_synchronize();
  933. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  934. {
  935. file.close();
  936. file_subcall_ctr--;
  937. openFileReadFilteredGcode(filenames[file_subcall_ctr],true);
  938. setIndex(filespos[file_subcall_ctr]);
  939. startFileprint();
  940. }
  941. else
  942. {
  943. quickStop();
  944. file.close();
  945. sdprinting = false;
  946. if(SD_FINISHED_STEPPERRELEASE)
  947. {
  948. finishAndDisableSteppers();
  949. //enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  950. }
  951. autotempShutdown();
  952. #ifdef SDCARD_SORT_ALPHA
  953. //presort();
  954. #endif
  955. }
  956. }
  957. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  958. {
  959. memset(ip, 0, 4);
  960. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  961. }
  962. #endif //SDSUPPORT