cardreader.cpp 29 KB

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