cardreader.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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(total, (runs == 0)?_i("Sorting files"):_i("Sorting folders"));
  780. for (uint16_t gap = sortCountFiles/2; gap > 0; gap /= 2)
  781. {
  782. for (uint16_t i = gap; i < sortCountFiles; i++)
  783. {
  784. if (!IS_SD_INSERTED) return;
  785. menu_progressbar_update(counter);
  786. counter++;
  787. manage_heater();
  788. uint8_t orderBckp = sort_order[i];
  789. getfilename_simple(sort_positions[orderBckp]);
  790. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  791. crmod_date_bckp = crmodDate;
  792. crmod_time_bckp = crmodTime;
  793. #if HAS_FOLDER_SORTING
  794. bool dir1 = filenameIsDir;
  795. #endif
  796. uint16_t j = i;
  797. getfilename_simple(sort_positions[sort_order[j - gap]]);
  798. char *name2 = LONGEST_FILENAME; // use the string in-place
  799. #if HAS_FOLDER_SORTING
  800. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_DIR(FOLDER_SORTING):_SORT_CMP_DIR(FOLDER_SORTING)))
  801. #else
  802. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_NODIR():_SORT_CMP_NODIR()))
  803. #endif
  804. {
  805. sort_order[j] = sort_order[j - gap];
  806. j -= gap;
  807. #ifdef SORTING_DUMP
  808. for (uint16_t z = 0; z < sortCountFiles; z++)
  809. {
  810. printf_P(PSTR("%2u "), sort_order[z]);
  811. }
  812. printf_P(PSTR("i%2d j%2d gap%2d orderBckp%2d\n"), i, j, gap, orderBckp);
  813. #endif
  814. if (j < gap) break;
  815. getfilename_simple(sort_positions[sort_order[j - gap]]);
  816. name2 = LONGEST_FILENAME; // use the string in-place
  817. }
  818. sort_order[j] = orderBckp;
  819. }
  820. }
  821. }
  822. #else //Bubble Sort
  823. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  824. #define _SORT_CMP_TIME_NODIR() (((crmod_date_bckp == crmodDate) && (crmod_time_bckp > crmodTime)) || (crmod_date_bckp > crmodDate))
  825. #if HAS_FOLDER_SORTING
  826. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  827. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  828. #endif
  829. uint16_t counter = 0;
  830. menu_progressbar_init(0.5*(fileCnt - 1)*(fileCnt), _i("Sorting files"));
  831. for (uint16_t i = fileCnt; --i;) {
  832. if (!IS_SD_INSERTED) return;
  833. bool didSwap = false;
  834. menu_progressbar_update(counter);
  835. counter++;
  836. for (uint16_t j = 0; j < i; ++j) {
  837. if (!IS_SD_INSERTED) return;
  838. #ifdef SORTING_DUMP
  839. for (uint16_t z = 0; z < fileCnt; z++)
  840. {
  841. printf_P(PSTR("%2u "), sort_order[z]);
  842. }
  843. MYSERIAL.println();
  844. #endif
  845. manage_heater();
  846. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  847. counter++;
  848. getfilename_simple(sort_positions[o1]);
  849. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  850. crmod_date_bckp = crmodDate;
  851. crmod_time_bckp = crmodTime;
  852. #if HAS_FOLDER_SORTING
  853. bool dir1 = filenameIsDir;
  854. #endif
  855. getfilename_simple(sort_positions[o2]);
  856. char *name2 = LONGEST_FILENAME; // use the string in-place
  857. // Sort the current pair according to settings.
  858. if (
  859. #if HAS_FOLDER_SORTING
  860. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_DIR(FOLDER_SORTING))
  861. #else
  862. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_NODIR())
  863. #endif
  864. )
  865. {
  866. #ifdef SORTING_DUMP
  867. puts_P(PSTR("swap"));
  868. #endif
  869. sort_order[j] = o2;
  870. sort_order[j + 1] = o1;
  871. didSwap = true;
  872. }
  873. }
  874. if (!didSwap) break;
  875. } //end of bubble sort loop
  876. #endif
  877. #ifdef SORTING_DUMP
  878. for (uint16_t z = 0; z < fileCnt; z++)
  879. printf_P(PSTR("%2u "), sort_order[z]);
  880. SERIAL_PROTOCOLLN();
  881. #endif
  882. uint8_t sort_order_reverse_index[fileCnt];
  883. for (uint8_t i = 0; i < fileCnt; i++)
  884. sort_order_reverse_index[sort_order[i]] = i;
  885. for (uint8_t i = 0; i < fileCnt; i++)
  886. {
  887. if (sort_order_reverse_index[i] != i)
  888. {
  889. uint32_t el = sort_positions[i];
  890. uint8_t idx = sort_order_reverse_index[i];
  891. while (idx != i)
  892. {
  893. uint32_t el1 = sort_positions[idx];
  894. uint8_t idx1 = sort_order_reverse_index[idx];
  895. sort_order_reverse_index[idx] = idx;
  896. sort_positions[idx] = el;
  897. idx = idx1;
  898. el = el1;
  899. }
  900. sort_order_reverse_index[idx] = idx;
  901. sort_positions[idx] = el;
  902. }
  903. }
  904. menu_progressbar_finish();
  905. }
  906. else {
  907. getfilename(0);
  908. sort_positions[0] = position;
  909. }
  910. sort_count = fileCnt;
  911. }
  912. lcd_update(2);
  913. KEEPALIVE_STATE(NOT_BUSY);
  914. }
  915. void CardReader::flush_presort() {
  916. if (sort_count > 0) {
  917. sort_count = 0;
  918. }
  919. }
  920. #endif // SDCARD_SORT_ALPHA
  921. void CardReader::printingHasFinished()
  922. {
  923. st_synchronize();
  924. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  925. {
  926. file.close();
  927. file_subcall_ctr--;
  928. openFileReadFilteredGcode(filenames[file_subcall_ctr],true);
  929. setIndex(filespos[file_subcall_ctr]);
  930. startFileprint();
  931. }
  932. else
  933. {
  934. quickStop();
  935. file.close();
  936. sdprinting = false;
  937. if(SD_FINISHED_STEPPERRELEASE)
  938. {
  939. finishAndDisableSteppers();
  940. //enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  941. }
  942. autotempShutdown();
  943. #ifdef SDCARD_SORT_ALPHA
  944. //presort();
  945. #endif
  946. }
  947. }
  948. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  949. {
  950. memset(ip, 0, 4);
  951. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  952. }
  953. #endif //SDSUPPORT