cardreader.cpp 28 KB

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