cardreader.cpp 27 KB

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