diff options
author | Golder, Cezary <cezary.golder@intel.com> | 2018-09-13 01:51:04 +0300 |
---|---|---|
committer | Golder, Cezary <cezary.golder@intel.com> | 2018-10-26 13:00:13 +0300 |
commit | b6b6b7c00d64e86a96d703434c7a76523d8408d7 (patch) | |
tree | acc9408c6cbe7c861ae73ff4c410c72ffae44b89 /gpiodaemon | |
parent | 3f2c07b04c6ef4bef6930c67241a6461f85f9716 (diff) | |
download | provingground-b6b6b7c00d64e86a96d703434c7a76523d8408d7.tar.xz |
Create gpio dbus service basing on EntityManager.
Service name is "xyz.openbmc_project.Gpio" with below properties:
.Direction
.Enabled
.Value
Whenever "Enabled" is set to "false" the "Value" and "Direction"
properties cannot be overridden.
Tested By: Cezary Golder
Change-Id: I9192676d00c56e3637ded9ca4029b1df50a96f26
Signed-off-by: Golder, Cezary <cezary.golder@intel.com>
Diffstat (limited to 'gpiodaemon')
-rw-r--r-- | gpiodaemon/.clang-format | 98 | ||||
-rw-r--r-- | gpiodaemon/CMakeLists.txt | 42 | ||||
-rw-r--r-- | gpiodaemon/LICENSE | 201 | ||||
-rw-r--r-- | gpiodaemon/gpiodaemon.service | 12 | ||||
-rw-r--r-- | gpiodaemon/include/gpiodaemon.hpp | 69 | ||||
-rw-r--r-- | gpiodaemon/include/gpioutils.hpp | 52 | ||||
-rw-r--r-- | gpiodaemon/src/gpiodaemon.cpp | 288 | ||||
-rw-r--r-- | gpiodaemon/src/gpioutils.cpp | 116 |
8 files changed, 878 insertions, 0 deletions
diff --git a/gpiodaemon/.clang-format b/gpiodaemon/.clang-format new file mode 100644 index 0000000..8c5278e --- /dev/null +++ b/gpiodaemon/.clang-format @@ -0,0 +1,98 @@ +--- +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 +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 +PointerAlignment: Left +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/gpiodaemon/CMakeLists.txt b/gpiodaemon/CMakeLists.txt new file mode 100644 index 0000000..9fca745 --- /dev/null +++ b/gpiodaemon/CMakeLists.txt @@ -0,0 +1,42 @@ +cmake_minimum_required(VERSION 3.5 FATAL_ERROR) +project(gpiodaemon CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti") +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-rtti") + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) +find_package(Boost REQUIRED) +include_directories(${Boost_INCLUDE_DIRS}) +add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY) +add_definitions(-DBOOST_SYSTEM_NO_DEPRECATED) +add_definitions(-DBOOST_ALL_NO_LIB) +add_definitions(-DBOOST_NO_RTTI) +add_definitions(-DBOOST_NO_TYPEID) +add_definitions(-DBOOST_ASIO_DISABLE_THREADS) + +set(SRC_FILES src/gpiodaemon.cpp src/gpioutils.cpp) + +# import libsystemd +find_package(PkgConfig REQUIRED) +pkg_check_modules(SYSTEMD libsystemd REQUIRED) + +# import sdbusplus +find_package(PkgConfig REQUIRED) +pkg_check_modules(SDBUSPLUSPLUS sdbusplus REQUIRED) + +# import phosphor-logging +find_package(PkgConfig REQUIRED) +pkg_check_modules(LOGGING phosphor-logging REQUIRED) + +add_executable(${PROJECT_NAME} ${SRC_FILES}) +target_link_libraries(${PROJECT_NAME} systemd) +target_link_libraries(${PROJECT_NAME} sdbusplus -lstdc++fs) +target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES}) + +link_directories(${EXTERNAL_INSTALL_LOCATION}/lib) + +set(SERVICE_FILES ${PROJECT_SOURCE_DIR}/gpiodaemon.service) + +install(TARGETS ${PROJECT_NAME} DESTINATION sbin) +install(FILES ${SERVICE_FILES} DESTINATION /lib/systemd/system/)
\ No newline at end of file diff --git a/gpiodaemon/LICENSE b/gpiodaemon/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/gpiodaemon/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/gpiodaemon/gpiodaemon.service b/gpiodaemon/gpiodaemon.service new file mode 100644 index 0000000..216697e --- /dev/null +++ b/gpiodaemon/gpiodaemon.service @@ -0,0 +1,12 @@ +[Unit] +Description=Gpio daemon + +[Service] +Restart=always +RestartSec=2 +ExecStart=/usr/sbin/gpiodaemon +StartLimitInterval=0 +Type=simple + +[Install] +WantedBy=default.target diff --git a/gpiodaemon/include/gpiodaemon.hpp b/gpiodaemon/include/gpiodaemon.hpp new file mode 100644 index 0000000..cd08d92 --- /dev/null +++ b/gpiodaemon/include/gpiodaemon.hpp @@ -0,0 +1,69 @@ +/* +// Copyright (c) 2018 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +*/ + +#pragma once +#include <boost/asio.hpp> +#include <experimental/filesystem> +#include <phosphor-logging/log.hpp> +#include <sdbusplus/asio/object_server.hpp> + +class GpioEn +{ + std::string name; + uint16_t number; + bool enabled; + + public: + GpioEn(const std::string& name_, uint16_t number_, bool enabled_) : + name(name_), number(number_), enabled(enabled_){}; + + std::string getName() const + { + return name; + } + uint16_t getNumber() const + { + return number; + } + bool getEnabled() const + { + return enabled; + } + void setEnabled(bool value) + { + enabled = value; + } +}; + +class GpioManager +{ + std::vector<GpioEn> gpioEnableList; + std::vector<std::experimental::filesystem::path> gpioPaths; + sdbusplus::asio::object_server& server; + std::shared_ptr<sdbusplus::asio::connection> conn; + std::shared_ptr<sdbusplus::asio::dbus_interface> iface; + std::vector<std::string> paths; + + GpioEn* findGpioObj(const std::string& gpioName); + bool findGpioDirs( + const std::experimental::filesystem::path& dirPath, + const std::string& matchString, + std::vector<std::experimental::filesystem::path>& foundPaths); + + public: + GpioManager(sdbusplus::asio::object_server& srv, + std::shared_ptr<sdbusplus::asio::connection>& conn); +}; diff --git a/gpiodaemon/include/gpioutils.hpp b/gpiodaemon/include/gpioutils.hpp new file mode 100644 index 0000000..3eb7225 --- /dev/null +++ b/gpiodaemon/include/gpioutils.hpp @@ -0,0 +1,52 @@ +/* +// Copyright (c) 2018 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +*/ + +#pragma once + +#include <experimental/filesystem> +#include <fstream> + +enum class GpioValue +{ + low = 0, + high +}; + +enum class GpioDirection +{ + in = 0, + out, + both +}; + +class Gpio +{ + std::string gpioNumber; + + bool gpioExist(); + void gpioExport(); + void gpioUnexport(); + + public: + Gpio(std::string number); + Gpio(const Gpio&) = default; + Gpio& operator=(const Gpio&) = default; + + GpioValue getValue(); + void setValue(const GpioValue& value); + std::string getDirection(); + void setDirection(const std::string& direction); +}; diff --git a/gpiodaemon/src/gpiodaemon.cpp b/gpiodaemon/src/gpiodaemon.cpp new file mode 100644 index 0000000..2cdfdc3 --- /dev/null +++ b/gpiodaemon/src/gpiodaemon.cpp @@ -0,0 +1,288 @@ +/* +// Copyright (c) 2018 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +*/ + +#include "gpiodaemon.hpp" + +#include "gpioutils.hpp" + +#include <boost/algorithm/string/replace.hpp> +#include <regex> + +static constexpr const char* entityMgrService = + "xyz.openbmc_project.EntityManager"; +static constexpr const char* gpioService = "xyz.openbmc_project.Gpio"; +static constexpr const char* gpioConfigInterface = + "xyz.openbmc_project.Configuration.Gpio"; +static constexpr const char* gpioInterface = "xyz.openbmc_project.Control.Gpio"; +static constexpr const char* gpioPath = "/xyz/openbmc_project/control/gpio/"; +static constexpr const char* propInterface = "org.freedesktop.DBus.Properties"; + +static constexpr const char* objPath = "/xyz/openbmc_project/object_mapper"; +static constexpr const char* objService = "xyz.openbmc_project.ObjectMapper"; +static constexpr const char* objInterface = "xyz.openbmc_project.ObjectMapper"; + +const static constexpr size_t waitTime = 2; // seconds + +using BasicVariantType = + sdbusplus::message::variant<std::string, int64_t, uint64_t, double, int32_t, + uint32_t, int16_t, uint16_t, uint8_t, bool>; + +GpioManager::GpioManager(sdbusplus::asio::object_server& srv_, + std::shared_ptr<sdbusplus::asio::connection>& conn_) : + server(srv_), + conn(conn_) +{ + using GetSubTreeType = std::vector<std::pair< + std::string, + std::vector<std::pair<std::string, std::vector<std::string>>>>>; + + auto mesg = + conn->new_method_call(objService, objPath, objInterface, "GetSubTree"); + + static const auto depth = 3; + mesg.append("/xyz/openbmc_project/inventory/system", depth, + std::vector<std::string>()); + + try + { + auto ret = conn->call(mesg); + + GetSubTreeType subtree; + ret.read(subtree); + + for (const auto& i : subtree) + { + for (const auto& j : i.second) + { + for (const auto& k : j.second) + { + if (gpioConfigInterface == k) + { + paths.push_back(i.first); + } + } + } + } + } + catch (sdbusplus::exception::SdBusError& e) + { + phosphor::logging::log<phosphor::logging::level::INFO>( + "ERROR while readding ObjectMapper."); + return; + } + + for (const auto& path : paths) + { + conn->async_method_call( + [this, &path]( + boost::system::error_code ec, + const boost::container::flat_map<std::string, BasicVariantType>& + result) { + if (ec) + { + phosphor::logging::log<phosphor::logging::level::INFO>( + ("ERROR with async_method_call path: " + path).c_str()); + } + else + { + auto nameFind = result.find("Name"); + auto indexFind = result.find("Index"); + auto polarityFind = result.find("Polarity"); + + if (nameFind == result.end() || indexFind == result.end() || + polarityFind == result.end()) + { + phosphor::logging::log<phosphor::logging::level::INFO>( + "ERROR accessing entity manager."); + return; + } + + uint64_t index = indexFind->second.get<uint64_t>(); + std::string gpioName = nameFind->second.get<std::string>(); + bool inverted = + polarityFind->second.get<std::string>() == "Low"; + + boost::replace_all(gpioName, " ", "_"); + + // Add gpio entries to be managed by gpiodaemon + gpioEnableList.push_back( + GpioEn(gpioName, (uint16_t)index, false)); + + // Read present gpio data from /sys/class/gpio/... + Gpio gpio = Gpio(std::to_string(index)); + + // Add path to server object + iface = server.add_interface(gpioPath + gpioName, + gpioInterface); + + ///////////////////////////// + // Set generic properties: + // - enabled - when set to false other properties like + // value and direction + // cannot be overriden + // - value + // - direction + // - polarity + ///////////////////////////// + iface->register_property( + "Enabled", true, + [this, gpioName](const bool& req, bool& propertyValue) { + auto it = findGpioObj(gpioName); + if (it != nullptr) + { + it->setEnabled(req); + propertyValue = req; + return 1; + } + return 0; + }); + + bool value = static_cast<bool>(gpio.getValue()); + if (inverted) + { + value = !value; + } + iface->register_property( + "Value", value, + // Override set + [this, gpioName, inverted](const bool& req, + bool& propertyValue) { + auto it = findGpioObj(gpioName); + + if (it != nullptr) + { + // If Gpio enabled property is set as true then + // reject set request + if (it->getEnabled()) + { + Gpio gpio = + Gpio(std::to_string(it->getNumber())); + bool setVal = req; + if (inverted) + { + setVal = !setVal; + } + gpio.setValue( + static_cast<GpioValue>(setVal)); + + propertyValue = req; + return 1; + } + return 0; + } + return 0; + }); + + iface->register_property( + "Direction", gpio.getDirection(), + // Override set + [this, gpioName](const std::string& req, + std::string& propertyValue) { + auto it = findGpioObj(gpioName); + + if (it != nullptr) + { + // If Gpio enabled property is set as true than + // reject request + if (it->getEnabled()) + { + Gpio gpio = + Gpio(std::to_string(it->getNumber())); + gpio.setDirection(req); + + propertyValue = req; + return 1; + } + return 0; + } + return 0; + }); + iface->initialize(); + } + }, + entityMgrService, path, propInterface, "GetAll", + gpioConfigInterface); + } +} + +GpioEn* GpioManager::findGpioObj(const std::string& gpioName) +{ + auto it = std::find_if( + gpioEnableList.begin(), gpioEnableList.end(), + [&gpioName](const GpioEn& obj) { return obj.getName() == gpioName; }); + if (it != gpioEnableList.end()) + { + return &(*it); + } + return nullptr; +} + +bool GpioManager::findGpioDirs( + const std::experimental::filesystem::path& dirPath, + const std::string& matchString, + std::vector<std::experimental::filesystem::path>& foundPaths) +{ + if (!std::experimental::filesystem::exists(dirPath)) + { + return false; + } + + std::regex search(matchString); + std::smatch match; + for (const auto& p : + std::experimental::filesystem::recursive_directory_iterator(dirPath)) + { + std::string path = p.path().string(); + if (is_directory(p)) + { + if (std::regex_search(path, match, search)) + { + foundPaths.emplace_back(p.path()); + } + } + } + return true; +} + +int main() +{ + boost::asio::io_service io; + auto systemBus = std::make_shared<sdbusplus::asio::connection>(io); + + systemBus->request_name(gpioService); + sdbusplus::asio::object_server server(systemBus); + + static auto match = std::make_unique<sdbusplus::bus::match::match>( + static_cast<sdbusplus::bus::bus&>(*systemBus), + "type='signal',member='PropertiesChanged'," + "arg0namespace='" + + std::string(gpioConfigInterface) + "'", + [](sdbusplus::message::message& message) { + phosphor::logging::log<phosphor::logging::level::INFO>( + "New configuration detected. Restarting gpiodaemon."); + + std::this_thread::sleep_for(std::chrono::seconds(waitTime)); + + // todo: restarting isn't the best approach, really we should detect + // what changed and add the appropriate gpios, this will be changed + // shortly + std::exit(0); + }); + + GpioManager gpioMgr(server, systemBus); + + io.run(); +} diff --git a/gpiodaemon/src/gpioutils.cpp b/gpiodaemon/src/gpioutils.cpp new file mode 100644 index 0000000..9561795 --- /dev/null +++ b/gpiodaemon/src/gpioutils.cpp @@ -0,0 +1,116 @@ +/* +// Copyright (c) 2018 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +*/ + +#include <gpioutils.hpp> + +static constexpr const char* pathExport = "/sys/class/gpio/export"; +static constexpr const char* pathUnexport = "/sys/class/gpio/unexport"; +static constexpr const char* prefix = "/sys/class/gpio/gpio"; +static constexpr const char* postfixValue = "/value"; +static constexpr const char* postfixDirection = "/direction"; + +Gpio::Gpio(std::string number) : gpioNumber(number) +{ + gpioExport(); +} + +bool Gpio::gpioExist() +{ + return std::experimental::filesystem::exists(prefix + gpioNumber); +} + +void Gpio::gpioExport() +{ + if (!gpioExist()) + { + std::fstream gpioExport; + gpioExport.open(pathExport, std::ios::out); + if (gpioExport.good()) + { + gpioExport << gpioNumber; + } + } +} + +void Gpio::gpioUnexport() +{ + if (gpioExist()) + { + std::fstream gpioExport; + gpioExport.open(pathUnexport, std::ios::out); + if (gpioExport.good()) + { + gpioExport << gpioNumber; + } + } +} + +GpioValue Gpio::getValue() +{ + std::fstream gpioFile; + std::string gpioValue; + std::string gpioFilePath = prefix + gpioNumber + postfixValue; + + gpioFile.open(gpioFilePath, std::ios::in); + if (gpioFile.good()) + { + gpioFile >> gpioValue; + } + + return gpioValue == "0" ? GpioValue::low : GpioValue::high; +} + +void Gpio::setValue(const GpioValue& value) +{ + std::fstream gpioFile; + std::string gpioFilePath = prefix + gpioNumber + postfixValue; + + setDirection("out"); + + gpioFile.open(gpioFilePath, std::ios::out); + if (gpioFile.good()) + { + gpioFile << std::to_string((uint8_t)value); + } +} + +std::string Gpio::getDirection() +{ + std::fstream gpioFile; + std::string gpioFilePath = prefix + gpioNumber + postfixDirection; + std::string direction; + + gpioFile.open(gpioFilePath, std::ios::in); + if (gpioFile.good()) + { + gpioFile >> direction; + } + + return direction; +} + +void Gpio::setDirection(const std::string& direction) +{ + std::fstream gpioFile; + std::string gpioFilePath = prefix + gpioNumber + postfixDirection; + + gpioFile.open(gpioFilePath, std::ios::out); + if (gpioFile.good()) + { + gpioFile << direction; + } + gpioFile.close(); +} |