... | ... | @@ -53,9 +53,16 @@ First of all we need to include the required dependencies. We also need to speci |
|
|
#include "events/EventHandler.h"
|
|
|
#include "events/EventBroker.h"
|
|
|
|
|
|
#define sEventBroker Singleton<EventBroker>::getInstance()
|
|
|
|
|
|
|
|
|
namespace Boardcore {
|
|
|
|
|
|
map<uint8_t, vector<EventHandlerBase*>> subscribers;
|
|
|
|
|
|
enum ExampleEvents : uint8_t
|
|
|
{
|
|
|
EV_1 = EV_FIRST_SIGNAL,
|
|
|
EV_1 = EV_FIRST_CUSTOM,
|
|
|
EV_2,
|
|
|
EV_3
|
|
|
};
|
... | ... | @@ -65,12 +72,7 @@ enum ExampleTopics : uint8_t |
|
|
TOPIC_1,
|
|
|
TOPIC_2
|
|
|
};
|
|
|
```
|
|
|
|
|
|
Then we can define a custom EventHandler.
|
|
|
This is basically the same class that is shown in the [EventHandler](EventHandler) page, but when an object is instantiated it automatically subscribes to the topic `TOPIC_1`.
|
|
|
|
|
|
```cpp
|
|
|
class MyEventHandler : public EventHandler
|
|
|
{
|
|
|
public:
|
... | ... | @@ -79,19 +81,19 @@ public: |
|
|
last_event(0)
|
|
|
{
|
|
|
// make this object to subscribe to TOPIC_1
|
|
|
sEventBroker->subscribe(this, TOPIC_1);
|
|
|
sEventBroker.subscribe(this, TOPIC_1);
|
|
|
}
|
|
|
|
|
|
~MyEventHandler()
|
|
|
{
|
|
|
// unsubscribe from all the topics this object was subscribed to
|
|
|
sEventBroker->unsubscribe(this);
|
|
|
sEventBroker.unsubscribe(this);
|
|
|
}
|
|
|
|
|
|
protected:
|
|
|
void handleEvent(const Event& ev) override
|
|
|
{
|
|
|
switch(ev.sig)
|
|
|
switch(ev)
|
|
|
{
|
|
|
case EV_1:
|
|
|
TRACE("Received EV_1 \n");
|
... | ... | @@ -103,12 +105,14 @@ protected: |
|
|
TRACE("Invalid event \n");
|
|
|
}
|
|
|
|
|
|
last_event = ev.sig;
|
|
|
last_event = ev;
|
|
|
}
|
|
|
|
|
|
private:
|
|
|
uint8_t last_event;
|
|
|
};
|
|
|
|
|
|
}
|
|
|
```
|
|
|
|
|
|
#### test-eventbroker.cpp
|
... | ... | @@ -116,14 +120,15 @@ In the main we need to create an instance of the EventBroker (it is a singleton |
|
|
Also, we need to start the custom EventHandler.
|
|
|
Then we can post some events, both on topic `TOPIC_1` and `TOPIC_2`.
|
|
|
```cpp
|
|
|
#include <Common.h>
|
|
|
#include <miosix.h>
|
|
|
#include "MyEventHandler.h"
|
|
|
|
|
|
using namespace miosix;
|
|
|
using namespace Boardcore;
|
|
|
|
|
|
int main()
|
|
|
{
|
|
|
EventBroker* broker = EventBroker::getInstance(); // singleton object
|
|
|
EventBroker* broker = &EventBroker::getInstance(); // singleton object
|
|
|
broker->start();
|
|
|
|
|
|
MyEventHandler evh;
|
... | ... | @@ -155,12 +160,13 @@ int main() |
|
|
|
|
|
return 0;
|
|
|
}
|
|
|
|
|
|
```
|
|
|
#### Output
|
|
|
What we can observe is that the program output will be only something like:
|
|
|
```
|
|
|
0.12> Received EV_1
|
|
|
1.32> Received EV_2
|
|
|
2.32> Invalid event
|
|
|
0.04> Received EV_1
|
|
|
1.24> Received EV_2
|
|
|
2.24> Invalid event
|
|
|
```
|
|
|
The last "Invalid event" is due to the `EV_EMPTY` posted by the `stop()` method of the EventHandler object. |
|
|
\ No newline at end of file |