cardreader.cpp 27 KB

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