ESPHome 2026.9.0
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 // Set whether this Entity should be hidden outside ESPHome. Prefer the 'internal:' YAML key
92 // whenever possible: it is guaranteed and has none of the limitations below. Use this only when
93 // the decision can only be made at boot. Must be called before MQTT and the API read the flag:
94 // from on_boot at the default priority, or a setup() that runs above setup_priority::AFTER_WIFI.
95 // If the answer comes from a device handshake, hold setup with can_proceed() until it arrives.
96 // Calls after setup finishes are undefined behavior: the flag is still written and an error is
97 // logged, and from 2027.3.0 the call will be ignored.
98 //
99 // Known limitations. Not bugs, so no issue reports please; a PR that removes one with no RAM
100 // or performance cost would be considered.
101 // - No consumer is notified of a change, so the flag can only be decided once per boot.
102 // - The guard is coarse: a call from a priority below AFTER_WIFI (an on_boot with a low priority,
103 // or a setup() at LATE) still passes, but the API camera listener is already registered, MQTT
104 // (AFTER_CONNECTION) has cached the flag, and an API client that connected while setup was
105 // stalled on a slow component has already listed the entities, so they keep the old value.
106 // - Un-hiding an entity declared 'internal: true' in YAML skips the duplicate name check that
107 // codegen runs for exposed entities, so a name collision can surface at runtime. Entities with
108 // only an 'id:' are forced internal and use the id as their name.
109 // - Zigbee codegen skips YAML internal entities entirely, so un-hiding cannot add them to Zigbee.
110 void set_internal(bool internal);
111
112 // Check if this object is declared to be disabled by default.
113 // That means that when the device gets added to Home Assistant (or other clients) it should
114 // not be added to the default view by default, and a user action is necessary to manually add it.
115 bool is_disabled_by_default() const { return this->flags_.disabled_by_default; }
116
117 // Get the entity category.
119
120 // Get this entity's device class into a stack buffer.
121 // On non-ESP8266: returns pointer to PROGMEM string directly (buffer unused).
122 // On ESP8266: copies from PROGMEM to buffer, returns buffer pointer.
123 const char *get_device_class_to(std::span<char, MAX_DEVICE_CLASS_LENGTH> buffer) const;
124
125 // Get unit of measurement as StringRef (from packed index)
127
128 // Get this entity's icon into a stack buffer.
129 // On ESP32: returns pointer to PROGMEM string directly (buffer unused).
130 // On ESP8266: copies from PROGMEM to buffer, returns buffer pointer.
131 const char *get_icon_to(std::span<char, MAX_ICON_LENGTH> buffer) const;
132
133#ifdef USE_DEVICES
134 // Get this entity's device id
136 if (this->device_ == nullptr) {
137 return 0; // No device set, return 0
138 }
139 return this->device_->get_device_id();
140 }
141 // Get the device this entity belongs to (nullptr if main device)
142 Device *get_device() const { return this->device_; }
143#endif
144
145 // Check if this entity has state
146 bool has_state() const { return this->flags_.has_state; }
147
148 // Set has_state - for components that need to manually set this
149 void set_has_state(bool state) { this->flags_.has_state = state; }
150
170 ESPDEPRECATED("Use make_entity_preference<T>() instead, or preferences won't be migrated. "
171 "See https://github.com/esphome/backlog/issues/85. Will be removed in 2027.1.0.",
172 "2026.7.0")
173 uint32_t get_preference_hash() {
174#ifdef USE_DEVICES
175 // Combine object_id_hash with device_id to ensure uniqueness across devices
176 // Note: device_id is 0 for the main device, so XORing with 0 preserves the original hash
177 // This ensures backward compatibility for existing single-device configurations
178 return this->get_object_id_hash() ^ this->get_device_id();
179#else
180 // Without devices, just use object_id_hash as before
181 return this->get_object_id_hash();
182#endif
183 }
184
188 template<typename T> ESPPreferenceObject make_entity_preference(uint32_t version = 0) {
189 static_assert(std::is_trivially_copyable<T>::value, "T must be trivially copyable");
190 return this->make_entity_preference_(sizeof(T), version);
191 }
192
193 protected:
194 friend void ::setup();
195 friend void ::original_setup();
196 // Application's register_<entity>(obj, name, hash, fields) overloads call configure_entity_
197 // before push_back, so codegen can emit a single combined call per entity.
198 friend class Application;
199
202 void configure_entity_(const char *name, uint32_t object_id_hash, uint32_t entity_fields);
203
204#ifdef USE_DEVICES
205 // Codegen-only setter — only accessible from setup() via friend declaration.
206 void set_device_(Device *device) { this->device_ = device; }
207#endif
208
212
213 void calc_object_id_();
214
217#ifdef USE_DEVICES
219#endif
220
221 // Bit-packed flags to save memory (1 byte instead of 5)
222 struct EntityFlags {
223 uint8_t has_own_name : 1;
224 uint8_t internal : 1;
226 uint8_t has_state : 1;
227 uint8_t entity_category : 2; // Supports up to 4 categories
228 uint8_t reserved : 2; // Reserved for future use
230 // String table indices — packed into the 3 padding bytes after flags_
231#ifdef USE_ENTITY_DEVICE_CLASS
233#endif
234#ifdef USE_ENTITY_UNIT_OF_MEASUREMENT
235 uint8_t uom_idx_{};
236#endif
237#ifdef USE_ENTITY_ICON
238 uint8_t icon_idx_{};
239#endif
240};
241
243#ifdef USE_ENTITY_ICON
244#define LOG_ENTITY_ICON(tag, prefix, obj) log_entity_icon(tag, prefix, obj)
245void log_entity_icon(const char *tag, const char *prefix, const EntityBase &obj);
246#else
247#define LOG_ENTITY_ICON(tag, prefix, obj) ((void) 0)
248inline void log_entity_icon(const char *, const char *, const EntityBase &) {}
249#endif
251#define LOG_ENTITY_DEVICE_CLASS(tag, prefix, obj) log_entity_device_class(tag, prefix, obj)
252void log_entity_device_class(const char *tag, const char *prefix, const EntityBase &obj);
254#define LOG_ENTITY_UNIT_OF_MEASUREMENT(tag, prefix, obj) log_entity_unit_of_measurement(tag, prefix, obj)
255void log_entity_unit_of_measurement(const char *tag, const char *prefix, const EntityBase &obj);
256
280template<typename T> class StatefulEntityBase : public EntityBase {
281 public:
283 virtual const T &get_state() const = 0;
285 T get_state_default(T default_value) const { return this->has_state() ? this->get_state() : default_value; }
287 void invalidate_state() { this->set_new_state({}); }
288
289 template<typename F> void add_full_state_callback(F &&callback) {
290 this->full_state_callbacks_.add(std::forward<F>(callback));
291 }
292 template<typename F> void add_on_state_callback(F &&callback) {
293 this->state_callbacks_.add(std::forward<F>(callback));
294 }
295
296 protected:
298 virtual bool get_trigger_on_initial_state() const = 0;
299
306 virtual bool set_new_state(const optional<T> &new_state) {
307 // Access flags_ directly to avoid function call overhead in this hot path
308 bool had_state = this->flags_.has_state;
309 // Use pointer to avoid requiring T to be default-constructible
310 const T *current = had_state ? &this->get_state() : nullptr;
311 if (new_state.has_value()) {
312 if (current != nullptr && *current == new_state.value())
313 return false; // same value, no change
314 } else if (!had_state) {
315 return false; // already invalidated, no change
316 }
317 // Capture old_state before set_state_value — current pointer aliases subclass storage
318 bool has_full_cbs = !this->full_state_callbacks_.empty();
319 optional<T> old_state;
320 if (has_full_cbs)
321 old_state = current != nullptr ? optional<T>(*current) : nullopt;
322 // Update storage before firing callbacks so callback code can inspect current state
323 this->flags_.has_state = new_state.has_value();
324 if (new_state.has_value()) {
325 this->set_state_value(new_state.value());
326 }
327 if (has_full_cbs)
328 this->full_state_callbacks_.call(old_state, new_state);
329 // had_state first: on every change except the first, skips the virtual call
330 if (new_state.has_value() && (had_state || this->get_trigger_on_initial_state()))
331 this->state_callbacks_.call(new_state.value());
332 return true;
333 }
335 virtual void set_state_value(const T &value) = 0;
336 LazyCallbackManager<void(optional<T> previous, optional<T> current)> full_state_callbacks_;
338};
339} // 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
const StringRef & get_name() const
Definition entity_base.h:71
const char * get_icon_to(std::span< char, MAX_ICON_LENGTH > buffer) const
void set_device_(Device *device)
uint32_t get_object_id_hash() const
Definition entity_base.h:77
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.
uint32_t get_device_id() const
bool is_disabled_by_default() const
ESPPreferenceObject make_entity_preference(uint32_t version=0)
Create a preference object for storing this entity's state/settings.
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...
void set_internal(bool internal)
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
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)
static void uint32_t