ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
entity_base.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4#include <span>
5#include <string>
6#include "string_ref.h"
7#include "helpers.h"
8#include "log.h"
9#include "preferences.h"
10
11#ifdef USE_DEVICES
12#include "device.h"
13#endif
14
15// Forward declarations for friend access from codegen-generated setup()
16void setup(); // NOLINT(readability-redundant-declaration) - may be declared in Arduino.h
17void original_setup(); // NOLINT(readability-redundant-declaration) - used by cpp unit tests
18
19namespace esphome {
20
21// Extern lookup functions for entity string tables.
22// Generated code provides strong definitions; weak defaults return "".
23extern const char *entity_device_class_lookup(uint8_t index);
24extern const char *entity_uom_lookup(uint8_t index);
25extern const char *entity_icon_lookup(uint8_t index);
26
27// Maximum device name length - keep in sync with validate_hostname() in esphome/core/config.py
28static constexpr size_t ESPHOME_DEVICE_NAME_MAX_LEN = 31;
29
30// Maximum friendly name length for entities and sub-devices - keep in sync with FRIENDLY_NAME_MAX_LEN in
31// esphome/core/config.py
32static constexpr size_t ESPHOME_FRIENDLY_NAME_MAX_LEN = 120;
33
34// Maximum domain length (longest: "alarm_control_panel" = 19)
35static constexpr size_t ESPHOME_DOMAIN_MAX_LEN = 20;
36
37// Maximum size for object_id buffer (friendly_name + null + margin)
38static constexpr size_t OBJECT_ID_MAX_LEN = 128;
39
40// Maximum state length that Home Assistant will accept without raising ValueError
41static constexpr size_t MAX_STATE_LEN = 255;
42
43// Maximum device class string buffer size (47 chars + null terminator)
44// Longest standard device class: "volatile_organic_compounds_parts" (32 chars)
45// Device classes are stored in PROGMEM; on ESP8266 they must be copied to a stack buffer.
46static constexpr size_t MAX_DEVICE_CLASS_LENGTH = 48;
47
48// Maximum icon string buffer size (63 chars + null terminator)
49// Icons are stored in PROGMEM; on ESP8266 they must be copied to a stack buffer.
50static constexpr size_t MAX_ICON_LENGTH = 64;
51
57
58// Bit layout for entity_fields parameter in configure_entity_().
59// Keep in sync with _*_SHIFT constants in esphome/core/entity_helpers.py
60static constexpr uint8_t ENTITY_FIELD_DC_SHIFT = 0;
61static constexpr uint8_t ENTITY_FIELD_UOM_SHIFT = 8;
62static constexpr uint8_t ENTITY_FIELD_ICON_SHIFT = 16;
63static constexpr uint8_t ENTITY_FIELD_INTERNAL_SHIFT = 24;
64static constexpr uint8_t ENTITY_FIELD_DISABLED_BY_DEFAULT_SHIFT = 25;
65static constexpr uint8_t ENTITY_FIELD_ENTITY_CATEGORY_SHIFT = 26;
66
67// The generic Entity base class that provides an interface common to all Entities.
69 public:
70 // Get the name of this Entity
71 const StringRef &get_name() const { return this->name_; }
72
73 // Get whether this Entity has its own name or it should use the device friendly_name.
74 bool has_own_name() const { return this->flags_.has_own_name; }
75
76 // Get the unique Object ID of this Entity
78
82 StringRef get_object_id_to(std::span<char, OBJECT_ID_MAX_LEN> buf) const;
83
86 size_t write_object_id_to(char *buf, size_t buf_size) const;
87
88 // Get whether this Entity should be hidden outside ESPHome
89 bool is_internal() const { return this->flags_.internal; }
90
91 // Deprecated: Calling set_internal() at runtime is undefined behavior. Components and clients
92 // are NOT notified of the change, the flag may have already been read during setup, and there
93 // is NO guarantee any consumer will observe the new value. Use the 'internal:' YAML key instead.
94 ESPDEPRECATED("set_internal() is undefined behavior at runtime — components and Home Assistant are NOT "
95 "notified. Use the 'internal:' YAML key instead. Will be removed in 2027.3.0.",
96 "2026.3.0")
97 void set_internal(bool internal) { this->flags_.internal = internal; }
98
99 // Check if this object is declared to be disabled by default.
100 // That means that when the device gets added to Home Assistant (or other clients) it should
101 // not be added to the default view by default, and a user action is necessary to manually add it.
102 bool is_disabled_by_default() const { return this->flags_.disabled_by_default; }
103
104 // Get the entity category.
106
107 // Get this entity's device class into a stack buffer.
108 // On non-ESP8266: returns pointer to PROGMEM string directly (buffer unused).
109 // On ESP8266: copies from PROGMEM to buffer, returns buffer pointer.
110 const char *get_device_class_to(std::span<char, MAX_DEVICE_CLASS_LENGTH> buffer) const;
111
112#ifdef USE_ESP8266
113 // On ESP8266, rodata is RAM. Device classes are in PROGMEM and cannot be accessed
114 // directly as const char*. Use get_device_class_to() with a stack buffer instead.
115 template<typename T = int> StringRef get_device_class_ref() const {
116 static_assert(sizeof(T) == 0, "get_device_class_ref() unavailable on ESP8266 (rodata is RAM). "
117 "Use get_device_class_to() with a stack buffer.");
118 return StringRef("");
119 }
120 template<typename T = int> std::string get_device_class() const {
121 static_assert(sizeof(T) == 0, "get_device_class() unavailable on ESP8266 (rodata is RAM). "
122 "Use get_device_class_to() with a stack buffer.");
123 return "";
124 }
125#else
126 // Deprecated: use get_device_class_to() instead. Device classes are in PROGMEM.
127 ESPDEPRECATED("Use get_device_class_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0")
129 ESPDEPRECATED("Use get_device_class_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0")
130 std::string get_device_class() const;
131#endif
132 // Get unit of measurement as StringRef (from packed index)
135 ESPDEPRECATED("Use get_unit_of_measurement_ref() instead for better performance (avoids string copy). Will be "
136 "removed in ESPHome 2026.9.0",
137 "2026.3.0")
138 std::string get_unit_of_measurement() const;
139
140 // Get this entity's icon into a stack buffer.
141 // On ESP32: returns pointer to PROGMEM string directly (buffer unused).
142 // On ESP8266: copies from PROGMEM to buffer, returns buffer pointer.
143 const char *get_icon_to(std::span<char, MAX_ICON_LENGTH> buffer) const;
144
145#ifdef USE_ESP8266
146 // On ESP8266, rodata is RAM. Icons are in PROGMEM and cannot be accessed
147 // directly as const char*. Use get_icon_to() with a stack buffer instead.
148 template<typename T = int> StringRef get_icon_ref() const {
149 static_assert(sizeof(T) == 0,
150 "get_icon_ref() unavailable on ESP8266 (rodata is RAM). Use get_icon_to() with a stack buffer.");
151 return StringRef("");
152 }
153 template<typename T = int> std::string get_icon() const {
154 static_assert(sizeof(T) == 0,
155 "get_icon() unavailable on ESP8266 (rodata is RAM). Use get_icon_to() with a stack buffer.");
156 return "";
157 }
158#else
159 // Deprecated: use get_icon_to() instead. Icons are in PROGMEM.
160 ESPDEPRECATED("Use get_icon_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0")
161 StringRef get_icon_ref() const;
162 ESPDEPRECATED("Use get_icon_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0")
163 std::string get_icon() const;
164#endif
165
166#ifdef USE_DEVICES
167 // Get this entity's device id
169 if (this->device_ == nullptr) {
170 return 0; // No device set, return 0
171 }
172 return this->device_->get_device_id();
173 }
174 // Get the device this entity belongs to (nullptr if main device)
175 Device *get_device() const { return this->device_; }
176#endif
177
178 // Check if this entity has state
179 bool has_state() const { return this->flags_.has_state; }
180
181 // Set has_state - for components that need to manually set this
182 void set_has_state(bool state) { this->flags_.has_state = state; }
183
203 ESPDEPRECATED("Use make_entity_preference<T>() instead, or preferences won't be migrated. "
204 "See https://github.com/esphome/backlog/issues/85. Will be removed in 2027.1.0.",
205 "2026.7.0")
206 uint32_t get_preference_hash() {
207#ifdef USE_DEVICES
208 // Combine object_id_hash with device_id to ensure uniqueness across devices
209 // Note: device_id is 0 for the main device, so XORing with 0 preserves the original hash
210 // This ensures backward compatibility for existing single-device configurations
211 return this->get_object_id_hash() ^ this->get_device_id();
212#else
213 // Without devices, just use object_id_hash as before
214 return this->get_object_id_hash();
215#endif
216 }
217
221 template<typename T> ESPPreferenceObject make_entity_preference(uint32_t version = 0) {
222 static_assert(std::is_trivially_copyable<T>::value, "T must be trivially copyable");
223 return this->make_entity_preference_(sizeof(T), version);
224 }
225
226 protected:
227 friend void ::setup();
228 friend void ::original_setup();
229 // Application's register_<entity>(obj, name, hash, fields) overloads call configure_entity_
230 // before push_back, so codegen can emit a single combined call per entity.
231 friend class Application;
232
235 void configure_entity_(const char *name, uint32_t object_id_hash, uint32_t entity_fields);
236
237#ifdef USE_DEVICES
238 // Codegen-only setter — only accessible from setup() via friend declaration.
239 void set_device_(Device *device) { this->device_ = device; }
240#endif
241
245
246 void calc_object_id_();
247
250#ifdef USE_DEVICES
252#endif
253
254 // Bit-packed flags to save memory (1 byte instead of 5)
255 struct EntityFlags {
256 uint8_t has_own_name : 1;
257 uint8_t internal : 1;
259 uint8_t has_state : 1;
260 uint8_t entity_category : 2; // Supports up to 4 categories
261 uint8_t reserved : 2; // Reserved for future use
263 // String table indices — packed into the 3 padding bytes after flags_
264#ifdef USE_ENTITY_DEVICE_CLASS
266#endif
267#ifdef USE_ENTITY_UNIT_OF_MEASUREMENT
268 uint8_t uom_idx_{};
269#endif
270#ifdef USE_ENTITY_ICON
271 uint8_t icon_idx_{};
272#endif
273};
274
276#ifdef USE_ENTITY_ICON
277#define LOG_ENTITY_ICON(tag, prefix, obj) log_entity_icon(tag, prefix, obj)
278void log_entity_icon(const char *tag, const char *prefix, const EntityBase &obj);
279#else
280#define LOG_ENTITY_ICON(tag, prefix, obj) ((void) 0)
281inline void log_entity_icon(const char *, const char *, const EntityBase &) {}
282#endif
284#define LOG_ENTITY_DEVICE_CLASS(tag, prefix, obj) log_entity_device_class(tag, prefix, obj)
285void log_entity_device_class(const char *tag, const char *prefix, const EntityBase &obj);
287#define LOG_ENTITY_UNIT_OF_MEASUREMENT(tag, prefix, obj) log_entity_unit_of_measurement(tag, prefix, obj)
288void log_entity_unit_of_measurement(const char *tag, const char *prefix, const EntityBase &obj);
289
313template<typename T> class StatefulEntityBase : public EntityBase {
314 public:
316 virtual const T &get_state() const = 0;
318 T get_state_default(T default_value) const { return this->has_state() ? this->get_state() : default_value; }
320 void invalidate_state() { this->set_new_state({}); }
321
322 template<typename F> void add_full_state_callback(F &&callback) {
323 this->full_state_callbacks_.add(std::forward<F>(callback));
324 }
325 template<typename F> void add_on_state_callback(F &&callback) {
326 this->state_callbacks_.add(std::forward<F>(callback));
327 }
328
329 protected:
331 virtual bool get_trigger_on_initial_state() const = 0;
332
339 virtual bool set_new_state(const optional<T> &new_state) {
340 // Access flags_ directly to avoid function call overhead in this hot path
341 bool had_state = this->flags_.has_state;
342 // Use pointer to avoid requiring T to be default-constructible
343 const T *current = had_state ? &this->get_state() : nullptr;
344 if (new_state.has_value()) {
345 if (current != nullptr && *current == new_state.value())
346 return false; // same value, no change
347 } else if (!had_state) {
348 return false; // already invalidated, no change
349 }
350 // Capture old_state before set_state_value — current pointer aliases subclass storage
351 bool has_full_cbs = !this->full_state_callbacks_.empty();
352 optional<T> old_state;
353 if (has_full_cbs)
354 old_state = current != nullptr ? optional<T>(*current) : nullopt;
355 // Update storage before firing callbacks so callback code can inspect current state
356 this->flags_.has_state = new_state.has_value();
357 if (new_state.has_value()) {
358 this->set_state_value(new_state.value());
359 }
360 if (has_full_cbs)
361 this->full_state_callbacks_.call(old_state, new_state);
362 // had_state first: on every change except the first, skips the virtual call
363 if (new_state.has_value() && (had_state || this->get_trigger_on_initial_state()))
364 this->state_callbacks_.call(new_state.value());
365 return true;
366 }
368 virtual void set_state_value(const T &value) = 0;
369 LazyCallbackManager<void(optional<T> previous, optional<T> current)> full_state_callbacks_;
371};
372} // namespace esphome
uint32_t get_device_id()
Definition device.h:8
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
bool has_own_name() const
Definition entity_base.h:74
bool is_internal() const
Definition entity_base.h:89
ESPDEPRECATED("Use get_device_class_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0") StringRef get_device_class_ref() const
StringRef get_icon_ref() const
std::string get_device_class() const
const StringRef & get_name() const
Definition entity_base.h:71
ESPDEPRECATED("Use get_unit_of_measurement_ref() instead for better performance (avoids string copy). Will be " "removed in ESPHome 2026.9.0", "2026.3.0") std const char * get_icon_to(std::span< char, MAX_ICON_LENGTH > buffer) const
Get the unit of measurement as std::string (deprecated, prefer get_unit_of_measurement_ref())
void set_device_(Device *device)
uint32_t get_object_id_hash() const
Definition entity_base.h:77
std::string get_icon() const
ESPDEPRECATED("Use get_icon_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0") std uint32_t get_device_id() 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...
ESPDEPRECATED("Use make_entity_preference<T>() instead, or preferences won't be migrated. " "See https://github.com/esphome/backlog/issues/85. Will be removed in 2027.1.0.", "2026.7.0") uint32_t get_preference_hash()
Get a unique hash for storing preferences/settings for this entity.
bool is_disabled_by_default() const
StringRef get_device_class_ref() const
ESPDEPRECATED("set_internal() is undefined behavior at runtime — components and Home Assistant are NOT " "notified. Use the 'internal:' YAML key instead. Will be removed in 2027.3.0.", "2026.3.0") void set_internal(bool internal)
Definition entity_base.h:94
ESPPreferenceObject make_entity_preference(uint32_t version=0)
Create a preference object for storing this entity's state/settings.
ESPDEPRECATED("Use get_icon_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0") StringRef get_icon_ref() const
ESPDEPRECATED("Use get_device_class_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0") std StringRef get_unit_of_measurement_ref() const
Device * get_device() const
void set_has_state(bool state)
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,...
bool has_state() const
EntityCategory get_entity_category() const
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...
Base class for entities that track a typed state value with change-detection and callbacks.
virtual bool get_trigger_on_initial_state() const =0
Subclasses return whether callbacks should fire on the very first state.
virtual const T & get_state() const =0
Return the current state value. Only valid when has_state() is true.
virtual bool set_new_state(const optional< T > &new_state)
Apply a new state, de-duplicating and firing callbacks as needed.
void add_full_state_callback(F &&callback)
virtual void set_state_value(const T &value)=0
Subclasses implement this to store the actual value into their own storage.
void invalidate_state()
Clear the state — sets has_state() to false and fires callbacks with nullopt.
LazyCallbackManager< void(T)> state_callbacks_
void add_on_state_callback(F &&callback)
T get_state_default(T default_value) const
Return the current state if available, otherwise return the provided default.
LazyCallbackManager< void(optional< T > previous, optional< T > current)> full_state_callbacks_
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
void original_setup()
void setup()
bool state
Definition fan.h:2
const char * tag
Definition log.h:74
void log_entity_icon(const char *tag, const char *prefix, const EntityBase &obj)
void log_entity_unit_of_measurement(const char *tag, const char *prefix, const EntityBase &obj)
const char * entity_device_class_lookup(uint8_t index)
uint16_t size
Definition helpers.cpp:25
@ ENTITY_CATEGORY_NONE
Definition entity_base.h:53
@ ENTITY_CATEGORY_CONFIG
Definition entity_base.h:54
@ ENTITY_CATEGORY_DIAGNOSTIC
Definition entity_base.h:55
const char * entity_uom_lookup(uint8_t index)
const char * entity_icon_lookup(uint8_t index)
void log_entity_device_class(const char *tag, const char *prefix, const EntityBase &obj)
STL namespace.
static void uint32_t