1 /**
2  * Copyright © 2019 Facebook
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "gpioMon.hpp"
18 
19 #include <CLI/CLI.hpp>
20 #include <boost/asio/io_context.hpp>
21 #include <nlohmann/json.hpp>
22 #include <phosphor-logging/lg2.hpp>
23 
24 #include <fstream>
25 
26 namespace phosphor
27 {
28 namespace gpio
29 {
30 
31 std::map<std::string, int> polarityMap = {
32     /**< Only watch falling edge events. */
33     {"FALLING", GPIOD_LINE_REQUEST_EVENT_FALLING_EDGE},
34     /**< Only watch rising edge events. */
35     {"RISING", GPIOD_LINE_REQUEST_EVENT_RISING_EDGE},
36     /**< Monitor both types of events. */
37     {"BOTH", GPIOD_LINE_REQUEST_EVENT_BOTH_EDGES}};
38 
39 }
40 } // namespace phosphor
41 
main(int argc,char ** argv)42 int main(int argc, char** argv)
43 {
44     boost::asio::io_context io;
45 
46     CLI::App app{"Monitor GPIO line for requested state change"};
47 
48     std::string gpioFileName;
49 
50     /* Add an input option */
51     app.add_option("-c,--config", gpioFileName, "Name of config json file")
52         ->required()
53         ->check(CLI::ExistingFile);
54 
55     /* Parse input parameter */
56     try
57     {
58         app.parse(argc, argv);
59     }
60     catch (const CLI::Error& e)
61     {
62         return app.exit(e);
63     }
64 
65     /* Get list of gpio config details from json file */
66     std::ifstream file(gpioFileName);
67     if (!file)
68     {
69         lg2::error("GPIO monitor config file not found: {FILE}", "FILE",
70                    gpioFileName);
71         return -1;
72     }
73 
74     nlohmann::json gpioMonObj;
75     file >> gpioMonObj;
76     file.close();
77 
78     std::vector<std::unique_ptr<phosphor::gpio::GpioMonitor>> gpios;
79 
80     for (auto& obj : gpioMonObj)
81     {
82         /* GPIO Line message */
83         std::string lineMsg = "GPIO Line ";
84 
85         /* GPIO line */
86         gpiod_line* line = NULL;
87 
88         /* GPIO line configuration, default to monitor both edge */
89         struct gpiod_line_request_config config
90         {
91             "gpio_monitor", GPIOD_LINE_REQUEST_EVENT_BOTH_EDGES, 0
92         };
93 
94         /* flag to monitor */
95         bool flag = false;
96 
97         /* target to start */
98         std::string target;
99 
100         /* multi targets to start */
101         std::map<std::string, std::vector<std::string>> targets;
102 
103         if (obj.find("LineName") == obj.end())
104         {
105             /* If there is no line Name defined then gpio num nd chip
106              * id must be defined. GpioNum is integer mapping to the
107              * GPIO key configured by the kernel
108              */
109             if (obj.find("GpioNum") == obj.end() ||
110                 obj.find("ChipId") == obj.end())
111             {
112                 lg2::error("Failed to find line name or gpio number: {FILE}",
113                            "FILE", gpioFileName);
114                 return -1;
115             }
116 
117             std::string chipIdStr = obj["ChipId"];
118             int gpioNum = obj["GpioNum"];
119 
120             lineMsg += std::to_string(gpioNum);
121 
122             /* Get the GPIO line */
123             line = gpiod_line_get(chipIdStr.c_str(), gpioNum);
124         }
125         else
126         {
127             /* Find the GPIO line */
128             std::string lineName = obj["LineName"];
129             lineMsg += lineName;
130             line = gpiod_line_find(lineName.c_str());
131         }
132 
133         if (line == NULL)
134         {
135             lg2::error("Failed to find the {GPIO}", "GPIO", lineMsg);
136             continue;
137         }
138 
139         /* Get event to be monitored, if it is not defined then
140          * Both rising falling edge will be monitored.
141          */
142         if (obj.find("EventMon") != obj.end())
143         {
144             std::string eventStr = obj["EventMon"];
145             auto findEvent = phosphor::gpio::polarityMap.find(eventStr);
146             if (findEvent == phosphor::gpio::polarityMap.end())
147             {
148                 lg2::error("{GPIO}: event missing: {EVENT}", "GPIO", lineMsg,
149                            "EVENT", eventStr);
150                 return -1;
151             }
152 
153             config.request_type = findEvent->second;
154         }
155 
156         /* Get flag if monitoring needs to continue after first event */
157         if (obj.find("Continue") != obj.end())
158         {
159             flag = obj["Continue"];
160         }
161 
162         /* Parse out target argument. It is fine if the user does not
163          * pass this if they are not interested in calling into any target
164          * on meeting a condition.
165          */
166         if (obj.find("Target") != obj.end())
167         {
168             target = obj["Target"];
169         }
170 
171         /* Parse out the targets argument if multi-targets are needed.*/
172         if (obj.find("Targets") != obj.end())
173         {
174             obj.at("Targets").get_to(targets);
175         }
176 
177         /* Create a monitor object and let it do all the rest */
178         gpios.push_back(std::make_unique<phosphor::gpio::GpioMonitor>(
179             line, config, io, target, targets, lineMsg, flag));
180     }
181     io.run();
182 
183     return 0;
184 }
185