cardreader.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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. openFile(name, false);
  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. // @@TODO merge with openFile, too much duplicated code and texts
  344. void CardReader::openFileFilteredGcode(const char* name, bool replace_current/* = false*/){
  345. if(!cardOK)
  346. return;
  347. if(file.isOpen()){ //replacing current file by new file, or subfile call
  348. if(!replace_current){
  349. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1){
  350. // SERIAL_ERROR_START;
  351. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  352. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  353. kill(_n("trying to call sub-gcode files with too many levels."), 1);
  354. return;
  355. }
  356. SERIAL_ECHO_START;
  357. SERIAL_ECHOPGM("SUBROUTINE CALL target:\"");
  358. SERIAL_ECHO(name);
  359. SERIAL_ECHOPGM("\" parent:\"");
  360. //store current filename and position
  361. getAbsFilename(filenames[file_subcall_ctr]);
  362. SERIAL_ECHO(filenames[file_subcall_ctr]);
  363. SERIAL_ECHOPGM("\" pos");
  364. SERIAL_ECHOLN(sdpos);
  365. filespos[file_subcall_ctr]=sdpos;
  366. file_subcall_ctr++;
  367. } else {
  368. SERIAL_ECHO_START;
  369. SERIAL_ECHOPGM("Now doing file: ");
  370. SERIAL_ECHOLN(name);
  371. }
  372. file.close();
  373. } else { //opening fresh file
  374. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  375. SERIAL_ECHO_START;
  376. SERIAL_ECHOPGM("Now fresh file: ");
  377. SERIAL_ECHOLN(name);
  378. }
  379. sdprinting = false;
  380. SdFile myDir;
  381. const char *fname=name;
  382. diveSubfolder(fname,myDir);
  383. if (file.openFilteredGcode(curDir, fname)) {
  384. filesize = file.fileSize();
  385. SERIAL_PROTOCOLRPGM(_N("File opened: "));////MSG_SD_FILE_OPENED
  386. SERIAL_PROTOCOL(fname);
  387. SERIAL_PROTOCOLRPGM(_n(" Size: "));////MSG_SD_SIZE
  388. SERIAL_PROTOCOLLN(filesize);
  389. sdpos = 0;
  390. SERIAL_PROTOCOLLNRPGM(_N("File selected"));////MSG_SD_FILE_SELECTED
  391. getfilename(0, fname);
  392. lcd_setstatus(longFilename[0] ? longFilename : fname);
  393. lcd_setstatus("SD-PRINTING ");
  394. } else {
  395. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  396. SERIAL_PROTOCOL(fname);
  397. SERIAL_PROTOCOLLN('.');
  398. }
  399. }
  400. void CardReader::openFile(const char* name,bool read, bool replace_current/*=true*/)
  401. {
  402. if(!cardOK)
  403. return;
  404. if(file.isOpen()) //replacing current file by new file, or subfile call
  405. {
  406. if(!replace_current)
  407. {
  408. if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1)
  409. {
  410. // SERIAL_ERROR_START;
  411. // SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:");
  412. // SERIAL_ERRORLN(SD_PROCEDURE_DEPTH);
  413. kill(_n("trying to call sub-gcode files with too many levels."), 1);
  414. return;
  415. }
  416. SERIAL_ECHO_START;
  417. SERIAL_ECHOPGM("SUBROUTINE CALL target:\"");
  418. SERIAL_ECHO(name);
  419. SERIAL_ECHOPGM("\" parent:\"");
  420. //store current filename and position
  421. getAbsFilename(filenames[file_subcall_ctr]);
  422. SERIAL_ECHO(filenames[file_subcall_ctr]);
  423. SERIAL_ECHOPGM("\" pos");
  424. SERIAL_ECHOLN(sdpos);
  425. filespos[file_subcall_ctr]=sdpos;
  426. file_subcall_ctr++;
  427. }
  428. else
  429. {
  430. SERIAL_ECHO_START;
  431. SERIAL_ECHOPGM("Now doing file: ");
  432. SERIAL_ECHOLN(name);
  433. }
  434. file.close();
  435. }
  436. else //opening fresh file
  437. {
  438. file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure
  439. SERIAL_ECHO_START;
  440. SERIAL_ECHOPGM("Now fresh file: ");
  441. SERIAL_ECHOLN(name);
  442. }
  443. sdprinting = false;
  444. SdFile myDir;
  445. const char *fname=name;
  446. diveSubfolder(fname,myDir);
  447. if(read)
  448. {
  449. if (file.open(curDir, fname, O_READ))
  450. {
  451. filesize = file.fileSize();
  452. SERIAL_PROTOCOLRPGM(_N("File opened: "));////MSG_SD_FILE_OPENED
  453. SERIAL_PROTOCOL(fname);
  454. SERIAL_PROTOCOLRPGM(_n(" Size: "));////MSG_SD_SIZE
  455. SERIAL_PROTOCOLLN(filesize);
  456. sdpos = 0;
  457. SERIAL_PROTOCOLLNRPGM(_N("File selected"));////MSG_SD_FILE_SELECTED
  458. getfilename(0, fname);
  459. lcd_setstatus(longFilename[0] ? longFilename : fname);
  460. lcd_setstatuspgm(PSTR("SD-PRINTING"));
  461. }
  462. else
  463. {
  464. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  465. SERIAL_PROTOCOL(fname);
  466. SERIAL_PROTOCOLLN('.');
  467. }
  468. }
  469. else
  470. { //write
  471. if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC))
  472. {
  473. SERIAL_PROTOCOLRPGM(MSG_SD_OPEN_FILE_FAIL);
  474. SERIAL_PROTOCOL(fname);
  475. SERIAL_PROTOCOLLN('.');
  476. }
  477. else
  478. {
  479. saving = true;
  480. SERIAL_PROTOCOLRPGM(_N("Writing to file: "));////MSG_SD_WRITE_TO_FILE
  481. SERIAL_PROTOCOLLN(name);
  482. lcd_setstatus(fname);
  483. }
  484. }
  485. }
  486. void CardReader::removeFile(const char* name)
  487. {
  488. if(!cardOK) return;
  489. file.close();
  490. sdprinting = false;
  491. SdFile myDir;
  492. const char *fname=name;
  493. diveSubfolder(fname,myDir);
  494. if (file.remove(curDir, fname))
  495. {
  496. SERIAL_PROTOCOLPGM("File deleted:");
  497. SERIAL_PROTOCOLLN(fname);
  498. sdpos = 0;
  499. #ifdef SDCARD_SORT_ALPHA
  500. presort();
  501. #endif
  502. }
  503. else
  504. {
  505. SERIAL_PROTOCOLPGM("Deletion failed, File: ");
  506. SERIAL_PROTOCOL(fname);
  507. SERIAL_PROTOCOLLN('.');
  508. }
  509. }
  510. uint32_t CardReader::getFileSize()
  511. {
  512. return filesize;
  513. }
  514. void CardReader::getStatus()
  515. {
  516. if(sdprinting)
  517. {
  518. if (isPrintPaused) {
  519. SERIAL_PROTOCOLLNPGM("SD print paused");
  520. }
  521. else if (saved_printing) {
  522. SERIAL_PROTOCOLLNPGM("Print saved");
  523. }
  524. else {
  525. SERIAL_PROTOCOLLN(LONGEST_FILENAME);
  526. SERIAL_PROTOCOLRPGM(_N("SD printing byte "));////MSG_SD_PRINTING_BYTE
  527. SERIAL_PROTOCOL(sdpos);
  528. SERIAL_PROTOCOL('/');
  529. SERIAL_PROTOCOLLN(filesize);
  530. uint16_t time = ( _millis() - starttime ) / 60000U;
  531. SERIAL_PROTOCOL(itostr2(time/60));
  532. SERIAL_PROTOCOL(':');
  533. SERIAL_PROTOCOLLN(itostr2(time%60));
  534. }
  535. }
  536. else {
  537. SERIAL_PROTOCOLLNPGM("Not SD printing");
  538. }
  539. }
  540. void CardReader::write_command(char *buf)
  541. {
  542. char* begin = buf;
  543. char* npos = 0;
  544. char* end = buf + strlen(buf) - 1;
  545. file.writeError = false;
  546. if((npos = strchr(buf, 'N')) != NULL)
  547. {
  548. begin = strchr(npos, ' ') + 1;
  549. end = strchr(npos, '*') - 1;
  550. }
  551. end[1] = '\r';
  552. end[2] = '\n';
  553. end[3] = '\0';
  554. file.write(begin);
  555. if (file.writeError)
  556. {
  557. SERIAL_ERROR_START;
  558. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  559. }
  560. }
  561. #define CHUNK_SIZE 64
  562. void CardReader::write_command_no_newline(char *buf)
  563. {
  564. file.write(buf, CHUNK_SIZE);
  565. if (file.writeError)
  566. {
  567. SERIAL_ERROR_START;
  568. SERIAL_ERRORLNRPGM(MSG_SD_ERR_WRITE_TO_FILE);
  569. SERIAL_PROTOCOLLNPGM("An error while writing to the SD Card.");
  570. }
  571. }
  572. void CardReader::checkautostart(bool force)
  573. {
  574. if(!force)
  575. {
  576. if(!autostart_stilltocheck)
  577. return;
  578. if(autostart_atmillis<_millis())
  579. return;
  580. }
  581. autostart_stilltocheck=false;
  582. if(!cardOK)
  583. {
  584. initsd();
  585. if(!cardOK) //fail
  586. return;
  587. }
  588. char autoname[30];
  589. sprintf_P(autoname, PSTR("auto%i.g"), lastnr);
  590. for(int8_t i=0;i<(int8_t)strlen(autoname);i++)
  591. autoname[i]=tolower(autoname[i]);
  592. dir_t p;
  593. root.rewind();
  594. bool found=false;
  595. while (root.readDir(p, NULL) > 0)
  596. {
  597. for(int8_t i=0;i<(int8_t)strlen((char*)p.name);i++)
  598. p.name[i]=tolower(p.name[i]);
  599. //Serial.print((char*)p.name);
  600. //Serial.print(" ");
  601. //Serial.println(autoname);
  602. if(p.name[9]!='~') //skip safety copies
  603. if(strncmp((char*)p.name,autoname,5)==0)
  604. {
  605. char cmd[30];
  606. // M23: Select SD file
  607. sprintf_P(cmd, PSTR("M23 %s"), autoname);
  608. enquecommand(cmd);
  609. // M24: Start/resume SD print
  610. enquecommand_P(PSTR("M24"));
  611. found=true;
  612. }
  613. }
  614. if(!found)
  615. lastnr=-1;
  616. else
  617. lastnr++;
  618. }
  619. void CardReader::closefile(bool store_location)
  620. {
  621. file.sync();
  622. file.close();
  623. saving = false;
  624. logging = false;
  625. if(store_location)
  626. {
  627. //future: store printer state, filename and position for continuing a stopped print
  628. // so one can unplug the printer and continue printing the next day.
  629. }
  630. }
  631. void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/)
  632. {
  633. curDir=&workDir;
  634. lsAction=LS_GetFilename;
  635. nrFiles=nr;
  636. curDir->rewind();
  637. lsDive("",*curDir,match);
  638. }
  639. void CardReader::getfilename_simple(uint32_t position, const char * const match/*=NULL*/)
  640. {
  641. curDir = &workDir;
  642. lsAction = LS_GetFilename;
  643. nrFiles = 0;
  644. curDir->seekSet(position);
  645. lsDive("", *curDir, match);
  646. }
  647. uint16_t CardReader::getnrfilenames()
  648. {
  649. curDir=&workDir;
  650. lsAction=LS_Count;
  651. nrFiles=0;
  652. curDir->rewind();
  653. lsDive("",*curDir);
  654. //SERIAL_ECHOLN(nrFiles);
  655. return nrFiles;
  656. }
  657. void CardReader::chdir(const char * relpath)
  658. {
  659. SdFile newfile;
  660. SdFile *parent=&root;
  661. if(workDir.isOpen())
  662. parent=&workDir;
  663. if(!newfile.open(*parent,relpath, O_READ))
  664. {
  665. SERIAL_ECHO_START;
  666. SERIAL_ECHORPGM(_n("Cannot enter subdir: "));////MSG_SD_CANT_ENTER_SUBDIR
  667. SERIAL_ECHOLN(relpath);
  668. }
  669. else
  670. {
  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. presort();
  679. #endif
  680. }
  681. }
  682. void CardReader::updir()
  683. {
  684. if(workDirDepth > 0)
  685. {
  686. --workDirDepth;
  687. workDir = workDirParents[0];
  688. for (unsigned int d = 0; d < workDirDepth; d++)
  689. {
  690. workDirParents[d] = workDirParents[d+1];
  691. }
  692. #ifdef SDCARD_SORT_ALPHA
  693. presort();
  694. #endif
  695. }
  696. }
  697. #ifdef SDCARD_SORT_ALPHA
  698. /**
  699. * Get the name of a file in the current directory by sort-index
  700. */
  701. void CardReader::getfilename_sorted(const uint16_t nr) {
  702. getfilename(
  703. #if SDSORT_GCODE
  704. sort_alpha &&
  705. #endif
  706. (nr < sort_count) ? sort_order[nr] : nr
  707. );
  708. }
  709. /**
  710. * Read all the files and produce a sort key
  711. *
  712. * We can do this in 3 ways...
  713. * - Minimal RAM: Read two filenames at a time sorting along...
  714. * - Some RAM: Buffer the directory just for this sort
  715. * - Most RAM: Buffer the directory and return filenames from RAM
  716. */
  717. void CardReader::presort() {
  718. if (farm_mode || IS_SD_INSERTED == false) return; //sorting is not used in farm mode
  719. uint8_t sdSort = eeprom_read_byte((uint8_t*)EEPROM_SD_SORT);
  720. if (sdSort == SD_SORT_NONE) return; //sd sort is turned off
  721. #if SDSORT_GCODE
  722. if (!sort_alpha) return;
  723. #endif
  724. KEEPALIVE_STATE(IN_HANDLER);
  725. // Throw away old sort index
  726. flush_presort();
  727. // If there are files, sort up to the limit
  728. uint16_t fileCnt = getnrfilenames();
  729. if (fileCnt > 0) {
  730. // Never sort more than the max allowed
  731. // If you use folders to organize, 20 may be enough
  732. if (fileCnt > SDSORT_LIMIT) {
  733. 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
  734. fileCnt = SDSORT_LIMIT;
  735. }
  736. lcd_clear();
  737. #if !SDSORT_USES_RAM
  738. lcd_set_progress();
  739. #endif
  740. lcd_puts_at_P(0, 1, _i("Sorting files"));////MSG_SORTING c=20 r=1
  741. // Sort order is always needed. May be static or dynamic.
  742. #if SDSORT_DYNAMIC_RAM
  743. sort_order = new uint8_t[fileCnt];
  744. #endif
  745. // Use RAM to store the entire directory during pre-sort.
  746. // SDSORT_LIMIT should be set to prevent over-allocation.
  747. #if SDSORT_USES_RAM
  748. // If using dynamic ram for names, allocate on the heap.
  749. #if SDSORT_CACHE_NAMES
  750. #if SDSORT_DYNAMIC_RAM
  751. sortshort = new char*[fileCnt];
  752. sortnames = new char*[fileCnt];
  753. #endif
  754. #elif SDSORT_USES_STACK
  755. char sortnames[fileCnt][LONG_FILENAME_LENGTH];
  756. uint16_t modification_time[fileCnt];
  757. uint16_t modification_date[fileCnt];
  758. #endif
  759. // Folder sorting needs 1 bit per entry for flags.
  760. #if HAS_FOLDER_SORTING
  761. #if SDSORT_DYNAMIC_RAM
  762. isDir = new uint8_t[(fileCnt + 7) >> 3];
  763. #elif SDSORT_USES_STACK
  764. uint8_t isDir[(fileCnt + 7) >> 3];
  765. #endif
  766. #endif
  767. #else // !SDSORT_USES_RAM
  768. uint32_t positions[fileCnt];
  769. // By default re-read the names from SD for every compare
  770. // retaining only two filenames at a time. This is very
  771. // slow but is safest and uses minimal RAM.
  772. char name1[LONG_FILENAME_LENGTH + 1];
  773. uint16_t crmod_time_bckp;
  774. uint16_t crmod_date_bckp;
  775. #endif
  776. position = 0;
  777. if (fileCnt > 1) {
  778. // Init sort order.
  779. for (uint16_t i = 0; i < fileCnt; i++) {
  780. if (!IS_SD_INSERTED) return;
  781. manage_heater();
  782. sort_order[i] = i;
  783. positions[i] = position;
  784. getfilename(i);
  785. // If using RAM then read all filenames now.
  786. #if SDSORT_USES_RAM
  787. getfilename(i);
  788. #if SDSORT_DYNAMIC_RAM
  789. // Use dynamic method to copy long filename
  790. sortnames[i] = strdup(LONGEST_FILENAME);
  791. #if SDSORT_CACHE_NAMES
  792. // When caching also store the short name, since
  793. // we're replacing the getfilename() behavior.
  794. sortshort[i] = strdup(filename);
  795. #endif
  796. #else
  797. // Copy filenames into the static array
  798. strcpy(sortnames[i], LONGEST_FILENAME);
  799. modification_time[i] = crmodTime;
  800. modification_date[i] = crmodDate;
  801. #if SDSORT_CACHE_NAMES
  802. strcpy(sortshort[i], filename);
  803. #endif
  804. #endif
  805. // char out[30];
  806. // sprintf_P(out, PSTR("---- %i %s %s"), i, filenameIsDir ? "D" : " ", sortnames[i]);
  807. // SERIAL_ECHOLN(out);
  808. #if HAS_FOLDER_SORTING
  809. const uint16_t bit = i & 0x07, ind = i >> 3;
  810. if (bit == 0) isDir[ind] = 0x00;
  811. if (filenameIsDir) isDir[ind] |= _BV(bit);
  812. #endif
  813. #endif
  814. }
  815. #ifdef QUICKSORT
  816. quicksort(0, fileCnt - 1);
  817. #else //Qicksort not defined, use Bubble Sort
  818. uint32_t counter = 0;
  819. uint16_t total = 0.5*(fileCnt - 1)*(fileCnt);
  820. // Compare names from the array or just the two buffered names
  821. #if SDSORT_USES_RAM
  822. #define _SORT_CMP_NODIR() (strcasecmp(sortnames[o1], sortnames[o2]) > 0)
  823. #define _SORT_CMP_TIME_NODIR() (((modification_date[o1] == modification_date[o2]) && (modification_time[o1] < modification_time[o2])) || \
  824. (modification_date[o1] < modification_date [o2]))
  825. #else
  826. #define _SORT_CMP_NODIR() (strcasecmp(name1, name2) > 0) //true if lowercase(name1) > lowercase(name2)
  827. #define _SORT_CMP_TIME_NODIR() (((crmod_date_bckp == crmodDate) && (crmod_time_bckp > crmodTime)) || \
  828. (crmod_date_bckp > crmodDate))
  829. #endif
  830. #if HAS_FOLDER_SORTING
  831. #if SDSORT_USES_RAM
  832. // Folder sorting needs an index and bit to test for folder-ness.
  833. const uint8_t ind1 = o1 >> 3, bit1 = o1 & 0x07,
  834. ind2 = o2 >> 3, bit2 = o2 & 0x07;
  835. #define _SORT_CMP_DIR(fs) \
  836. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  837. ? _SORT_CMP_NODIR() \
  838. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  839. #define _SORT_CMP_TIME_DIR(fs) \
  840. (((isDir[ind1] & _BV(bit1)) != 0) == ((isDir[ind2] & _BV(bit2)) != 0) \
  841. ? _SORT_CMP_TIME_NODIR() \
  842. : (isDir[fs > 0 ? ind1 : ind2] & (fs > 0 ? _BV(bit1) : _BV(bit2))) != 0)
  843. #else
  844. #define _SORT_CMP_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_NODIR() : (fs > 0 ? dir1 : !dir1))
  845. #define _SORT_CMP_TIME_DIR(fs) ((dir1 == filenameIsDir) ? _SORT_CMP_TIME_NODIR() : (fs < 0 ? dir1 : !dir1))
  846. #endif
  847. #endif
  848. for (uint16_t i = fileCnt; --i;) {
  849. if (!IS_SD_INSERTED) return;
  850. bool didSwap = false;
  851. #if !SDSORT_USES_RAM //show progresss bar only if slow sorting method is used
  852. int8_t percent = (counter * 100) / total;//((counter * 100) / pow((fileCnt-1),2));
  853. for (int column = 0; column < 20; column++) {
  854. if (column < (percent / 5))
  855. {
  856. lcd_putc_at(column, 2, '\x01'); //simple progress bar
  857. }
  858. }
  859. counter++;
  860. #endif
  861. //MYSERIAL.println(int(i));
  862. for (uint16_t j = 0; j < i; ++j) {
  863. if (!IS_SD_INSERTED) return;
  864. manage_heater();
  865. const uint16_t o1 = sort_order[j], o2 = sort_order[j + 1];
  866. // The most economical method reads names as-needed
  867. // throughout the loop. Slow if there are many.
  868. #if !SDSORT_USES_RAM
  869. counter++;
  870. getfilename_simple(positions[o1]);
  871. strcpy(name1, LONGEST_FILENAME); // save (or getfilename below will trounce it)
  872. crmod_date_bckp = crmodDate;
  873. crmod_time_bckp = crmodTime;
  874. #if HAS_FOLDER_SORTING
  875. bool dir1 = filenameIsDir;
  876. #endif
  877. getfilename_simple(positions[o2]);
  878. char *name2 = LONGEST_FILENAME; // use the string in-place
  879. #endif // !SDSORT_USES_RAM
  880. // Sort the current pair according to settings.
  881. if (
  882. #if HAS_FOLDER_SORTING
  883. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_DIR(FOLDER_SORTING)) || (sdSort == SD_SORT_ALPHA && _SORT_CMP_DIR(FOLDER_SORTING))
  884. #else
  885. (sdSort == SD_SORT_TIME && _SORT_CMP_TIME_NODIR()) || (sdSort == SD_SORT_ALPHA && _SORT_CMP_NODIR())
  886. #endif
  887. )
  888. {
  889. sort_order[j] = o2;
  890. sort_order[j + 1] = o1;
  891. didSwap = true;
  892. }
  893. }
  894. if (!didSwap) break;
  895. } //end of bubble sort loop
  896. #endif
  897. // Using RAM but not keeping names around
  898. #if (SDSORT_USES_RAM && !SDSORT_CACHE_NAMES)
  899. #if SDSORT_DYNAMIC_RAM
  900. for (uint16_t i = 0; i < fileCnt; ++i) free(sortnames[i]);
  901. #if HAS_FOLDER_SORTING
  902. free(isDir);
  903. #endif
  904. #endif
  905. #endif
  906. }
  907. else {
  908. sort_order[0] = 0;
  909. #if (SDSORT_USES_RAM && SDSORT_CACHE_NAMES)
  910. getfilename(0);
  911. #if SDSORT_DYNAMIC_RAM
  912. sortnames = new char*[1];
  913. sortnames[0] = strdup(LONGEST_FILENAME); // malloc
  914. sortshort = new char*[1];
  915. sortshort[0] = strdup(filename); // malloc
  916. isDir = new uint8_t[1];
  917. #else
  918. strcpy(sortnames[0], LONGEST_FILENAME);
  919. strcpy(sortshort[0], filename);
  920. #endif
  921. isDir[0] = filenameIsDir ? 0x01 : 0x00;
  922. #endif
  923. }
  924. sort_count = fileCnt;
  925. }
  926. #if !SDSORT_USES_RAM //show progresss bar only if slow sorting method is used
  927. for (int column = 0; column <= 19; column++)
  928. {
  929. lcd_putc_at(column, 2, '\x01'); //simple progress bar
  930. }
  931. _delay(300);
  932. lcd_set_degree();
  933. lcd_clear();
  934. #endif
  935. lcd_update(2);
  936. KEEPALIVE_STATE(NOT_BUSY);
  937. lcd_timeoutToStatus.start();
  938. }
  939. void CardReader::flush_presort() {
  940. if (sort_count > 0) {
  941. #if SDSORT_DYNAMIC_RAM
  942. delete sort_order;
  943. #if SDSORT_CACHE_NAMES
  944. for (uint8_t i = 0; i < sort_count; ++i) {
  945. free(sortshort[i]); // strdup
  946. free(sortnames[i]); // strdup
  947. }
  948. delete sortshort;
  949. delete sortnames;
  950. #endif
  951. #endif
  952. sort_count = 0;
  953. }
  954. }
  955. #endif // SDCARD_SORT_ALPHA
  956. void CardReader::printingHasFinished()
  957. {
  958. st_synchronize();
  959. if(file_subcall_ctr>0) //heading up to a parent file that called current as a procedure.
  960. {
  961. file.close();
  962. file_subcall_ctr--;
  963. openFile(filenames[file_subcall_ctr],true,true);
  964. setIndex(filespos[file_subcall_ctr]);
  965. startFileprint();
  966. }
  967. else
  968. {
  969. quickStop();
  970. file.close();
  971. sdprinting = false;
  972. if(SD_FINISHED_STEPPERRELEASE)
  973. {
  974. finishAndDisableSteppers();
  975. //enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  976. }
  977. autotempShutdown();
  978. #ifdef SDCARD_SORT_ALPHA
  979. //presort();
  980. #endif
  981. }
  982. }
  983. bool CardReader::ToshibaFlashAir_GetIP(uint8_t *ip)
  984. {
  985. memset(ip, 0, 4);
  986. return card.readExtMemory(1, 1, 0x400+0x150, 4, ip);
  987. }
  988. #endif //SDSUPPORT