cardreader.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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(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. //SERIAL_PROTOCOLCHAR(' ');
  110. SERIAL_PROTOCOLLN(p.fileSize);
  111. break;
  112. case LS_GetFilename:
  113. createFilename(filename, p);
  114. if (match != NULL) {
  115. if (strcasecmp(match, filename) == 0) return;
  116. }
  117. else if (cnt == nrFiles) return;
  118. cnt++;
  119. break;
  120. }
  121. }
  122. } // while readDir
  123. }
  124. void CardReader::ls()
  125. {
  126. lsAction=LS_SerialPrint;
  127. // if(lsAction==LS_Count)
  128. // nrFiles=0;
  129. root.rewind();
  130. lsDive("",root);
  131. }
  132. void CardReader::initsd()
  133. {
  134. cardOK = false;
  135. if(root.isOpen())
  136. root.close();
  137. #ifdef SDSLOW
  138. if (!card.init(SPI_HALF_SPEED,SDSS)
  139. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  140. && !card.init(SPI_HALF_SPEED,LCD_SDSS)
  141. #endif
  142. )
  143. #else
  144. if (!card.init(SPI_FULL_SPEED,SDSS)
  145. #if defined(LCD_SDSS) && (LCD_SDSS != SDSS)
  146. && !card.init(SPI_FULL_SPEED,LCD_SDSS)
  147. #endif
  148. )
  149. #endif
  150. {
  151. //if (!card.init(SPI_HALF_SPEED,SDSS))
  152. SERIAL_ECHO_START;
  153. SERIAL_ECHOLNRPGM(MSG_SD_INIT_FAIL);
  154. }
  155. else if (!volume.init(&card))
  156. {
  157. SERIAL_ERROR_START;
  158. SERIAL_ERRORLNRPGM(MSG_SD_VOL_INIT_FAIL);
  159. }
  160. else if (!root.openRoot(&volume))
  161. {
  162. SERIAL_ERROR_START;
  163. SERIAL_ERRORLNRPGM(MSG_SD_OPENROOT_FAIL);
  164. }
  165. else
  166. {
  167. cardOK = true;
  168. SERIAL_ECHO_START;
  169. SERIAL_ECHOLNRPGM(MSG_SD_CARD_OK);
  170. }
  171. workDir=root;
  172. curDir=&root;
  173. #ifdef SDCARD_SORT_ALPHA
  174. presort();
  175. #endif
  176. /*
  177. if(!workDir.openRoot(&volume))
  178. {
  179. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  180. }
  181. */
  182. }
  183. void CardReader::setroot()
  184. {
  185. /*if(!workDir.openRoot(&volume))
  186. {
  187. SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL);
  188. }*/
  189. workDir=root;
  190. curDir=&workDir;
  191. #ifdef SDCARD_SORT_ALPHA
  192. presort();
  193. #endif
  194. }
  195. void CardReader::release()
  196. {
  197. sdprinting = false;
  198. cardOK = false;
  199. }
  200. void CardReader::startFileprint()
  201. {
  202. if(cardOK)
  203. {
  204. sdprinting = true;
  205. #ifdef SDCARD_SORT_ALPHA
  206. flush_presort();
  207. #endif
  208. }
  209. }
  210. void CardReader::pauseSDPrint()
  211. {
  212. if(sdprinting)
  213. {
  214. sdprinting = false;
  215. }
  216. }
  217. void CardReader::openLogFile(char* name)
  218. {
  219. logging = true;
  220. openFile(name, false);
  221. }
  222. void CardReader::getAbsFilename(char *t)
  223. {
  224. uint8_t cnt=0;
  225. *t='/';t++;cnt++;
  226. for(uint8_t i=0;i<workDirDepth;i++)
  227. {
  228. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  229. while(*t!=0 && cnt< MAXPATHNAMELENGTH)
  230. {t++;cnt++;} //crawl counter forward.
  231. }
  232. if(cnt<MAXPATHNAMELENGTH-13)
  233. file.getFilename(t);
  234. else
  235. t[0]=0;
  236. }
  237. void CardReader::openFile(char* name,bool read, bool replace_current/*=true*/)
  238. {
  239. if(!cardOK)
  240. return;
  241. if(file.isOpen()) //replacing current file by new file, or subfile call
  242. {
  243. if(!replace_current)
  244. {
  245. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1)
  246. {
  247. SERIAL_ERROR_START;
  248. SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  249. SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  250. kill();
  251. return;
  252. }
  253. SERIAL_ECHO_START;
  254. SERIAL_ECHOPGM("SUBROUTINE CALL target:\"");
  255. SERIAL_ECHO(name);
  256. SERIAL_ECHOPGM("\" parent:\"");
  257. //store current filename and position
  258. getAbsFilename(filenames[file_subcall_ctr]);
  259. SERIAL_ECHO(filenames[file_subcall_ctr]);
  260. SERIAL_ECHOPGM("\" pos");
  261. SERIAL_ECHOLN(sdpos);
  262. filespos[file_subcall_ctr]=sdpos;
  263. file_subcall_ctr++;
  264. }
  265. else
  266. {
  267. SERIAL_ECHO_START;
  268. SERIAL_ECHOPGM("Now doing file: ");
  269. SERIAL_ECHOLN(name);
  270. }
  271. file.close();
  272. }
  273. else //opening fresh file
  274. {
  275. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  276. SERIAL_ECHO_START;
  277. SERIAL_ECHOPGM("Now fresh file: ");
  278. SERIAL_ECHOLN(name);
  279. }
  280. sdprinting = false;
  281. SdFile myDir;
  282. curDir=&root;
  283. char *fname=name;
  284. char *dirname_start,*dirname_end;
  285. if(name[0]=='/')
  286. {
  287. dirname_start=strchr(name,'/')+1;
  288. while(dirname_start>0)
  289. {
  290. dirname_end=strchr(dirname_start,'/');
  291. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
  292. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name));
  293. if(dirname_end>0 && dirname_end>dirname_start)
  294. {
  295. char subdirname[13];
  296. strncpy(subdirname, dirname_start, dirname_end-dirname_start);
  297. subdirname[dirname_end-dirname_start]=0;
  298. SERIAL_ECHOLN(subdirname);
  299. if(!myDir.open(curDir,subdirname,O_READ))
  300. {
  301. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  302. SERIAL_PROTOCOL(subdirname);
  303. SERIAL_PROTOCOLLNPGM(".");
  304. return;
  305. }
  306. else
  307. {
  308. //SERIAL_ECHOLN("dive ok");
  309. }
  310. curDir=&myDir;
  311. dirname_start=dirname_end+1;
  312. }
  313. else // the reminder after all /fsa/fdsa/ is the filename
  314. {
  315. fname=dirname_start;
  316. //SERIAL_ECHOLN("remaider");
  317. //SERIAL_ECHOLN(fname);
  318. break;
  319. }
  320. }
  321. }
  322. else //relative path
  323. {
  324. curDir=&workDir;
  325. }
  326. if(read)
  327. {
  328. if (file.open(curDir, fname, O_READ))
  329. {
  330. filesize = file.fileSize();
  331. SERIAL_PROTOCOLRPGM(MSG_SD_FILE_OPENED);
  332. SERIAL_PROTOCOL(fname);
  333. SERIAL_PROTOCOLRPGM(MSG_SD_SIZE);
  334. SERIAL_PROTOCOLLN(filesize);
  335. sdpos = 0;
  336. SERIAL_PROTOCOLLNRPGM(MSG_SD_FILE_SELECTED);
  337. getfilename(0, fname);
  338. lcd_setstatus(longFilename[0] ? longFilename : fname);
  339. lcd_setstatus("SD-PRINTING ");
  340. }
  341. else
  342. {
  343. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  344. SERIAL_PROTOCOL(fname);
  345. SERIAL_PROTOCOLLNPGM(".");
  346. }
  347. }
  348. else
  349. { //write
  350. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC))
  351. {
  352. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  353. SERIAL_PROTOCOL(fname);
  354. SERIAL_PROTOCOLLNPGM(".");
  355. }
  356. else
  357. {
  358. saving = true;
  359. SERIAL_PROTOCOLRPGM(MSG_SD_WRITE_TO_FILE);
  360. SERIAL_PROTOCOLLN(name);
  361. lcd_setstatus(fname);
  362. }
  363. }
  364. }
  365. void CardReader::removeFile(char* name)
  366. {
  367. if(!cardOK)
  368. return;
  369. file.close();
  370. sdprinting = false;
  371. SdFile myDir;
  372. curDir=&root;
  373. char *fname=name;
  374. char *dirname_start,*dirname_end;
  375. if(name[0]=='/')
  376. {
  377. dirname_start=strchr(name,'/')+1;
  378. while(dirname_start>0)
  379. {
  380. dirname_end=strchr(dirname_start,'/');
  381. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
  382. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name));
  383. if(dirname_end>0 && dirname_end>dirname_start)
  384. {
  385. char subdirname[13];
  386. strncpy(subdirname, dirname_start, dirname_end-dirname_start);
  387. subdirname[dirname_end-dirname_start]=0;
  388. SERIAL_ECHOLN(subdirname);
  389. if(!myDir.open(curDir,subdirname,O_READ))
  390. {
  391. SERIAL_PROTOCOLRPGM("open failed, File: ");
  392. SERIAL_PROTOCOL(subdirname);
  393. SERIAL_PROTOCOLLNPGM(".");
  394. return;
  395. }
  396. else
  397. {
  398. //SERIAL_ECHOLN("dive ok");
  399. }
  400. curDir=&myDir;
  401. dirname_start=dirname_end+1;
  402. }
  403. else // the reminder after all /fsa/fdsa/ is the filename
  404. {
  405. fname=dirname_start;
  406. //SERIAL_ECHOLN("remaider");
  407. //SERIAL_ECHOLN(fname);
  408. break;
  409. }
  410. }
  411. }
  412. else //relative path
  413. {
  414. curDir=&workDir;
  415. }
  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. void CardReader::getStatus()
  433. {
  434. if(sdprinting){
  435. SERIAL_PROTOCOL(longFilename);
  436. SERIAL_PROTOCOLPGM("\n");
  437. SERIAL_PROTOCOLRPGM(MSG_SD_PRINTING_BYTE);
  438. SERIAL_PROTOCOL(sdpos);
  439. SERIAL_PROTOCOLPGM("/");
  440. SERIAL_PROTOCOLLN(filesize);
  441. uint16_t time = millis()/60000 - starttime/60000;
  442. SERIAL_PROTOCOL(itostr2(time/60));
  443. SERIAL_PROTOCOL(':');
  444. SERIAL_PROTOCOL(itostr2(time%60));
  445. SERIAL_PROTOCOLPGM("\n");
  446. }
  447. else{
  448. SERIAL_PROTOCOLLNRPGM("Not printing");
  449. }
  450. }
  451. void CardReader::write_command(char *buf)
  452. {
  453. char* begin = buf;
  454. char* npos = 0;
  455. char* end = buf + strlen(buf) - 1;
  456. file.writeError = false;
  457. if((npos = strchr(buf, 'N')) != NULL)
  458. {
  459. begin = strchr(npos, ' ') + 1;
  460. end = strchr(npos, '*') - 1;
  461. }
  462. end[1] = '\r';
  463. end[2] = '\n';
  464. end[3] = '\0';
  465. file.write(begin);
  466. if (file.writeError)
  467. {
  468. SERIAL_ERROR_START;
  469. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  470. }
  471. }
  472. #define CHUNK_SIZE 64
  473. void CardReader::write_command_no_newline(char *buf)
  474. {
  475. file.write(buf, CHUNK_SIZE);
  476. if (file.writeError)
  477. {
  478. SERIAL_ERROR_START;
  479. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  480. MYSERIAL.println("An error while writing to the SD Card.");
  481. }
  482. }
  483. void CardReader::checkautostart(bool force)
  484. {
  485. if(!force)
  486. {
  487. if(!autostart_stilltocheck)
  488. return;
  489. if(autostart_atmillis<millis())
  490. return;
  491. }
  492. autostart_stilltocheck=false;
  493. if(!cardOK)
  494. {
  495. initsd();
  496. if(!cardOK) //fail
  497. return;
  498. }
  499. char autoname[30];
  500. sprintf_P(autoname, PSTR("auto%i.g"), lastnr);
  501. for(int8_t i=0;i<(int8_t)strlen(autoname);i++)
  502. autoname[i]=tolower(autoname[i]);
  503. dir_t p;
  504. root.rewind();
  505. bool found=false;
  506. while (root.readDir(p, NULL) > 0)
  507. {
  508. for(int8_t i=0;i<(int8_t)strlen((char*)p.name);i++)
  509. p.name[i]=tolower(p.name[i]);
  510. //Serial.print((char*)p.name);
  511. //Serial.print(" ");
  512. //Serial.println(autoname);
  513. if(p.name[9]!='~') //skip safety copies
  514. if(strncmp((char*)p.name,autoname,5)==0)
  515. {
  516. char cmd[30];
  517. // M23: Select SD file
  518. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  519. enquecommand(cmd);
  520. // M24: Start/resume SD print
  521. enquecommand_P(PSTR("M24"));
  522. found=true;
  523. }
  524. }
  525. if(!found)
  526. lastnr=-1;
  527. else
  528. lastnr++;
  529. }
  530. void CardReader::closefile(bool store_location)
  531. {
  532. file.sync();
  533. file.close();
  534. saving = false;
  535. logging = false;
  536. if(store_location)
  537. {
  538. //future: store printer state, filename and position for continuing a stopped print
  539. // so one can unplug the printer and continue printing the next day.
  540. }
  541. }
  542. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/)
  543. {
  544. curDir=&workDir;
  545. lsAction=LS_GetFilename;
  546. nrFiles=nr;
  547. curDir->rewind();
  548. lsDive("",*curDir,match);
  549. }
  550. uint16_t CardReader::getnrfilenames()
  551. {
  552. curDir=&workDir;
  553. lsAction=LS_Count;
  554. nrFiles=0;
  555. curDir->rewind();
  556. lsDive("",*curDir);
  557. //SERIAL_ECHOLN(nrFiles);
  558. return nrFiles;
  559. }
  560. void CardReader::chdir(const char * relpath)
  561. {
  562. SdFile newfile;
  563. SdFile *parent=&root;
  564. if(workDir.isOpen())
  565. parent=&workDir;
  566. if(!newfile.open(*parent,relpath, O_READ))
  567. {
  568. SERIAL_ECHO_START;
  569. SERIAL_ECHORPGM(MSG_SD_CANT_ENTER_SUBDIR);
  570. SERIAL_ECHOLN(relpath);
  571. }
  572. else
  573. {
  574. if (workDirDepth < MAX_DIR_DEPTH) {
  575. for (int d = ++workDirDepth; d--;)
  576. workDirParents[d+1] = workDirParents[d];
  577. workDirParents[0]=*parent;
  578. }
  579. workDir=newfile;
  580. }
  581. }
  582. void CardReader::updir()
  583. {
  584. if(workDirDepth > 0)
  585. {
  586. --workDirDepth;
  587. workDir = workDirParents[0];
  588. int d;
  589. for (int d = 0; d < workDirDepth; d++)
  590. workDirParents[d] = workDirParents[d+1];
  591. }
  592. }
  593. #ifdef SDCARD_SORT_ALPHA
  594. /**
  595. * Get the name of a file in the current directory by sort-index
  596. */
  597. void CardReader::getfilename_sorted(const uint16_t nr) {
  598. getfilename(
  599. #if SDSORT_GCODE
  600. sort_alpha &&
  601. #endif
  602. (nr < sort_count) ? sort_order[nr] : nr
  603. );
  604. }
  605. /**
  606. * Read all the files and produce a sort key
  607. *
  608. * We can do this in 3 ways...
  609. * - Minimal RAM: Read two filenames at a time sorting along...
  610. * - Some RAM: Buffer the directory just for this sort
  611. * - Most RAM: Buffer the directory and return filenames from RAM
  612. */
  613. void CardReader::presort() {
  614. #if SDSORT_GCODE
  615. if (!sort_alpha) return;
  616. #endif
  617. // Throw away old sort index
  618. flush_presort();
  619. // If there are files, sort up to the limit
  620. uint16_t fileCnt = getnrfilenames();
  621. if (fileCnt > 0) {
  622. // Never sort more than the max allowed
  623. // If you use folders to organize, 20 may be enough
  624. if (fileCnt > SDSORT_LIMIT) fileCnt = SDSORT_LIMIT;
  625. // Sort order is always needed. May be static or dynamic.
  626. #if SDSORT_DYNAMIC_RAM
  627. sort_order = new uint8_t[fileCnt];
  628. #endif
  629. // Use RAM to store the entire directory during pre-sort.
  630. // SDSORT_LIMIT should be set to prevent over-allocation.
  631. #if SDSORT_USES_RAM
  632. // If using dynamic ram for names, allocate on the heap.
  633. #if SDSORT_CACHE_NAMES
  634. #if SDSORT_DYNAMIC_RAM
  635. sortshort = new char*[fileCnt];
  636. sortnames = new char*[fileCnt];
  637. #endif
  638. #elif SDSORT_USES_STACK
  639. char sortnames[fileCnt][LONG_FILENAME_LENGTH];
  640. #endif
  641. // Folder sorting needs 1 bit per entry for flags.
  642. #if HAS_FOLDER_SORTING
  643. #if SDSORT_DYNAMIC_RAM
  644. isDir = new uint8_t[(fileCnt + 7) >> 3];
  645. #elif SDSORT_USES_STACK
  646. uint8_t isDir[(fileCnt + 7) >> 3];
  647. #endif
  648. #endif
  649. #else // !SDSORT_USES_RAM
  650. // By default re-read the names from SD for every compare
  651. // retaining only two filenames at a time. This is very
  652. // slow but is safest and uses minimal RAM.
  653. char name1[LONG_FILENAME_LENGTH + 1];
  654. #endif
  655. if (fileCnt > 1) {
  656. SERIAL_ECHOLNPGM("Sort order:");
  657. // Init sort order.
  658. for (uint16_t i = 0; i < fileCnt; i++) {
  659. sort_order[i] = i;
  660. // If using RAM then read all filenames now.
  661. #if SDSORT_USES_RAM
  662. getfilename(i);
  663. #if SDSORT_DYNAMIC_RAM
  664. // Use dynamic method to copy long filename
  665. sortnames[i] = strdup(LONGEST_FILENAME);
  666. #if SDSORT_CACHE_NAMES
  667. // When caching also store the short name, since
  668. // we're replacing the getfilename() behavior.
  669. sortshort[i] = strdup(filename);
  670. #endif
  671. #else
  672. // Copy filenames into the static array
  673. strcpy(sortnames[i], LONGEST_FILENAME);
  674. #if SDSORT_CACHE_NAMES
  675. strcpy(sortshort[i], filename);
  676. #endif
  677. #endif
  678. // char out[30];
  679. // sprintf_P(out, PSTR("---- %i %s %s"), i, filenameIsDir ? "D" : " ", sortnames[i]);
  680. // SERIAL_ECHOLN(out);
  681. #if HAS_FOLDER_SORTING
  682. const uint16_t bit = i & 0x07, ind = i >> 3;
  683. if (bit == 0) isDir[ind] = 0x00;
  684. if (filenameIsDir) isDir[ind] |= _BV(bit);
  685. #endif
  686. #endif
  687. }
  688. SERIAL_ECHOPGM("FILE_CNT:");
  689. MYSERIAL.println(int(fileCnt));
  690. // Bubble Sort
  691. for (uint16_t i = fileCnt; --i;) {
  692. bool didSwap = false;
  693. MYSERIAL.println(int(i));
  694. for (uint16_t j = 0; j < i; ++j) {
  695. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  696. // Compare names from the array or just the two buffered names
  697. #if SDSORT_USES_RAM
  698. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  699. #else
  700. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0) //true if lowercase(name1) > lowercase(name2)
  701. #endif
  702. #if HAS_FOLDER_SORTING
  703. #if SDSORT_USES_RAM
  704. // Folder sorting needs an index and bit to test for folder-ness.
  705. const uint8_t ind1 = o1 >> 3, bit1 = o1 & 0x07,
  706. ind2 = o2 >> 3, bit2 = o2 & 0x07;
  707. #define _SORT_CMP_DIR(fs) \
  708. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  709. ? _SORT_CMP_NODIR() \
  710. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  711. #else
  712. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  713. #endif
  714. #endif
  715. // The most economical method reads names as-needed
  716. // throughout the loop. Slow if there are many.
  717. #if !SDSORT_USES_RAM
  718. SERIAL_ECHOPGM("o1 & o2: ");
  719. MYSERIAL.println(int(o1));
  720. MYSERIAL.println(int(o2));
  721. getfilename(o1);
  722. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  723. #if HAS_FOLDER_SORTING
  724. bool dir1 = filenameIsDir;
  725. #endif
  726. getfilename(o2);
  727. char *name2 = LONGEST_FILENAME; // use the string in-place
  728. SERIAL_ECHOLNPGM("Names:");
  729. MYSERIAL.println(name1);
  730. MYSERIAL.println(name2);
  731. #endif // !SDSORT_USES_RAM
  732. // Sort the current pair according to settings.
  733. if (
  734. #if HAS_FOLDER_SORTING
  735. #if SDSORT_GCODE
  736. sort_folders ? _SORT_CMP_DIR(sort_folders) : _SORT_CMP_NODIR()
  737. #else
  738. _SORT_CMP_DIR(FOLDER_SORTING)
  739. #endif
  740. #else
  741. _SORT_CMP_NODIR()
  742. #endif
  743. ) {
  744. sort_order[j] = o2;
  745. sort_order[j + 1] = o1;
  746. didSwap = true;
  747. SERIAL_ECHOLNPGM("Did swap");
  748. }
  749. }
  750. if (!didSwap) break;
  751. }
  752. // Using RAM but not keeping names around
  753. #if (SDSORT_USES_RAM && !SDSORT_CACHE_NAMES)
  754. #if SDSORT_DYNAMIC_RAM
  755. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  756. #if HAS_FOLDER_SORTING
  757. free(isDir);
  758. #endif
  759. #endif
  760. #endif
  761. }
  762. else {
  763. sort_order[0] = 0;
  764. #if (SDSORT_USES_RAM && SDSORT_CACHE_NAMES)
  765. getfilename(0);
  766. #if SDSORT_DYNAMIC_RAM
  767. sortnames = new char*[1];
  768. sortnames[0] = strdup(LONGEST_FILENAME); // malloc
  769. sortshort = new char*[1];
  770. sortshort[0] = strdup(filename); // malloc
  771. isDir = new uint8_t[1];
  772. #else
  773. strcpy(sortnames[0], LONGEST_FILENAME);
  774. strcpy(sortshort[0], filename);
  775. #endif
  776. isDir[0] = filenameIsDir ? 0x01 : 0x00;
  777. #endif
  778. }
  779. sort_count = fileCnt;
  780. }
  781. }
  782. void CardReader::flush_presort() {
  783. if (sort_count > 0) {
  784. #if SDSORT_DYNAMIC_RAM
  785. delete sort_order;
  786. #if SDSORT_CACHE_NAMES
  787. for (uint8_t i = 0; i < sort_count; ++i) {
  788. free(sortshort[i]); // strdup
  789. free(sortnames[i]); // strdup
  790. }
  791. delete sortshort;
  792. delete sortnames;
  793. #endif
  794. #endif
  795. sort_count = 0;
  796. }
  797. }
  798. #endif // SDCARD_SORT_ALPHA
  799. void CardReader::printingHasFinished()
  800. {
  801. st_synchronize();
  802. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  803. {
  804. file.close();
  805. file_subcall_ctr--;
  806. openFile(filenames[file_subcall_ctr],true,true);
  807. setIndex(filespos[file_subcall_ctr]);
  808. startFileprint();
  809. }
  810. else
  811. {
  812. quickStop();
  813. file.close();
  814. sdprinting = false;
  815. if(SD_FINISHED_STEPPERRELEASE)
  816. {
  817. //finishAndDisableSteppers();
  818. enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  819. }
  820. autotempShutdown();
  821. #ifdef SDCARD_SORT_ALPHA
  822. presort();
  823. #endif
  824. }
  825. }
  826. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  827. {
  828. memset(ip, 0, 4);
  829. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  830. }
  831. #endif //SDSUPPORT