cardreader.cpp 29 KB

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