cardreader.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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. void CardReader::getStatus()
  447. {
  448. if(sdprinting){
  449. SERIAL_PROTOCOL(longFilename);
  450. SERIAL_PROTOCOLPGM("\n");
  451. SERIAL_PROTOCOLRPGM(MSG_SD_PRINTING_BYTE);
  452. SERIAL_PROTOCOL(sdpos);
  453. SERIAL_PROTOCOLPGM("/");
  454. SERIAL_PROTOCOLLN(filesize);
  455. uint16_t time = millis()/60000 - starttime/60000;
  456. SERIAL_PROTOCOL(itostr2(time/60));
  457. SERIAL_PROTOCOL(':');
  458. SERIAL_PROTOCOL(itostr2(time%60));
  459. SERIAL_PROTOCOLPGM("\n");
  460. }
  461. else{
  462. SERIAL_PROTOCOLLNRPGM("Not printing");
  463. }
  464. }
  465. void CardReader::write_command(char *buf)
  466. {
  467. char* begin = buf;
  468. char* npos = 0;
  469. char* end = buf + strlen(buf) - 1;
  470. file.writeError = false;
  471. if((npos = strchr(buf, 'N')) != NULL)
  472. {
  473. begin = strchr(npos, ' ') + 1;
  474. end = strchr(npos, '*') - 1;
  475. }
  476. end[1] = '\r';
  477. end[2] = '\n';
  478. end[3] = '\0';
  479. file.write(begin);
  480. if (file.writeError)
  481. {
  482. SERIAL_ERROR_START;
  483. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  484. }
  485. }
  486. #define CHUNK_SIZE 64
  487. void CardReader::write_command_no_newline(char *buf)
  488. {
  489. file.write(buf, CHUNK_SIZE);
  490. if (file.writeError)
  491. {
  492. SERIAL_ERROR_START;
  493. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  494. MYSERIAL.println("An error while writing to the SD Card.");
  495. }
  496. }
  497. void CardReader::checkautostart(bool force)
  498. {
  499. if(!force)
  500. {
  501. if(!autostart_stilltocheck)
  502. return;
  503. if(autostart_atmillis<millis())
  504. return;
  505. }
  506. autostart_stilltocheck=false;
  507. if(!cardOK)
  508. {
  509. initsd();
  510. if(!cardOK) //fail
  511. return;
  512. }
  513. char autoname[30];
  514. sprintf_P(autoname, PSTR("auto%i.g"), lastnr);
  515. for(int8_t i=0;i<(int8_t)strlen(autoname);i++)
  516. autoname[i]=tolower(autoname[i]);
  517. dir_t p;
  518. root.rewind();
  519. bool found=false;
  520. while (root.readDir(p, NULL) > 0)
  521. {
  522. for(int8_t i=0;i<(int8_t)strlen((char*)p.name);i++)
  523. p.name[i]=tolower(p.name[i]);
  524. //Serial.print((char*)p.name);
  525. //Serial.print(" ");
  526. //Serial.println(autoname);
  527. if(p.name[9]!='~') //skip safety copies
  528. if(strncmp((char*)p.name,autoname,5)==0)
  529. {
  530. char cmd[30];
  531. // M23: Select SD file
  532. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  533. enquecommand(cmd);
  534. // M24: Start/resume SD print
  535. enquecommand_P(PSTR("M24"));
  536. found=true;
  537. }
  538. }
  539. if(!found)
  540. lastnr=-1;
  541. else
  542. lastnr++;
  543. }
  544. void CardReader::closefile(bool store_location)
  545. {
  546. file.sync();
  547. file.close();
  548. saving = false;
  549. logging = false;
  550. if(store_location)
  551. {
  552. //future: store printer state, filename and position for continuing a stopped print
  553. // so one can unplug the printer and continue printing the next day.
  554. }
  555. }
  556. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/)
  557. {
  558. curDir=&workDir;
  559. lsAction=LS_GetFilename;
  560. nrFiles=nr;
  561. curDir->rewind();
  562. lsDive("",*curDir,match);
  563. }
  564. uint16_t CardReader::getnrfilenames()
  565. {
  566. curDir=&workDir;
  567. lsAction=LS_Count;
  568. nrFiles=0;
  569. curDir->rewind();
  570. lsDive("",*curDir);
  571. //SERIAL_ECHOLN(nrFiles);
  572. return nrFiles;
  573. }
  574. void CardReader::chdir(const char * relpath)
  575. {
  576. SdFile newfile;
  577. SdFile *parent=&root;
  578. if(workDir.isOpen())
  579. parent=&workDir;
  580. if(!newfile.open(*parent,relpath, O_READ))
  581. {
  582. SERIAL_ECHO_START;
  583. SERIAL_ECHORPGM(MSG_SD_CANT_ENTER_SUBDIR);
  584. SERIAL_ECHOLN(relpath);
  585. }
  586. else
  587. {
  588. if (workDirDepth < MAX_DIR_DEPTH) {
  589. for (int d = ++workDirDepth; d--;)
  590. workDirParents[d+1] = workDirParents[d];
  591. workDirParents[0]=*parent;
  592. }
  593. workDir=newfile;
  594. }
  595. }
  596. void CardReader::updir()
  597. {
  598. if(workDirDepth > 0)
  599. {
  600. --workDirDepth;
  601. workDir = workDirParents[0];
  602. int d;
  603. for (int d = 0; d < workDirDepth; d++)
  604. workDirParents[d] = workDirParents[d+1];
  605. }
  606. }
  607. #ifdef SDCARD_SORT_ALPHA
  608. /**
  609. * Get the name of a file in the current directory by sort-index
  610. */
  611. void CardReader::getfilename_sorted(const uint16_t nr) {
  612. getfilename(
  613. #if SDSORT_GCODE
  614. sort_alpha &&
  615. #endif
  616. (nr < sort_count) ? sort_order[nr] : nr
  617. );
  618. }
  619. /**
  620. * Read all the files and produce a sort key
  621. *
  622. * We can do this in 3 ways...
  623. * - Minimal RAM: Read two filenames at a time sorting along...
  624. * - Some RAM: Buffer the directory just for this sort
  625. * - Most RAM: Buffer the directory and return filenames from RAM
  626. */
  627. void CardReader::presort() {
  628. uint8_t sdSort = eeprom_read_byte((uint8_t*)EEPROM_SD_SORT);
  629. if (sdSort == 2) return; //sd sort is turned off
  630. #if !SDSORT_USES_RAM
  631. lcd_set_progress();
  632. #endif
  633. lcd_implementation_clear();
  634. lcd_print_at_PGM(0, 1, MSG_SORTING);
  635. #if SDSORT_GCODE
  636. if (!sort_alpha) return;
  637. #endif
  638. // Throw away old sort index
  639. flush_presort();
  640. // If there are files, sort up to the limit
  641. uint16_t fileCnt = getnrfilenames();
  642. if (fileCnt > 0) {
  643. // Never sort more than the max allowed
  644. // If you use folders to organize, 20 may be enough
  645. if (fileCnt > SDSORT_LIMIT) fileCnt = SDSORT_LIMIT;
  646. // Sort order is always needed. May be static or dynamic.
  647. #if SDSORT_DYNAMIC_RAM
  648. sort_order = new uint8_t[fileCnt];
  649. #endif
  650. // Use RAM to store the entire directory during pre-sort.
  651. // SDSORT_LIMIT should be set to prevent over-allocation.
  652. #if SDSORT_USES_RAM
  653. // If using dynamic ram for names, allocate on the heap.
  654. #if SDSORT_CACHE_NAMES
  655. #if SDSORT_DYNAMIC_RAM
  656. sortshort = new char*[fileCnt];
  657. sortnames = new char*[fileCnt];
  658. #endif
  659. #elif SDSORT_USES_STACK
  660. char sortnames[fileCnt][LONG_FILENAME_LENGTH];
  661. uint16_t creation_time[SDSORT_LIMIT];
  662. uint16_t creation_date[SDSORT_LIMIT];
  663. #endif
  664. // Folder sorting needs 1 bit per entry for flags.
  665. #if HAS_FOLDER_SORTING
  666. #if SDSORT_DYNAMIC_RAM
  667. isDir = new uint8_t[(fileCnt + 7) >> 3];
  668. #elif SDSORT_USES_STACK
  669. uint8_t isDir[(fileCnt + 7) >> 3];
  670. #endif
  671. #endif
  672. #else // !SDSORT_USES_RAM
  673. // By default re-read the names from SD for every compare
  674. // retaining only two filenames at a time. This is very
  675. // slow but is safest and uses minimal RAM.
  676. char name1[LONG_FILENAME_LENGTH + 1];
  677. uint16_t creation_time_bckp;
  678. uint16_t creation_date_bckp;
  679. #endif
  680. if (fileCnt > 1) {
  681. // Init sort order.
  682. for (uint16_t i = 0; i < fileCnt; i++) {
  683. sort_order[i] = i;
  684. // If using RAM then read all filenames now.
  685. #if SDSORT_USES_RAM
  686. getfilename(i);
  687. #if SDSORT_DYNAMIC_RAM
  688. // Use dynamic method to copy long filename
  689. sortnames[i] = strdup(LONGEST_FILENAME);
  690. #if SDSORT_CACHE_NAMES
  691. // When caching also store the short name, since
  692. // we're replacing the getfilename() behavior.
  693. sortshort[i] = strdup(filename);
  694. #endif
  695. #else
  696. // Copy filenames into the static array
  697. strcpy(sortnames[i], LONGEST_FILENAME);
  698. creation_time[i] = creationTime;
  699. creation_date[i] = creationDate;
  700. #if SDSORT_CACHE_NAMES
  701. strcpy(sortshort[i], filename);
  702. #endif
  703. #endif
  704. // char out[30];
  705. // sprintf_P(out, PSTR("---- %i %s %s"), i, filenameIsDir ? "D" : " ", sortnames[i]);
  706. // SERIAL_ECHOLN(out);
  707. #if HAS_FOLDER_SORTING
  708. const uint16_t bit = i & 0x07, ind = i >> 3;
  709. if (bit == 0) isDir[ind] = 0x00;
  710. if (filenameIsDir) isDir[ind] |= _BV(bit);
  711. #endif
  712. #endif
  713. }
  714. // Bubble Sort
  715. uint16_t counter = 0;
  716. for (uint16_t i = fileCnt; --i;) {
  717. bool didSwap = false;
  718. #if !SDSORT_USES_RAM //show progresss bar only if slow sorting method is used
  719. int8_t percent = ((counter * 100) / (fileCnt-1));
  720. for (int column = 0; column < 20; column++) {
  721. if (column < (percent/5)) lcd_implementation_print_at(column, 2, "\x01"); //simple progress bar
  722. }
  723. counter++;
  724. #endif
  725. //MYSERIAL.println(int(i));
  726. for (uint16_t j = 0; j < i; ++j) {
  727. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  728. // Compare names from the array or just the two buffered names
  729. #if SDSORT_USES_RAM
  730. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  731. #define _SORT_CMP_TIME_NODIR() (((creation_date[o1] == creation_date[o2]) && (creation_time[o1] < creation_time[o2])) || \
  732. (creation_date[o1] < creation_date [o2]))
  733. #else
  734. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0) //true if lowercase(name1) > lowercase(name2)
  735. #define _SORT_CMP_TIME_NODIR() (((creation_date_bckp == creationDate) && (creation_time_bckp < creationTime)) || \
  736. (creation_date_bckp < creationDate))
  737. #endif
  738. #if HAS_FOLDER_SORTING
  739. #if SDSORT_USES_RAM
  740. // Folder sorting needs an index and bit to test for folder-ness.
  741. const uint8_t ind1 = o1 >> 3, bit1 = o1 & 0x07,
  742. ind2 = o2 >> 3, bit2 = o2 & 0x07;
  743. #define _SORT_CMP_DIR(fs) \
  744. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  745. ? _SORT_CMP_NODIR() \
  746. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  747. #define _SORT_CMP_TIME_DIR(fs) \
  748. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  749. ? _SORT_CMP_TIME_NODIR() \
  750. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  751. #else
  752. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  753. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs > 0 ? dir1 : !dir1))
  754. #endif
  755. #endif
  756. // The most economical method reads names as-needed
  757. // throughout the loop. Slow if there are many.
  758. #if !SDSORT_USES_RAM
  759. getfilename(o1);
  760. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  761. creation_date_bckp = creationDate;
  762. creation_time_bckp = creationTime;
  763. #if HAS_FOLDER_SORTING
  764. bool dir1 = filenameIsDir;
  765. #endif
  766. getfilename(o2);
  767. char *name2 = LONGEST_FILENAME; // use the string in-place
  768. #endif // !SDSORT_USES_RAM
  769. // Sort the current pair according to settings.
  770. if(
  771. #if HAS_FOLDER_SORTING
  772. (sdSort == 0 && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == 1 && _SORT_CMP_DIR(FOLDER_SORTING))
  773. #else
  774. (sdSort == 0 && _SORT_CMP_TIME_NODIR()) || (sdSort == 1 && _SORT_CMP_NODIR())
  775. #endif
  776. )
  777. {
  778. sort_order[j] = o2;
  779. sort_order[j + 1] = o1;
  780. didSwap = true;
  781. //SERIAL_ECHOLNPGM("did swap");
  782. }
  783. }
  784. if (!didSwap) break;
  785. } //end of bubble sort loop
  786. // Using RAM but not keeping names around
  787. #if (SDSORT_USES_RAM && !SDSORT_CACHE_NAMES)
  788. #if SDSORT_DYNAMIC_RAM
  789. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  790. #if HAS_FOLDER_SORTING
  791. free(isDir);
  792. #endif
  793. #endif
  794. #endif
  795. }
  796. else {
  797. sort_order[0] = 0;
  798. #if (SDSORT_USES_RAM && SDSORT_CACHE_NAMES)
  799. getfilename(0);
  800. #if SDSORT_DYNAMIC_RAM
  801. sortnames = new char*[1];
  802. sortnames[0] = strdup(LONGEST_FILENAME); // malloc
  803. sortshort = new char*[1];
  804. sortshort[0] = strdup(filename); // malloc
  805. isDir = new uint8_t[1];
  806. #else
  807. strcpy(sortnames[0], LONGEST_FILENAME);
  808. strcpy(sortshort[0], filename);
  809. #endif
  810. isDir[0] = filenameIsDir ? 0x01 : 0x00;
  811. #endif
  812. }
  813. sort_count = fileCnt;
  814. }
  815. #if !SDSORT_USES_RAM //show progresss bar only if slow sorting method is used
  816. for(int column = 0; column <=19; column++ ) lcd_implementation_print_at(column, 2, "\x01"); //simple progress bar
  817. delay(500);
  818. lcd_set_arrows();
  819. lcd_update(2);
  820. #endif
  821. }
  822. void CardReader::flush_presort() {
  823. if (sort_count > 0) {
  824. #if SDSORT_DYNAMIC_RAM
  825. delete sort_order;
  826. #if SDSORT_CACHE_NAMES
  827. for (uint8_t i = 0; i < sort_count; ++i) {
  828. free(sortshort[i]); // strdup
  829. free(sortnames[i]); // strdup
  830. }
  831. delete sortshort;
  832. delete sortnames;
  833. #endif
  834. #endif
  835. sort_count = 0;
  836. }
  837. }
  838. #endif // SDCARD_SORT_ALPHA
  839. void CardReader::printingHasFinished()
  840. {
  841. st_synchronize();
  842. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  843. {
  844. file.close();
  845. file_subcall_ctr--;
  846. openFile(filenames[file_subcall_ctr],true,true);
  847. setIndex(filespos[file_subcall_ctr]);
  848. startFileprint();
  849. }
  850. else
  851. {
  852. quickStop();
  853. file.close();
  854. sdprinting = false;
  855. if(SD_FINISHED_STEPPERRELEASE)
  856. {
  857. //finishAndDisableSteppers();
  858. enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  859. }
  860. autotempShutdown();
  861. #ifdef SDCARD_SORT_ALPHA
  862. presort();
  863. #endif
  864. }
  865. }
  866. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  867. {
  868. memset(ip, 0, 4);
  869. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  870. }
  871. #endif //SDSUPPORT