cardreader.cpp 29 KB

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