cardreader.cpp 26 KB

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