cardreader.cpp 27 KB

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