xref: /openbmc/phosphor-power/gpio.hpp (revision 48781aef)
1 #pragma once
2 
3 #include "file_descriptor.hpp"
4 
5 #include <linux/gpio.h>
6 
7 #include <string>
8 #include <type_traits>
9 
10 namespace phosphor
11 {
12 namespace gpio
13 {
14 
15 typedef std::remove_reference<
16     decltype(gpiohandle_request::lineoffsets[0])>::type gpioNum_t;
17 
18 typedef std::remove_reference<decltype(gpiohandle_data::values[0])>::type
19     gpioValue_t;
20 
21 /**
22  * If the GPIO is an input or output
23  */
24 enum class Direction
25 {
26     input,
27     output
28 };
29 
30 /**
31  * The possible values - low or high
32  */
33 enum class Value
34 {
35     low,
36     high
37 };
38 
39 /**
40  * Represents a GPIO.
41  *
42  * Currently supports reading a GPIO.
43  *
44  * Write support may be added in the future.
45  */
46 class GPIO
47 {
48   public:
49     GPIO() = delete;
50     GPIO(const GPIO&) = delete;
51     GPIO(GPIO&&) = default;
52     GPIO& operator=(const GPIO&) = delete;
53     GPIO& operator=(GPIO&&) = default;
54     ~GPIO() = default;
55 
56     /**
57      * Constructor
58      *
59      * @param[in] device - the GPIO device file
60      * @param[in] gpio - the GPIO number
61      * @param[in] direction - the GPIO direction
62      */
63     GPIO(const std::string& device, gpioNum_t gpio, Direction direction) :
64         device(device), gpio(gpio), direction(direction)
65     {}
66 
67     /**
68      * Reads the GPIO value
69      *
70      * Requests the GPIO line if it hasn't been done already.
71      *
72      * @return Value - the GPIO value
73      */
74     Value read();
75 
76     /**
77      * Sets the GPIO value to low or high
78      *
79      * Requests the GPIO line if it hasn't been done already.
80      *
81      * @param[in] Value - the value to set
82      */
83     void set(Value value);
84 
85   private:
86     /**
87      * Requests a GPIO line from the GPIO device
88      *
89      * @param[in] defaultValue - The default value, required for
90      *                           output GPIOs only.
91      */
92     void requestLine(Value defaultValue = Value::high);
93 
94     /**
95      * The GPIO device name, like /dev/gpiochip0
96      */
97     const std::string device;
98 
99     /**
100      * The GPIO number
101      */
102     const gpioNum_t gpio;
103 
104     /**
105      * The GPIO direction
106      */
107     const Direction direction;
108 
109     /**
110      * File descriptor for the GPIO line
111      */
112     power::util::FileDescriptor lineFD;
113 };
114 
115 } // namespace gpio
116 } // namespace phosphor
117