cardreader.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. scrollstuff = 0;
  384. }
  385. else
  386. {
  387. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  388. SERIAL_PROTOCOL(fname);
  389. SERIAL_PROTOCOLLNPGM(".");
  390. }
  391. }
  392. else
  393. { //write
  394. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC))
  395. {
  396. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  397. SERIAL_PROTOCOL(fname);
  398. SERIAL_PROTOCOLLNPGM(".");
  399. }
  400. else
  401. {
  402. saving = true;
  403. SERIAL_PROTOCOLRPGM(_N("Writing to file: "));////MSG_SD_WRITE_TO_FILE
  404. SERIAL_PROTOCOLLN(name);
  405. lcd_setstatus(fname);
  406. }
  407. }
  408. }
  409. void CardReader::removeFile(const char* name)
  410. {
  411. if(!cardOK) return;
  412. file.close();
  413. sdprinting = false;
  414. SdFile myDir;
  415. const char *fname=name;
  416. diveSubfolder(fname,myDir);
  417. if (file.remove(curDir, fname))
  418. {
  419. SERIAL_PROTOCOLPGM("File deleted:");
  420. SERIAL_PROTOCOLLN(fname);
  421. sdpos = 0;
  422. #ifdef SDCARD_SORT_ALPHA
  423. presort();
  424. #endif
  425. }
  426. else
  427. {
  428. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  429. SERIAL_PROTOCOL(fname);
  430. SERIAL_PROTOCOLLNPGM(".");
  431. }
  432. }
  433. uint32_t CardReader::getFileSize()
  434. {
  435. return filesize;
  436. }
  437. void CardReader::getStatus()
  438. {
  439. if(sdprinting)
  440. {
  441. if (isPrintPaused) {
  442. SERIAL_PROTOCOLLNPGM("SD print paused");
  443. }
  444. else if (saved_printing) {
  445. SERIAL_PROTOCOLLNPGM("Print saved");
  446. }
  447. else {
  448. SERIAL_PROTOCOL(longFilename);
  449. SERIAL_PROTOCOLPGM("\n");
  450. SERIAL_PROTOCOLRPGM(_N("SD printing byte "));////MSG_SD_PRINTING_BYTE
  451. SERIAL_PROTOCOL(sdpos);
  452. SERIAL_PROTOCOLPGM("/");
  453. SERIAL_PROTOCOLLN(filesize);
  454. uint16_t time = _millis()/60000 - starttime/60000;
  455. SERIAL_PROTOCOL(itostr2(time/60));
  456. SERIAL_PROTOCOL(':');
  457. SERIAL_PROTOCOL(itostr2(time%60));
  458. SERIAL_PROTOCOLPGM("\n");
  459. }
  460. }
  461. else {
  462. SERIAL_PROTOCOLLNPGM("Not SD printing");
  463. }
  464. }
  465. void CardReader::write_command(char *buf)
  466. {
  467. char* begin = buf;
  468. char* npos = 0;
  469. char* end = buf + strlen(buf) - 1;
  470. file.writeError = false;
  471. if((npos = strchr(buf, 'N')) != NULL)
  472. {
  473. begin = strchr(npos, ' ') + 1;
  474. end = strchr(npos, '*') - 1;
  475. }
  476. end[1] = '\r';
  477. end[2] = '\n';
  478. end[3] = '\0';
  479. file.write(begin);
  480. if (file.writeError)
  481. {
  482. SERIAL_ERROR_START;
  483. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  484. }
  485. }
  486. #define CHUNK_SIZE 64
  487. void CardReader::write_command_no_newline(char *buf)
  488. {
  489. file.write(buf, CHUNK_SIZE);
  490. if (file.writeError)
  491. {
  492. SERIAL_ERROR_START;
  493. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  494. MYSERIAL.println("An error while writing to the SD Card.");
  495. }
  496. }
  497. void CardReader::checkautostart(bool force)
  498. {
  499. if(!force)
  500. {
  501. if(!autostart_stilltocheck)
  502. return;
  503. if(autostart_atmillis<_millis())
  504. return;
  505. }
  506. autostart_stilltocheck=false;
  507. if(!cardOK)
  508. {
  509. initsd();
  510. if(!cardOK) //fail
  511. return;
  512. }
  513. char autoname[30];
  514. sprintf_P(autoname, PSTR("auto%i.g"), lastnr);
  515. for(int8_t i=0;i<(int8_t)strlen(autoname);i++)
  516. autoname[i]=tolower(autoname[i]);
  517. dir_t p;
  518. root.rewind();
  519. bool found=false;
  520. while (root.readDir(p, NULL) > 0)
  521. {
  522. for(int8_t i=0;i<(int8_t)strlen((char*)p.name);i++)
  523. p.name[i]=tolower(p.name[i]);
  524. //Serial.print((char*)p.name);
  525. //Serial.print(" ");
  526. //Serial.println(autoname);
  527. if(p.name[9]!='~') //skip safety copies
  528. if(strncmp((char*)p.name,autoname,5)==0)
  529. {
  530. char cmd[30];
  531. // M23: Select SD file
  532. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  533. enquecommand(cmd);
  534. // M24: Start/resume SD print
  535. enquecommand_P(PSTR("M24"));
  536. found=true;
  537. }
  538. }
  539. if(!found)
  540. lastnr=-1;
  541. else
  542. lastnr++;
  543. }
  544. void CardReader::closefile(bool store_location)
  545. {
  546. file.sync();
  547. file.close();
  548. saving = false;
  549. logging = false;
  550. if(store_location)
  551. {
  552. //future: store printer state, filename and position for continuing a stopped print
  553. // so one can unplug the printer and continue printing the next day.
  554. }
  555. }
  556. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/)
  557. {
  558. curDir=&workDir;
  559. lsAction=LS_GetFilename;
  560. nrFiles=nr;
  561. curDir->rewind();
  562. lsDive("",*curDir,match);
  563. }
  564. void CardReader::getfilename_simple(uint32_t position, const char * const match/*=NULL*/)
  565. {
  566. curDir = &workDir;
  567. lsAction = LS_GetFilename;
  568. nrFiles = 0;
  569. curDir->seekSet(position);
  570. lsDive("", *curDir, match);
  571. }
  572. uint16_t CardReader::getnrfilenames()
  573. {
  574. curDir=&workDir;
  575. lsAction=LS_Count;
  576. nrFiles=0;
  577. curDir->rewind();
  578. lsDive("",*curDir);
  579. //SERIAL_ECHOLN(nrFiles);
  580. return nrFiles;
  581. }
  582. void CardReader::chdir(const char * relpath)
  583. {
  584. SdFile newfile;
  585. SdFile *parent=&root;
  586. if(workDir.isOpen())
  587. parent=&workDir;
  588. if(!newfile.open(*parent,relpath, O_READ))
  589. {
  590. SERIAL_ECHO_START;
  591. SERIAL_ECHORPGM(_n("Cannot enter subdir: "));////MSG_SD_CANT_ENTER_SUBDIR
  592. SERIAL_ECHOLN(relpath);
  593. }
  594. else
  595. {
  596. if (workDirDepth < MAX_DIR_DEPTH) {
  597. for (int d = ++workDirDepth; d--;)
  598. workDirParents[d+1] = workDirParents[d];
  599. workDirParents[0]=*parent;
  600. }
  601. workDir=newfile;
  602. #ifdef SDCARD_SORT_ALPHA
  603. presort();
  604. #endif
  605. }
  606. }
  607. void CardReader::updir()
  608. {
  609. if(workDirDepth > 0)
  610. {
  611. --workDirDepth;
  612. workDir = workDirParents[0];
  613. for (unsigned int d = 0; d < workDirDepth; d++)
  614. {
  615. workDirParents[d] = workDirParents[d+1];
  616. }
  617. #ifdef SDCARD_SORT_ALPHA
  618. presort();
  619. #endif
  620. }
  621. }
  622. #ifdef SDCARD_SORT_ALPHA
  623. /**
  624. * Get the name of a file in the current directory by sort-index
  625. */
  626. void CardReader::getfilename_sorted(const uint16_t nr) {
  627. if (nr < sort_count)
  628. getfilename_simple(
  629. #if SDSORT_GCODE
  630. sort_alpha &&
  631. #endif
  632. sort_positions[sort_order[nr]]
  633. );
  634. else
  635. getfilename(
  636. #if SDSORT_GCODE
  637. sort_alpha &&
  638. #endif
  639. 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. lcd_puts_at_P(0, 1, _i("Sorting files"));////MSG_SORTING c=20 r=1
  671. // uint32_t positions[fileCnt];
  672. // By default re-read the names from SD for every compare
  673. // retaining only two filenames at a time. This is very
  674. // slow but is safest and uses minimal RAM.
  675. char name1[LONG_FILENAME_LENGTH + 1];
  676. uint16_t modification_time_bckp;
  677. uint16_t modification_date_bckp;
  678. #if HAS_FOLDER_SORTING
  679. uint16_t dirCnt = 0;
  680. #endif
  681. position = 0;
  682. //might need to also load the file at position 0 for filenameIsDir to work on the first file
  683. if (fileCnt > 1) {
  684. // Init sort order.
  685. for (uint16_t i = 0; i < fileCnt; i++) {
  686. if (!IS_SD_INSERTED) return;
  687. manage_heater();
  688. sort_order[i] = i;
  689. sort_positions[i] = position;
  690. getfilename(i);
  691. #if HAS_FOLDER_SORTING
  692. if (filenameIsDir) dirCnt++;
  693. #endif
  694. }
  695. #ifdef QUICKSORT
  696. quicksort(0, fileCnt - 1);
  697. #elif defined(SHELLSORT)
  698. #define _SORT_CMP_NODIR() (strcasecmp(name2, name1) < 0)
  699. #define _SORT_CMP_TIME_NODIR() (((modification_date_bckp == modificationDate) && (modification_time_bckp < modificationTime)) || (modification_date_bckp < modificationDate))
  700. #if HAS_FOLDER_SORTING
  701. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? filenameIsDir : !filenameIsDir))
  702. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? filenameIsDir : !filenameIsDir))
  703. #endif
  704. for (uint8_t runs = 0; runs < 2; runs++)
  705. {
  706. uint8_t* sortingBaseArray;
  707. //run=0: sorts all files and moves folders to the beginning
  708. //run=1: assumes all folders are at the beginning of the list and sorts them
  709. uint16_t sortCountFiles = 0;
  710. if (runs == 0)
  711. {
  712. sortingBaseArray = sort_order;
  713. sortCountFiles = fileCnt;
  714. }
  715. #if HAS_FOLDER_SORTING
  716. else
  717. {
  718. sortingBaseArray = sort_order + /* sizeof(sort_order[0]) * */ (fileCnt - dirCnt);
  719. sortCountFiles = dirCnt;
  720. }
  721. #endif
  722. if (sortCountFiles < 2) break;
  723. uint16_t counter = 0;
  724. uint16_t total = 0;
  725. for (uint16_t i = sortCountFiles/2; i > 0; i /= 2) total += sortCountFiles - i; //total runs for progress bar
  726. for (uint16_t gap = sortCountFiles/2; gap > 0; gap /= 2)
  727. {
  728. for (uint16_t i = gap; i < sortCountFiles; i++)
  729. {
  730. if (!IS_SD_INSERTED) return;
  731. int8_t percent = (counter * 100) / total;
  732. for (int column = 0; column < 20; column++) {
  733. if (column < (percent / 5))
  734. {
  735. lcd_set_cursor(column, 2);
  736. lcd_print('\xFF'); //simple progress bar
  737. }
  738. }
  739. counter++;
  740. manage_heater();
  741. uint8_t orderBckp = sortingBaseArray[i];
  742. getfilename_simple(sort_positions[orderBckp]);
  743. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  744. modification_date_bckp = modificationDate;
  745. modification_time_bckp = modificationTime;
  746. #if HAS_FOLDER_SORTING
  747. bool dir1 = filenameIsDir;
  748. #endif
  749. uint16_t j = i;
  750. getfilename_simple(sort_positions[sortingBaseArray[j - gap]]);
  751. char *name2 = LONGEST_FILENAME; // use the string in-place
  752. #if HAS_FOLDER_SORTING
  753. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_DIR(FOLDER_SORTING):_SORT_CMP_DIR(FOLDER_SORTING)))
  754. #else
  755. while (j >= gap && ((sdSort == SD_SORT_TIME)?_SORT_CMP_TIME_NODIR():_SORT_CMP_NODIR()))
  756. #endif
  757. {
  758. sortingBaseArray[j] = sortingBaseArray[j - gap];
  759. j -= gap;
  760. #ifdef SORTING_DUMP
  761. for (uint16_t z = 0; z < sortCountFiles; z++)
  762. {
  763. printf_P(PSTR("%2u "), sortingBaseArray[z]);
  764. }
  765. printf_P(PSTR("i%2d j%2d gap%2d orderBckp%2d\n"), i, j, gap, orderBckp);
  766. #endif
  767. if (j < gap) break;
  768. getfilename_simple(sort_positions[sortingBaseArray[j - gap]]);
  769. name2 = LONGEST_FILENAME; // use the string in-place
  770. }
  771. sortingBaseArray[j] = orderBckp;
  772. }
  773. }
  774. }
  775. #else //Bubble Sort
  776. uint32_t counter = 0;
  777. uint16_t total = 0.5*(fileCnt - 1)*(fileCnt);
  778. // Compare names from the array or just the two buffered names
  779. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  780. #define _SORT_CMP_TIME_NODIR() (((modification_date_bckp == modificationDate) && (modification_time_bckp > modificationTime)) || (modification_date_bckp > modificationDate))
  781. #if HAS_FOLDER_SORTING
  782. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  783. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  784. #endif
  785. for (uint16_t i = fileCnt; --i;) {
  786. if (!IS_SD_INSERTED) return;
  787. bool didSwap = false;
  788. int8_t percent = (counter * 100) / total;//((counter * 100) / pow((fileCnt-1),2));
  789. for (int column = 0; column < 20; column++) {
  790. if (column < (percent / 5))
  791. {
  792. lcd_set_cursor(column, 2);
  793. lcd_print('\xFF'); //simple progress bar
  794. }
  795. }
  796. counter++;
  797. //MYSERIAL.println(int(i));
  798. for (uint16_t j = 0; j < i; ++j) {
  799. if (!IS_SD_INSERTED) return;
  800. #ifdef SORTING_DUMP
  801. for (uint16_t z = 0; z < fileCnt; z++)
  802. {
  803. printf_P(PSTR("%2u "), sort_order[z]);
  804. }
  805. MYSERIAL.println();
  806. #endif
  807. manage_heater();
  808. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  809. // The most economical method reads names as-needed
  810. // throughout the loop. Slow if there are many.
  811. #if !SDSORT_USES_RAM
  812. counter++;
  813. getfilename_simple(sort_positions[o1]);
  814. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  815. modification_date_bckp = modificationDate;
  816. modification_time_bckp = modificationTime;
  817. #if HAS_FOLDER_SORTING
  818. bool dir1 = filenameIsDir;
  819. #endif
  820. getfilename_simple(sort_positions[o2]);
  821. char *name2 = LONGEST_FILENAME; // use the string in-place
  822. #endif // !SDSORT_USES_RAM
  823. // Sort the current pair according to settings.
  824. if (
  825. #if HAS_FOLDER_SORTING
  826. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && _SORT_CMP_DIR(FOLDER_SORTING))
  827. #else
  828. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && _SORT_CMP_NODIR())
  829. #endif
  830. )
  831. {
  832. sort_order[j] = o2;
  833. sort_order[j + 1] = o1;
  834. didSwap = true;
  835. }
  836. }
  837. if (!didSwap) break;
  838. } //end of bubble sort loop
  839. #endif
  840. }
  841. else {
  842. sort_order[0] = 0;
  843. }
  844. sort_count = fileCnt;
  845. }
  846. #if !SDSORT_USES_RAM //show progresss bar only if slow sorting method is used
  847. for (int column = 0; column <= 19; column++)
  848. {
  849. lcd_set_cursor(column, 2);
  850. lcd_print('\xFF'); //simple progress bar
  851. }
  852. _delay(300);
  853. lcd_clear();
  854. #endif
  855. lcd_scrollTimer.start();
  856. lcd_update(2);
  857. KEEPALIVE_STATE(NOT_BUSY);
  858. lcd_timeoutToStatus.start();
  859. }
  860. void CardReader::flush_presort() {
  861. if (sort_count > 0) {
  862. #if SDSORT_DYNAMIC_RAM
  863. delete sort_order;
  864. #if SDSORT_CACHE_NAMES
  865. for (uint8_t i = 0; i < sort_count; ++i) {
  866. free(sortshort[i]); // strdup
  867. free(sortnames[i]); // strdup
  868. }
  869. delete sortshort;
  870. delete sortnames;
  871. #endif
  872. #endif
  873. sort_count = 0;
  874. }
  875. }
  876. #endif // SDCARD_SORT_ALPHA
  877. void CardReader::printingHasFinished()
  878. {
  879. st_synchronize();
  880. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  881. {
  882. file.close();
  883. file_subcall_ctr--;
  884. openFile(filenames[file_subcall_ctr],true,true);
  885. setIndex(filespos[file_subcall_ctr]);
  886. startFileprint();
  887. }
  888. else
  889. {
  890. quickStop();
  891. file.close();
  892. sdprinting = false;
  893. if(SD_FINISHED_STEPPERRELEASE)
  894. {
  895. finishAndDisableSteppers();
  896. //enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  897. }
  898. autotempShutdown();
  899. #ifdef SDCARD_SORT_ALPHA
  900. //presort();
  901. #endif
  902. }
  903. }
  904. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  905. {
  906. memset(ip, 0, 4);
  907. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  908. }
  909. #endif //SDSUPPORT