blob: 973b012f6a4a3084dec0de2c9a0291522177e3da [file] [log] [blame]
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -06001#include <chrono>
2#include <system_error>
3#include <string.h>
4#include "timer.hpp"
5
6namespace phosphor
7{
8namespace hwmon
9{
10
11static std::chrono::microseconds getTime()
12{
13 using namespace std::chrono;
14 auto usec = steady_clock::now().time_since_epoch();
15 return duration_cast<microseconds>(usec);
16}
17
18Timer::Timer(sd_event* event,
19 std::function<void()> callback,
20 std::chrono::microseconds usec,
21 timer::Action action):
22 event(event),
23 callback(callback),
24 duration(usec),
25 action(action)
26{
27 auto r = sd_event_add_time(event, &eventSource,
28 CLOCK_MONOTONIC, // Time base
29 (getTime() + usec).count(), // When to fire
30 0, // Use default event accuracy
31 timeoutHandler, // Callback handler on timeout
32 this); // User data
33 if (r < 0)
34 {
35 throw std::system_error(r, std::generic_category(), strerror(-r));
36 }
37}
38
39int Timer::timeoutHandler(sd_event_source* eventSource,
40 uint64_t usec, void* userData)
41{
42 auto timer = static_cast<Timer*>(userData);
43
44 if (timer->getAction() == timer::ON)
45 {
46 auto r = sd_event_source_set_time(
47 eventSource, (getTime() + timer->getDuration()).count());
48 if (r < 0)
49 {
50 throw std::system_error(r, std::generic_category(), strerror(-r));
51 }
52 r = sd_event_source_set_enabled(eventSource, timer::ON);
53 if (r < 0)
54 {
55 throw std::system_error(r, std::generic_category(), strerror(-r));
56 }
57 }
58
59 if(timer->callback)
60 {
61 timer->callback();
62 }
63
64 return 0;
65}
66
67} // namespace hwmon
68} // namespace phosphor