cardreader.cpp 26 KB

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