cardreader.cpp 26 KB

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