| 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 | /* |
| 339 | |
| 340 | Performs the initialisation required by the sdfatlib library. |
| 341 | |
| 342 | Return true if initialization succeeds, false otherwise. |
| 343 | |
| 344 | */ |
| 345 | return card.init(SPI_HALF_SPEED, csPin) && |
| 346 | volume.init(card) && |
| 347 | root.openRoot(volume); |
| 348 | } |
| 349 | |
| 350 | boolean SDClass::begin(uint32_t clock, uint8_t csPin) { |
| 351 | return card.init(SPI_HALF_SPEED, csPin) && |
| 352 | card.setSpiClock(clock) && |
| 353 | volume.init(card) && |
| 354 | root.openRoot(volume); |
| 355 | } |
| 356 | |
| 357 | // this little helper is used to traverse paths |
| 358 | SdFile SDClass::getParentDir(const char *filepath, int *index) { |
| 359 | // get parent directory |
| 360 | SdFile d1 = root; // start with the mostparent, root! |
| 361 | SdFile d2; |
| 362 | |
| 363 | // we'll use the pointers to swap between the two objects |
| 364 | SdFile *parent = &d1; |
| 365 | SdFile *subdir = &d2; |
| 366 | |
| 367 | const char *origpath = filepath; |
| 368 | |
| 369 | while (strchr(filepath, '/')) { |
| 370 | |
| 371 | // get rid of leading /'s |
| 372 | if (filepath[0] == '/') { |
| 373 | filepath++; |
| 374 | continue; |
| 375 | } |
| 376 | |
| 377 | if (! strchr(filepath, '/')) { |
| 378 | // it was in the root directory, so leave now |
| 379 | break; |
| 380 | } |
| 381 | |
| 382 | // extract just the name of the next subdirectory |
| 383 | uint8_t idx = strchr(filepath, '/') - filepath; |
| 384 | if (idx > 12) |
| 385 | idx = 12; // dont let them specify long names |
| 386 | char subdirname[13]; |
| 387 | strncpy(subdirname, filepath, idx); |
| 388 | subdirname[idx] = 0; |
| 389 | |
| 390 | // close the subdir (we reuse them) if open |
| 391 | subdir->close(); |
| 392 | if (! subdir->open(parent, subdirname, O_READ)) { |
| 393 | // failed to open one of the subdirectories |
| 394 | return SdFile(); |
| 395 | } |
| 396 | // move forward to the next subdirectory |
| 397 | filepath += idx; |
| 398 | |
| 399 | // we reuse the objects, close it. |
| 400 | parent->close(); |
| 401 | |
| 402 | // swap the pointers |
| 403 | SdFile *t = parent; |
| 404 | parent = subdir; |
| 405 | subdir = t; |
| 406 | } |
| 407 | |
| 408 | *index = (int)(filepath - origpath); |
| 409 | // parent is now the parent diretory of the file! |
| 410 | return *parent; |
| 411 | } |
| 412 | |
| 413 | |
| 414 | File SDClass::open(const char *filepath, uint8_t mode) { |
| 415 | /* |
| 416 | |
| 417 | Open the supplied file path for reading or writing. |
| 418 | |
| 419 | The file content can be accessed via the `file` property of |
| 420 | the `SDClass` object--this property is currently |
| 421 | a standard `SdFile` object from `sdfatlib`. |
| 422 | |
| 423 | Defaults to read only. |
| 424 | |
| 425 | If `write` is true, default action (when `append` is true) is to |
| 426 | append data to the end of the file. |
| 427 | |
| 428 | If `append` is false then the file will be truncated first. |
| 429 | |
| 430 | If the file does not exist and it is opened for writing the file |
| 431 | will be created. |
| 432 | |
| 433 | An attempt to open a file for reading that does not exist is an |
| 434 | error. |
| 435 | |
| 436 | */ |
| 437 | |
| 438 | int pathidx; |
| 439 | |
| 440 | // do the interative search |
| 441 | SdFile parentdir = getParentDir(filepath, &pathidx); |
| 442 | // no more subdirs! |
| 443 | |
| 444 | filepath += pathidx; |
| 445 | |
| 446 | if (! filepath[0]) { |
| 447 | // it was the directory itself! |
| 448 | return File(parentdir, "/"); |
| 449 | } |
| 450 | |
| 451 | // Open the file itself |
| 452 | SdFile file; |
| 453 | |
| 454 | // failed to open a subdir! |
| 455 | if (!parentdir.isOpen()) |
| 456 | return File(); |
| 457 | |
| 458 | // there is a special case for the Root directory since its a static dir |
| 459 | if (parentdir.isRoot()) { |
| 460 | if ( ! file.open(root, filepath, mode)) { |
| 461 | // failed to open the file :( |
| 462 | return File(); |
| 463 | } |
| 464 | // dont close the root! |
| 465 | } else { |
| 466 | if ( ! file.open(parentdir, filepath, mode)) { |
| 467 | return File(); |
| 468 | } |
| 469 | // close the parent |
| 470 | parentdir.close(); |
| 471 | } |
| 472 | |
| 473 | if (mode & (O_APPEND | O_WRITE)) |
| 474 | file.seekSet(file.fileSize()); |
| 475 | return File(file, filepath); |
| 476 | } |
| 477 | |
| 478 | |
| 479 | /* |
| 480 | File SDClass::open(char *filepath, uint8_t mode) { |
| 481 | // |
| 482 | |
| 483 | Open the supplied file path for reading or writing. |
| 484 | |
| 485 | The file content can be accessed via the `file` property of |
| 486 | the `SDClass` object--this property is currently |
| 487 | a standard `SdFile` object from `sdfatlib`. |
| 488 | |
| 489 | Defaults to read only. |
| 490 | |
| 491 | If `write` is true, default action (when `append` is true) is to |
| 492 | append data to the end of the file. |
| 493 | |
| 494 | If `append` is false then the file will be truncated first. |
| 495 | |
| 496 | If the file does not exist and it is opened for writing the file |
| 497 | will be created. |
| 498 | |
| 499 | An attempt to open a file for reading that does not exist is an |
| 500 | error. |
| 501 | |
| 502 | // |
| 503 | |
| 504 | // TODO: Allow for read&write? (Possibly not, as it requires seek.) |
| 505 | |
| 506 | fileOpenMode = mode; |
| 507 | walkPath(filepath, root, callback_openPath, this); |
| 508 | |
| 509 | return File(); |
| 510 | |
| 511 | } |
| 512 | */ |
| 513 | |
| 514 | |
| 515 | //boolean SDClass::close() { |
| 516 | // /* |
| 517 | // |
| 518 | // Closes the file opened by the `open` method. |
| 519 | // |
| 520 | // */ |
| 521 | // file.close(); |
| 522 | //} |
| 523 | |
| 524 | |
| 525 | boolean SDClass::exists(const char *filepath) { |
| 526 | /* |
| 527 | |
| 528 | Returns true if the supplied file path exists. |
| 529 | |
| 530 | */ |
| 531 | return walkPath(filepath, root, callback_pathExists); |
| 532 | } |
| 533 | |
| 534 | |
| 535 | //boolean SDClass::exists(char *filepath, SdFile& parentDir) { |
| 536 | // /* |
| 537 | // |
| 538 | // Returns true if the supplied file path rooted at `parentDir` |
| 539 | // exists. |
| 540 | // |
| 541 | // */ |
| 542 | // return walkPath(filepath, parentDir, callback_pathExists); |
| 543 | //} |
| 544 | |
| 545 | |
| 546 | boolean SDClass::mkdir(const char *filepath) { |
| 547 | /* |
| 548 | |
| 549 | Makes a single directory or a heirarchy of directories. |
| 550 | |
| 551 | A rough equivalent to `mkdir -p`. |
| 552 | |
| 553 | */ |
| 554 | return walkPath(filepath, root, callback_makeDirPath); |
| 555 | } |
| 556 | |
| 557 | boolean SDClass::rmdir(const char *filepath) { |
| 558 | /* |
| 559 | |
| 560 | Remove a single directory or a heirarchy of directories. |
| 561 | |
| 562 | A rough equivalent to `rm -rf`. |
| 563 | |
| 564 | */ |
| 565 | return walkPath(filepath, root, callback_rmdir); |
| 566 | } |
| 567 | |
| 568 | boolean SDClass::remove(const char *filepath) { |
| 569 | return walkPath(filepath, root, callback_remove); |
| 570 | } |
| 571 | |
| 572 | |
| 573 | // allows you to recurse into a directory |
| 574 | File File::openNextFile(uint8_t mode) { |
| 575 | dir_t p; |
| 576 | |
| 577 | //Serial.print("\t\treading dir..."); |
| 578 | while (_file->readDir(&p) > 0) { |
| 579 | |
| 580 | // done if past last used entry |
| 581 | if (p.name[0] == DIR_NAME_FREE) { |
| 582 | //Serial.println("end"); |
| 583 | return File(); |
| 584 | } |
| 585 | |
| 586 | // skip deleted entry and entries for . and .. |
| 587 | if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') { |
| 588 | //Serial.println("dots"); |
| 589 | continue; |
| 590 | } |
| 591 | |
| 592 | // only list subdirectories and files |
| 593 | if (!DIR_IS_FILE_OR_SUBDIR(&p)) { |
| 594 | //Serial.println("notafile"); |
| 595 | continue; |
| 596 | } |
| 597 | |
| 598 | // print file name with possible blank fill |
| 599 | SdFile f; |
| 600 | char name[13]; |
| 601 | _file->dirName(p, name); |
| 602 | //Serial.print("try to open file "); |
| 603 | //Serial.println(name); |
| 604 | |
| 605 | if (f.open(_file, name, mode)) { |
| 606 | //Serial.println("OK!"); |
| 607 | return File(f, name); |
| 608 | } else { |
| 609 | //Serial.println("ugh"); |
| 610 | return File(); |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | //Serial.println("nothing"); |
| 615 | return File(); |
| 616 | } |
| 617 | |
| 618 | void File::rewindDirectory(void) { |
| 619 | if (isDirectory()) |
| 620 | _file->rewind(); |
| 621 | } |
| 622 | |
| 623 | SDClass SD; |
| 624 | |
| 625 | }; |