blob: 500a7aecd5c60c89cf2eeef1158d165eca0809a5 [file] [log] [blame]
Ratan Gupta4f80c1a2017-09-03 18:01:22 +05301#pragma once
2
Patrick Venture189d44e2018-07-09 12:30:59 -07003#include <systemd/sd-event.h>
4
Ratan Gupta4f80c1a2017-09-03 18:01:22 +05305#include <chrono>
6#include <functional>
Ratan Gupta4f80c1a2017-09-03 18:01:22 +05307
8namespace phosphor
9{
10namespace network
11{
12
13/** @class Timer
14 * @brief Usage would be,instantiate the timer with the call back
15 * and start the timer for the given time.
16 */
17class Timer
18{
19 public:
20 /** @brief Only need the default Timer */
21 Timer() = delete;
22 Timer(const Timer&) = delete;
23 Timer& operator=(const Timer&) = delete;
24 Timer(Timer&&) = delete;
25 Timer& operator=(Timer&&) = delete;
26
27 /** @brief Constructs timer object
28 *
29 * @param[in] funcCallBack - optional function callback for timer
30 * expirations
31 */
32 Timer(std::function<void()> userCallBack = nullptr):
33 userCallBack(userCallBack)
34 {
35 // Initialize the timer
36 initialize();
37 }
38
39 ~Timer()
40 {
41 if (eventSource)
42 {
43 eventSource = sd_event_source_unref(eventSource);
44 }
45 if(timeEvent)
46 {
47 timeEvent = sd_event_unref(timeEvent);
48 }
49 }
50
51 inline auto isExpired() const
52 {
53 return expired;
54 }
55
56 /** @brief Starts the timer with specified expiration value.
57 * input is an offset from the current steady_clock
58 */
59 int startTimer(std::chrono::microseconds usec);
60
61 /** @brief Enables / disables the timer */
62 int setTimer(int action);
63
64 private:
65 /** @brief the sd_event structure */
66 sd_event* timeEvent = nullptr;
67
68 /** @brief Source of events */
69 sd_event_source* eventSource = nullptr;
70
71 bool expired = true;
72
73 /** @brief Initializes the timer object with infinite
74 * expiration time and sets up the callback handler
75 *
76 * @return None.
77 *
78 * @error std::runtime exception thrown
79 */
80 void initialize();
81
82 /** @brief Callback function when timer goes off
83 *
84 * @param[in] eventSource - Source of the event
85 * @param[in] usec - time in micro seconds
86 * @param[in] userData - User data pointer
87 *
88 */
89 static int timeoutHandler(sd_event_source* eventSource,
90 uint64_t usec, void* userData);
91
92 /** @brief Gets the current time from steady clock */
93 static std::chrono::microseconds getTime();
94
95 /** @brief Optional function to call on timer expiration */
96 std::function<void()> userCallBack;
97};
98
99} // namespace network
100} // namespace phosphor