cardreader.cpp 26 KB

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