cardreader.cpp 29 KB

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