cardreader.cpp 27 KB

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