cardreader.cpp 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. paused = 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 c=0 r=0
  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. creationDate = p.creationDate;
  129. creationTime = p.creationTime;
  130. //writeDate = p.lastAccessDate;
  131. if (match != NULL) {
  132. if (strcasecmp(match, filename) == 0) return;
  133. }
  134. else if (cnt == nrFiles) return;
  135. cnt++;
  136. break;
  137. }
  138. }
  139. } // while readDir
  140. }
  141. void CardReader::ls()
  142. {
  143. lsAction=LS_SerialPrint;
  144. //if(lsAction==LS_Count)
  145. //nrFiles=0;
  146. root.rewind();
  147. lsDive("",root);
  148. }
  149. void CardReader::initsd()
  150. {
  151. cardOK = false;
  152. if(root.isOpen())
  153. root.close();
  154. #ifdef SDSLOW
  155. if (!card.init(SPI_HALF_SPEED,SDSS)
  156. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  157. && !card.init(SPI_HALF_SPEED,LCD_SDSS)
  158. #endif
  159. )
  160. #else
  161. if (!card.init(SPI_FULL_SPEED,SDSS)
  162. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  163. && !card.init(SPI_FULL_SPEED,LCD_SDSS)
  164. #endif
  165. )
  166. #endif
  167. {
  168. //if (!card.init(SPI_HALF_SPEED,SDSS))
  169. SERIAL_ECHO_START;
  170. SERIAL_ECHOLNRPGM(_i("SD init fail"));////MSG_SD_INIT_FAIL c=0 r=0
  171. }
  172. else if (!volume.init(&card))
  173. {
  174. SERIAL_ERROR_START;
  175. SERIAL_ERRORLNRPGM(_i("volume.init failed"));////MSG_SD_VOL_INIT_FAIL c=0 r=0
  176. }
  177. else if (!root.openRoot(&volume))
  178. {
  179. SERIAL_ERROR_START;
  180. SERIAL_ERRORLNRPGM(_i("openRoot failed"));////MSG_SD_OPENROOT_FAIL c=0 r=0
  181. }
  182. else
  183. {
  184. cardOK = true;
  185. SERIAL_ECHO_START;
  186. SERIAL_ECHOLNRPGM(_i("SD card ok"));////MSG_SD_CARD_OK c=0 r=0
  187. }
  188. workDir=root;
  189. curDir=&root;
  190. #ifdef SDCARD_SORT_ALPHA
  191. presort();
  192. #endif
  193. /*
  194. if(!workDir.openRoot(&volume))
  195. {
  196. SERIAL_ECHOLNPGM(_T(MSG_SD_WORKDIR_FAIL));
  197. }
  198. */
  199. }
  200. void CardReader::setroot()
  201. {
  202. /*if(!workDir.openRoot(&volume))
  203. {
  204. SERIAL_ECHOLNPGM(_T(MSG_SD_WORKDIR_FAIL));
  205. }*/
  206. workDir=root;
  207. curDir=&workDir;
  208. #ifdef SDCARD_SORT_ALPHA
  209. presort();
  210. #endif
  211. }
  212. void CardReader::release()
  213. {
  214. sdprinting = false;
  215. cardOK = false;
  216. }
  217. void CardReader::startFileprint()
  218. {
  219. if(cardOK)
  220. {
  221. sdprinting = true;
  222. paused = false;
  223. #ifdef SDCARD_SORT_ALPHA
  224. //flush_presort();
  225. #endif
  226. }
  227. }
  228. void CardReader::pauseSDPrint()
  229. {
  230. if(sdprinting)
  231. {
  232. sdprinting = false;
  233. paused = true;
  234. }
  235. }
  236. void CardReader::openLogFile(char* name)
  237. {
  238. logging = true;
  239. openFile(name, false);
  240. }
  241. void CardReader::getDirName(char* name, uint8_t level)
  242. {
  243. workDirParents[level].getFilename(name);
  244. }
  245. uint16_t CardReader::getWorkDirDepth() {
  246. return workDirDepth;
  247. }
  248. void CardReader::getAbsFilename(char *t)
  249. {
  250. uint8_t cnt=0;
  251. *t='/';t++;cnt++;
  252. for(uint8_t i=0;i<workDirDepth;i++)
  253. {
  254. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  255. while(*t!=0 && cnt< MAXPATHNAMELENGTH)
  256. {t++;cnt++;} //crawl counter forward.
  257. }
  258. if(cnt<MAXPATHNAMELENGTH-13)
  259. file.getFilename(t);
  260. else
  261. t[0]=0;
  262. }
  263. void CardReader::openFile(char* name,bool read, bool replace_current/*=true*/)
  264. {
  265. if(!cardOK)
  266. return;
  267. if(file.isOpen()) //replacing current file by new file, or subfile call
  268. {
  269. if(!replace_current)
  270. {
  271. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1)
  272. {
  273. SERIAL_ERROR_START;
  274. SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  275. SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  276. kill("", 1);
  277. return;
  278. }
  279. SERIAL_ECHO_START;
  280. SERIAL_ECHOPGM("SUBROUTINE CALL target:\"");
  281. SERIAL_ECHO(name);
  282. SERIAL_ECHOPGM("\" parent:\"");
  283. //store current filename and position
  284. getAbsFilename(filenames[file_subcall_ctr]);
  285. SERIAL_ECHO(filenames[file_subcall_ctr]);
  286. SERIAL_ECHOPGM("\" pos");
  287. SERIAL_ECHOLN(sdpos);
  288. filespos[file_subcall_ctr]=sdpos;
  289. file_subcall_ctr++;
  290. }
  291. else
  292. {
  293. SERIAL_ECHO_START;
  294. SERIAL_ECHOPGM("Now doing file: ");
  295. SERIAL_ECHOLN(name);
  296. }
  297. file.close();
  298. }
  299. else //opening fresh file
  300. {
  301. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  302. SERIAL_ECHO_START;
  303. SERIAL_ECHOPGM("Now fresh file: ");
  304. SERIAL_ECHOLN(name);
  305. }
  306. sdprinting = false;
  307. paused = false;
  308. SdFile myDir;
  309. curDir=&root;
  310. char *fname=name;
  311. char *dirname_start,*dirname_end;
  312. if(name[0]=='/')
  313. {
  314. dirname_start=strchr(name,'/')+1;
  315. while(dirname_start>0)
  316. {
  317. dirname_end=strchr(dirname_start,'/');
  318. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
  319. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name));
  320. if(dirname_end>0 && dirname_end>dirname_start)
  321. {
  322. char subdirname[13];
  323. strncpy(subdirname, dirname_start, dirname_end-dirname_start);
  324. subdirname[dirname_end-dirname_start]=0;
  325. SERIAL_ECHOLN(subdirname);
  326. if(!myDir.open(curDir,subdirname,O_READ))
  327. {
  328. SERIAL_PROTOCOLRPGM(_T(MSG_SD_OPEN_FILE_FAIL));
  329. SERIAL_PROTOCOL(subdirname);
  330. SERIAL_PROTOCOLLNPGM(".");
  331. return;
  332. }
  333. else
  334. {
  335. //SERIAL_ECHOLN("dive ok");
  336. }
  337. curDir=&myDir;
  338. dirname_start=dirname_end+1;
  339. }
  340. else // the reminder after all /fsa/fdsa/ is the filename
  341. {
  342. fname=dirname_start;
  343. //SERIAL_ECHOLN("remaider");
  344. //SERIAL_ECHOLN(fname);
  345. break;
  346. }
  347. }
  348. }
  349. else //relative path
  350. {
  351. curDir=&workDir;
  352. }
  353. if(read)
  354. {
  355. if (file.open(curDir, fname, O_READ))
  356. {
  357. filesize = file.fileSize();
  358. SERIAL_PROTOCOLRPGM(_N("File opened: "));////MSG_SD_FILE_OPENED c=0 r=0
  359. SERIAL_PROTOCOL(fname);
  360. SERIAL_PROTOCOLRPGM(_n(" Size: "));////MSG_SD_SIZE c=0 r=0
  361. SERIAL_PROTOCOLLN(filesize);
  362. sdpos = 0;
  363. SERIAL_PROTOCOLLNRPGM(_N("File selected"));////MSG_SD_FILE_SELECTED c=0 r=0
  364. getfilename(0, fname);
  365. lcd_setstatus(longFilename[0] ? longFilename : fname);
  366. lcd_setstatus("SD-PRINTING ");
  367. }
  368. else
  369. {
  370. SERIAL_PROTOCOLRPGM(_T(MSG_SD_OPEN_FILE_FAIL));
  371. SERIAL_PROTOCOL(fname);
  372. SERIAL_PROTOCOLLNPGM(".");
  373. }
  374. }
  375. else
  376. { //write
  377. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC))
  378. {
  379. SERIAL_PROTOCOLRPGM(_T(MSG_SD_OPEN_FILE_FAIL));
  380. SERIAL_PROTOCOL(fname);
  381. SERIAL_PROTOCOLLNPGM(".");
  382. }
  383. else
  384. {
  385. saving = true;
  386. SERIAL_PROTOCOLRPGM(_N("Writing to file: "));////MSG_SD_WRITE_TO_FILE c=0 r=0
  387. SERIAL_PROTOCOLLN(name);
  388. lcd_setstatus(fname);
  389. }
  390. }
  391. }
  392. void CardReader::removeFile(char* name)
  393. {
  394. if(!cardOK)
  395. return;
  396. file.close();
  397. sdprinting = false;
  398. SdFile myDir;
  399. curDir=&root;
  400. char *fname=name;
  401. char *dirname_start,*dirname_end;
  402. if(name[0]=='/')
  403. {
  404. dirname_start=strchr(name,'/')+1;
  405. while(dirname_start>0)
  406. {
  407. dirname_end=strchr(dirname_start,'/');
  408. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
  409. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name));
  410. if(dirname_end>0 && dirname_end>dirname_start)
  411. {
  412. char subdirname[13];
  413. strncpy(subdirname, dirname_start, dirname_end-dirname_start);
  414. subdirname[dirname_end-dirname_start]=0;
  415. SERIAL_ECHOLN(subdirname);
  416. if(!myDir.open(curDir,subdirname,O_READ))
  417. {
  418. SERIAL_PROTOCOLRPGM("open failed, File: ");
  419. SERIAL_PROTOCOL(subdirname);
  420. SERIAL_PROTOCOLLNPGM(".");
  421. return;
  422. }
  423. else
  424. {
  425. //SERIAL_ECHOLN("dive ok");
  426. }
  427. curDir=&myDir;
  428. dirname_start=dirname_end+1;
  429. }
  430. else // the reminder after all /fsa/fdsa/ is the filename
  431. {
  432. fname=dirname_start;
  433. //SERIAL_ECHOLN("remaider");
  434. //SERIAL_ECHOLN(fname);
  435. break;
  436. }
  437. }
  438. }
  439. else //relative path
  440. {
  441. curDir=&workDir;
  442. }
  443. if (file.remove(curDir, fname))
  444. {
  445. SERIAL_PROTOCOLPGM("File deleted:");
  446. SERIAL_PROTOCOLLN(fname);
  447. sdpos = 0;
  448. #ifdef SDCARD_SORT_ALPHA
  449. presort();
  450. #endif
  451. }
  452. else
  453. {
  454. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  455. SERIAL_PROTOCOL(fname);
  456. SERIAL_PROTOCOLLNPGM(".");
  457. }
  458. }
  459. uint32_t CardReader::getFileSize()
  460. {
  461. return filesize;
  462. }
  463. void CardReader::getStatus()
  464. {
  465. if(sdprinting){
  466. SERIAL_PROTOCOL(longFilename);
  467. SERIAL_PROTOCOLPGM("\n");
  468. SERIAL_PROTOCOLRPGM(_N("SD printing byte "));////MSG_SD_PRINTING_BYTE c=0 r=0
  469. SERIAL_PROTOCOL(sdpos);
  470. SERIAL_PROTOCOLPGM("/");
  471. SERIAL_PROTOCOLLN(filesize);
  472. uint16_t time = millis()/60000 - starttime/60000;
  473. SERIAL_PROTOCOL(itostr2(time/60));
  474. SERIAL_PROTOCOL(':');
  475. SERIAL_PROTOCOL(itostr2(time%60));
  476. SERIAL_PROTOCOLPGM("\n");
  477. }
  478. else if (paused) {
  479. SERIAL_PROTOCOLLNPGM("SD print paused");
  480. }
  481. else if (saved_printing) {
  482. SERIAL_PROTOCOLLNPGM("Print saved");
  483. }
  484. else {
  485. SERIAL_PROTOCOLLNPGM("Not SD printing");
  486. }
  487. }
  488. void CardReader::write_command(char *buf)
  489. {
  490. char* begin = buf;
  491. char* npos = 0;
  492. char* end = buf + strlen(buf) - 1;
  493. file.writeError = false;
  494. if((npos = strchr(buf, 'N')) != NULL)
  495. {
  496. begin = strchr(npos, ' ') + 1;
  497. end = strchr(npos, '*') - 1;
  498. }
  499. end[1] = '\r';
  500. end[2] = '\n';
  501. end[3] = '\0';
  502. file.write(begin);
  503. if (file.writeError)
  504. {
  505. SERIAL_ERROR_START;
  506. SERIAL_ERRORLNRPGM(_T(MSG_SD_ERR_WRITE_TO_FILE));
  507. }
  508. }
  509. #define CHUNK_SIZE 64
  510. void CardReader::write_command_no_newline(char *buf)
  511. {
  512. file.write(buf, CHUNK_SIZE);
  513. if (file.writeError)
  514. {
  515. SERIAL_ERROR_START;
  516. SERIAL_ERRORLNRPGM(_T(MSG_SD_ERR_WRITE_TO_FILE));
  517. MYSERIAL.println("An error while writing to the SD Card.");
  518. }
  519. }
  520. void CardReader::checkautostart(bool force)
  521. {
  522. if(!force)
  523. {
  524. if(!autostart_stilltocheck)
  525. return;
  526. if(autostart_atmillis<millis())
  527. return;
  528. }
  529. autostart_stilltocheck=false;
  530. if(!cardOK)
  531. {
  532. initsd();
  533. if(!cardOK) //fail
  534. return;
  535. }
  536. char autoname[30];
  537. sprintf_P(autoname, PSTR("auto%i.g"), lastnr);
  538. for(int8_t i=0;i<(int8_t)strlen(autoname);i++)
  539. autoname[i]=tolower(autoname[i]);
  540. dir_t p;
  541. root.rewind();
  542. bool found=false;
  543. while (root.readDir(p, NULL) > 0)
  544. {
  545. for(int8_t i=0;i<(int8_t)strlen((char*)p.name);i++)
  546. p.name[i]=tolower(p.name[i]);
  547. //Serial.print((char*)p.name);
  548. //Serial.print(" ");
  549. //Serial.println(autoname);
  550. if(p.name[9]!='~') //skip safety copies
  551. if(strncmp((char*)p.name,autoname,5)==0)
  552. {
  553. char cmd[30];
  554. // M23: Select SD file
  555. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  556. enquecommand(cmd);
  557. // M24: Start/resume SD print
  558. enquecommand_P(PSTR("M24"));
  559. found=true;
  560. }
  561. }
  562. if(!found)
  563. lastnr=-1;
  564. else
  565. lastnr++;
  566. }
  567. void CardReader::closefile(bool store_location)
  568. {
  569. file.sync();
  570. file.close();
  571. saving = false;
  572. logging = false;
  573. if(store_location)
  574. {
  575. //future: store printer state, filename and position for continuing a stopped print
  576. // so one can unplug the printer and continue printing the next day.
  577. }
  578. }
  579. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/)
  580. {
  581. curDir=&workDir;
  582. lsAction=LS_GetFilename;
  583. nrFiles=nr;
  584. curDir->rewind();
  585. lsDive("",*curDir,match);
  586. }
  587. void CardReader::getfilename_simple(uint32_t position, const char * const match/*=NULL*/)
  588. {
  589. curDir = &workDir;
  590. lsAction = LS_GetFilename;
  591. nrFiles = 0;
  592. curDir->seekSet(position);
  593. lsDive("", *curDir, match);
  594. }
  595. uint16_t CardReader::getnrfilenames()
  596. {
  597. curDir=&workDir;
  598. lsAction=LS_Count;
  599. nrFiles=0;
  600. curDir->rewind();
  601. lsDive("",*curDir);
  602. //SERIAL_ECHOLN(nrFiles);
  603. return nrFiles;
  604. }
  605. void CardReader::chdir(const char * relpath)
  606. {
  607. SdFile newfile;
  608. SdFile *parent=&root;
  609. if(workDir.isOpen())
  610. parent=&workDir;
  611. if(!newfile.open(*parent,relpath, O_READ))
  612. {
  613. SERIAL_ECHO_START;
  614. SERIAL_ECHORPGM(_i("Cannot enter subdir: "));////MSG_SD_CANT_ENTER_SUBDIR c=0 r=0
  615. SERIAL_ECHOLN(relpath);
  616. }
  617. else
  618. {
  619. if (workDirDepth < MAX_DIR_DEPTH) {
  620. for (int d = ++workDirDepth; d--;)
  621. workDirParents[d+1] = workDirParents[d];
  622. workDirParents[0]=*parent;
  623. }
  624. workDir=newfile;
  625. #ifdef SDCARD_SORT_ALPHA
  626. presort();
  627. #endif
  628. }
  629. }
  630. void CardReader::updir()
  631. {
  632. if(workDirDepth > 0)
  633. {
  634. --workDirDepth;
  635. workDir = workDirParents[0];
  636. int d;
  637. for (int d = 0; d < workDirDepth; d++)
  638. workDirParents[d] = workDirParents[d+1];
  639. #ifdef SDCARD_SORT_ALPHA
  640. presort();
  641. #endif
  642. }
  643. }
  644. #ifdef SDCARD_SORT_ALPHA
  645. /**
  646. * Get the name of a file in the current directory by sort-index
  647. */
  648. void CardReader::getfilename_sorted(const uint16_t nr) {
  649. getfilename(
  650. #if SDSORT_GCODE
  651. sort_alpha &&
  652. #endif
  653. (nr < sort_count) ? sort_order[nr] : nr
  654. );
  655. }
  656. /**
  657. * Read all the files and produce a sort key
  658. *
  659. * We can do this in 3 ways...
  660. * - Minimal RAM: Read two filenames at a time sorting along...
  661. * - Some RAM: Buffer the directory just for this sort
  662. * - Most RAM: Buffer the directory and return filenames from RAM
  663. */
  664. void CardReader::presort() {
  665. if (farm_mode || IS_SD_INSERTED == false) return; //sorting is not used in farm mode
  666. uint8_t sdSort = eeprom_read_byte((uint8_t*)EEPROM_SD_SORT);
  667. if (sdSort == SD_SORT_NONE) return; //sd sort is turned off
  668. #if SDSORT_GCODE
  669. if (!sort_alpha) return;
  670. #endif
  671. KEEPALIVE_STATE(IN_HANDLER);
  672. // Throw away old sort index
  673. flush_presort();
  674. // If there are files, sort up to the limit
  675. uint16_t fileCnt = getnrfilenames();
  676. if (fileCnt > 0) {
  677. // Never sort more than the max allowed
  678. // If you use folders to organize, 20 may be enough
  679. if (fileCnt > SDSORT_LIMIT) {
  680. 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
  681. fileCnt = SDSORT_LIMIT;
  682. }
  683. lcd_clear();
  684. #if !SDSORT_USES_RAM
  685. lcd_set_progress();
  686. #endif
  687. lcd_puts_at_P(0, 1, _i("Sorting files"));////MSG_SORTING c=20 r=1
  688. // Sort order is always needed. May be static or dynamic.
  689. #if SDSORT_DYNAMIC_RAM
  690. sort_order = new uint8_t[fileCnt];
  691. #endif
  692. // Use RAM to store the entire directory during pre-sort.
  693. // SDSORT_LIMIT should be set to prevent over-allocation.
  694. #if SDSORT_USES_RAM
  695. // If using dynamic ram for names, allocate on the heap.
  696. #if SDSORT_CACHE_NAMES
  697. #if SDSORT_DYNAMIC_RAM
  698. sortshort = new char*[fileCnt];
  699. sortnames = new char*[fileCnt];
  700. #endif
  701. #elif SDSORT_USES_STACK
  702. char sortnames[fileCnt][LONG_FILENAME_LENGTH];
  703. uint16_t creation_time[fileCnt];
  704. uint16_t creation_date[fileCnt];
  705. #endif
  706. // Folder sorting needs 1 bit per entry for flags.
  707. #if HAS_FOLDER_SORTING
  708. #if SDSORT_DYNAMIC_RAM
  709. isDir = new uint8_t[(fileCnt + 7) >> 3];
  710. #elif SDSORT_USES_STACK
  711. uint8_t isDir[(fileCnt + 7) >> 3];
  712. #endif
  713. #endif
  714. #else // !SDSORT_USES_RAM
  715. uint32_t positions[fileCnt];
  716. // By default re-read the names from SD for every compare
  717. // retaining only two filenames at a time. This is very
  718. // slow but is safest and uses minimal RAM.
  719. char name1[LONG_FILENAME_LENGTH + 1];
  720. uint16_t creation_time_bckp;
  721. uint16_t creation_date_bckp;
  722. #endif
  723. position = 0;
  724. if (fileCnt > 1) {
  725. // Init sort order.
  726. for (uint16_t i = 0; i < fileCnt; i++) {
  727. if (!IS_SD_INSERTED) return;
  728. manage_heater();
  729. sort_order[i] = i;
  730. positions[i] = position;
  731. getfilename(i);
  732. // If using RAM then read all filenames now.
  733. #if SDSORT_USES_RAM
  734. getfilename(i);
  735. #if SDSORT_DYNAMIC_RAM
  736. // Use dynamic method to copy long filename
  737. sortnames[i] = strdup(LONGEST_FILENAME);
  738. #if SDSORT_CACHE_NAMES
  739. // When caching also store the short name, since
  740. // we're replacing the getfilename() behavior.
  741. sortshort[i] = strdup(filename);
  742. #endif
  743. #else
  744. // Copy filenames into the static array
  745. strcpy(sortnames[i], LONGEST_FILENAME);
  746. creation_time[i] = creationTime;
  747. creation_date[i] = creationDate;
  748. #if SDSORT_CACHE_NAMES
  749. strcpy(sortshort[i], filename);
  750. #endif
  751. #endif
  752. // char out[30];
  753. // sprintf_P(out, PSTR("---- %i %s %s"), i, filenameIsDir ? "D" : " ", sortnames[i]);
  754. // SERIAL_ECHOLN(out);
  755. #if HAS_FOLDER_SORTING
  756. const uint16_t bit = i & 0x07, ind = i >> 3;
  757. if (bit == 0) isDir[ind] = 0x00;
  758. if (filenameIsDir) isDir[ind] |= _BV(bit);
  759. #endif
  760. #endif
  761. }
  762. #ifdef QUICKSORT
  763. quicksort(0, fileCnt - 1);
  764. #else //Qicksort not defined, use Bubble Sort
  765. uint32_t counter = 0;
  766. uint16_t total = 0.5*(fileCnt - 1)*(fileCnt);
  767. // Compare names from the array or just the two buffered names
  768. #if SDSORT_USES_RAM
  769. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  770. #define _SORT_CMP_TIME_NODIR() (((creation_date[o1] == creation_date[o2]) && (creation_time[o1] < creation_time[o2])) || \
  771. (creation_date[o1] < creation_date [o2]))
  772. #else
  773. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0) //true if lowercase(name1) > lowercase(name2)
  774. #define _SORT_CMP_TIME_NODIR() (((creation_date_bckp == creationDate) && (creation_time_bckp > creationTime)) || \
  775. (creation_date_bckp > creationDate))
  776. #endif
  777. #if HAS_FOLDER_SORTING
  778. #if SDSORT_USES_RAM
  779. // Folder sorting needs an index and bit to test for folder-ness.
  780. const uint8_t ind1 = o1 >> 3, bit1 = o1 & 0x07,
  781. ind2 = o2 >> 3, bit2 = o2 & 0x07;
  782. #define _SORT_CMP_DIR(fs) \
  783. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  784. ? _SORT_CMP_NODIR() \
  785. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  786. #define _SORT_CMP_TIME_DIR(fs) \
  787. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  788. ? _SORT_CMP_TIME_NODIR() \
  789. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  790. #else
  791. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  792. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  793. #endif
  794. #endif
  795. for (uint16_t i = fileCnt; --i;) {
  796. if (!IS_SD_INSERTED) return;
  797. bool didSwap = false;
  798. #if !SDSORT_USES_RAM //show progresss bar only if slow sorting method is used
  799. int8_t percent = (counter * 100) / total;//((counter * 100) / pow((fileCnt-1),2));
  800. for (int column = 0; column < 20; column++) {
  801. if (column < (percent / 5))
  802. {
  803. lcd_set_cursor(column, 2);
  804. lcd_print('\x01'); //simple progress bar
  805. }
  806. }
  807. counter++;
  808. #endif
  809. //MYSERIAL.println(int(i));
  810. for (uint16_t j = 0; j < i; ++j) {
  811. if (!IS_SD_INSERTED) return;
  812. manage_heater();
  813. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  814. // The most economical method reads names as-needed
  815. // throughout the loop. Slow if there are many.
  816. #if !SDSORT_USES_RAM
  817. counter++;
  818. getfilename_simple(positions[o1]);
  819. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  820. creation_date_bckp = creationDate;
  821. creation_time_bckp = creationTime;
  822. #if HAS_FOLDER_SORTING
  823. bool dir1 = filenameIsDir;
  824. #endif
  825. getfilename_simple(positions[o2]);
  826. char *name2 = LONGEST_FILENAME; // use the string in-place
  827. #endif // !SDSORT_USES_RAM
  828. // Sort the current pair according to settings.
  829. if (
  830. #if HAS_FOLDER_SORTING
  831. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && _SORT_CMP_DIR(FOLDER_SORTING))
  832. #else
  833. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && _SORT_CMP_NODIR())
  834. #endif
  835. )
  836. {
  837. sort_order[j] = o2;
  838. sort_order[j + 1] = o1;
  839. didSwap = true;
  840. }
  841. }
  842. if (!didSwap) break;
  843. } //end of bubble sort loop
  844. #endif
  845. // Using RAM but not keeping names around
  846. #if (SDSORT_USES_RAM && !SDSORT_CACHE_NAMES)
  847. #if SDSORT_DYNAMIC_RAM
  848. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  849. #if HAS_FOLDER_SORTING
  850. free(isDir);
  851. #endif
  852. #endif
  853. #endif
  854. }
  855. else {
  856. sort_order[0] = 0;
  857. #if (SDSORT_USES_RAM && SDSORT_CACHE_NAMES)
  858. getfilename(0);
  859. #if SDSORT_DYNAMIC_RAM
  860. sortnames = new char*[1];
  861. sortnames[0] = strdup(LONGEST_FILENAME); // malloc
  862. sortshort = new char*[1];
  863. sortshort[0] = strdup(filename); // malloc
  864. isDir = new uint8_t[1];
  865. #else
  866. strcpy(sortnames[0], LONGEST_FILENAME);
  867. strcpy(sortshort[0], filename);
  868. #endif
  869. isDir[0] = filenameIsDir ? 0x01 : 0x00;
  870. #endif
  871. }
  872. sort_count = fileCnt;
  873. }
  874. #if !SDSORT_USES_RAM //show progresss bar only if slow sorting method is used
  875. for (int column = 0; column <= 19; column++)
  876. {
  877. lcd_set_cursor(column, 2);
  878. lcd_print('\x01'); //simple progress bar
  879. }
  880. delay(300);
  881. lcd_set_degree();
  882. lcd_clear();
  883. #endif
  884. lcd_update(2);
  885. KEEPALIVE_STATE(NOT_BUSY);
  886. lcd_timeoutToStatus = millis() + LCD_TIMEOUT_TO_STATUS;
  887. }
  888. void CardReader::flush_presort() {
  889. if (sort_count > 0) {
  890. #if SDSORT_DYNAMIC_RAM
  891. delete sort_order;
  892. #if SDSORT_CACHE_NAMES
  893. for (uint8_t i = 0; i < sort_count; ++i) {
  894. free(sortshort[i]); // strdup
  895. free(sortnames[i]); // strdup
  896. }
  897. delete sortshort;
  898. delete sortnames;
  899. #endif
  900. #endif
  901. sort_count = 0;
  902. }
  903. }
  904. #endif // SDCARD_SORT_ALPHA
  905. void CardReader::printingHasFinished()
  906. {
  907. st_synchronize();
  908. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  909. {
  910. file.close();
  911. file_subcall_ctr--;
  912. openFile(filenames[file_subcall_ctr],true,true);
  913. setIndex(filespos[file_subcall_ctr]);
  914. startFileprint();
  915. }
  916. else
  917. {
  918. quickStop();
  919. file.close();
  920. sdprinting = false;
  921. if(SD_FINISHED_STEPPERRELEASE)
  922. {
  923. finishAndDisableSteppers();
  924. //enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  925. }
  926. autotempShutdown();
  927. #ifdef SDCARD_SORT_ALPHA
  928. //presort();
  929. #endif
  930. }
  931. }
  932. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  933. {
  934. memset(ip, 0, 4);
  935. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  936. }
  937. #endif //SDSUPPORT