forked from arcturial/arduino-event
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvent.cpp
95 lines (82 loc) · 1.76 KB
/
Event.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Event
This class serves as a "callback" manager to register events
to happen on certain triggers or after certain intervals.
*/
#include "Arduino.h"
#include "Event.h"
/**
* Constructs a new EventManager and
* figures out the size of the available
* array slots.
*/
EventManager::EventManager()
{
_intervalSize = sizeof(_interval) / sizeof(TimedTask);
_intervalPos = 0;
_subSize = sizeof(_sub) / sizeof(Subscriber);
}
/**
* Subscribes a new Subscriber to the
* event manager.
*/
void EventManager::subscribe(Subscriber sub)
{
if (_subSize >= _subPos)
{
_sub[_subPos] = sub;
_subPos++;
}
}
/**
* Triggers a specified event which will find the applicable
* Subscriber and execute it's EventTask
*/
void EventManager::trigger(Event evt)
{
for (int i = 0; i < _subSize; i++)
{
Subscriber *sub = &_sub[i];
if ((String) sub->label == (String) evt.label)
{
// Execute event
sub->task->execute(evt);
}
}
}
/**
* Setup a timed trigger that will execute an
* event after a couple of milliseconds.
*/
void EventManager::triggerInterval(TimedTask task)
{
if (_intervalSize >= _intervalPos)
{
_interval[_intervalPos] = task;
_intervalPos++;
}
}
/**
* Tick the EventManager to evaluate any
* timed instances for the manager.
*/
void EventManager::tick()
{
unsigned long currentMs = millis();
unsigned long difference = currentMs - _previousMs;
for (int i = 0; i < _intervalSize; i++)
{
TimedTask *task = &_interval[i];
if (task->alive)
{
task->current = task->current + difference;
if (task->eval())
{
// Run the timed event when it evalutes to
// ready.
trigger(task->evt);
}
}
}
_previousMs = currentMs;
}