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