BeeeOn Gateway  v2020.3.1-2-g6f737dc
Platform to interconnect the IoT world
EventSource.h
1 #pragma once
2 
3 #include <list>
4 #include <typeinfo>
5 
6 #include <Poco/Exception.h>
7 #include <Poco/SharedPtr.h>
8 
9 #include "util/AsyncExecutor.h"
10 #include "util/ClassInfo.h"
11 #include "util/Loggable.h"
12 #include "util/Once.h"
13 
14 namespace BeeeOn {
15 
23 template <typename Listener>
24 class EventSource : protected Loggable {
25 public:
26  EventSource();
27  virtual ~EventSource();
28 
29  void setAsyncExecutor(AsyncExecutor::Ptr executor);
30  AsyncExecutor::Ptr asyncExecutor() const;
31 
32  void addListener(typename Listener::Ptr listener);
33  void clearListeners();
34 
54  template <typename Event, typename Method>
55  void fireEvent(const Event &e, const Method &m);
56 
57 private:
58  AsyncExecutor::Ptr m_executor;
59  std::list<typename Listener::Ptr> m_listeners;
60 };
61 
62 template <typename Listener>
64 {
65 }
66 
67 template <typename Listener>
68 EventSource<Listener>::~EventSource()
69 {
70 }
71 
72 template <typename Listener>
73 void EventSource<Listener>::setAsyncExecutor(AsyncExecutor::Ptr executor)
74 {
75  m_executor = executor;
76 }
77 
78 template <typename Listener>
79 AsyncExecutor::Ptr EventSource<Listener>::asyncExecutor() const
80 {
81  return m_executor;
82 }
83 
84 template <typename Listener>
85 void EventSource<Listener>::addListener(typename Listener::Ptr listener)
86 {
87  m_listeners.push_back(listener);
88 }
89 
90 template <typename Listener>
91 void EventSource<Listener>::clearListeners()
92 {
93  m_listeners.clear();
94 }
95 
96 template <typename Listener> template <typename Event, typename Method>
97 void EventSource<Listener>::fireEvent(const Event &e, const Method &m)
98 {
99  static Once once;
100 
101  if (m_executor.isNull()) {
102  once.execute([&]() {
103  poco_warning(logger(), "no async executor is set");
104  });
105  return;
106  }
107 
108  auto copy = m_listeners;
109 
110  m_executor->invoke([=]() {
111  if (logger().debug()) {
112  logger().debug("firing event " + ClassInfo(e).name(),
113  __FILE__, __LINE__);
114  }
115 
116  for (auto listener : copy) {
117  try {
118  (listener->*m)(e);
119  }
120  BEEEON_CATCH_CHAIN_MESSAGE(
121  logger(),
122  "failed to deliver event " + ClassInfo(e).name())
123  }
124  });
125 }
126 
127 }
EventSource implements common logic for firing events to listeners.
Definition: EventSource.h:24
void fireEvent(const Event &e, const Method &m)
Definition: EventSource.h:97
Definition: Once.h:15
Definition: ClassInfo.h:9
Definition: Loggable.h:19