NVS APIs

NVS

The NVS component provides a simple class representing an NVS controller.

NVSHandle

The NVSHandle class manages individual NVS storage handles, allowing for scoped control over specific NVS namespaces. It simplifies operations like reading, writing, and committing key-value pairs within these namespaces.

Code examples for the NVS and NVSHandle API are provided in the nvs example folder.

API Reference

Header File

Classes

class Nvs : public espp::BaseComponent

Class to interface with the NVS.

This class is used to interface with the ESP NVS system. It is used to init and erase the partition, or get and set variables

NVS Example

    std::error_code ec;
    uint8_t counter = 0;
    espp::Nvs nvs;
    nvs.init(ec);
    ec.clear();
    // note that the namespace and key strings must be <= 15 characters
    nvs.get_or_set_var("system", "reset_counter", counter, counter, ec);
    ec.clear();
    fmt::print("Reset Counter = {}\n", counter);

    bool flag = false;
    nvs.get_or_set_var("other-namespace", "flag", flag, flag, ec);
    ec.clear();
    fmt::print("Got / Set Flag = {}\n", flag);
    // now toggle the flag
    flag = !flag;
    nvs.set_var("other-namespace", "flag", flag, ec);
    ec.clear();
    fmt::print("Toggled Flag = {}\n", flag);

    // test protection against really long namespace names (length > 15)
    std::string long_ns(16, 'a');
    nvs.get_or_set_var(long_ns, "flag", flag, flag, ec);
    if (ec) {
      fmt::print("Expected error: {}\n", ec.message());
    } else {
      fmt::print("Unexpected success\n");
    }
    ec.clear();

    // test getting a non-existent key
    nvs.get_var("system", "not-here", counter, ec);
    if (ec) {
      fmt::print("Expected error: {}\n", ec.message());
    } else {
      fmt::print("Unexpected success\n");
    }
    ec.clear();

    // test getting a string value
    std::string str;
    nvs.get_or_set_var("system", "string", str, std::string("default"), ec);
    if (ec) {
      fmt::print("Error: {}\n", ec.message());
    } else {
      fmt::print("String = '{}'\n", str);
    }
    ec.clear();

    // test setting a string value
    str = "hello";
    nvs.set_var("system", "string", str, ec);
    if (ec) {
      fmt::print("Error: {}\n", ec.message());
    } else {
      fmt::print("String set to '{}'\n", str);
    }
    ec.clear();

    // test getting the string value again
    nvs.get_var("system", "string", str, ec);
    if (ec) {
      fmt::print("Error: {}\n", ec.message());
    } else {
      fmt::print("String = '{}'\n", str);
    }
    ec.clear();

    // test erasing the string value
    nvs.erase("system", "string", ec);
    if (ec) {
      fmt::print("Error: {}\n", ec.message());
    } else {
      fmt::print("String erased\n");
    }
    ec.clear();

    // now test getting it again to ensure it was erased
    nvs.get_var("system", "string", str, ec);
    if (ec) {
      fmt::print("Sucess, got expected error when reading erased value: {}\n", ec.message());
    } else {
      fmt::print("Failure, got unexpected success when reading erased value\n");
    }
    ec.clear();

    counter++;

    if (counter > 10) {
      // test erasing the whole namespace
      nvs.erase("system", ec);
      if (ec) {
        fmt::print("Error: {}\n", ec.message());
      } else {
        fmt::print("Namespace erased\n");
      }
      ec.clear();

      // now erase the wole nvs partition
      nvs.erase(ec);
      nvs.init(ec);
      counter = 0;
      fmt::print("NVS erased, Reset Counter set to 0\n");
      ec.clear();
    }

    nvs.set_var("system", "reset_counter", counter, ec);
    fmt::print("Next Reset Counter will be = {}\n", counter);
    fmt::print("NVS example complete!\n");

Public Functions

inline explicit Nvs()

Construct a new NVS object.

inline void init(std::error_code &ec)

Initialize the NVS.

If the flash init fails because of no free pages or new version, it erases the NVS and re-initializes

Parameters

ec[out] Saves a std::error_code representing success or failure

inline void erase(std::error_code &ec)

Erase the NVS.

Parameters

