Non-Volatile Storage (NVS)
The non-volatile storage in ESP-IDF uses a portion of the main flash memory through esp_partition.h
APIs to store key-value pairs. Since NVS is permanent, even if the device is restarted or powered off, the stored data will not be lost. NVS has been specially designed to prevent data corruption caused by power failure, and to distribute the written data throughout NVS in case of flash wear and tear. The dedicated partition in flash used by NVS stores data of various types, such as integers, NULL
-terminated strings, and binary data.
NVS is suitable for storing small data, rather than large data such as strings or binary large objects (BLOBs) which should be handled by the FAT file system based on wear leveling. In IoT projects, NVS can store not only the unique mass production data for products, but also any user data related to the application.
Following are several key concepts of NVS: key-value pairs, namespaces, security, tamper resistance, and robustness.
Key-value pairs
NVS operates on key-value pairs, as in "key:value". Keys are ASCII strings of up to 15 characters, while values can be any of the following types:
- Integers:
uint8_t
,int8_t
,uint16_t
,int16_t
,uint32_t
,int32_t
,
uint64_t
, andint64_t
. - Strings ending with "0".
- Variable-length binary data.
Namespaces
To mitigate potential conflicts in key names between different components, NVS assigns a namespace to each key-value pair, which follows the same naming rule as keys, i.e., the maximum length is 15 characters. These names are specified in the nvs_open()
or nvs_open_from_part()
call. This call returns an opaque handle, which is used in subsequent calls to nvs_get_*()
, nvs_set_*()
, and nvs_commit()
functions. In this way, a handle is associated with each namespace, and key names will not collide with the same names in other namespaces. Please note that the namespaces with the same name in different NVS partitions are considered as separate namespaces.
Security, tamper resistance, and robustness
After NVS encryption, data will be stored in encrypted form. If NVS encryption is not enabled, any user with physical access to the flash can modify, erase, or add key-value pairs. If NVS encryption is enabled, key-value pairs cannot be modified or added without knowing the corresponding NVS encryption key. However, there is no tamper-resistance against the erase operation.
When the flash runs into an inconsistent state, NVS will try recovering. Powering off a device at any time and then powering it back on will not cause data loss. However, if the device is powered off while writing a new key-value pair, that specific pair may be lost.