Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

619 lines
15KB

  1. /*
  2. SD - a slightly more friendly wrapper for sdfatlib
  3. This library aims to expose a subset of SD card functionality
  4. in the form of a higher level "wrapper" object.
  5. License: GNU General Public License V3
  6. (Because sdfatlib is licensed with this.)
  7. (C) Copyright 2010 SparkFun Electronics
  8. This library provides four key benefits:
  9. * Including `SD.h` automatically creates a global
  10. `SD` object which can be interacted with in a similar
  11. manner to other standard global objects like `Serial` and `Ethernet`.
  12. * Boilerplate initialisation code is contained in one method named
  13. `begin` and no further objects need to be created in order to access
  14. the SD card.
  15. * Calls to `open` can supply a full path name including parent
  16. directories which simplifies interacting with files in subdirectories.
  17. * Utility methods are provided to determine whether a file exists
  18. and to create a directory heirarchy.
  19. Note however that not all functionality provided by the underlying
  20. sdfatlib library is exposed.
  21. */
  22. /*
  23. Implementation Notes
  24. In order to handle multi-directory path traversal, functionality that
  25. requires this ability is implemented as callback functions.
  26. Individual methods call the `walkPath` function which performs the actual
  27. directory traversal (swapping between two different directory/file handles
  28. along the way) and at each level calls the supplied callback function.
  29. Some types of functionality will take an action at each level (e.g. exists
  30. or make directory) which others will only take an action at the bottom
  31. level (e.g. open).
  32. */
  33. #include "SD.h"
  34. #ifndef __SD_t3_H__
  35. // Used by `getNextPathComponent`
  36. #define MAX_COMPONENT_LEN 12 // What is max length?
  37. #define PATH_COMPONENT_BUFFER_LEN MAX_COMPONENT_LEN+1
  38. bool getNextPathComponent(const char *path, unsigned int *p_offset,
  39. char *buffer) {
  40. /*
  41. Parse individual path components from a path.
  42. e.g. after repeated calls '/foo/bar/baz' will be split
  43. into 'foo', 'bar', 'baz'.
  44. This is similar to `strtok()` but copies the component into the
  45. supplied buffer rather than modifying the original string.
  46. `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size.
  47. `p_offset` needs to point to an integer of the offset at
  48. which the previous path component finished.
  49. Returns `true` if more components remain.
  50. Returns `false` if this is the last component.
  51. (This means path ended with 'foo' or 'foo/'.)
  52. */
  53. // TODO: Have buffer local to this function, so we know it's the
  54. // correct length?
  55. int bufferOffset = 0;
  56. int offset = *p_offset;
  57. // Skip root or other separator
  58. if (path[offset] == '/') {
  59. offset++;
  60. }
  61. // Copy the next next path segment
  62. while (bufferOffset < MAX_COMPONENT_LEN
  63. && (path[offset] != '/')
  64. && (path[offset] != '\0')) {
  65. buffer[bufferOffset++] = path[offset++];
  66. }
  67. buffer[bufferOffset] = '\0';
  68. // Skip trailing separator so we can determine if this
  69. // is the last component in the path or not.
  70. if (path[offset] == '/') {
  71. offset++;
  72. }
  73. *p_offset = offset;
  74. return (path[offset] != '\0');
  75. }
  76. boolean walkPath(const char *filepath, SdFile& parentDir,
  77. boolean (*callback)(SdFile& parentDir,
  78. char *filePathComponent,
  79. boolean isLastComponent,
  80. void *object),
  81. void *object = NULL) {
  82. /*
  83. When given a file path (and parent directory--normally root),
  84. this function traverses the directories in the path and at each
  85. level calls the supplied callback function while also providing
  86. the supplied object for context if required.
  87. e.g. given the path '/foo/bar/baz'
  88. the callback would be called at the equivalent of
  89. '/foo', '/foo/bar' and '/foo/bar/baz'.
  90. The implementation swaps between two different directory/file
  91. handles as it traverses the directories and does not use recursion
  92. in an attempt to use memory efficiently.
  93. If a callback wishes to stop the directory traversal it should
  94. return false--in this case the function will stop the traversal,
  95. tidy up and return false.
  96. If a directory path doesn't exist at some point this function will
  97. also return false and not subsequently call the callback.
  98. If a directory path specified is complete, valid and the callback
  99. did not indicate the traversal should be interrupted then this
  100. function will return true.
  101. */
  102. SdFile subfile1;
  103. SdFile subfile2;
  104. char buffer[PATH_COMPONENT_BUFFER_LEN];
  105. unsigned int offset = 0;
  106. SdFile *p_parent;
  107. SdFile *p_child;
  108. SdFile *p_tmp_sdfile;
  109. p_child = &subfile1;
  110. p_parent = &parentDir;
  111. while (true) {
  112. boolean moreComponents = getNextPathComponent(filepath, &offset, buffer);
  113. boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object);
  114. if (!shouldContinue) {
  115. // TODO: Don't repeat this code?
  116. // If it's one we've created then we
  117. // don't need the parent handle anymore.
  118. if (p_parent != &parentDir) {
  119. (*p_parent).close();
  120. }
  121. return false;
  122. }
  123. if (!moreComponents) {
  124. break;
  125. }
  126. boolean exists = (*p_child).open(*p_parent, buffer, O_RDONLY);
  127. // If it's one we've created then we
  128. // don't need the parent handle anymore.
  129. if (p_parent != &parentDir) {
  130. (*p_parent).close();
  131. }
  132. // Handle case when it doesn't exist and we can't continue...
  133. if (exists) {
  134. // We alternate between two file handles as we go down
  135. // the path.
  136. if (p_parent == &parentDir) {
  137. p_parent = &subfile2;
  138. }
  139. p_tmp_sdfile = p_parent;
  140. p_parent = p_child;
  141. p_child = p_tmp_sdfile;
  142. } else {
  143. return false;
  144. }
  145. }
  146. if (p_parent != &parentDir) {
  147. (*p_parent).close(); // TODO: Return/ handle different?
  148. }
  149. return true;
  150. }
  151. /*
  152. The callbacks used to implement various functionality follow.
  153. Each callback is supplied with a parent directory handle,
  154. character string with the name of the current file path component,
  155. a flag indicating if this component is the last in the path and
  156. a pointer to an arbitrary object used for context.
  157. */
  158. boolean callback_pathExists(SdFile& parentDir, char *filePathComponent,
  159. boolean isLastComponent, void *object) {
  160. /*
  161. Callback used to determine if a file/directory exists in parent
  162. directory.
  163. Returns true if file path exists.
  164. */
  165. SdFile child;
  166. boolean exists = child.open(parentDir, filePathComponent, O_RDONLY);
  167. if (exists) {
  168. child.close();
  169. }
  170. return exists;
  171. }
  172. boolean callback_makeDirPath(SdFile& parentDir, char *filePathComponent,
  173. boolean isLastComponent, void *object) {
  174. /*
  175. Callback used to create a directory in the parent directory if
  176. it does not already exist.
  177. Returns true if a directory was created or it already existed.
  178. */
  179. boolean result = false;
  180. SdFile child;
  181. result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object);
  182. if (!result) {
  183. result = child.makeDir(parentDir, filePathComponent);
  184. }
  185. return result;
  186. }
  187. /*
  188. boolean callback_openPath(SdFile& parentDir, char *filePathComponent,
  189. boolean isLastComponent, void *object) {
  190. Callback used to open a file specified by a filepath that may
  191. specify one or more directories above it.
  192. Expects the context object to be an instance of `SDClass` and
  193. will use the `file` property of the instance to open the requested
  194. file/directory with the associated file open mode property.
  195. Always returns true if the directory traversal hasn't reached the
  196. bottom of the directory heirarchy.
  197. Returns false once the file has been opened--to prevent the traversal
  198. from descending further. (This may be unnecessary.)
  199. if (isLastComponent) {
  200. SDClass *p_SD = static_cast<SDClass*>(object);
  201. p_SD->file.open(parentDir, filePathComponent, p_SD->fileOpenMode);
  202. if (p_SD->fileOpenMode == FILE_WRITE) {
  203. p_SD->file.seekSet(p_SD->file.fileSize());
  204. }
  205. // TODO: Return file open result?
  206. return false;
  207. }
  208. return true;
  209. }
  210. */
  211. boolean callback_remove(SdFile& parentDir, char *filePathComponent,
  212. boolean isLastComponent, void *object) {
  213. if (isLastComponent) {
  214. return SdFile::remove(parentDir, filePathComponent);
  215. }
  216. return true;
  217. }
  218. boolean callback_rmdir(SdFile& parentDir, char *filePathComponent,
  219. boolean isLastComponent, void *object) {
  220. if (isLastComponent) {
  221. SdFile f;
  222. if (!f.open(parentDir, filePathComponent, O_READ)) return false;
  223. return f.rmDir();
  224. }
  225. return true;
  226. }
  227. /* Implementation of class used to create `SDCard` object. */
  228. boolean SDClass::begin(uint8_t csPin) {
  229. /*
  230. Performs the initialisation required by the sdfatlib library.
  231. Return true if initialization succeeds, false otherwise.
  232. */
  233. return card.init(SPI_HALF_SPEED, csPin) &&
  234. volume.init(card) &&
  235. root.openRoot(volume);
  236. }
  237. // this little helper is used to traverse paths
  238. SdFile SDClass::getParentDir(const char *filepath, int *index) {
  239. // get parent directory
  240. SdFile d1 = root; // start with the mostparent, root!
  241. SdFile d2;
  242. // we'll use the pointers to swap between the two objects
  243. SdFile *parent = &d1;
  244. SdFile *subdir = &d2;
  245. const char *origpath = filepath;
  246. while (strchr(filepath, '/')) {
  247. // get rid of leading /'s
  248. if (filepath[0] == '/') {
  249. filepath++;
  250. continue;
  251. }
  252. if (! strchr(filepath, '/')) {
  253. // it was in the root directory, so leave now
  254. break;
  255. }
  256. // extract just the name of the next subdirectory
  257. uint8_t idx = strchr(filepath, '/') - filepath;
  258. if (idx > 12)
  259. idx = 12; // dont let them specify long names
  260. char subdirname[13];
  261. strncpy(subdirname, filepath, idx);
  262. subdirname[idx] = 0;
  263. // close the subdir (we reuse them) if open
  264. subdir->close();
  265. if (! subdir->open(parent, subdirname, O_READ)) {
  266. // failed to open one of the subdirectories
  267. return SdFile();
  268. }
  269. // move forward to the next subdirectory
  270. filepath += idx;
  271. // we reuse the objects, close it.
  272. parent->close();
  273. // swap the pointers
  274. SdFile *t = parent;
  275. parent = subdir;
  276. subdir = t;
  277. }
  278. *index = (int)(filepath - origpath);
  279. // parent is now the parent diretory of the file!
  280. return *parent;
  281. }
  282. File SDClass::open(const char *filepath, uint8_t mode) {
  283. /*
  284. Open the supplied file path for reading or writing.
  285. The file content can be accessed via the `file` property of
  286. the `SDClass` object--this property is currently
  287. a standard `SdFile` object from `sdfatlib`.
  288. Defaults to read only.
  289. If `write` is true, default action (when `append` is true) is to
  290. append data to the end of the file.
  291. If `append` is false then the file will be truncated first.
  292. If the file does not exist and it is opened for writing the file
  293. will be created.
  294. An attempt to open a file for reading that does not exist is an
  295. error.
  296. */
  297. int pathidx;
  298. // do the interative search
  299. SdFile parentdir = getParentDir(filepath, &pathidx);
  300. // no more subdirs!
  301. filepath += pathidx;
  302. if (! filepath[0]) {
  303. // it was the directory itself!
  304. return File(parentdir, "/");
  305. }
  306. // Open the file itself
  307. SdFile file;
  308. // failed to open a subdir!
  309. if (!parentdir.isOpen())
  310. return File();
  311. // there is a special case for the Root directory since its a static dir
  312. if (parentdir.isRoot()) {
  313. if ( ! file.open(SD.root, filepath, mode)) {
  314. // failed to open the file :(
  315. return File();
  316. }
  317. // dont close the root!
  318. } else {
  319. if ( ! file.open(parentdir, filepath, mode)) {
  320. return File();
  321. }
  322. // close the parent
  323. parentdir.close();
  324. }
  325. if (mode & (O_APPEND | O_WRITE))
  326. file.seekSet(file.fileSize());
  327. return File(file, filepath);
  328. }
  329. /*
  330. File SDClass::open(char *filepath, uint8_t mode) {
  331. //
  332. Open the supplied file path for reading or writing.
  333. The file content can be accessed via the `file` property of
  334. the `SDClass` object--this property is currently
  335. a standard `SdFile` object from `sdfatlib`.
  336. Defaults to read only.
  337. If `write` is true, default action (when `append` is true) is to
  338. append data to the end of the file.
  339. If `append` is false then the file will be truncated first.
  340. If the file does not exist and it is opened for writing the file
  341. will be created.
  342. An attempt to open a file for reading that does not exist is an
  343. error.
  344. //
  345. // TODO: Allow for read&write? (Possibly not, as it requires seek.)
  346. fileOpenMode = mode;
  347. walkPath(filepath, root, callback_openPath, this);
  348. return File();
  349. }
  350. */
  351. //boolean SDClass::close() {
  352. // /*
  353. //
  354. // Closes the file opened by the `open` method.
  355. //
  356. // */
  357. // file.close();
  358. //}
  359. boolean SDClass::exists(const char *filepath) {
  360. /*
  361. Returns true if the supplied file path exists.
  362. */
  363. return walkPath(filepath, root, callback_pathExists);
  364. }
  365. //boolean SDClass::exists(char *filepath, SdFile& parentDir) {
  366. // /*
  367. //
  368. // Returns true if the supplied file path rooted at `parentDir`
  369. // exists.
  370. //
  371. // */
  372. // return walkPath(filepath, parentDir, callback_pathExists);
  373. //}
  374. boolean SDClass::mkdir(const char *filepath) {
  375. /*
  376. Makes a single directory or a heirarchy of directories.
  377. A rough equivalent to `mkdir -p`.
  378. */
  379. return walkPath(filepath, root, callback_makeDirPath);
  380. }
  381. boolean SDClass::rmdir(const char *filepath) {
  382. /*
  383. Makes a single directory or a heirarchy of directories.
  384. A rough equivalent to `mkdir -p`.
  385. */
  386. return walkPath(filepath, root, callback_rmdir);
  387. }
  388. boolean SDClass::remove(const char *filepath) {
  389. return walkPath(filepath, root, callback_remove);
  390. }
  391. // allows you to recurse into a directory
  392. File File::openNextFile(uint8_t mode) {
  393. dir_t p;
  394. //Serial.print("\t\treading dir...");
  395. while (_file->readDir(&p) > 0) {
  396. // done if past last used entry
  397. if (p.name[0] == DIR_NAME_FREE) {
  398. //Serial.println("end");
  399. return File();
  400. }
  401. // skip deleted entry and entries for . and ..
  402. if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') {
  403. //Serial.println("dots");
  404. continue;
  405. }
  406. // only list subdirectories and files
  407. if (!DIR_IS_FILE_OR_SUBDIR(&p)) {
  408. //Serial.println("notafile");
  409. continue;
  410. }
  411. // print file name with possible blank fill
  412. SdFile f;
  413. char name[13];
  414. _file->dirName(p, name);
  415. //Serial.print("try to open file ");
  416. //Serial.println(name);
  417. if (f.open(_file, name, mode)) {
  418. //Serial.println("OK!");
  419. return File(f, name);
  420. } else {
  421. //Serial.println("ugh");
  422. return File();
  423. }
  424. }
  425. //Serial.println("nothing");
  426. return File();
  427. }
  428. void File::rewindDirectory(void) {
  429. if (isDirectory())
  430. _file->rewind();
  431. }
  432. SDClass SD;
  433. #endif