cardreader.cpp 29 KB

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