1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
#include "nvs_flash.h"
#include "esp_log.h"
#include <string.h>
#include "nvs.h"
#define NVS_GOAM_NAMESPACE "goam"
static const char *TAG = "nvs";
static void nvs_init_partition(const char* partition) {
esp_err_t ret = nvs_flash_init_partition(partition);
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase_partition(partition));
ret = nvs_flash_init_partition(partition);
}
ESP_ERROR_CHECK(ret);
}
void nvs_init() {
nvs_init_partition("nvs");
ESP_LOGI(TAG, "NVS initialized");
}
void nvs_write(const char* key, const char* value) {
nvs_handle_t outHandle;
ESP_ERROR_CHECK(nvs_open(NVS_GOAM_NAMESPACE, NVS_READWRITE, &outHandle));
ESP_ERROR_CHECK(nvs_set_str(outHandle, key, value));
ESP_ERROR_CHECK(nvs_commit(outHandle));
nvs_close(outHandle);
}
void nvs_read(const char* key, char** output) {
nvs_handle_t inHandle;
esp_err_t err = nvs_open(NVS_GOAM_NAMESPACE, NVS_READONLY, &inHandle);
if (err == ESP_ERR_NVS_NOT_FOUND) {
*output = NULL;
nvs_close(inHandle);
return;
}
ESP_ERROR_CHECK(err);
size_t size = 0;
err = nvs_get_str(inHandle, key, NULL, &size);
if (err != ESP_OK) {
*output = NULL;
nvs_close(inHandle);
return;
}
if (size == 0) {
*output = NULL;
nvs_close(inHandle);
return;
}
free(*output);
*output = malloc(size * sizeof(char));
ESP_ERROR_CHECK(nvs_get_str(inHandle, key, *output, &size));
nvs_close(inHandle);
}
void nvs_write_i32(const char* key, int32_t value) {
nvs_handle_t outHandle;
ESP_ERROR_CHECK(nvs_open(NVS_GOAM_NAMESPACE, NVS_READWRITE, &outHandle));
ESP_ERROR_CHECK(nvs_set_i32(outHandle, key, value));
ESP_ERROR_CHECK(nvs_commit(outHandle));
nvs_close(outHandle);
}
void nvs_read_i32(const char* key, int32_t* output) {
nvs_handle_t inHandle;
esp_err_t err = nvs_open(NVS_GOAM_NAMESPACE, NVS_READONLY, &inHandle);
if (err == ESP_ERR_NVS_NOT_FOUND) {
nvs_close(inHandle);
return;
}
ESP_ERROR_CHECK(err);
err = nvs_get_i32(inHandle, key, output);
if (err != ESP_OK) {
nvs_close(inHandle);
return;
}
nvs_close(inHandle);
}
|