cardreader.cpp 29 KB

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