ec[out] Saves a std::error_code representing success or failure

inline bool erase(std::string_view ns_name, std::error_code &ec)

Erase a namespace from the NVS.

Parameters
  • ns_name[in] Namespace of the variable to erase

  • ec[out] Saves a std::error_code representing success or failure

inline bool erase(std::string_view ns_name, std::string_view key, std::error_code &ec)

Erase a key from the NVS.

Parameters
  • ns_name[in] Namespace of the variable to erase

  • key[in] NVS Key of the variable to erase

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void set_var(std::string_view ns_name, std::string_view key, T value, std::error_code &ec)

Save a variable in the NVS and commit.

Parameters
  • ns_name[in] Namespace of the variable to save

  • key[in] NVS Key of the variable to save

  • value[in] Variable to save

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void get_var(std::string_view ns_name, std::string_view key, T &value, std::error_code &ec)

Reads a variable from the NVS.

Parameters
  • ns_name[in] Namespace of the variable to read

  • key[in] NVS Key of the variable to read

  • value[out] Variable to read

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void get_or_set_var(std::string_view ns_name, std::string_view key, T &value, T default_value, std::error_code &ec)

Reads a variable from the NVS.

Parameters
  • ns_name[in] Namespace of the variable to read

  • key[in] NVS Key of the variable to read

  • value[out] Variable to read

  • default_value[in] If the key isn’t found in the NVS, this value is saved to NVS

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void set_var(const char *ns_name, const char *key, T value, std::error_code &ec)

Save a variable in the NVS and commit.

Saves the key/variable pair, and commits the NVS.

Parameters
  • ns_name[in] Namespace of the variable to save

  • key[in] NVS Key of the variable to save

  • value[in] Variable to save

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void get_var(const char *ns_name, const char *key, T &value, std::error_code &ec)

Reads a variable from the NVS.

Read the key/variable pair

Parameters
  • ns_name[in] Namespace of the variable to read

  • key[in] NVS Key of the variable to read

  • value[out] Variable to read

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void get_or_set_var(const char *ns_name, const char *key, T &value, T default_value, std::error_code &ec)

Reads a variable from the NVS.

Read the key/variable pair, If the key isn’t found in the NVS, default_value is saved to NVS

Parameters
  • ns_name[in] Namespace of the variable to read

  • key[in] NVS Key of the variable to read

  • value[out] Variable to read

  • default_value[in] If the key isn’t found in the NVS, this value is saved to NVS

  • ec[out] Saves a std::error_code representing success or failure

inline const std::string &get_name() const

Get the name of the component

Note

This is the tag of the logger

Returns

A const reference to the name of the component

inline void set_log_tag(const std::string_view &tag)

Set the tag for the logger

Parameters

tag – The tag to use for the logger

inline espp::Logger::Verbosity get_log_level() const

Get the log level for the logger

Returns

The verbosity level of the logger

inline void set_log_level(espp::Logger::Verbosity level)

Set the log level for the logger

Parameters

level – The verbosity level to use for the logger

inline void set_log_verbosity(espp::Logger::Verbosity level)

Set the log verbosity for the logger

See also

set_log_level

Note

This is a convenience method that calls set_log_level

Parameters

level – The verbosity level to use for the logger

inline espp::Logger::Verbosity get_log_verbosity() const

Get the log verbosity for the logger

See also

get_log_level

Note

This is a convenience method that calls get_log_level

Returns

The verbosity level of the logger

inline void set_log_rate_limit(std::chrono::duration<float> rate_limit)

Set the rate limit for the logger

Note

Only calls to the logger that have _rate_limit suffix will be rate limited

Parameters

rate_limit – The rate limit to use for the logger

Header File

Classes

class NvsHandle : public espp::BaseComponent

Class to manage NVS handles.

This class provides an interface for managing specific ESP NVS namespaces, enabling operations like reading, writing, and committing key-value pairs. It encapsulates all direct interactions with the NVS to ensure proper error handling and namespace management.

