cardreader.cpp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. /**
  54. +* Dive into a folder and recurse depth-first to perform a pre-set operation lsAction:
  55. +* LS_Count - Add +1 to nrFiles for every file within the parent
  56. +* LS_GetFilename - Get the filename of the file indexed by nrFiles
  57. +* LS_SerialPrint - Print the full path and size of each file to serial output
  58. +*/
  59. void CardReader::lsDive(const char *prepend, SdFile parent, const char * const match/*=NULL*/) {
  60. dir_t p;
  61. uint8_t cnt = 0;
  62. // Read the next entry from a directory
  63. while (parent.readDir(p, longFilename) > 0) {
  64. // If the entry is a directory and the action is LS_SerialPrint
  65. if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) {
  66. // Get the short name for the item, which we know is a folder
  67. char lfilename[FILENAME_LENGTH];
  68. createFilename(lfilename, p);
  69. // Allocate enough stack space for the full path to a folder, trailing slash, and nul
  70. bool prepend_is_empty = (prepend[0] == '\0');
  71. int len = (prepend_is_empty ? 1 : strlen(prepend)) + strlen(lfilename) + 1 + 1;
  72. char path[len];
  73. // Append the FOLDERNAME12/ to the passed string.
  74. // It contains the full path to the "parent" argument.
  75. // We now have the full path to the item in this folder.
  76. strcpy(path, prepend_is_empty ? "/" : prepend); // root slash if prepend is empty
  77. strcat(path, lfilename); // FILENAME_LENGTH-1 characters maximum
  78. strcat(path, "/"); // 1 character
  79. // Serial.print(path);
  80. // Get a new directory object using the full path
  81. // and dive recursively into it.
  82. SdFile dir;
  83. if (!dir.open(parent, lfilename, O_READ)) {
  84. if (lsAction == LS_SerialPrint) {
  85. //SERIAL_ECHO_START();
  86. //SERIAL_ECHOPGM(_i("Cannot open subdir"));////MSG_SD_CANT_OPEN_SUBDIR
  87. //SERIAL_ECHOLN(lfilename);
  88. }
  89. }
  90. lsDive(path, dir);
  91. // close() is done automatically by destructor of SdFile
  92. }
  93. else {
  94. uint8_t pn0 = p.name[0];
  95. if (pn0 == DIR_NAME_FREE) break;
  96. if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue;
  97. if (longFilename[0] == '.') continue;
  98. if (!DIR_IS_FILE_OR_SUBDIR(&p) || (p.attributes & DIR_ATT_HIDDEN)) continue;
  99. filenameIsDir = DIR_IS_SUBDIR(&p);
  100. if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue;
  101. switch (lsAction) {
  102. case LS_Count:
  103. nrFiles++;
  104. break;
  105. case LS_SerialPrint:
  106. createFilename(filename, p);
  107. SERIAL_PROTOCOL(prepend);
  108. SERIAL_PROTOCOL(filename);
  109. MYSERIAL.write(' ');
  110. SERIAL_PROTOCOLLN(p.fileSize);
  111. break;
  112. case LS_GetFilename:
  113. //SERIAL_ECHOPGM("File: ");
  114. createFilename(filename, p);
  115. cluster = parent.curCluster();
  116. position = parent.curPosition();
  117. /*MYSERIAL.println(filename);
  118. SERIAL_ECHOPGM("Write date: ");
  119. writeDate = p.lastWriteDate;
  120. MYSERIAL.println(writeDate);
  121. writeTime = p.lastWriteTime;
  122. SERIAL_ECHOPGM("Creation date: ");
  123. MYSERIAL.println(p.creationDate);
  124. SERIAL_ECHOPGM("Access date: ");
  125. MYSERIAL.println(p.lastAccessDate);
  126. SERIAL_ECHOLNPGM("");*/
  127. modificationDate = p.lastWriteDate;
  128. modificationTime = p.lastWriteTime;
  129. //writeDate = p.lastAccessDate;
  130. if (match != NULL) {
  131. if (strcasecmp(match, filename) == 0) return;
  132. }
  133. else if (cnt == nrFiles) return;
  134. cnt++;
  135. break;
  136. }
  137. }
  138. } // while readDir
  139. }
  140. void CardReader::ls()
  141. {
  142. lsAction=LS_SerialPrint;
  143. //if(lsAction==LS_Count)
  144. //nrFiles=0;
  145. root.rewind();
  146. lsDive("",root);
  147. }
  148. void CardReader::initsd()
  149. {
  150. cardOK = false;
  151. if(root.isOpen())
  152. root.close();
  153. #ifdef SDSLOW
  154. if (!card.init(SPI_HALF_SPEED,SDSS)
  155. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  156. && !card.init(SPI_HALF_SPEED,LCD_SDSS)
  157. #endif
  158. )
  159. #else
  160. if (!card.init(SPI_FULL_SPEED,SDSS)
  161. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  162. && !card.init(SPI_FULL_SPEED,LCD_SDSS)
  163. #endif
  164. )
  165. #endif
  166. {
  167. //if (!card.init(SPI_HALF_SPEED,SDSS))
  168. SERIAL_ECHO_START;
  169. SERIAL_ECHOLNRPGM(_n("SD init fail"));////MSG_SD_INIT_FAIL
  170. }
  171. else if (!volume.init(&card))
  172. {
  173. SERIAL_ERROR_START;
  174. SERIAL_ERRORLNRPGM(_n("volume.init failed"));////MSG_SD_VOL_INIT_FAIL
  175. }
  176. else if (!root.openRoot(&volume))
  177. {
  178. SERIAL_ERROR_START;
  179. SERIAL_ERRORLNRPGM(_n("openRoot failed"));////MSG_SD_OPENROOT_FAIL
  180. }
  181. else
  182. {
  183. cardOK = true;
  184. SERIAL_ECHO_START;
  185. SERIAL_ECHOLNRPGM(_n("SD card ok"));////MSG_SD_CARD_OK
  186. }
  187. workDir=root;
  188. curDir=&root;
  189. workDirDepth = 0;
  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. Stopped = false;
  223. #ifdef SDCARD_SORT_ALPHA
  224. //flush_presort();
  225. #endif
  226. }
  227. }
  228. void CardReader::openLogFile(const char* name)
  229. {
  230. logging = true;
  231. openFile(name, false);
  232. }
  233. void CardReader::getDirName(char* name, uint8_t level)
  234. {
  235. workDirParents[level].getFilename(name);
  236. }
  237. uint16_t CardReader::getWorkDirDepth() {
  238. return workDirDepth;
  239. }
  240. void CardReader::getAbsFilename(char *t)
  241. {
  242. uint8_t cnt=0;
  243. *t='/';t++;cnt++;
  244. for(uint8_t i=0;i<workDirDepth;i++)
  245. {
  246. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  247. while(*t!=0 && cnt< MAXPATHNAMELENGTH)
  248. {t++;cnt++;} //crawl counter forward.
  249. }
  250. if(cnt<MAXPATHNAMELENGTH-13)
  251. file.getFilename(t);
  252. else
  253. t[0]=0;
  254. }
  255. /**
  256. * @brief Dive into subfolder
  257. *
  258. * Method sets curDir to point to root, in case fileName is null.
  259. * Method sets curDir to point to workDir, in case fileName path is relative
  260. * (doesn't start with '/')
  261. * Method sets curDir to point to dir, which is specified by absolute path
  262. * specified by fileName. In such case fileName is updated so it points to
  263. * file name without the path.
  264. *
  265. * @param[in,out] fileName
  266. * expects file name including path
  267. * in case of absolute path, file name without path is returned
  268. * @param[in,out] dir SdFile object to operate with,
  269. * in case of absolute path, curDir is modified to point to dir,
  270. * so it is not possible to create on stack inside this function,
  271. * as curDir would point to destroyed object.
  272. */
  273. void CardReader::diveSubfolder (const char *fileName, SdFile& dir)
  274. {
  275. curDir=&root;
  276. if (!fileName) return;
  277. const char *dirname_start, *dirname_end;
  278. if (fileName[0] == '/') // absolute path
  279. {
  280. dirname_start = fileName + 1;
  281. while (*dirname_start)
  282. {
  283. dirname_end = strchr(dirname_start, '/');
  284. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
  285. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name));
  286. if (dirname_end && dirname_end > dirname_start)
  287. {
  288. const size_t maxLen = 12;
  289. char subdirname[maxLen+1];
  290. subdirname[maxLen] = 0;
  291. const size_t len = ((static_cast<size_t>(dirname_end-dirname_start))>maxLen) ? maxLen : (dirname_end-dirname_start);
  292. strncpy(subdirname, dirname_start, len);
  293. SERIAL_ECHOLN(subdirname);
  294. if (!dir.open(curDir, subdirname, O_READ))
  295. {
  296. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  297. SERIAL_PROTOCOL(subdirname);
  298. SERIAL_PROTOCOLLNPGM(".");
  299. return;
  300. }
  301. else
  302. {
  303. //SERIAL_ECHOLN("dive ok");
  304. }
  305. curDir = &dir;
  306. dirname_start = dirname_end + 1;
  307. }
  308. else // the reminder after all /fsa/fdsa/ is the filename
  309. {
  310. fileName = dirname_start;
  311. //SERIAL_ECHOLN("remaider");
  312. //SERIAL_ECHOLN(fname);
  313. break;
  314. }
  315. }
  316. }
  317. else //relative path
  318. {
  319. curDir = &workDir;
  320. }
  321. }
  322. void CardReader::openFile(const char* name,bool read, bool replace_current/*=true*/)
  323. {
  324. if(!cardOK)
  325. return;
  326. if(file.isOpen()) //replacing current file by new file, or subfile call
  327. {
  328. if(!replace_current)
  329. {
  330. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1)
  331. {
  332. // SERIAL_ERROR_START;
  333. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  334. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  335. kill(_n("trying to call sub-gcode files with too many levels."), 1);
  336. return;
  337. }
  338. SERIAL_ECHO_START;
  339. SERIAL_ECHOPGM("SUBROUTINE CALL target:\"");
  340. SERIAL_ECHO(name);
  341. SERIAL_ECHOPGM("\" parent:\"");
  342. //store current filename and position
  343. getAbsFilename(filenames[file_subcall_ctr]);
  344. SERIAL_ECHO(filenames[file_subcall_ctr]);
  345. SERIAL_ECHOPGM("\" pos");
  346. SERIAL_ECHOLN(sdpos);
  347. filespos[file_subcall_ctr]=sdpos;
  348. file_subcall_ctr++;
  349. }
  350. else
  351. {
  352. SERIAL_ECHO_START;
  353. SERIAL_ECHOPGM("Now doing file: ");
  354. SERIAL_ECHOLN(name);
  355. }
  356. file.close();
  357. }
  358. else //opening fresh file
  359. {
  360. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  361. SERIAL_ECHO_START;
  362. SERIAL_ECHOPGM("Now fresh file: ");
  363. SERIAL_ECHOLN(name);
  364. }
  365. sdprinting = false;
  366. SdFile myDir;
  367. const char *fname=name;
  368. diveSubfolder(fname,myDir);
  369. if(read)
  370. {
  371. if (file.open(curDir, fname, O_READ))
  372. {
  373. filesize = file.fileSize();
  374. SERIAL_PROTOCOLRPGM(_N("File opened: "));////MSG_SD_FILE_OPENED
  375. SERIAL_PROTOCOL(fname);
  376. SERIAL_PROTOCOLRPGM(_n(" Size: "));////MSG_SD_SIZE
  377. SERIAL_PROTOCOLLN(filesize);
  378. sdpos = 0;
  379. SERIAL_PROTOCOLLNRPGM(_N("File selected"));////MSG_SD_FILE_SELECTED
  380. getfilename(0, fname);
  381. lcd_setstatus(longFilename[0] ? longFilename : fname);
  382. lcd_setstatus("SD-PRINTING ");
  383. scrollstuff = 0;
  384. }
  385. else
  386. {
  387. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  388. SERIAL_PROTOCOL(fname);
  389. SERIAL_PROTOCOLLNPGM(".");
  390. }
  391. }
  392. else
  393. { //write
  394. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC))
  395. {
  396. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  397. SERIAL_PROTOCOL(fname);
  398. SERIAL_PROTOCOLLNPGM(".");
  399. }
  400. else
  401. {
  402. saving = true;
  403. SERIAL_PROTOCOLRPGM(_N("Writing to file: "));////MSG_SD_WRITE_TO_FILE
  404. SERIAL_PROTOCOLLN(name);
  405. lcd_setstatus(fname);
  406. }
  407. }
  408. }
  409. void CardReader::removeFile(const char* name)
  410. {
  411. if(!cardOK) return;
  412. file.close();
  413. sdprinting = false;
  414. SdFile myDir;
  415. const char *fname=name;
  416. diveSubfolder(fname,myDir);
  417. if (file.remove(curDir, fname))
  418. {
  419. SERIAL_PROTOCOLPGM("File deleted:");
  420. SERIAL_PROTOCOLLN(fname);
  421. sdpos = 0;
  422. #ifdef SDCARD_SORT_ALPHA
  423. presort();
  424. #endif
  425. }
  426. else
  427. {
  428. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  429. SERIAL_PROTOCOL(fname);
  430. SERIAL_PROTOCOLLNPGM(".");
  431. }
  432. }
  433. uint32_t CardReader::getFileSize()
  434. {
  435. return filesize;
  436. }
  437. void CardReader::getStatus()
  438. {
  439. if(sdprinting)
  440. {
  441. if (isPrintPaused) {
  442. SERIAL_PROTOCOLLNPGM("SD print paused");
  443. }
  444. else if (saved_printing) {
  445. SERIAL_PROTOCOLLNPGM("Print saved");
  446. }
  447. else {
  448. SERIAL_PROTOCOL(longFilename);
  449. SERIAL_PROTOCOLPGM("\n");
  450. SERIAL_PROTOCOLRPGM(_N("SD printing byte "));////MSG_SD_PRINTING_BYTE
  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. }
  461. else {
  462. SERIAL_PROTOCOLLNPGM("Not SD 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(_n("Cannot enter subdir: "));////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 (unsigned int d = 0; d < workDirDepth; d++)
  614. {
  615. workDirParents[d] = workDirParents[d+1];
  616. }
  617. #ifdef SDCARD_SORT_ALPHA
  618. presort();
  619. #endif
  620. }
  621. }
  622. #ifdef SDCARD_SORT_ALPHA
  623. /**
  624. * Get the name of a file in the current directory by sort-index
  625. */
  626. void CardReader::getfilename_sorted(const uint16_t nr) {
  627. if (nr < sort_count)
  628. getfilename_simple(
  629. #if SDSORT_GCODE
  630. sort_alpha &&
  631. #endif
  632. sort_positions[sort_order[nr]]
  633. );
  634. else
  635. getfilename(
  636. #if SDSORT_GCODE
  637. sort_alpha &&
  638. #endif
  639. nr
  640. );
  641. }
  642. /**
  643. * Read all the files and produce a sort key
  644. *
  645. * We can do this in 3 ways...
  646. * - Minimal RAM: Read two filenames at a time sorting along...
  647. * - Some RAM: Buffer the directory just for this sort
  648. * - Most RAM: Buffer the directory and return filenames from RAM
  649. */
  650. void CardReader::presort() {
  651. if (farm_mode || IS_SD_INSERTED == false) return; //sorting is not used in farm mode
  652. uint8_t sdSort = eeprom_read_byte((uint8_t*)EEPROM_SD_SORT);
  653. if (sdSort == SD_SORT_NONE) return; //sd sort is turned off
  654. #if SDSORT_GCODE
  655. if (!sort_alpha) return;
  656. #endif
  657. KEEPALIVE_STATE(IN_HANDLER);
  658. // Throw away old sort index
  659. flush_presort();
  660. // If there are files, sort up to the limit
  661. uint16_t fileCnt = getnrfilenames();
  662. if (fileCnt > 0) {
  663. // Never sort more than the max allowed
  664. // If you use folders to organize, 20 may be enough
  665. if (fileCnt > SDSORT_LIMIT) {
  666. 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
  667. fileCnt = SDSORT_LIMIT;
  668. }
  669. lcd_clear();
  670. // uint32_t positions[fileCnt];
  671. // By default re-read the names from SD for every compare
  672. // retaining only two filenames at a time. This is very
  673. // slow but is safest and uses minimal RAM.
  674. char name1[LONG_FILENAME_LENGTH + 1];
  675. uint16_t modification_time_bckp;
  676. uint16_t modification_date_bckp;
  677. #if HAS_FOLDER_SORTING
  678. uint16_t dirCnt = 0;
  679. #endif
  680. position = 0;
  681. //might need to also load the file at position 0 for filenameIsDir to work on the first file
  682. if (fileCnt > 1) {
  683. // Init sort order.
  684. for (uint16_t i = 0; i < fileCnt; i++) {
  685. if (!IS_SD_INSERTED) return;
  686. manage_heater();
  687. sort_order[i] = i;
  688. sort_positions[i] = position;
  689. getfilename(i);
  690. #if HAS_FOLDER_SORTING
  691. if (filenameIsDir) dirCnt++;
  692. #endif
  693. }
  694. #ifdef QUICKSORT
  695. quicksort(0, fileCnt - 1);
  696. #elif defined(SHELLSORT)
  697. #define _SORT_CMP_NODIR() (strcasecmp(name2, name1) < 0)
  698. #define _SORT_CMP_TIME_NODIR() (((modification_date_bckp == modificationDate) && (modification_time_bckp < modificationTime)) || (modification_date_bckp < modificationDate))
  699. #if HAS_FOLDER_SORTING
  700. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? filenameIsDir : !filenameIsDir))
  701. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? filenameIsDir : !filenameIsDir))
  702. #endif
  703. for (uint8_t runs = 0; runs < 2; runs++)
  704. {
  705. uint8_t* sortingBaseArray;
  706. //run=0: sorts all files and moves folders to the beginning
  707. //run=1: assumes all folders are at the beginning of the list and sorts them
  708. lcd_set_cursor(0, 1);
  709. lcd_printf_P(PSTR("%-20.20S"), (runs == 0)?_i("Sorting files"):_i("Sorting folders"));
  710. uint16_t sortCountFiles = 0;
  711. if (runs == 0)
  712. {
  713. sortingBaseArray = sort_order;
  714. sortCountFiles = fileCnt;
  715. }
  716. #if HAS_FOLDER_SORTING
  717. else
  718. {
  719. sortingBaseArray = sort_order + /* sizeof(sort_order[0]) * */ (fileCnt - dirCnt);
  720. sortCountFiles = dirCnt;
  721. }
  722. #endif
  723. if (sortCountFiles < 2) break;
  724. uint16_t counter = 0;
  725. uint16_t total = 0;
  726. for (uint16_t i = sortCountFiles/2; i > 0; i /= 2) total += sortCountFiles - i; //total runs for progress bar
  727. for (uint16_t gap = sortCountFiles/2; gap > 0; gap /= 2)
  728. {
  729. for (uint16_t i = gap; i < sortCountFiles; i++)
  730. {
  731. if (!IS_SD_INSERTED) return;
  732. int8_t percent = (counter * 100) / total;
  733. lcd_set_cursor(0, 2);
  734. for (int column = 0; column < 20; column++) {
  735. if (column < (percent / 5)) lcd_print('\xFF'); //simple progress bar
  736. else lcd_print(' ');
  737. }
  738. counter++;
  739. manage_heater();
  740. uint8_t orderBckp = sortingBaseArray[i];
  741. getfilename_simple(sort_positions[orderBckp]);
  742. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  743. modification_date_bckp = modificationDate;
  744. modification_time_bckp = modificationTime;
  745. #if HAS_FOLDER_SORTING
  746. bool dir1 = filenameIsDir;
  747. #endif
  748. uint16_t j = i;
  749. getfilename_simple(sort_positions[sortingBaseArray[j - gap]]);
  750. char *name2 = LONGEST_FILENAME; // use the string in-place
  751. #if HAS_FOLDER_SORTING
  752. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_DIR(FOLDER_SORTING):_SORT_CMP_DIR(FOLDER_SORTING)))
  753. #else
  754. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_NODIR():_SORT_CMP_NODIR()))
  755. #endif
  756. {
  757. sortingBaseArray[j] = sortingBaseArray[j - gap];
  758. j -= gap;
  759. #ifdef SORTING_DUMP
  760. for (uint16_t z = 0; z < sortCountFiles; z++)
  761. {
  762. printf_P(PSTR("%2u "), sortingBaseArray[z]);
  763. }
  764. printf_P(PSTR("i%2d j%2d gap%2d orderBckp%2d\n"), i, j, gap, orderBckp);
  765. #endif
  766. if (j < gap) break;
  767. getfilename_simple(sort_positions[sortingBaseArray[j - gap]]);
  768. name2 = LONGEST_FILENAME; // use the string in-place
  769. }
  770. sortingBaseArray[j] = orderBckp;
  771. }
  772. }
  773. }
  774. #else //Bubble Sort
  775. uint32_t counter = 0;
  776. uint16_t total = 0.5*(fileCnt - 1)*(fileCnt);
  777. // Compare names from the array or just the two buffered names
  778. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  779. #define _SORT_CMP_TIME_NODIR() (((modification_date_bckp == modificationDate) && (modification_time_bckp > modificationTime)) || (modification_date_bckp > modificationDate))
  780. #if HAS_FOLDER_SORTING
  781. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  782. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  783. #endif
  784. for (uint16_t i = fileCnt; --i;) {
  785. if (!IS_SD_INSERTED) return;
  786. bool didSwap = false;
  787. int8_t percent = (counter * 100) / total;//((counter * 100) / pow((fileCnt-1),2));
  788. lcd_set_cursor(0, 2);
  789. for (int column = 0; column < 20; column++) {
  790. if (column < (percent / 5)) lcd_print('\xFF'); //simple progress bar
  791. else lcd_print(' ');
  792. }
  793. counter++;
  794. //MYSERIAL.println(int(i));
  795. for (uint16_t j = 0; j < i; ++j) {
  796. if (!IS_SD_INSERTED) return;
  797. #ifdef SORTING_DUMP
  798. for (uint16_t z = 0; z < fileCnt; z++)
  799. {
  800. printf_P(PSTR("%2u "), sort_order[z]);
  801. }
  802. MYSERIAL.println();
  803. #endif
  804. manage_heater();
  805. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  806. // The most economical method reads names as-needed
  807. // throughout the loop. Slow if there are many.
  808. #if !SDSORT_USES_RAM
  809. counter++;
  810. getfilename_simple(sort_positions[o1]);
  811. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  812. modification_date_bckp = modificationDate;
  813. modification_time_bckp = modificationTime;
  814. #if HAS_FOLDER_SORTING
  815. bool dir1 = filenameIsDir;
  816. #endif
  817. getfilename_simple(sort_positions[o2]);
  818. char *name2 = LONGEST_FILENAME; // use the string in-place
  819. #endif // !SDSORT_USES_RAM
  820. // Sort the current pair according to settings.
  821. if (
  822. #if HAS_FOLDER_SORTING
  823. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && _SORT_CMP_DIR(FOLDER_SORTING))
  824. #else
  825. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && _SORT_CMP_NODIR())
  826. #endif
  827. )
  828. {
  829. sort_order[j] = o2;
  830. sort_order[j + 1] = o1;
  831. didSwap = true;
  832. }
  833. }
  834. if (!didSwap) break;
  835. } //end of bubble sort loop
  836. #endif
  837. }
  838. else {
  839. sort_order[0] = 0;
  840. }
  841. sort_count = fileCnt;
  842. }
  843. #if !SDSORT_USES_RAM //show progresss bar only if slow sorting method is used
  844. lcd_set_cursor(0, 2);
  845. for (int column = 0; column <= 19; column++) lcd_print('\xFF'); //simple progress bar
  846. _delay(300);
  847. lcd_clear();
  848. #endif
  849. lcd_update(2);
  850. KEEPALIVE_STATE(NOT_BUSY);
  851. lcd_timeoutToStatus.start();
  852. }
  853. void CardReader::flush_presort() {
  854. if (sort_count > 0) {
  855. #if SDSORT_DYNAMIC_RAM
  856. delete sort_order;
  857. #if SDSORT_CACHE_NAMES
  858. for (uint8_t i = 0; i < sort_count; ++i) {
  859. free(sortshort[i]); // strdup
  860. free(sortnames[i]); // strdup
  861. }
  862. delete sortshort;
  863. delete sortnames;
  864. #endif
  865. #endif
  866. sort_count = 0;
  867. }
  868. }
  869. #endif // SDCARD_SORT_ALPHA
  870. void CardReader::printingHasFinished()
  871. {
  872. st_synchronize();
  873. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  874. {
  875. file.close();
  876. file_subcall_ctr--;
  877. openFile(filenames[file_subcall_ctr],true,true);
  878. setIndex(filespos[file_subcall_ctr]);
  879. startFileprint();
  880. }
  881. else
  882. {
  883. quickStop();
  884. file.close();
  885. sdprinting = false;
  886. if(SD_FINISHED_STEPPERRELEASE)
  887. {
  888. finishAndDisableSteppers();
  889. //enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  890. }
  891. autotempShutdown();
  892. #ifdef SDCARD_SORT_ALPHA
  893. //presort();
  894. #endif
  895. }
  896. }
  897. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  898. {
  899. memset(ip, 0, 4);
  900. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  901. }
  902. #endif //SDSUPPORT