An EventSniffer is a class that can subscribe to a list of topics and when an event is received on one of those topics automatically calls a callback function.
In fact in its constructor we have to provide a reference to the EventBroker, the list (vector) of topics and the callback.
The callback type is defined as:
using OnEventReceived = function<void(uint8_t, uint8_t)>;
where the two parameters are the event ID and the topic on which that event has been received.
For each one of the specified topics, a Sniffer is created.
A Sniffer is a very simple class that extends EventHandlerBase: when created it subscribes to the given topic and when an event is posted on that topic (i.e. its postEvent(const Event& ev) method is called) it calls the callback function (passing it the event ID and the topic).
You can find the complete implementation of the EventSniffer in src/shared/events/utils/EventSniffer.h
.
Example
This example shows the usage of the EventSniffer, in the simple case in which it is subscribed to a single topic.
First of all define the possible events and topics:
#include <Common.h>
#include "events/EventBroker.h"
#include "events/utils/EventSniffer.h"
using namespace miosix;
enum ExampleEvents : uint8_t
{
EV_1 = EV_FIRST_SIGNAL,
EV_2
};
enum ExampleTopics : uint8_t
{
TOPIC_1 = 0,
TOPIC_2 = 1
};
Let's create also a callback function that reacts to the received events:
void callback(uint8_t ev_sig, uint8_t topic)
{
if (ev_sig == EV_1)
{
TRACE("Callback : EV_1 on topic %d \n", topic);
}
else if (ev_sig == EV_2)
{
TRACE("Callback : EV_2 on topic %d \n", topic);
}
}
In the main we can create a vector of topics (only TOPIC_1
in this case) and pass it to the EventSniffer together with a reference to the callback function:
int main()
{
vector<uint8_t> topics{TOPIC_1};
EventSniffer sniffer(*sEventBroker, topics, &callback);
// the first two events will trigger the callback
sEventBroker->post(Event{EV_1}, TOPIC_1);
Thread::sleep(100);
sEventBroker->post(Event{EV_2}, TOPIC_1);
Thread::sleep(100);
// this will not tigger the callback since
// the sniffer is subscribed only to TOPIC_1
sEventBroker->post(Event{EV_2}, TOPIC_2);
Thread::sleep(100);
sEventBroker->stop();
return 0;
}
Output
0.12> Callback : EV_1 on topic 0
0.24> Callback : EV_2 on topic 0