cardreader.cpp 24 KB

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