Debian Codegraph @

app/testdata/libraries/SD_1.2.1/SD/src/SD.cpp

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