cardreader.cpp 27 KB

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