cardreader.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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)
  185. )
  186. #else
  187. if (!card.init(SPI_FULL_SPEED)
  188. )
  189. #endif
  190. {
  191. SERIAL_ECHO_START;
  192. SERIAL_ECHOLNRPGM(_n("SD init fail"));////MSG_SD_INIT_FAIL
  193. }
  194. else if (!volume.init(&card))
  195. {
  196. SERIAL_ERROR_START;
  197. SERIAL_ERRORLNRPGM(_n("volume.init failed"));////MSG_SD_VOL_INIT_FAIL
  198. }
  199. else if (!root.openRoot(&volume))
  200. {
  201. SERIAL_ERROR_START;
  202. SERIAL_ERRORLNRPGM(_n("openRoot failed"));////MSG_SD_OPENROOT_FAIL
  203. }
  204. else
  205. {
  206. cardOK = true;
  207. SERIAL_ECHO_START;
  208. SERIAL_ECHOLNRPGM(_n("SD card ok"));////MSG_SD_CARD_OK
  209. }
  210. workDir=root;
  211. curDir=&root;
  212. workDirDepth = 0;
  213. #ifdef SDCARD_SORT_ALPHA
  214. if (doPresort)
  215. presort();
  216. #endif
  217. /*
  218. if(!workDir.openRoot(&volume))
  219. {
  220. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  221. }
  222. */
  223. }
  224. void CardReader::setroot(bool doPresort)
  225. {
  226. workDir=root;
  227. workDirDepth = 0;
  228. curDir=&workDir;
  229. #ifdef SDCARD_SORT_ALPHA
  230. if (doPresort)
  231. presort();
  232. else
  233. presort_flag = true;
  234. #endif
  235. }
  236. void CardReader::release()
  237. {
  238. sdprinting = false;
  239. cardOK = false;
  240. SERIAL_ECHO_START;
  241. SERIAL_ECHOLNRPGM(_n("SD card released"));////MSG_SD_CARD_RELEASED
  242. }
  243. void CardReader::startFileprint()
  244. {
  245. if(cardOK)
  246. {
  247. sdprinting = true;
  248. Stopped = false;
  249. #ifdef SDCARD_SORT_ALPHA
  250. //flush_presort();
  251. #endif
  252. }
  253. }
  254. void CardReader::openLogFile(const char* name)
  255. {
  256. logging = true;
  257. openFileWrite(name);
  258. }
  259. void CardReader::getDirName(char* name, uint8_t level)
  260. {
  261. workDirParents[level].getFilename(name);
  262. }
  263. uint16_t CardReader::getWorkDirDepth() {
  264. return workDirDepth;
  265. }
  266. void CardReader::getAbsFilename(char *t)
  267. {
  268. uint8_t cnt=0;
  269. *t='/';t++;cnt++;
  270. for(uint8_t i=0;i<workDirDepth;i++)
  271. {
  272. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  273. while(*t!=0 && cnt< MAXPATHNAMELENGTH)
  274. {t++;cnt++;} //crawl counter forward.
  275. }
  276. if(cnt<MAXPATHNAMELENGTH-13)
  277. file.getFilename(t);
  278. else
  279. t[0]=0;
  280. }
  281. void CardReader::printAbsFilenameFast()
  282. {
  283. SERIAL_PROTOCOL('/');
  284. for (uint8_t i = 0; i < getWorkDirDepth(); i++)
  285. {
  286. SERIAL_PROTOCOL(dir_names[i]);
  287. SERIAL_PROTOCOL('/');
  288. }
  289. SERIAL_PROTOCOL(LONGEST_FILENAME);
  290. }
  291. /**
  292. * @brief Dive into subfolder
  293. *
  294. * Method sets curDir to point to root, in case fileName is null.
  295. * Method sets curDir to point to workDir, in case fileName path is relative
  296. * (doesn't start with '/')
  297. * Method sets curDir to point to dir, which is specified by absolute path
  298. * specified by fileName. In such case fileName is updated so it points to
  299. * file name without the path.
  300. *
  301. * @param[in,out] fileName
  302. * expects file name including path
  303. * in case of absolute path, file name without path is returned
  304. */
  305. bool CardReader::diveSubfolder (const char *&fileName)
  306. {
  307. curDir=&root;
  308. if (!fileName)
  309. return 1;
  310. const char *dirname_start, *dirname_end;
  311. if (fileName[0] == '/') // absolute path
  312. {
  313. setroot(false);
  314. dirname_start = fileName + 1;
  315. while (*dirname_start)
  316. {
  317. dirname_end = strchr(dirname_start, '/');
  318. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
  319. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name));
  320. if (dirname_end && dirname_end > dirname_start)
  321. {
  322. const size_t maxLen = 12;
  323. char subdirname[maxLen+1];
  324. const size_t len = ((static_cast<size_t>(dirname_end-dirname_start))>maxLen) ? maxLen : (dirname_end-dirname_start);
  325. strncpy(subdirname, dirname_start, len);
  326. subdirname[len] = 0;
  327. if (!chdir(subdirname, false))
  328. return 0;
  329. curDir = &workDir;
  330. dirname_start = dirname_end + 1;
  331. }
  332. else // the reminder after all /fsa/fdsa/ is the filename
  333. {
  334. fileName = dirname_start;
  335. //SERIAL_ECHOLN("remaider");
  336. //SERIAL_ECHOLN(fname);
  337. break;
  338. }
  339. }
  340. }
  341. else //relative path
  342. {
  343. curDir = &workDir;
  344. }
  345. return 1;
  346. }
  347. static const char ofKill[] PROGMEM = "trying to call sub-gcode files with too many levels.";
  348. static const char ofSubroutineCallTgt[] PROGMEM = "SUBROUTINE CALL target:\"";
  349. static const char ofParent[] PROGMEM = "\" parent:\"";
  350. static const char ofPos[] PROGMEM = "\" pos";
  351. static const char ofNowDoingFile[] PROGMEM = "Now doing file: ";
  352. static const char ofNowFreshFile[] PROGMEM = "Now fresh file: ";
  353. static const char ofFileOpened[] PROGMEM = "File opened: ";
  354. static const char ofSize[] PROGMEM = " Size: ";
  355. static const char ofFileSelected[] PROGMEM = "File selected";
  356. static const char ofSDPrinting[] PROGMEM = "SD-PRINTING";
  357. static const char ofWritingToFile[] PROGMEM = "Writing to file: ";
  358. void CardReader::openFileReadFilteredGcode(const char* name, bool replace_current/* = false*/){
  359. if(!cardOK)
  360. return;
  361. if(file.isOpen()){ //replacing current file by new file, or subfile call
  362. if(!replace_current){
  363. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1){
  364. // SERIAL_ERROR_START;
  365. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  366. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  367. kill(ofKill, 1);
  368. return;
  369. }
  370. SERIAL_ECHO_START;
  371. SERIAL_ECHORPGM(ofSubroutineCallTgt);
  372. SERIAL_ECHO(name);
  373. SERIAL_ECHORPGM(ofParent);
  374. //store current filename and position
  375. getAbsFilename(filenames[file_subcall_ctr]);
  376. SERIAL_ECHO(filenames[file_subcall_ctr]);
  377. SERIAL_ECHORPGM(ofPos);
  378. SERIAL_ECHOLN(sdpos);
  379. filespos[file_subcall_ctr]=sdpos;
  380. file_subcall_ctr++;
  381. } else {
  382. SERIAL_ECHO_START;
  383. SERIAL_ECHORPGM(ofNowDoingFile);
  384. SERIAL_ECHOLN(name);
  385. }
  386. file.close();
  387. } else { //opening fresh file
  388. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  389. SERIAL_ECHO_START;
  390. SERIAL_ECHORPGM(ofNowFreshFile);
  391. SERIAL_ECHOLN(name);
  392. }
  393. sdprinting = false;
  394. const char *fname=name;
  395. if (!diveSubfolder(fname))
  396. return;
  397. if (file.openFilteredGcode(curDir, fname)) {
  398. getfilename(0, fname);
  399. filesize = file.fileSize();
  400. SERIAL_PROTOCOLRPGM(ofFileOpened);////MSG_SD_FILE_OPENED
  401. printAbsFilenameFast();
  402. SERIAL_PROTOCOLRPGM(ofSize);////MSG_SD_SIZE
  403. SERIAL_PROTOCOLLN(filesize);
  404. sdpos = 0;
  405. SERIAL_PROTOCOLLNRPGM(ofFileSelected);////MSG_SD_FILE_SELECTED
  406. lcd_setstatuspgm(ofFileSelected);
  407. scrollstuff = 0;
  408. } else {
  409. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  410. SERIAL_PROTOCOL(fname);
  411. SERIAL_PROTOCOLLN('.');
  412. }
  413. }
  414. void CardReader::openFileWrite(const char* name)
  415. {
  416. if(!cardOK)
  417. return;
  418. if(file.isOpen()){ //replacing current file by new file, or subfile call
  419. #if 0
  420. // I doubt chained files support is necessary for file saving:
  421. // Intentionally disabled because it takes a lot of code size while being not used
  422. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1){
  423. // SERIAL_ERROR_START;
  424. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  425. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  426. kill(ofKill, 1);
  427. return;
  428. }
  429. SERIAL_ECHO_START;
  430. SERIAL_ECHORPGM(ofSubroutineCallTgt);
  431. SERIAL_ECHO(name);
  432. SERIAL_ECHORPGM(ofParent);
  433. //store current filename and position
  434. getAbsFilename(filenames[file_subcall_ctr]);
  435. SERIAL_ECHO(filenames[file_subcall_ctr]);
  436. SERIAL_ECHORPGM(ofPos);
  437. SERIAL_ECHOLN(sdpos);
  438. filespos[file_subcall_ctr]=sdpos;
  439. file_subcall_ctr++;
  440. file.close();
  441. #else
  442. SERIAL_ECHOLNPGM("File already opened");
  443. #endif
  444. } else { //opening fresh file
  445. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  446. SERIAL_ECHO_START;
  447. SERIAL_ECHORPGM(ofNowFreshFile);
  448. SERIAL_ECHOLN(name);
  449. }
  450. sdprinting = false;
  451. const char *fname=name;
  452. if (!diveSubfolder(fname))
  453. return;
  454. //write
  455. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)){
  456. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  457. SERIAL_PROTOCOL(fname);
  458. SERIAL_PROTOCOLLN('.');
  459. } else {
  460. saving = true;
  461. getfilename(0, fname);
  462. SERIAL_PROTOCOLRPGM(ofWritingToFile);////MSG_SD_WRITE_TO_FILE
  463. printAbsFilenameFast();
  464. SERIAL_PROTOCOLLN();
  465. SERIAL_PROTOCOLLNRPGM(ofFileSelected);////MSG_SD_FILE_SELECTED
  466. lcd_setstatuspgm(ofFileSelected);
  467. scrollstuff = 0;
  468. }
  469. }
  470. void CardReader::removeFile(const char* name)
  471. {
  472. if(!cardOK) return;
  473. file.close();
  474. sdprinting = false;
  475. const char *fname=name;
  476. if (!diveSubfolder(fname))
  477. return;
  478. if (file.remove(curDir, fname))
  479. {
  480. SERIAL_PROTOCOLPGM("File deleted:");
  481. SERIAL_PROTOCOLLN(fname);
  482. sdpos = 0;
  483. #ifdef SDCARD_SORT_ALPHA
  484. presort();
  485. #endif
  486. }
  487. else
  488. {
  489. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  490. SERIAL_PROTOCOL(fname);
  491. SERIAL_PROTOCOLLN('.');
  492. }
  493. }
  494. uint32_t CardReader::getFileSize()
  495. {
  496. return filesize;
  497. }
  498. void CardReader::getStatus(bool arg_P)
  499. {
  500. if (isPrintPaused)
  501. {
  502. if (saved_printing && (saved_printing_type == PRINTING_TYPE_SD))
  503. SERIAL_PROTOCOLLNPGM("SD print paused");
  504. else
  505. SERIAL_PROTOCOLLNPGM("Print saved");
  506. }
  507. else if (sdprinting)
  508. {
  509. if (arg_P)
  510. {
  511. printAbsFilenameFast();
  512. SERIAL_PROTOCOLLN();
  513. }
  514. else
  515. SERIAL_PROTOCOLLN(LONGEST_FILENAME);
  516. SERIAL_PROTOCOLRPGM(_N("SD printing byte "));////MSG_SD_PRINTING_BYTE
  517. SERIAL_PROTOCOL(sdpos);
  518. SERIAL_PROTOCOL('/');
  519. SERIAL_PROTOCOLLN(filesize);
  520. uint16_t time = ( _millis() - starttime ) / 60000U;
  521. SERIAL_PROTOCOL(itostr2(time/60));
  522. SERIAL_PROTOCOL(':');
  523. SERIAL_PROTOCOLLN(itostr2(time%60));
  524. }
  525. else
  526. SERIAL_PROTOCOLLNPGM("Not SD printing");
  527. }
  528. void CardReader::write_command(char *buf)
  529. {
  530. file.writeError = false;
  531. file.write(buf); //write command
  532. file.write("\r\n"); //write line termination
  533. if (file.writeError)
  534. {
  535. SERIAL_ERROR_START;
  536. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  537. }
  538. }
  539. #define CHUNK_SIZE 64
  540. void CardReader::write_command_no_newline(char *buf)
  541. {
  542. file.write(buf, CHUNK_SIZE);
  543. if (file.writeError)
  544. {
  545. SERIAL_ERROR_START;
  546. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  547. SERIAL_PROTOCOLLNPGM("An error while writing to the SD Card.");
  548. }
  549. }
  550. void CardReader::checkautostart(bool force)
  551. {
  552. if(!force)
  553. {
  554. if(!autostart_stilltocheck)
  555. return;
  556. if(autostart_atmillis<_millis())
  557. return;
  558. }
  559. autostart_stilltocheck=false;
  560. if(!cardOK)
  561. {
  562. initsd();
  563. if(!cardOK) //fail
  564. return;
  565. }
  566. char autoname[30];
  567. sprintf_P(autoname, PSTR("auto%i.g"), lastnr);
  568. for(int8_t i=0;i<(int8_t)strlen(autoname);i++)
  569. autoname[i]=tolower(autoname[i]);
  570. dir_t p;
  571. root.rewind();
  572. bool found=false;
  573. while (root.readDir(p, NULL) > 0)
  574. {
  575. for(int8_t i=0;i<(int8_t)strlen((char*)p.name);i++)
  576. p.name[i]=tolower(p.name[i]);
  577. //Serial.print((char*)p.name);
  578. //Serial.print(" ");
  579. //Serial.println(autoname);
  580. if(p.name[9]!='~') //skip safety copies
  581. if(strncmp((char*)p.name,autoname,5)==0)
  582. {
  583. char cmd[30];
  584. // M23: Select SD file
  585. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  586. enquecommand(cmd);
  587. // M24: Start/resume SD print
  588. enquecommand_P(PSTR("M24"));
  589. found=true;
  590. }
  591. }
  592. if(!found)
  593. lastnr=-1;
  594. else
  595. lastnr++;
  596. }
  597. void CardReader::closefile(bool store_location)
  598. {
  599. file.sync();
  600. file.close();
  601. saving = false;
  602. logging = false;
  603. if(store_location)
  604. {
  605. //future: store printer state, filename and position for continuing a stopped print
  606. // so one can unplug the printer and continue printing the next day.
  607. }
  608. }
  609. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/)
  610. {
  611. curDir=&workDir;
  612. nrFiles=nr;
  613. curDir->rewind();
  614. lsDive("",*curDir,match, LS_GetFilename);
  615. }
  616. void CardReader::getfilename_simple(uint32_t position, const char * const match/*=NULL*/)
  617. {
  618. curDir = &workDir;
  619. nrFiles = 0;
  620. curDir->seekSet(position);
  621. lsDive("", *curDir, match, LS_GetFilename);
  622. }
  623. void CardReader::getfilename_next(uint32_t position, const char * const match/*=NULL*/)
  624. {
  625. curDir = &workDir;
  626. nrFiles = 1;
  627. curDir->seekSet(position);
  628. lsDive("", *curDir, match, LS_GetFilename);
  629. }
  630. uint16_t CardReader::getnrfilenames()
  631. {
  632. curDir=&workDir;
  633. nrFiles=0;
  634. curDir->rewind();
  635. lsDive("",*curDir, NULL, LS_Count);
  636. //SERIAL_ECHOLN(nrFiles);
  637. return nrFiles;
  638. }
  639. bool CardReader::chdir(const char * relpath, bool doPresort)
  640. {
  641. SdFile newfile;
  642. SdFile *parent=&root;
  643. if(workDir.isOpen())
  644. parent=&workDir;
  645. if(!newfile.open(*parent,relpath, O_READ) || ((workDirDepth + 1) >= MAX_DIR_DEPTH))
  646. {
  647. SERIAL_ECHO_START;
  648. SERIAL_ECHORPGM(_n("Cannot enter subdir: "));////MSG_SD_CANT_ENTER_SUBDIR
  649. SERIAL_ECHOLN(relpath);
  650. return 0;
  651. }
  652. else
  653. {
  654. strcpy(dir_names[workDirDepth], relpath);
  655. puts(relpath);
  656. if (workDirDepth < MAX_DIR_DEPTH) {
  657. for (int d = ++workDirDepth; d--;)
  658. workDirParents[d+1] = workDirParents[d];
  659. workDirParents[0]=*parent;
  660. }
  661. workDir=newfile;
  662. #ifdef SDCARD_SORT_ALPHA
  663. if (doPresort)
  664. presort();
  665. else
  666. presort_flag = true;
  667. #endif
  668. return 1;
  669. }
  670. }
  671. void CardReader::updir()
  672. {
  673. if(workDirDepth > 0)
  674. {
  675. --workDirDepth;
  676. workDir = workDirParents[0];
  677. for (unsigned int d = 0; d < workDirDepth; d++)
  678. {
  679. workDirParents[d] = workDirParents[d+1];
  680. }
  681. #ifdef SDCARD_SORT_ALPHA
  682. presort();
  683. #endif
  684. }
  685. }
  686. #ifdef SDCARD_SORT_ALPHA
  687. /**
  688. * Get the name of a file in the current directory by sort-index
  689. */
  690. void CardReader::getfilename_sorted(const uint16_t nr, uint8_t sdSort) {
  691. if (nr < sort_count)
  692. getfilename_simple(sort_positions[(sdSort == SD_SORT_ALPHA) ? (sort_count - nr - 1) : nr]);
  693. else
  694. getfilename(nr);
  695. }
  696. /**
  697. * Read all the files and produce a sort key
  698. *
  699. * We can do this in 3 ways...
  700. * - Minimal RAM: Read two filenames at a time sorting along...
  701. * - Some RAM: Buffer the directory just for this sort
  702. * - Most RAM: Buffer the directory and return filenames from RAM
  703. */
  704. void CardReader::presort() {
  705. if (farm_mode || IS_SD_INSERTED == false) return; //sorting is not used in farm mode
  706. uint8_t sdSort = eeprom_read_byte((uint8_t*)EEPROM_SD_SORT);
  707. if (sdSort == SD_SORT_NONE) return; //sd sort is turned off
  708. KEEPALIVE_STATE(IN_HANDLER);
  709. // Throw away old sort index
  710. flush_presort();
  711. // If there are files, sort up to the limit
  712. uint16_t fileCnt = getnrfilenames();
  713. if (fileCnt > 0) {
  714. // Never sort more than the max allowed
  715. // If you use folders to organize, 20 may be enough
  716. if (fileCnt > SDSORT_LIMIT) {
  717. 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
  718. fileCnt = SDSORT_LIMIT;
  719. }
  720. // By default re-read the names from SD for every compare
  721. // retaining only two filenames at a time. This is very
  722. // slow but is safest and uses minimal RAM.
  723. char name1[LONG_FILENAME_LENGTH];
  724. uint16_t crmod_time_bckp;
  725. uint16_t crmod_date_bckp;
  726. #if HAS_FOLDER_SORTING
  727. uint16_t dirCnt = 0;
  728. #endif
  729. if (fileCnt > 1) {
  730. // Init sort order.
  731. uint8_t sort_order[fileCnt];
  732. for (uint16_t i = 0; i < fileCnt; i++) {
  733. if (!IS_SD_INSERTED) return;
  734. manage_heater();
  735. if (i == 0)
  736. getfilename(0);
  737. else
  738. getfilename_next(position);
  739. sort_order[i] = i;
  740. sort_positions[i] = position;
  741. #if HAS_FOLDER_SORTING
  742. if (filenameIsDir) dirCnt++;
  743. #endif
  744. }
  745. #ifdef QUICKSORT
  746. quicksort(0, fileCnt - 1);
  747. #elif defined(SHELLSORT)
  748. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  749. #define _SORT_CMP_TIME_NODIR() (((crmod_date_bckp == crmodDate) && (crmod_time_bckp < crmodTime)) || (crmod_date_bckp < crmodDate))
  750. #if HAS_FOLDER_SORTING
  751. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  752. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  753. #endif
  754. for (uint8_t runs = 0; runs < 2; runs++)
  755. {
  756. //run=0: sorts all files and moves folders to the beginning
  757. //run=1: assumes all folders are at the beginning of the list and sorts them
  758. uint16_t sortCountFiles = 0;
  759. if (runs == 0)
  760. {
  761. sortCountFiles = fileCnt;
  762. }
  763. #if HAS_FOLDER_SORTING
  764. else
  765. {
  766. sortCountFiles = dirCnt;
  767. }
  768. #endif
  769. uint16_t counter = 0;
  770. uint16_t total = 0;
  771. for (uint16_t i = sortCountFiles/2; i > 0; i /= 2) total += sortCountFiles - i; //total runs for progress bar
  772. menu_progressbar_init(total, (runs == 0)?_i("Sorting files"):_i("Sorting folders"));
  773. for (uint16_t gap = sortCountFiles/2; gap > 0; gap /= 2)
  774. {
  775. for (uint16_t i = gap; i < sortCountFiles; i++)
  776. {
  777. if (!IS_SD_INSERTED) return;
  778. menu_progressbar_update(counter);
  779. counter++;
  780. manage_heater();
  781. uint8_t orderBckp = sort_order[i];
  782. getfilename_simple(sort_positions[orderBckp]);
  783. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  784. crmod_date_bckp = crmodDate;
  785. crmod_time_bckp = crmodTime;
  786. #if HAS_FOLDER_SORTING
  787. bool dir1 = filenameIsDir;
  788. #endif
  789. uint16_t j = i;
  790. getfilename_simple(sort_positions[sort_order[j - gap]]);
  791. char *name2 = LONGEST_FILENAME; // use the string in-place
  792. #if HAS_FOLDER_SORTING
  793. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_DIR(FOLDER_SORTING):_SORT_CMP_DIR(FOLDER_SORTING)))
  794. #else
  795. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_NODIR():_SORT_CMP_NODIR()))
  796. #endif
  797. {
  798. sort_order[j] = sort_order[j - gap];
  799. j -= gap;
  800. #ifdef SORTING_DUMP
  801. for (uint16_t z = 0; z < sortCountFiles; z++)
  802. {
  803. printf_P(PSTR("%2u "), sort_order[z]);
  804. }
  805. printf_P(PSTR("i%2d j%2d gap%2d orderBckp%2d\n"), i, j, gap, orderBckp);
  806. #endif
  807. if (j < gap) break;
  808. getfilename_simple(sort_positions[sort_order[j - gap]]);
  809. name2 = LONGEST_FILENAME; // use the string in-place
  810. }
  811. sort_order[j] = orderBckp;
  812. }
  813. }
  814. }
  815. #else //Bubble Sort
  816. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  817. #define _SORT_CMP_TIME_NODIR() (((crmod_date_bckp == crmodDate) && (crmod_time_bckp > crmodTime)) || (crmod_date_bckp > crmodDate))
  818. #if HAS_FOLDER_SORTING
  819. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  820. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  821. #endif
  822. uint16_t counter = 0;
  823. menu_progressbar_init(0.5*(fileCnt - 1)*(fileCnt), _i("Sorting files"));
  824. for (uint16_t i = fileCnt; --i;) {
  825. if (!IS_SD_INSERTED) return;
  826. bool didSwap = false;
  827. menu_progressbar_update(counter);
  828. counter++;
  829. for (uint16_t j = 0; j < i; ++j) {
  830. if (!IS_SD_INSERTED) return;
  831. #ifdef SORTING_DUMP
  832. for (uint16_t z = 0; z < fileCnt; z++)
  833. {
  834. printf_P(PSTR("%2u "), sort_order[z]);
  835. }
  836. MYSERIAL.println();
  837. #endif
  838. manage_heater();
  839. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  840. counter++;
  841. getfilename_simple(sort_positions[o1]);
  842. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  843. crmod_date_bckp = crmodDate;
  844. crmod_time_bckp = crmodTime;
  845. #if HAS_FOLDER_SORTING
  846. bool dir1 = filenameIsDir;
  847. #endif
  848. getfilename_simple(sort_positions[o2]);
  849. char *name2 = LONGEST_FILENAME; // use the string in-place
  850. // Sort the current pair according to settings.
  851. if (
  852. #if HAS_FOLDER_SORTING
  853. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_DIR(FOLDER_SORTING))
  854. #else
  855. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_NODIR())
  856. #endif
  857. )
  858. {
  859. #ifdef SORTING_DUMP
  860. puts_P(PSTR("swap"));
  861. #endif
  862. sort_order[j] = o2;
  863. sort_order[j + 1] = o1;
  864. didSwap = true;
  865. }
  866. }
  867. if (!didSwap) break;
  868. } //end of bubble sort loop
  869. #endif
  870. #ifdef SORTING_DUMP
  871. for (uint16_t z = 0; z < fileCnt; z++)
  872. printf_P(PSTR("%2u "), sort_order[z]);
  873. SERIAL_PROTOCOLLN();
  874. #endif
  875. uint8_t sort_order_reverse_index[fileCnt];
  876. for (uint8_t i = 0; i < fileCnt; i++)
  877. sort_order_reverse_index[sort_order[i]] = i;
  878. for (uint8_t i = 0; i < fileCnt; i++)
  879. {
  880. if (sort_order_reverse_index[i] != i)
  881. {
  882. uint32_t el = sort_positions[i];
  883. uint8_t idx = sort_order_reverse_index[i];
  884. while (idx != i)
  885. {
  886. uint32_t el1 = sort_positions[idx];
  887. uint8_t idx1 = sort_order_reverse_index[idx];
  888. sort_order_reverse_index[idx] = idx;
  889. sort_positions[idx] = el;
  890. idx = idx1;
  891. el = el1;
  892. }
  893. sort_order_reverse_index[idx] = idx;
  894. sort_positions[idx] = el;
  895. }
  896. }
  897. menu_progressbar_finish();
  898. }
  899. else {
  900. getfilename(0);
  901. sort_positions[0] = position;
  902. }
  903. sort_count = fileCnt;
  904. }
  905. lcd_update(2);
  906. KEEPALIVE_STATE(NOT_BUSY);
  907. lcd_timeoutToStatus.start();
  908. }
  909. void CardReader::flush_presort() {
  910. if (sort_count > 0) {
  911. sort_count = 0;
  912. }
  913. }
  914. #endif // SDCARD_SORT_ALPHA
  915. void CardReader::printingHasFinished()
  916. {
  917. st_synchronize();
  918. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  919. {
  920. file.close();
  921. file_subcall_ctr--;
  922. openFileReadFilteredGcode(filenames[file_subcall_ctr],true);
  923. setIndex(filespos[file_subcall_ctr]);
  924. startFileprint();
  925. }
  926. else
  927. {
  928. quickStop();
  929. file.close();
  930. sdprinting = false;
  931. if(SD_FINISHED_STEPPERRELEASE)
  932. {
  933. finishAndDisableSteppers();
  934. //enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  935. }
  936. autotempShutdown();
  937. #ifdef SDCARD_SORT_ALPHA
  938. //presort();
  939. #endif
  940. }
  941. }
  942. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  943. {
  944. memset(ip, 0, 4);
  945. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  946. }
  947. #endif //SDSUPPORT