cardreader.cpp 27 KB

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