cardreader.cpp 27 KB

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