If we want to check if how many events of each type have been posted, we can use the EventCounter class.
It is implemented as an EventHandler.
It also need the reference to the EventBroker, which has to be passed to the constructor.
In fact this class can subscribe to one or multiple topics and count how many times any event is posted to those topics: it keep the count both for the total number of events and the count for a single type of event.
Methods
The available methods are:
- unsigned int getCount(const Event& ev): return how many times the specified event has been posted to the topics the event counter is subscribed to.
- unsigned int getCount(uint8_t ev_sig): return how many times the specified event has been posted to the topics the event counter is subscribed to.
- unsigned int getTotalCount(): return how many events the event counter has received in total.
You can find the complete implementation of the EventCounter in src/shared/events/utils/EventCounter.h
.
Example
This example shows the usage of the EventCounter using a single topic.
First of all define the possible events and topics:
#include <miosix.h>
#include "events/EventBroker.h"
#include "events/utils/EventCounter.h"
#define sEventBroker Singleton<EventBroker>::getInstance()
using namespace miosix;
using namespace Boardcore;
enum ExampleEvents : uint8_t
{
EV_1 = EV_FIRST_CUSTOM,
EV_2
};
enum ExampleTopics : uint8_t
{
TOPIC_1
};
Then we can instantiate a new EventCounter and subscribe it to the existing topic TOPIC_1
.
If we post some events, we can check how many events have been posted, both in total or for each event type:
int main()
{
EventCounter counter{sEventBroker};
counter.subscribe(TOPIC_1);
Thread::sleep(100);
// post two events
sEventBroker.post(Event{EV_1}, TOPIC_1);
Thread::sleep(100);
sEventBroker.post(Event{EV_2}, TOPIC_1);
Thread::sleep(100);
// As a result we have 2 events in total
// 1 for type EV_1 and 1 for type EV_2
TRACE("Total : %d \n", counter.getTotalCount());
TRACE("EV_1 count : %d \n", counter.getCount(EV_1));
TRACE("EV_2 count : %d \n", counter.getCount(Event{EV_2}));
// The last event is EV_2, its id should be 5
// (which is EV_FIRST_SIGNAL + 1, as defined in the above enum)
TRACE("Last event : %d \n", counter.getLastEvent());
counter.stop();
sEventBroker.stop();
return 0;
}
Output
0.34> Total : 2
0.34> EV_1 count : 1
0.34> EV_2 count : 1
0.34> Last event : 5