Nagaraju Goruganti | 41a774e | 2018-04-06 06:15:27 -0500 | [diff] [blame] | 1 | #include <chrono> |
| 2 | #include <system_error> |
| 3 | #include <string.h> |
| 4 | #include "timer.hpp" |
| 5 | |
| 6 | namespace phosphor |
| 7 | { |
| 8 | namespace state |
| 9 | { |
| 10 | namespace manager |
| 11 | { |
| 12 | static std::chrono::microseconds getTime() |
| 13 | { |
| 14 | using namespace std::chrono; |
| 15 | auto usec = steady_clock::now().time_since_epoch(); |
| 16 | return duration_cast<microseconds>(usec); |
| 17 | } |
| 18 | |
| 19 | int Timer::state(timer::Action value) |
| 20 | { |
| 21 | action_ = value; |
| 22 | return sd_event_source_set_enabled(eventSource_.get(), action_); |
| 23 | } |
| 24 | |
| 25 | timer::Action Timer::getAction() const |
| 26 | { |
| 27 | return action_; |
| 28 | } |
| 29 | |
| 30 | std::chrono::microseconds Timer::getDuration() const |
| 31 | { |
| 32 | return duration_; |
| 33 | } |
| 34 | |
| 35 | Timer::Timer(EventPtr& event, std::function<void()> callback, |
| 36 | std::chrono::microseconds usec, timer::Action action) : |
| 37 | event_(event), |
| 38 | callback_(callback), duration_(usec), action_(action) |
| 39 | { |
| 40 | // Add infinite expiration time |
| 41 | sd_event_source* sourcePtr = nullptr; |
| 42 | |
| 43 | auto r = sd_event_add_time(event_.get(), &sourcePtr, |
| 44 | CLOCK_MONOTONIC, // Time base |
| 45 | (getTime() + usec).count(), // When to fire |
| 46 | 0, // Use default event accuracy |
| 47 | timeoutHandler, // Callback handler on timeout |
| 48 | this); // User data |
| 49 | |
| 50 | if (r < 0) |
| 51 | { |
| 52 | throw std::system_error(r, std::generic_category(), strerror(-r)); |
| 53 | } |
| 54 | |
| 55 | eventSource_.reset(sourcePtr); |
| 56 | } |
| 57 | |
| 58 | int Timer::timeoutHandler(sd_event_source* eventSrc, uint64_t usec, |
| 59 | void* userData) |
| 60 | { |
| 61 | auto timer = static_cast<Timer*>(userData); |
| 62 | |
| 63 | if (timer->getAction() == timer::ON) |
| 64 | { |
| 65 | auto r = sd_event_source_set_time( |
| 66 | eventSrc, (getTime() + timer->getDuration()).count()); |
| 67 | if (r < 0) |
| 68 | { |
| 69 | throw std::system_error(r, std::generic_category(), strerror(-r)); |
| 70 | } |
| 71 | |
| 72 | r = sd_event_source_set_enabled(eventSrc, timer::ON); |
| 73 | if (r < 0) |
| 74 | { |
| 75 | throw std::system_error(r, std::generic_category(), strerror(-r)); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | if (timer->callback_) |
| 80 | { |
| 81 | timer->callback_(); |
| 82 | } |
| 83 | |
| 84 | return 0; |
| 85 | } |
| 86 | |
| 87 | } // namespace manager |
| 88 | } // namespace state |
| 89 | } // namespace phosphor |