Unverified Commit 4e50fe86 authored by Earle F. Philhower, III's avatar Earle F. Philhower, III Committed by GitHub

Add LittleFS, SD, and SDFS Filesystems and File:: interface (#49)

Pull in the ESP8266 File/Dir/etc. filesystem and port LittleFS
and SD/SDFS to the RP2040.

See https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html
for more information
parent 1eb48f72
......@@ -7,6 +7,12 @@
[submodule "system/pyserial"]
path = tools/pyserial
url = https://github.com/pyserial/pyserial.git
[submodule "libraries/LittleFS/lib/littlefs"]
path = libraries/LittleFS/lib/littlefs
url = https://github.com/littlefs-project/littlefs.git
[submodule "libraries/SdFat"]
path = libraries/SdFat
url = https://github.com/earlephilhower/ESP8266SdFat.git
[submodule "pico-extras"]
path = pico-extras
url = https://github.com/raspberrypi/pico-extras.git
......@@ -66,7 +66,17 @@ Them hit the upload button and your sketch should upload and run.
In some cases the Pico will encounter a hard hang and its USB port will not respond to the auto-reset request. Should this happen, just
follow the initial procedure of holding the BOOTSEL button down while plugging in the Pico to enter the ROM bootloader.
# Uploading with Picoprobe
# Uploading Filesystem Images
The onboard flash filesystem for the Pico, LittleFS, lets you upload a filesystem image from the sketch directory for your sketch to use. Download the needed plugin from
* https://github.com/earlephilhower/arduino-pico-littlefs-plugin/releases
To install, follow the directions in
* https://github.com/earlephilhower/arduino-pico-littlefs-plugin/blob/master/README.md
For detailed usage information, please check the ESP8266 repo documentation (ignore SPIFFS related notes) available at
* https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html
# Uploading Sketches with Picoprobe
If you have built a Raspberry Pi Picoprobe, you can use OpenOCD to handle your sketch uploads and for debugging with GDB.
Under Windows a local admin user should be able to access the Picoprobe port automatically, but under Linux `udev` must be told about the device and to allow normal users access.
......@@ -88,15 +98,17 @@ The installed tools include a version of OpenOCD (in the pqt-openocd directory)
Relatively stable and very functional, but bug reports and PRs always accepted.
* digitalWrite/Read
* shiftIn/Out
* SPI master (tested using SdFat 2.0 https://github.com/greiman/SdFat ... note that the Pico voltage regulator can't reliably supply enough power for a SD Card so use external power, and adjust the `USE_SIMPLE_LITTLE_ENDIAN` define in `src/sdfat.h` to 0)
* SPI master
* analogWrite/PWM
* tone/noTone
* Wire/I2C Master and Slave (tested using DS3231 https://github.com/rodan/ds3231)
* Wire/I2C Master and Slave
* EEPROM
* USB Serial(ACM) w/automatic reboot-to-UF2 upload)
* Hardware UART
* Servo
* Servo, glitchless
* Overclocking and underclocking from the menus
* analogRead and Pico chip temperature
* Filesystems (LittleFS and SD/SDFS)
* I2S audio output
* printf (i.e. debug) output over USB serial
......@@ -105,13 +117,9 @@ The RP2040 PIO state machines (SMs) are used to generate jitter-free:
* Tones
* I2S Output
# Todo
Some major features I want to add are:
* Installable filesystem support (SD, LittleFS, etc.)
* Updated debug infrastructure
# Tutorials from Across the Web
Here are some links to coverage and additional tutorials for using `arduino-pico`
* The File:: class is taken from the ESP8266. See https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html
* Arduino Support for the Pi Pico available! And how fast is the Pico? - https://youtu.be/-XHh17cuH5E
* Pre-release Adafruit QT Py RP2040 - https://www.youtube.com/watch?v=sfC1msqXX0I
* Adafruit Feather RP2040 running LCD + TMP117 - https://www.youtube.com/watch?v=fKDeqZiIwHg
......
This diff is collapsed.
/*
FS.h - file system wrapper
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef FS_H
#define FS_H
#include <memory>
#include <Arduino.h>
#include <../include/time.h> // See issue #6714
class SDClass;
namespace fs {
class File;
class Dir;
class FS;
class FileImpl;
typedef std::shared_ptr<FileImpl> FileImplPtr;
class FSImpl;
typedef std::shared_ptr<FSImpl> FSImplPtr;
class DirImpl;
typedef std::shared_ptr<DirImpl> DirImplPtr;
template <typename Tfs>
bool mount(Tfs& fs, const char* mountPoint);
enum SeekMode {
SeekSet = 0,
SeekCur = 1,
SeekEnd = 2
};
class File : public Stream
{
public:
File(FileImplPtr p = FileImplPtr(), FS *baseFS = nullptr) : _p(p), _fakeDir(nullptr), _baseFS(baseFS) { }
// Print methods:
size_t write(uint8_t) override;
size_t write(const uint8_t *buf, size_t size) override;
int availableForWrite() override;
// Stream methods:
int available() override;
int read() override;
int peek() override;
void flush() override;
size_t readBytes(char *buffer, size_t length) {
return read((uint8_t*)buffer, length);
}
int read(uint8_t* buf, size_t size);
bool seek(uint32_t pos, SeekMode mode);
bool seek(uint32_t pos) {
return seek(pos, SeekSet);
}
size_t position() const;
size_t size() const;
virtual ssize_t streamRemaining() { return (ssize_t)size() - (ssize_t)position(); }
void close();
operator bool() const;
const char* name() const;
const char* fullName() const; // Includes path
bool truncate(uint32_t size);
bool isFile() const;
bool isDirectory() const;
// Arduino "class SD" methods for compatibility
//TODO use stream::send / check read(buf,size) result
template<typename T> size_t write(T &src){
uint8_t obuf[256];
size_t doneLen = 0;
size_t sentLen;
int i;
while (src.available() > sizeof(obuf)){
src.read(obuf, sizeof(obuf));
sentLen = write(obuf, sizeof(obuf));
doneLen = doneLen + sentLen;
if(sentLen != sizeof(obuf)){
return doneLen;
}
}
size_t leftLen = src.available();
src.read(obuf, leftLen);
sentLen = write(obuf, leftLen);
doneLen = doneLen + sentLen;
return doneLen;
}
using Print::write;
void rewindDirectory();
File openNextFile();
String readString();
time_t getLastWrite();
time_t getCreationTime();
void setTimeCallback(time_t (*cb)(void));
protected:
FileImplPtr _p;
time_t (*_timeCallback)(void) = nullptr;
// Arduino SD class emulation
std::shared_ptr<Dir> _fakeDir;
FS *_baseFS;
};
class Dir {
public:
Dir(DirImplPtr impl = DirImplPtr(), FS *baseFS = nullptr): _impl(impl), _baseFS(baseFS) { }
File openFile(const char* mode);
String fileName();
size_t fileSize();
time_t fileTime();
time_t fileCreationTime();
bool isFile() const;
bool isDirectory() const;
bool next();
bool rewind();
void setTimeCallback(time_t (*cb)(void));
protected:
DirImplPtr _impl;
FS *_baseFS;
time_t (*_timeCallback)(void) = nullptr;
};
// Backwards compatible, <4GB filesystem usage
struct FSInfo {
size_t totalBytes;
size_t usedBytes;
size_t blockSize;
size_t pageSize;
size_t maxOpenFiles;
size_t maxPathLength;
};
// Support > 4GB filesystems (SD, etc.)
struct FSInfo64 {
uint64_t totalBytes;
uint64_t usedBytes;
size_t blockSize;
size_t pageSize;
size_t maxOpenFiles;
size_t maxPathLength;
};
class FSConfig
{
public:
static constexpr uint32_t FSId = 0x00000000;
FSConfig(uint32_t type = FSId, bool autoFormat = true) : _type(type), _autoFormat(autoFormat) { }
FSConfig setAutoFormat(bool val = true) {
_autoFormat = val;
return *this;
}
uint32_t _type;
bool _autoFormat;
};
class SPIFFSConfig : public FSConfig
{
public:
static constexpr uint32_t FSId = 0x53504946;
SPIFFSConfig(bool autoFormat = true) : FSConfig(FSId, autoFormat) { }
// Inherit _type and _autoFormat
// nothing yet, enableTime TBD when SPIFFS has metadate
};
class FS
{
public:
FS(FSImplPtr impl) : _impl(impl) { _timeCallback = _defaultTimeCB; }
bool setConfig(const FSConfig &cfg);
bool begin();
void end();
bool format();
bool info(FSInfo& info);
bool info64(FSInfo64& info);
File open(const char* path, const char* mode);
File open(const String& path, const char* mode);
bool exists(const char* path);
bool exists(const String& path);
Dir openDir(const char* path);
Dir openDir(const String& path);
bool remove(const char* path);
bool remove(const String& path);
bool rename(const char* pathFrom, const char* pathTo);
bool rename(const String& pathFrom, const String& pathTo);
bool mkdir(const char* path);
bool mkdir(const String& path);
bool rmdir(const char* path);
bool rmdir(const String& path);
// Low-level FS routines, not needed by most applications
bool gc();
bool check();
time_t getCreationTime();
void setTimeCallback(time_t (*cb)(void));
friend class ::SDClass; // More of a frenemy, but SD needs internal implementation to get private FAT bits
protected:
FSImplPtr _impl;
FSImplPtr getImpl() { return _impl; }
time_t (*_timeCallback)(void) = nullptr;
static time_t _defaultTimeCB(void) { return time(NULL); }
};
} // namespace fs
extern "C"
{
void close_all_fs(void);
void littlefs_request_end(void);
void spiffs_request_end(void);
}
#ifndef FS_NO_GLOBALS
using fs::FS;
using fs::File;
using fs::Dir;
using fs::SeekMode;
using fs::SeekSet;
using fs::SeekCur;
using fs::SeekEnd;
using fs::FSInfo;
using fs::FSConfig;
using fs::SPIFFSConfig;
#endif //FS_NO_GLOBALS
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SPIFFS)
extern fs::FS SPIFFS __attribute__((deprecated("SPIFFS has been deprecated. Please consider moving to LittleFS or other filesystems.")));
#endif
#endif //FS_H
/*
FSImpl.h - base file system interface
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef FSIMPL_H
#define FSIMPL_H
#include <stddef.h>
#include <stdint.h>
#include <FS.h>
namespace fs {
class FileImpl {
public:
virtual ~FileImpl() { }
virtual size_t write(const uint8_t *buf, size_t size) = 0;
virtual int read(uint8_t* buf, size_t size) = 0;
virtual void flush() = 0;
virtual bool seek(uint32_t pos, SeekMode mode) = 0;
virtual size_t position() const = 0;
virtual size_t size() const = 0;
virtual int availableForWrite() { return 0; }
virtual bool truncate(uint32_t size) = 0;
virtual void close() = 0;
virtual const char* name() const = 0;
virtual const char* fullName() const = 0;
virtual bool isFile() const = 0;
virtual bool isDirectory() const = 0;
// Filesystems *may* support a timestamp per-file, so allow the user to override with
// their own callback for *this specific* file (as opposed to the FSImpl call of the
// same name. The default implementation simply returns time(null)
virtual void setTimeCallback(time_t (*cb)(void)) { _timeCallback = cb; }
// Return the last written time for a file. Undefined when called on a writable file
// as the FS is allowed to return either the time of the last write() operation or the
// time present in the filesystem metadata (often the last time the file was closed)
virtual time_t getLastWrite() { return 0; } // Default is to not support timestamps
// Same for creation time.
virtual time_t getCreationTime() { return 0; } // Default is to not support timestamps
protected:
time_t (*_timeCallback)(void) = nullptr;
};
enum OpenMode {
OM_DEFAULT = 0,
OM_CREATE = 1,
OM_APPEND = 2,
OM_TRUNCATE = 4
};
enum AccessMode {
AM_READ = 1,
AM_WRITE = 2,
AM_RW = AM_READ | AM_WRITE
};
class DirImpl {
public:
virtual ~DirImpl() { }
virtual FileImplPtr openFile(OpenMode openMode, AccessMode accessMode) = 0;
virtual const char* fileName() = 0;
virtual size_t fileSize() = 0;
// Return the last written time for a file. Undefined when called on a writable file
// as the FS is allowed to return either the time of the last write() operation or the
// time present in the filesystem metadata (often the last time the file was closed)
virtual time_t fileTime() { return 0; } // By default, FS doesn't report file times
virtual time_t fileCreationTime() { return 0; } // By default, FS doesn't report file times
virtual bool isFile() const = 0;
virtual bool isDirectory() const = 0;
virtual bool next() = 0;
virtual bool rewind() = 0;
// Filesystems *may* support a timestamp per-file, so allow the user to override with
// their own callback for *this specific* file (as opposed to the FSImpl call of the
// same name. The default implementation simply returns time(null)
virtual void setTimeCallback(time_t (*cb)(void)) { _timeCallback = cb; }
protected:
time_t (*_timeCallback)(void) = nullptr;
};
class FSImpl {
public:
virtual ~FSImpl () { }
virtual bool setConfig(const FSConfig &cfg) = 0;
virtual bool begin() = 0;
virtual void end() = 0;
virtual bool format() = 0;
virtual bool info(FSInfo& info) = 0;
virtual bool info64(FSInfo64& info) = 0;
virtual FileImplPtr open(const char* path, OpenMode openMode, AccessMode accessMode) = 0;
virtual bool exists(const char* path) = 0;
virtual DirImplPtr openDir(const char* path) = 0;
virtual bool rename(const char* pathFrom, const char* pathTo) = 0;
virtual bool remove(const char* path) = 0;
virtual bool mkdir(const char* path) = 0;
virtual bool rmdir(const char* path) = 0;
virtual bool gc() { return true; } // May not be implemented in all file systems.
virtual bool check() { return true; } // May not be implemented in all file systems.
virtual time_t getCreationTime() { return 0; } // May not be implemented in all file systems.
// Filesystems *may* support a timestamp per-file, so allow the user to override with
// their own callback for all files on this FS. The default implementation simply
// returns the present time as reported by time(null)
virtual void setTimeCallback(time_t (*cb)(void)) { _timeCallback = cb; }
protected:
time_t (*_timeCallback)(void) = nullptr;
};
} // namespace fs
#endif //FSIMPL_H
// Released to the public domain
//
// This sketch will read an uploaded file and increment a counter file
// each time the sketch is booted.
// Be sure to install the Pico LittleFS Data Upload extension for the
// Arduino IDE from:
// https://github.com/earlephilhower/arduino-pico-littlefs-plugin/
// The latest release is available from:
// https://github.com/earlephilhower/arduino-pico-littlefs-plugin/releases
// Before running:
// 1) Select Tools->Flash Size->(some size with a FS/filesystem)
// 2) Use the Tools->Pico Sketch Data Upload tool to transfer the contents of
// the sketch data directory to the Pico
#include <LittleFS.h>
void setup() {
Serial.begin(115200);
delay(5000);
LittleFS.begin();
char buff[32];
int cnt = 1;
File f = LittleFS.open("counts.txt", "r");
if (f) {
bzero(buff, 32);
if (f.read((uint8_t *)buff, 31)) {
sscanf(buff, "%d", &cnt);
Serial.printf("I have been run %d times\n", cnt);
}
f.close();
}
cnt++;
sprintf(buff, "%d\n", cnt);
f = LittleFS.open("counts.txt", "w");
if (f) {
f.write(buff, strlen(buff));
f.close();
}
Serial.println("---------------");
File i = LittleFS.open("file1.txt", "r");
if (i) {
while (i.available()) {
Serial.write(i.read());
}
Serial.println("---------------");
i.close();
}
}
void loop() {
}
Hello!
Welcome to the Raspberry Pi Pico using arduino-pico!
// Simple speed test for filesystem objects
// Released to the public domain by Earle F. Philhower, III
#include <FS.h>
#include <LittleFS.h>
// Choose the filesystem to test
// WARNING: The filesystem will be formatted at the start of the test!
#define TESTFS LittleFS
//#define TESTFS SDFS
// How large of a file to test
#define TESTSIZEKB 256
void DoTest(FS *fs) {
if (!fs->format()) {
Serial.printf("Unable to format(), aborting\n");
return;
}
if (!fs->begin()) {
Serial.printf("Unable to begin(), aborting\n");
return;
}
uint8_t data[256];
for (int i = 0; i < 256; i++) {
data[i] = (uint8_t) i;
}
Serial.printf("Creating %dKB file, may take a while...\n", TESTSIZEKB);
long start = millis();
File f = fs->open("/testwrite.bin", "w");
if (!f) {
Serial.printf("Unable to open file for writing, aborting\n");
return;
}
for (int i = 0; i < TESTSIZEKB; i++) {
for (int j = 0; j < 4; j++) {
f.write(data, 256);
}
}
f.close();
long stop = millis();
Serial.printf("==> Time to write %dKB in 256b chunks = %ld milliseconds\n", TESTSIZEKB, stop - start);
f = fs->open("/testwrite.bin", "r");
Serial.printf("==> Created file size = %d\n", f.size());
f.close();
Serial.printf("Reading %dKB file sequentially in 256b chunks\n", TESTSIZEKB);
start = millis();
f = fs->open("/testwrite.bin", "r");
for (int i = 0; i < TESTSIZEKB; i++) {
for (int j = 0; j < 4; j++) {
f.read(data, 256);
}
}
f.close();
stop = millis();
Serial.printf("==> Time to read %dKB sequentially in 256b chunks = %ld milliseconds = %ld bytes/s\n", TESTSIZEKB, stop - start, TESTSIZEKB * 1024 / (stop - start) * 1000);
Serial.printf("Reading %dKB file MISALIGNED in flash and RAM sequentially in 256b chunks\n", TESTSIZEKB);
start = millis();
f = fs->open("/testwrite.bin", "r");
f.read();
for (int i = 0; i < TESTSIZEKB; i++) {
for (int j = 0; j < 4; j++) {
f.read(data + 1, 256);
}
}
f.close();
stop = millis();
Serial.printf("==> Time to read %dKB sequentially MISALIGNED in flash and RAM in 256b chunks = %ld milliseconds = %ld bytes/s\n", TESTSIZEKB, stop - start, TESTSIZEKB * 1024 / (stop - start) * 1000);
Serial.printf("Reading %dKB file in reverse by 256b chunks\n", TESTSIZEKB);
start = millis();
f = fs->open("/testwrite.bin", "r");
for (int i = 0; i < TESTSIZEKB; i++) {
for (int j = 0; j < 4; j++) {
if (!f.seek(256 + 256 * j * i, SeekEnd)) {
Serial.printf("Unable to seek to %d, aborting\n", -256 - 256 * j * i);
return;
}
if (256 != f.read(data, 256)) {
Serial.printf("Unable to read 256 bytes, aborting\n");
return;
}
}
}
f.close();
stop = millis();
Serial.printf("==> Time to read %dKB in reverse in 256b chunks = %ld milliseconds = %ld bytes/s\n", TESTSIZEKB, stop - start, TESTSIZEKB * 1024 / (stop - start) * 1000);
Serial.printf("Writing 64K file in 1-byte chunks\n");
start = millis();
f = fs->open("/test1b.bin", "w");
for (int i = 0; i < 65536; i++) {
f.write((uint8_t*)&i, 1);
}
f.close();
stop = millis();
Serial.printf("==> Time to write 64KB in 1b chunks = %ld milliseconds = %ld bytes/s\n", stop - start, 65536 / (stop - start) * 1000);
Serial.printf("Reading 64K file in 1-byte chunks\n");
start = millis();
f = fs->open("/test1b.bin", "r");
for (int i = 0; i < 65536; i++) {
char c;
f.read((uint8_t*)&c, 1);
}
f.close();
stop = millis();
Serial.printf("==> Time to read 64KB in 1b chunks = %ld milliseconds = %ld bytes/s\n", stop - start, 65536 / (stop - start) * 1000);
}
void setup() {
Serial.begin(115200);
delay(5000);
Serial.printf("Beginning test\n");
Serial.flush();
DoTest(&TESTFS);
}
void loop() {
delay(10000);
}
Subproject commit 1863dc7883d82bd6ca79faa164b65341064d1c16
name=LittleFS
version=0.1.0
author=Earle F. Philhower, III
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Port of LittleFS to RP2040 Arduino
paragraph=Filesystem in the onboard flash, supporting power fail safety and high performance
category=Data Storage
url=https://github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
/*
LittleFS.cpp - Wrapper for LittleFS for RP2040
Copyright (c) 2021 Earle F. Philhower, III. All rights reserved.
Based extensively off of the ESP8266 SPIFFS code, which is
Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include <stdlib.h>
#include <algorithm>
#include "LittleFS.h"
#include <hardware/flash.h>
#include <hardware/sync.h>
extern uint8_t _FS_start;
extern uint8_t _FS_end;
namespace littlefs_impl {
FileImplPtr LittleFSImpl::open(const char* path, OpenMode openMode, AccessMode accessMode) {
if (!_mounted) {
DEBUGV("LittleFSImpl::open() called on unmounted FS\n");
return FileImplPtr();
}
if (!path || !path[0]) {
DEBUGV("LittleFSImpl::open() called with invalid filename\n");
return FileImplPtr();
}
if (!LittleFSImpl::pathValid(path)) {
DEBUGV("LittleFSImpl::open() called with too long filename\n");
return FileImplPtr();
}
int flags = _getFlags(openMode, accessMode);
auto fd = std::make_shared<lfs_file_t>();
if ((openMode & OM_CREATE) && strchr(path, '/')) {
// For file creation, silently make subdirs as needed. If any fail,
// it will be caught by the real file open later on
char *pathStr = strdup(path);
if (pathStr) {
// Make dirs up to the final fnamepart
char *ptr = strchr(pathStr, '/');
while (ptr) {
*ptr = 0;
lfs_mkdir(&_lfs, pathStr);
*ptr = '/';
ptr = strchr(ptr+1, '/');
}
}
free(pathStr);
}
time_t creation = 0;
if (_timeCallback && (openMode & OM_CREATE)) {
// O_CREATE means we *may* make the file, but not if it already exists.
// See if it exists, and only if not update the creation time
int rc = lfs_file_open(&_lfs, fd.get(), path, LFS_O_RDONLY);
if (rc == 0) {
lfs_file_close(&_lfs, fd.get()); // It exists, don't update create time
} else {
creation = _timeCallback(); // File didn't exist or otherwise, so we're going to create this time
}
}
int rc = lfs_file_open(&_lfs, fd.get(), path, flags);
if (rc == LFS_ERR_ISDIR) {
// To support the SD.openNextFile, a null FD indicates to the LittleFSFile this is just
// a directory whose name we are carrying around but which cannot be read or written
return std::make_shared<LittleFSFileImpl>(this, path, nullptr, flags, creation);
} else if (rc == 0) {
lfs_file_sync(&_lfs, fd.get());
return std::make_shared<LittleFSFileImpl>(this, path, fd, flags, creation);
} else {
DEBUGV("LittleFSDirImpl::openFile: rc=%d fd=%p path=`%s` openMode=%d accessMode=%d err=%d\n",
rc, fd.get(), path, openMode, accessMode, rc);
return FileImplPtr();
}
}
DirImplPtr LittleFSImpl::openDir(const char *path) {
if (!_mounted || !path) {
return DirImplPtr();
}
char *pathStr = strdup(path); // Allow edits on our scratch copy
// Get rid of any trailing slashes
while (strlen(pathStr) && (pathStr[strlen(pathStr)-1]=='/')) {
pathStr[strlen(pathStr)-1] = 0;
}
// At this point we have a name of "blah/blah/blah" or "blah" or ""
// If that references a directory, just open it and we're done.
lfs_info info;
auto dir = std::make_shared<lfs_dir_t>();
int rc;
const char *filter = "";
if (!pathStr[0]) {
// openDir("") === openDir("/")
rc = lfs_dir_open(&_lfs, dir.get(), "/");
filter = "";
} else if (lfs_stat(&_lfs, pathStr, &info) >= 0) {
if (info.type == LFS_TYPE_DIR) {
// Easy peasy, path specifies an existing dir!
rc = lfs_dir_open(&_lfs, dir.get(), pathStr);
filter = "";
} else {
// This is a file, so open the containing dir
char *ptr = strrchr(pathStr, '/');
if (!ptr) {
// No slashes, open the root dir
rc = lfs_dir_open(&_lfs, dir.get(), "/");
filter = pathStr;
} else {
// We've got slashes, open the dir one up
*ptr = 0; // Remove slash, truncate string
rc = lfs_dir_open(&_lfs, dir.get(), pathStr);
filter = ptr + 1;
}
}
} else {
// Name doesn't exist, so use the parent dir of whatever was sent in
// This is a file, so open the containing dir
char *ptr = strrchr(pathStr, '/');
if (!ptr) {
// No slashes, open the root dir
rc = lfs_dir_open(&_lfs, dir.get(), "/");
filter = pathStr;
} else {
// We've got slashes, open the dir one up
*ptr = 0; // Remove slash, truncate string
rc = lfs_dir_open(&_lfs, dir.get(), pathStr);
filter = ptr + 1;
}
}
if (rc < 0) {
DEBUGV("LittleFSImpl::openDir: path=`%s` err=%d\n", path, rc);
free(pathStr);
return DirImplPtr();
}
// Skip the . and .. entries
lfs_info dirent;
lfs_dir_read(&_lfs, dir.get(), &dirent);
lfs_dir_read(&_lfs, dir.get(), &dirent);
auto ret = std::make_shared<LittleFSDirImpl>(filter, this, dir, pathStr);
free(pathStr);
return ret;
}
int LittleFSImpl::lfs_flash_read(const struct lfs_config *c,
lfs_block_t block, lfs_off_t off, void *dst, lfs_size_t size) {
LittleFSImpl *me = reinterpret_cast<LittleFSImpl*>(c->context);
// Serial.printf(" READ: %p, %d\n", me->_start + (block * me->_blockSize) + off, size);
memcpy(dst, me->_start + (block * me->_blockSize) + off, size);
return 0;
}
int LittleFSImpl::lfs_flash_prog(const struct lfs_config *c,
lfs_block_t block, lfs_off_t off, const void *buffer, lfs_size_t size) {
LittleFSImpl *me = reinterpret_cast<LittleFSImpl*>(c->context);
uint8_t *addr = me->_start + (block * me->_blockSize) + off;
uint32_t save = save_and_disable_interrupts();
// Serial.printf("WRITE: %p, $d\n", (intptr_t)addr - (intptr_t)XIP_BASE, size);
flash_range_program((intptr_t)addr - (intptr_t)XIP_BASE, (const uint8_t *)buffer, size);
restore_interrupts(save);
return 0;
}
int LittleFSImpl::lfs_flash_erase(const struct lfs_config *c, lfs_block_t block) {
LittleFSImpl *me = reinterpret_cast<LittleFSImpl*>(c->context);
uint8_t *addr = me->_start + (block * me->_blockSize);
// Serial.printf("ERASE: %p, %d\n", (intptr_t)addr - (intptr_t)XIP_BASE, me->_blockSize);
uint32_t save = save_and_disable_interrupts();
flash_range_erase((intptr_t)addr - (intptr_t)XIP_BASE, me->_blockSize);
restore_interrupts(save);
return 0;
}
int LittleFSImpl::lfs_flash_sync(const struct lfs_config *c) {
/* NOOP */
(void) c;
return 0;
}
}; // namespace
FS LittleFS = FS(FSImplPtr(new littlefs_impl::LittleFSImpl(&_FS_start, &_FS_end - &_FS_start, 256, 4096, 16)));
This diff is collapsed.
// Can't place library in ths src/ directory, Arduino will attempt to build the tests/etc.
// Just have a stub here that redirects to the actual source file
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#define LFS_NAME_MAX 32
#define LFS_NO_DEBUG
#define LFS_NO_WARN
#define LFS_NO_ERROR
#include "../lib/littlefs/lfs.c"
#define LFS_NAME_MAX 32
#define LFS_NO_DEBUG
#define LFS_NO_WARN
#define LFS_NO_ERROR
#include "../lib/littlefs/lfs_util.c"
# Arduino "class SD" shim wrapper
This is a simple wrapper class to replace the ancient Arduino SD.h
access method for SD cards. It calls the underlying SDFS and the latest
SdFat lib to do all the work, and is now compatible with the rest of the
ESP8266 filesystem things.
-Earle F. Philhower, III
<earlephilhower@yahoo.com>
/*
SD card datalogger
This example shows how to log data from three analog sensors
to an SD card using the SD library.
The circuit:
analog sensors on analog ins 0, 1, and 2
SD card attached to SPI bus as follows (Raspberry Pi Pico):
** MISO - pin 0
** MOSI - pin 3
** CS - pin 1
** SCK - pin 2
created 24 Nov 2010
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}
void loop() {
// make a string for assembling the data to log:
String dataString = "";
// read three sensors and append to the string:
for (int analogPin = 0; analogPin < 3; analogPin++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2) {
dataString += ",";
}
}
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}
/*
SD card file dump
This example shows how to read a file from the SD card using the
SD library and send it over the serial port.
The circuit:
SD card attached to SPI bus as follows:
** MISO - pin 0
** MOSI - pin 3
** CS - pin 1
** SCK - pin 2
created 22 December 2010
by Limor Fried
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt");
// if the file is available, write to it:
if (dataFile) {
while (dataFile.available()) {
Serial.write(dataFile.read());
}
dataFile.close();
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}
void loop() {
}
/*
SD card basic file example
This example shows how to create and destroy an SD card file
The circuit:
SD card attached to SPI bus as follows:
** MISO - pin 0
** MOSI - pin 3
** CS - pin 1
** SCK - pin 2
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
} else {
Serial.println("example.txt doesn't exist.");
}
// open a new file and immediately close it:
Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();
// Check to see if the file exists:
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
} else {
Serial.println("example.txt doesn't exist.");
}
// delete the file:
Serial.println("Removing example.txt...");
SD.remove("example.txt");
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
} else {
Serial.println("example.txt doesn't exist.");
}
}
void loop() {
// nothing happens after setup finishes.
}
/*
SD card read/write
This example shows how to read and write data to and from an SD card file
The circuit:
SD card attached to SPI bus as follows:
** MISO - pin 0
** MOSI - pin 3
** CS - pin 1
** SCK - pin 2
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}
void loop() {
// nothing happens after setup
}
/*
Listfiles
This example shows how print out the files in a
directory on a SD card
The circuit:
SD card attached to SPI bus as follows:
** MISO - pin 0
** MOSI - pin 3
** CS - pin 1
** SCK - pin 2
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
modified 2 Feb 2014
by Scott Fitzgerald
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
File root;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
Serial.print("Initializing SD card...");
if (!SD.begin(SS)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
root = SD.open("/");
printDirectory(root, 0);
Serial.println("done!");
}
void loop() {
// nothing happens after setup finishes.
}
void printDirectory(File dir, int numTabs) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numTabs + 1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.print(entry.size(), DEC);
time_t cr = entry.getCreationTime();
time_t lw = entry.getLastWrite();
struct tm * tmstruct = localtime(&cr);
Serial.printf("\tCREATION: %d-%02d-%02d %02d:%02d:%02d", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec);
tmstruct = localtime(&lw);
Serial.printf("\tLAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec);
}
entry.close();
}
}
#######################################
# Syntax Coloring Map SD
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
SD KEYWORD1 SD
File KEYWORD1 SD
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
exists KEYWORD2
mkdir KEYWORD2
remove KEYWORD2
rmdir KEYWORD2
open KEYWORD2
close KEYWORD2
seek KEYWORD2
position KEYWORD2
size KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
FILE_READ LITERAL1
FILE_WRITE LITERAL1
name=SD(rp2040)
version=2.0.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Enables reading and writing on SD cards using SDFS
paragraph=Once an SD memory card is connected to the SPI interfare of the Arduino board you are enabled to create files and read/write on them. You can also move through directories on the SD card. This is a complete rewrite of the original Arduino SD.h class.
category=Data Storage
url=http://www.github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
#include "SD.h"
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SD)
SDClass SD;
#endif
void (*__SD__userDateTimeCB)(uint16_t*, uint16_t*) = nullptr;
/*
SD.h - A thin shim for Arduino ESP8266 Filesystems
Copyright (c) 2019 Earle F. Philhower, III. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __SD_H__
#define __SD_H__
#include <Arduino.h>
#include <FS.h>
#include <SDFS.h>
#undef FILE_READ
#define FILE_READ O_READ
#undef FILE_WRITE
#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)
class SDClass {
public:
boolean begin(uint8_t csPin, uint32_t cfg = SPI_HALF_SPEED) {
SDFS.setConfig(SDFSConfig(csPin, cfg));
return (boolean)SDFS.begin();
}
void end(bool endSPI = true) {
SDFS.end();
if (endSPI) {
SPI.end();
}
}
File open(const char *filename, int mode = FILE_READ) {
return SDFS.open(filename, getMode(mode));
}
File open(const char *filename, const char *mode) {
return SDFS.open(filename, mode);
}
File open(const String &filename, int mode = FILE_READ) {
return open(filename.c_str(), mode);
}
File open(const String &filename, const char *mode) {
return open(filename.c_str(), mode);
}
boolean exists(const char *filepath) {
return (boolean)SDFS.exists(filepath);
}
boolean exists(const String &filepath) {
return (boolean)SDFS.exists(filepath.c_str());
}
boolean rename(const char* filepathfrom, const char* filepathto) {
return (boolean)SDFS.rename(filepathfrom, filepathto);
}
boolean rename(const String &filepathfrom, const String &filepathto) {
return (boolean)rename(filepathfrom.c_str(), filepathto.c_str());
}
boolean mkdir(const char *filepath) {
return (boolean)SDFS.mkdir(filepath);
}
boolean mkdir(const String &filepath) {
return (boolean)SDFS.mkdir(filepath.c_str());
}
boolean remove(const char *filepath) {
return (boolean)SDFS.remove(filepath);
}
boolean remove(const String &filepath) {
return remove(filepath.c_str());
}
boolean rmdir(const char *filepath) {
return (boolean)SDFS.rmdir(filepath);
}
boolean rmdir(const String &filepath) {
return rmdir(filepath.c_str());
}
uint8_t type() {
sdfs::SDFSImpl* sd = static_cast<sdfs::SDFSImpl*>(SDFS.getImpl().get());
return sd->type();
}
uint8_t fatType() {
sdfs::SDFSImpl* sd = static_cast<sdfs::SDFSImpl*>(SDFS.getImpl().get());
return sd->fatType();
}
size_t blocksPerCluster() {
sdfs::SDFSImpl* sd = static_cast<sdfs::SDFSImpl*>(SDFS.getImpl().get());
return sd->blocksPerCluster();
}
size_t totalClusters() {
sdfs::SDFSImpl* sd = static_cast<sdfs::SDFSImpl*>(SDFS.getImpl().get());
return sd->totalClusters();
}
size_t blockSize() {
return 512;
}
size_t totalBlocks() {
return (totalClusters() / blocksPerCluster());
}
size_t clusterSize() {
return blocksPerCluster() * blockSize();
}
size_t size() {
uint64_t sz = size64();
#ifdef DEBUG_ESP_PORT
if (sz > (uint64_t)SIZE_MAX) {
DEBUG_ESP_PORT.printf_P(PSTR("WARNING: SD card size overflow (%lld>= 4GB). Please update source to use size64().\n"), sz);
}
#endif
return (size_t)sz;
}
uint64_t size64() {
return ((uint64_t)clusterSize() * (uint64_t)totalClusters());
}
void setTimeCallback(time_t (*cb)(void)) {
SDFS.setTimeCallback(cb);
}
// Wrapper to allow obsolete datetimecallback use, silently convert to time_t in wrappertimecb
void dateTimeCallback(void (*cb)(uint16_t*, uint16_t*)) {
extern void (*__SD__userDateTimeCB)(uint16_t*, uint16_t*);
__SD__userDateTimeCB = cb;
SDFS.setTimeCallback(wrapperTimeCB);
}
private:
const char *getMode(uint8_t mode) {
bool read = (mode & O_READ) ? true : false;
bool write = (mode & O_WRITE) ? true : false;
bool append = (mode & O_APPEND) ? true : false;
if ( read & !write ) { return "r"; }
else if ( !read & write & !append ) { return "w+"; }
else if ( !read & write & append ) { return "a"; }
else if ( read & write & !append ) { return "w+"; } // may be a bug in FS::mode interpretation, "r+" seems proper
else if ( read & write & append ) { return "a+"; }
else { return "r"; }
}
static time_t wrapperTimeCB(void) {
extern void (*__SD__userDateTimeCB)(uint16_t*, uint16_t*);
if (__SD__userDateTimeCB) {
uint16_t d, t;
__SD__userDateTimeCB(&d, &t);
return sdfs::SDFSImpl::FatToTimeT(d, t);
}
return time(nullptr);
}
};
// Expose FatStructs.h helpers for MSDOS date/time for use with dateTimeCallback
static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) {
return (year - 1980) << 9 | month << 5 | day;
}
static inline uint16_t FAT_YEAR(uint16_t fatDate) {
return 1980 + (fatDate >> 9);
}
static inline uint8_t FAT_MONTH(uint16_t fatDate) {
return (fatDate >> 5) & 0XF;
}
static inline uint8_t FAT_DAY(uint16_t fatDate) {
return fatDate & 0X1F;
}
static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) {
return hour << 11 | minute << 5 | second >> 1;
}
static inline uint8_t FAT_HOUR(uint16_t fatTime) {
return fatTime >> 11;
}
static inline uint8_t FAT_MINUTE(uint16_t fatTime) {
return (fatTime >> 5) & 0X3F;
}
static inline uint8_t FAT_SECOND(uint16_t fatTime) {
return 2*(fatTime & 0X1F);
}
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SD)
extern SDClass SD;
#endif
#endif
name=SDFS
version=0.1.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=FS filesystem for use on SD cards using Bill Greiman's amazing FAT16/FAT32 Arduino library.
paragraph=FS filesystem for use on SD cards using Bill Greiman's amazing FAT16/FAT32 Arduino library.
category=Data Storage
url=https://github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
/*
SDFS.cpp - file system wrapper for SdFat
Copyright (c) 2019 Earle F. Philhower, III. All rights reserved.
Based on spiffs_api.cpp which is:
| Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.
This code was influenced by NodeMCU and Sming libraries, and first version of
Arduino wrapper written by Hristo Gochkov.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "SDFS.h"
#include <FS.h>
using namespace fs;
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SDFS)
FS SDFS = FS(FSImplPtr(new sdfs::SDFSImpl()));
#endif
namespace sdfs {
// Required to be global because SDFAT doesn't allow a this pointer in it's own time call
time_t (*__sdfs_timeCallback)(void) = nullptr;
FileImplPtr SDFSImpl::open(const char* path, OpenMode openMode, AccessMode accessMode)
{
if (!_mounted) {
DEBUGV("SDFSImpl::open() called on unmounted FS\n");
return FileImplPtr();
}
if (!path || !path[0]) {
DEBUGV("SDFSImpl::open() called with invalid filename\n");
return FileImplPtr();
}
int flags = _getFlags(openMode, accessMode);
if ((openMode && OM_CREATE) && strchr(path, '/')) {
// For file creation, silently make subdirs as needed. If any fail,
// it will be caught by the real file open later on
char *pathStr = strdup(path);
if (pathStr) {
// Make dirs up to the final fnamepart
char *ptr = strrchr(pathStr, '/');
if (ptr && ptr != pathStr) { // Don't try to make root dir!
*ptr = 0;
_fs.mkdir(pathStr, true);
}
}
free(pathStr);
}
sdfat::File32 fd = _fs.open(path, flags);
if (!fd) {
DEBUGV("SDFSImpl::openFile: fd=%p path=`%s` openMode=%d accessMode=%d",
&fd, path, openMode, accessMode);
return FileImplPtr();
}
auto sharedFd = std::make_shared<sdfat::File32>(fd);
return std::make_shared<SDFSFileImpl>(this, sharedFd, path);
}
DirImplPtr SDFSImpl::openDir(const char* path)
{
if (!_mounted) {
return DirImplPtr();
}
char *pathStr = strdup(path); // Allow edits on our scratch copy
if (!pathStr) {
// OOM
return DirImplPtr();
}
// Get rid of any trailing slashes
while (strlen(pathStr) && (pathStr[strlen(pathStr)-1]=='/')) {
pathStr[strlen(pathStr)-1] = 0;
}
// At this point we have a name of "/blah/blah/blah" or "blah" or ""
// If that references a directory, just open it and we're done.
sdfat::File32 dirFile;
const char *filter = "";
if (!pathStr[0]) {
// openDir("") === openDir("/")
dirFile = _fs.open("/", O_RDONLY);
filter = "";
} else if (_fs.exists(pathStr)) {
dirFile = _fs.open(pathStr, O_RDONLY);
if (dirFile.isDir()) {
// Easy peasy, path specifies an existing dir!
filter = "";
} else {
dirFile.close();
// This is a file, so open the containing dir
char *ptr = strrchr(pathStr, '/');
if (!ptr) {
// No slashes, open the root dir
dirFile = _fs.open("/", O_RDONLY);
filter = pathStr;
} else {
// We've got slashes, open the dir one up
*ptr = 0; // Remove slash, truncare string
dirFile = _fs.open(pathStr, O_RDONLY);
filter = ptr + 1;
}
}
} else {
// Name doesn't exist, so use the parent dir of whatever was sent in
// This is a file, so open the containing dir
char *ptr = strrchr(pathStr, '/');
if (!ptr) {
// No slashes, open the root dir
dirFile = _fs.open("/", O_RDONLY);
filter = pathStr;
} else {
// We've got slashes, open the dir one up
*ptr = 0; // Remove slash, truncare string
dirFile = _fs.open(pathStr, O_RDONLY);
filter = ptr + 1;
}
}
if (!dirFile) {
DEBUGV("SDFSImpl::openDir: path=`%s`\n", path);
return DirImplPtr();
}
auto sharedDir = std::make_shared<sdfat::File32>(dirFile);
auto ret = std::make_shared<SDFSDirImpl>(filter, this, sharedDir, pathStr);
free(pathStr);
return ret;
}
bool SDFSImpl::format() {
if (_mounted) {
return false;
}
sdfat::SdCardFactory cardFactory;
sdfat::SdCard* card = cardFactory.newCard(sdfat::SdSpiConfig(_cfg._csPin, DEDICATED_SPI, _cfg._spiSettings));
if (!card || card->errorCode()) {
return false;
}
sdfat::FatFormatter fatFormatter;
uint8_t *sectorBuffer = new uint8_t[512];
bool ret = fatFormatter.format(card, sectorBuffer, nullptr);
delete[] sectorBuffer;
return ret;
}
}; // namespace sdfs
This diff is collapsed.
Subproject commit 3f50e5547d20854d4dfdc715446758ccc734bec2
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment