#include "settings.h" #include #define TAG "Settings" Settings::Settings(const char* ns, bool read_write) : read_write_(read_write) { nvs_open_mode_t mode = read_write ? NVS_READWRITE : NVS_READONLY; esp_err_t err = nvs_open(ns, mode, &handle_); if (err != ESP_OK) { // ESP_ERR_NVS_NOT_FOUND in read-only mode just means the namespace has // never been written — that's a valid "no data yet" case (e.g. the // "friends" namespace on first boot), not an error worth warning about. if (!(err == ESP_ERR_NVS_NOT_FOUND && !read_write)) { ESP_LOGW(TAG, "Failed to open NVS namespace '%s': %s", ns, esp_err_to_name(err)); } handle_ = 0; } } Settings::~Settings() { if (handle_) { if (dirty_) { nvs_commit(handle_); } nvs_close(handle_); } } std::string Settings::GetString(const char* key, const std::string& default_val) const { if (!handle_) return default_val; size_t required_size = 0; if (nvs_get_str(handle_, key, nullptr, &required_size) != ESP_OK) { return default_val; } std::string value(required_size - 1, '\0'); if (nvs_get_str(handle_, key, &value[0], &required_size) != ESP_OK) { return default_val; } return value; } void Settings::SetString(const char* key, const std::string& value) { if (!handle_ || !read_write_) return; nvs_set_str(handle_, key, value.c_str()); dirty_ = true; } int Settings::GetInt(const char* key, int default_val) const { if (!handle_) return default_val; int32_t value = default_val; nvs_get_i32(handle_, key, &value); return value; } void Settings::SetInt(const char* key, int value) { if (!handle_ || !read_write_) return; nvs_set_i32(handle_, key, value); dirty_ = true; } void Settings::EraseKey(const char* key) { if (!handle_ || !read_write_) return; nvs_erase_key(handle_, key); dirty_ = true; } void Settings::EraseAll() { if (!handle_ || !read_write_) return; nvs_erase_all(handle_); dirty_ = true; }