ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
entity_base.cpp
Go to the documentation of this file.
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
8
9#include <new>
10
11namespace esphome {
12
13ESPHOME_LOG_TAG(TAG, "entity_base");
14
15#ifdef USE_ESP8266
16namespace {
17// RAM copies made by the deprecated get_name(), only for entities whose name is asked for. Remove before 2027.5.0
18struct NameCopy {
19 NameCopy *next;
20 const char *key;
21 StringRef ref;
22};
23NameCopy *name_copies = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
24const StringRef EMPTY_NAME;
25} // namespace
26
27const StringRef &EntityBase::get_name() const {
28 const char *key = this->name_.progmem_ptr();
29 for (NameCopy *copy = name_copies; copy != nullptr; copy = copy->next) {
30 if (copy->key == key)
31 return copy->ref;
32 }
33 size_t len = this->name_.size();
34 void *mem = malloc(sizeof(NameCopy) + len + 1); // NOLINT(cppcoreguidelines-no-malloc)
35 if (mem == nullptr)
36 return EMPTY_NAME;
37 char *buf = static_cast<char *>(mem) + sizeof(NameCopy);
38 this->name_.write_to(buf, len + 1);
39 name_copies = new (mem) NameCopy{name_copies, key, StringRef(buf, len)};
40 return name_copies->ref;
41}
42#endif
43
44void EntityBase::configure_entity_(const char *name, uint32_t object_id_hash, uint32_t entity_fields) {
45 this->name_ = ProgmemStringRef(name, ESPHOME_strlen_P(name));
46 if (this->name_.empty()) {
47 StringRef fallback;
48#ifdef USE_DEVICES
49 if (this->device_ != nullptr) {
50 fallback = StringRef(this->device_->get_name());
51 } else
52#endif
53 {
54 // Bug-for-bug compatibility with OLD behavior:
55 // - With MAC suffix: OLD code used App.get_friendly_name() directly (no fallback)
56 // - Without MAC suffix: OLD code used pre-computed object_id with fallback to device name
57 const auto &friendly = App.get_friendly_name();
59 // MAC suffix enabled - use friendly_name directly (even if empty) for compatibility
60 fallback = friendly;
61 } else {
62 // No MAC suffix - fallback to device name if friendly_name is empty
63 fallback = !friendly.empty() ? friendly : App.get_name();
64 }
65 }
66 this->name_ = ProgmemStringRef(fallback);
67 this->flags_.has_own_name = false;
68 // Dynamic name in RAM - hash it at runtime
69 this->object_id_hash_ = fnv1_hash_object_id(fallback.c_str(), fallback.size());
70 } else {
71 this->flags_.has_own_name = true;
72 // Static name - codegen precomputes the hash; external register_* callers may pass 0
73 if (object_id_hash == 0) {
74 // The name is in flash on ESP8266, so read it byte by byte through progmem_read_byte()
75 const char *name_p = this->name_.progmem_ptr();
76 object_id_hash = fnv1_hash_object_id(this->name_.size(), [name_p](size_t i) {
77 return static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(name_p + i)));
78 });
79 }
80 this->object_id_hash_ = object_id_hash;
81 }
82 // Unpack entity string table indices and flags from entity_fields.
83#ifdef USE_ENTITY_DEVICE_CLASS
84 this->device_class_idx_ = (entity_fields >> ENTITY_FIELD_DC_SHIFT) & 0xFF;
85#endif
86#ifdef USE_ENTITY_UNIT_OF_MEASUREMENT
87 this->uom_idx_ = (entity_fields >> ENTITY_FIELD_UOM_SHIFT) & 0xFF;
88#endif
89#ifdef USE_ENTITY_ICON
90 this->icon_idx_ = (entity_fields >> ENTITY_FIELD_ICON_SHIFT) & 0xFF;
91#endif
92 this->flags_.internal = (entity_fields >> ENTITY_FIELD_INTERNAL_SHIFT) & 1;
93 this->flags_.disabled_by_default = (entity_fields >> ENTITY_FIELD_DISABLED_BY_DEFAULT_SHIFT) & 1;
94 this->flags_.entity_category = (entity_fields >> ENTITY_FIELD_ENTITY_CATEGORY_SHIFT) & 0x3;
95}
96
97void EntityBase::set_internal(bool internal) {
98 // Remove the after-setup path in 2027.3.0 and ignore the call instead.
99 if (App.is_setup_complete()) {
100 ESP_LOGE(TAG, "'%s': set_internal() after setup is undefined behavior, stops working in 2027.3.0",
101 LOG_STR_ARG(this->get_log_name()));
102 }
103 this->flags_.internal = internal;
104}
105
106// Weak default lookup functions — overridden by generated code in main.cpp
107__attribute__((weak)) const char *entity_device_class_lookup(uint8_t) { return ""; }
108__attribute__((weak)) const char *entity_uom_lookup(uint8_t) { return ""; }
109__attribute__((weak)) const char *entity_icon_lookup(uint8_t) { return ""; }
110
111static ProgmemStringRef table_ref(const char *s) { return {s, ESPHOME_strlen_P(s)}; }
112
114#ifdef USE_ENTITY_DEVICE_CLASS
115 return table_ref(entity_device_class_lookup(this->device_class_idx_));
116#else
117 return {};
118#endif
119}
120
121const char *EntityBase::get_device_class_to([[maybe_unused]] std::span<char, MAX_DEVICE_CLASS_LENGTH> buffer) const {
122#ifdef USE_ESP8266
123 this->get_device_class_progmem().write_to(buffer.data(), buffer.size());
124 return buffer.data();
125#else
126 return this->get_device_class_progmem().progmem_ptr();
127#endif
128}
129
130// Entity unit of measurement (from index)
132#ifdef USE_ENTITY_UNIT_OF_MEASUREMENT
133 return StringRef(entity_uom_lookup(this->uom_idx_));
134#else
135 return StringRef(entity_uom_lookup(0));
136#endif
137}
139#ifdef USE_ENTITY_ICON
140 return table_ref(entity_icon_lookup(this->icon_idx_));
141#else
142 return {};
143#endif
144}
145
146const char *EntityBase::get_icon_to([[maybe_unused]] std::span<char, MAX_ICON_LENGTH> buffer) const {
147#ifdef USE_ESP8266
148 this->get_icon_progmem().write_to(buffer.data(), buffer.size());
149 return buffer.data();
150#else
151 return this->get_icon_progmem().progmem_ptr();
152#endif
153}
154
155size_t EntityBase::write_object_id_to(char *buf, size_t buf_size) const {
156 size_t len = this->write_name_to(buf, buf_size);
157 for (size_t i = 0; i < len; i++) {
158 buf[i] = to_sanitized_char(to_snake_case_char(buf[i]));
159 }
160 return len;
161}
162
163StringRef EntityBase::get_object_id_to(std::span<char, OBJECT_ID_MAX_LEN> buf) const {
164 size_t len = this->write_object_id_to(buf.data(), buf.size());
165 return StringRef(buf.data(), len);
166}
167
169 // The key hashes the sanitized object_id, so multiple entity names can collide on one
170 // key and overwrite each other's stored preferences ("Living Room" and "living_room",
171 // or two UTF-8 names that both sanitize to underscores). Keys hashed from the raw name
172 // fix this, but they change the entity key API clients track, which the Home Assistant
173 // esphome integration cannot handle yet. See: https://github.com/esphome/backlog/issues/85
174#pragma GCC diagnostic push
175#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
176 return this->get_preference_hash() ^ version;
177#pragma GCC diagnostic pop
178}
179
183
185 return global_preferences->make_preference(size, this->entity_preference_key_(version), in_flash);
186}
187
188bool log_entity_header(const char *tag, const char *prefix, const char *type, const EntityBase *obj) {
189 if (obj == nullptr)
190 return false;
191 ESP_LOGCONFIG(tag, "%s%s '%s'", prefix, type, LOG_STR_ARG(obj->get_log_name()));
192 return true;
193}
194
195#ifdef USE_ENTITY_ICON
196void log_entity_icon(const char *tag, const char *prefix, const EntityBase &obj) {
198 if (!icon.empty()) {
199 ESP_LOGCONFIG(tag, "%s Icon: '%s'", prefix, icon.progmem_ptr());
200 }
201}
202#endif
203
204void log_entity_device_class(const char *tag, const char *prefix, const EntityBase &obj) {
206 if (!dc.empty()) {
207 ESP_LOGCONFIG(tag, "%s Device Class: '%s'", prefix, dc.progmem_ptr());
208 }
209}
210
211void log_entity_unit_of_measurement(const char *tag, const char *prefix, const EntityBase &obj) {
212 if (!obj.get_unit_of_measurement_ref().empty()) {
213 ESP_LOGCONFIG(tag, "%s Unit of Measurement: '%s'", prefix, obj.get_unit_of_measurement_ref().c_str());
214 }
215}
216
217} // namespace esphome
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
bool is_name_add_mac_suffix_enabled() const
bool is_setup_complete() const
True once Application::setup() has finished walking all components and finalized the initial status f...
const char * get_name()
Definition device.h:22
struct esphome::EntityBase::EntityFlags flags_
ESPPreferenceObject make_entity_preference_(size_t size, uint32_t version)
Non-template helpers for make_entity_preference() to avoid code bloat.
const char * get_device_class_to(std::span< char, MAX_DEVICE_CLASS_LENGTH > buffer) const
ProgmemStringRef get_device_class_progmem() const
The device class as stored (in flash on ESP8266), for consumers that read flash themselves.
size_t write_name_to(char *buf, size_t buf_size) const
Copy the name into buf (null terminated), returns its length.
Definition entity_base.h:97
ProgmemStringRef name_
const char * get_icon_to(std::span< char, MAX_ICON_LENGTH > buffer) const
ProgmemStringRef get_icon_progmem() const
The icon as stored (in flash on ESP8266), for consumers that read flash themselves.
size_t write_object_id_to(char *buf, size_t buf_size) const
Write object_id directly to buffer, returns length written (excluding null) Useful for building compo...
uint32_t entity_preference_key_(uint32_t version)
Key for both helpers; preference hash migration goes here.
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
StringRef get_unit_of_measurement_ref() const
void configure_entity_(const char *name, uint32_t object_id_hash, uint32_t entity_fields)
Combined entity setup from codegen: set name, object_id hash, entity string indices,...
StringRef get_object_id_to(std::span< char, OBJECT_ID_MAX_LEN > buf) const
Get object_id with zero heap allocation For static case: returns StringRef to internal storage (buffe...
void set_internal(bool internal)
A string that may live in flash (on ESP8266): pointer and length, with no byte-reading operations.
Definition string_ref.h:230
constexpr const char * progmem_ptr() const
Definition string_ref.h:238
size_t write_to(char *buf, size_t buf_size) const
Copy into buf (null terminated, truncated to fit), returns the length copied.
Definition string_ref.h:243
constexpr size_t size() const
Definition string_ref.h:239
constexpr bool empty() const
Definition string_ref.h:240
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
constexpr const char * c_str() const
Definition string_ref.h:78
constexpr bool empty() const
Definition string_ref.h:81
constexpr size_type size() const
Definition string_ref.h:79
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
uint8_t type
StringRef ref
const char * key
NameCopy * next
uint32_t buffer
Definition gif.cpp:50
ESPHOME_LOG_TAG(TAG, CRASH_LOG_TAG)
bool log_entity_header(const char *tag, const char *prefix, const char *type, const EntityBase *obj)
Log "<prefix><type> '<name>'" for a dump_config header; returns false when obj is null.
void log_entity_icon(const char *tag, const char *prefix, const EntityBase &obj)
constexpr char to_sanitized_char(char c)
Sanitize a single char: keep alphanumerics, dashes, underscores; replace others with underscore.
Definition helpers.h:1186
void log_entity_unit_of_measurement(const char *tag, const char *prefix, const EntityBase &obj)
const char * entity_device_class_lookup(uint8_t index)
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:34
ESPPreferences * global_preferences
uint32_t fnv1_hash_object_id(size_t len, ReadByte read_byte)
Calculate FNV-1 hash of a string while applying snake_case + sanitize transformations.
Definition helpers.h:1211
const char * entity_uom_lookup(uint8_t index)
const char * entity_icon_lookup(uint8_t index)
constexpr char to_snake_case_char(char c)
Convert a single char to snake_case: lowercase and space to underscore.
Definition helpers.h:1183
Application App
Global storage of Application pointer - only one Application can exist.
void log_entity_device_class(const char *tag, const char *prefix, const EntityBase &obj)
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24