cardreader.cpp 27 KB

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