35#include <Preferences.h>
76 NVSFile(
const String& path,
const String& mode, Preferences& prefs)
77 : mKey(path), mMode(mode), mPrefs(prefs), mValid(true) {
81 }
else if (mMode ==
"w") {
94 operator bool()
const {
return mValid; }
111 size_t write(
const uint8_t* data,
size_t size) {
112 if (!mValid || mMode !=
"w") {
116 mBuffer =
Bytes(data, size);
133 if (!mValid || mMode !=
"r") {
159 if (mBuffer.size() == 0) {
160 mPrefs.remove(mKey.c_str());
162 mPrefs.putBytes(mKey.c_str(), mBuffer.raw(), mBuffer.size());
184 String normalized = path;
185 if (normalized.startsWith(
"/")) {
186 normalized = normalized.substring(1);
188 if (normalized.length() > 15) {
189 normalized = normalized.substring(0, 15);
190 UNIOT_LOG_WARN(
"NVS key truncated to 15 chars: %s", normalized.c_str());
213 if (!mPrefs.isKey(mKey.c_str())) {
218 size_t dataSize = mPrefs.getBytesLength(mKey.c_str());
224 mBuffer = Bytes(
nullptr, dataSize);
225 if (mBuffer.size() != dataSize) {
226 UNIOT_LOG_ERROR(
"NVS read failed, no memory for %u bytes: %s", dataSize, mKey.c_str());
234 auto read = mBuffer.fill([
this](uint8_t* buf,
size_t size) {
235 return mPrefs.getBytes(mKey.c_str(), buf, size);
292 bool begin(
bool formatOnFail =
false) {
293 if (mInitialized)
return true;
295 mInitialized = mPrefs.begin(
"uniot_files",
false);
312 mInitialized =
false;
335 return NVSFile(
"",
"", mPrefs);
337 return NVSFile(path, mode, mPrefs);
359 return mPrefs.remove(key.c_str());
379extern NVSFileSystem
NVSFS;
384#error "NVSFS is only supported on ESP32. Please define UNIOT_USE_NVSFS=1 for ESP32 projects."
size_t write(const uint8_t *data, size_t size)
Write data to the file buffer.
Definition NVSFS.h:111
static String normalizePath(const String &path)
Normalize a file path to a valid NVS key.
Definition NVSFS.h:183
Bytes getBytes()
Get the entire file content as Bytes object.
Definition NVSFS.h:132
void close()
Close the file and commit any pending write operations.
Definition NVSFS.h:153
NVSFile(const String &path, const String &mode, Preferences &prefs)
Constructs an NVSFile object for a specific path and mode.
Definition NVSFS.h:76
NVSFileSystem()
Default constructor.
Definition NVSFS.h:277
bool remove(const String &path)
Remove a file from NVS storage.
Definition NVSFS.h:353
void end()
Deinitialize the NVS file system.
Definition NVSFS.h:309
bool begin(bool formatOnFail=false)
Initialize the NVS file system.
Definition NVSFS.h:292
NVSFile open(const String &path, const String &mode)
Open a file for reading or writing.
Definition NVSFS.h:332
#define UNIOT_LOG_WARN(...)
Log an WARN level message Used for warnings about potentially problematic situations....
Definition Logger.h:294
#define UNIOT_LOG_ERROR(...)
Log an ERROR level message Used for critical errors that may prevent normal operation....
Definition Logger.h:273
Contains all classes and functions related to the Uniot Core.
NVSFileSystem NVSFS
Global NVS file system instance.
Definition NVSFS.cpp:5