YAHAL
Yet Another Hardware Abstraction Library
Loading...
Searching...
No Matches
task_timer.h
1// ---------------------------------------------
2// This file is part of
3// _ _ __ _ _ __ __
4// ( \/ ) /__\ ( )_( ) /__\ ( )
5// \ / /(__)\ ) _ ( /(__)\ )(__
6// (__)(__)(__)(_) (_)(__)(__)(____)
7//
8// Yet Another HW Abstraction Library
9// Copyright (C) Andreas Terstegge
10// BSD Licensed (see file LICENSE)
11//
12// ---------------------------------------------
13//
14// A simple timer_interface implementation based on
15// the task class. The maximum timer resolution is
16// the tick count period - typically 1ms.
17//
18#ifndef _TASK_TIMER_H_
19#define _TASK_TIMER_H_
20
21#include "timer_interface.h"
22#include "task.h"
23#include <cassert>
24
25class task_timer : public task, public timer_interface {
26public:
27 explicit task_timer(const char *name,
28 uint16_t stack_size = DEFAULT_STACK_SIZE)
29 : task(name, stack_size) {
30
31 _mode = TIMER::ONE_SHOT;
32 _running = false;
33 _delta_ms = 0;
34 _next_ms = 0;
35
36 _callback = nullptr;
37 }
38
39 ~task_timer() override = default;
40
41 // No copy, no assignment
42 task_timer(const task_timer &) = delete;
43 task_timer &operator=(const task_timer &) = delete;
44
45 void setPeriod(uint32_t us, TIMER::timer_mode mode) override {
46 assert((us % 1000) == 0);
47 _delta_ms = us / 1000;
48 _mode = mode;
49 }
50
51 uint32_t getPeriod() override {
52 return _delta_ms * 1000;
53 }
54
55 void setCallback(function<void()> f) override {
56 _callback = f;
57 }
58
59 void start() override {
60 _running = true;
61 reset();
62 resume();
63 yield();
64 }
65
66 void stop() override {
67 suspend();
68 yield();
69 }
70
71 bool isRunning() override {
72 return getState() != state_t::SUSPENDED;
73 }
74
75 void reset() override {
76 _next_ms = task::millis() + _delta_ms;
77 }
78
79 [[noreturn]] void run() override {
80 while (true) {
81 if (_running) {
82 uint64_t now = task::millis();
83 if (now < _next_ms) {
84 uint64_t diff = _next_ms - now;
85 sleep_ms(diff);
86 } else {
87 _callback();
88 _next_ms += _delta_ms;
89 if (_mode == TIMER::ONE_SHOT) {
90 _running = false;
91 }
92 }
93 } else {
94 suspend();
95 yield();
96 }
97 }
98 }
99
100private:
101
102 TIMER::timer_mode _mode;
103 bool _running;
104 uint64_t _delta_ms;
105 uint64_t _next_ms;
106
107 function<void()> _callback;
108};
109
110#endif // _TASK_TIMER_H_
Definition task.h:39