cardreader.cpp 24 KB

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