Skip to content

Commit c10d431

Browse files
tvedpgeorge
authored andcommitted
esp32: Add basic support for Non-Volatile-Storage in esp32 module.
This commit implements basic NVS support for the esp32. It follows the pattern of the esp32.Partition class and exposes an NVS object per NVS namespace. The initial support provided is only for signed 32-bit integers and binary blobs. It's easy (albeit a bit tedious) to add support for more types. See discussions in: adafruit#4436, adafruit#4707, adafruit#6780
1 parent 143372a commit c10d431

File tree

7 files changed

+283
-0
lines changed

7 files changed

+283
-0
lines changed

docs/library/esp32.rst

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,3 +269,51 @@ Constants
269269
esp32.WAKEUP_ANY_HIGH
270270

271271
Selects the wake level for pins.
272+
273+
Non-Volatile Storage
274+
--------------------
275+
276+
This class gives access to the Non-Volatile storage managed by ESP-IDF. The NVS is partitioned
277+
into namespaces and each namespace contains typed key-value pairs. The keys are strings and the
278+
values may be various integer types, strings, and binary blobs. The driver currently only
279+
supports 32-bit signed integers and blobs.
280+
281+
.. warning::
282+
283+
Changes to NVS need to be committed to flash by calling the commit method. Failure
284+
to call commit results in changes being lost at the next reset.
285+
286+
.. class:: NVS(namespace)
287+
288+
Create an object providing access to a namespace (which is automatically created if not
289+
present).
290+
291+
.. method:: NVS.set_i32(key, value)
292+
293+
Sets a 32-bit signed integer value for the specified key. Remember to call *commit*!
294+
295+
.. method:: NVS.get_i32(key)
296+
297+
Returns the signed integer value for the specified key. Raises an OSError if the key does not
298+
exist or has a different type.
299+
300+
.. method:: NVS.set_blob(key, value)
301+
302+
Sets a binary blob value for the specified key. The value passed in must support the buffer
303+
protocol, e.g. bytes, bytearray, str. (Note that esp-idf distinguishes blobs and strings, this
304+
method always writes a blob even if a string is passed in as value.)
305+
Remember to call *commit*!
306+
307+
.. method:: NVS.get_blob(key, buffer)
308+
309+
Reads the value of the blob for the specified key into the buffer, which must be a bytearray.
310+
Returns the actual length read. Raises an OSError if the key does not exist, has a different
311+
type, or if the buffer is too small.
312+
313+
.. method:: NVS.erase_key(key)
314+
315+
Erases a key-value pair.
316+
317+
.. method:: NVS.commit()
318+
319+
Commits changes made by *set_xxx* methods to flash.

