From dace680fa404d7c02a68db105fd7b958b4681442 Mon Sep 17 00:00:00 2001 From: Patrick Venture Date: Thu, 1 Nov 2018 16:52:10 -0700 Subject: Add clang-format to repo Add clang-format to repo. Change-Id: I3f8704d80dd0bdde0706ab189c68cffe6d347995 Signed-off-by: Patrick Venture --- .clang-format | 99 +++++++++++++++++++ argument.cpp | 35 +++---- argument.hpp | 75 +++++++-------- evdev.cpp | 15 +-- evdev.hpp | 137 +++++++++++++------------- file.hpp | 80 ++++++++-------- gpio-util/argument.cpp | 30 +++--- gpio-util/argument.hpp | 75 +++++++-------- gpio-util/gpio.cpp | 30 +++--- gpio-util/gpio.hpp | 170 ++++++++++++++++----------------- gpio-util/main.cpp | 33 ++----- mainapp.cpp | 24 +++-- monitor.cpp | 32 ++++--- monitor.hpp | 124 ++++++++++++------------ presence/argument.cpp | 36 +++---- presence/gpio_presence.cpp | 80 +++++++--------- presence/gpio_presence.hpp | 232 ++++++++++++++++++++++----------------------- presence/main.cpp | 21 ++-- test/utest.cpp | 100 +++++++++---------- 19 files changed, 750 insertions(+), 678 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..ea71ad6 --- /dev/null +++ b/.clang-format @@ -0,0 +1,99 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlinesLeft: false +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +PointerAlignment: Left +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^[<"](gtest|gmock)' + Priority: 5 + - Regex: '^"config.h"' + Priority: -1 + - Regex: '^".*\.hpp"' + Priority: 1 + - Regex: '^<.*\.h>' + Priority: 2 + - Regex: '^<.*' + Priority: 3 + - Regex: '.*' + Priority: 4 +IndentCaseLabels: true +IndentWidth: 4 +IndentWrappedFunctionNames: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 4 +UseTab: Never +... + diff --git a/argument.cpp b/argument.cpp index 3a59f68..74bdda2 100644 --- a/argument.cpp +++ b/argument.cpp @@ -14,11 +14,12 @@ * limitations under the License. */ -#include -#include +#include "argument.hpp" + #include #include -#include "argument.hpp" +#include +#include namespace phosphor { @@ -31,21 +32,21 @@ const std::string ArgumentParser::trueString = "true"s; const std::string ArgumentParser::emptyString = ""s; const char* ArgumentParser::optionStr = "p:k:r:t:?h"; -const option ArgumentParser::options[] = -{ - { "path", required_argument, nullptr, 'p' }, - { "key", required_argument, nullptr, 'k' }, - { "polarity", required_argument, nullptr, 'r' }, - { "target", required_argument, nullptr, 't' }, - { "continue", no_argument, nullptr, 'c' }, - { "help", no_argument, nullptr, 'h' }, - { 0, 0, 0, 0}, +const option ArgumentParser::options[] = { + {"path", required_argument, nullptr, 'p'}, + {"key", required_argument, nullptr, 'k'}, + {"polarity", required_argument, nullptr, 'r'}, + {"target", required_argument, nullptr, 't'}, + {"continue", no_argument, nullptr, 'c'}, + {"help", no_argument, nullptr, 'h'}, + {0, 0, 0, 0}, }; ArgumentParser::ArgumentParser(int argc, char** argv) { int option = 0; - while (-1 != (option = getopt_long(argc, argv, optionStr, options, nullptr))) + while (-1 != + (option = getopt_long(argc, argv, optionStr, options, nullptr))) { if ((option == '?') || (option == 'h')) { @@ -88,14 +89,14 @@ void ArgumentParser::usage(char** argv) std::cerr << "Options:\n"; std::cerr << " --help Print this menu\n"; std::cerr << " --path= Path of input device." - " Ex: /dev/input/event2\n"; + " Ex: /dev/input/event2\n"; std::cerr << " --key= Input GPIO key number\n"; std::cerr << " --polarity= Asertion polarity to look for." - " This is 0 / 1 \n"; + " This is 0 / 1 \n"; std::cerr << " --target= Systemd unit to be called on GPIO" - " state change\n"; + " state change\n"; std::cerr << " [--continue] Whether or not to continue" - " after key pressed\n"; + " after key pressed\n"; } } // namespace gpio } // namespace phosphor diff --git a/argument.hpp b/argument.hpp index 3debea5..7917b8a 100644 --- a/argument.hpp +++ b/argument.hpp @@ -1,6 +1,7 @@ #pragma once #include + #include #include @@ -13,51 +14,51 @@ namespace gpio */ class ArgumentParser { - public: - ArgumentParser() = delete; - ~ArgumentParser() = default; - ArgumentParser(const ArgumentParser&) = delete; - ArgumentParser& operator=(const ArgumentParser&) = delete; - ArgumentParser(ArgumentParser&&) = default; - ArgumentParser& operator=(ArgumentParser&&) = default; + public: + ArgumentParser() = delete; + ~ArgumentParser() = default; + ArgumentParser(const ArgumentParser&) = delete; + ArgumentParser& operator=(const ArgumentParser&) = delete; + ArgumentParser(ArgumentParser&&) = default; + ArgumentParser& operator=(ArgumentParser&&) = default; - /** @brief Constructs Argument object - * - * @param argc - the main function's argc passed as is - * @param argv - the main function's argv passed as is - * @return Object constructed - */ - ArgumentParser(int argc, char** argv); + /** @brief Constructs Argument object + * + * @param argc - the main function's argc passed as is + * @param argv - the main function's argv passed as is + * @return Object constructed + */ + ArgumentParser(int argc, char** argv); - /** @brief Given an option, returns its argument(optarg) - * - * @param opt - command line option string - * - * @return argument which is a standard optarg - */ - const std::string& operator[](const std::string& opt); + /** @brief Given an option, returns its argument(optarg) + * + * @param opt - command line option string + * + * @return argument which is a standard optarg + */ + const std::string& operator[](const std::string& opt); - /** @brief Displays usage - * - * @param argv - the main function's argv passed as is - */ - static void usage(char** argv); + /** @brief Displays usage + * + * @param argv - the main function's argv passed as is + */ + static void usage(char** argv); - /** @brief Set to 'true' when an option is passed */ - static const std::string trueString; + /** @brief Set to 'true' when an option is passed */ + static const std::string trueString; - /** @brief Set to '' when an option is not passed */ - static const std::string emptyString; + /** @brief Set to '' when an option is not passed */ + static const std::string emptyString; - private: - /** @brief Option to argument mapping */ - std::map arguments; + private: + /** @brief Option to argument mapping */ + std::map arguments; - /** @brief Array of struct options as needed by getopt_long */ - static const option options[]; + /** @brief Array of struct options as needed by getopt_long */ + static const option options[]; - /** @brief optstring as needed by getopt_long */ - static const char* optionStr; + /** @brief optstring as needed by getopt_long */ + static const char* optionStr; }; } // namespace gpio diff --git a/evdev.cpp b/evdev.cpp index e8e98e2..056093a 100644 --- a/evdev.cpp +++ b/evdev.cpp @@ -1,10 +1,13 @@ -#include +#include "evdev.hpp" + +#include "xyz/openbmc_project/Common/error.hpp" + #include +#include + +#include #include #include -#include -#include "xyz/openbmc_project/Common/error.hpp" -#include "evdev.hpp" namespace phosphor { @@ -56,8 +59,8 @@ void Evdev::initEvDev() void Evdev::registerCallback() { decltype(eventSource.get()) sourcePtr = nullptr; - auto rc = sd_event_add_io(event.get(), &sourcePtr, (fd)(), - EPOLLIN, callbackHandler, this); + auto rc = sd_event_add_io(event.get(), &sourcePtr, (fd)(), EPOLLIN, + callbackHandler, this); eventSource.reset(sourcePtr); if (rc < 0) diff --git a/evdev.hpp b/evdev.hpp index 353c593..eb7781b 100644 --- a/evdev.hpp +++ b/evdev.hpp @@ -1,9 +1,14 @@ #pragma once -#include -#include -#include #include "file.hpp" +#include +#include + +#include +#include +#include +#include + namespace phosphor { namespace gpio @@ -46,85 +51,79 @@ using EvdevPtr = std::unique_ptr; class Evdev { - using Property = std::string; - using Value = sdbusplus::message::variant; - // Association between property and its value - using PropertyMap = std::map; - using Interface = std::string; - // Association between interface and the D-Bus property - using InterfaceMap = std::map; - using Object = sdbusplus::message::object_path; - // Association between object and the interface - using ObjectMap = std::map; - - public: - Evdev() = delete; - ~Evdev() = default; - Evdev(const Evdev&) = delete; - Evdev& operator=(const Evdev&) = delete; - Evdev(Evdev&&) = delete; - Evdev& operator=(Evdev&&) = delete; - - /** @brief Constructs Evdev object. - * - * @param[in] path - Device path to read for GPIO pin state - * @param[in] key - GPIO key to monitor - * @param[in] event - sd_event handler - * @param[in] handler - IO callback handler. - * @param[in] useEvDev - Whether to use EvDev to retrieve events - */ - Evdev(const std::string& path, - const unsigned int key, - EventPtr& event, - sd_event_io_handler_t handler, - bool useEvDev = true) : - path(path), - key(key), - event(event), - callbackHandler(handler), - fd(openDevice()) + using Property = std::string; + using Value = sdbusplus::message::variant; + // Association between property and its value + using PropertyMap = std::map; + using Interface = std::string; + // Association between interface and the D-Bus property + using InterfaceMap = std::map; + using Object = sdbusplus::message::object_path; + // Association between object and the interface + using ObjectMap = std::map; + + public: + Evdev() = delete; + ~Evdev() = default; + Evdev(const Evdev&) = delete; + Evdev& operator=(const Evdev&) = delete; + Evdev(Evdev&&) = delete; + Evdev& operator=(Evdev&&) = delete; + + /** @brief Constructs Evdev object. + * + * @param[in] path - Device path to read for GPIO pin state + * @param[in] key - GPIO key to monitor + * @param[in] event - sd_event handler + * @param[in] handler - IO callback handler. + * @param[in] useEvDev - Whether to use EvDev to retrieve events + */ + Evdev(const std::string& path, const unsigned int key, EventPtr& event, + sd_event_io_handler_t handler, bool useEvDev = true) : + path(path), + key(key), event(event), callbackHandler(handler), fd(openDevice()) + { + if (useEvDev) { - if (useEvDev) - { - // If we are asked to use EvDev, do that initialization. - initEvDev(); - } - - // Register callback handler when FD has some data - registerCallback(); + // If we are asked to use EvDev, do that initialization. + initEvDev(); } - protected: - /** @brief Device path to read for GPIO pin state */ - const std::string path; + // Register callback handler when FD has some data + registerCallback(); + } + + protected: + /** @brief Device path to read for GPIO pin state */ + const std::string path; - /** @brief GPIO key to monitor */ - const unsigned int key; + /** @brief GPIO key to monitor */ + const unsigned int key; - /** @brief Event structure */ - EvdevPtr devicePtr; + /** @brief Event structure */ + EvdevPtr devicePtr; - /** @brief Monitor to sd_event */ - EventPtr& event; + /** @brief Monitor to sd_event */ + EventPtr& event; - /** @brief Callback handler when the FD has some data */ - sd_event_io_handler_t callbackHandler; + /** @brief Callback handler when the FD has some data */ + sd_event_io_handler_t callbackHandler; - /** @brief event source */ - EventSourcePtr eventSource; + /** @brief event source */ + EventSourcePtr eventSource; - /** @brief Opens the device and populates the descriptor */ - int openDevice(); + /** @brief Opens the device and populates the descriptor */ + int openDevice(); - /** @brief attaches FD to events and sets up callback handler */ - void registerCallback(); + /** @brief attaches FD to events and sets up callback handler */ + void registerCallback(); - /** @brief File descriptor manager */ - FileDescriptor fd; + /** @brief File descriptor manager */ + FileDescriptor fd; - /** @brief Initializes evdev handle with the fd */ - void initEvDev(); + /** @brief Initializes evdev handle with the fd */ + void initEvDev(); }; } // namespace gpio diff --git a/file.hpp b/file.hpp index ee8fd4b..500d8be 100644 --- a/file.hpp +++ b/file.hpp @@ -10,48 +10,48 @@ namespace gpio */ class FileDescriptor { - private: - /** @brief File descriptor for the gpio input device */ - int fd = -1; - - public: - FileDescriptor() = default; - FileDescriptor(const FileDescriptor&) = delete; - FileDescriptor& operator=(const FileDescriptor&) = delete; - FileDescriptor(FileDescriptor&&) = delete; - FileDescriptor& operator=(FileDescriptor&&) = delete; - - /** @brief Saves File descriptor and uses it to do file operation - * - * @param[in] fd - File descriptor - */ - FileDescriptor(int fd) : fd(fd) + private: + /** @brief File descriptor for the gpio input device */ + int fd = -1; + + public: + FileDescriptor() = default; + FileDescriptor(const FileDescriptor&) = delete; + FileDescriptor& operator=(const FileDescriptor&) = delete; + FileDescriptor(FileDescriptor&&) = delete; + FileDescriptor& operator=(FileDescriptor&&) = delete; + + /** @brief Saves File descriptor and uses it to do file operation + * + * @param[in] fd - File descriptor + */ + FileDescriptor(int fd) : fd(fd) + { + // Nothing + } + + ~FileDescriptor() + { + if (fd >= 0) { - // Nothing - } - - ~FileDescriptor() - { - if (fd >=0) - { - close(fd); - } - } - - int operator()() - { - return fd; - } - - operator bool() const - { - return fd != -1; - } - - void set(int descriptor) - { - fd = descriptor; + close(fd); } + } + + int operator()() + { + return fd; + } + + operator bool() const + { + return fd != -1; + } + + void set(int descriptor) + { + fd = descriptor; + } }; } // namespace gpio diff --git a/gpio-util/argument.cpp b/gpio-util/argument.cpp index 222b7d3..913313c 100644 --- a/gpio-util/argument.cpp +++ b/gpio-util/argument.cpp @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "argument.hpp" + +#include #include #include -#include -#include "argument.hpp" namespace phosphor { @@ -67,23 +68,22 @@ void ArgumentParser::usage(char** argv) std::cerr << " --help Print this menu.\n"; std::cerr << " --gpio= The GPIO number. Example: 1\n"; std::cerr << " --path= The path to the GPIO device." - " Example: /dev/gpiochip0\n"; + " Example: /dev/gpiochip0\n"; std::cerr << " --delay= The delay in ms in between a toggle." - " Example: 5\n"; + " Example: 5\n"; std::cerr << " --action= The action to do.\n"; std::cerr << " Valid actions: low, high, low_high, " - "high_low\n"; + "high_low\n"; std::cerr << std::flush; } -const option ArgumentParser::options[] = -{ - { "action", required_argument, NULL, 'a' }, - { "gpio", required_argument, NULL, 'g' }, - { "delay", required_argument, NULL, 'd' }, - { "path", required_argument, NULL, 'p' }, - { "help", no_argument, NULL, 'h' }, - { 0, 0, 0, 0}, +const option ArgumentParser::options[] = { + {"action", required_argument, NULL, 'a'}, + {"gpio", required_argument, NULL, 'g'}, + {"delay", required_argument, NULL, 'd'}, + {"path", required_argument, NULL, 'p'}, + {"help", no_argument, NULL, 'h'}, + {0, 0, 0, 0}, }; const char* ArgumentParser::optionStr = "a:g:d:p:h?"; @@ -91,5 +91,5 @@ const char* ArgumentParser::optionStr = "a:g:d:p:h?"; const std::string ArgumentParser::trueString = "true"; const std::string ArgumentParser::emptyString = ""; -} -} +} // namespace gpio +} // namespace phosphor diff --git a/gpio-util/argument.hpp b/gpio-util/argument.hpp index 3debea5..7917b8a 100644 --- a/gpio-util/argument.hpp +++ b/gpio-util/argument.hpp @@ -1,6 +1,7 @@ #pragma once #include + #include #include @@ -13,51 +14,51 @@ namespace gpio */ class ArgumentParser { - public: - ArgumentParser() = delete; - ~ArgumentParser() = default; - ArgumentParser(const ArgumentParser&) = delete; - ArgumentParser& operator=(const ArgumentParser&) = delete; - ArgumentParser(ArgumentParser&&) = default; - ArgumentParser& operator=(ArgumentParser&&) = default; + public: + ArgumentParser() = delete; + ~ArgumentParser() = default; + ArgumentParser(const ArgumentParser&) = delete; + ArgumentParser& operator=(const ArgumentParser&) = delete; + ArgumentParser(ArgumentParser&&) = default; + ArgumentParser& operator=(ArgumentParser&&) = default; - /** @brief Constructs Argument object - * - * @param argc - the main function's argc passed as is - * @param argv - the main function's argv passed as is - * @return Object constructed - */ - ArgumentParser(int argc, char** argv); + /** @brief Constructs Argument object + * + * @param argc - the main function's argc passed as is + * @param argv - the main function's argv passed as is + * @return Object constructed + */ + ArgumentParser(int argc, char** argv); - /** @brief Given an option, returns its argument(optarg) - * - * @param opt - command line option string - * - * @return argument which is a standard optarg - */ - const std::string& operator[](const std::string& opt); + /** @brief Given an option, returns its argument(optarg) + * + * @param opt - command line option string + * + * @return argument which is a standard optarg + */ + const std::string& operator[](const std::string& opt); - /** @brief Displays usage - * - * @param argv - the main function's argv passed as is - */ - static void usage(char** argv); + /** @brief Displays usage + * + * @param argv - the main function's argv passed as is + */ + static void usage(char** argv); - /** @brief Set to 'true' when an option is passed */ - static const std::string trueString; + /** @brief Set to 'true' when an option is passed */ + static const std::string trueString; - /** @brief Set to '' when an option is not passed */ - static const std::string emptyString; + /** @brief Set to '' when an option is not passed */ + static const std::string emptyString; - private: - /** @brief Option to argument mapping */ - std::map arguments; + private: + /** @brief Option to argument mapping */ + std::map arguments; - /** @brief Array of struct options as needed by getopt_long */ - static const option options[]; + /** @brief Array of struct options as needed by getopt_long */ + static const option options[]; - /** @brief optstring as needed by getopt_long */ - static const char* optionStr; + /** @brief optstring as needed by getopt_long */ + static const char* optionStr; }; } // namespace gpio diff --git a/gpio-util/gpio.cpp b/gpio-util/gpio.cpp index 080ab99..da5801e 100644 --- a/gpio-util/gpio.cpp +++ b/gpio-util/gpio.cpp @@ -13,10 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "gpio.hpp" + #include -#include #include -#include "gpio.hpp" + +#include namespace phosphor { @@ -38,16 +40,14 @@ void GPIO::set(Value value) if (rc == -1) { auto e = errno; - log("Failed SET_LINE_VALUES ioctl", - entry("ERRNO=%d", e)); + log("Failed SET_LINE_VALUES ioctl", entry("ERRNO=%d", e)); throw std::runtime_error("Failed SET_LINE_VALUES ioctl"); } } - void GPIO::requestLine(Value defaultValue) { - //Only need to do this once + // Only need to do this once if (lineFD) { return; @@ -63,15 +63,14 @@ void GPIO::requestLine(Value defaultValue) throw std::runtime_error("Failed opening GPIO device"); } - //Make an ioctl call to request the GPIO line, which will - //return the descriptor to use to access it. + // Make an ioctl call to request the GPIO line, which will + // return the descriptor to use to access it. gpiohandle_request request{}; - strncpy(request.consumer_label, - "phosphor-gpio-util", + strncpy(request.consumer_label, "phosphor-gpio-util", sizeof(request.consumer_label)); - request.flags = (direction == Direction::output) ? - GPIOHANDLE_REQUEST_OUTPUT : GPIOHANDLE_REQUEST_INPUT; + request.flags = (direction == Direction::output) ? GPIOHANDLE_REQUEST_OUTPUT + : GPIOHANDLE_REQUEST_INPUT; request.lineoffsets[0] = gpio; request.lines = 1; @@ -85,8 +84,7 @@ void GPIO::requestLine(Value defaultValue) if (rc == -1) { auto e = errno; - log("Failed GET_LINEHANDLE ioctl", - entry("GPIO=%d", gpio), + log("Failed GET_LINEHANDLE ioctl", entry("GPIO=%d", gpio), entry("ERRNO=%d", e)); throw std::runtime_error("Failed GET_LINEHANDLE ioctl"); } @@ -94,5 +92,5 @@ void GPIO::requestLine(Value defaultValue) lineFD.set(request.fd); } -} -} +} // namespace gpio +} // namespace phosphor diff --git a/gpio-util/gpio.hpp b/gpio-util/gpio.hpp index ba8cce3..d4ac47b 100644 --- a/gpio-util/gpio.hpp +++ b/gpio-util/gpio.hpp @@ -1,18 +1,22 @@ #pragma once -#include #include "file.hpp" +#include + +#include +#include + namespace phosphor { namespace gpio { - typedef std::remove_reference::type gpioNum_t; +typedef std::remove_reference::type gpioNum_t; - typedef std::remove_reference::type gpioValue_t; +typedef std::remove_reference::type + gpioValue_t; /** * Represents a GPIO. @@ -23,86 +27,80 @@ namespace gpio */ class GPIO { - public: - - /** - * If the GPIO is an input or output - */ - enum class Direction - { - input, - output - }; - - /** - * The possible values - low or high - */ - enum class Value - { - low, - high - }; - - GPIO() = delete; - GPIO(const GPIO&) = delete; - GPIO(GPIO&&) = default; - GPIO& operator=(const GPIO&) = delete; - GPIO& operator=(GPIO&&) = default; - ~GPIO() = default; - - /** - * Constructor - * - * @param[in] device - the GPIO device file - * @param[in] gpio - the GPIO number - * @param[in] direction - the GPIO direction - */ - GPIO(const std::string& device, - gpioNum_t gpio, - Direction direction) : - device(device), - gpio(gpio), - direction(direction) - { - } - - /** - * Sets the GPIO value - * - * Requests the GPIO line if it hasn't been done already. - */ - void set(Value value); - - private: - - /** - * Requests a GPIO line from the GPIO device - * - * @param[in] defaultValue - The default value, required for - * output GPIOs only. - */ - void requestLine(Value defaultValue = Value::high); - - /** - * The GPIO device name, like /dev/gpiochip0 - */ - const std::string device; - - /** - * The GPIO number - */ - const gpioNum_t gpio; - - /** - * The GPIO direction - */ - const Direction direction; - - /** - * File descriptor for the GPIO line - */ - FileDescriptor lineFD; + public: + /** + * If the GPIO is an input or output + */ + enum class Direction + { + input, + output + }; + + /** + * The possible values - low or high + */ + enum class Value + { + low, + high + }; + + GPIO() = delete; + GPIO(const GPIO&) = delete; + GPIO(GPIO&&) = default; + GPIO& operator=(const GPIO&) = delete; + GPIO& operator=(GPIO&&) = default; + ~GPIO() = default; + + /** + * Constructor + * + * @param[in] device - the GPIO device file + * @param[in] gpio - the GPIO number + * @param[in] direction - the GPIO direction + */ + GPIO(const std::string& device, gpioNum_t gpio, Direction direction) : + device(device), gpio(gpio), direction(direction) + { + } + + /** + * Sets the GPIO value + * + * Requests the GPIO line if it hasn't been done already. + */ + void set(Value value); + + private: + /** + * Requests a GPIO line from the GPIO device + * + * @param[in] defaultValue - The default value, required for + * output GPIOs only. + */ + void requestLine(Value defaultValue = Value::high); + + /** + * The GPIO device name, like /dev/gpiochip0 + */ + const std::string device; + + /** + * The GPIO number + */ + const gpioNum_t gpio; + + /** + * The GPIO direction + */ + const Direction direction; + + /** + * File descriptor for the GPIO line + */ + FileDescriptor lineFD; }; -} -} +} // namespace gpio +} // namespace phosphor diff --git a/gpio-util/main.cpp b/gpio-util/main.cpp index fb56e66..89e61f9 100644 --- a/gpio-util/main.cpp +++ b/gpio-util/main.cpp @@ -23,14 +23,15 @@ * high_low: Set a GPIO high, delay if requested, set it low */ +#include "argument.hpp" +#include "gpio.hpp" + #include #include #include #include -#include #include -#include "argument.hpp" -#include "gpio.hpp" +#include using namespace phosphor::gpio; using namespace phosphor::logging; @@ -49,7 +50,6 @@ void low(GPIO& gpio, unsigned int delayInMS) gpio.set(GPIO::Value::low); } - /** * Sets a GPIO high * @@ -61,7 +61,6 @@ void high(GPIO& gpio, unsigned int delayInMS) gpio.set(GPIO::Value::high); } - /** * Sets a GPIO high, then delays, then sets it low * @@ -78,7 +77,6 @@ void highLow(GPIO& gpio, unsigned int delayInMS) gpio.set(GPIO::Value::low); } - /** * Sets a GPIO low, then delays, then sets it high * @@ -95,18 +93,11 @@ void lowHigh(GPIO& gpio, unsigned int delayInMS) gpio.set(GPIO::Value::high); } - /** * The actions supported by this program */ -static const gpioFunctionMap functions -{ - {"low", low}, - {"high", high}, - {"low_high", lowHigh}, - {"high_low", highLow} -}; - +static const gpioFunctionMap functions{ + {"low", low}, {"high", high}, {"low_high", lowHigh}, {"high_low", highLow}}; /** * Prints usage and exits the program @@ -121,7 +112,6 @@ void exitWithError(const char* err, char** argv) exit(EXIT_FAILURE); } - /** * Returns the number value of the argument passed in. * @@ -129,15 +119,13 @@ void exitWithError(const char* err, char** argv) * @param[in] parser - the argument parser * @param[in] argv - arv from main() */ -template -T getValueFromArg(const char* name, - ArgumentParser& parser, - char** argv) +template +T getValueFromArg(const char* name, ArgumentParser& parser, char** argv) { char* p = NULL; auto val = strtol(parser[name].c_str(), &p, 10); - //strol sets p on error, also we don't allow negative values + // strol sets p on error, also we don't allow negative values if (*p || (val < 0)) { using namespace std::string_literals; @@ -147,7 +135,6 @@ T getValueFromArg(const char* name, return static_cast(val); } - int main(int argc, char** argv) { ArgumentParser args(argc, argv); @@ -171,7 +158,7 @@ int main(int argc, char** argv) auto gpioNum = getValueFromArg("gpio", args, argv); - //Not all actions require a delay, so not required + // Not all actions require a delay, so not required unsigned int delay = 0; if (args["delay"] != ArgumentParser::emptyString) { diff --git a/mainapp.cpp b/mainapp.cpp index 9ecaad2..2663f8f 100644 --- a/mainapp.cpp +++ b/mainapp.cpp @@ -14,13 +14,15 @@ * limitations under the License. */ -#include -#include -#include -#include #include "argument.hpp" #include "monitor.hpp" +#include + +#include +#include +#include + using namespace phosphor::logging; static void exitWithError(const char* err, char** argv) { @@ -63,7 +65,7 @@ int main(int argc, char** argv) auto target = (options)["target"]; bool continueRun = - (options["continue"] == phosphor::gpio::ArgumentParser::trueString); + (options["continue"] == phosphor::gpio::ArgumentParser::trueString); sd_event* event = nullptr; auto r = sd_event_default(&event); @@ -76,23 +78,19 @@ int main(int argc, char** argv) event = nullptr; // Create a monitor object and let it do all the rest - phosphor::gpio::Monitor monitor(path, - std::stoi(key), - std::stoi(polarity), - target, - eventP, - continueRun); + phosphor::gpio::Monitor monitor(path, std::stoi(key), std::stoi(polarity), + target, eventP, continueRun); // Wait for client requests until this application has processed // at least one expected GPIO state change - while(!monitor.completed()) + while (!monitor.completed()) { // -1 denotes wait for ever r = sd_event_run(eventP.get(), (uint64_t)-1); if (r < 0) { log("Failure in processing request", - entry("ERROR=%s", strerror(-r))); + entry("ERROR=%s", strerror(-r))); break; } } diff --git a/monitor.cpp b/monitor.cpp index 159127d..dd96fe9 100644 --- a/monitor.cpp +++ b/monitor.cpp @@ -14,10 +14,13 @@ * limitations under the License. */ +#include "config.h" + +#include "monitor.hpp" + #include + #include -#include "monitor.hpp" -#include "config.h" namespace phosphor { @@ -25,15 +28,15 @@ namespace gpio { // systemd service to kick start a target. -constexpr auto SYSTEMD_SERVICE = "org.freedesktop.systemd1"; -constexpr auto SYSTEMD_ROOT = "/org/freedesktop/systemd1"; -constexpr auto SYSTEMD_INTERFACE = "org.freedesktop.systemd1.Manager"; +constexpr auto SYSTEMD_SERVICE = "org.freedesktop.systemd1"; +constexpr auto SYSTEMD_ROOT = "/org/freedesktop/systemd1"; +constexpr auto SYSTEMD_INTERFACE = "org.freedesktop.systemd1.Manager"; using namespace phosphor::logging; // Callback handler when there is an activity on the FD -int Monitor::processEvents(sd_event_source* es, int fd, - uint32_t revents, void* userData) +int Monitor::processEvents(sd_event_source* es, int fd, uint32_t revents, + void* userData) { log("GPIO line altered"); auto monitor = static_cast(userData); @@ -46,7 +49,9 @@ int Monitor::processEvents(sd_event_source* es, int fd, void Monitor::analyzeEvent() { // Data returned - struct input_event ev{}; + struct input_event ev + { + }; int rc = 0; // While testing, observed that not having a loop here was leading @@ -54,8 +59,8 @@ void Monitor::analyzeEvent() while (rc >= 0) { // Wait until no more events are available on the device. - rc = libevdev_next_event(devicePtr.get(), - LIBEVDEV_READ_FLAG_NORMAL, &ev); + rc = libevdev_next_event(devicePtr.get(), LIBEVDEV_READ_FLAG_NORMAL, + &ev); if (rc < 0) { // There was an error waiting for events, mostly that there are no @@ -76,10 +81,9 @@ void Monitor::analyzeEvent() if (!target.empty()) { auto bus = sdbusplus::bus::new_default(); - auto method = bus.new_method_call(SYSTEMD_SERVICE, - SYSTEMD_ROOT, - SYSTEMD_INTERFACE, - "StartUnit"); + auto method = + bus.new_method_call(SYSTEMD_SERVICE, SYSTEMD_ROOT, + SYSTEMD_INTERFACE, "StartUnit"); method.append(target); method.append("replace"); diff --git a/monitor.hpp b/monitor.hpp index f4b07de..771492a 100644 --- a/monitor.hpp +++ b/monitor.hpp @@ -1,11 +1,13 @@ #pragma once -#include -#include +#include "evdev.hpp" + #include #include +#include + #include -#include "evdev.hpp" +#include namespace phosphor { @@ -18,74 +20,70 @@ namespace gpio */ class Monitor : public Evdev { - public: - Monitor() = delete; - ~Monitor() = default; - Monitor(const Monitor&) = delete; - Monitor& operator=(const Monitor&) = delete; - Monitor(Monitor&&) = delete; - Monitor& operator=(Monitor&&) = delete; + public: + Monitor() = delete; + ~Monitor() = default; + Monitor(const Monitor&) = delete; + Monitor& operator=(const Monitor&) = delete; + Monitor(Monitor&&) = delete; + Monitor& operator=(Monitor&&) = delete; - /** @brief Constructs Monitor object. - * - * @param[in] path - Path to gpio input device - * @param[in] key - GPIO key to monitor - * @param[in] polarity - GPIO assertion polarity to look for - * @param[in] target - systemd unit to be started on GPIO - * value change - * @param[in] event - sd_event handler - * @param[in] continueRun - Whether to continue after key pressed - * @param[in] handler - IO callback handler. Defaults to one in this - * class - * @param[in] useEvDev - Whether to use EvDev to retrieve events - */ - Monitor(const std::string& path, - decltype(input_event::code) key, - decltype(input_event::value) polarity, - const std::string& target, - EventPtr& event, - bool continueRun, - sd_event_io_handler_t handler = Monitor::processEvents, - bool useEvDev = true) - : Evdev(path, key, event, handler, useEvDev), - polarity(polarity), - target(target), - continueAfterKeyPress(continueRun) {}; + /** @brief Constructs Monitor object. + * + * @param[in] path - Path to gpio input device + * @param[in] key - GPIO key to monitor + * @param[in] polarity - GPIO assertion polarity to look for + * @param[in] target - systemd unit to be started on GPIO + * value change + * @param[in] event - sd_event handler + * @param[in] continueRun - Whether to continue after key pressed + * @param[in] handler - IO callback handler. Defaults to one in this + * class + * @param[in] useEvDev - Whether to use EvDev to retrieve events + */ + Monitor(const std::string& path, decltype(input_event::code) key, + decltype(input_event::value) polarity, const std::string& target, + EventPtr& event, bool continueRun, + sd_event_io_handler_t handler = Monitor::processEvents, + bool useEvDev = true) : + Evdev(path, key, event, handler, useEvDev), + polarity(polarity), target(target), + continueAfterKeyPress(continueRun){}; - /** @brief Callback handler when the FD has some activity on it - * - * @param[in] es - Populated event source - * @param[in] fd - Associated File descriptor - * @param[in] revents - Type of event - * @param[in] userData - User data that was passed during registration - * - * @return - 0 or positive number on success and negative - * errno otherwise - */ - static int processEvents(sd_event_source* es, int fd, - uint32_t revents, void* userData); + /** @brief Callback handler when the FD has some activity on it + * + * @param[in] es - Populated event source + * @param[in] fd - Associated File descriptor + * @param[in] revents - Type of event + * @param[in] userData - User data that was passed during registration + * + * @return - 0 or positive number on success and negative + * errno otherwise + */ + static int processEvents(sd_event_source* es, int fd, uint32_t revents, + void* userData); - /** @brief Returns the completion state of this handler */ - inline auto completed() const - { - return complete; - } + /** @brief Returns the completion state of this handler */ + inline auto completed() const + { + return complete; + } - private: - /** @brief GPIO key value that is of interest */ - decltype(input_event::value) polarity; + private: + /** @brief GPIO key value that is of interest */ + decltype(input_event::value) polarity; - /** @brief Systemd unit to be started when the condition is met */ - const std::string& target; + /** @brief Systemd unit to be started when the condition is met */ + const std::string& target; - /** @brief If the monitor should continue after key press */ - bool continueAfterKeyPress; + /** @brief If the monitor should continue after key press */ + bool continueAfterKeyPress; - /** @brief Completion indicator */ - bool complete = false; + /** @brief Completion indicator */ + bool complete = false; - /** @brief Analyzes the GPIO event and starts configured target */ - void analyzeEvent(); + /** @brief Analyzes the GPIO event and starts configured target */ + void analyzeEvent(); }; } // namespace gpio diff --git a/presence/argument.cpp b/presence/argument.cpp index a4b664e..e256426 100644 --- a/presence/argument.cpp +++ b/presence/argument.cpp @@ -14,10 +14,11 @@ * limitations under the License. */ +#include "argument.hpp" + +#include #include #include -#include -#include "argument.hpp" namespace phosphor { @@ -30,22 +31,21 @@ const std::string ArgumentParser::trueString = "true"s; const std::string ArgumentParser::emptyString = ""s; const char* ArgumentParser::optionStr = "p:k:n:i:d:?h"; -const option ArgumentParser::options[] = -{ - { "path", required_argument, nullptr, 'p' }, - { "key", required_argument, nullptr, 'k' }, - { "name", required_argument, nullptr, 'n' }, - { "inventory", required_argument, nullptr, 'i' }, - { "drivers", required_argument, nullptr, 'd' }, - { "help", no_argument, nullptr, 'h' }, - { 0, 0, 0, 0}, +const option ArgumentParser::options[] = { + {"path", required_argument, nullptr, 'p'}, + {"key", required_argument, nullptr, 'k'}, + {"name", required_argument, nullptr, 'n'}, + {"inventory", required_argument, nullptr, 'i'}, + {"drivers", required_argument, nullptr, 'd'}, + {"help", no_argument, nullptr, 'h'}, + {0, 0, 0, 0}, }; ArgumentParser::ArgumentParser(int argc, char** argv) { auto option = 0; - while (-1 != (option = getopt_long(argc, argv, - optionStr, options, nullptr))) + while (-1 != + (option = getopt_long(argc, argv, optionStr, options, nullptr))) { if ((option == '?') || (option == 'h')) { @@ -85,16 +85,16 @@ void ArgumentParser::usage(char** argv) std::cerr << "Options:\n"; std::cerr << " --help Print this menu\n"; std::cerr << " --inventory= Object path under inventory" - " that will be created\n"; + " that will be created\n"; std::cerr << " --path= Path of device to read for GPIO pin" - " state to determine presence of inventory item\n"; + " state to determine presence of inventory item\n"; std::cerr << " --key= Input GPIO key number\n"; std::cerr << " --name= Pretty name of the inventory" - " item\n"; + " item\n"; std::cerr << " --drivers= List of drivers to bind when card" - " is added and unbind when card is removed\n"; + " is added and unbind when card is removed\n"; std::cerr << " Format is a space separated list" - " of path,device pairs. For example:\n"; + " of path,device pairs. For example:\n"; std::cerr << " " "/sys/bus/i2c/drivers/some-driver,3-0068\n"; std::cerr << std::flush; diff --git a/presence/gpio_presence.cpp b/presence/gpio_presence.cpp index 4a11d98..1671721 100644 --- a/presence/gpio_presence.cpp +++ b/presence/gpio_presence.cpp @@ -1,11 +1,14 @@ +#include "gpio_presence.hpp" + +#include "xyz/openbmc_project/Common/error.hpp" + #include -#include #include + +#include +#include #include #include -#include -#include "xyz/openbmc_project/Common/error.hpp" -#include "gpio_presence.hpp" namespace phosphor { @@ -24,14 +27,11 @@ constexpr auto MAPPER_BUSNAME = "xyz.openbmc_project.ObjectMapper"; constexpr auto MAPPER_PATH = "/xyz/openbmc_project/object_mapper"; constexpr auto MAPPER_INTERFACE = "xyz.openbmc_project.ObjectMapper"; -std::string getService(const std::string& path, - const std::string& interface, +std::string getService(const std::string& path, const std::string& interface, sdbusplus::bus::bus& bus) { - auto mapperCall = bus.new_method_call(MAPPER_BUSNAME, - MAPPER_PATH, - MAPPER_INTERFACE, - "GetObject"); + auto mapperCall = bus.new_method_call(MAPPER_BUSNAME, MAPPER_PATH, + MAPPER_INTERFACE, "GetObject"); mapperCall.append(path); mapperCall.append(std::vector({interface})); @@ -45,16 +45,14 @@ std::string getService(const std::string& path, elog(); } - std::map> mapperResponse; mapperResponseMsg.read(mapperResponse); if (mapperResponse.empty()) { - log( - "Error in mapper response for getting service name", - entry("PATH=%s", path.c_str()), - entry("INTERFACE=%s", interface.c_str())); + log("Error in mapper response for getting service name", + entry("PATH=%s", path.c_str()), + entry("INTERFACE=%s", interface.c_str())); elog(); } @@ -65,8 +63,8 @@ void Presence::determinePresence() { auto present = false; auto value = static_cast(0); - auto fetch_rc = libevdev_fetch_event_value(devicePtr.get(), EV_KEY, - key, &value); + auto fetch_rc = + libevdev_fetch_event_value(devicePtr.get(), EV_KEY, key, &value); if (0 == fetch_rc) { log("Device does not support event type", @@ -83,8 +81,8 @@ void Presence::determinePresence() } // Callback handler when there is an activity on the FD -int Presence::processEvents(sd_event_source* es, int fd, - uint32_t revents, void* userData) +int Presence::processEvents(sd_event_source* es, int fd, uint32_t revents, + void* userData) { auto presence = static_cast(userData); @@ -92,13 +90,14 @@ int Presence::processEvents(sd_event_source* es, int fd, return 0; } - // Analyzes the GPIO event void Presence::analyzeEvent() { // Data returned - struct input_event ev {}; + struct input_event ev + { + }; int rc = 0; // While testing, observed that not having a loop here was leading @@ -106,8 +105,8 @@ void Presence::analyzeEvent() while (rc >= 0) { // Wait until no more events are available on the device. - rc = libevdev_next_event(devicePtr.get(), - LIBEVDEV_READ_FLAG_NORMAL, &ev); + rc = libevdev_next_event(devicePtr.get(), LIBEVDEV_READ_FLAG_NORMAL, + &ev); if (rc < 0) { // There was an error waiting for events, mostly that there are no @@ -145,8 +144,7 @@ Presence::ObjectMap Presence::getObjectMap(bool present) invProp.emplace("Present", present); invProp.emplace("PrettyName", name); - invIntf.emplace("xyz.openbmc_project.Inventory.Item", - std::move(invProp)); + invIntf.emplace("xyz.openbmc_project.Inventory.Item", std::move(invProp)); invObj.emplace(std::move(inventory), std::move(invIntf)); return invObj; @@ -163,19 +161,15 @@ void Presence::updateInventory(bool present) auto invService = getService(INVENTORY_PATH, INVENTORY_INTF, bus); // Update inventory - auto invMsg = bus.new_method_call(invService.c_str(), - INVENTORY_PATH, - INVENTORY_INTF, - "Notify"); + auto invMsg = bus.new_method_call(invService.c_str(), INVENTORY_PATH, + INVENTORY_INTF, "Notify"); invMsg.append(std::move(invObj)); auto invMgrResponseMsg = bus.call(invMsg); if (invMgrResponseMsg.is_method_error()) { - log( - "Error in inventory manager call to update inventory"); + log("Error in inventory manager call to update inventory"); elog(); } - } void Presence::bindOrUnbindDrivers(bool present) @@ -189,25 +183,21 @@ void Presence::bindOrUnbindDrivers(bool present) if (present) { - log( - "Binding a device driver", - entry("PATH=%s", path.c_str()), - entry("DEVICE=%s", device.c_str())); + log("Binding a device driver", + entry("PATH=%s", path.c_str()), + entry("DEVICE=%s", device.c_str())); } else { - log( - "Unbinding a device driver", - entry("PATH=%s", path.c_str()), - entry("DEVICE=%s", device.c_str())); + log("Unbinding a device driver", + entry("PATH=%s", path.c_str()), + entry("DEVICE=%s", device.c_str())); } std::ofstream file; - file.exceptions( - std::ofstream::failbit | - std::ofstream::badbit | - std::ofstream::eofbit); + file.exceptions(std::ofstream::failbit | std::ofstream::badbit | + std::ofstream::eofbit); try { @@ -228,8 +218,6 @@ void Presence::bindOrUnbindDrivers(bool present) } } - } // namespace presence } // namespace gpio } // namespace phosphor - diff --git a/presence/gpio_presence.hpp b/presence/gpio_presence.hpp index b5feddd..834a171 100644 --- a/presence/gpio_presence.hpp +++ b/presence/gpio_presence.hpp @@ -1,8 +1,10 @@ #pragma once +#include "evdev.hpp" + +#include + #include #include -#include -#include "evdev.hpp" namespace phosphor { @@ -25,120 +27,114 @@ using Driver = std::tuple; class Presence : public Evdev { - using Property = std::string; - using Value = sdbusplus::message::variant; - // Association between property and its value - using PropertyMap = std::map; - using Interface = std::string; - // Association between interface and the D-Bus property - using InterfaceMap = std::map; - using Object = sdbusplus::message::object_path; - // Association between object and the interface - using ObjectMap = std::map; - - public: - Presence() = delete; - ~Presence() = default; - Presence(const Presence&) = delete; - Presence& operator=(const Presence&) = delete; - Presence(Presence&&) = delete; - Presence& operator=(Presence&&) = delete; - - /** @brief Constructs Presence object. - * - * @param[in] bus - D-Bus bus Object - * @param[in] inventory - Object path under inventory - to display this inventory item - * @param[in] path - Device path to read for GPIO pin state - to determine presence of inventory item - * @param[in] key - GPIO key to monitor - * @param[in] name - Pretty name of the inventory item - * @param[in] event - sd_event handler - * @param[in] drivers - list of device drivers to bind and unbind - * @param[in] handler - IO callback handler. Defaults to one in this - * class - */ - Presence(sdbusplus::bus::bus& bus, - const std::string& inventory, - const std::string& path, - const unsigned int key, - const std::string& name, - EventPtr& event, - const std::vector& drivers, - sd_event_io_handler_t handler = Presence::processEvents) : - Evdev(path, key, event, handler, true), - bus(bus), - inventory(inventory), - name(name), - drivers(drivers) - { - determinePresence(); - } - - /** @brief Callback handler when the FD has some activity on it - * - * @param[in] es - Populated event source - * @param[in] fd - Associated File descriptor - * @param[in] revents - Type of event - * @param[in] userData - User data that was passed during registration - * - * @return - 0 or positive number on success and negative - * errno otherwise - */ - static int processEvents(sd_event_source* es, int fd, - uint32_t revents, void* userData); - - private: - /** - * @brief Update the present property for the inventory item. - * - * @param[in] present - What the present property should be set to. - */ - void updateInventory(bool present); - - /** - * @brief Construct the inventory object map for the inventory item. - * - * @param[in] present - What the present property should be set to. - * - * @return The inventory object map to update inventory - */ - ObjectMap getObjectMap(bool present); - - /** @brief Connection for sdbusplus bus */ - sdbusplus::bus::bus& bus; - - /** - * @brief Read the GPIO device to determine initial presence and set - * present property at D-Bus path. - */ - void determinePresence(); - - /** @brief Object path under inventory to display this inventory item */ - const std::string inventory; - - /** @brief Pretty name of the inventory item*/ - const std::string name; - - /** @brief Analyzes the GPIO event and update present property*/ - void analyzeEvent(); - - /** @brief Vector of path and device tuples to bind/unbind*/ - const std::vector drivers; - - /** - * @brief Binds or unbinds drivers - * - * Called when a presence change is detected to either - * bind the drivers for the new card or unbind them for - * the just removed card. Operates on the drivers vector. - * - * Writes to /bind (or unbind) - * - * @param present - when true, will bind the drivers - * when false, will unbind them - */ - void bindOrUnbindDrivers(bool present); + using Property = std::string; + using Value = sdbusplus::message::variant; + // Association between property and its value + using PropertyMap = std::map; + using Interface = std::string; + // Association between interface and the D-Bus property + using InterfaceMap = std::map; + using Object = sdbusplus::message::object_path; + // Association between object and the interface + using ObjectMap = std::map; + + public: + Presence() = delete; + ~Presence() = default; + Presence(const Presence&) = delete; + Presence& operator=(const Presence&) = delete; + Presence(Presence&&) = delete; + Presence& operator=(Presence&&) = delete; + + /** @brief Constructs Presence object. + * + * @param[in] bus - D-Bus bus Object + * @param[in] inventory - Object path under inventory + to display this inventory item + * @param[in] path - Device path to read for GPIO pin state + to determine presence of inventory item + * @param[in] key - GPIO key to monitor + * @param[in] name - Pretty name of the inventory item + * @param[in] event - sd_event handler + * @param[in] drivers - list of device drivers to bind and unbind + * @param[in] handler - IO callback handler. Defaults to one in this + * class + */ + Presence(sdbusplus::bus::bus& bus, const std::string& inventory, + const std::string& path, const unsigned int key, + const std::string& name, EventPtr& event, + const std::vector& drivers, + sd_event_io_handler_t handler = Presence::processEvents) : + Evdev(path, key, event, handler, true), + bus(bus), inventory(inventory), name(name), drivers(drivers) + { + determinePresence(); + } + + /** @brief Callback handler when the FD has some activity on it + * + * @param[in] es - Populated event source + * @param[in] fd - Associated File descriptor + * @param[in] revents - Type of event + * @param[in] userData - User data that was passed during registration + * + * @return - 0 or positive number on success and negative + * errno otherwise + */ + static int processEvents(sd_event_source* es, int fd, uint32_t revents, + void* userData); + + private: + /** + * @brief Update the present property for the inventory item. + * + * @param[in] present - What the present property should be set to. + */ + void updateInventory(bool present); + + /** + * @brief Construct the inventory object map for the inventory item. + * + * @param[in] present - What the present property should be set to. + * + * @return The inventory object map to update inventory + */ + ObjectMap getObjectMap(bool present); + + /** @brief Connection for sdbusplus bus */ + sdbusplus::bus::bus& bus; + + /** + * @brief Read the GPIO device to determine initial presence and set + * present property at D-Bus path. + */ + void determinePresence(); + + /** @brief Object path under inventory to display this inventory item */ + const std::string inventory; + + /** @brief Pretty name of the inventory item*/ + const std::string name; + + /** @brief Analyzes the GPIO event and update present property*/ + void analyzeEvent(); + + /** @brief Vector of path and device tuples to bind/unbind*/ + const std::vector drivers; + + /** + * @brief Binds or unbinds drivers + * + * Called when a presence change is detected to either + * bind the drivers for the new card or unbind them for + * the just removed card. Operates on the drivers vector. + * + * Writes to /bind (or unbind) + * + * @param present - when true, will bind the drivers + * when false, will unbind them + */ + void bindOrUnbindDrivers(bool present); }; /** @@ -151,11 +147,9 @@ class Presence : public Evdev * * @return The service name */ -std::string getService(const std::string& path, - const std::string& interface, +std::string getService(const std::string& path, const std::string& interface, sdbusplus::bus::bus& bus); } // namespace presence } // namespace gpio } // namespace phosphor - diff --git a/presence/main.cpp b/presence/main.cpp index 1eaa18b..16866d4 100644 --- a/presence/main.cpp +++ b/presence/main.cpp @@ -1,9 +1,11 @@ -#include -#include -#include #include "argument.hpp" #include "gpio_presence.hpp" +#include + +#include +#include + using namespace phosphor::logging; using namespace phosphor::gpio; using namespace phosphor::gpio::presence; @@ -27,7 +29,7 @@ static int getDrivers(const std::string& driverString, { std::string entry; - //Extract each path,device pair + // Extract each path,device pair stream >> entry; if (entry.empty()) @@ -35,7 +37,7 @@ static int getDrivers(const std::string& driverString, break; } - //Extract the path and device and save them + // Extract the path and device and save them auto pos = entry.rfind(','); if (pos != std::string::npos) { @@ -88,7 +90,7 @@ int main(int argc, char* argv[]) std::vector driverList; - //Driver list is optional + // Driver list is optional if (drivers != ArgumentParser::emptyString) { if (getDrivers(drivers, driverList) < 0) @@ -110,13 +112,13 @@ int main(int argc, char* argv[]) event = nullptr; auto name = options["name"]; - Presence presence( - bus, inventory, path, std::stoul(key), name, eventP, driverList); + Presence presence(bus, inventory, path, std::stoul(key), name, eventP, + driverList); while (true) { // -1 denotes wait forever - rc = sd_event_run(eventP.get(), (uint64_t) - 1); + rc = sd_event_run(eventP.get(), (uint64_t)-1); if (rc < 0) { log("Failure in processing request", @@ -126,4 +128,3 @@ int main(int argc, char* argv[]) } return rc; } - diff --git a/test/utest.cpp b/test/utest.cpp index a023cde..5fb870f 100644 --- a/test/utest.cpp +++ b/test/utest.cpp @@ -1,63 +1,65 @@ -#include +#include "evdev.hpp" +#include "monitor.hpp" + +#include #include + #include +#include #include -#include + #include -#include "monitor.hpp" -#include "evdev.hpp" using namespace phosphor::gpio; // Exit helper. Ideally should be class but need // this to be used inside a static method. -bool completed {}; +bool completed{}; class GpioTest : public ::testing::Test { - public: - static constexpr auto DEVICE = "/tmp/test_fifo"; + public: + static constexpr auto DEVICE = "/tmp/test_fifo"; - // systemd event handler - sd_event* events; + // systemd event handler + sd_event* events; - // Really needed just for the constructor - decltype(input_event::code) code = 10; + // Really needed just for the constructor + decltype(input_event::code) code = 10; - // Really needed just for the constructor - decltype(input_event::value) value = 10; + // Really needed just for the constructor + decltype(input_event::value) value = 10; - // Need this so that events can be initialized. - int rc; + // Need this so that events can be initialized. + int rc; - // Gets called as part of each TEST_F construction - GpioTest() - : rc(sd_event_default(&events)) - { - // Check for successful creation of event handler - EXPECT_GE(rc, 0); + // Gets called as part of each TEST_F construction + GpioTest() : rc(sd_event_default(&events)) + { + // Check for successful creation of event handler + EXPECT_GE(rc, 0); - // FIFO created to simulate data available - EXPECT_EQ(0, mknod(DEVICE, S_IFIFO|0666, 0)); - } + // FIFO created to simulate data available + EXPECT_EQ(0, mknod(DEVICE, S_IFIFO | 0666, 0)); + } - // Gets called as part of each TEST_F destruction - ~GpioTest() - { - EXPECT_EQ(0, remove(DEVICE)); + // Gets called as part of each TEST_F destruction + ~GpioTest() + { + EXPECT_EQ(0, remove(DEVICE)); - events = sd_event_unref(events); - EXPECT_EQ(events, nullptr); - } + events = sd_event_unref(events); + EXPECT_EQ(events, nullptr); + } - // Callback handler on data - static int callbackHandler(sd_event_source* es, int fd, - uint32_t revents, void* userData) - { - std::cout <<"Event fired" << std::endl; - completed = true; - return 0; - } + // Callback handler on data + static int callbackHandler(sd_event_source* es, int fd, uint32_t revents, + void* userData) + { + std::cout << "Event fired" << std::endl; + completed = true; + return 0; + } }; /** @brief Makes sure that event never comes for 3 seconds @@ -66,20 +68,20 @@ TEST_F(GpioTest, noEventIn3Seconds) { using namespace std::chrono; - phosphor::gpio::EventPtr eventP { events }; + phosphor::gpio::EventPtr eventP{events}; events = nullptr; const std::string emptyTarget = ""; - Monitor gpio(DEVICE, code, value, emptyTarget, - eventP, false, callbackHandler, false); + Monitor gpio(DEVICE, code, value, emptyTarget, eventP, false, + callbackHandler, false); // Waiting 3 seconds and check if the completion status is set int count = 0; - while(count < 3) + while (count < 3) { // Returns -0- on timeout and positive number on dispatch auto sleepTime = duration_cast(seconds(1)); - if(!sd_event_run(eventP.get(), sleepTime.count())) + if (!sd_event_run(eventP.get(), sleepTime.count())) { count++; } @@ -95,16 +97,16 @@ TEST_F(GpioTest, pumpDataAndExpectCallBack) { using namespace std::chrono; - phosphor::gpio::EventPtr eventP { events }; + phosphor::gpio::EventPtr eventP{events}; events = nullptr; const std::string emptyTarget = ""; - Monitor gpio(DEVICE, code, value, emptyTarget, - eventP, false, callbackHandler, false); + Monitor gpio(DEVICE, code, value, emptyTarget, eventP, false, + callbackHandler, false); // Pump the data in the middle int count = 0; - while(count < 2 && !completed) + while (count < 2 && !completed) { if (count == 1) { @@ -114,7 +116,7 @@ TEST_F(GpioTest, pumpDataAndExpectCallBack) // Returns -0- on timeout auto sleepTime = duration_cast(seconds(1)); - if(!sd_event_run(eventP.get(), sleepTime.count())) + if (!sd_event_run(eventP.get(), sleepTime.count())) { count++; } -- cgit v1.2.1