PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
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.

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