SdFile.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /* Arduino SdFat Library
  2. * Copyright (C) 2009 by William Greiman
  3. *
  4. * This file is part of the Arduino SdFat Library
  5. *
  6. * This Library is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This Library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with the Arduino SdFat Library. If not, see
  18. * <http://www.gnu.org/licenses/>.
  19. */
  20. #include "Marlin.h"
  21. #ifdef SDSUPPORT
  22. #include "SdFile.h"
  23. /** Create a file object and open it in the current working directory.
  24. *
  25. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  26. *
  27. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  28. * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
  29. */
  30. SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) {
  31. }
  32. //size=100B
  33. bool SdFile::openFilteredGcode(SdBaseFile* dirFile, const char* path){
  34. if( open(dirFile, path, O_READ) ){
  35. gfReset(0,0);
  36. // compute the block to start with
  37. if( ! gfComputeNextFileBlock() )
  38. return false;
  39. return true;
  40. } else {
  41. return false;
  42. }
  43. }
  44. //size=90B
  45. bool SdFile::seekSetFilteredGcode(uint32_t pos){
  46. bool rv = seekSet(pos);
  47. gfComputeNextFileBlock();
  48. return rv;
  49. }
  50. //size=50B
  51. void SdFile::gfReset(uint32_t blk, uint16_t ofs){
  52. // @@TODO clean up
  53. gfBlock = blk;
  54. gfOffset = ofs;
  55. gfCachePBegin = vol_->cache()->data;
  56. // reset cache read ptr to its begin
  57. gfCacheP = gfCachePBegin;
  58. }
  59. //FORCE_INLINE const uint8_t * find_endl(const uint8_t *p){
  60. // while( *(++p) != '\n' ); // skip until a newline is found
  61. // return p;
  62. //}
  63. // think twice before allowing this to inline - manipulating 4B longs is costly
  64. // moreover - this function has its parameters in registers only, so no heavy stack usage besides the call/ret
  65. void __attribute__((noinline)) SdFile::gfUpdateCurrentPosition(uint16_t inc){
  66. curPosition_ += inc;
  67. }
  68. #define find_endl(resultP, startP) \
  69. __asm__ __volatile__ ( \
  70. "adiw r30, 1 \n" /* workaround the ++gfCacheP into post increment Z+ */ \
  71. "cycle: \n" \
  72. "ld r22, Z+ \n" \
  73. "cpi r22, 0x0A \n" \
  74. "brne cycle \n" \
  75. "sbiw r30, 1 \n" /* workaround the ++gfCacheP into post increment Z+ */ \
  76. : "=z" (resultP) /* result of the ASM code - in our case the Z register (R30:R31) */ \
  77. : "z" (startP) /* input of the ASM code - in our case the Z register as well (R30:R31) */ \
  78. : "r22" /* modifying register R22 - so that the compiler knows */ \
  79. )
  80. //size=400B
  81. // avoid calling the default heavy-weight read() for just one byte
  82. int16_t SdFile::readFilteredGcode(){
  83. gfEnsureBlock(); // this is unfortunate :( ... other calls are using the cache and we can loose the data block of our gcode file
  84. // assume, we have the 512B block cache filled and terminated with a '\n'
  85. // SERIAL_PROTOCOLPGM("read_byte enter:");
  86. // for(uint8_t i = 0; i < 16; ++i){
  87. // SERIAL_PROTOCOL( cacheP[i] );
  88. // }
  89. const uint8_t *start = gfCacheP;
  90. uint8_t consecutiveCommentLines = 0;
  91. while( *gfCacheP == ';' ){
  92. for(;;){
  93. //while( *(++gfCacheP) != '\n' ); // skip until a newline is found - suboptimal code!
  94. // Wondering, why this "nice while cycle" is done in such a weird way using a separate find_endl() function?
  95. // Have a look at the ASM code GCC produced!
  96. // At first - a separate find_endl() makes the compiler understand,
  97. // that I don't need to store gfCacheP every time, I'm only interested in the final address where the '\n' was found
  98. // - the cycle can run on CPU registers only without touching memory besides reading the character being compared.
  99. // Not only makes the code run considerably faster, but is also 40B shorter!
  100. // This was the generated code:
  101. //FORCE_INLINE const uint8_t * find_endl(const uint8_t *p){
  102. // while( *(++p) != '\n' ); // skip until a newline is found
  103. // return p; }
  104. // 11c5e: movw r30, r18
  105. // 11c60: subi r18, 0xFF ; 255
  106. // 11c62: sbci r19, 0xFF ; 255
  107. // 11c64: ld r22, Z
  108. // 11c66: cpi r22, 0x0A ; 10
  109. // 11c68: brne .-12 ; 0x11c5e <get_command()+0x524>
  110. // Still, even that was suboptimal as the compiler seems not to understand the usage of ld r22, Z+ (the plus is important)
  111. // aka automatic increment of the Z register (R30:R31 pair)
  112. // There is no other way than pure ASM!
  113. find_endl(gfCacheP, gfCacheP);
  114. // found a newline, prepare the next block if block cache end reached
  115. if( gfCacheP - gfCachePBegin >= 512 ){
  116. // at the end of block cache, fill new data in
  117. gfUpdateCurrentPosition( gfCacheP - start );
  118. if( ! gfComputeNextFileBlock() )goto fail;
  119. gfEnsureBlock(); // fetch it into RAM
  120. gfCacheP = start = gfCachePBegin;
  121. } else {
  122. if(++consecutiveCommentLines == 255){
  123. // SERIAL_PROTOCOLLN(sd->curPosition_);
  124. goto forceExit;
  125. }
  126. // peek the next byte - we are inside the block at least at 511th index - still safe
  127. if( *(gfCacheP+1) == ';' ){
  128. // consecutive comment
  129. ++gfCacheP;
  130. ++consecutiveCommentLines;
  131. }
  132. break; // found the real end of the line even across many blocks
  133. }
  134. }
  135. }
  136. forceExit:
  137. {
  138. gfUpdateCurrentPosition( gfCacheP - start + 1 );
  139. int16_t rv = *gfCacheP++;
  140. // prepare next block if needed
  141. if( gfCacheP - gfCachePBegin >= 512 ){
  142. if( ! gfComputeNextFileBlock() )goto fail;
  143. // don't need to force fetch the block here, it will get loaded on the next call
  144. gfCacheP = gfCachePBegin;
  145. }
  146. return rv;
  147. }
  148. fail:
  149. // SERIAL_PROTOCOLLNPGM("CacheFAIL");
  150. return -1;
  151. }
  152. //size=100B
  153. bool SdFile::gfEnsureBlock(){
  154. if ( vol_->cacheRawBlock(gfBlock, SdVolume::CACHE_FOR_READ)){
  155. // terminate with a '\n'
  156. const uint16_t terminateOfs = (fileSize_ - gfOffset) < 512 ? (fileSize_ - gfOffset) : 512U;
  157. vol_->cache()->data[ terminateOfs ] = '\n';
  158. return true;
  159. } else {
  160. return false;
  161. }
  162. }
  163. //size=350B
  164. bool SdFile::gfComputeNextFileBlock() {
  165. // error if not open or write only
  166. if (!isOpen() || !(flags_ & O_READ)) return false;
  167. gfOffset = curPosition_ & 0X1FF; // offset in block
  168. if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
  169. gfBlock = vol_->rootDirStart() + (curPosition_ >> 9);
  170. } else {
  171. uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
  172. if (gfOffset == 0 && blockOfCluster == 0) {
  173. // start of new cluster
  174. if (curPosition_ == 0) {
  175. // use first cluster in file
  176. curCluster_ = firstCluster_;
  177. } else {
  178. // get next cluster from FAT
  179. if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
  180. }
  181. }
  182. gfBlock = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
  183. }
  184. return true;
  185. }
  186. //------------------------------------------------------------------------------
  187. /** Write data to an open file.
  188. *
  189. * \note Data is moved to the cache but may not be written to the
  190. * storage device until sync() is called.
  191. *
  192. * \param[in] buf Pointer to the location of the data to be written.
  193. *
  194. * \param[in] nbyte Number of bytes to write.
  195. *
  196. * \return For success write() returns the number of bytes written, always
  197. * \a nbyte. If an error occurs, write() returns -1. Possible errors
  198. * include write() is called before a file has been opened, write is called
  199. * for a read-only file, device is full, a corrupt file system or an I/O error.
  200. *
  201. */
  202. int16_t SdFile::write(const void* buf, uint16_t nbyte) {
  203. return SdBaseFile::write(buf, nbyte);
  204. }
  205. //------------------------------------------------------------------------------
  206. /** Write a byte to a file. Required by the Arduino Print class.
  207. * \param[in] b the byte to be written.
  208. * Use writeError to check for errors.
  209. */
  210. #if ARDUINO >= 100
  211. size_t SdFile::write(uint8_t b)
  212. {
  213. return SdBaseFile::write(&b, 1);
  214. }
  215. #else
  216. void SdFile::write(uint8_t b)
  217. {
  218. SdBaseFile::write(&b, 1);
  219. }
  220. #endif
  221. //------------------------------------------------------------------------------
  222. /** Write a string to a file. Used by the Arduino Print class.
  223. * \param[in] str Pointer to the string.
  224. * Use writeError to check for errors.
  225. */
  226. void SdFile::write(const char* str) {
  227. SdBaseFile::write(str, strlen(str));
  228. }
  229. //------------------------------------------------------------------------------
  230. /** Write a PROGMEM string to a file.
  231. * \param[in] str Pointer to the PROGMEM string.
  232. * Use writeError to check for errors.
  233. */
  234. void SdFile::write_P(PGM_P str) {
  235. for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
  236. }
  237. //------------------------------------------------------------------------------
  238. /** Write a PROGMEM string followed by CR/LF to a file.
  239. * \param[in] str Pointer to the PROGMEM string.
  240. * Use writeError to check for errors.
  241. */
  242. void SdFile::writeln_P(PGM_P str) {
  243. write_P(str);
  244. write_P(PSTR("\r\n"));
  245. }
  246. #endif