cardreader.cpp 29 KB

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