cardreader.cpp 27 KB

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