cardreader.cpp 29 KB

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