cardreader.cpp 29 KB

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