cardreader.cpp 26 KB

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