1 /**
2  * Copyright © 2016 IBM Corporation
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 "monitor.hpp"
18 
19 #include <systemd/sd-event.h>
20 
21 #include <CLI/CLI.hpp>
22 #include <phosphor-logging/lg2.hpp>
23 
24 #include <iostream>
25 #include <string>
26 
27 int main(int argc, char** argv)
28 {
29     CLI::App app{"Monitor GPIO line for requested state change"};
30 
31     // Read arguments.
32     std::string path{};
33     std::string key{};
34     std::string polarity{};
35     std::string target{};
36     bool continueRun = false;
37 
38     /* Add an input option */
39     app.add_option("-p,--path", path,
40                    "Path of input device. Ex: /dev/input/event2")
41         ->required();
42     app.add_option("-k,--key", key, "Input GPIO key number")->required();
43     app.add_option("-r,--polarity", polarity,
44                    "Asertion polarity to look for. This is 0 / 1")
45         ->required();
46     app.add_option("-t,--target", target,
47                    "Systemd unit to be called on GPIO state change")
48         ->required();
49     app.add_flag("-c,--continue", continueRun,
50                  "Whether or not to continue after key pressed");
51 
52     /* Parse input parameter */
53     try
54     {
55         app.parse(argc, argv);
56     }
57     catch (const CLI::Error& e)
58     {
59         return app.exit(e);
60     }
61 
62     sd_event* event = nullptr;
63     auto r = sd_event_default(&event);
64     if (r < 0)
65     {
66         lg2::error("Error creating a default sd_event handler");
67         return r;
68     }
69     phosphor::gpio::EventPtr eventP{event};
70     event = nullptr;
71 
72     // Create a monitor object and let it do all the rest
73     phosphor::gpio::Monitor monitor(path, std::stoi(key), std::stoi(polarity),
74                                     target, eventP, continueRun);
75 
76     // Wait for client requests until this application has processed
77     // at least one expected GPIO state change
78     while (!monitor.completed())
79     {
80         // -1 denotes wait for ever
81         r = sd_event_run(eventP.get(), (uint64_t)-1);
82         if (r < 0)
83         {
84             lg2::error("Failure in processing request: {RC}", "RC", r);
85             return r;
86         }
87     }
88 
89     return 0;
90 }
91