cardreader.cpp 27 KB

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