cardreader.cpp 26 KB

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