cardreader.cpp 29 KB

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