cardreader.cpp 26 KB

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