ESPHome 2026.10.0
Loading...
Searching...
No Matches
entity_base.cpp
Go to the documentation of this file.
4#include "esphome/core/log.h"
7
8namespace esphome {
9
10ESPHOME_LOG_TAG(TAG, "entity_base");
11
12void EntityBase::configure_entity_(const char *name, uint32_t object_id_hash, uint32_t entity_fields) {
13 this->name_ = StringRef(name);
14 if (this->name_.empty()) {
15#ifdef USE_DEVICES
16 if (this->device_ != nullptr) {
17 this->name_ = StringRef(this->device_->get_name());
18 } else
19#endif
20 {
21 // Bug-for-bug compatibility with OLD behavior:
22 // - With MAC suffix: OLD code used App.get_friendly_name() directly (no fallback)
23 // - Without MAC suffix: OLD code used pre-computed object_id with fallback to device name
24 const auto &friendly = App.get_friendly_name();
26 // MAC suffix enabled - use friendly_name directly (even if empty) for compatibility
27 this->name_ = friendly;
28 } else {
29 // No MAC suffix - fallback to device name if friendly_name is empty
30 this->name_ = !friendly.empty() ? friendly : App.get_name();
31 }
32 }
33 this->flags_.has_own_name = false;
34 // Dynamic name - must calculate hash at runtime
35 this->calc_object_id_();
36 } else {
37 this->flags_.has_own_name = true;
38 // Static name - use pre-computed hash if provided
39 if (object_id_hash != 0) {
40 this->object_id_hash_ = object_id_hash;
41 } else {
42 this->calc_object_id_();
43 }
44 }
45 // Unpack entity string table indices and flags from entity_fields.
46#ifdef USE_ENTITY_DEVICE_CLASS
47 this->device_class_idx_ = (entity_fields >> ENTITY_FIELD_DC_SHIFT) & 0xFF;
48#endif
49#ifdef USE_ENTITY_UNIT_OF_MEASUREMENT
50 this->uom_idx_ = (entity_fields >> ENTITY_FIELD_UOM_SHIFT) & 0xFF;
51#endif
52#ifdef USE_ENTITY_ICON
53 this->icon_idx_ = (entity_fields >> ENTITY_FIELD_ICON_SHIFT) & 0xFF;
54#endif
55 this->flags_.internal = (entity_fields >> ENTITY_FIELD_INTERNAL_SHIFT) & 1;
56 this->flags_.disabled_by_default = (entity_fields >> ENTITY_FIELD_DISABLED_BY_DEFAULT_SHIFT) & 1;
57 this->flags_.entity_category = (entity_fields >> ENTITY_FIELD_ENTITY_CATEGORY_SHIFT) & 0x3;
58}
59
60void EntityBase::set_internal(bool internal) {
61 // Remove the after-setup path in 2027.3.0 and ignore the call instead.
62 if (App.is_setup_complete()) {
63 ESP_LOGE(TAG, "'%s': set_internal() after setup is undefined behavior, stops working in 2027.3.0",
64 this->get_name().c_str());
65 }
66 this->flags_.internal = internal;
67}
68
69// Weak default lookup functions — overridden by generated code in main.cpp
70__attribute__((weak)) const char *entity_device_class_lookup(uint8_t) { return ""; }
71__attribute__((weak)) const char *entity_uom_lookup(uint8_t) { return ""; }
72__attribute__((weak)) const char *entity_icon_lookup(uint8_t) { return ""; }
73
74// Entity device class — buffer-based API for PROGMEM safety on ESP8266
75const char *EntityBase::get_device_class_to([[maybe_unused]] std::span<char, MAX_DEVICE_CLASS_LENGTH> buffer) const {
76#ifdef USE_ENTITY_DEVICE_CLASS
77 const uint8_t idx = this->device_class_idx_;
78#else
79 const uint8_t idx = 0;
80#endif
81#ifdef USE_ESP8266
82 if (idx == 0)
83 return "";
84 const char *dc = entity_device_class_lookup(idx);
85 ESPHOME_strncpy_P(buffer.data(), dc, buffer.size() - 1);
86 buffer[buffer.size() - 1] = '\0';
87 return buffer.data();
88#else
90#endif
91}
92
93// Entity unit of measurement (from index)
95#ifdef USE_ENTITY_UNIT_OF_MEASUREMENT
97#else
99#endif
100}
101// Entity icon — buffer-based API for PROGMEM safety on ESP8266
102const char *EntityBase::get_icon_to([[maybe_unused]] std::span<char, MAX_ICON_LENGTH> buffer) const {
103#ifdef USE_ENTITY_ICON
104 const uint8_t idx = this->icon_idx_;
105#else
106 const uint8_t idx = 0;
107#endif
108#ifdef USE_ESP8266
109 if (idx == 0)
110 return "";
111 const char *icon = entity_icon_lookup(idx);
112 ESPHOME_strncpy_P(buffer.data(), icon, buffer.size() - 1);
113 buffer[buffer.size() - 1] = '\0';
114 return buffer.data();
115#else
116 return entity_icon_lookup(idx);
117#endif
118}
119
120// Calculate Object ID Hash directly from name using snake_case + sanitize
122 this->object_id_hash_ = fnv1_hash_object_id(this->name_.c_str(), this->name_.size());
123}
124
125size_t EntityBase::write_object_id_to(char *buf, size_t buf_size) const {
126 size_t len = std::min(this->name_.size(), buf_size - 1);
127 for (size_t i = 0; i < len; i++) {
128 buf[i] = to_sanitized_char(to_snake_case_char(this->name_[i]));
129 }
130 buf[len] = '\0';
131 return len;
132}
133
134StringRef EntityBase::get_object_id_to(std::span<char, OBJECT_ID_MAX_LEN> buf) const {
135 size_t len = this->write_object_id_to(buf.data(), buf.size());
136 return StringRef(buf.data(), len);
137}
138
140 // The key hashes the sanitized object_id, so multiple entity names can collide on one
141 // key and overwrite each other's stored preferences ("Living Room" and "living_room",
142 // or two UTF-8 names that both sanitize to underscores). Keys hashed from the raw name
143 // fix this, but they change the entity key API clients track, which the Home Assistant
144 // esphome integration cannot handle yet. See: https://github.com/esphome/backlog/issues/85
145#pragma GCC diagnostic push
146#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
147 uint32_t key = this->get_preference_hash() ^ version;
148#pragma GCC diagnostic pop
150}
151
152#ifdef USE_ENTITY_ICON
153void log_entity_icon(const char *tag, const char *prefix, const EntityBase &obj) {
154 char icon_buf[MAX_ICON_LENGTH];
155 const char *icon = obj.get_icon_to(icon_buf);
156 if (icon[0] != '\0') {
157 ESP_LOGCONFIG(tag, "%s Icon: '%s'", prefix, icon);
158 }
159}
160#endif
161
162void log_entity_device_class(const char *tag, const char *prefix, const EntityBase &obj) {
163 char dc_buf[MAX_DEVICE_CLASS_LENGTH];
164 const char *dc = obj.get_device_class_to(dc_buf);
165 if (dc[0] != '\0') {
166 ESP_LOGCONFIG(tag, "%s Device Class: '%s'", prefix, dc);
167 }
168}
169
170void log_entity_unit_of_measurement(const char *tag, const char *prefix, const EntityBase &obj) {
171 if (!obj.get_unit_of_measurement_ref().empty()) {
172 ESP_LOGCONFIG(tag, "%s Unit of Measurement: '%s'", prefix, obj.get_unit_of_measurement_ref().c_str());
173 }
174}
175
176} // 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:10
struct esphome::EntityBase::EntityFlags flags_
ESPPreferenceObject make_entity_preference_(size_t size, uint32_t version)
Non-template helper for make_entity_preference() to avoid code bloat.
const char * get_device_class_to(std::span< char, MAX_DEVICE_CLASS_LENGTH > buffer) const
const StringRef & get_name() const
Definition entity_base.h:71
const char * get_icon_to(std::span< char, MAX_ICON_LENGTH > buffer) const
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...
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)
StringRef is a reference to a string owned by something else.
Definition string_ref.h:30
constexpr const char * c_str() const
Definition string_ref.h:77
constexpr bool empty() const
Definition string_ref.h:80
constexpr size_type size() const
Definition string_ref.h:78
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
uint32_t buffer
Definition gif.cpp:50
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:1117
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:64
uint16_t size
Definition helpers.cpp:33
ESPPreferences * global_preferences
uint32_t fnv1_hash_object_id(const char *str, size_t len)
Calculate FNV-1 hash of a string while applying snake_case + sanitize transformations.
Definition helpers.h:1143
const char * entity_uom_lookup(uint8_t index)
ESPHOME_LOG_TAG(TAG, "app")
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:1113
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