cardreader.cpp 29 KB

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