ports/esp32/esp32_nvs.c

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
/*
2+
* This file is part of the MicroPython project, http://micropython.org/
3+
*
4+
* The MIT License (MIT)
5+
*
6+
* Copyright (c) 2021 by Thorsten von Eicken
7+
*
8+
* Permission is hereby granted, free of charge, to any person obtaining a copy
9+
* of this software and associated documentation files (the "Software"), to deal
10+
* in the Software without restriction, including without limitation the rights
11+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
* copies of the Software, and to permit persons to whom the Software is
13+
* furnished to do so, subject to the following conditions:
14+
*
15+
* The above copyright notice and this permission notice shall be included in
16+
* all copies or substantial portions of the Software.
17+
*
18+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24+
* THE SOFTWARE.
25+
*/
26+
27+
#include <string.h>
28+
29+
#include "py/runtime.h"
30+
#include "py/mperrno.h"
31+
#include "mphalport.h"
32+
#include "modesp32.h"
33+
#include "nvs_flash.h"
34+
#include "nvs.h"
35+
36+
// This file implements the NVS (Non-Volatile Storage) class in the esp32 module.
37+
// It provides simple access to the NVS feature provided by ESP-IDF.
38+
39+
// NVS python object that represents an NVS namespace.
40+
typedef struct _esp32_nvs_obj_t {
41+
mp_obj_base_t base;
42+
nvs_handle_t namespace;
43+
} esp32_nvs_obj_t;
44+
45+
// *esp32_nvs_new allocates a python NVS object given a handle to an esp-idf namespace C obj.
46+
STATIC esp32_nvs_obj_t *esp32_nvs_new(nvs_handle_t namespace) {
47+
esp32_nvs_obj_t *self = m_new_obj(esp32_nvs_obj_t);
48+
self->base.type = &esp32_nvs_type;
49+
self->namespace = namespace;
50+
return self;
51+
}
52+
53+
// esp32_nvs_print prints an NVS object, unfortunately it doesn't seem possible to extract the
54+
// namespace string or anything else from the opaque handle provided by esp-idf.
55+
STATIC void esp32_nvs_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
56+
// esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
57+
mp_printf(print, "<NVS namespace>");
58+
}
59+
60+
// esp32_nvs_make_new constructs a handle to an NVS namespace.
61+
STATIC mp_obj_t esp32_nvs_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
62+
// Check args
63+
mp_arg_check_num(n_args, n_kw, 1, 1, false);
64+
65+
// Get requested nvs namespace
66+
const char *ns_name = mp_obj_str_get_str(all_args[0]);
67+
nvs_handle_t namespace;
68+
check_esp_err(nvs_open(ns_name, NVS_READWRITE, &namespace));
69+
return MP_OBJ_FROM_PTR(esp32_nvs_new(namespace));
70+
}
71+
72+
// esp32_nvs_set_i32 sets a 32-bit integer value
73+
STATIC mp_obj_t esp32_nvs_set_i32(mp_obj_t self_in, mp_obj_t key_in, mp_obj_t value_in) {
74+
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
75+
const char *key = mp_obj_str_get_str(key_in);
76+
int32_t value = mp_obj_get_int(value_in);
77+
check_esp_err(nvs_set_i32(self->namespace, key, value));
78+
return mp_const_none;
79+
}
80+
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_nvs_set_i32_obj, esp32_nvs_set_i32);
81+
82+
// esp32_nvs_get_i32 reads a 32-bit integer value
83+
STATIC mp_obj_t esp32_nvs_get_i32(mp_obj_t self_in, mp_obj_t key_in) {
84+
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
85+
const char *key = mp_obj_str_get_str(key_in);
86+
int32_t value;
87+
check_esp_err(nvs_get_i32(self->namespace, key, &value));
88+
return mp_obj_new_int(value);
89+
}
90+
STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp32_nvs_get_i32_obj, esp32_nvs_get_i32);
91+
92+
// esp32_nvs_set_blob writes a buffer object into a binary blob value.
93+
STATIC mp_obj_t esp32_nvs_set_blob(mp_obj_t self_in, mp_obj_t key_in, mp_obj_t value_in) {
94+
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
95+
const char *key = mp_obj_str_get_str(key_in);
96+
mp_buffer_info_t value;
97+
mp_get_buffer_raise(value_in, &value, MP_BUFFER_READ);
98+
check_esp_err(nvs_set_blob(self->namespace, key, value.buf, value.len));
99+
return mp_const_none;
100+
}
101+
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_nvs_set_blob_obj, esp32_nvs_set_blob);
102+
103+
// esp32_nvs_get_blob reads a binary blob value into a bytearray. Returns actual length.
104+
STATIC mp_obj_t esp32_nvs_get_blob(mp_obj_t self_in, mp_obj_t key_in, mp_obj_t value_in) {
105+
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
106+
const char *key = mp_obj_str_get_str(key_in);
107+
// get buffer to be filled
108+
mp_buffer_info_t value;
109+
mp_get_buffer_raise(value_in, &value, MP_BUFFER_WRITE);
110+
size_t length = value.len;
111+
// fill the buffer with the value, will raise an esp-idf error if the length of
112+
// the provided buffer (bytearray) is too small
113+
check_esp_err(nvs_get_blob(self->namespace, key, value.buf, &length));
114+
return MP_OBJ_NEW_SMALL_INT(length);
115+
}
116+
STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_nvs_get_blob_obj, esp32_nvs_get_blob);
117+
118+
// esp32_nvs_erase_key erases one key.
119+
STATIC mp_obj_t esp32_nvs_erase_key(mp_obj_t self_in, mp_obj_t key_in) {
120+
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
121+
const char *key = mp_obj_str_get_str(key_in);
122+
check_esp_err(nvs_erase_key(self->namespace, key));
123+
return mp_const_none;
124+
}
125+
STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp32_nvs_erase_key_obj, esp32_nvs_erase_key);
126+
127+
// esp32_nvs_commit commits any changes to flash.
128+
STATIC mp_obj_t esp32_nvs_commit(mp_obj_t self_in) {
129+
esp32_nvs_obj_t *self = MP_OBJ_TO_PTR(self_in);
130+
check_esp_err(nvs_commit(self->namespace));
131+
return mp_const_none;
132+
}
133+
STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp32_nvs_commit_obj, esp32_nvs_commit);
134+
135+
STATIC const mp_rom_map_elem_t esp32_nvs_locals_dict_table[] = {
136+
{ MP_ROM_QSTR(MP_QSTR_get_i32), MP_ROM_PTR(&esp32_nvs_get_i32_obj) },
137+
{ MP_ROM_QSTR(MP_QSTR_set_i32), MP_ROM_PTR(&esp32_nvs_set_i32_obj) },
138+
{ MP_ROM_QSTR(MP_QSTR_get_blob), MP_ROM_PTR(&esp32_nvs_get_blob_obj) },
139+
{ MP_ROM_QSTR(MP_QSTR_set_blob), MP_ROM_PTR(&esp32_nvs_set_blob_obj) },
140+
{ MP_ROM_QSTR(MP_QSTR_erase_key), MP_ROM_PTR(&esp32_nvs_erase_key_obj) },
141+
{ MP_ROM_QSTR(MP_QSTR_commit), MP_ROM_PTR(&esp32_nvs_commit_obj) },
142+
};
143+
STATIC MP_DEFINE_CONST_DICT(esp32_nvs_locals_dict, esp32_nvs_locals_dict_table);
144+
145+
const mp_obj_type_t esp32_nvs_type = {
146+
{ &mp_type_type },
147+
.name = MP_QSTR_NVS,
148+
.print = esp32_nvs_print,
149+
.make_new = esp32_nvs_make_new,
150+
.locals_dict = (mp_obj_dict_t *)&esp32_nvs_locals_dict,
151+
};

