ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
preferences.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
3#include "preferences.h"
5#include "esphome/core/log.h"
7#include <esp_attr.h>
8#include <esp_idf_version.h>
9#include <nvs_flash.h>
10#include <soc/soc_caps.h>
11#include <algorithm>
12#include <cstring>
13#include <vector>
14
15namespace esphome::esp32 {
16
17ESPHOME_LOG_TAG(TAG, "preferences");
18
19struct NVSData {
20 uint32_t key;
21 SmallInlineBuffer<8> data; // Most prefs fit in 8 bytes (covers fan, cover, select, etc.)
22};
23
24// The NVS namespace for ESPHome's preferences.
25static constexpr const char ESPHOME_NAMESPACE[] = "esphome";
26
27// Key that stores the preferences metadata.
28static constexpr const char METADATA_KEY[] = "metadata";
29
30// The original preferences format.
31// All values are stored in NVS as blobs.
32static constexpr uint8_t FORMAT_V1 = 1;
33
34// Values of up to 7 bytes are stored as an i64 with the length in the top byte, 8-byte values as a u64 and larger
35// values as blobs, all under the same key name. Values still held as V1 blobs are read until they are next written.
36// Writing a key with another type replaces the old entry, so a value has one entry.
37static constexpr uint8_t FORMAT_V2 = 2;
38
39// The most recently supported format.
40// Preferences will be erased on a downgrade when the stored format version is greater than this value.
41static constexpr uint8_t FORMAT_LATEST_SUPPORTED = FORMAT_V2;
42
43// The format new and converted preferences use. NVS replaces an integer with a blob only from ESP-IDF 5.5, and its
44// legacy duplicate key mode never replaces another type, so those builds stay on V1.
45#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0) && !defined(CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY)
46static constexpr uint8_t FORMAT_ADOPTED = FORMAT_V2;
47#else
48static constexpr uint8_t FORMAT_ADOPTED = FORMAT_V1;
49#endif
50
51union Metadata {
52 struct {
53 uint8_t format;
54 uint8_t reserved[7];
55 };
56 uint64_t raw;
57};
58
59static constexpr size_t KEY_NAME_MAX_SIZE = UINT32_MAX_STR_SIZE;
60static_assert(KEY_NAME_MAX_SIZE <= NVS_KEY_NAME_MAX_SIZE);
61
62// Bit position of the length byte in a value stored as an i64; the length keeps the sign bit clear.
63static constexpr unsigned I64_LENGTH_SHIFT = 56;
64
65// The preference format, zero when preferences are not initialized.
66static uint8_t s_format{0}; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
67
68static bool stored_as_integer(size_t len) { return s_format >= FORMAT_V2 && len <= sizeof(uint64_t); }
69
70static esp_err_t nvs_read_blob(uint32_t handle, const char *key_name, uint8_t *out, size_t len) {
71 size_t current_len;
72 const esp_err_t err = nvs_get_blob(handle, key_name, nullptr, &current_len);
73 if (err != ESP_OK)
74 return err;
75 if (current_len != len)
76 return ESP_ERR_NVS_INVALID_LENGTH;
77 return out == nullptr ? ESP_OK : nvs_get_blob(handle, key_name, out, &current_len);
78}
79
80// Fills key_name and reads exactly len bytes into out; with out null, only checks that a value of that length is
81// stored. A value not yet rewritten in the integer form is read from its blob.
82static esp_err_t nvs_read_value(uint32_t handle, uint32_t key, char *key_name, uint8_t *out, size_t len) {
83 *uint32_to_str_unchecked(key_name, key) = '\0';
84 if (stored_as_integer(len)) {
85 uint64_t value = 0;
86 esp_err_t err;
87 if (len == sizeof(uint64_t)) {
88 err = nvs_get_u64(handle, key_name, &value);
89 } else {
90 int64_t stored = 0;
91 err = nvs_get_i64(handle, key_name, &stored);
92 value = static_cast<uint64_t>(stored);
93 if (err == ESP_OK && (value >> I64_LENGTH_SHIFT) != len)
94 return ESP_ERR_NVS_INVALID_LENGTH;
95 }
96 if (err == ESP_OK) {
97 if (out != nullptr)
98 memcpy(out, &value, len);
99 return ESP_OK;
100 }
101 if (err != ESP_ERR_NVS_NOT_FOUND && err != ESP_ERR_NVS_TYPE_MISMATCH)
102 return err;
103 }
104 return nvs_read_blob(handle, key_name, out, len);
105}
106
107static std::vector<NVSData> s_pending_save; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
108
109// RTC memory backend for preferences requested with in_flash=false. Survives deep sleep and
110// software/CPU resets, but not power loss; integrity is guarded by a per-record checksum so
111// power-on garbage is detected on load. Keep this small: RTC memory is scarce and shared.
112//
113// Only compiled in when USE_ESP32_RTC_PREFERENCES_STORAGE is set (see preferences.h): the storage
114// buffer reserves RTC memory, so it exists only when some config option actually selected RTC
115// storage AND the variant has RTC memory (the ESP32-C2 and -C61 have none, so RTC_NOINIT_ATTR would
116// have no section to land in and fail to link). Otherwise in_flash=false transparently falls back
117// to NVS (see make_preference below).
118//
119// On variants with only RTC fast memory (C3/C6/H2/P4/C5/...) RTC_NOINIT_ATTR lands in RTC fast memory.
120// This is still safe: the linker reserves .rtc_noinit ahead of any RTC-fast-as-heap pool
121// (CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP), and IDF keeps the RTC fast power domain on in deep
122// sleep (forced on whether or not it is used as heap), so the data is retained across both resets and
123// deep sleep -- only power loss clears it.
124#ifdef USE_ESP32_RTC_PREFERENCES_STORAGE
125static constexpr size_t RTC_PREF_SIZE_WORDS = 64; // 256 bytes
126static constexpr size_t RTC_PREF_MAX_WORDS = 255; // length_words field is a uint8_t
127
128// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
129static RTC_NOINIT_ATTR uint32_t s_rtc_storage[RTC_PREF_SIZE_WORDS];
130
131static bool save_to_rtc(uint16_t offset, uint32_t key, uint8_t length_words, const uint8_t *data, size_t len) {
132 if (rtc_pref_bytes_to_words(len) != length_words)
133 return false;
134 const size_t buffer_size = static_cast<size_t>(length_words) + 1;
135 if (static_cast<size_t>(offset) + buffer_size > RTC_PREF_SIZE_WORDS)
136 return false;
137 rtc_pref_encode(&s_rtc_storage[offset], key, length_words, data, len);
138 return true;
139}
140
141static bool load_from_rtc(uint16_t offset, uint32_t key, uint8_t length_words, uint8_t *data, size_t len) {
142 if (rtc_pref_bytes_to_words(len) != length_words)
143 return false;
144 const size_t buffer_size = static_cast<size_t>(length_words) + 1;
145 if (static_cast<size_t>(offset) + buffer_size > RTC_PREF_SIZE_WORDS)
146 return false;
147 return rtc_pref_decode(&s_rtc_storage[offset], key, length_words, data, len);
148}
149#endif // USE_ESP32_RTC_PREFERENCES_STORAGE
150
151// open() runs from app_main() before the logger is initialized, so any failure
152// must be deferred until after global_logger is set. This is emitted from the
153// first make_preference() call, which runs from the generated setup() after
154// log->pre_setup() has run at EARLY_INIT priority.
155static esp_err_t s_open_err = ESP_OK; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
156static bool s_partition_erased = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
157
158bool ESP32PreferenceBackend::save(const uint8_t *data, size_t len) {
159#ifdef USE_ESP32_RTC_PREFERENCES_STORAGE
160 if (!this->in_flash)
161 return save_to_rtc(this->rtc_offset, this->key, this->length_words, data, len);
162#endif
163 // try find in pending saves and update that
164 for (auto &obj : s_pending_save) {
165 if (obj.key == this->key) {
166 obj.data.set(data, len);
167 return true;
168 }
169 }
170 NVSData save{};
171 save.key = this->key;
172 save.data.set(data, len);
173 s_pending_save.push_back(std::move(save));
174 ESP_LOGVV(TAG, "s_pending_save: key: %" PRIu32 ", len: %zu", this->key, len);
175 return true;
176}
177
179#ifdef USE_ESP32_RTC_PREFERENCES_STORAGE
180 if (!this->in_flash)
181 return false; // RTC memory does not survive a power loss
182#endif
183 return get_preferences()->sync_key(this->key);
184}
185
186bool ESP32PreferenceBackend::load(uint8_t *data, size_t len) {
187#ifdef USE_ESP32_RTC_PREFERENCES_STORAGE
188 if (!this->in_flash)
189 return load_from_rtc(this->rtc_offset, this->key, this->length_words, data, len);
190#endif
191 // try find in pending saves and load from that
192 for (auto &obj : s_pending_save) {
193 if (obj.key == this->key) {
194 if (obj.data.size() != len) {
195 // size mismatch
196 return false;
197 }
198 memcpy(data, obj.data.data(), len);
199 return true;
200 }
201 }
202
203 char key_name[KEY_NAME_MAX_SIZE];
204 const esp_err_t err = nvs_read_value(this->nvs_handle, this->key, key_name, data, len);
205 if (err == ESP_OK) {
206 ESP_LOGVV(TAG, "NVS read '%s': length=%zu", key_name, len);
207 return true;
208 }
209 ESP_LOGV(TAG, "NVS read '%s': %s", key_name, esp_err_to_name(err));
210 return false;
211}
212
214 // Runs from app_main() before the logger is initialized; any logging here
215 // must be deferred. See s_open_err and make_preference() below.
216 // Components that need NVS check nvs_handle instead of initializing it again.
217 nvs_flash_init();
218
219 Metadata metadata{};
220 bool adopt_latest_format = false;
221 this->nvs_handle = 0;
222 esp_err_t err = nvs_open(ESPHOME_NAMESPACE, NVS_READWRITE, &this->nvs_handle);
223 if (err == ESP_OK) {
224 err = nvs_get_u64(this->nvs_handle, METADATA_KEY, &metadata.raw);
225 if (err == ESP_OK) {
226 if (metadata.format < FORMAT_V1 || metadata.format > FORMAT_LATEST_SUPPORTED) {
227 err = ESP_ERR_NOT_SUPPORTED;
228 }
229 } else if (err == ESP_ERR_NVS_NOT_FOUND) {
230 // New or V1 preferences: V2 still reads the V1 blobs and converts each value when it next changes
231 adopt_latest_format = true;
232 err = ESP_OK;
233 } else if (err != ESP_ERR_NVS_TYPE_MISMATCH) {
234 // A read error says nothing about the stored data: leave it alone and run this boot without preferences
235 s_open_err = err;
236 nvs_close(this->nvs_handle);
237 this->nvs_handle = 0;
238 return;
239 }
240 if (err != ESP_OK) {
241 // Try to resolve the error by erasing just the ESPHome namespace within NVS.
242 s_open_err = err;
243 err = nvs_erase_all(this->nvs_handle);
244 adopt_latest_format = true;
245 }
246 } else {
247 s_open_err = err;
248 }
249 if (err != ESP_OK) {
250 // For unrecoverable errors, erase the entire NVS partition including other namespaces.
251 s_partition_erased = true;
252 nvs_close(this->nvs_handle);
253 this->nvs_handle = 0;
254 nvs_flash_deinit();
255 nvs_flash_erase();
256 nvs_flash_init();
257 err = nvs_open(ESPHOME_NAMESPACE, NVS_READWRITE, &this->nvs_handle);
258 if (err != ESP_OK)
259 return;
260 adopt_latest_format = true;
261 }
262 if (adopt_latest_format) {
263 metadata.format = FORMAT_ADOPTED;
264 // A full partition can refuse the metadata: keep the original format, which needs none
265 if (FORMAT_ADOPTED != FORMAT_V1 && nvs_set_u64(this->nvs_handle, METADATA_KEY, metadata.raw) != ESP_OK)
266 metadata.format = FORMAT_V1;
267 }
268 s_format = metadata.format;
269}
270
272#ifdef USE_ESP32_RTC_PREFERENCES_STORAGE
273 if (!in_flash)
274 return this->make_rtc_preference_(length, type);
275#else
276 if (!in_flash) {
277 // RTC storage is not compiled in (no config option selected it), so this request
278 // falls back to NVS -- the historic ESP32 behavior. Warn once so callers explicitly
279 // asking for RTC storage can discover the fallback.
280 static bool warned = false;
281 if (!warned) {
282 ESP_LOGW(TAG, "RTC preference storage not compiled in; using NVS (enable with 'preferences: rtc_storage: true')");
283 warned = true;
284 }
285 }
286#endif
287 // in_flash, or RTC storage not compiled in: fall back to NVS.
288 return this->make_preference(length, type);
289}
290
292 if (s_open_err != ESP_OK) {
293 const LogString *outcome = this->nvs_handle == 0 ? LOG_STR("NVS unavailable")
294 : s_partition_erased ? LOG_STR("erased the whole NVS partition")
295 : LOG_STR("erased the stored preferences");
296 ESP_LOGW(TAG, "Open failed: %s - %s", esp_err_to_name(s_open_err), LOG_STR_ARG(outcome));
297 s_open_err = ESP_OK;
298 }
299 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
301}
302
304 // in_flash keeps its default of true, selecting the NVS path
306 backend.nvs_handle = this->nvs_handle;
307 backend.key = type;
308 return backend;
309}
310
311bool ESP32Preferences::load_from_key(uint32_t type, uint8_t *data, size_t len) {
312 ESP32PreferenceBackend backend = this->make_backend_(type);
313 return backend.load(data, len);
314}
315
316#ifdef USE_ESP32_RTC_PREFERENCES_STORAGE
318 const uint32_t length_words = rtc_pref_bytes_to_words(length);
319 if (length_words > RTC_PREF_MAX_WORDS) {
320 ESP_LOGE(TAG, "RTC preference too large: %" PRIu32 " words", length_words);
321 return {};
322 }
323 const uint32_t total_words = length_words + 1; // +1 for checksum
324 if (static_cast<size_t>(this->current_rtc_offset_) + total_words > RTC_PREF_SIZE_WORDS) {
325 ESP_LOGE(TAG, "RTC preference storage full, cannot allocate %" PRIu32 " words", total_words);
326 return {};
327 }
328 auto *pref = new ESP32PreferenceBackend(); // NOLINT(cppcoreguidelines-owning-memory)
329 pref->key = type;
330 pref->in_flash = false;
331 pref->rtc_offset = this->current_rtc_offset_;
332 pref->length_words = static_cast<uint8_t>(length_words);
333 this->current_rtc_offset_ += static_cast<uint16_t>(total_words);
334
335 return ESPPreferenceObject(pref);
336}
337#endif // USE_ESP32_RTC_PREFERENCES_STORAGE
338
340 if (s_pending_save.empty())
341 return true;
342 // No handle after reset() or a failed open, both already logged
343 if (this->nvs_handle == 0) {
344 s_pending_save.clear();
345 return false;
346 }
347
348 ESP_LOGV(TAG, "Saving %zu items...", s_pending_save.size());
349 int cached = 0, written = 0, failed = 0;
350 esp_err_t last_err = ESP_OK;
351 uint32_t last_key = 0;
352
353 for (const auto &save : s_pending_save) {
354 bool changed;
355 esp_err_t err = this->write_if_changed_(save, &changed);
356 if (err != ESP_OK) {
357 failed++;
358 last_err = err;
359 last_key = save.key;
360 } else if (changed) {
361 written++;
362 } else {
363 cached++;
364 }
365 }
366 s_pending_save.clear();
367
368 if (failed > 0) {
369 ESP_LOGE(TAG, "Writing %d items: %d cached, %d written, %d failed. Last error=%s for key=%" PRIu32,
370 cached + written + failed, cached, written, failed, esp_err_to_name(last_err), last_key);
371 } else if (written > 0) {
372 ESP_LOGD(TAG, "Writing %d items: %d cached, %d written, %d failed", cached + written + failed, cached, written,
373 failed);
374 } else {
375 ESP_LOGV(TAG, "Writing %d items: %d cached, %d written, %d failed", cached + written + failed, cached, written,
376 failed);
377 }
378
379 // note: commit on esp-idf currently is a no-op, nvs_set_blob always writes
380 esp_err_t err = nvs_commit(this->nvs_handle);
381 if (err != 0) {
382 ESP_LOGV(TAG, "nvs_commit() failed: %s", esp_err_to_name(err));
383 return false;
384 }
385
386 return failed == 0;
387}
388
389esp_err_t ESP32Preferences::write_if_changed_(const NVSData &save, bool *changed) {
390 const uint32_t key = save.key;
391 const uint8_t *const data = save.data.data();
392 const size_t len = save.data.size();
393 *changed = false;
394 char key_name[KEY_NAME_MAX_SIZE];
395 // Only a stored value of the same length can be unchanged, so the comparison buffer is not allocated otherwise
396 esp_err_t err = nvs_read_value(this->nvs_handle, key, key_name, nullptr, len);
397 if (err == ESP_OK) {
399 err = nvs_read_value(this->nvs_handle, key, key_name, current.get(), len);
400 if (err == ESP_OK && memcmp(data, current.get(), len) == 0) {
401 ESP_LOGV(TAG, "NVS unchanged: key=%" PRIu32 ", length=%zu", key, len);
402 return ESP_OK;
403 }
404 }
405 ESP_LOGVV(TAG, "NVS read '%s': %s", key_name, esp_err_to_name(err));
406 // A V1 blob under this key is replaced by the integer entry
407 if (stored_as_integer(len)) {
408 uint64_t value = 0;
409 memcpy(&value, data, len);
410 if (len == sizeof(uint64_t)) {
411 err = nvs_set_u64(this->nvs_handle, key_name, value);
412 } else {
413 value |= static_cast<uint64_t>(len) << I64_LENGTH_SHIFT;
414 err = nvs_set_i64(this->nvs_handle, key_name, static_cast<int64_t>(value));
415 }
416 ESP_LOGVV(TAG, "NVS set '%s': %s, value=0x%" PRIx64, key_name, esp_err_to_name(err), value);
417 } else {
418 err = nvs_set_blob(this->nvs_handle, key_name, data, len);
419 ESP_LOGVV(TAG, "NVS set '%s': %s, length=%zu", key_name, esp_err_to_name(err), len);
420 }
421 if (err == ESP_OK) {
422 *changed = true;
423 ESP_LOGV(TAG, "NVS changed: key=%" PRIu32 ", length=%zu", key, len);
424 }
425 return err;
426}
427
429 if (this->nvs_handle == 0)
430 return false;
431 auto it =
432 std::find_if(s_pending_save.begin(), s_pending_save.end(), [key](const NVSData &d) { return d.key == key; });
433 if (it == s_pending_save.end())
434 return true;
435 // On failure the save stays queued, so the global sync retries it
436 bool changed;
437 esp_err_t err = this->write_if_changed_(*it, &changed);
438 if (err == ESP_OK && changed)
439 err = nvs_commit(this->nvs_handle);
440 if (err != ESP_OK) {
441 ESP_LOGE(TAG, "Writing key %" PRIu32 " failed: %s", key, esp_err_to_name(err));
442 return false;
443 }
444 s_pending_save.erase(it);
445 return true;
446}
447
449 ESP_LOGD(TAG, "Erasing storage");
450 s_pending_save.clear();
451#ifdef USE_ESP32_RTC_PREFERENCES_STORAGE
452 // Invalidate RTC-backed preferences too (checksum will no longer match). current_rtc_offset_ is
453 // deliberately left alone: existing backends keep pointing at their allocated slots, and reset()
454 // is always followed by a restart (same reason nvs_handle is zeroed below).
455 memset(s_rtc_storage, 0, sizeof(s_rtc_storage));
456#endif
457
458 nvs_flash_deinit();
459 nvs_flash_erase();
460 // Make the handle invalid to prevent any saves until restart
461 this->nvs_handle = 0;
462 return true;
463}
464
465static ESP32Preferences s_preferences; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
466
467ESP32Preferences *get_preferences() { return &s_preferences; }
468
470 s_preferences.open();
471 global_preferences = &s_preferences;
472}
473
474} // namespace esphome::esp32
475
476namespace esphome {
477ESPPreferences *global_preferences; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
478} // namespace esphome
479
480#endif // USE_ESP32
Helper class for efficient buffer allocation - uses stack for small sizes, heap for large This is use...
Definition helpers.h:1019
Small buffer optimization - stores data inline when small, heap-allocates for large data This avoids ...
Definition helpers.h:255
size_t size() const
Definition helpers.h:322
bool load(uint8_t *data, size_t len)
bool save(const uint8_t *data, size_t len)
esp_err_t write_if_changed_(const NVSData &save, bool *changed)
Writes save unless NVS already holds it; *changed tells whether it wrote.
ESP32PreferenceBackend make_backend_(uint32_t type) const
ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)
bool load_from_key(uint32_t type, uint8_t *data, size_t len)
One-shot read of a stored preference by key, without allocating a backend.
ESPPreferenceObject make_rtc_preference_(size_t length, uint32_t type)
uint8_t type
const char * key
std::vector< uint8_t > & out
Definition gif.cpp:49
ESP32Preferences * get_preferences()
void setup_preferences()
ESPHOME_LOG_TAG(TAG, CRASH_LOG_TAG)
size_t rtc_pref_bytes_to_words(size_t bytes)
Round a byte count up to whole 32-bit words.
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
bool rtc_pref_decode(const uint32_t *buffer, uint32_t type, uint8_t length_words, uint8_t *data, size_t len)
Verify the checksum of a record held in buffer (length_words data words + 1 checksum word) and,...
ESPPreferences * global_preferences
void rtc_pref_encode(uint32_t *buffer, uint32_t type, uint8_t length_words, const uint8_t *data, size_t len)
Encode len data bytes into buffer (length_words data words + 1 trailing checksum word).
char * uint32_to_str_unchecked(char *buf, uint32_t val)
Write unsigned 32-bit integer to buffer (internal, no size check).
Definition helpers.cpp:445
int written
Definition helpers.h:1537
static void uint32_t
uint16_t length
Definition tt21100.cpp:0
spi_device_handle_t handle