cardreader.cpp 28 KB

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