cardreader.cpp 26 KB

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