This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
/
timer.h
123 lines (97 loc) · 2.14 KB
/
timer.h
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
117
118
119
120
121
122
123
/*
* timer.h
*
* Created on: Apr 14, 2021
* Author: Bas
*/
#ifndef MAIN_ESPLIB_RTOS_TIMER_H_
#define MAIN_ESPLIB_RTOS_TIMER_H_
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
namespace FreeRTOS
{
class Timer
{
TimerHandle_t xTimer;
Callback<void, Timer*> callback;
static void tCallback(TimerHandle_t xTimer)
{
Timer* t = static_cast<Timer*>(pvTimerGetTimerID(xTimer));
//ESP_LOGI("Timer", "Elapsed '%s'", t->GetName());
if (t->callback.IsBound())
t->callback.Invoke(t);
}
public:
Timer()
{
}
~Timer()
{
//todo: what if this fails???
xTimerDelete(xTimer, 0);
}
void Init(const char* name, TickType_t period, bool autoReload = false)
{
period /= portTICK_PERIOD_MS;
if (period < 1)
period = 1;
xTimer = xTimerCreate(name, period, autoReload, this, &tCallback);
}
template<typename T>
void SetCallback(T* instance, void(T::* mp)(Timer*))
{
callback.Bind(instance, mp);
}
void SetCallback(void(*fp)(Timer*))
{
callback.Bind(fp);
}
bool Start(int timeout = 0)
{
return xTimerStart(xTimer, timeout / portTICK_PERIOD_MS) == pdPASS;
}
bool Stop(int timeout = 0)
{
return xTimerStop(xTimer, timeout / portTICK_PERIOD_MS) == pdPASS;
}
bool Reset(int timeout = 0)
{
return xTimerReset(xTimer, timeout / portTICK_PERIOD_MS) == pdPASS;
}
bool IsRunning()
{
return xTimerIsTimerActive(xTimer) != pdFALSE;
}
bool SetPeriod(TickType_t period, int timeout = 0)
{
period /= portTICK_PERIOD_MS;
if (period < 1)
period = 1;
return xTimerChangePeriod(xTimer, period, timeout / portTICK_PERIOD_MS) == pdPASS;
}
TickType_t GetPeriod(int timeout = 0)
{
return xTimerGetPeriod(xTimer);
}
TickType_t GetExpireTime()
{
return xTimerGetExpiryTime(xTimer) * portTICK_PERIOD_MS;
}
TickType_t GetRemainingTime()
{
if (xTimerIsTimerActive(xTimer) != pdFALSE)
{
return ((xTimerGetExpiryTime(xTimer) - xTaskGetTickCount()) * portTICK_PERIOD_MS);
}
else
{
return 0;
}
}
const char* GetName()
{
return pcTimerGetTimerName(xTimer);
}
};
}
#endif /* MAIN_ESPLIB_RTOS_TIMER_H_ */