cardreader.cpp 27 KB

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