Deepak Kodihalli | 6aa24d4 | 2018-03-07 01:10:03 -0600 | [diff] [blame] | 1 | #include <chrono> |
| 2 | #include <system_error> |
| 3 | #include <string.h> |
| 4 | #include "timer.hpp" |
| 5 | |
| 6 | namespace phosphor |
| 7 | { |
| 8 | namespace hwmon |
| 9 | { |
| 10 | |
| 11 | static 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 | |
| 18 | Timer::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 | |
| 39 | int 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 |