ports/esp32/main/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ set(MICROPY_SOURCE_PORT
5555
${PROJECT_DIR}/mpnimbleport.c
5656
${PROJECT_DIR}/modsocket.c
5757
${PROJECT_DIR}/modesp.c
58+
${PROJECT_DIR}/esp32_nvs.c
5859
${PROJECT_DIR}/esp32_partition.c
5960
${PROJECT_DIR}/esp32_rmt.c
6061
${PROJECT_DIR}/esp32_ulp.c

ports/esp32/modesp32.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ STATIC const mp_rom_map_elem_t esp32_module_globals_table[] = {
186186
{ MP_ROM_QSTR(MP_QSTR_hall_sensor), MP_ROM_PTR(&esp32_hall_sensor_obj) },
187187
{ MP_ROM_QSTR(MP_QSTR_idf_heap_info), MP_ROM_PTR(&esp32_idf_heap_info_obj) },
188188

189+
{ MP_ROM_QSTR(MP_QSTR_NVS), MP_ROM_PTR(&esp32_nvs_type) },
189190
{ MP_ROM_QSTR(MP_QSTR_Partition), MP_ROM_PTR(&esp32_partition_type) },
190191
{ MP_ROM_QSTR(MP_QSTR_RMT), MP_ROM_PTR(&esp32_rmt_type) },
191192
{ MP_ROM_QSTR(MP_QSTR_ULP), MP_ROM_PTR(&esp32_ulp_type) },

ports/esp32/modesp32.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#define RTC_LAST_EXT_PIN 39
2727
#define RTC_IS_VALID_EXT_PIN(pin_id) ((1ll << (pin_id)) & RTC_VALID_EXT_PINS)
2828

29+
extern const mp_obj_type_t esp32_nvs_type;
2930
extern const mp_obj_type_t esp32_partition_type;
3031
extern const mp_obj_type_t esp32_rmt_type;
3132
extern const mp_obj_type_t esp32_ulp_type;

tests/esp32/esp32_nvs.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Test the esp32 NVS class - access to esp-idf's Non-Volatile-Storage
2+
3+
from esp32 import NVS
4+
5+
nvs = NVS("mp-test")
6+
7+
# test setting and gettin an integer kv
8+
nvs.set_i32("key1", 1234)
9+
print(nvs.get_i32("key1"))
10+
nvs.set_i32("key2", -503)
11+
print(nvs.get_i32("key2"))
12+
print(nvs.get_i32("key1"))
13+
14+
# test setting and getting a blob kv using a bytearray
15+
blob1 = "testing a string as a blob"
16+
nvs.set_blob("blob1", blob1)
17+
buf1 = bytearray(len(blob1))
18+
len1 = nvs.get_blob("blob1", buf1)
19+
print(buf1)
20+
print(len(blob1), len1)
21+
22+
# test setting and getting a blob kv using a string
23+
blob2 = b"testing a bytearray"
24+
nvs.set_blob("blob2", blob2)
25+
buf2 = bytearray(len(blob2))
26+
len2 = nvs.get_blob("blob2", buf2)
27+
print(buf2)
28+
print(len(blob2), len2)
29+
30+
# test raising of error exceptions
31+
nvs.erase_key("key1")
32+
try:
33+
nvs.erase_key("key1") # not found
34+
except OSError as e:
35+
print(e)
36+
try:
37+
nvs.get_i32("key1") # not found
38+
except OSError as e:
39+
print(e)
40+
try:
41+
nvs.get_i32("blob1") # not found (blob1 exists but diff type)
42+
except OSError as e:
43+
print(e)
44+
try:
45+
buf3 = bytearray(10)
46+
nvs.get_blob("blob1", buf3) # invalid length (too short)
47+
except OSError as e:
48+
print(e)
49+
50+
nvs.commit() # we're not verifying that this does anything, just doesn't error
51+
52+
# test using a second namespace and that it doesn't interfere with first
53+
nvs2 = NVS("mp-test2")
54+
try:
55+
print(nvs2.get_i32("key2"))
56+
except OSError as e:
57+
print(e)
58+
nvs2.set_i32("key2", 7654)
59+
print(nvs.get_i32("key2"))
60+
print(nvs2.get_i32("key2"))
61+
62+
# clean-up (the namespaces will remain)
63+
nvs.erase_key("key2")
64+
nvs.erase_key("blob1")
65+
nvs.erase_key("blob2")
66+
nvs2.erase_key("key2")
67+
nvs.commit()

tests/esp32/esp32_nvs.py.exp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
1234
2+
-503
3+
1234
4+
bytearray(b'testing a string as a blob')
5+
26 26
6+
bytearray(b'testing a bytearray')
7+
19 19
8+
(-4354, 'ESP_ERR_NVS_NOT_FOUND')
9+
(-4354, 'ESP_ERR_NVS_NOT_FOUND')
10+
(-4354, 'ESP_ERR_NVS_NOT_FOUND')
11+
(-4364, 'ESP_ERR_NVS_INVALID_LENGTH')
12+
(-4354, 'ESP_ERR_NVS_NOT_FOUND')
13+
-503
14+
7654

0 commit comments

Comments
 (0)