blob: a99ec469df153faf106feb9e49a4fd689219b4ca [file] [log] [blame]
Patrick Venture043d3232018-08-31 10:10:53 -07001#include "timer.hpp"
2
3#include <string.h>
4
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -06005#include <chrono>
6#include <system_error>
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -06007
8namespace phosphor
9{
10namespace hwmon
11{
12
13static std::chrono::microseconds getTime()
14{
15 using namespace std::chrono;
16 auto usec = steady_clock::now().time_since_epoch();
17 return duration_cast<microseconds>(usec);
18}
19
Patrick Venture043d3232018-08-31 10:10:53 -070020Timer::Timer(sd_event* event, std::function<void()> callback,
21 std::chrono::microseconds usec, timer::Action action) :
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -060022 event(event),
Patrick Venture043d3232018-08-31 10:10:53 -070023 callback(callback), duration(usec), action(action)
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -060024{
25 auto r = sd_event_add_time(event, &eventSource,
Patrick Venture043d3232018-08-31 10:10:53 -070026 CLOCK_MONOTONIC, // Time base
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -060027 (getTime() + usec).count(), // When to fire
Patrick Venture043d3232018-08-31 10:10:53 -070028 0, // Use default event accuracy
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -060029 timeoutHandler, // Callback handler on timeout
Patrick Venture043d3232018-08-31 10:10:53 -070030 this); // User data
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -060031 if (r < 0)
32 {
33 throw std::system_error(r, std::generic_category(), strerror(-r));
34 }
35}
36
Patrick Venture043d3232018-08-31 10:10:53 -070037int Timer::timeoutHandler(sd_event_source* eventSource, uint64_t usec,
38 void* userData)
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -060039{
40 auto timer = static_cast<Timer*>(userData);
41
42 if (timer->getAction() == timer::ON)
43 {
44 auto r = sd_event_source_set_time(
Patrick Venture043d3232018-08-31 10:10:53 -070045 eventSource, (getTime() + timer->getDuration()).count());
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -060046 if (r < 0)
47 {
48 throw std::system_error(r, std::generic_category(), strerror(-r));
49 }
50 r = sd_event_source_set_enabled(eventSource, timer::ON);
51 if (r < 0)
52 {
53 throw std::system_error(r, std::generic_category(), strerror(-r));
54 }
55 }
56
Patrick Venture043d3232018-08-31 10:10:53 -070057 if (timer->callback)
Deepak Kodihalli6aa24d42018-03-07 01:10:03 -060058 {
59 timer->callback();
60 }
61
62 return 0;
63}
64
65} // namespace hwmon
66} // namespace phosphor