Brad Bishop | e54a98f | 2017-06-14 23:10:37 -0400 | [diff] [blame] | 1 | #pragma once |
| 2 | |
| 3 | #include <functional> |
| 4 | #include <memory> |
| 5 | #include <phosphor-logging/elog.hpp> |
| 6 | #include <phosphor-logging/elog-errors.hpp> |
| 7 | #include <systemd/sd-event.h> |
| 8 | #include <xyz/openbmc_project/Common/error.hpp> |
| 9 | |
| 10 | #include "sdevent/source.hpp" |
| 11 | #include "sdevent/event.hpp" |
| 12 | |
| 13 | namespace sdevent |
| 14 | { |
| 15 | namespace event |
| 16 | { |
| 17 | namespace io |
| 18 | { |
| 19 | |
| 20 | /** @class IO |
| 21 | * @brief Provides C++ bindings to the sd_event_source* io functions. |
| 22 | */ |
| 23 | class IO |
| 24 | { |
| 25 | private: |
| 26 | using InternalFailure = sdbusplus::xyz::openbmc_project::Common:: |
| 27 | Error::InternalFailure; |
| 28 | |
| 29 | public: |
| 30 | /* Define all of the basic class operations: |
| 31 | * Not allowed: |
| 32 | * - Default constructor to avoid nullptrs. |
| 33 | * - Copy operations due to internal unique_ptr. |
| 34 | * Allowed: |
| 35 | * - Move operations. |
| 36 | * - Destructor. |
| 37 | */ |
| 38 | IO() = delete; |
| 39 | IO(const IO&) = delete; |
| 40 | IO& operator=(const IO&) = delete; |
| 41 | IO(IO&&) = default; |
| 42 | IO& operator=(IO&&) = default; |
| 43 | ~IO() = default; |
| 44 | |
| 45 | using Callback = std::function<void(source::Source&)>; |
| 46 | |
| 47 | /** @brief Register an io callback. |
| 48 | * |
| 49 | * @param[in] event - The event to register on. |
| 50 | * @param[in] fd - The file descriptor to poll. |
| 51 | * @param[in] callback - The callback method. |
| 52 | */ |
| 53 | IO( |
| 54 | sdevent::event::Event& event, |
| 55 | int fd, |
| 56 | Callback callback) |
| 57 | : src(nullptr), |
| 58 | cb(std::make_unique<Callback>(std::move(callback))) |
| 59 | { |
| 60 | sd_event_source* source = nullptr; |
| 61 | auto rc = sd_event_add_io( |
| 62 | event.get(), |
| 63 | &source, |
| 64 | fd, |
| 65 | EPOLLIN, |
| 66 | callCallback, |
| 67 | cb.get()); |
| 68 | if (rc < 0) |
| 69 | { |
| 70 | phosphor::logging::elog<InternalFailure>(); |
| 71 | } |
| 72 | |
| 73 | src = decltype(src){source, std::false_type()}; |
| 74 | } |
| 75 | |
| 76 | /** @brief Set the IO source enable state. */ |
| 77 | void enable(int enable) |
| 78 | { |
| 79 | src.enable(enable); |
| 80 | } |
| 81 | |
| 82 | /** @brief Query the IO enable state. */ |
| 83 | auto enabled() |
| 84 | { |
| 85 | return src.enabled(); |
| 86 | } |
| 87 | |
| 88 | private: |
| 89 | source::Source src; |
| 90 | std::unique_ptr<Callback> cb = nullptr; |
| 91 | |
| 92 | static int callCallback(sd_event_source* s, int fd, uint32_t events, |
| 93 | void* context) |
| 94 | { |
| 95 | source::Source source(s); |
| 96 | auto c = static_cast<Callback*>(context); |
| 97 | (*c)(source); |
| 98 | |
| 99 | return 0; |
| 100 | } |
| 101 | }; |
| 102 | } // namespace io |
| 103 | } // namespace event |
| 104 | } // namespace sdevent |