ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
preferences_rtc.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <cstring>
6
7namespace esphome {
8
9// Shared storage format for word-addressable preference backends.
10//
11// Several platforms persist preferences as a buffer of 32-bit words followed by a
12// single checksum word, seeded with the preference's `type` (its hashed key). This
13// format is used for RTC user memory (ESP8266, ESP32) and for the ESP8266
14// flash-emulation buffer. The helpers here are platform independent; each backend
15// supplies its own word read/write primitives and offset allocation.
16
18inline size_t rtc_pref_bytes_to_words(size_t bytes) { return (bytes + 3) / 4; }
19
24template<class It> uint32_t rtc_pref_calculate_checksum(It first, It last, uint32_t type) {
26 while (first != last) {
27 // UINT32_C keeps the multiply wrapping at 32 bits regardless of the width of
28 // unsigned long, so 64-bit host builds compute the same value as the devices.
29 checksum ^= (*first++ * UINT32_C(2654435769)) >> 1;
30 }
31 return checksum;
32}
33
37inline void rtc_pref_encode(uint32_t *buffer, uint32_t type, uint8_t length_words, const uint8_t *data, size_t len) {
38 memset(buffer, 0, (static_cast<size_t>(length_words) + 1) * sizeof(uint32_t));
39 memcpy(buffer, data, len);
40 buffer[length_words] = rtc_pref_calculate_checksum(buffer, buffer + length_words, type);
41}
42
46inline bool rtc_pref_decode(const uint32_t *buffer, uint32_t type, uint8_t length_words, uint8_t *data, size_t len) {
47 if (buffer[length_words] != rtc_pref_calculate_checksum(buffer, buffer + length_words, type)) {
48 return false;
49 }
50 memcpy(data, buffer, len);
51 return true;
52}
53
54} // namespace esphome
uint8_t checksum
Definition bl0906.h:3
uint16_t type
size_t rtc_pref_bytes_to_words(size_t bytes)
Round a byte count up to whole 32-bit words.
const void size_t len
Definition hal.h:64
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,...
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).
uint32_t rtc_pref_calculate_checksum(It first, It last, uint32_t type)
Compute the integrity checksum over [first, last), seeded with type.
static void uint32_t