cardreader.cpp 28 KB

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