cardreader.cpp 27 KB

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