ESPHome 2026.4.0-dev
Loading...
Searching...
No Matches
preference_backend.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4
7
8// Include the concrete preference backend for the active platform.
9// Each header defines its backend class, forward-declares its manager class,
10// declares get_preferences(), and provides the PreferenceBackend alias.
11#ifdef USE_ESP32
13#elif defined(USE_ESP8266)
15#elif defined(USE_RP2040)
17#elif defined(USE_LIBRETINY)
19#elif defined(USE_HOST)
21#elif defined(USE_ZEPHYR) && defined(CONFIG_SETTINGS)
23#endif
24
25namespace esphome {
26
27#if !defined(USE_ESP32) && !defined(USE_ESP8266) && !defined(USE_RP2040) && !defined(USE_LIBRETINY) && \
28 !defined(USE_HOST) && !(defined(USE_ZEPHYR) && defined(CONFIG_SETTINGS))
29// Stub for static analysis when no platform is defined.
31 bool save(const uint8_t *, size_t) { return false; }
32 bool load(uint8_t *, size_t) { return false; }
33};
34#endif
35
37
39 public:
41 explicit ESPPreferenceObject(PreferenceBackend *backend) : backend_(backend) {}
42
43 template<typename T> bool save(const T *src) {
44 if (this->backend_ == nullptr)
45 return false;
46 return this->backend_->save(reinterpret_cast<const uint8_t *>(src), sizeof(T));
47 }
48
49 template<typename T> bool load(T *dest) {
50 if (this->backend_ == nullptr)
51 return false;
52 return this->backend_->load(reinterpret_cast<uint8_t *>(dest), sizeof(T));
53 }
54
55 protected:
57};
58
61template<typename Derived> class PreferencesMixin {
62 public:
63 template<typename T, enable_if_t<is_trivially_copyable<T>::value, bool> = true>
65 return static_cast<Derived *>(this)->make_preference(sizeof(T), type, in_flash);
66 }
67
68 template<typename T, enable_if_t<is_trivially_copyable<T>::value, bool> = true>
70 return static_cast<Derived *>(this)->make_preference(sizeof(T), type);
71 }
72};
73
74// Macro for platform preferences.h headers to declare the standard aliases.
75// Must be used at file scope (outside any namespace).
76#define DECLARE_PREFERENCE_ALIASES(platform_class) \
77 namespace esphome { \
78 using Preferences = platform_class; \
79 using ESPPreferences = Preferences; \
80 extern ESPPreferences *global_preferences; /* NOLINT(cppcoreguidelines-avoid-non-const-global-variables) */ \
81 }
82
83} // namespace esphome
ESPPreferenceObject(PreferenceBackend *backend)
CRTP mixin providing type-safe template make_preference<T>() helpers.
ESPPreferenceObject make_preference(uint32_t type)
ESPPreferenceObject make_preference(uint32_t type, bool in_flash)
uint16_t type
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
esp32::ESP32PreferenceBackend PreferenceBackend
static void uint32_t
bool save(const uint8_t *, size_t)
bool load(uint8_t *, size_t)