cardreader.cpp 30 KB

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