cardreader.cpp 26 KB

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