cardreader.cpp 25 KB

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