35#include <Preferences.h>
77 NVSFile(
const String& path,
const String& mode, Preferences& prefs)
78 : mKey(path), mMode(mode), mPrefs(prefs), mValid(true) {
82 }
else if (mMode ==
"w") {
95 operator bool()
const {
return mValid; }
112 size_t write(
const uint8_t* data,
size_t size) {
113 if (!mValid || mMode !=
"w") {
117 mBuffer =
Bytes(data, size);
134 if (!mValid || mMode !=
"r") {
160 if (mBuffer.size() == 0) {
161 mPrefs.remove(mKey.c_str());
163 mPrefs.putBytes(mKey.c_str(), mBuffer.raw(), mBuffer.size());
185 String normalized = path;
186 if (normalized.startsWith(
"/")) {
187 normalized = normalized.substring(1);
189 if (normalized.length() > 15) {
190 normalized = normalized.substring(0, 15);
191 UNIOT_LOG_WARN(
"NVS key truncated to 15 chars: %s", normalized.c_str());
214 if (!mPrefs.isKey(mKey.c_str())) {
219 size_t dataSize = mPrefs.getBytesLength(mKey.c_str());
225 mBuffer = Bytes(
nullptr, dataSize);
226 mBuffer.fill([
this, dataSize](uint8_t* buf,
size_t size) {
227 return mPrefs.getBytes(mKey.c_str(), buf, dataSize);
283 bool begin(
bool formatOnFail =
false) {
284 if (mInitialized)
return true;
286 mInitialized = mPrefs.begin(
"uniot_files",
false);
303 mInitialized =
false;
326 return NVSFile(
"",
"", mPrefs);
328 return NVSFile(path, mode, mPrefs);
350 return mPrefs.remove(key.c_str());
370extern NVSFileSystem
NVSFS;
375#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:112
static String normalizePath(const String &path)
Normalize a file path to a valid NVS key.
Definition NVSFS.h:184
Bytes getBytes()
Get the entire file content as Bytes object.
Definition NVSFS.h:133
void close()
Close the file and commit any pending write operations.
Definition NVSFS.h:154
NVSFile(const String &path, const String &mode, Preferences &prefs)
Constructs an NVSFile object for a specific path and mode.
Definition NVSFS.h:77
NVSFileSystem()
Default constructor.
Definition NVSFS.h:268
bool remove(const String &path)
Remove a file from NVS storage.
Definition NVSFS.h:344
void end()
Deinitialize the NVS file system.
Definition NVSFS.h:300
bool begin(bool formatOnFail=false)
Initialize the NVS file system.
Definition NVSFS.h:283
NVSFile open(const String &path, const String &mode)
Open a file for reading or writing.
Definition NVSFS.h:323
#define UNIOT_LOG_WARN(...)
Log an WARN level message Used for warnings about potentially problematic situations....
Definition Logger.h:247
#define UNIOT_LOG_ERROR(...)
Log an ERROR level message Used for critical errors that may prevent normal operation....
Definition Logger.h:226
Contains all classes and functions related to the Uniot Core.
NVSFileSystem NVSFS
Global NVS file system instance.
Definition NVSFS.cpp:5