NvsHandle Example

    // Init NVS
    std::error_code ec;
    espp::Nvs nvs;
    nvs.init(ec);
    ec.clear();

    // Open
    fmt::print("\nOpening Non-Volatile Storage (NVS) handle... ");
    // Handle will automatically close when going out of scope or when it's reset.
    espp::NvsHandle storage("storage", ec);
    fmt::print("Done\n");
    ec.clear();

    // Read
    fmt::print("Reading restart counter from NVS ... ");
    int32_t restart_counter = 0;
    storage.get("restart_counter", restart_counter, ec);
    if (ec) {
      if (ec.value() == static_cast<int>(NvsErrc::Key_Not_Found)) {
        fmt::print("The value is not initialized yet!\n");
      } else if (ec.value() == static_cast<int>(NvsErrc::Read_NVS_Failed)) {
        fmt::print("Failed to read from NVS: {}\n", ec.message().c_str());
      } else {
        fmt::print("An error occurred: {}\n", ec.message().c_str());
      }
    } else {
      fmt::print("Done\n");
      fmt::print("Restart counter = {}\n", restart_counter);
    }
    ec.clear();

    // Write
    fmt::print("Updating restart counter in NVS ... ");
    restart_counter++;
    storage.set("restart_counter", restart_counter, ec);
    fmt::print("Done\n");
    ec.clear();

    // Commit written value.
    // After setting any values, nvs_commit() must be called to ensure changes are written
    // to flash storage. Implementations may write to storage at other times,
    // but this is not guaranteed.
    fmt::print("Committing updates in NVS ... ");
    storage.commit(ec);
    fmt::print("Done\n");
    ec.clear();

    fmt::print("\n");
    fflush(stdout);

Public Functions

inline explicit NvsHandle(const char *ns_name, std::error_code &ec)

Construct a new NvsHandle object.

Create an NvsHandle object for the key-value pairs in the ns_name namespace

Parameters
  • ns_name[in] Namespace for NVS

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void get(const char *key, T &value, std::error_code &ec)

Reads a variable from the NVS.

Reads the value of key into value, if key exists

Parameters
  • key[in] NVS Key of the variable to read

  • value[out] Variable to read

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void get(std::string_view key, T &value, std::error_code &ec)

Reads a variable from the NVS.

Parameters
  • key[in] NVS Key of the variable to read

  • value[out] Variable to read

  • ec[out] Saves a std::error_code representing success or failure

inline void get(const char *key, bool &value, std::error_code &ec)

Reads a bool from the NVS.

Read the key/variable pair

Parameters
  • key[in] NVS Key of the bool to read

  • value[out] bool to read

  • ec[out] Saves a std::error_code representing success or failure

inline void get(std::string_view key, bool &value, std::error_code &ec)

Reads a bool from the NVS.

Parameters
  • key[in] NVS Key of the bool to read

  • value[out] bool to read

  • ec[out] Saves a std::error_code representing success or failure

inline void get(std::string_view key, std::string &value, std::error_code &ec)

Reads a string from the NVS.

Parameters
  • key[in] NVS Key of the string to read

  • value[inout] string to read

  • ec[out] Saves a std::error_code representing success or failure

inline void get(const char *key, std::string &value, std::error_code &ec)

Reads a string from the NVS.

Parameters
  • key[in] NVS Key of the string to read

  • value[out] string to read

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void get(const char *key, T &value, const T default_value, std::error_code &ec)

Reads a variable from the NVS.

Reads the value of key into value, if key exists

Parameters
  • key[in] NVS Key of the variable to read

  • value[out] Variable to read

  • default_value[in] Default value to return if key is not found

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void get(std::string_view key, T &value, const T default_value, std::error_code &ec)

Reads a variable from the NVS.

Parameters
  • key[in] NVS Key of the variable to read

  • value[out] Variable to read

  • default_value[in] Default value to return if key is not found

  • ec[out] Saves a std::error_code representing success or failure

inline void get(const char *key, bool &value, const bool default_value, std::error_code &ec)

Reads a bool from the NVS.

Read the key/variable pair

Parameters
  • key[in] NVS Key of the bool to read

  • value[out] bool to read

  • default_value[in] Default value to return if key is not found

  • ec[out] Saves a std::error_code representing success or failure

inline void get(std::string_view key, bool &value, const bool default_value, std::error_code &ec)

Reads a bool from the NVS.

