cardreader.cpp 29 KB

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