Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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