ESPHome  2025.2.0
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 
9 namespace esphome {
10 namespace event_emitter {
11 
12 using 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.
17 template<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
void raise_event_emitter_full_error()
EventEmitterListenerID on(EvtType event, std::function< void(Args...)> listener)
Definition: event_emitter.h:19
void off(EvtType event, EventEmitterListenerID id)
Definition: event_emitter.h:25
EventEmitterListenerID get_next_id_(EvtType event)
Definition: event_emitter.h:40
uint32_t EventEmitterListenerID
Definition: event_emitter.h:12
void emit_(EvtType event, Args... args)
Definition: event_emitter.h:32
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7