ESPHome 2026.5.0b1
Loading...
Searching...
No Matches
event.cpp
Go to the documentation of this file.
1#include "event.h"
4#include "esphome/core/log.h"
5
6namespace esphome::event {
7
8static const char *const TAG = "event";
9
10void Event::trigger(const std::string &event_type) {
11 // Linear search with strcmp - faster than std::set for small datasets (1-5 items typical)
12 const char *found = nullptr;
13 for (const char *type : this->types_) {
14 if (strcmp(type, event_type.c_str()) == 0) {
15 found = type;
16 break;
17 }
18 }
19 if (found == nullptr) {
20 ESP_LOGE(TAG, "'%s': invalid event type for trigger(): %s", this->get_name().c_str(), event_type.c_str());
21 return;
22 }
23 this->last_event_type_ = found;
24 ESP_LOGV(TAG, "'%s' >> '%s'", this->get_name().c_str(), this->last_event_type_);
25 this->event_callback_.call(StringRef(found));
26#if defined(USE_EVENT) && defined(USE_CONTROLLER_REGISTRY)
27 ControllerRegistry::notify_event(this);
28#endif
29}
30
32 this->types_.init(event_types.size());
33 for (const char *type : event_types) {
34 this->types_.push_back(type);
35 }
36 this->last_event_type_ = nullptr; // Reset when types change
37}
38
39void Event::set_event_types(const std::vector<const char *> &event_types) {
40 this->types_.init(event_types.size());
41 for (const char *type : event_types) {
42 this->types_.push_back(type);
43 }
44 this->last_event_type_ = nullptr; // Reset when types change
45}
46
47} // namespace esphome::event
const StringRef & get_name() const
Definition entity_base.h:71
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:529
size_t size() const
Definition helpers.h:686
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:646
void init(size_t n)
Definition helpers.h:619
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
LazyCallbackManager< void(StringRef event_type)> event_callback_
Definition event.h:73
void set_event_types(std::initializer_list< const char * > event_types)
Set the event types supported by this event (from initializer list).
Definition event.h:27
void trigger(const std::string &event_type)
Definition event.cpp:10
FixedVector< const char * > types_
Definition event.h:74
uint16_t type