|
|
The **EventBroker** allows to post events to specific topics, as in a [Publish-Subscribe architecture](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern).
|
|
|
|
|
|
The **EventBroker** allows to post events to specific topics, as in a [Publish-Subscribe architecture](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern).
|
|
|
|
|
|
The following image shows a simple scenario with two topics (`TOPIC_1` and `TOPIC_2`), two publishers (one that publishes on topic `TOPIC_1` and the other that publishes on both topics) and two subscribers (one subscribed to both topics and one subscribed only to topic `TOPIC_2`).
|
|
|
Then, `Subscriber 1` will receive events that are published both on `TOPIC_1` or on `TOPIC_2`, while `Subscriber 2` will only received the events that are posted on `TOPIC_2`.
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
## Implementation
|
|
|
The EventBroker is a [singleton](Singleton), [active object](Active-Object).
|
|
|
[EventHandlerBase](EventHandler) objects can ask the EventBroker to subscribe to a specific topic: this way a subscriber will receive all the events that are posted on the topics it is subscribed to.
|
|
|
|
|
|
[EventHandlerBase](EventHandler) objects can ask the EventBroker to subscribe to a specific topic: this way a subscriber will receive all the events that are posted on the topics it is subscribed to.
|
|
|
|
|
|
In order to manage this events exchange, the broker maintains a map that associates each topic ID to a vector of EventHandlerBase objects:
|
|
|
```cpp
|
|
|
map<uint8_t, vector<EventHandlerBase*>> subscribers;
|
... | ... | @@ -20,7 +19,7 @@ The events that are posted to the broker are put in an event queue. The active o |
|
|
#### Methods
|
|
|
In addition to the Singleton and ActiveObject methods, the EventBroker exposes:
|
|
|
- **void post(const Event& ev, uint8_t topic)**: post an event to a specific topic.
|
|
|
- **uint16_t postDelayed(const Event& ev, uint8_t topic)**: post an event to a specific topic after a given delay in milliseconds (the delay can be passed as a template, e.g. *postDelayed<100>(...)*).
|
|
|
- **uint16_t postDelayed(const Event& ev, uint8_t topic)**: post an event to a specific topic after a given delay in milliseconds (the delay can be passed as a template, e.g. _postDelayed<100>(...)_).
|
|
|
- **void removeDelayed(uint16_t id)**: remove a pending delayed event from the event queue.
|
|
|
- **void subscribe(EventHandlerBase\* subscriber, uint8_t topic)**: subscribe the given subscriber to the specified topic.
|
|
|
- **void unsubscribe(EventHandlerBase\* subscriber, uint8_t topic)**: unsubscribe the given subscriber to the specified topic. If no topic is passed, the unsubscribe the subscriber from every topic it was subscribed to.
|
... | ... | |