cardreader.cpp 24 KB

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