forked from Toshik/TickerScheduler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TickerScheduler.cpp
116 lines (94 loc) · 2.22 KB
/
TickerScheduler.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "TickerScheduler.h"
TickerScheduler::TickerScheduler(uint8_t size)
{
this->items = new TickerSchedulerItem[size];
this->size = size;
}
TickerScheduler::~TickerScheduler()
{
for (uint8_t i = 0; i < this->size; i++)
{
this->remove(i);
yield();
}
delete[] this->items;
this->items = NULL;
this->size = 0;
}
void TickerScheduler::handleTickerFlag(volatile bool * flag)
{
if (!*flag)
*flag = true;
}
void TickerScheduler::handleTicker(tscallback_t f, void * arg, volatile bool * flag)
{
if (*flag)
{
yield();
*flag = false;
yield();
f(arg);
yield();
}
}
bool TickerScheduler::add(uint8_t i, uint32_t period, tscallback_t f, void* arg, boolean shouldFireNow)
{
if (i >= this->size || this->items[i].is_used)
return false;
this->items[i].cb = f;
this->items[i].cb_arg = arg;
this->items[i].flag = shouldFireNow;
this->items[i].period = period;
this->items[i].is_used = true;
enable(i);
return true;
}
bool TickerScheduler::remove(uint8_t i)
{
if (i >= this->size || !this->items[i].is_used)
return false;
this->items[i].is_used = false;
this->items[i].t.detach();
this->items[i].flag = false;
this->items[i].cb = NULL;
return true;
}
bool TickerScheduler::disable(uint8_t i)
{
if (i >= this->size || !this->items[i].is_used)
return false;
this->items[i].t.detach();
return true;
}
bool TickerScheduler::enable(uint8_t i)
{
if (i >= this->size || !this->items[i].is_used)
return false;
volatile bool * flag = &this->items[i].flag;
this->items[i].t.attach_ms(this->items[i].period, TickerScheduler::handleTickerFlag, flag);
return true;
}
void TickerScheduler::disableAll()
{
for (uint8_t i = 0; i < this->size; i++)
disable(i);
}
void TickerScheduler::enableAll()
{
for (uint8_t i = 0; i < this->size; i++)
enable(i);
}
void TickerScheduler::update()
{
for (uint8_t i = 0; i < this->size; i++)
{
if (this->items[i].is_used)
{
#ifdef ARDUINO_ARCH_AVR
this->items[i].t.Tick();
#endif
handleTicker(this->items[i].cb, this->items[i].cb_arg, &this->items[i].flag);
}
yield();
}
}