Parameters
  • key[in] NVS Key of the bool to read

  • value[out] bool to read

  • default_value[in] Default value to return if key is not found

  • ec[out] Saves a std::error_code representing success or failure

inline void get(std::string_view key, std::string &value, const std::string &default_value, std::error_code &ec)

Reads a string from the NVS.

Parameters
  • key[in] NVS Key of the string to read

  • value[out] string to read

  • default_value[in] Default value to return if key is not found

  • ec[out] Saves a std::error_code representing success or failure

inline void get(const char *key, std::string &value, const std::string &default_value, std::error_code &ec)

Reads a string from the NVS.

Parameters
  • key[in] NVS Key of the string to read

  • value[out] string to read

  • default_value[in] Default value to return if key is not found

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void set(const char *key, T value, std::error_code &ec)

Save a variable in the NVS.

Saves the key/variable pair without committing the NVS.

Parameters
  • key[in] NVS Key of the variable to read

  • value[in] Variable to read

  • ec[out] Saves a std::error_code representing success or failure

template<typename T>
inline void set(std::string_view key, T value, std::error_code &ec)

Save a variable in the NVS.

Parameters
  • key[in] NVS Key of the variable to save

  • value[in] Variable to save

  • ec[out] Saves a std::error_code representing success or failure

inline void set(std::string_view key, bool value, std::error_code &ec)

Set a bool in the NVS.

Parameters
  • key[in] NVS Key of the bool to set

  • value[in] bool to set

  • ec[out] Saves a std::error_code representing success or failure

inline void set(const char *key, bool value, std::error_code &ec)

Set a bool in the NVS.

Parameters
  • key[in] NVS Key of the bool to set

  • value[in] bool to set

  • ec[out] Saves a std::error_code representing success or failure

inline void set(std::string_view key, const std::string &value, std::error_code &ec)

Set a string in the NVS.

Parameters
  • key[in] NVS Key of the string to set

  • value[in] string to set

  • ec[out] Saves a std::error_code representing success or failure

inline void set(const char *key, const std::string &value, std::error_code &ec)

Set a string in the NVS.

Parameters
  • key[in] NVS Key of the string to set

  • value[in] string to set

  • ec[out] Saves a std::error_code representing success or failure

inline void commit(std::error_code &ec)

Commit changes.

Commits changes to the NVS

Parameters

ec[out] Saves a std::error_code representing success or failure

inline bool erase(std::string_view key, std::error_code &ec)

Erase a key from the NVS.

Parameters
  • key[in] NVS Key to erase

  • ec[out] Saves a std::error_code representing success or failure

Returns

true if successful, false otherwise

inline bool erase(const char *key, std::error_code &ec)

Erase a key from the NVS.

Parameters
  • key[in] NVS Key to erase

  • ec[out] Saves a std::error_code representing success or failure

Returns

true if successful, false otherwise

inline bool erase(std::error_code &ec)

Erase all keys from the NVS associated with the namespace / handle.

Parameters

ec[out] Saves a std::error_code representing success or failure

Returns

true if successful, false otherwise

inline const std::string &get_name() const

Get the name of the component

Note

This is the tag of the logger

Returns

A const reference to the name of the component

inline void set_log_tag(const std::string_view &tag)

Set the tag for the logger

Parameters

tag – The tag to use for the logger

inline espp::Logger::Verbosity get_log_level() const

Get the log level for the logger

Returns

The verbosity level of the logger

inline void set_log_level(espp::Logger::Verbosity level)

Set the log level for the logger

Parameters

level – The verbosity level to use for the logger

inline void set_log_verbosity(espp::Logger::Verbosity level)

Set the log verbosity for the logger

See also

set_log_level

Note

This is a convenience method that calls set_log_level

Parameters

level – The verbosity level to use for the logger

inline espp::Logger::Verbosity get_log_verbosity() const

Get the log verbosity for the logger

See also

get_log_level

Note

This is a convenience method that calls get_log_level

Returns

The verbosity level of the logger

inline void set_log_rate_limit(std::chrono::duration<float> rate_limit)

Set the rate limit for the logger

Note

Only calls to the logger that have _rate_limit suffix will be rate limited

Parameters

rate_limit – The rate limit to use for the logger