You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

612 lines
14KB

  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;
  241. SdFile d2;
  242. d1.openRoot(volume); // start with the mostparent, root!
  243. // we'll use the pointers to swap between the two objects
  244. SdFile *parent = &d1;
  245. SdFile *subdir = &d2;
  246. const char *origpath = filepath;
  247. while (strchr(filepath, '/')) {
  248. // get rid of leading /'s
  249. if (filepath[0] == '/') {
  250. filepath++;
  251. continue;
  252. }
  253. if (! strchr(filepath, '/')) {
  254. // it was in the root directory, so leave now
  255. break;
  256. }
  257. // extract just the name of the next subdirectory
  258. uint8_t idx = strchr(filepath, '/') - filepath;
  259. if (idx > 12)
  260. idx = 12; // dont let them specify long names
  261. char subdirname[13];
  262. strncpy(subdirname, filepath, idx);
  263. subdirname[idx] = 0;
  264. // close the subdir (we reuse them) if open
  265. subdir->close();
  266. if (! subdir->open(parent, subdirname, O_READ)) {
  267. // failed to open one of the subdirectories
  268. return SdFile();
  269. }
  270. // move forward to the next subdirectory
  271. filepath += idx;
  272. // we reuse the objects, close it.
  273. parent->close();
  274. // swap the pointers
  275. SdFile *t = parent;
  276. parent = subdir;
  277. subdir = t;
  278. }
  279. *index = (int)(filepath - origpath);
  280. // parent is now the parent diretory of the file!
  281. return *parent;
  282. }
  283. File SDClass::open(const char *filepath, uint8_t mode) {
  284. /*
  285. Open the supplied file path for reading or writing.
  286. The file content can be accessed via the `file` property of
  287. the `SDClass` object--this property is currently
  288. a standard `SdFile` object from `sdfatlib`.
  289. Defaults to read only.
  290. If `write` is true, default action (when `append` is true) is to
  291. append data to the end of the file.
  292. If `append` is false then the file will be truncated first.
  293. If the file does not exist and it is opened for writing the file
  294. will be created.
  295. An attempt to open a file for reading that does not exist is an
  296. error.
  297. */
  298. int pathidx;
  299. // do the interative search
  300. SdFile parentdir = getParentDir(filepath, &pathidx);
  301. // no more subdirs!
  302. filepath += pathidx;
  303. if (! filepath[0]) {
  304. // it was the directory itself!
  305. return File(parentdir, "/");
  306. }
  307. // Open the file itself
  308. SdFile file;
  309. // failed to open a subdir!
  310. if (!parentdir.isOpen())
  311. return File();
  312. if ( ! file.open(parentdir, filepath, mode)) {
  313. return File();
  314. }
  315. // close the parent
  316. parentdir.close();
  317. if (mode & (O_APPEND | O_WRITE))
  318. file.seekSet(file.fileSize());
  319. return File(file, filepath);
  320. }
  321. /*
  322. File SDClass::open(char *filepath, uint8_t mode) {
  323. //
  324. Open the supplied file path for reading or writing.
  325. The file content can be accessed via the `file` property of
  326. the `SDClass` object--this property is currently
  327. a standard `SdFile` object from `sdfatlib`.
  328. Defaults to read only.
  329. If `write` is true, default action (when `append` is true) is to
  330. append data to the end of the file.
  331. If `append` is false then the file will be truncated first.
  332. If the file does not exist and it is opened for writing the file
  333. will be created.
  334. An attempt to open a file for reading that does not exist is an
  335. error.
  336. //
  337. // TODO: Allow for read&write? (Possibly not, as it requires seek.)
  338. fileOpenMode = mode;
  339. walkPath(filepath, root, callback_openPath, this);
  340. return File();
  341. }
  342. */
  343. //boolean SDClass::close() {
  344. // /*
  345. //
  346. // Closes the file opened by the `open` method.
  347. //
  348. // */
  349. // file.close();
  350. //}
  351. boolean SDClass::exists(const char *filepath) {
  352. /*
  353. Returns true if the supplied file path exists.
  354. */
  355. return walkPath(filepath, root, callback_pathExists);
  356. }
  357. //boolean SDClass::exists(char *filepath, SdFile& parentDir) {
  358. // /*
  359. //
  360. // Returns true if the supplied file path rooted at `parentDir`
  361. // exists.
  362. //
  363. // */
  364. // return walkPath(filepath, parentDir, callback_pathExists);
  365. //}
  366. boolean SDClass::mkdir(const char *filepath) {
  367. /*
  368. Makes a single directory or a heirarchy of directories.
  369. A rough equivalent to `mkdir -p`.
  370. */
  371. return walkPath(filepath, root, callback_makeDirPath);
  372. }
  373. boolean SDClass::rmdir(const char *filepath) {
  374. /*
  375. Makes a single directory or a heirarchy of directories.
  376. A rough equivalent to `mkdir -p`.
  377. */
  378. return walkPath(filepath, root, callback_rmdir);
  379. }
  380. boolean SDClass::remove(const char *filepath) {
  381. return walkPath(filepath, root, callback_remove);
  382. }
  383. // allows you to recurse into a directory
  384. File File::openNextFile(uint8_t mode) {
  385. dir_t p;
  386. //Serial.print("\t\treading dir...");
  387. while (_file->readDir(&p) > 0) {
  388. // done if past last used entry
  389. if (p.name[0] == DIR_NAME_FREE) {
  390. //Serial.println("end");
  391. return File();
  392. }
  393. // skip deleted entry and entries for . and ..
  394. if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') {
  395. //Serial.println("dots");
  396. continue;
  397. }
  398. // only list subdirectories and files
  399. if (!DIR_IS_FILE_OR_SUBDIR(&p)) {
  400. //Serial.println("notafile");
  401. continue;
  402. }
  403. // print file name with possible blank fill
  404. SdFile f;
  405. char name[13];
  406. _file->dirName(p, name);
  407. //Serial.print("try to open file ");
  408. //Serial.println(name);
  409. if (f.open(_file, name, mode)) {
  410. //Serial.println("OK!");
  411. return File(f, name);
  412. } else {
  413. //Serial.println("ugh");
  414. return File();
  415. }
  416. }
  417. //Serial.println("nothing");
  418. return File();
  419. }
  420. void File::rewindDirectory(void) {
  421. if (isDirectory())
  422. _file->rewind();
  423. }
  424. SDClass SD;
  425. #endif