ESPHome 2025.12.0-dev
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 {
7namespace event {
8
9static const char *const TAG = "event";
10
11void Event::trigger(const std::string &event_type) {
12 // Linear search with strcmp - faster than std::set for small datasets (1-5 items typical)
13 const char *found = nullptr;
14 for (const char *type : this->types_) {
15 if (strcmp(type, event_type.c_str()) == 0) {
16 found = type;
17 break;
18 }
19 }
20 if (found == nullptr) {
21 ESP_LOGE(TAG, "'%s': invalid event type for trigger(): %s", this->get_name().c_str(), event_type.c_str());
22 return;
23 }
24 this->last_event_type_ = found;
25 ESP_LOGD(TAG, "'%s' Triggered event '%s'", this->get_name().c_str(), this->last_event_type_);
26 this->event_callback_.call(event_type);
27#if defined(USE_EVENT) && defined(USE_CONTROLLER_REGISTRY)
29#endif
30}
31
33 this->types_.init(event_types.size());
34 for (const char *type : event_types) {
35 this->types_.push_back(type);
36 }
37 this->last_event_type_ = nullptr; // Reset when types change
38}
39
40void Event::set_event_types(const std::vector<const char *> &event_types) {
41 this->types_.init(event_types.size());
42 for (const char *type : event_types) {
43 this->types_.push_back(type);
44 }
45 this->last_event_type_ = nullptr; // Reset when types change
46}
47
48void Event::add_on_event_callback(std::function<void(const std::string &event_type)> &&callback) {
49 this->event_callback_.add(std::move(callback));
50}
51
52} // namespace event
53} // namespace esphome
static void notify_event(event::Event *obj)
const StringRef & get_name() const
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:184
size_t size() const
Definition helpers.h:338
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:298
void init(size_t n)
Definition helpers.h:271
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:30
void trigger(const std::string &event_type)
Definition event.cpp:11
void add_on_event_callback(std::function< void(const std::string &event_type)> &&callback)
Definition event.cpp:48
FixedVector< const char * > types_
Definition event.h:54
CallbackManager< void(const std::string &event_type)> event_callback_
Definition event.h:53
uint16_t type
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7