cardreader.cpp 26 KB

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