cardreader.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. #include "Prusa_farm.h"
  11. #ifdef SDSUPPORT
  12. #define LONGEST_FILENAME (longFilename[0] ? longFilename : filename)
  13. CardReader::CardReader()
  14. {
  15. #ifdef SDCARD_SORT_ALPHA
  16. sort_count = 0;
  17. #endif
  18. filesize = 0;
  19. sdpos = 0;
  20. sdprinting = false;
  21. cardOK = false;
  22. saving = false;
  23. logging = false;
  24. workDirDepth = 0;
  25. file_subcall_ctr=0;
  26. memset(workDirParents, 0, sizeof(workDirParents));
  27. presort_flag = false;
  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. #ifdef SDCARD_SORT_ALPHA
  248. //flush_presort();
  249. #endif
  250. }
  251. }
  252. void CardReader::openLogFile(const char* name)
  253. {
  254. logging = true;
  255. openFileWrite(name);
  256. }
  257. void CardReader::getDirName(char* name, uint8_t level)
  258. {
  259. workDirParents[level].getFilename(name);
  260. }
  261. uint8_t CardReader::getWorkDirDepth() {
  262. return workDirDepth;
  263. }
  264. void CardReader::getAbsFilename(char *t)
  265. {
  266. uint8_t cnt=0;
  267. *t='/';t++;cnt++;
  268. for(uint8_t i=0;i<workDirDepth;i++)
  269. {
  270. workDirParents[i].getFilename(t); //SDBaseFile.getfilename!
  271. while(*t!=0 && cnt< MAXPATHNAMELENGTH)
  272. {t++;cnt++;} //crawl counter forward.
  273. }
  274. if(cnt < MAXPATHNAMELENGTH - FILENAME_LENGTH)
  275. file.getFilename(t);
  276. else
  277. t[0]=0;
  278. }
  279. void CardReader::printAbsFilenameFast()
  280. {
  281. SERIAL_PROTOCOL('/');
  282. for (uint8_t i = 0; i < getWorkDirDepth(); i++)
  283. {
  284. SERIAL_PROTOCOL(dir_names[i]);
  285. SERIAL_PROTOCOL('/');
  286. }
  287. SERIAL_PROTOCOL(LONGEST_FILENAME);
  288. }
  289. /**
  290. * @brief Dive into subfolder
  291. *
  292. * Method sets curDir to point to root, in case fileName is null.
  293. * Method sets curDir to point to workDir, in case fileName path is relative
  294. * (doesn't start with '/')
  295. * Method sets curDir to point to dir, which is specified by absolute path
  296. * specified by fileName. In such case fileName is updated so it points to
  297. * file name without the path.
  298. *
  299. * @param[in,out] fileName
  300. * expects file name including path
  301. * in case of absolute path, file name without path is returned
  302. */
  303. bool CardReader::diveSubfolder (const char *&fileName)
  304. {
  305. curDir=&root;
  306. if (!fileName)
  307. return 1;
  308. const char *dirname_start, *dirname_end;
  309. if (fileName[0] == '/') // absolute path
  310. {
  311. setroot(false);
  312. dirname_start = fileName + 1;
  313. while (*dirname_start)
  314. {
  315. dirname_end = strchr(dirname_start, '/');
  316. //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name));
  317. //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name));
  318. if (dirname_end && dirname_end > dirname_start)
  319. {
  320. const size_t maxLen = 12;
  321. char subdirname[maxLen+1];
  322. const size_t len = ((static_cast<size_t>(dirname_end-dirname_start))>maxLen) ? maxLen : (dirname_end-dirname_start);
  323. strncpy(subdirname, dirname_start, len);
  324. subdirname[len] = 0;
  325. if (!chdir(subdirname, false))
  326. return 0;
  327. curDir = &workDir;
  328. dirname_start = dirname_end + 1;
  329. }
  330. else // the reminder after all /fsa/fdsa/ is the filename
  331. {
  332. fileName = dirname_start;
  333. //SERIAL_ECHOLN("remaider");
  334. //SERIAL_ECHOLN(fname);
  335. break;
  336. }
  337. }
  338. }
  339. else //relative path
  340. {
  341. curDir = &workDir;
  342. }
  343. return 1;
  344. }
  345. static const char ofKill[] PROGMEM = "trying to call sub-gcode files with too many levels.";
  346. static const char ofSubroutineCallTgt[] PROGMEM = "SUBROUTINE CALL target:\"";
  347. static const char ofParent[] PROGMEM = "\" parent:\"";
  348. static const char ofPos[] PROGMEM = "\" pos";
  349. static const char ofNowDoingFile[] PROGMEM = "Now doing file: ";
  350. static const char ofNowFreshFile[] PROGMEM = "Now fresh file: ";
  351. static const char ofFileOpened[] PROGMEM = "File opened: ";
  352. static const char ofSize[] PROGMEM = " Size: ";
  353. static const char ofFileSelected[] PROGMEM = "File selected";
  354. static const char ofSDPrinting[] PROGMEM = "SD-PRINTING";
  355. static const char ofWritingToFile[] PROGMEM = "Writing to file: ";
  356. void CardReader::openFileReadFilteredGcode(const char* name, bool replace_current/* = false*/){
  357. if(!cardOK)
  358. return;
  359. if(file.isOpen()){ //replacing current file by new file, or subfile call
  360. if(!replace_current){
  361. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1){
  362. // SERIAL_ERROR_START;
  363. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  364. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  365. kill(ofKill, 1);
  366. return;
  367. }
  368. SERIAL_ECHO_START;
  369. SERIAL_ECHORPGM(ofSubroutineCallTgt);
  370. SERIAL_ECHO(name);
  371. SERIAL_ECHORPGM(ofParent);
  372. //store current filename and position
  373. getAbsFilename(filenames[file_subcall_ctr]);
  374. SERIAL_ECHO(filenames[file_subcall_ctr]);
  375. SERIAL_ECHORPGM(ofPos);
  376. SERIAL_ECHOLN(sdpos);
  377. filespos[file_subcall_ctr]=sdpos;
  378. file_subcall_ctr++;
  379. } else {
  380. SERIAL_ECHO_START;
  381. SERIAL_ECHORPGM(ofNowDoingFile);
  382. SERIAL_ECHOLN(name);
  383. }
  384. file.close();
  385. } else { //opening fresh file
  386. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  387. SERIAL_ECHO_START;
  388. SERIAL_ECHORPGM(ofNowFreshFile);
  389. SERIAL_ECHOLN(name);
  390. }
  391. sdprinting = false;
  392. const char *fname=name;
  393. if (!diveSubfolder(fname))
  394. return;
  395. if (file.openFilteredGcode(curDir, fname)) {
  396. getfilename(0, fname);
  397. filesize = file.fileSize();
  398. SERIAL_PROTOCOLRPGM(ofFileOpened);////MSG_SD_FILE_OPENED
  399. printAbsFilenameFast();
  400. SERIAL_PROTOCOLRPGM(ofSize);////MSG_SD_SIZE
  401. SERIAL_PROTOCOLLN(filesize);
  402. sdpos = 0;
  403. SERIAL_PROTOCOLLNRPGM(ofFileSelected);////MSG_SD_FILE_SELECTED
  404. lcd_setstatuspgm(ofFileSelected);
  405. scrollstuff = 0;
  406. } else {
  407. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  408. SERIAL_PROTOCOL(fname);
  409. SERIAL_PROTOCOLLN('.');
  410. }
  411. }
  412. void CardReader::openFileWrite(const char* name)
  413. {
  414. if(!cardOK)
  415. return;
  416. if(file.isOpen()){ //replacing current file by new file, or subfile call
  417. #if 0
  418. // I doubt chained files support is necessary for file saving:
  419. // Intentionally disabled because it takes a lot of code size while being not used
  420. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1){
  421. // SERIAL_ERROR_START;
  422. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  423. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  424. kill(ofKill, 1);
  425. return;
  426. }
  427. SERIAL_ECHO_START;
  428. SERIAL_ECHORPGM(ofSubroutineCallTgt);
  429. SERIAL_ECHO(name);
  430. SERIAL_ECHORPGM(ofParent);
  431. //store current filename and position
  432. getAbsFilename(filenames[file_subcall_ctr]);
  433. SERIAL_ECHO(filenames[file_subcall_ctr]);
  434. SERIAL_ECHORPGM(ofPos);
  435. SERIAL_ECHOLN(sdpos);
  436. filespos[file_subcall_ctr]=sdpos;
  437. file_subcall_ctr++;
  438. file.close();
  439. #else
  440. SERIAL_ECHOLNPGM("File already opened");
  441. #endif
  442. } else { //opening fresh file
  443. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  444. SERIAL_ECHO_START;
  445. SERIAL_ECHORPGM(ofNowFreshFile);
  446. SERIAL_ECHOLN(name);
  447. }
  448. sdprinting = false;
  449. const char *fname=name;
  450. if (!diveSubfolder(fname))
  451. return;
  452. //write
  453. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)){
  454. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  455. SERIAL_PROTOCOL(fname);
  456. SERIAL_PROTOCOLLN('.');
  457. } else {
  458. saving = true;
  459. getfilename(0, fname);
  460. SERIAL_PROTOCOLRPGM(ofWritingToFile);////MSG_SD_WRITE_TO_FILE
  461. printAbsFilenameFast();
  462. SERIAL_PROTOCOLLN();
  463. SERIAL_PROTOCOLLNRPGM(ofFileSelected);////MSG_SD_FILE_SELECTED
  464. lcd_setstatuspgm(ofFileSelected);
  465. scrollstuff = 0;
  466. }
  467. }
  468. void CardReader::removeFile(const char* name)
  469. {
  470. if(!cardOK) return;
  471. file.close();
  472. sdprinting = false;
  473. const char *fname=name;
  474. if (!diveSubfolder(fname))
  475. return;
  476. if (file.remove(curDir, fname))
  477. {
  478. SERIAL_PROTOCOLPGM("File deleted:");
  479. SERIAL_PROTOCOLLN(fname);
  480. sdpos = 0;
  481. #ifdef SDCARD_SORT_ALPHA
  482. presort();
  483. #endif
  484. }
  485. else
  486. {
  487. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  488. SERIAL_PROTOCOL(fname);
  489. SERIAL_PROTOCOLLN('.');
  490. }
  491. }
  492. uint32_t CardReader::getFileSize()
  493. {
  494. return filesize;
  495. }
  496. void CardReader::getStatus(bool arg_P)
  497. {
  498. if (isPrintPaused)
  499. {
  500. if (saved_printing && (saved_printing_type == PRINTING_TYPE_SD))
  501. SERIAL_PROTOCOLLNPGM("SD print paused");
  502. else
  503. SERIAL_PROTOCOLLNPGM("Print saved");
  504. }
  505. else if (sdprinting)
  506. {
  507. if (arg_P)
  508. {
  509. printAbsFilenameFast();
  510. SERIAL_PROTOCOLLN();
  511. }
  512. else
  513. SERIAL_PROTOCOLLN(LONGEST_FILENAME);
  514. SERIAL_PROTOCOLRPGM(_N("SD printing byte "));////MSG_SD_PRINTING_BYTE
  515. SERIAL_PROTOCOL(sdpos);
  516. SERIAL_PROTOCOL('/');
  517. SERIAL_PROTOCOLLN(filesize);
  518. uint16_t time = ( _millis() - starttime ) / 60000U;
  519. SERIAL_PROTOCOL(itostr2(time/60));
  520. SERIAL_PROTOCOL(':');
  521. SERIAL_PROTOCOLLN(itostr2(time%60));
  522. }
  523. else
  524. SERIAL_PROTOCOLLNPGM("Not SD printing");
  525. }
  526. void CardReader::write_command(char *buf)
  527. {
  528. file.writeError = false;
  529. file.write(buf); //write command
  530. file.write("\r\n"); //write line termination
  531. if (file.writeError)
  532. {
  533. SERIAL_ERROR_START;
  534. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  535. }
  536. }
  537. #define CHUNK_SIZE 64
  538. void CardReader::write_command_no_newline(char *buf)
  539. {
  540. file.write(buf, CHUNK_SIZE);
  541. if (file.writeError)
  542. {
  543. SERIAL_ERROR_START;
  544. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  545. SERIAL_PROTOCOLLNPGM("An error while writing to the SD Card.");
  546. }
  547. }
  548. void CardReader::checkautostart(bool force)
  549. {
  550. // The SD start is delayed because otherwise the serial cannot answer
  551. // fast enough to make contact with the host software.
  552. static bool autostart_stilltocheck = true;
  553. if(!force)
  554. {
  555. if(!autostart_stilltocheck)
  556. return;
  557. if(autostart_atmillis.expired(5000))
  558. return;
  559. }
  560. autostart_stilltocheck = false;
  561. if(!cardOK)
  562. {
  563. initsd();
  564. if(!cardOK) //fail
  565. return;
  566. }
  567. char autoname[30];
  568. sprintf_P(autoname, PSTR("auto%i.g"), lastnr);
  569. for(int8_t i=0;i<(int8_t)strlen(autoname);i++)
  570. autoname[i]=tolower(autoname[i]);
  571. dir_t p;
  572. root.rewind();
  573. bool found=false;
  574. while (root.readDir(p, NULL) > 0)
  575. {
  576. for(int8_t i=0;i<(int8_t)strlen((char*)p.name);i++)
  577. p.name[i]=tolower(p.name[i]);
  578. //Serial.print((char*)p.name);
  579. //Serial.print(" ");
  580. //Serial.println(autoname);
  581. if(p.name[9]!='~') //skip safety copies
  582. if(strncmp((char*)p.name,autoname,5)==0)
  583. {
  584. char cmd[30];
  585. // M23: Select SD file
  586. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  587. enquecommand(cmd);
  588. // M24: Start/resume SD print
  589. enquecommand_P(PSTR("M24"));
  590. found=true;
  591. }
  592. }
  593. if(!found)
  594. lastnr=-1;
  595. else
  596. lastnr++;
  597. }
  598. void CardReader::closefile(bool store_location)
  599. {
  600. file.sync();
  601. file.close();
  602. saving = false;
  603. logging = false;
  604. if(store_location)
  605. {
  606. //future: store printer state, filename and position for continuing a stopped print
  607. // so one can unplug the printer and continue printing the next day.
  608. }
  609. }
  610. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/)
  611. {
  612. curDir=&workDir;
  613. nrFiles=nr;
  614. curDir->rewind();
  615. lsDive("",*curDir,match, LS_GetFilename);
  616. }
  617. void CardReader::getfilename_simple(uint16_t entry, const char * const match/*=NULL*/)
  618. {
  619. curDir = &workDir;
  620. nrFiles = 0;
  621. curDir->seekSet((uint32_t)entry << 5);
  622. lsDive("", *curDir, match, LS_GetFilename);
  623. }
  624. void CardReader::getfilename_next(uint32_t position, const char * const match/*=NULL*/)
  625. {
  626. curDir = &workDir;
  627. nrFiles = 1;
  628. curDir->seekSet(position);
  629. lsDive("", *curDir, match, LS_GetFilename);
  630. }
  631. uint16_t CardReader::getnrfilenames()
  632. {
  633. curDir=&workDir;
  634. nrFiles=0;
  635. curDir->rewind();
  636. lsDive("",*curDir, NULL, LS_Count);
  637. //SERIAL_ECHOLN(nrFiles);
  638. return nrFiles;
  639. }
  640. bool CardReader::chdir(const char * relpath, bool doPresort)
  641. {
  642. SdFile newfile;
  643. SdFile *parent=&root;
  644. if(workDir.isOpen())
  645. parent=&workDir;
  646. if(!newfile.open(*parent,relpath, O_READ) || ((workDirDepth + 1) >= MAX_DIR_DEPTH))
  647. {
  648. SERIAL_ECHO_START;
  649. SERIAL_ECHORPGM(_n("Cannot enter subdir: "));////MSG_SD_CANT_ENTER_SUBDIR
  650. SERIAL_ECHOLN(relpath);
  651. return 0;
  652. }
  653. else
  654. {
  655. strcpy(dir_names[workDirDepth], relpath);
  656. puts(relpath);
  657. if (workDirDepth < MAX_DIR_DEPTH) {
  658. for (uint8_t d = ++workDirDepth; d--;)
  659. workDirParents[d+1] = workDirParents[d];
  660. workDirParents[0]=*parent;
  661. }
  662. workDir=newfile;
  663. #ifdef SDCARD_SORT_ALPHA
  664. if (doPresort)
  665. presort();
  666. else
  667. presort_flag = true;
  668. #endif
  669. return 1;
  670. }
  671. }
  672. void CardReader::updir()
  673. {
  674. if(workDirDepth > 0)
  675. {
  676. --workDirDepth;
  677. workDir = workDirParents[0];
  678. for (uint8_t d = 0; d < workDirDepth; d++)
  679. {
  680. workDirParents[d] = workDirParents[d+1];
  681. }
  682. #ifdef SDCARD_SORT_ALPHA
  683. presort();
  684. #endif
  685. }
  686. }
  687. #ifdef SDCARD_SORT_ALPHA
  688. /**
  689. * Get the name of a file in the current directory by sort-index
  690. */
  691. void CardReader::getfilename_sorted(const uint16_t nr, uint8_t sdSort) {
  692. if (nr < sort_count)
  693. getfilename_simple(sort_entries[(sdSort == SD_SORT_ALPHA) ? (sort_count - nr - 1) : nr]);
  694. else
  695. getfilename_afterMaxSorting(nr);
  696. }
  697. void CardReader::getfilename_afterMaxSorting(uint16_t entry, const char * const match/*=NULL*/)
  698. {
  699. curDir = &workDir;
  700. nrFiles = entry - sort_count + 1;
  701. curDir->seekSet(lastSortedFilePosition << 5);
  702. lsDive("", *curDir, match, LS_GetFilename);
  703. }
  704. /**
  705. * Read all the files and produce a sort key
  706. *
  707. * We can do this in 3 ways...
  708. * - Minimal RAM: Read two filenames at a time sorting along...
  709. * - Some RAM: Buffer the directory just for this sort
  710. * - Most RAM: Buffer the directory and return filenames from RAM
  711. */
  712. void CardReader::presort() {
  713. // Throw away old sort index
  714. flush_presort();
  715. if (IS_SD_INSERTED == false) return; //sorting is not used in farm mode
  716. uint8_t sdSort = eeprom_read_byte((uint8_t*)EEPROM_SD_SORT);
  717. KEEPALIVE_STATE(IN_HANDLER);
  718. // If there are files, sort up to the limit
  719. uint16_t fileCnt = getnrfilenames();
  720. if (fileCnt > 0) {
  721. // Never sort more than the max allowed
  722. // If you use folders to organize, 20 may be enough
  723. if (fileCnt > SDSORT_LIMIT) {
  724. if ((sdSort != SD_SORT_NONE) && !farm_mode) {
  725. 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
  726. }
  727. fileCnt = SDSORT_LIMIT;
  728. }
  729. sort_count = fileCnt;
  730. // Init sort order.
  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_entries[i] = position >> 5;
  739. }
  740. if ((fileCnt > 1) && (sdSort != SD_SORT_NONE) && !farm_mode) {
  741. #ifdef SORTING_SPEEDTEST
  742. LongTimer sortingSpeedtestTimer;
  743. sortingSpeedtestTimer.start();
  744. #endif //SORTING_SPEEDTEST
  745. lastSortedFilePosition = position >> 5;
  746. // By default re-read the names from SD for every compare
  747. // retaining only two filenames at a time. This is very
  748. // slow but is safest and uses minimal RAM.
  749. char name1[LONG_FILENAME_LENGTH];
  750. uint16_t crmod_time_bckp;
  751. uint16_t crmod_date_bckp;
  752. #ifdef INSERTSORT
  753. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  754. #define _SORT_CMP_TIME_NODIR() (((crmod_date_bckp == crmodDate) && (crmod_time_bckp > crmodTime)) || (crmod_date_bckp > crmodDate))
  755. #if HAS_FOLDER_SORTING
  756. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  757. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  758. #endif
  759. uint16_t counter = 0;
  760. menu_progressbar_init(fileCnt * fileCnt / 2, _T(MSG_SORTING_FILES));
  761. for (uint16_t i = 1; i < fileCnt; ++i){
  762. // if (!IS_SD_INSERTED) return;
  763. menu_progressbar_update(counter);
  764. counter += i;
  765. /// pop the position
  766. const uint16_t o1 = sort_entries[i];
  767. getfilename_simple(o1);
  768. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  769. crmod_date_bckp = crmodDate;
  770. crmod_time_bckp = crmodTime;
  771. #if HAS_FOLDER_SORTING
  772. bool dir1 = filenameIsDir;
  773. #endif
  774. /// find proper place
  775. uint16_t j = i;
  776. for (; j > 0; --j){
  777. if (!IS_SD_INSERTED) return;
  778. #ifdef SORTING_DUMP
  779. for (uint16_t z = 0; z < fileCnt; z++){
  780. printf_P(PSTR("%2u "), sort_entries[z]);
  781. }
  782. MYSERIAL.println();
  783. #endif
  784. manage_heater();
  785. const uint16_t o2 = sort_entries[j - 1];
  786. getfilename_simple(o2);
  787. char *name2 = LONGEST_FILENAME; // use the string in-place
  788. // Sort the current pair according to settings.
  789. if (
  790. #if HAS_FOLDER_SORTING
  791. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_DIR(FOLDER_SORTING))
  792. #else
  793. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_NODIR())
  794. #endif
  795. )
  796. {
  797. break;
  798. } else {
  799. #ifdef SORTING_DUMP
  800. puts_P(PSTR("shift"));
  801. #endif
  802. sort_entries[j] = o2;
  803. }
  804. }
  805. /// place the position
  806. sort_entries[j] = o1;
  807. }
  808. #else //Bubble Sort
  809. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) < 0) //true if lowercase(name1) < lowercase(name2)
  810. #define _SORT_CMP_TIME_NODIR() (((crmod_date_bckp == crmodDate) && (crmod_time_bckp > crmodTime)) || (crmod_date_bckp > crmodDate))
  811. #if HAS_FOLDER_SORTING
  812. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs < 0 ? dir1 : !dir1))
  813. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  814. #endif
  815. uint16_t counter = 0;
  816. menu_progressbar_init(0.5*(fileCnt - 1)*(fileCnt), _T(MSG_SORTING_FILES));
  817. for (uint16_t i = fileCnt; --i;) {
  818. if (!IS_SD_INSERTED) return;
  819. bool didSwap = false;
  820. menu_progressbar_update(counter);
  821. counter++;
  822. for (uint16_t j = 0; j < i; ++j) {
  823. if (!IS_SD_INSERTED) return;
  824. #ifdef SORTING_DUMP
  825. for (uint16_t z = 0; z < fileCnt; z++)
  826. {
  827. printf_P(PSTR("%2u "), sort_entries[z]);
  828. }
  829. MYSERIAL.println();
  830. #endif
  831. manage_heater();
  832. const uint16_t o1 = sort_entries[j], o2 = sort_entries[j + 1];
  833. counter++;
  834. getfilename_simple(o1);
  835. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  836. crmod_date_bckp = crmodDate;
  837. crmod_time_bckp = crmodTime;
  838. #if HAS_FOLDER_SORTING
  839. bool dir1 = filenameIsDir;
  840. #endif
  841. getfilename_simple(o2);
  842. char *name2 = LONGEST_FILENAME; // use the string in-place
  843. // Sort the current pair according to settings.
  844. if (
  845. #if HAS_FOLDER_SORTING
  846. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_DIR(FOLDER_SORTING))
  847. #else
  848. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && !_SORT_CMP_NODIR())
  849. #endif
  850. )
  851. {
  852. #ifdef SORTING_DUMP
  853. puts_P(PSTR("swap"));
  854. #endif
  855. sort_entries[j] = o2;
  856. sort_entries[j + 1] = o1;
  857. didSwap = true;
  858. }
  859. }
  860. if (!didSwap) break;
  861. } //end of bubble sort loop
  862. #endif
  863. #ifdef SORTING_SPEEDTEST
  864. printf_P(PSTR("sortingSpeedtestTimer:%lu\n"), sortingSpeedtestTimer.elapsed());
  865. #endif //SORTING_SPEEDTEST
  866. #ifdef SORTING_DUMP
  867. for (uint16_t z = 0; z < fileCnt; z++)
  868. printf_P(PSTR("%2u "), sort_entries[z]);
  869. SERIAL_PROTOCOLLN();
  870. #endif
  871. menu_progressbar_finish();
  872. }
  873. }
  874. KEEPALIVE_STATE(NOT_BUSY);
  875. }
  876. void CardReader::flush_presort() {
  877. sort_count = 0;
  878. lastSortedFilePosition = 0;
  879. }
  880. #endif // SDCARD_SORT_ALPHA
  881. void CardReader::printingHasFinished()
  882. {
  883. st_synchronize();
  884. file.close();
  885. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  886. {
  887. file_subcall_ctr--;
  888. openFileReadFilteredGcode(filenames[file_subcall_ctr],true);
  889. setIndex(filespos[file_subcall_ctr]);
  890. startFileprint();
  891. }
  892. else
  893. {
  894. sdprinting = false;
  895. if(SD_FINISHED_STEPPERRELEASE)
  896. {
  897. finishAndDisableSteppers();
  898. //enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  899. }
  900. autotempShutdown();
  901. #ifdef SDCARD_SORT_ALPHA
  902. //presort();
  903. #endif
  904. }
  905. }
  906. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  907. {
  908. memset(ip, 0, 4);
  909. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  910. }
  911. #endif //SDSUPPORT