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