cardreader.cpp 27 KB

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