blob: bb1d6e94dad23735d5549aa3a5a92862400e7300 [file] [log] [blame]
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -06001#pragma once
2
3#include <chrono>
4#include <functional>
5#include <systemd/sd-event.h>
6
7namespace phosphor
8{
9namespace hwmon
10{
11namespace timer
12{
13
14enum Action
15{
16 OFF = SD_EVENT_OFF,
17 ON = SD_EVENT_ON,
18 ONESHOT = SD_EVENT_ONESHOT
19};
20
21}
22
23/** @class Timer
24 * @brief Provides a timer source and a mechanism to callback when the timer
25 * expires.
26 *
27 * The timer is armed upon construction. The constructor requires a timeout
28 * handler function, the timer expiry duration, and the timer state (one-shot,
29 * repetitive, disabled).
30 * It's possible to change the state of the timer after it's been armed via the
31 * state() API.
32 */
33class Timer
34{
35 public:
36 Timer() = delete;
37 Timer(const Timer&) = delete;
38 Timer& operator=(const Timer&) = delete;
39 Timer(Timer&&) = delete;
40 Timer& operator=(Timer&&) = delete;
41
42 /** @brief Constructs timer object
43 *
44 * @param[in] events - sd_event pointer
45 * @param[in] callback - function callback for timer expiry
46 * @param[in] usec - timer duration, in micro seconds
47 * @param[in] action - controls the timer's lifetime
48 */
49 Timer(sd_event* event,
50 std::function<void()> userCallback,
51 std::chrono::microseconds usec,
52 timer::Action action);
53
54 ~Timer()
55 {
56 if (eventSource)
57 {
58 eventSource = sd_event_source_unref(eventSource);
59 }
60 }
61
62 /** @brief Timer expiry handler - invokes callback
63 *
64 * @param[in] eventSource - Source of the event
65 * @param[in] usec - time in micro seconds
66 * @param[in] userData - User data pointer
67 *
68 */
69 static int timeoutHandler(sd_event_source* eventSource,
70 uint64_t usec, void* userData);
71
72 /** @brief Enables / disables the timer
73 * @param[in] action - controls the timer's lifetime
74 */
75 int state(timer::Action action)
76 {
77 return sd_event_source_set_enabled(eventSource, action);
78 }
79
80 timer::Action getAction() const
81 {
82 return action;
83 }
84
85 std::chrono::microseconds getDuration() const
86 {
87 return duration;
88 }
89
90 private:
91 /** @brief the sd_event structure */
92 sd_event* event = nullptr;
93
94 /** @brief Source of events */
95 sd_event_source* eventSource = nullptr;
96
97 /** @brief Optional function to call on timer expiration */
98 std::function<void()> callback{};
99
100 /** @brief Duration of the timer */
101 std::chrono::microseconds duration{};
102
103 /** @brief whether the timer is enabled/disabled/one-shot */
104 timer::Action action = timer::OFF;
105};
106
107} // namespace hwmon
108} // namespace phosphor