ESPHome 2025.5.0
Loading...
Searching...
No Matches
event_emitter.h
Go to the documentation of this file.
1#pragma once
2#include <unordered_map>
3#include <vector>
4#include <functional>
5#include <limits>
6
7#include "esphome/core/log.h"
8
9namespace esphome {
10namespace event_emitter {
11
12using EventEmitterListenerID = uint32_t;
14
15// EventEmitter class that can emit events with a specific name (it is highly recommended to use an enum class for this)
16// and a list of arguments. Supports multiple listeners for each event.
17template<typename EvtType, typename... Args> class EventEmitter {
18 public:
19 EventEmitterListenerID on(EvtType event, std::function<void(Args...)> listener) {
20 EventEmitterListenerID listener_id = get_next_id_(event);
21 listeners_[event][listener_id] = listener;
22 return listener_id;
23 }
24
25 void off(EvtType event, EventEmitterListenerID id) {
26 if (listeners_.count(event) == 0)
27 return;
28 listeners_[event].erase(id);
29 }
30
31 protected:
32 void emit_(EvtType event, Args... args) {
33 if (listeners_.count(event) == 0)
34 return;
35 for (const auto &listener : listeners_[event]) {
36 listener.second(args...);
37 }
38 }
39
41 // Check if the map is full
42 if (listeners_[event].size() == std::numeric_limits<EventEmitterListenerID>::max()) {
43 // Raise an error if the map is full
45 off(event, 0);
46 return 0;
47 }
48 // Get the next ID for the given event.
49 EventEmitterListenerID next_id = (current_id_ + 1) % std::numeric_limits<EventEmitterListenerID>::max();
50 while (listeners_[event].count(next_id) > 0) {
51 next_id = (next_id + 1) % std::numeric_limits<EventEmitterListenerID>::max();
52 }
53 current_id_ = next_id;
54 return current_id_;
55 }
56
57 private:
58 std::unordered_map<EvtType, std::unordered_map<EventEmitterListenerID, std::function<void(Args...)>>> listeners_;
59 EventEmitterListenerID current_id_ = 0;
60};
61
62} // namespace event_emitter
63} // namespace esphome
EventEmitterListenerID get_next_id_(EvtType event)
EventEmitterListenerID on(EvtType event, std::function< void(Args...)> listener)
void off(EvtType event, EventEmitterListenerID id)
void emit_(EvtType event, Args... args)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7