From a27ecb70699f6f48cd4ad75a1b643b6d1083af97 Mon Sep 17 00:00:00 2001 From: Dynamic Readme Date: Fri, 10 Sep 2021 20:59:58 +0000 Subject: [PATCH 001/147] =?UTF-8?q?=F0=9F=92=AC=20-=20File=20Rebuilt=20|?= =?UTF-8?q?=20Github=20Action=20Runner=20:=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 7725d8e..65f9ac5 100644 --- a/README.md +++ b/README.md @@ -8,26 +8,26 @@ - - + + - - + + - - + + - - + + - - + + - - + + - - + +

From f10d55eb46c782d5ddc0da70818c2602fb14baa0 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Sat, 11 Sep 2021 20:40:14 -0300 Subject: [PATCH 002/147] Adding the Routine interface to the routine.cpp and routine.hpp archives --- src/classes/routine/routine.cpp | 10 ++++++++++ src/classes/routine/routine.hpp | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/classes/routine/routine.cpp b/src/classes/routine/routine.cpp index e69de29..83c6aef 100644 --- a/src/classes/routine/routine.cpp +++ b/src/classes/routine/routine.cpp @@ -0,0 +1,10 @@ +/* +* service.cpp +* +* Author: Carlos Craveiro (@CarlosCraveiro) +* Created On: September 11, 2021 +* +*/ + +#include "routine.hpp" + diff --git a/src/classes/routine/routine.hpp b/src/classes/routine/routine.hpp index e69de29..7d53db2 100644 --- a/src/classes/routine/routine.hpp +++ b/src/classes/routine/routine.hpp @@ -0,0 +1,26 @@ +/* +* routine.hpp +* +* Author: Carlos Craveiro (@CarlosCraveiro) +* Created On: September 11, 2021 +* +*/ + +#pragma once + +typedef enum state_t { + MISSINGDEPENDENCIES = 0, UNINITIALIZED, INITIALIZED, RUNNING, STOPED, DEAD + +}; + +class IRoutine { + public: + std::string id; + public: + virtual void onLoad()=0; + virtual void loop()=0; + virtual void unload()=0; + IRoutine(std::string id): id{id} {} + ~IRoutine(void){}; +}; + From 7c0d8c505d02fc69192a737401f51ca1bf64221b Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Sat, 11 Sep 2021 20:44:25 -0300 Subject: [PATCH 003/147] Fixing compiling problems with routine.hpp --- src/classes/routine/routine.hpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/classes/routine/routine.hpp b/src/classes/routine/routine.hpp index 7d53db2..394246b 100644 --- a/src/classes/routine/routine.hpp +++ b/src/classes/routine/routine.hpp @@ -7,11 +7,12 @@ */ #pragma once +#include -typedef enum state_t { +typedef enum { MISSINGDEPENDENCIES = 0, UNINITIALIZED, INITIALIZED, RUNNING, STOPED, DEAD -}; +} stateT; class IRoutine { public: From c1f7772efa04ccddf0944ae849a15ffb0464ba98 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Sun, 12 Sep 2021 03:39:14 -0300 Subject: [PATCH 004/147] adding the routine-handler functionality --- .../routine-handler/routine-handler.cpp | 68 +++++++++++++++++++ .../routine-handler/routine-handler.hpp | 30 ++++++++ src/classes/routine/routine.hpp | 12 +++- 3 files changed, 107 insertions(+), 3 deletions(-) diff --git a/src/classes/routine-handler/routine-handler.cpp b/src/classes/routine-handler/routine-handler.cpp index e69de29..eafc6a6 100644 --- a/src/classes/routine-handler/routine-handler.cpp +++ b/src/classes/routine-handler/routine-handler.cpp @@ -0,0 +1,68 @@ +/* +* routine-handler.cpp +* +* Author: Carlos Craveiro (@CarlosCraveiro) +* Created On: September 11, 2021 +*/ + +#include "routine-handler.hpp" + +void routineModule(IRoutine& routine, Status& status) { + routine.onLoad(); + status.mtx.lock(); + status.state = Status::RUNNING; + status.mtx.unlock(); + while(status.state == Status::STOPED){ + status.mtx.unlock(); + routine.loop(); + status.mtx.lock(); + } + status.mtx.unlock(); +} + +RoutineHandler::RoutineHandler(IRoutine& routine, nlohmann::json dependecies, nlohmann::json currentDependecies) { + (*this->routine) = routine; + this->status.mtx.lock(); + this->status.state = Status::UNINITIALIZED; + this->status.mtx.unlock(); + (*this->dependecies) = dependecies; + this->currentDependecies = currentDependecies; +} + +RoutineHandler::~RoutineHandler() { + //DO NOTHING +} + +void RoutineHandler::run(void) { + std::thread thread(routineModule, std::ref(*routine), std::ref(status)); + status.mtx.lock(); + status.state = Status::INITIALIZED; + status.mtx.unlock(); + std::swap(thread, innerThread); +} + +void RoutineHandler::stop(void) { + status.mtx.lock(); + status.state = Status::STOPED; + status.mtx.unlock(); + innerThread.join(); + status.mtx.lock(); + status.state = Status::DEAD; + status.mtx.unlock(); +} + +nlohmann::json RoutineHandler::getStatus(void) { + //DO NOTHING + nlohmann::json myjson; + myjson["pi"] = 3.14; + return myjson; + +} + +nlohmann::json RoutineHandler::update(nlohmann::json& updateList) { + //DO NOTHING + nlohmann::json myjson; + myjson["pi"] = 3.14; + return myjson; +} + diff --git a/src/classes/routine-handler/routine-handler.hpp b/src/classes/routine-handler/routine-handler.hpp index e69de29..f7fa92f 100644 --- a/src/classes/routine-handler/routine-handler.hpp +++ b/src/classes/routine-handler/routine-handler.hpp @@ -0,0 +1,30 @@ +/* +* routine-handler.hpp +* +* Author: Carlos Craveiro (@CarlosCraveiro) +* Created On: September 11, 2021 +*/ + +#pragma once +#include +#include "../routine/routine.hpp" + +void routineModule(IRoutine& routine, Status& status); + +class RoutineHandler { + public: + IRoutine* routine; + Status status; + std::thread innerThread; + nlohmann::json* dependecies; + nlohmann::json currentDependecies; + + public: + void run(void); + void stop(void); + nlohmann::json getStatus(void); + nlohmann::json update(nlohmann::json& updateList); + RoutineHandler(IRoutine& routine, nlohmann::json dependecies, nlohmann::json currentDependecies); + ~RoutineHandler(void); +}; + diff --git a/src/classes/routine/routine.hpp b/src/classes/routine/routine.hpp index 394246b..fadb445 100644 --- a/src/classes/routine/routine.hpp +++ b/src/classes/routine/routine.hpp @@ -8,11 +8,17 @@ #pragma once #include +#include -typedef enum { - MISSINGDEPENDENCIES = 0, UNINITIALIZED, INITIALIZED, RUNNING, STOPED, DEAD +class Status { + public: + enum stateT { + MISSINGDEPENDENCIES = 0, UNINITIALIZED, INITIALIZED, RUNNING, STOPED, DEAD -} stateT; + }; + stateT state; + std::mutex mtx; +}; class IRoutine { public: From f4ee34b18f4428032dffcc248c74c21c1380fcb1 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Sun, 12 Sep 2021 03:49:07 -0300 Subject: [PATCH 005/147] solving a mutex problem in routineModule --- src/classes/routine-handler/routine-handler.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/classes/routine-handler/routine-handler.cpp b/src/classes/routine-handler/routine-handler.cpp index eafc6a6..28069dc 100644 --- a/src/classes/routine-handler/routine-handler.cpp +++ b/src/classes/routine-handler/routine-handler.cpp @@ -11,7 +11,6 @@ void routineModule(IRoutine& routine, Status& status) { routine.onLoad(); status.mtx.lock(); status.state = Status::RUNNING; - status.mtx.unlock(); while(status.state == Status::STOPED){ status.mtx.unlock(); routine.loop(); From fc381229b8f995d7c44ea2a833adfd330f518cd6 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Sun, 12 Sep 2021 13:57:46 +0200 Subject: [PATCH 006/147] adding cmake and conan simple setup files --- CMakeLists.txt | 10 ++++++++++ conanfile.txt | 6 ++++++ 2 files changed, 16 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 conanfile.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..ea00286 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.16.3) +project(daemons-framework) + +add_definitions("-std=c++17") + +include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) +conan_basic_setup() + +add_executable(daemonTest tests/mainTest.cpp) +target_link_libraries(daemonTest ${CONAN_LIBS}) \ No newline at end of file diff --git a/conanfile.txt b/conanfile.txt new file mode 100644 index 0000000..cb82b6e --- /dev/null +++ b/conanfile.txt @@ -0,0 +1,6 @@ +[requires] +nlohmann_json/3.10.2 +sdbus-cpp/0.8.3 + +[generators] +cmake \ No newline at end of file From b77c933c86f128e418cf0c6973588b86a47c0f0c Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 14 Sep 2021 01:25:33 +0200 Subject: [PATCH 007/147] adding test to git ignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 193da6a..a05b696 100644 --- a/.gitignore +++ b/.gitignore @@ -1038,3 +1038,4 @@ modules.order Module.symvers Mkfile.old dkms.conf +tests/mainTest.cpp \ No newline at end of file From 4c10a6b007c6dc8132e10f97a575b9b4754913af Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Tue, 14 Sep 2021 17:48:32 -0300 Subject: [PATCH 008/147] Adding checkStatus and update functionalities to the routine-handler --- .../routine-handler/routine-handler.cpp | 56 ++++++++++++++----- .../routine-handler/routine-handler.hpp | 14 +++-- 2 files changed, 52 insertions(+), 18 deletions(-) diff --git a/src/classes/routine-handler/routine-handler.cpp b/src/classes/routine-handler/routine-handler.cpp index 28069dc..d2bd9f3 100644 --- a/src/classes/routine-handler/routine-handler.cpp +++ b/src/classes/routine-handler/routine-handler.cpp @@ -19,13 +19,18 @@ void routineModule(IRoutine& routine, Status& status) { status.mtx.unlock(); } -RoutineHandler::RoutineHandler(IRoutine& routine, nlohmann::json dependecies, nlohmann::json currentDependecies) { +RoutineHandler::RoutineHandler(IRoutine& routine, nlohmann::json& configs) { (*this->routine) = routine; this->status.mtx.lock(); - this->status.state = Status::UNINITIALIZED; + this->status.state = Status::MISSINGDEPENDENCIES; this->status.mtx.unlock(); - (*this->dependecies) = dependecies; - this->currentDependecies = currentDependecies; + this->depsRefState = configs["dependencies"]; + this->depsCrntState = configs["dependencies"]; + for(nlohmann::json& dependencie : this->depsCrntState) { + dependencie["status"] = Status::MISSINGDEPENDENCIES; + } + this->info.data = configs; + } RoutineHandler::~RoutineHandler() { @@ -47,21 +52,44 @@ void RoutineHandler::stop(void) { innerThread.join(); status.mtx.lock(); status.state = Status::DEAD; - status.mtx.unlock(); + status.mtx.unlock(); } nlohmann::json RoutineHandler::getStatus(void) { - //DO NOTHING - nlohmann::json myjson; - myjson["pi"] = 3.14; - return myjson; + std::lock_guard lck(info.occupied); + status.mtx.lock(); + info.data["state"] = status.state; + status.mtx.unlock(); + return info.data; } -nlohmann::json RoutineHandler::update(nlohmann::json& updateList) { - //DO NOTHING - nlohmann::json myjson; - myjson["pi"] = 3.14; - return myjson; +nlohmann::json RoutineHandler::update(void) { + int missingDeps = depsRefState["lenght"]; + for(int i = 0; i < depsRefState["lenght"]; i++) { + using namespace nlohmann; + const json& dependencie = depsCrntState[i]; + const json& dependencieRef = depsRefState[i]; + if(dependencie["status"] == dependencieRef["status"]) { + missingDeps--; + } + } + if(!missingDeps) { + run(); + nlohmann::json changes = getStatus(); + return (nlohmann::json) {{{"changed", true}}, changes}; + } + status.mtx.lock(); + if(status.state == Status::RUNNING) { + status.mtx.unlock(); + stop(); + status.mtx.lock(); + status.state = Status::MISSINGDEPENDENCIES; + status.mtx.unlock(); + nlohmann::json changes = getStatus(); + return (nlohmann::json) {{{"changed", true}}, changes}; + } + status.mtx.unlock(); + return (nlohmann::json) {{"changed", false}}; } diff --git a/src/classes/routine-handler/routine-handler.hpp b/src/classes/routine-handler/routine-handler.hpp index f7fa92f..e9f183c 100644 --- a/src/classes/routine-handler/routine-handler.hpp +++ b/src/classes/routine-handler/routine-handler.hpp @@ -7,6 +7,7 @@ #pragma once #include +#include #include "../routine/routine.hpp" void routineModule(IRoutine& routine, Status& status); @@ -14,17 +15,22 @@ void routineModule(IRoutine& routine, Status& status); class RoutineHandler { public: IRoutine* routine; + struct Info { + nlohmann::json data; + std::mutex occupied; + }; + Info info; Status status; std::thread innerThread; - nlohmann::json* dependecies; - nlohmann::json currentDependecies; + nlohmann::json depsRefState; + nlohmann::json depsCrntState; public: void run(void); void stop(void); nlohmann::json getStatus(void); - nlohmann::json update(nlohmann::json& updateList); - RoutineHandler(IRoutine& routine, nlohmann::json dependecies, nlohmann::json currentDependecies); + nlohmann::json update(void); + RoutineHandler(IRoutine& routine, nlohmann::json& configs); ~RoutineHandler(void); }; From aefd0e2694267997b2f032a2588db9bf1799d500 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Thu, 16 Sep 2021 17:37:43 +0200 Subject: [PATCH 009/147] initial model of .conf deamon file --- examples/configModel.json | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 examples/configModel.json diff --git a/examples/configModel.json b/examples/configModel.json new file mode 100644 index 0000000..02c66bb --- /dev/null +++ b/examples/configModel.json @@ -0,0 +1,36 @@ +{ + "daemonId": "DaemonIdExample", + "endpoints": [{ + "id": "endpoint1Name", + "type": "signal", + "triggers": ["trigger1", "trigger2", "..."], + "dependencies": [{ + "type": "routine", + "name": "org.zenith.daemons.daemon1.routineA", + "status": 0 + }] + }, + { + "id": "endpoint2Name", + "type": "method", + "triggers": ["trigger1"], + "dependencies": [{ + "type": "daemon", + "name": "org.zenith.daemons.daemon2", + "status": 1 + }] + } + ], + "routines": [{ + "id": "routine1Name", + "signals": ["mySignal1, mySignal2"], + "dependencies": [{ + "type": "endpoint", + "name": "org.zenith.daemons.daemon3.endpointB", + "status": 2 + }] + }], + "data": { + "anything": "anything" + } +} \ No newline at end of file From fdd2c30bb9e226079dcb9fdaf8e0f34c44c9626d Mon Sep 17 00:00:00 2001 From: Math-42 Date: Thu, 16 Sep 2021 17:37:53 +0200 Subject: [PATCH 010/147] removing gitkeep --- examples/.gitkeep | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 examples/.gitkeep diff --git a/examples/.gitkeep b/examples/.gitkeep deleted file mode 100644 index e69de29..0000000 From 7c0cfee46e0b67e5884c5c8fa9e87596abaad537 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Wed, 15 Sep 2021 22:25:11 +0200 Subject: [PATCH 011/147] moving XML-configurator to the tools dir --- {src/classes => tools}/XML-configurator/XML-configurator.cpp | 0 {src/classes => tools}/XML-configurator/XML-configurator.hpp | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {src/classes => tools}/XML-configurator/XML-configurator.cpp (100%) rename {src/classes => tools}/XML-configurator/XML-configurator.hpp (100%) diff --git a/src/classes/XML-configurator/XML-configurator.cpp b/tools/XML-configurator/XML-configurator.cpp similarity index 100% rename from src/classes/XML-configurator/XML-configurator.cpp rename to tools/XML-configurator/XML-configurator.cpp diff --git a/src/classes/XML-configurator/XML-configurator.hpp b/tools/XML-configurator/XML-configurator.hpp similarity index 100% rename from src/classes/XML-configurator/XML-configurator.hpp rename to tools/XML-configurator/XML-configurator.hpp From 5345ba43eaa58d2f6ae85e126245c04e0680097c Mon Sep 17 00:00:00 2001 From: Math-42 Date: Wed, 15 Sep 2021 22:26:08 +0200 Subject: [PATCH 012/147] adding utilitie tool to handle dbus functionality names --- .../DBusNameHandler/dbus-name-handler.cpp | 37 +++++++++++++++++++ .../DBusNameHandler/dbus-name-handler.hpp | 24 ++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 src/utilities/DBusNameHandler/dbus-name-handler.cpp create mode 100644 src/utilities/DBusNameHandler/dbus-name-handler.hpp diff --git a/src/utilities/DBusNameHandler/dbus-name-handler.cpp b/src/utilities/DBusNameHandler/dbus-name-handler.cpp new file mode 100644 index 0000000..ab74b7f --- /dev/null +++ b/src/utilities/DBusNameHandler/dbus-name-handler.cpp @@ -0,0 +1,37 @@ +#include "./dbus-name-handler.hpp" + +DBusName::DBusName(std::string serviceId) { + serviceIdDots = "org.frameworkd." + serviceId; + serviceIdSlashes = "/" + serviceIdDots; + std::replace(serviceIdSlashes.begin(), serviceIdSlashes.end(), '.', '/'); +} + +std::string DBusName::getDaemonId() { + return serviceIdDots; +} + +std::string DBusName::getObjectPath(std::string objectName) { + return serviceIdSlashes + "/" + objectName; +} + +std::string DBusName::getInterfaceName(std::string interfaceName) { + return serviceIdDots + "." + interfaceName; +} + +nlohmann::json DBusName::parseFuncionalityPath(std::string functionalityPath) { + std::replace(functionalityPath.begin(), functionalityPath.end(), '/', ' '); + std::vector array; + std::stringstream ss(functionalityPath); + + std::string word; + while (ss >> word) array.push_back(word); + + nlohmann::json parsedResponse; + + parsedResponse["serviceId"] = array[0] + "." + array[1] + "." + array[2]; + parsedResponse["objectPath"] = "/" + array[0] + "/" + array[1] + "/" + array[2] + "/" + array[3]; + parsedResponse["interfaceName"] = array[0] + "." + array[1] + "." + array[2] +"." + array[3]; + parsedResponse["functionalityName"] = array[4]; + + return parsedResponse; +} diff --git a/src/utilities/DBusNameHandler/dbus-name-handler.hpp b/src/utilities/DBusNameHandler/dbus-name-handler.hpp new file mode 100644 index 0000000..a477adb --- /dev/null +++ b/src/utilities/DBusNameHandler/dbus-name-handler.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include +#include +#include + +class DBusName { + private: + + std::string serviceIdDots; + std::string serviceIdSlashes; + + public: + + DBusName(std::string serviceId); + std::string getObjectPath(std::string objectName); + std::string getDaemonId(); + std::string getInterfaceName(std::string interfaceName); + + static nlohmann::json parseFuncionalityPath(std::string funcionalityPath); + +}; \ No newline at end of file From b5b49335191c9f2ac22aaa47fef327f0da688cf9 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 16 Sep 2021 01:04:27 -0300 Subject: [PATCH 013/147] Starting the service.hpp --- src/classes/service/service.hpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/classes/service/service.hpp b/src/classes/service/service.hpp index e69de29..9bce00b 100644 --- a/src/classes/service/service.hpp +++ b/src/classes/service/service.hpp @@ -0,0 +1,26 @@ +/* + * service.hpp + * + * Author: Carlos Craveiro (@CarlosCraveiro) + * Created On: September 15, 2021 + */ + +#pragma once +#include +#include +#include "../routine-handler/routine-handler.hpp" + +class Service { + public: + std::vector routines; + std::vector endpoints; + public: + nlohmann::json getServiceStatus(void); + nlohmann::json updateAll(nlohmann::json updateList); + nlohmann::json registerEndpoints(void); + nlohmann::json registerRoutines(void); + + void buildEndpoint(/*IEndpoint& newEndpoint*/); + void buildRoutine(IRoutine& newRoutine); +}; + From 04e44c30708c2af3814d2cbd1225eedccf7c7523 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Thu, 16 Sep 2021 17:34:07 +0200 Subject: [PATCH 014/147] first version of DBusHandler methods --- src/classes/dbus-handler/dbus-handler.cpp | 65 +++++++++++++++++++++++ src/classes/dbus-handler/dbus-handler.hpp | 24 +++++++++ 2 files changed, 89 insertions(+) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index e69de29..3b4453a 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -0,0 +1,65 @@ +#include "./dbus-handler.hpp" + +#include +#include + +DBusHandler::DBusHandler(std::string serviceName, nlohmann::json DBusObjectConfig) { + std::string objectNameTemp = DBusObjectConfig["id"]; + interfaceName = objectPath = serviceName + "." + objectNameTemp; + + std::replace(objectPath.begin(), objectPath.end(), ".", "/"); + objectPath = "/" + objectPath; + + DBusObject = sdbus::createObject(*connection, objectPath); + SDbusEmitter = DBusObject.get(); + + std::vector signalsNames = DBusObjectConfig["emittedSignals"]; + registerSignals(signalsNames); +} + +/** + * + *@todo + * Adicionar regex para o endpoint name /word/word/word... + * Adicionar callMethod async(?) + */ +nlohmann::json DBusHandler::callMethod(std::string endpointName, nlohmann::json arg) { + if (DBusProxys.count(endpointName) != true) throw std::invalid_argument("endpoint not found"); + + std::vector response; + std::string destinationInterface = endpointName; + + destinationInterface.erase(0, 1); + std::replace(destinationInterface.begin(), destinationInterface.end(), "/", "."); + + auto method = DBusProxys[endpointName]->createMethodCall(interfaceName, endpointName); + method << nlohmann::json::to_bson(arg); + auto reply = DBusProxys[endpointName]->callMethod(method); + + reply >> response; + + return nlohmann::json::from_bson(response); +} + +void DBusHandler::emitSignal(std::string signalName, nlohmann::json arg) { + auto signal = SDbusEmitter->createSignal(interfaceName, signalName); + signal << nlohmann::json::to_bson(arg); + SDbusEmitter->emitSignal(signal); +} + +void DBusHandler::registerSignals(std::vector signalsNames) { + for (int i = 0; i < signalsNames.size(); i++) { + DBusObject->registerSignal(interfaceName, signalsNames[i], "ai"); + } +} + +void DBusHandler::getProxys(nlohmann::json DBusObjectConfig) { + std::vector tempDependencies = DBusObjectConfig["dependencies"]; + + for(const& dependency : tempDependencies){ + + } +} + +void bind() { +} diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index e69de29..aa1c770 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -0,0 +1,24 @@ +#include + +#include +#include +#include + +class DBusHandler { + private: + std::string objectPath; + std::string interfaceName; + + std::unique_ptr connection; + + sdbus::IObject* SDbusEmitter; + std::unique_ptr DBusObject; + std::map> DBusProxys; + void getProxys(nlohmann::json DBusObjectConfig); + public: + + DBusHandler(std::string serviceName, nlohmann::json DBusObjectConfig); + void emitSignal(std::string signalName, nlohmann::json arg); + nlohmann::json callMethod(std::string endpointName, nlohmann::json arg); + void registerSignals(std::vector signalsNames); +}; \ No newline at end of file From 993025561d64385aeb49cf405de1809d2d918182 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Thu, 16 Sep 2021 17:35:10 +0200 Subject: [PATCH 015/147] dbus-controller header file --- .../dbus-controller/dbus-controller.cpp | 5 +++++ .../dbus-controller/dbus-controller.hpp | 20 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/classes/dbus-controller/dbus-controller.cpp b/src/classes/dbus-controller/dbus-controller.cpp index e69de29..77ba9cf 100644 --- a/src/classes/dbus-controller/dbus-controller.cpp +++ b/src/classes/dbus-controller/dbus-controller.cpp @@ -0,0 +1,5 @@ +#include "./dbus-controller.hpp" + +DBusController::DBusController(std::string serviceName) : serviceName{serviceName} { + connection = sdbus::createSystemBusConnection(serviceName); +} \ No newline at end of file diff --git a/src/classes/dbus-controller/dbus-controller.hpp b/src/classes/dbus-controller/dbus-controller.hpp index e69de29..42d5488 100644 --- a/src/classes/dbus-controller/dbus-controller.hpp +++ b/src/classes/dbus-controller/dbus-controller.hpp @@ -0,0 +1,20 @@ +#include + +#include +#include +class DBusController { + private: + std::string serviceName; + + std::unique_ptr connection; + std::map> DBusObjects; + + public: + DBusController(std::string serviceName); + + void bindSignal(std::string signalName, void (*signalHandler)(std::string json)); + void bindEndpoint(std::string endpointName, sdbus::method_callback signalHandler); + void startListen(); + + ~DBusController(); +}; From acedaa6863bef19dd829bdbee166a85a9c39dedb Mon Sep 17 00:00:00 2001 From: math-42 Date: Sun, 19 Sep 2021 19:37:19 -0300 Subject: [PATCH 016/147] DBus handler header file interfaces --- src/classes/dbus-handler/dbus-handler.hpp | 82 +++++++++++++++++++---- 1 file changed, 70 insertions(+), 12 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index aa1c770..fed989d 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -1,24 +1,82 @@ -#include +#pragma once +#include "../../utils/path-handler/path-handler.hpp" +#include #include #include #include +#include +#include class DBusHandler { + + public: + + using DBusObjectMap = std::map>; + using DBusProxyMap = std::map>; + using DBusVoidCallback = std::function; + using DBusCallback = std::function; + + private: + + std::string _serviceName; + bool _started; + + std::unique_ptr _connection; + + DBusObjectMap _DBusObjects; + DBusProxyMap _DBusProxys; + private: - std::string objectPath; - std::string interfaceName; - std::unique_ptr connection; + sdbus::IObject* addObject(std::string objectPath); + + sdbus::IProxy* addProxy(std::string service, std::string objectPath); + + void registerMethod(PathHandler::dbusPath path, DBusCallback callback); + + void subscribeToSignal(PathHandler::dbusPath path, DBusVoidCallback callback); + + void registerSignal(PathHandler::dbusPath path); + + nlohmann::json callMethod(PathHandler::dbusPath path, nlohmann::json arg); + + void callMethodAsync(PathHandler::dbusPath path, nlohmann::json arg, DBusVoidCallback callback); + + void emitSignal(PathHandler::dbusPath path, nlohmann::json arg); + + - sdbus::IObject* SDbusEmitter; - std::unique_ptr DBusObject; - std::map> DBusProxys; - void getProxys(nlohmann::json DBusObjectConfig); public: - DBusHandler(std::string serviceName, nlohmann::json DBusObjectConfig); - void emitSignal(std::string signalName, nlohmann::json arg); - nlohmann::json callMethod(std::string endpointName, nlohmann::json arg); - void registerSignals(std::vector signalsNames); + DBusHandler(std::string serviceName); + + DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys); + + DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys, std::unique_ptr connection); + + nlohmann::json call(std::string dbusPath, nlohmann::json req); + + nlohmann::json call(std::string dbusPath, nlohmann::json req, DBusCallback callback); + + nlohmann::json expose(std::string dbusPath, nlohmann::json req, DBusCallback getter, DBusVoidCallback setter); + + nlohmann::json get(std::string dbusPath, nlohmann::json req); + + nlohmann::json get(std::string dbusPath, nlohmann::json req, DBusVoidCallback callback); + + nlohmann::json set(std::string dbusPath, nlohmann::json req); + + nlohmann::json subscribe(std::string dbusPath, DBusCallback callback); + + nlohmann::json subscribe(std::string dbusPath, DBusCallback callback, nlohmann::json dependencies); + + nlohmann::json bind(std::string dbusPath, DBusCallback callback); + + nlohmann::json bind(std::string dbusPath, DBusCallback callback, nlohmann::json dependencies); + + nlohmann::json emit(std::string dbusPath, nlohmann::json arg); + + void finish(); + }; \ No newline at end of file From b3823fc6f549efcabc1c996bcdbe00905f5bfb2c Mon Sep 17 00:00:00 2001 From: math-42 Date: Sun, 19 Sep 2021 19:38:17 -0300 Subject: [PATCH 017/147] first version of the private methods --- src/classes/dbus-handler/dbus-handler.cpp | 164 ++++++++++++++++------ 1 file changed, 124 insertions(+), 40 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index 3b4453a..71d6ec3 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,65 +1,149 @@ #include "./dbus-handler.hpp" -#include -#include -DBusHandler::DBusHandler(std::string serviceName, nlohmann::json DBusObjectConfig) { - std::string objectNameTemp = DBusObjectConfig["id"]; - interfaceName = objectPath = serviceName + "." + objectNameTemp; - std::replace(objectPath.begin(), objectPath.end(), ".", "/"); - objectPath = "/" + objectPath; +DBusHandler::DBusHandler(std::string serviceName) { + _serviceName = "org.frameworkd." + serviceName; + _connection = sdbus::createSystemBusConnection(_serviceName); +} + +sdbus::IObject* DBusHandler::addObject(std::string objectPath) { + _DBusObjects[objectPath] = sdbus::createObject(*_connection, objectPath); + return _DBusObjects[objectPath].get(); +} + +sdbus::IProxy* DBusHandler::addProxy(std::string destinationService, std::string objectPath) { - DBusObject = sdbus::createObject(*connection, objectPath); - SDbusEmitter = DBusObject.get(); + std::string uniqueId = destinationService + objectPath; + + _DBusProxys[uniqueId] = sdbus::createProxy(destinationService, objectPath); - std::vector signalsNames = DBusObjectConfig["emittedSignals"]; - registerSignals(signalsNames); + return _DBusProxys[uniqueId].get(); } -/** - * - *@todo - * Adicionar regex para o endpoint name /word/word/word... - * Adicionar callMethod async(?) - */ -nlohmann::json DBusHandler::callMethod(std::string endpointName, nlohmann::json arg) { - if (DBusProxys.count(endpointName) != true) throw std::invalid_argument("endpoint not found"); +void DBusHandler::registerMethod(PathHandler::dbusPath path, DBusCallback callback) { + + auto exists = _DBusObjects.find(path.objectPath); + auto object = (exists != _DBusObjects.end())? exists->second.get() : addObject(path.objectPath); + + auto wrapper = [&callback](sdbus::MethodCall call) { + + std::vector bson; + call >> bson; - std::vector response; - std::string destinationInterface = endpointName; + nlohmann::json answer = callback(nlohmann::json::from_bson(bson)); + + auto reply = call.createReply(); + + reply << nlohmann::json::to_bson(answer); + + reply.send(); + + }; + + object->registerMethod(path.interface, path.functionality, "ai", "ai", wrapper); + +} - destinationInterface.erase(0, 1); - std::replace(destinationInterface.begin(), destinationInterface.end(), "/", "."); +void DBusHandler::subscribeToSignal(PathHandler::dbusPath path, DBusVoidCallback callback) { + + std::string uniqueId = path.service + path.objectPath; + + auto exists = _DBusProxys.find(uniqueId); + auto proxy = (exists != _DBusProxys.end())? exists->second.get() : addProxy(path.service, path.objectPath); + + auto wrapper = [&callback](sdbus::Signal& signal) { + + std::vector bson; + signal >> bson; + + callback(nlohmann::json::from_bson(bson)); + + }; + + proxy->registerSignalHandler(path.interface, path.functionality, wrapper); + +} + +void DBusHandler::registerSignal(PathHandler::dbusPath path) { + + auto exists = _DBusObjects.find(path.objectPath); + auto object = (exists != _DBusObjects.end())? exists->second.get() : addObject(path.objectPath); + + object->registerSignal(path.interface, path.functionality, "ai"); + +} + +nlohmann::json DBusHandler::callMethod(PathHandler::dbusPath path, nlohmann::json arg) { + if(!_started) return; //add error + + std::string uniqueId = path.service + path.objectPath; + + auto exists = _DBusProxys.find(uniqueId); + auto proxy = (exists != _DBusProxys.end())? exists->second.get() : addProxy(path.service, path.objectPath); + + auto method = proxy->createMethodCall(path.interface, path.functionality); - auto method = DBusProxys[endpointName]->createMethodCall(interfaceName, endpointName); method << nlohmann::json::to_bson(arg); - auto reply = DBusProxys[endpointName]->callMethod(method); - reply >> response; + auto reply = proxy->callMethod(method); + + std::vector bson; + + reply >> bson; + + return nlohmann::json::from_bson(bson); - return nlohmann::json::from_bson(response); } -void DBusHandler::emitSignal(std::string signalName, nlohmann::json arg) { - auto signal = SDbusEmitter->createSignal(interfaceName, signalName); - signal << nlohmann::json::to_bson(arg); - SDbusEmitter->emitSignal(signal); +void DBusHandler::callMethodAsync(PathHandler::dbusPath path, nlohmann::json arg, DBusVoidCallback callback) { + if(!_started) return; //add error + + std::string uniqueId = path.service + path.objectPath; + + auto exists = _DBusProxys.find(uniqueId); + auto proxy = (exists != _DBusProxys.end())? exists->second.get() : addProxy(path.service, path.objectPath); + + auto method = proxy->createMethodCall(path.interface, path.functionality); + + method << nlohmann::json::to_bson(arg); + + auto wrapper = [&callback](sdbus::MethodReply& reply, const sdbus::Error* error) { + + std::vector bson; + reply >> bson; + + callback(nlohmann::json::from_bson(bson)); + + }; + + auto reply = proxy->callMethod(method, wrapper); } -void DBusHandler::registerSignals(std::vector signalsNames) { - for (int i = 0; i < signalsNames.size(); i++) { - DBusObject->registerSignal(interfaceName, signalsNames[i], "ai"); - } +void DBusHandler::emitSignal(PathHandler::dbusPath path, nlohmann::json arg) { + if(!_started) return; //add error + + auto exists = _DBusObjects.find(path.objectPath); + auto object = (exists != _DBusObjects.end())? exists->second.get() : addObject(path.objectPath); + + auto signal = object->createSignal(path.interface, path.functionality); + + signal << nlohmann::json::to_bson(arg); + + object->emitSignal(signal); } -void DBusHandler::getProxys(nlohmann::json DBusObjectConfig) { - std::vector tempDependencies = DBusObjectConfig["dependencies"]; +void DBusHandler::finish() { - for(const& dependency : tempDependencies){ + for (auto const& proxy : _DBusProxys) { + proxy.second->finishRegistration(); + } + for (auto const& object : _DBusObjects) { + object.second->finishRegistration(); } -} -void bind() { + _started = true; + + _connection->enterEventLoop(); } From 1621ac88cca7120818303d5f6edf9e0266701de8 Mon Sep 17 00:00:00 2001 From: math-42 Date: Sun, 19 Sep 2021 21:38:09 -0300 Subject: [PATCH 018/147] adding test environment to git ignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index a05b696..0991ed6 100644 --- a/.gitignore +++ b/.gitignore @@ -1038,4 +1038,4 @@ modules.order Module.symvers Mkfile.old dkms.conf -tests/mainTest.cpp \ No newline at end of file +tests/test-environment/* \ No newline at end of file From 74cb66a131d9d2da3e6adebdf9ab0585ed922a8e Mon Sep 17 00:00:00 2001 From: math-42 Date: Sun, 19 Sep 2021 21:38:37 -0300 Subject: [PATCH 019/147] changing dbus path name to DBusPath --- src/classes/dbus-handler/dbus-handler.hpp | 41 ++++++++++++----------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index fed989d..63ed917 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -21,61 +21,62 @@ class DBusHandler { std::string _serviceName; bool _started; + bool _isServer; std::unique_ptr _connection; DBusObjectMap _DBusObjects; DBusProxyMap _DBusProxys; - private: + public: sdbus::IObject* addObject(std::string objectPath); sdbus::IProxy* addProxy(std::string service, std::string objectPath); - void registerMethod(PathHandler::dbusPath path, DBusCallback callback); + void registerMethod(PathHandler::DBusPath path, DBusCallback callback); - void subscribeToSignal(PathHandler::dbusPath path, DBusVoidCallback callback); + void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback callback); - void registerSignal(PathHandler::dbusPath path); + void registerSignal(PathHandler::DBusPath path); - nlohmann::json callMethod(PathHandler::dbusPath path, nlohmann::json arg); + nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); - void callMethodAsync(PathHandler::dbusPath path, nlohmann::json arg, DBusVoidCallback callback); + void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback callback); - void emitSignal(PathHandler::dbusPath path, nlohmann::json arg); - - + void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); public: DBusHandler(std::string serviceName); + DBusHandler(std::string serviceName, bool isServer); + DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys); DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys, std::unique_ptr connection); - nlohmann::json call(std::string dbusPath, nlohmann::json req); + nlohmann::json call(std::string DBusPath, nlohmann::json req); - nlohmann::json call(std::string dbusPath, nlohmann::json req, DBusCallback callback); + nlohmann::json call(std::string DBusPath, nlohmann::json req, DBusCallback callback); - nlohmann::json expose(std::string dbusPath, nlohmann::json req, DBusCallback getter, DBusVoidCallback setter); + nlohmann::json expose(std::string DBusPath, nlohmann::json req, DBusCallback getter, DBusVoidCallback setter); - nlohmann::json get(std::string dbusPath, nlohmann::json req); + nlohmann::json get(std::string DBusPath, nlohmann::json req); - nlohmann::json get(std::string dbusPath, nlohmann::json req, DBusVoidCallback callback); + nlohmann::json get(std::string DBusPath, nlohmann::json req, DBusVoidCallback callback); - nlohmann::json set(std::string dbusPath, nlohmann::json req); + nlohmann::json set(std::string DBusPath, nlohmann::json req); - nlohmann::json subscribe(std::string dbusPath, DBusCallback callback); + nlohmann::json subscribe(std::string DBusPath, DBusCallback callback); - nlohmann::json subscribe(std::string dbusPath, DBusCallback callback, nlohmann::json dependencies); + nlohmann::json subscribe(std::string DBusPath, DBusCallback callback, nlohmann::json dependencies); - nlohmann::json bind(std::string dbusPath, DBusCallback callback); + nlohmann::json bind(std::string DBusPath, DBusCallback callback); - nlohmann::json bind(std::string dbusPath, DBusCallback callback, nlohmann::json dependencies); + nlohmann::json bind(std::string DBusPath, DBusCallback callback, nlohmann::json dependencies); - nlohmann::json emit(std::string dbusPath, nlohmann::json arg); + nlohmann::json emit(std::string DBusPath, nlohmann::json arg); void finish(); From 1733b58e423c9e24dc9608fc04c90b7fc99531a0 Mon Sep 17 00:00:00 2001 From: math-42 Date: Sun, 19 Sep 2021 21:39:13 -0300 Subject: [PATCH 020/147] adding isServer functionality --- src/classes/dbus-handler/dbus-handler.cpp | 32 +++++++++++++---------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index 71d6ec3..811b488 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,12 +1,16 @@ #include "./dbus-handler.hpp" - -DBusHandler::DBusHandler(std::string serviceName) { - _serviceName = "org.frameworkd." + serviceName; +DBusHandler::DBusHandler(std::string serviceName):_isServer{true} { + _serviceName = serviceName; _connection = sdbus::createSystemBusConnection(_serviceName); } +DBusHandler::DBusHandler(std::string serviceName, bool isServer):_isServer{isServer}{ + _serviceName = serviceName; + if(isServer) _connection = sdbus::createSystemBusConnection(_serviceName); +} + sdbus::IObject* DBusHandler::addObject(std::string objectPath) { _DBusObjects[objectPath] = sdbus::createObject(*_connection, objectPath); return _DBusObjects[objectPath].get(); @@ -21,7 +25,7 @@ sdbus::IProxy* DBusHandler::addProxy(std::string destinationService, std::string return _DBusProxys[uniqueId].get(); } -void DBusHandler::registerMethod(PathHandler::dbusPath path, DBusCallback callback) { +void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback callback) { auto exists = _DBusObjects.find(path.objectPath); auto object = (exists != _DBusObjects.end())? exists->second.get() : addObject(path.objectPath); @@ -41,11 +45,11 @@ void DBusHandler::registerMethod(PathHandler::dbusPath path, DBusCallback callba }; - object->registerMethod(path.interface, path.functionality, "ai", "ai", wrapper); + object->registerMethod(path.interface, path.functionality, "ay", "ay", wrapper); } -void DBusHandler::subscribeToSignal(PathHandler::dbusPath path, DBusVoidCallback callback) { +void DBusHandler::subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback callback) { std::string uniqueId = path.service + path.objectPath; @@ -65,17 +69,16 @@ void DBusHandler::subscribeToSignal(PathHandler::dbusPath path, DBusVoidCallback } -void DBusHandler::registerSignal(PathHandler::dbusPath path) { +void DBusHandler::registerSignal(PathHandler::DBusPath path) { auto exists = _DBusObjects.find(path.objectPath); auto object = (exists != _DBusObjects.end())? exists->second.get() : addObject(path.objectPath); - object->registerSignal(path.interface, path.functionality, "ai"); + object->registerSignal(path.interface, path.functionality, "ay"); } -nlohmann::json DBusHandler::callMethod(PathHandler::dbusPath path, nlohmann::json arg) { - if(!_started) return; //add error +nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::json arg) { std::string uniqueId = path.service + path.objectPath; @@ -96,8 +99,7 @@ nlohmann::json DBusHandler::callMethod(PathHandler::dbusPath path, nlohmann::jso } -void DBusHandler::callMethodAsync(PathHandler::dbusPath path, nlohmann::json arg, DBusVoidCallback callback) { - if(!_started) return; //add error +void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback callback) { std::string uniqueId = path.service + path.objectPath; @@ -120,7 +122,7 @@ void DBusHandler::callMethodAsync(PathHandler::dbusPath path, nlohmann::json arg auto reply = proxy->callMethod(method, wrapper); } -void DBusHandler::emitSignal(PathHandler::dbusPath path, nlohmann::json arg) { +void DBusHandler::emitSignal(PathHandler::DBusPath path, nlohmann::json arg) { if(!_started) return; //add error auto exists = _DBusObjects.find(path.objectPath); @@ -145,5 +147,7 @@ void DBusHandler::finish() { _started = true; - _connection->enterEventLoop(); + if(_isServer)_connection->enterEventLoop(); } + + From bd000cb733752c489795e3707b8caefef5cd1c30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 22 Sep 2021 21:59:18 -0300 Subject: [PATCH 021/147] dbus-handler: adding new get/set signatures --- src/classes/dbus-handler/dbus-handler.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 63ed917..98ac785 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -60,13 +60,13 @@ class DBusHandler { nlohmann::json call(std::string DBusPath, nlohmann::json req, DBusCallback callback); - nlohmann::json expose(std::string DBusPath, nlohmann::json req, DBusCallback getter, DBusVoidCallback setter); + void expose(PathHandler::DBusPath path, DBusCallback getter, DBusVoidCallback setter); - nlohmann::json get(std::string DBusPath, nlohmann::json req); + nlohmann::json get(PathHandler::DBusPath path); - nlohmann::json get(std::string DBusPath, nlohmann::json req, DBusVoidCallback callback); + void get(PathHandler::DBusPath path , DBusVoidCallback callback); - nlohmann::json set(std::string DBusPath, nlohmann::json req); + void set(PathHandler::DBusPath path, nlohmann::json arg); nlohmann::json subscribe(std::string DBusPath, DBusCallback callback); From 617423b58b34a3b97456ccdc4d16eec3b1b2a9de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 22 Sep 2021 22:06:15 -0300 Subject: [PATCH 022/147] dbus-handler: find object and proxy methods --- src/classes/dbus-handler/dbus-handler.cpp | 86 ++++++++++++----------- src/classes/dbus-handler/dbus-handler.hpp | 68 +++++++++--------- 2 files changed, 79 insertions(+), 75 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index 811b488..e922c59 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,34 +1,53 @@ #include "./dbus-handler.hpp" -DBusHandler::DBusHandler(std::string serviceName):_isServer{true} { - _serviceName = serviceName; - _connection = sdbus::createSystemBusConnection(_serviceName); +DBusHandler::DBusHandler(std::string serviceName) : _isServer{true}, _serviceName{serviceName} { + + _connection = sdbus::createSystemBusConnection(serviceName); + } -DBusHandler::DBusHandler(std::string serviceName, bool isServer):_isServer{isServer}{ - _serviceName = serviceName; - if(isServer) _connection = sdbus::createSystemBusConnection(_serviceName); +DBusHandler::DBusHandler(std::string serviceName, bool isServer) : _isServer{isServer}, _serviceName{serviceName} { + + if (isServer) _connection = sdbus::createSystemBusConnection(serviceName); + } -sdbus::IObject* DBusHandler::addObject(std::string objectPath) { - _DBusObjects[objectPath] = sdbus::createObject(*_connection, objectPath); - return _DBusObjects[objectPath].get(); +sdbus::IObject* DBusHandler::findObject(PathHandler::DBusPath path) { + + try { + + return _DBusObjects.at(path.objectPath).get(); + + } catch (std::out_of_range& e) { + + _DBusObjects[path.objectPath] = sdbus::createObject(*_connection, path.objectPath); + return _DBusObjects[path.objectPath].get(); + + } + } -sdbus::IProxy* DBusHandler::addProxy(std::string destinationService, std::string objectPath) { +sdbus::IProxy* DBusHandler::findProxy(PathHandler::DBusPath path) { - std::string uniqueId = destinationService + objectPath; - - _DBusProxys[uniqueId] = sdbus::createProxy(destinationService, objectPath); + std::string uniqueId = path.service + path.objectPath; + + try { + + return _DBusProxys.at(uniqueId).get(); + + } catch (std::out_of_range& e) { + + _DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); + return _DBusProxys[uniqueId].get(); + + } - return _DBusProxys[uniqueId].get(); } void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback callback) { - auto exists = _DBusObjects.find(path.objectPath); - auto object = (exists != _DBusObjects.end())? exists->second.get() : addObject(path.objectPath); + sdbus::IObject* object = findObject(path); auto wrapper = [&callback](sdbus::MethodCall call) { @@ -51,10 +70,7 @@ void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback callba void DBusHandler::subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback callback) { - std::string uniqueId = path.service + path.objectPath; - - auto exists = _DBusProxys.find(uniqueId); - auto proxy = (exists != _DBusProxys.end())? exists->second.get() : addProxy(path.service, path.objectPath); + sdbus::IProxy* proxy = findProxy(path); auto wrapper = [&callback](sdbus::Signal& signal) { @@ -71,20 +87,14 @@ void DBusHandler::subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback void DBusHandler::registerSignal(PathHandler::DBusPath path) { - auto exists = _DBusObjects.find(path.objectPath); - auto object = (exists != _DBusObjects.end())? exists->second.get() : addObject(path.objectPath); - + sdbus::IObject* object = findObject(path); object->registerSignal(path.interface, path.functionality, "ay"); } nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::json arg) { - std::string uniqueId = path.service + path.objectPath; - - auto exists = _DBusProxys.find(uniqueId); - auto proxy = (exists != _DBusProxys.end())? exists->second.get() : addProxy(path.service, path.objectPath); - + sdbus::IProxy* proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); method << nlohmann::json::to_bson(arg); @@ -92,7 +102,6 @@ nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::jso auto reply = proxy->callMethod(method); std::vector bson; - reply >> bson; return nlohmann::json::from_bson(bson); @@ -101,11 +110,7 @@ nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::jso void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback callback) { - std::string uniqueId = path.service + path.objectPath; - - auto exists = _DBusProxys.find(uniqueId); - auto proxy = (exists != _DBusProxys.end())? exists->second.get() : addProxy(path.service, path.objectPath); - + sdbus::IProxy* proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); method << nlohmann::json::to_bson(arg); @@ -120,19 +125,20 @@ void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg }; auto reply = proxy->callMethod(method, wrapper); + } void DBusHandler::emitSignal(PathHandler::DBusPath path, nlohmann::json arg) { - if(!_started) return; //add error + + if (!_started) return; //add error - auto exists = _DBusObjects.find(path.objectPath); - auto object = (exists != _DBusObjects.end())? exists->second.get() : addObject(path.objectPath); + sdbus::IObject* object = findObject(path); auto signal = object->createSignal(path.interface, path.functionality); - signal << nlohmann::json::to_bson(arg); object->emitSignal(signal); + } void DBusHandler::finish() { @@ -147,7 +153,7 @@ void DBusHandler::finish() { _started = true; - if(_isServer)_connection->enterEventLoop(); -} + if (_isServer) _connection->enterEventLoop(); +} diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 98ac785..2a32a51 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -12,53 +12,51 @@ class DBusHandler { public: - using DBusObjectMap = std::map>; - using DBusProxyMap = std::map>; - using DBusVoidCallback = std::function; - using DBusCallback = std::function; + using DBusObjectMap = std::map>; + using DBusProxyMap = std::map>; + using DBusVoidCallback = std::function; + using DBusCallback = std::function; private: - std::string _serviceName; - bool _started; - bool _isServer; + std::string _serviceName; + bool _started; + bool _isServer; - std::unique_ptr _connection; + std::unique_ptr _connection; - DBusObjectMap _DBusObjects; - DBusProxyMap _DBusProxys; + DBusObjectMap _DBusObjects; + DBusProxyMap _DBusProxys; - public: + sdbus::IProxy* findProxy(PathHandler::DBusPath path); + + sdbus::IObject* findObject(PathHandler::DBusPath path); - sdbus::IObject* addObject(std::string objectPath); + void registerMethod(PathHandler::DBusPath path, DBusCallback callback); - sdbus::IProxy* addProxy(std::string service, std::string objectPath); - - void registerMethod(PathHandler::DBusPath path, DBusCallback callback); + void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback callback); - void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback callback); + void registerSignal(PathHandler::DBusPath path); - void registerSignal(PathHandler::DBusPath path); - - nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); + nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); - void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback callback); + void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback callback); - void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); + void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); public: - DBusHandler(std::string serviceName); + DBusHandler(std::string serviceName); - DBusHandler(std::string serviceName, bool isServer); + DBusHandler(std::string serviceName, bool isServer); - DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys); + DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys); - DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys, std::unique_ptr connection); + DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys, std::unique_ptr connection); - nlohmann::json call(std::string DBusPath, nlohmann::json req); + nlohmann::json call(std::string DBusPath, nlohmann::json req); - nlohmann::json call(std::string DBusPath, nlohmann::json req, DBusCallback callback); + nlohmann::json call(std::string DBusPath, nlohmann::json req, DBusCallback callback); void expose(PathHandler::DBusPath path, DBusCallback getter, DBusVoidCallback setter); @@ -68,16 +66,16 @@ class DBusHandler { void set(PathHandler::DBusPath path, nlohmann::json arg); - nlohmann::json subscribe(std::string DBusPath, DBusCallback callback); + nlohmann::json subscribe(std::string DBusPath, DBusCallback callback); + + nlohmann::json subscribe(std::string DBusPath, DBusCallback callback, nlohmann::json dependencies); - nlohmann::json subscribe(std::string DBusPath, DBusCallback callback, nlohmann::json dependencies); + nlohmann::json bind(std::string DBusPath, DBusCallback callback); - nlohmann::json bind(std::string DBusPath, DBusCallback callback); + nlohmann::json bind(std::string DBusPath, DBusCallback callback, nlohmann::json dependencies); - nlohmann::json bind(std::string DBusPath, DBusCallback callback, nlohmann::json dependencies); + nlohmann::json emit(std::string DBusPath, nlohmann::json arg); - nlohmann::json emit(std::string DBusPath, nlohmann::json arg); + void finish(); - void finish(); - -}; \ No newline at end of file +}; From e384fe6774e601fb6ddf2955b2eaf06347939a0e Mon Sep 17 00:00:00 2001 From: math-42 Date: Thu, 23 Sep 2021 18:17:43 -0300 Subject: [PATCH 023/147] adding clang config files and commands --- .clang-format | 1 + .clang-tidy | 2 ++ CMakeLists.txt | 5 ++--- 3 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 .clang-format create mode 100644 .clang-tidy diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..d4f347b --- /dev/null +++ b/.clang-format @@ -0,0 +1 @@ +BasedOnStyle: Microsoft diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..8b058c7 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,2 @@ +Checks: '-*,google-*,cppcoreguidelines-*,clang-*,readability-*,modernize-*,-cppcoreguidelines-*' +FormatStyle: 'file' \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index ea00286..9ea7ea3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,10 +1,9 @@ cmake_minimum_required(VERSION 3.16.3) -project(daemons-framework) +project(frameworkd) add_definitions("-std=c++17") include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup() +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -add_executable(daemonTest tests/mainTest.cpp) -target_link_libraries(daemonTest ${CONAN_LIBS}) \ No newline at end of file From e1faf291d78e5d717b3a5fc85f9ce420ff5af1e1 Mon Sep 17 00:00:00 2001 From: math-42 Date: Thu, 23 Sep 2021 18:50:47 -0300 Subject: [PATCH 024/147] adding path handler --- src/utils/path-handler/path-handler.cpp | 83 +++++++++++++++++++++++++ src/utils/path-handler/path-handler.hpp | 22 +++++++ 2 files changed, 105 insertions(+) create mode 100644 src/utils/path-handler/path-handler.cpp create mode 100644 src/utils/path-handler/path-handler.hpp diff --git a/src/utils/path-handler/path-handler.cpp b/src/utils/path-handler/path-handler.cpp new file mode 100644 index 0000000..4404a35 --- /dev/null +++ b/src/utils/path-handler/path-handler.cpp @@ -0,0 +1,83 @@ +#include "./path-handler.hpp" + + +PathHandler::parsedPath PathHandler::parsePath(std::string path){ + std::replace(path.begin(), path.end(), '/', ' '); + std::vector array; + std::stringstream ss(path); + + std::string word; + while (ss >> word) array.push_back(word); + + PathHandler::parsedPath parsedResponse; + + parsedResponse.service = array[0] + "." + array[1] + "." + array[2]; + parsedResponse.objectPath = "/" + array[0] + "/" + array[1] + "/" + array[2] + "/" + array[3]; + parsedResponse.interface = array[0] + "." + array[1] + "." + array[2] +"." + array[3]; + parsedResponse.functionality = array[4]; + + return parsedResponse; +} + +std::vector PathHandler::splitPath(std::string path){ + std::replace(path.begin(), path.end(), '/', ' '); + std::vector parsedPath; + std::stringstream ss(path); + + std::string word; + while (ss >> word) parsedPath.push_back(word); + + return parsedPath; +} + +bool PathHandler::regexMatch(std::string path) { +} + +/* + +Daemons do mesmo framework podem ser referenciadas do seguinte modo: + +daemon/caminho/do/objeto:interface/funcionalidade + +daemon/:interface/funcionalidade + +nesse caso temos: + +nome do servico: org.frameworkd.daemon + +objectPath: org/frameworkd/daemon/caminho/do/objeto + +interface: org.frameworkd.daemon.interface + +obs: caso a interface tenha mais de um nome, o nome dela serĂ¡ todo o conteudo que estiver entre :: + +nome da funcionalidade (sinal ou metodo ou propriedade (?)): funcionalidade + + +para falar com daemons do lado de fora do framework podera utilizar a mesma estrutura com os seguintes poren + +nome.do.servico/caminho/do/objeto/nome.da.interface:metodo + + +TODO: + +Achar um jeito de indicar que o nome da interface/ objeto deve ser concatenado com o nome do servico + +nome.do.servico/caminho/do/objeto/nome.da.interface:funcionalidade + +dbus.register("feature.cand/can/sender/sender:send",algumaCoisa, [](){ + +}, requirements["asdqwe"]); + +{ + "asdasd": asdasd + "asdasd":{ + "asdasd":{ + + } + } +} + + + +*/ diff --git a/src/utils/path-handler/path-handler.hpp b/src/utils/path-handler/path-handler.hpp new file mode 100644 index 0000000..5feabc2 --- /dev/null +++ b/src/utils/path-handler/path-handler.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include +#include + +namespace PathHandler { + + struct DBusPath{ + std::string service = ""; + std::string objectPath = ""; + std::string interface = ""; + std::string functionality = ""; + }; + + static DBusPath parsePath(std::string path); + + static std::vector splitPath(std::string path); + + static bool regexMatch(std::string path); +}; From 9061ab19c0e87e4e036b91c61b37d62cf4448562 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Tue, 28 Sep 2021 17:54:00 -0300 Subject: [PATCH 025/147] signal: fixing callback reference pointer --- src/classes/dbus-handler/dbus-handler.cpp | 13 +++++++------ src/classes/dbus-handler/dbus-handler.hpp | 10 +++++----- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index e922c59..adbb4de 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,4 +1,5 @@ #include "./dbus-handler.hpp" +#include DBusHandler::DBusHandler(std::string serviceName) : _isServer{true}, _serviceName{serviceName} { @@ -45,11 +46,11 @@ sdbus::IProxy* DBusHandler::findProxy(PathHandler::DBusPath path) { } -void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback callback) { +void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback&& callback) { sdbus::IObject* object = findObject(path); - auto wrapper = [&callback](sdbus::MethodCall call) { + auto wrapper = [callback](sdbus::MethodCall call) { std::vector bson; call >> bson; @@ -68,11 +69,11 @@ void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback callba } -void DBusHandler::subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback callback) { +void DBusHandler::subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback) { sdbus::IProxy* proxy = findProxy(path); - auto wrapper = [&callback](sdbus::Signal& signal) { + auto wrapper = [callback](sdbus::Signal& signal) { std::vector bson; signal >> bson; @@ -108,14 +109,14 @@ nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::jso } -void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback callback) { +void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback) { sdbus::IProxy* proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); method << nlohmann::json::to_bson(arg); - auto wrapper = [&callback](sdbus::MethodReply& reply, const sdbus::Error* error) { + auto wrapper = [callback](sdbus::MethodReply& reply, const sdbus::Error* error) { std::vector bson; reply >> bson; diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 2a32a51..9dc5dac 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -28,24 +28,24 @@ class DBusHandler { DBusObjectMap _DBusObjects; DBusProxyMap _DBusProxys; + public: + sdbus::IProxy* findProxy(PathHandler::DBusPath path); sdbus::IObject* findObject(PathHandler::DBusPath path); - void registerMethod(PathHandler::DBusPath path, DBusCallback callback); + void registerMethod(PathHandler::DBusPath path, DBusCallback&& callback); - void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback callback); + void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback); void registerSignal(PathHandler::DBusPath path); nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); - void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback callback); + void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback); void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); - public: - DBusHandler(std::string serviceName); DBusHandler(std::string serviceName, bool isServer); From 356aeaa082282eb821bdf78e2d532c2a6c474f6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Tue, 28 Sep 2021 18:00:34 -0300 Subject: [PATCH 026/147] dbus-handler: deleting unused methods prototypes --- src/classes/dbus-handler/dbus-handler.cpp | 2 -- src/classes/dbus-handler/dbus-handler.hpp | 36 +++++++---------------- 2 files changed, 11 insertions(+), 27 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index adbb4de..bba0373 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,6 +1,4 @@ #include "./dbus-handler.hpp" -#include - DBusHandler::DBusHandler(std::string serviceName) : _isServer{true}, _serviceName{serviceName} { diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 9dc5dac..9af48a6 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -28,23 +28,11 @@ class DBusHandler { DBusObjectMap _DBusObjects; DBusProxyMap _DBusProxys; - public: - sdbus::IProxy* findProxy(PathHandler::DBusPath path); sdbus::IObject* findObject(PathHandler::DBusPath path); - void registerMethod(PathHandler::DBusPath path, DBusCallback&& callback); - - void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback); - - void registerSignal(PathHandler::DBusPath path); - - nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); - - void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback); - - void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); + public: DBusHandler(std::string serviceName); @@ -54,27 +42,25 @@ class DBusHandler { DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys, std::unique_ptr connection); - nlohmann::json call(std::string DBusPath, nlohmann::json req); - - nlohmann::json call(std::string DBusPath, nlohmann::json req, DBusCallback callback); + void registerMethod(PathHandler::DBusPath path, DBusCallback&& callback); - void expose(PathHandler::DBusPath path, DBusCallback getter, DBusVoidCallback setter); + void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback); - nlohmann::json get(PathHandler::DBusPath path); + void registerSignal(PathHandler::DBusPath path); - void get(PathHandler::DBusPath path , DBusVoidCallback callback); + nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); - void set(PathHandler::DBusPath path, nlohmann::json arg); + void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback); - nlohmann::json subscribe(std::string DBusPath, DBusCallback callback); + void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); - nlohmann::json subscribe(std::string DBusPath, DBusCallback callback, nlohmann::json dependencies); + void exposeProperty(PathHandler::DBusPath path, DBusCallback getter, DBusVoidCallback setter); - nlohmann::json bind(std::string DBusPath, DBusCallback callback); + nlohmann::json getProperty(PathHandler::DBusPath path); - nlohmann::json bind(std::string DBusPath, DBusCallback callback, nlohmann::json dependencies); + void getProperty(PathHandler::DBusPath path, DBusVoidCallback callback); - nlohmann::json emit(std::string DBusPath, nlohmann::json arg); + void setProperty(PathHandler::DBusPath path, nlohmann::json arg); void finish(); From 4d9d5579419db93827278774d0cb41a1685d54aa Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Fri, 1 Oct 2021 20:45:39 -0300 Subject: [PATCH 027/147] Upgrading the CMakeLists.txt --- CMakeLists.txt | 164 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 159 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9ea7ea3..a3fe09c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,9 +1,163 @@ -cmake_minimum_required(VERSION 3.16.3) -project(frameworkd) +#------------------------------- +# PROJECT INFORMATION +#------------------------------- -add_definitions("-std=c++17") +cmake_minimum_required(VERSION 3.18) +project(frameworkd VERSION 0.1 LANGUAGES CXX) -include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) -conan_basic_setup() +include(GNUInstallDirs) # Installation directories for `install` command and pkgconfig file + +#------------------------------- +# PROJECT MACROS DEFINITION +#------------------------------- + +macro(FRAMEWORKD_ADD_DEPS_FILEPATHS_TO outputList baseDir subDir depsList fileExt) + + foreach(dependency IN LISTS ${depsList}) + list(APPEND ${outputList} ${baseDir}/${subDir}/${dependency}/${dependency}.${fileExt}) + endforeach() + +endmacro(FRAMEWORKD_ADD_DEPS_FILEPATHS_TO) + + +macro(FRAMEWORKD_ADD_DEPS_DIRPATHS_TO outputList baseDir subDir depsList) + + foreach(dependency IN LISTS ${depsList}) + list(APPEND ${outputList} ${baseDir}/${subDir}/${dependency}/) + endforeach() + +endmacro(FRAMEWORKD_ADD_DEPS_DIRPATHS_TO) + + +macro(FRAMEWORKD_CREATE_DICT contentList indexList dictName) + + set(i 0) + foreach(element IN LISTS ${contentList}) + list(GET ${indexList} ${i} index) + set(${dictName}-${index} ${element}) + math(EXPR i "${i} + 1") + endforeach() + +endmacro(FRAMEWORKD_CREATE_DICT) + + +#------------------ +# SET SOURCE FILES +#------------------ + +set(FRAMEWORKD_CLASSES + daemon + service + service-handler) + +set(FRAMEWORKD_UTILITIES + dbus-handler) +#---------------------------- +# SOURCE FILES CONFIGURATION +#---------------------------- + +set(FRAMEWORKD_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) +set(FRAMEWORKD_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include) +set(FRAMEWORKD_UTIL_SUBDIR utilities) +set(FRAMEWORKD_CLSS_SUBDIR classes) + +set(FRAMEWORKD_CPP_SRCS) + +FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_CPP_SRCS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_CLSS_SUBDIR} FRAMEWORKD_CLASSES cpp) +FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_CPP_SRCS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_UTIL_SUBDIR} FRAMEWORKD_UTILITIES cpp) + +set(FRAMEWORKD_HDR_SRCS) + +FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_HDR_SRCS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_CLSS_SUBDIR} FRAMEWORKD_CLASSES hpp) +FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_HDR_SRCS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_UTIL_SUBDIR} FRAMEWORKD_UTILITIES hpp) + +set(FRAMEWORKD_PUBLIC_HDRS) + +FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_PUBLIC_HDRS ${FRAMEWORKD_INCLUDE_DIR} ${FRAMEWORKD_CLSS_SUBDIR} FRAMEWORKD_CLASSES hpp) +FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_PUBLIC_HDRS ${FRAMEWORKD_INCLUDE_DIR} ${FRAMEWORKD_UTIL_SUBDIR} FRAMEWORKD_UTILITIES hpp) + +set(FRAMEWORKD_SRCS ${FRAMEWORKD_CPP_SRCS} ${FRAMEWORKD_HDR_SRCS} ${FRAMEWORKD_PUBLIC_HDRS}) + +add_library(troops OBJECT ${FRAMEWORKD_SRCS}) + +#------------------------------- +# GENERAL COMPILER CONFIGURATION +#------------------------------- + +set(CMAKE_CXX_STANDARD 17) + +#----------------------------------- +# INCLUDE CONAN SETINGS FOR DEVELOPERS +#----------------------------------- + +option(FRAMEWORKD_USING_CONAN_FOR_DEV "(default ON)" ON) + +if(FRAMEWORKD_USING_CONAN_FOR_DEV) + include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) + conan_basic_setup() +endif() + +#---------------------------------- +# LIBRARY BUILD INFORMATION +#---------------------------------- + +set(FRAMEWORKD_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}") +set(FRAMEWORKD_VERSION "${PROJECT_VERSION}") + +set(FRAMEWORKD_SRC_DIRS) +FRAMEWORKD_ADD_DEPS_DIRPATHS_TO(FRAMEWORKD_SRC_DIRS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_CLSS_SUBDIR} FRAMEWORKD_CLASSES) +FRAMEWORKD_ADD_DEPS_DIRPATHS_TO(FRAMEWORKD_SRC_DIRS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_UTIL_SUBDIR} FRAMEWORKD_UTILITIES) + +FRAMEWORKD_CREATE_DICT(FRAMEWORKD_SRC_DIRS FRAMEWORKD_DEPS FRAMEWORKD_DIR) + +add_library(frameworkd-objlib OBJECT ${FRAMEWORKD_SRCS}) +target_compile_definitions(frameworkd-objlib PRIVATE BUILD_LIB=1) + +target_include_directories(frameworkd-objlib PUBLIC $ + $ + $ + $ +) + +if(DEFINED BUILD_SHARED_LIBS) + set_target_properties(frameworkd-objlib PROPERTIES POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS}) +endif() + +add_library(frameworkd) +target_include_directories(frameworkd PUBLIC $ + $ + $ + $ + $) + +set_target_properties(frameworkd + PROPERTIES PUBLIC_HEADER "${FRAMEWORKD_PUBLIC_HDRS}" + VERSION "${FRAMEWORKD_VERSION}" + OUTPUT_NAME "frameworkd") + +if(FRAMEWORKD_USING_CONAN_FOR_DEV) + target_link_libraries(frameworkd PRIVATE frameworkd-objlib ${CONANLIBS}) +else() + target_link_libraries(frameworkd PRIVATE frameworkd-objlibs) +endif() set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +#---------------------------------- +# INSTALLATION +#---------------------------------- + +# COMMING SOON... + + +#---------------------------------- +# TESTS +#---------------------------------- + +option(BUILD_TESTS "Build and install tests (default OFF)" OFF) + +if(BUILD_TESTS) + message(STATUS "Building with tests") + enable_testing() + add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/tests") +endif() + From b70cc507eab47a029cb31186d1326201ad815791 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Fri, 1 Oct 2021 22:07:12 -0300 Subject: [PATCH 028/147] Fixing bugs in CMakeLists.txt --- CMakeLists.txt | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index a3fe09c..fc65673 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -161,3 +161,16 @@ if(BUILD_TESTS) add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/tests") endif() + +#------ +# BIN +#------ +# Uncoment this section to build your binnaries with this CMake +# NOTE: This section is temporary!! +# It will persist until the maintainer solve problems with outside inclusion by "include_subdirectory" mode. +# +# +#add_executable(sample ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) +#target_link_libraries(sample ${CONAN_LIBS} frameworkd) + + From c9a49202ab40f1a803026b9e1cba538387b7646d Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Sun, 3 Oct 2021 10:53:36 -0300 Subject: [PATCH 029/147] Removed the boolena flag from the DbuHandler constructor --- src/classes/dbus-handler/dbus-handler.cpp | 66 ++++++++++------------ src/classes/dbus-handler/dbus-handler.hpp | 68 +++++++++++------------ 2 files changed, 60 insertions(+), 74 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index bba0373..163fb4e 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,18 +1,15 @@ #include "./dbus-handler.hpp" -DBusHandler::DBusHandler(std::string serviceName) : _isServer{true}, _serviceName{serviceName} { +DBusHandler::DBusHandler(std::string serviceName) + : _isServer { true } + , _serviceName { serviceName } +{ _connection = sdbus::createSystemBusConnection(serviceName); - -} - -DBusHandler::DBusHandler(std::string serviceName, bool isServer) : _isServer{isServer}, _serviceName{serviceName} { - - if (isServer) _connection = sdbus::createSystemBusConnection(serviceName); - } -sdbus::IObject* DBusHandler::findObject(PathHandler::DBusPath path) { +sdbus::IObject* DBusHandler::findObject(PathHandler::DBusPath path) +{ try { @@ -22,12 +19,11 @@ sdbus::IObject* DBusHandler::findObject(PathHandler::DBusPath path) { _DBusObjects[path.objectPath] = sdbus::createObject(*_connection, path.objectPath); return _DBusObjects[path.objectPath].get(); - } - } -sdbus::IProxy* DBusHandler::findProxy(PathHandler::DBusPath path) { +sdbus::IProxy* DBusHandler::findProxy(PathHandler::DBusPath path) +{ std::string uniqueId = path.service + path.objectPath; @@ -39,17 +35,15 @@ sdbus::IProxy* DBusHandler::findProxy(PathHandler::DBusPath path) { _DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); return _DBusProxys[uniqueId].get(); - } - } -void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback&& callback) { +void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback&& callback) +{ sdbus::IObject* object = findObject(path); auto wrapper = [callback](sdbus::MethodCall call) { - std::vector bson; call >> bson; @@ -60,38 +54,35 @@ void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback&& call reply << nlohmann::json::to_bson(answer); reply.send(); - }; object->registerMethod(path.interface, path.functionality, "ay", "ay", wrapper); - } -void DBusHandler::subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback) { +void DBusHandler::subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback) +{ sdbus::IProxy* proxy = findProxy(path); auto wrapper = [callback](sdbus::Signal& signal) { - std::vector bson; signal >> bson; callback(nlohmann::json::from_bson(bson)); - }; proxy->registerSignalHandler(path.interface, path.functionality, wrapper); - } -void DBusHandler::registerSignal(PathHandler::DBusPath path) { - +void DBusHandler::registerSignal(PathHandler::DBusPath path) +{ + sdbus::IObject* object = findObject(path); object->registerSignal(path.interface, path.functionality, "ay"); - } -nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::json arg) { +nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::json arg) +{ sdbus::IProxy* proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); @@ -104,10 +95,10 @@ nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::jso reply >> bson; return nlohmann::json::from_bson(bson); - } -void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback) { +void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback) +{ sdbus::IProxy* proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); @@ -115,32 +106,31 @@ void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg method << nlohmann::json::to_bson(arg); auto wrapper = [callback](sdbus::MethodReply& reply, const sdbus::Error* error) { - std::vector bson; reply >> bson; callback(nlohmann::json::from_bson(bson)); - }; auto reply = proxy->callMethod(method, wrapper); - } -void DBusHandler::emitSignal(PathHandler::DBusPath path, nlohmann::json arg) { +void DBusHandler::emitSignal(PathHandler::DBusPath path, nlohmann::json arg) +{ + + if (!_started) + return; //add error - if (!_started) return; //add error - sdbus::IObject* object = findObject(path); auto signal = object->createSignal(path.interface, path.functionality); signal << nlohmann::json::to_bson(arg); object->emitSignal(signal); - } -void DBusHandler::finish() { +void DBusHandler::finish() +{ for (auto const& proxy : _DBusProxys) { proxy.second->finishRegistration(); @@ -152,7 +142,7 @@ void DBusHandler::finish() { _started = true; - if (_isServer) _connection->enterEventLoop(); - + if (_isServer) + _connection->enterEventLoop(); } diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 9af48a6..fdc246a 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -1,67 +1,63 @@ #pragma once #include "../../utils/path-handler/path-handler.hpp" -#include #include #include -#include +#include #include +#include #include class DBusHandler { - public: - - using DBusObjectMap = std::map>; - using DBusProxyMap = std::map>; - using DBusVoidCallback = std::function; - using DBusCallback = std::function; - - private: - - std::string _serviceName; - bool _started; - bool _isServer; - - std::unique_ptr _connection; +public: + using DBusObjectMap = std::map>; + using DBusProxyMap = std::map>; + using DBusVoidCallback = std::function; + using DBusCallback = std::function; - DBusObjectMap _DBusObjects; - DBusProxyMap _DBusProxys; +private: + std::string _serviceName; + bool _started; + bool _isServer; - sdbus::IProxy* findProxy(PathHandler::DBusPath path); + std::unique_ptr _connection; - sdbus::IObject* findObject(PathHandler::DBusPath path); + DBusObjectMap _DBusObjects; + DBusProxyMap _DBusProxys; - public: + sdbus::IProxy* findProxy(PathHandler::DBusPath path); - DBusHandler(std::string serviceName); + sdbus::IObject* findObject(PathHandler::DBusPath path); - DBusHandler(std::string serviceName, bool isServer); +public: + DBusHandler(std::string serviceName); - DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys); + DBusHandler() = default; - DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys, std::unique_ptr connection); + DBusHandler(std::string serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys); - void registerMethod(PathHandler::DBusPath path, DBusCallback&& callback); + DBusHandler(std::string serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys, std::unique_ptr connection); - void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback); + void registerMethod(PathHandler::DBusPath path, DBusCallback&& callback); - void registerSignal(PathHandler::DBusPath path); + void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback); - nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); + void registerSignal(PathHandler::DBusPath path); - void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback); + nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); - void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); + void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback); - void exposeProperty(PathHandler::DBusPath path, DBusCallback getter, DBusVoidCallback setter); + void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); - nlohmann::json getProperty(PathHandler::DBusPath path); + void exposeProperty(PathHandler::DBusPath path, DBusCallback getter, DBusVoidCallback setter); - void getProperty(PathHandler::DBusPath path, DBusVoidCallback callback); + nlohmann::json getProperty(PathHandler::DBusPath path); - void setProperty(PathHandler::DBusPath path, nlohmann::json arg); + void getProperty(PathHandler::DBusPath path, DBusVoidCallback callback); - void finish(); + void setProperty(PathHandler::DBusPath path, nlohmann::json arg); + void finish(); }; From 42762af6aba77199be185e3d48fbe9b9d5d2807d Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Sun, 3 Oct 2021 10:55:04 -0300 Subject: [PATCH 030/147] Started using unit tests --- .clang-format | 2 +- CMakeLists.txt | 2 ++ conanfile.txt | 3 ++- tests/CMakeLists.txt | 6 ++++++ tests/daemon-test.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 tests/CMakeLists.txt create mode 100644 tests/daemon-test.cpp diff --git a/.clang-format b/.clang-format index d4f347b..202e2c1 100644 --- a/.clang-format +++ b/.clang-format @@ -1 +1 @@ -BasedOnStyle: Microsoft +BasedOnStyle: Webkit diff --git a/CMakeLists.txt b/CMakeLists.txt index 9ea7ea3..7b8e0c9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,3 +7,5 @@ include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup() set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +enable_testing() +add_subdirectory(tests) diff --git a/conanfile.txt b/conanfile.txt index cb82b6e..cba8f69 100644 --- a/conanfile.txt +++ b/conanfile.txt @@ -1,6 +1,7 @@ [requires] nlohmann_json/3.10.2 sdbus-cpp/0.8.3 +gtest/cci.20210126 [generators] -cmake \ No newline at end of file +cmake diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..b78d62c --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,6 @@ +add_executable(daemon-test daemon-test.cpp ../src/classes/dbus-handler/dbus-handler.cpp) + +target_link_libraries(daemon-test ${CONAN_LIBS}) + +include(GoogleTest) +gtest_discover_tests(daemon-test) diff --git a/tests/daemon-test.cpp b/tests/daemon-test.cpp new file mode 100644 index 0000000..e875efa --- /dev/null +++ b/tests/daemon-test.cpp @@ -0,0 +1,47 @@ +#include "../src/classes/dbus-handler/dbus-handler.hpp" +#include +#include +#include +#include + +class ServerClient : public ::testing::Test { +protected: + PathHandler::DBusPath m_serverPath = { + "org.sdbuscpp.concatenator", + "/org/sdbuscpp/concatenator", + "org.sdbuscpp.Concatenator", + "concatenate" + }; + DBusHandler m_client; + + void SetUp() override + { + std::thread t1(&ServerClient::server, this); + t1.detach(); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + } + + void server() + { + DBusHandler server(m_serverPath.service); + server.registerMethod(m_serverPath, [](nlohmann::json req) { + nlohmann::json res; + int num = req["num"]; + res["num"] = num * 2; + return res; + }); + + server.finish(); + } +}; + +TEST_F(ServerClient, Method) +{ + nlohmann::json arg; + nlohmann::json res; + + int num = 4; + arg["num"] = num; + res = m_client.callMethod(m_serverPath, arg); + EXPECT_EQ(num * 3, res["num"]); +} From 23b04ebbd54be0835c20f5eaecc3595042b3dcbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Mon, 4 Oct 2021 21:47:28 +0000 Subject: [PATCH 031/147] dbus-handler: add get and set property method --- src/classes/dbus-handler/dbus-handler.cpp | 57 +++++++++++++++++++++-- src/classes/dbus-handler/dbus-handler.hpp | 4 +- 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index bba0373..f011ef6 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,4 +1,4 @@ -#include "./dbus-handler.hpp" +#include "dbus-handler.hpp" DBusHandler::DBusHandler(std::string serviceName) : _isServer{true}, _serviceName{serviceName} { @@ -8,7 +8,9 @@ DBusHandler::DBusHandler(std::string serviceName) : _isServer{true}, _serviceNam DBusHandler::DBusHandler(std::string serviceName, bool isServer) : _isServer{isServer}, _serviceName{serviceName} { - if (isServer) _connection = sdbus::createSystemBusConnection(serviceName); + if (isServer) { + _connection = sdbus::createSystemBusConnection(serviceName); + } } @@ -140,6 +142,51 @@ void DBusHandler::emitSignal(PathHandler::DBusPath path, nlohmann::json arg) { } +void DBusHandler::exposeProperty(PathHandler::DBusPath path, std::function&& getter, DBusVoidCallback&& setter) { + + sdbus::IObject* object = findObject(path); + + auto getterWrapper = [getter]() { + + return nlohmann::json::to_bson(getter()); + + }; + + auto setterWrapper = [setter](const std::vector& arg) { + + setter(nlohmann::json::from_bson(arg)); + + }; + + object->registerProperty(path.functionality).onInterface(path.interface).withGetter(getterWrapper).withSetter(setterWrapper); + +} + +nlohmann::json DBusHandler::getProperty(PathHandler::DBusPath path) { + + sdbus::IProxy* proxy = findProxy(path); + std::vector property = proxy->getProperty(path.functionality).onInterface(path.interface); + + return nlohmann::json::from_bson(property); + +} + +void DBusHandler::getProperty(PathHandler::DBusPath path, DBusVoidCallback&& callback) { + + sdbus::IProxy* proxy = findProxy(path); + std::vector property = proxy->getProperty(path.functionality).onInterface(path.interface); + + callback(nlohmann::json::from_bson(property)); + +} + +void DBusHandler::setProperty(PathHandler::DBusPath path, nlohmann::json arg) { + + sdbus::IProxy* proxy = findProxy(path); + proxy->setProperty(path.functionality).onInterface(path.interface).toValue(nlohmann::json::to_bson(arg)); + +} + void DBusHandler::finish() { for (auto const& proxy : _DBusProxys) { @@ -152,7 +199,11 @@ void DBusHandler::finish() { _started = true; - if (_isServer) _connection->enterEventLoop(); + if (_isServer) { + + _connection->enterEventLoop(); + + } } diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 9af48a6..ec590d9 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -54,11 +54,11 @@ class DBusHandler { void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); - void exposeProperty(PathHandler::DBusPath path, DBusCallback getter, DBusVoidCallback setter); + void exposeProperty(PathHandler::DBusPath path, std::function&& getter, DBusVoidCallback&& setter); nlohmann::json getProperty(PathHandler::DBusPath path); - void getProperty(PathHandler::DBusPath path, DBusVoidCallback callback); + void getProperty(PathHandler::DBusPath path, DBusVoidCallback&& callback); void setProperty(PathHandler::DBusPath path, nlohmann::json arg); From 092f5499158dda5d0e1fff49604e54330ca4eca0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 6 Oct 2021 10:59:23 +0000 Subject: [PATCH 032/147] dbus-handler: adding struct Path --- src/classes/dbus-handler/dbus-handler.cpp | 166 +++++++++++----------- src/classes/dbus-handler/dbus-handler.hpp | 84 ++++++----- 2 files changed, 130 insertions(+), 120 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index f011ef6..17ab5d7 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,57 +1,58 @@ #include "dbus-handler.hpp" -DBusHandler::DBusHandler(std::string serviceName) : _isServer{true}, _serviceName{serviceName} { - - _connection = sdbus::createSystemBusConnection(serviceName); - -} - -DBusHandler::DBusHandler(std::string serviceName, bool isServer) : _isServer{isServer}, _serviceName{serviceName} { - - if (isServer) { - _connection = sdbus::createSystemBusConnection(serviceName); - } - -} - -sdbus::IObject* DBusHandler::findObject(PathHandler::DBusPath path) { - - try { - +sdbus::IObject *DBusHandler::findObject(const DBusHandler::Path &path) +{ + try + { return _DBusObjects.at(path.objectPath).get(); - - } catch (std::out_of_range& e) { + } + catch (std::out_of_range &e) + { _DBusObjects[path.objectPath] = sdbus::createObject(*_connection, path.objectPath); return _DBusObjects[path.objectPath].get(); - } - } -sdbus::IProxy* DBusHandler::findProxy(PathHandler::DBusPath path) { +sdbus::IProxy *DBusHandler::findProxy(const DBusHandler::Path &path) +{ - std::string uniqueId = path.service + path.objectPath; + const std::string uniqueId = path.service + path.objectPath; - try { + try + { return _DBusProxys.at(uniqueId).get(); - - } catch (std::out_of_range& e) { + } + catch (std::out_of_range &e) + { _DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); return _DBusProxys[uniqueId].get(); - } +} +DBusHandler::DBusHandler(const std::string &serviceName) : _isServer{true}, _serviceName{serviceName} +{ + + _connection = sdbus::createSystemBusConnection(serviceName); } -void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback&& callback) { +DBusHandler::DBusHandler(const std::string &serviceName, bool isServer) : _isServer{isServer}, _serviceName{serviceName} +{ - sdbus::IObject* object = findObject(path); + if (isServer) + { + _connection = sdbus::createSystemBusConnection(serviceName); + } +} - auto wrapper = [callback](sdbus::MethodCall call) { +void DBusHandler::registerMethod(const DBusHandler::Path &path, DBusCallback &&callback) +{ + sdbus::IObject *object = findObject(path); + + auto wrapper = [callback](sdbus::MethodCall call) { std::vector bson; call >> bson; @@ -62,40 +63,37 @@ void DBusHandler::registerMethod(PathHandler::DBusPath path, DBusCallback&& call reply << nlohmann::json::to_bson(answer); reply.send(); - }; object->registerMethod(path.interface, path.functionality, "ay", "ay", wrapper); - } -void DBusHandler::subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback) { +void DBusHandler::subscribeToSignal(const DBusHandler::Path &path, DBusVoidCallback &&callback) +{ - sdbus::IProxy* proxy = findProxy(path); - - auto wrapper = [callback](sdbus::Signal& signal) { + sdbus::IProxy *proxy = findProxy(path); + auto wrapper = [callback](sdbus::Signal &signal) { std::vector bson; signal >> bson; callback(nlohmann::json::from_bson(bson)); - }; proxy->registerSignalHandler(path.interface, path.functionality, wrapper); - } -void DBusHandler::registerSignal(PathHandler::DBusPath path) { - - sdbus::IObject* object = findObject(path); - object->registerSignal(path.interface, path.functionality, "ay"); +void DBusHandler::registerSignal(const DBusHandler::Path &path) +{ + sdbus::IObject *object = findObject(path); + object->registerSignal(path.interface, path.functionality, "ay"); } -nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::json arg) { +nlohmann::json DBusHandler::callMethod(const DBusHandler::Path &path, nlohmann::json arg) +{ - sdbus::IProxy* proxy = findProxy(path); + sdbus::IProxy *proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); method << nlohmann::json::to_bson(arg); @@ -106,104 +104,100 @@ nlohmann::json DBusHandler::callMethod(PathHandler::DBusPath path, nlohmann::jso reply >> bson; return nlohmann::json::from_bson(bson); - } -void DBusHandler::callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback) { +void DBusHandler::callMethodAsync(const DBusHandler::Path &path, nlohmann::json arg, DBusVoidCallback &&callback) +{ - sdbus::IProxy* proxy = findProxy(path); + sdbus::IProxy *proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); method << nlohmann::json::to_bson(arg); - auto wrapper = [callback](sdbus::MethodReply& reply, const sdbus::Error* error) { - + auto wrapper = [callback](sdbus::MethodReply &reply, const sdbus::Error *error) { std::vector bson; reply >> bson; callback(nlohmann::json::from_bson(bson)); - }; auto reply = proxy->callMethod(method, wrapper); - } -void DBusHandler::emitSignal(PathHandler::DBusPath path, nlohmann::json arg) { +void DBusHandler::emitSignal(const DBusHandler::Path &path, nlohmann::json arg) +{ - if (!_started) return; //add error - - sdbus::IObject* object = findObject(path); + if (!_started) + return; // add error + + sdbus::IObject *object = findObject(path); auto signal = object->createSignal(path.interface, path.functionality); signal << nlohmann::json::to_bson(arg); object->emitSignal(signal); - } -void DBusHandler::exposeProperty(PathHandler::DBusPath path, std::function&& getter, DBusVoidCallback&& setter) { +void DBusHandler::exposeProperty(const DBusHandler::Path &path, std::function &&getter, + DBusVoidCallback &&setter) +{ - sdbus::IObject* object = findObject(path); + sdbus::IObject *object = findObject(path); - auto getterWrapper = [getter]() { - - return nlohmann::json::to_bson(getter()); - - }; + auto getterWrapper = [getter]() { return nlohmann::json::to_bson(getter()); }; - auto setterWrapper = [setter](const std::vector& arg) { - - setter(nlohmann::json::from_bson(arg)); - - }; - - object->registerProperty(path.functionality).onInterface(path.interface).withGetter(getterWrapper).withSetter(setterWrapper); + auto setterWrapper = [setter](const std::vector &arg) { setter(nlohmann::json::from_bson(arg)); }; + object->registerProperty(path.functionality) + .onInterface(path.interface) + .withGetter(getterWrapper) + .withSetter(setterWrapper); } -nlohmann::json DBusHandler::getProperty(PathHandler::DBusPath path) { +nlohmann::json DBusHandler::getProperty(const DBusHandler::Path &path) +{ - sdbus::IProxy* proxy = findProxy(path); + sdbus::IProxy *proxy = findProxy(path); std::vector property = proxy->getProperty(path.functionality).onInterface(path.interface); return nlohmann::json::from_bson(property); - } -void DBusHandler::getProperty(PathHandler::DBusPath path, DBusVoidCallback&& callback) { +void DBusHandler::getProperty(const DBusHandler::Path &path, DBusVoidCallback &&callback) +{ - sdbus::IProxy* proxy = findProxy(path); + sdbus::IProxy *proxy = findProxy(path); std::vector property = proxy->getProperty(path.functionality).onInterface(path.interface); callback(nlohmann::json::from_bson(property)); - } -void DBusHandler::setProperty(PathHandler::DBusPath path, nlohmann::json arg) { +void DBusHandler::setProperty(const DBusHandler::Path &path, nlohmann::json arg) +{ - sdbus::IProxy* proxy = findProxy(path); + sdbus::IProxy *proxy = findProxy(path); proxy->setProperty(path.functionality).onInterface(path.interface).toValue(nlohmann::json::to_bson(arg)); - } -void DBusHandler::finish() { +void DBusHandler::finish() +{ - for (auto const& proxy : _DBusProxys) { + for (auto const &proxy : _DBusProxys) + { proxy.second->finishRegistration(); } - for (auto const& object : _DBusObjects) { + for (auto const &object : _DBusObjects) + { object.second->finishRegistration(); } _started = true; - if (_isServer) { + if (_isServer) + { _connection->enterEventLoop(); - } - } diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index ec590d9..1ddf8b6 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -1,67 +1,83 @@ #pragma once -#include "../../utils/path-handler/path-handler.hpp" -#include #include #include -#include +#include #include +#include #include -class DBusHandler { +class DBusHandler +{ + + public: + using DBusObjectMap = std::map>; + using DBusProxyMap = std::map>; + using DBusVoidCallback = std::function; + using DBusCallback = std::function; - public: + struct Path + { - using DBusObjectMap = std::map>; - using DBusProxyMap = std::map>; - using DBusVoidCallback = std::function; - using DBusCallback = std::function; + std::string service; + std::string objectPath; + std::string interface; + std::string functionality; - private: + Path(const std::string &service, const std::string &objectPath, const std::string &interface, + const std::string &functionality) + : service{std::move(service)}, objectPath{std::move(objectPath)}, interface{std::move(interface)}, + functionality{std::move(functionality)} { - std::string _serviceName; - bool _started; - bool _isServer; + // throw exception if one property is empty - std::unique_ptr _connection; + }; + }; - DBusObjectMap _DBusObjects; - DBusProxyMap _DBusProxys; + private: + std::string _serviceName; + bool _started; + bool _isServer; - sdbus::IProxy* findProxy(PathHandler::DBusPath path); + std::unique_ptr _connection; - sdbus::IObject* findObject(PathHandler::DBusPath path); + DBusObjectMap _DBusObjects; + DBusProxyMap _DBusProxys; - public: + sdbus::IProxy *findProxy(const DBusHandler::Path &path); - DBusHandler(std::string serviceName); + sdbus::IObject *findObject(const DBusHandler::Path &path); - DBusHandler(std::string serviceName, bool isServer); + public: + DBusHandler(const std::string &serviceName); - DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys); + DBusHandler(const std::string &serviceName, bool isServer); - DBusHandler(std::string serviceName, DBusObjectMap DBusObjects , DBusProxyMap DBusProxys, std::unique_ptr connection); + DBusHandler(const std::string &serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys); - void registerMethod(PathHandler::DBusPath path, DBusCallback&& callback); + DBusHandler(const std::string &serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys, + std::unique_ptr connection); - void subscribeToSignal(PathHandler::DBusPath path, DBusVoidCallback&& callback); + void registerMethod(const DBusHandler::Path &path, DBusCallback &&callback); - void registerSignal(PathHandler::DBusPath path); + void subscribeToSignal(const DBusHandler::Path &path, DBusVoidCallback &&callback); - nlohmann::json callMethod(PathHandler::DBusPath path, nlohmann::json arg); + void registerSignal(const DBusHandler::Path &path); - void callMethodAsync(PathHandler::DBusPath path, nlohmann::json arg, DBusVoidCallback&& callback); + nlohmann::json callMethod(const DBusHandler::Path &path, nlohmann::json arg); - void emitSignal(PathHandler::DBusPath path, nlohmann::json arg); + void callMethodAsync(const DBusHandler::Path &path, nlohmann::json arg, DBusVoidCallback &&callback); - void exposeProperty(PathHandler::DBusPath path, std::function&& getter, DBusVoidCallback&& setter); + void emitSignal(const DBusHandler::Path &path, nlohmann::json arg); - nlohmann::json getProperty(PathHandler::DBusPath path); + void exposeProperty(const DBusHandler::Path &path, std::function &&getter, + DBusVoidCallback &&setter); - void getProperty(PathHandler::DBusPath path, DBusVoidCallback&& callback); + nlohmann::json getProperty(const DBusHandler::Path &path); - void setProperty(PathHandler::DBusPath path, nlohmann::json arg); + void getProperty(const DBusHandler::Path &path, DBusVoidCallback &&callback); - void finish(); + void setProperty(const DBusHandler::Path &path, nlohmann::json arg); + void finish(); }; From 37989dc17be077b2c9710447d990ec718562e2bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 6 Oct 2021 11:01:38 +0000 Subject: [PATCH 033/147] PathHandler: deleting PathHandler files --- src/utils/path-handler/path-handler.cpp | 83 ------------------------- src/utils/path-handler/path-handler.hpp | 22 ------- 2 files changed, 105 deletions(-) delete mode 100644 src/utils/path-handler/path-handler.cpp delete mode 100644 src/utils/path-handler/path-handler.hpp diff --git a/src/utils/path-handler/path-handler.cpp b/src/utils/path-handler/path-handler.cpp deleted file mode 100644 index 4404a35..0000000 --- a/src/utils/path-handler/path-handler.cpp +++ /dev/null @@ -1,83 +0,0 @@ -#include "./path-handler.hpp" - - -PathHandler::parsedPath PathHandler::parsePath(std::string path){ - std::replace(path.begin(), path.end(), '/', ' '); - std::vector array; - std::stringstream ss(path); - - std::string word; - while (ss >> word) array.push_back(word); - - PathHandler::parsedPath parsedResponse; - - parsedResponse.service = array[0] + "." + array[1] + "." + array[2]; - parsedResponse.objectPath = "/" + array[0] + "/" + array[1] + "/" + array[2] + "/" + array[3]; - parsedResponse.interface = array[0] + "." + array[1] + "." + array[2] +"." + array[3]; - parsedResponse.functionality = array[4]; - - return parsedResponse; -} - -std::vector PathHandler::splitPath(std::string path){ - std::replace(path.begin(), path.end(), '/', ' '); - std::vector parsedPath; - std::stringstream ss(path); - - std::string word; - while (ss >> word) parsedPath.push_back(word); - - return parsedPath; -} - -bool PathHandler::regexMatch(std::string path) { -} - -/* - -Daemons do mesmo framework podem ser referenciadas do seguinte modo: - -daemon/caminho/do/objeto:interface/funcionalidade - -daemon/:interface/funcionalidade - -nesse caso temos: - -nome do servico: org.frameworkd.daemon - -objectPath: org/frameworkd/daemon/caminho/do/objeto - -interface: org.frameworkd.daemon.interface - -obs: caso a interface tenha mais de um nome, o nome dela serĂ¡ todo o conteudo que estiver entre :: - -nome da funcionalidade (sinal ou metodo ou propriedade (?)): funcionalidade - - -para falar com daemons do lado de fora do framework podera utilizar a mesma estrutura com os seguintes poren - -nome.do.servico/caminho/do/objeto/nome.da.interface:metodo - - -TODO: - -Achar um jeito de indicar que o nome da interface/ objeto deve ser concatenado com o nome do servico - -nome.do.servico/caminho/do/objeto/nome.da.interface:funcionalidade - -dbus.register("feature.cand/can/sender/sender:send",algumaCoisa, [](){ - -}, requirements["asdqwe"]); - -{ - "asdasd": asdasd - "asdasd":{ - "asdasd":{ - - } - } -} - - - -*/ diff --git a/src/utils/path-handler/path-handler.hpp b/src/utils/path-handler/path-handler.hpp deleted file mode 100644 index 5feabc2..0000000 --- a/src/utils/path-handler/path-handler.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace PathHandler { - - struct DBusPath{ - std::string service = ""; - std::string objectPath = ""; - std::string interface = ""; - std::string functionality = ""; - }; - - static DBusPath parsePath(std::string path); - - static std::vector splitPath(std::string path); - - static bool regexMatch(std::string path); -}; From 26bf01738ba334bcaf9f10bd47a031c5839e78dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 6 Oct 2021 11:38:01 +0000 Subject: [PATCH 034/147] dbus-handler: adding exception to path constructor --- src/classes/dbus-handler/dbus-handler.hpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 1ddf8b6..a57170c 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -27,11 +28,13 @@ class DBusHandler Path(const std::string &service, const std::string &objectPath, const std::string &interface, const std::string &functionality) : service{std::move(service)}, objectPath{std::move(objectPath)}, interface{std::move(interface)}, - functionality{std::move(functionality)} { - - // throw exception if one property is empty - - }; + functionality{std::move(functionality)} + { + if (service.empty() || objectPath.empty() || interface.empty() || functionality.empty()) + { + throw std::invalid_argument("Invalid path: empty string doesn't satisfies path format"); + } + }; }; private: From a45c598347c397778ab72787b7b71e1c0397826f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 6 Oct 2021 11:38:38 +0000 Subject: [PATCH 035/147] dbus-handler: add default constructor to struct Path --- src/classes/dbus-handler/dbus-handler.hpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index a57170c..c0cba22 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -25,6 +25,8 @@ class DBusHandler std::string interface; std::string functionality; + Path() = default; + Path(const std::string &service, const std::string &objectPath, const std::string &interface, const std::string &functionality) : service{std::move(service)}, objectPath{std::move(objectPath)}, interface{std::move(interface)}, From e64a57466f57bf356a4e04a32b115d6b644115f6 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Wed, 6 Oct 2021 09:16:24 -0300 Subject: [PATCH 036/147] Adding tests for Signal and CallMethod Async --- tests/daemon-test.cpp | 75 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 15 deletions(-) diff --git a/tests/daemon-test.cpp b/tests/daemon-test.cpp index e875efa..85256c6 100644 --- a/tests/daemon-test.cpp +++ b/tests/daemon-test.cpp @@ -4,33 +4,46 @@ #include #include +PathHandler::DBusPath m_methodPath = { + "org.sdbuscpp.concatenator", + "/org/sdbuscpp/concatenator", + "org.sdbuscpp.Concatenator", + "concatenate" +}; +PathHandler::DBusPath m_signalPath = { + "org.sdbuscpp.concatenator", + "/org/sdbuscpp/concatenator", + "org.sdbuscpp.Concatenator", + "concatenated" +}; + +bool isServerConfig; + class ServerClient : public ::testing::Test { -protected: - PathHandler::DBusPath m_serverPath = { - "org.sdbuscpp.concatenator", - "/org/sdbuscpp/concatenator", - "org.sdbuscpp.Concatenator", - "concatenate" - }; +public: DBusHandler m_client; - void SetUp() override + static void SetUpTestSuite() { - std::thread t1(&ServerClient::server, this); + isServerConfig = true; + std::thread t1(&ServerClient::server); t1.detach(); - std::this_thread::sleep_for(std::chrono::milliseconds(200)); + while (isServerConfig) { }; } - void server() + static void server() { - DBusHandler server(m_serverPath.service); - server.registerMethod(m_serverPath, [](nlohmann::json req) { + DBusHandler server(m_methodPath.service); + server.registerSignal(m_signalPath); + server.registerMethod(m_methodPath, [&](nlohmann::json req) { nlohmann::json res; int num = req["num"]; res["num"] = num * 2; + server.emitSignal(m_signalPath, res); return res; }); + isServerConfig = false; server.finish(); } }; @@ -42,6 +55,38 @@ TEST_F(ServerClient, Method) int num = 4; arg["num"] = num; - res = m_client.callMethod(m_serverPath, arg); - EXPECT_EQ(num * 3, res["num"]); + res = m_client.callMethod(m_methodPath, arg); + + EXPECT_EQ(num * 2, res["num"]); +} + +TEST_F(ServerClient, AsyncMethod) +{ + nlohmann::json arg; + bool isCalled = false; + int num = 4; + + arg["num"] = num; + + m_client.finish(); + m_client.callMethodAsync(m_methodPath, arg, [&](nlohmann::json res) { + EXPECT_EQ(num * 2, res["num"]); + isCalled = true; + }); + while (!isCalled) { } +} + +TEST_F(ServerClient, Signal) +{ + nlohmann::json arg; + nlohmann::json res; + int num = 4; + m_client.subscribeToSignal(m_signalPath, [&](nlohmann::json rec) { + EXPECT_EQ(num * 2, rec["num"]); + }); + m_client.finish(); + arg["num"] = num; + + res = m_client.callMethod(m_methodPath, arg); } + From 5291243961d80fc6a63c61da0ec4e16009317c95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 6 Oct 2021 13:39:37 +0000 Subject: [PATCH 037/147] unit test: adding get and set unit tests --- tests/daemon-test.cpp | 58 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 6 deletions(-) diff --git a/tests/daemon-test.cpp b/tests/daemon-test.cpp index 85256c6..9a736f1 100644 --- a/tests/daemon-test.cpp +++ b/tests/daemon-test.cpp @@ -4,28 +4,40 @@ #include #include -PathHandler::DBusPath m_methodPath = { +DBusHandler::Path m_methodPath { "org.sdbuscpp.concatenator", "/org/sdbuscpp/concatenator", "org.sdbuscpp.Concatenator", "concatenate" }; -PathHandler::DBusPath m_signalPath = { + +DBusHandler::Path m_signalPath { "org.sdbuscpp.concatenator", "/org/sdbuscpp/concatenator", "org.sdbuscpp.Concatenator", "concatenated" }; +DBusHandler::Path m_propertiesPath { + "org.sdbuscpp.concatenator", + "/org/sdbuscpp/concatenator", + "org.sdbuscpp.Concatenator", + "properties" +}; + bool isServerConfig; +nlohmann::json m_properties; class ServerClient : public ::testing::Test { public: - DBusHandler m_client; + DBusHandler m_client { m_methodPath.service, false }; static void SetUpTestSuite() { isServerConfig = true; + + m_properties["num"] = 9; + std::thread t1(&ServerClient::server); t1.detach(); while (isServerConfig) { }; @@ -34,14 +46,18 @@ class ServerClient : public ::testing::Test { static void server() { DBusHandler server(m_methodPath.service); + server.registerSignal(m_signalPath); server.registerMethod(m_methodPath, [&](nlohmann::json req) { nlohmann::json res; int num = req["num"]; + res["num"] = num * 2; server.emitSignal(m_signalPath, res); return res; }); + server.exposeProperty( + m_propertiesPath, [&]() { return m_properties; }, [&](nlohmann::json req) { m_properties = req; }); isServerConfig = false; server.finish(); @@ -63,7 +79,6 @@ TEST_F(ServerClient, Method) TEST_F(ServerClient, AsyncMethod) { nlohmann::json arg; - bool isCalled = false; int num = 4; arg["num"] = num; @@ -71,9 +86,7 @@ TEST_F(ServerClient, AsyncMethod) m_client.finish(); m_client.callMethodAsync(m_methodPath, arg, [&](nlohmann::json res) { EXPECT_EQ(num * 2, res["num"]); - isCalled = true; }); - while (!isCalled) { } } TEST_F(ServerClient, Signal) @@ -81,12 +94,45 @@ TEST_F(ServerClient, Signal) nlohmann::json arg; nlohmann::json res; int num = 4; + m_client.subscribeToSignal(m_signalPath, [&](nlohmann::json rec) { EXPECT_EQ(num * 2, rec["num"]); }); + m_client.finish(); arg["num"] = num; res = m_client.callMethod(m_methodPath, arg); } +TEST_F(ServerClient, Get) +{ + m_client.finish(); + + nlohmann::json res = m_client.getProperty(m_propertiesPath); + + EXPECT_EQ(res, m_properties); +} + +TEST_F(ServerClient, AsyncGet) +{ + m_client.finish(); + + m_client.getProperty(m_propertiesPath, [&](nlohmann::json arg) { + EXPECT_EQ(arg, m_properties); + }); +} + +TEST_F(ServerClient, Set) +{ + nlohmann::json arg; + + arg["num"] = (int)m_properties["num"] * 4; + + m_client.finish(); + + m_client.setProperty(m_propertiesPath, arg); + + EXPECT_EQ(arg, m_properties); +} + From 90b080d9dc66c9f69c03b58bcb75ea974e5691d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 6 Oct 2021 11:23:08 -0300 Subject: [PATCH 038/147] dbus-handler: adding linting --- src/classes/dbus-handler/dbus-handler.cpp | 106 ++++++++-------------- 1 file changed, 39 insertions(+), 67 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index 17ab5d7..e1b456c 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,56 +1,46 @@ #include "dbus-handler.hpp" -sdbus::IObject *DBusHandler::findObject(const DBusHandler::Path &path) +sdbus::IObject* DBusHandler::findObject(const DBusHandler::Path& path) { - try - { + try { return _DBusObjects.at(path.objectPath).get(); - } - catch (std::out_of_range &e) - { - + } catch (std::out_of_range& e) { _DBusObjects[path.objectPath] = sdbus::createObject(*_connection, path.objectPath); return _DBusObjects[path.objectPath].get(); } } -sdbus::IProxy *DBusHandler::findProxy(const DBusHandler::Path &path) +sdbus::IProxy* DBusHandler::findProxy(const DBusHandler::Path& path) { - const std::string uniqueId = path.service + path.objectPath; - try - { - + try { return _DBusProxys.at(uniqueId).get(); - } - catch (std::out_of_range &e) - { - + } catch (std::out_of_range& e) { _DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); return _DBusProxys[uniqueId].get(); } } -DBusHandler::DBusHandler(const std::string &serviceName) : _isServer{true}, _serviceName{serviceName} +DBusHandler::DBusHandler(const std::string& serviceName) + : _isServer { true } + , _serviceName { serviceName } { - _connection = sdbus::createSystemBusConnection(serviceName); } -DBusHandler::DBusHandler(const std::string &serviceName, bool isServer) : _isServer{isServer}, _serviceName{serviceName} +DBusHandler::DBusHandler(const std::string& serviceName, bool isServer) + : _isServer { isServer } + , _serviceName { serviceName } { - - if (isServer) - { + if (isServer) { _connection = sdbus::createSystemBusConnection(serviceName); } } -void DBusHandler::registerMethod(const DBusHandler::Path &path, DBusCallback &&callback) +void DBusHandler::registerMethod(const DBusHandler::Path& path, DBusCallback&& callback) { - - sdbus::IObject *object = findObject(path); + sdbus::IObject* object = findObject(path); auto wrapper = [callback](sdbus::MethodCall call) { std::vector bson; @@ -68,12 +58,11 @@ void DBusHandler::registerMethod(const DBusHandler::Path &path, DBusCallback &&c object->registerMethod(path.interface, path.functionality, "ay", "ay", wrapper); } -void DBusHandler::subscribeToSignal(const DBusHandler::Path &path, DBusVoidCallback &&callback) +void DBusHandler::subscribeToSignal(const DBusHandler::Path& path, DBusVoidCallback&& callback) { + sdbus::IProxy* proxy = findProxy(path); - sdbus::IProxy *proxy = findProxy(path); - - auto wrapper = [callback](sdbus::Signal &signal) { + auto wrapper = [callback](sdbus::Signal& signal) { std::vector bson; signal >> bson; @@ -83,17 +72,15 @@ void DBusHandler::subscribeToSignal(const DBusHandler::Path &path, DBusVoidCallb proxy->registerSignalHandler(path.interface, path.functionality, wrapper); } -void DBusHandler::registerSignal(const DBusHandler::Path &path) +void DBusHandler::registerSignal(const DBusHandler::Path& path) { - - sdbus::IObject *object = findObject(path); + sdbus::IObject* object = findObject(path); object->registerSignal(path.interface, path.functionality, "ay"); } -nlohmann::json DBusHandler::callMethod(const DBusHandler::Path &path, nlohmann::json arg) +nlohmann::json DBusHandler::callMethod(const DBusHandler::Path& path, nlohmann::json arg) { - - sdbus::IProxy *proxy = findProxy(path); + sdbus::IProxy* proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); method << nlohmann::json::to_bson(arg); @@ -106,15 +93,14 @@ nlohmann::json DBusHandler::callMethod(const DBusHandler::Path &path, nlohmann:: return nlohmann::json::from_bson(bson); } -void DBusHandler::callMethodAsync(const DBusHandler::Path &path, nlohmann::json arg, DBusVoidCallback &&callback) +void DBusHandler::callMethodAsync(const DBusHandler::Path& path, nlohmann::json arg, DBusVoidCallback&& callback) { - - sdbus::IProxy *proxy = findProxy(path); + sdbus::IProxy* proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); method << nlohmann::json::to_bson(arg); - auto wrapper = [callback](sdbus::MethodReply &reply, const sdbus::Error *error) { + auto wrapper = [callback](sdbus::MethodReply& reply, const sdbus::Error* error) { std::vector bson; reply >> bson; @@ -124,13 +110,12 @@ void DBusHandler::callMethodAsync(const DBusHandler::Path &path, nlohmann::json auto reply = proxy->callMethod(method, wrapper); } -void DBusHandler::emitSignal(const DBusHandler::Path &path, nlohmann::json arg) +void DBusHandler::emitSignal(const DBusHandler::Path& path, nlohmann::json arg) { - if (!_started) return; // add error - sdbus::IObject *object = findObject(path); + sdbus::IObject* object = findObject(path); auto signal = object->createSignal(path.interface, path.functionality); signal << nlohmann::json::to_bson(arg); @@ -138,15 +123,14 @@ void DBusHandler::emitSignal(const DBusHandler::Path &path, nlohmann::json arg) object->emitSignal(signal); } -void DBusHandler::exposeProperty(const DBusHandler::Path &path, std::function &&getter, - DBusVoidCallback &&setter) +void DBusHandler::exposeProperty(const DBusHandler::Path& path, std::function&& getter, + DBusVoidCallback&& setter) { - - sdbus::IObject *object = findObject(path); + sdbus::IObject* object = findObject(path); auto getterWrapper = [getter]() { return nlohmann::json::to_bson(getter()); }; - auto setterWrapper = [setter](const std::vector &arg) { setter(nlohmann::json::from_bson(arg)); }; + auto setterWrapper = [setter](const std::vector& arg) { setter(nlohmann::json::from_bson(arg)); }; object->registerProperty(path.functionality) .onInterface(path.interface) @@ -154,50 +138,38 @@ void DBusHandler::exposeProperty(const DBusHandler::Path &path, std::function property = proxy->getProperty(path.functionality).onInterface(path.interface); return nlohmann::json::from_bson(property); } -void DBusHandler::getProperty(const DBusHandler::Path &path, DBusVoidCallback &&callback) +void DBusHandler::getProperty(const DBusHandler::Path& path, DBusVoidCallback&& callback) { - - sdbus::IProxy *proxy = findProxy(path); + sdbus::IProxy* proxy = findProxy(path); std::vector property = proxy->getProperty(path.functionality).onInterface(path.interface); callback(nlohmann::json::from_bson(property)); } -void DBusHandler::setProperty(const DBusHandler::Path &path, nlohmann::json arg) +void DBusHandler::setProperty(const DBusHandler::Path& path, nlohmann::json arg) { - - sdbus::IProxy *proxy = findProxy(path); + sdbus::IProxy* proxy = findProxy(path); proxy->setProperty(path.functionality).onInterface(path.interface).toValue(nlohmann::json::to_bson(arg)); } void DBusHandler::finish() { - - for (auto const &proxy : _DBusProxys) - { + for (auto const& proxy : _DBusProxys) proxy.second->finishRegistration(); - } - for (auto const &object : _DBusObjects) - { + for (auto const& object : _DBusObjects) object.second->finishRegistration(); - } _started = true; if (_isServer) - { - _connection->enterEventLoop(); - } } - From 0b4d77cbccf88c37e9c9215cc3132b139d290523 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Wed, 6 Oct 2021 12:08:44 -0300 Subject: [PATCH 039/147] unit test: doing static cast instead of (int) --- tests/daemon-test.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/tests/daemon-test.cpp b/tests/daemon-test.cpp index 9a736f1..8ba4e08 100644 --- a/tests/daemon-test.cpp +++ b/tests/daemon-test.cpp @@ -1,7 +1,9 @@ #include "../src/classes/dbus-handler/dbus-handler.hpp" + #include #include #include +#include #include DBusHandler::Path m_methodPath { @@ -110,7 +112,6 @@ TEST_F(ServerClient, Get) m_client.finish(); nlohmann::json res = m_client.getProperty(m_propertiesPath); - EXPECT_EQ(res, m_properties); } @@ -126,13 +127,10 @@ TEST_F(ServerClient, AsyncGet) TEST_F(ServerClient, Set) { nlohmann::json arg; - - arg["num"] = (int)m_properties["num"] * 4; + arg["num"] = std::static_cast(m_properties["num"]) * 4; m_client.finish(); - m_client.setProperty(m_propertiesPath, arg); EXPECT_EQ(arg, m_properties); } - From ad5da61f00f2d1db264c26296d6ee0fd6c1f758d Mon Sep 17 00:00:00 2001 From: math-42 Date: Wed, 6 Oct 2021 15:22:10 -0300 Subject: [PATCH 040/147] =?UTF-8?q?aplicando=20regra=20de=20nomea=C3=A7?= =?UTF-8?q?=C3=A3o=20de=20vari=C3=A1veis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/classes/dbus-handler/dbus-handler.hpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index b7e0b12..afa0b8c 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -39,14 +39,14 @@ class DBusHandler { }; private: - std::string _serviceName; - bool _started; - bool _isServer; + std::string m_serviceName; + bool m_started; + bool m_isServer; - std::unique_ptr _connection; + std::unique_ptr m_connection; - DBusObjectMap _DBusObjects; - DBusProxyMap _DBusProxys; + DBusObjectMap m_DBusObjects; + DBusProxyMap m_DBusProxys; sdbus::IProxy* findProxy(const DBusHandler::Path& path); From 61d04b62aa8c6491308f3229e2e1494a18a68e2f Mon Sep 17 00:00:00 2001 From: math-42 Date: Wed, 6 Oct 2021 15:24:09 -0300 Subject: [PATCH 041/147] implementando construtor para clientes --- src/classes/dbus-handler/dbus-handler.cpp | 4 +++- src/classes/dbus-handler/dbus-handler.hpp | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index e1b456c..9ebfd88 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -36,7 +36,9 @@ DBusHandler::DBusHandler(const std::string& serviceName, bool isServer) if (isServer) { _connection = sdbus::createSystemBusConnection(serviceName); } -} + +DBusHandler::DBusHandler() + : m_isServer { false } {}; void DBusHandler::registerMethod(const DBusHandler::Path& path, DBusCallback&& callback) { diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index afa0b8c..3433880 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -53,9 +53,9 @@ class DBusHandler { sdbus::IObject* findObject(const DBusHandler::Path& path); public: - DBusHandler(const std::string& serviceName); + DBusHandler(); - DBusHandler(const std::string& serviceName, bool isServer); + DBusHandler(const std::string& serviceName); DBusHandler(const std::string& serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys); From 64d991f51acdd1dd2e5700423f2857b6cc7ed2cc Mon Sep 17 00:00:00 2001 From: math-42 Date: Wed, 6 Oct 2021 15:24:37 -0300 Subject: [PATCH 042/147] formatando arquivo e adicionando tratamento de erros --- src/classes/dbus-handler/dbus-handler.cpp | 69 ++++++++++++++--------- 1 file changed, 43 insertions(+), 26 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index 9ebfd88..5e43280 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -3,10 +3,11 @@ sdbus::IObject* DBusHandler::findObject(const DBusHandler::Path& path) { try { - return _DBusObjects.at(path.objectPath).get(); + return m_DBusObjects.at(path.objectPath).get(); } catch (std::out_of_range& e) { - _DBusObjects[path.objectPath] = sdbus::createObject(*_connection, path.objectPath); - return _DBusObjects[path.objectPath].get(); + + m_DBusObjects[path.objectPath] = sdbus::createObject(*m_connection, path.objectPath); + return m_DBusObjects[path.objectPath].get(); } } @@ -15,33 +16,33 @@ sdbus::IProxy* DBusHandler::findProxy(const DBusHandler::Path& path) const std::string uniqueId = path.service + path.objectPath; try { - return _DBusProxys.at(uniqueId).get(); + + return m_DBusProxys.at(uniqueId).get(); } catch (std::out_of_range& e) { - _DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); - return _DBusProxys[uniqueId].get(); + + m_DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); + return m_DBusProxys[uniqueId].get(); } } DBusHandler::DBusHandler(const std::string& serviceName) - : _isServer { true } - , _serviceName { serviceName } + : m_isServer { true } + , m_serviceName { serviceName } { - _connection = sdbus::createSystemBusConnection(serviceName); -} -DBusHandler::DBusHandler(const std::string& serviceName, bool isServer) - : _isServer { isServer } - , _serviceName { serviceName } -{ - if (isServer) { - _connection = sdbus::createSystemBusConnection(serviceName); - } + m_connection = sdbus::createSystemBusConnection(serviceName); +} DBusHandler::DBusHandler() : m_isServer { false } {}; void DBusHandler::registerMethod(const DBusHandler::Path& path, DBusCallback&& callback) { + if (!m_isServer) + throw std::logic_error("Only servers can register methods"); + if (m_started) + throw std::logic_error("methods should be register before finishing the handler"); + sdbus::IObject* object = findObject(path); auto wrapper = [callback](sdbus::MethodCall call) { @@ -76,6 +77,11 @@ void DBusHandler::subscribeToSignal(const DBusHandler::Path& path, DBusVoidCallb void DBusHandler::registerSignal(const DBusHandler::Path& path) { + if (!m_isServer) + throw std::logic_error("Only servers can register signals"); + if (m_started) + throw std::logic_error("register signals is only possible before finishing the handler"); + sdbus::IObject* object = findObject(path); object->registerSignal(path.interface, path.functionality, "ay"); } @@ -91,7 +97,6 @@ nlohmann::json DBusHandler::callMethod(const DBusHandler::Path& path, nlohmann:: std::vector bson; reply >> bson; - return nlohmann::json::from_bson(bson); } @@ -114,8 +119,10 @@ void DBusHandler::callMethodAsync(const DBusHandler::Path& path, nlohmann::json void DBusHandler::emitSignal(const DBusHandler::Path& path, nlohmann::json arg) { - if (!_started) - return; // add error + if (!m_isServer) + throw std::logic_error("Only servers can emit signals"); + if (!m_started) + throw std::logic_error("emit a signal is only possible after finishing the handler"); sdbus::IObject* object = findObject(path); @@ -128,6 +135,12 @@ void DBusHandler::emitSignal(const DBusHandler::Path& path, nlohmann::json arg) void DBusHandler::exposeProperty(const DBusHandler::Path& path, std::function&& getter, DBusVoidCallback&& setter) { + + if (!m_isServer) + throw std::logic_error("Only servers can expose properties"); + if (m_started) + throw std::logic_error("expose a property is only possible before finishing the handler"); + sdbus::IObject* object = findObject(path); auto getterWrapper = [getter]() { return nlohmann::json::to_bson(getter()); }; @@ -164,14 +177,18 @@ void DBusHandler::setProperty(const DBusHandler::Path& path, nlohmann::json arg) void DBusHandler::finish() { - for (auto const& proxy : _DBusProxys) - proxy.second->finishRegistration(); + m_started = true; - for (auto const& object : _DBusObjects) + for (auto const& object : m_DBusObjects) { object.second->finishRegistration(); + } - _started = true; + for (auto const& proxy : m_DBusProxys) { + proxy.second->finishRegistration(); + } - if (_isServer) - _connection->enterEventLoop(); + if (m_isServer) { + + m_connection->enterEventLoop(); + } } From fd5d4f04d59999260988baeac397c61c5fddf92a Mon Sep 17 00:00:00 2001 From: math-42 Date: Wed, 6 Oct 2021 15:33:32 -0300 Subject: [PATCH 043/147] removendo std:: do static cast --- tests/daemon-test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/daemon-test.cpp b/tests/daemon-test.cpp index 8ba4e08..a856e55 100644 --- a/tests/daemon-test.cpp +++ b/tests/daemon-test.cpp @@ -32,7 +32,7 @@ nlohmann::json m_properties; class ServerClient : public ::testing::Test { public: - DBusHandler m_client { m_methodPath.service, false }; + DBusHandler m_client {}; static void SetUpTestSuite() { @@ -127,7 +127,7 @@ TEST_F(ServerClient, AsyncGet) TEST_F(ServerClient, Set) { nlohmann::json arg; - arg["num"] = std::static_cast(m_properties["num"]) * 4; + arg["num"] = static_cast(m_properties["num"]) * 4; m_client.finish(); m_client.setProperty(m_propertiesPath, arg); From 4e9bbe2f319f210252a4b869ad2aca8185cc3a77 Mon Sep 17 00:00:00 2001 From: math-42 Date: Wed, 6 Oct 2021 15:54:55 -0300 Subject: [PATCH 044/147] =?UTF-8?q?removendo=20arquivos=20que=20n=C3=A3o?= =?UTF-8?q?=20ser=C3=A3o=20utilizados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/classes/dbus-controller/dbus-controller.cpp | 0 src/classes/dbus-controller/dbus-controller.hpp | 0 src/classes/endpoint-handler/endpoint-handler.cpp | 0 src/classes/endpoint-handler/endpoint-handler.hpp | 0 src/classes/endpoint/endpoint.cpp | 0 src/classes/endpoint/endpoint.hpp | 0 6 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/classes/dbus-controller/dbus-controller.cpp delete mode 100644 src/classes/dbus-controller/dbus-controller.hpp delete mode 100644 src/classes/endpoint-handler/endpoint-handler.cpp delete mode 100644 src/classes/endpoint-handler/endpoint-handler.hpp delete mode 100644 src/classes/endpoint/endpoint.cpp delete mode 100644 src/classes/endpoint/endpoint.hpp diff --git a/src/classes/dbus-controller/dbus-controller.cpp b/src/classes/dbus-controller/dbus-controller.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/dbus-controller/dbus-controller.hpp b/src/classes/dbus-controller/dbus-controller.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/endpoint-handler/endpoint-handler.cpp b/src/classes/endpoint-handler/endpoint-handler.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/endpoint-handler/endpoint-handler.hpp b/src/classes/endpoint-handler/endpoint-handler.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/endpoint/endpoint.cpp b/src/classes/endpoint/endpoint.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/endpoint/endpoint.hpp b/src/classes/endpoint/endpoint.hpp deleted file mode 100644 index e69de29..0000000 From 8e31f0a5afbcf6b28025434b92001e1a508e9aa8 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 03:09:36 -0300 Subject: [PATCH 045/147] Refactoring the Repo based in new decisions --- .../endpoint-handler/endpoint-handler.hpp | 0 src/classes/endpoint/endpoint.cpp | 0 src/classes/endpoint/endpoint.hpp | 0 src/classes/routine/routine.cpp | 10 ----- src/classes/routine/routine.hpp | 33 --------------- .../service-handler.cpp} | 0 .../service-handler/service-handler.hpp | 26 ++++++++++++ .../service-proxy.cpp} | 0 .../service-proxy.hpp} | 0 src/classes/service/service.cpp | 10 +++++ src/classes/service/service.hpp | 41 +++++++++++-------- 11 files changed, 60 insertions(+), 60 deletions(-) delete mode 100644 src/classes/endpoint-handler/endpoint-handler.hpp delete mode 100644 src/classes/endpoint/endpoint.cpp delete mode 100644 src/classes/endpoint/endpoint.hpp delete mode 100644 src/classes/routine/routine.cpp delete mode 100644 src/classes/routine/routine.hpp rename src/classes/{endpoint-handler/endpoint-handler.cpp => service-handler/service-handler.cpp} (100%) create mode 100644 src/classes/service-handler/service-handler.hpp rename src/classes/{routine-handler/routine-handler.cpp => service-proxy/service-proxy.cpp} (100%) rename src/classes/{routine-handler/routine-handler.hpp => service-proxy/service-proxy.hpp} (100%) diff --git a/src/classes/endpoint-handler/endpoint-handler.hpp b/src/classes/endpoint-handler/endpoint-handler.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/endpoint/endpoint.cpp b/src/classes/endpoint/endpoint.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/endpoint/endpoint.hpp b/src/classes/endpoint/endpoint.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/routine/routine.cpp b/src/classes/routine/routine.cpp deleted file mode 100644 index 83c6aef..0000000 --- a/src/classes/routine/routine.cpp +++ /dev/null @@ -1,10 +0,0 @@ -/* -* service.cpp -* -* Author: Carlos Craveiro (@CarlosCraveiro) -* Created On: September 11, 2021 -* -*/ - -#include "routine.hpp" - diff --git a/src/classes/routine/routine.hpp b/src/classes/routine/routine.hpp deleted file mode 100644 index fadb445..0000000 --- a/src/classes/routine/routine.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/* -* routine.hpp -* -* Author: Carlos Craveiro (@CarlosCraveiro) -* Created On: September 11, 2021 -* -*/ - -#pragma once -#include -#include - -class Status { - public: - enum stateT { - MISSINGDEPENDENCIES = 0, UNINITIALIZED, INITIALIZED, RUNNING, STOPED, DEAD - - }; - stateT state; - std::mutex mtx; -}; - -class IRoutine { - public: - std::string id; - public: - virtual void onLoad()=0; - virtual void loop()=0; - virtual void unload()=0; - IRoutine(std::string id): id{id} {} - ~IRoutine(void){}; -}; - diff --git a/src/classes/endpoint-handler/endpoint-handler.cpp b/src/classes/service-handler/service-handler.cpp similarity index 100% rename from src/classes/endpoint-handler/endpoint-handler.cpp rename to src/classes/service-handler/service-handler.cpp diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp new file mode 100644 index 0000000..9bce00b --- /dev/null +++ b/src/classes/service-handler/service-handler.hpp @@ -0,0 +1,26 @@ +/* + * service.hpp + * + * Author: Carlos Craveiro (@CarlosCraveiro) + * Created On: September 15, 2021 + */ + +#pragma once +#include +#include +#include "../routine-handler/routine-handler.hpp" + +class Service { + public: + std::vector routines; + std::vector endpoints; + public: + nlohmann::json getServiceStatus(void); + nlohmann::json updateAll(nlohmann::json updateList); + nlohmann::json registerEndpoints(void); + nlohmann::json registerRoutines(void); + + void buildEndpoint(/*IEndpoint& newEndpoint*/); + void buildRoutine(IRoutine& newRoutine); +}; + diff --git a/src/classes/routine-handler/routine-handler.cpp b/src/classes/service-proxy/service-proxy.cpp similarity index 100% rename from src/classes/routine-handler/routine-handler.cpp rename to src/classes/service-proxy/service-proxy.cpp diff --git a/src/classes/routine-handler/routine-handler.hpp b/src/classes/service-proxy/service-proxy.hpp similarity index 100% rename from src/classes/routine-handler/routine-handler.hpp rename to src/classes/service-proxy/service-proxy.hpp diff --git a/src/classes/service/service.cpp b/src/classes/service/service.cpp index e69de29..83c6aef 100644 --- a/src/classes/service/service.cpp +++ b/src/classes/service/service.cpp @@ -0,0 +1,10 @@ +/* +* service.cpp +* +* Author: Carlos Craveiro (@CarlosCraveiro) +* Created On: September 11, 2021 +* +*/ + +#include "routine.hpp" + diff --git a/src/classes/service/service.hpp b/src/classes/service/service.hpp index 9bce00b..fadb445 100644 --- a/src/classes/service/service.hpp +++ b/src/classes/service/service.hpp @@ -1,26 +1,33 @@ /* - * service.hpp - * - * Author: Carlos Craveiro (@CarlosCraveiro) - * Created On: September 15, 2021 - */ +* routine.hpp +* +* Author: Carlos Craveiro (@CarlosCraveiro) +* Created On: September 11, 2021 +* +*/ #pragma once -#include +#include #include -#include "../routine-handler/routine-handler.hpp" -class Service { +class Status { public: - std::vector routines; - std::vector endpoints; - public: - nlohmann::json getServiceStatus(void); - nlohmann::json updateAll(nlohmann::json updateList); - nlohmann::json registerEndpoints(void); - nlohmann::json registerRoutines(void); + enum stateT { + MISSINGDEPENDENCIES = 0, UNINITIALIZED, INITIALIZED, RUNNING, STOPED, DEAD + + }; + stateT state; + std::mutex mtx; +}; - void buildEndpoint(/*IEndpoint& newEndpoint*/); - void buildRoutine(IRoutine& newRoutine); +class IRoutine { + public: + std::string id; + public: + virtual void onLoad()=0; + virtual void loop()=0; + virtual void unload()=0; + IRoutine(std::string id): id{id} {} + ~IRoutine(void){}; }; From 15b6cd18d6b57ed07d3eec8fda37d86b13c98e9a Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 03:14:38 -0300 Subject: [PATCH 046/147] Removing an old not needed anymore class --- src/classes/dbus-controller/dbus-controller.cpp | 0 src/classes/dbus-controller/dbus-controller.hpp | 0 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/classes/dbus-controller/dbus-controller.cpp delete mode 100644 src/classes/dbus-controller/dbus-controller.hpp diff --git a/src/classes/dbus-controller/dbus-controller.cpp b/src/classes/dbus-controller/dbus-controller.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/dbus-controller/dbus-controller.hpp b/src/classes/dbus-controller/dbus-controller.hpp deleted file mode 100644 index e69de29..0000000 From 587d1b2199e883d16bafe60814ba9139d9652c0d Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 04:08:01 -0300 Subject: [PATCH 047/147] fixing requested changes --- CMakeLists.txt | 172 ++++++++++++++++++++++++++++--------------------- 1 file changed, 98 insertions(+), 74 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index fc65673..c7b40ec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ # PROJECT INFORMATION #------------------------------- -cmake_minimum_required(VERSION 3.18) +cmake_minimum_required(VERSION 3.16.3) project(frameworkd VERSION 0.1 LANGUAGES CXX) include(GNUInstallDirs) # Installation directories for `install` command and pkgconfig file @@ -11,74 +11,80 @@ include(GNUInstallDirs) # Installation directories for `install` command and pkg # PROJECT MACROS DEFINITION #------------------------------- -macro(FRAMEWORKD_ADD_DEPS_FILEPATHS_TO outputList baseDir subDir depsList fileExt) - - foreach(dependency IN LISTS ${depsList}) - list(APPEND ${outputList} ${baseDir}/${subDir}/${dependency}/${dependency}.${fileExt}) - endforeach() +macro(ZFKD_ADD_DEPS_FILEPATHS_TO outputList baseDir subDir depsList fileExt) + + foreach(dependency IN LISTS ${depsList}) + list(APPEND ${outputList} ${baseDir}/${subDir}/${dependency}/${dependency}.${fileExt}) + endforeach() -endmacro(FRAMEWORKD_ADD_DEPS_FILEPATHS_TO) +endmacro(ZFKD_ADD_DEPS_FILEPATHS_TO) -macro(FRAMEWORKD_ADD_DEPS_DIRPATHS_TO outputList baseDir subDir depsList) - - foreach(dependency IN LISTS ${depsList}) - list(APPEND ${outputList} ${baseDir}/${subDir}/${dependency}/) - endforeach() +macro(ZFKD_ADD_DEPS_DIRPATHS_TO outputList baseDir subDir depsList) + + foreach(dependency IN LISTS ${depsList}) + list(APPEND ${outputList} ${baseDir}/${subDir}/${dependency}/) + endforeach() -endmacro(FRAMEWORKD_ADD_DEPS_DIRPATHS_TO) +endmacro(ZFKD_ADD_DEPS_DIRPATHS_TO) -macro(FRAMEWORKD_CREATE_DICT contentList indexList dictName) - - set(i 0) - foreach(element IN LISTS ${contentList}) - list(GET ${indexList} ${i} index) - set(${dictName}-${index} ${element}) - math(EXPR i "${i} + 1") - endforeach() +macro(ZFKD_CREATE_DICT contentList indexList dictName) + + set(i 0) + foreach(element IN LISTS ${contentList}) + list(GET ${indexList} ${i} index) + set(${dictName}-${index} ${element}) + math(EXPR i "${i} + 1") + endforeach() -endmacro(FRAMEWORKD_CREATE_DICT) +endmacro(ZFKD_CREATE_DICT) #------------------ # SET SOURCE FILES #------------------ -set(FRAMEWORKD_CLASSES - daemon - service - service-handler) +set(ZFKD_CLASSES + + daemon + service + service-handler + service-proxy +) + +set(ZFKD_UTILITIES + + dbus-handler + config-handler + locked-storage +) -set(FRAMEWORKD_UTILITIES - dbus-handler) #---------------------------- # SOURCE FILES CONFIGURATION #---------------------------- -set(FRAMEWORKD_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) -set(FRAMEWORKD_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include) -set(FRAMEWORKD_UTIL_SUBDIR utilities) -set(FRAMEWORKD_CLSS_SUBDIR classes) - -set(FRAMEWORKD_CPP_SRCS) +set(ZFKD_SRC_DIR ${CMAKE_CURRENT_SRC_DIR}/src) +set(ZFKD_INCLUDE_DIR ${CMAKE_CURRENT_SRC_DIR}/include) +set(ZFKD_UTIL_SUBDIR utilities) +set(ZFKD_CLSS_SUBDIR classes) -FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_CPP_SRCS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_CLSS_SUBDIR} FRAMEWORKD_CLASSES cpp) -FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_CPP_SRCS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_UTIL_SUBDIR} FRAMEWORKD_UTILITIES cpp) +set(ZFKD_CPP_SRCS) -set(FRAMEWORKD_HDR_SRCS) +ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_CPP_SRCS ${ZFKD_SRC_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_CLASSES cpp) +ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_CPP_SRCS ${ZFKD_SRC_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_UTILITIES cpp) -FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_HDR_SRCS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_CLSS_SUBDIR} FRAMEWORKD_CLASSES hpp) -FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_HDR_SRCS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_UTIL_SUBDIR} FRAMEWORKD_UTILITIES hpp) +set(ZFKD_HDR_SRCS) -set(FRAMEWORKD_PUBLIC_HDRS) +ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_HDR_SRCS ${ZFKD_SRC_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_CLASSES hpp) +ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_HDR_SRCS ${ZFKD_SRC_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_UTILITIES hpp) -FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_PUBLIC_HDRS ${FRAMEWORKD_INCLUDE_DIR} ${FRAMEWORKD_CLSS_SUBDIR} FRAMEWORKD_CLASSES hpp) -FRAMEWORKD_ADD_DEPS_FILEPATHS_TO(FRAMEWORKD_PUBLIC_HDRS ${FRAMEWORKD_INCLUDE_DIR} ${FRAMEWORKD_UTIL_SUBDIR} FRAMEWORKD_UTILITIES hpp) +set(ZFKD_PUBLIC_HDRS) -set(FRAMEWORKD_SRCS ${FRAMEWORKD_CPP_SRCS} ${FRAMEWORKD_HDR_SRCS} ${FRAMEWORKD_PUBLIC_HDRS}) +ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_PUBLIC_HDRS ${ZFKD_INCLUDE_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_CLASSES hpp) +ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_PUBLIC_HDRS ${ZFKD_INCLUDE_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_UTILITIES hpp) -add_library(troops OBJECT ${FRAMEWORKD_SRCS}) +set(ZFKD_SRCS ${ZFKD_CPP_SRCS} ${ZFKD_HDR_SRCS} ${ZFKD_PUBLIC_HDRS}) #------------------------------- # GENERAL COMPILER CONFIGURATION @@ -90,33 +96,38 @@ set(CMAKE_CXX_STANDARD 17) # INCLUDE CONAN SETINGS FOR DEVELOPERS #----------------------------------- -option(FRAMEWORKD_USING_CONAN_FOR_DEV "(default ON)" ON) +option(ZFKD_USING_CONAN_FOR_DEV "(default ON)" ON) -if(FRAMEWORKD_USING_CONAN_FOR_DEV) - include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) - conan_basic_setup() +if(ZFKD_USING_CONAN_FOR_DEV) + include(frameworkd-objlib ${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) + conan_basic_setup() endif() #---------------------------------- # LIBRARY BUILD INFORMATION #---------------------------------- -set(FRAMEWORKD_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}") -set(FRAMEWORKD_VERSION "${PROJECT_VERSION}") +set(ZFKD_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}") +set(ZFKD_VERSION "${PROJECT_VERSION}") -set(FRAMEWORKD_SRC_DIRS) -FRAMEWORKD_ADD_DEPS_DIRPATHS_TO(FRAMEWORKD_SRC_DIRS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_CLSS_SUBDIR} FRAMEWORKD_CLASSES) -FRAMEWORKD_ADD_DEPS_DIRPATHS_TO(FRAMEWORKD_SRC_DIRS ${FRAMEWORKD_SOURCE_DIR} ${FRAMEWORKD_UTIL_SUBDIR} FRAMEWORKD_UTILITIES) +set(ZFKD_SRC_DIRS) +ZFKD_ADD_DEPS_DIRPATHS_TO(ZFKD_SRC_DIRS ${ZFKD_SRC_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_CLASSES) +ZFKD_ADD_DEPS_DIRPATHS_TO(ZFKD_SRC_DIRS ${ZFKD_SRC_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_UTILITIES) -FRAMEWORKD_CREATE_DICT(FRAMEWORKD_SRC_DIRS FRAMEWORKD_DEPS FRAMEWORKD_DIR) +ZFKD_CREATE_DICT(ZFKD_SRC_DIRS ZFKD_DEPS ZFKD_DIR) -add_library(frameworkd-objlib OBJECT ${FRAMEWORKD_SRCS}) +add_library(frameworkd-objlib OBJECT ${ZFKD_SRCS}) target_compile_definitions(frameworkd-objlib PRIVATE BUILD_LIB=1) -target_include_directories(frameworkd-objlib PUBLIC $ - $ - $ - $ +target_include_directories(frameworkd-objlib PUBLIC + + $ + $ + $ + $ + $ + $ + $ ) if(DEFINED BUILD_SHARED_LIBS) @@ -124,22 +135,35 @@ if(DEFINED BUILD_SHARED_LIBS) endif() add_library(frameworkd) -target_include_directories(frameworkd PUBLIC $ - $ - $ - $ - $) +target_include_directories(frameworkd PUBLIC + + $ + $ + $ + $ + $ + $ + $ + $ +) set_target_properties(frameworkd - PROPERTIES PUBLIC_HEADER "${FRAMEWORKD_PUBLIC_HDRS}" - VERSION "${FRAMEWORKD_VERSION}" - OUTPUT_NAME "frameworkd") + + PROPERTIES PUBLIC_HEADER "${ZFKD_PUBLIC_HDRS}" + VERSION "${ZFKD_VERSION}" + OUTPUT_NAME "frameworkd" +) -if(FRAMEWORKD_USING_CONAN_FOR_DEV) +if(ZFKD_USING_CONAN_FOR_DEV) + target_link_libraries(frameworkd PRIVATE frameworkd-objlib ${CONANLIBS}) + else() - target_link_libraries(frameworkd PRIVATE frameworkd-objlibs) + + target_link_libraries(frameworkd PRIVATE frameworkd-objlib) + endif() + set(CMAKE_EXPORT_COMPILE_COMMANDS ON) #---------------------------------- @@ -156,9 +180,9 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS ON) option(BUILD_TESTS "Build and install tests (default OFF)" OFF) if(BUILD_TESTS) - message(STATUS "Building with tests") - enable_testing() - add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/tests") + message(STATUS "Building with tests") + enable_testing() + add_subdirectory("${CMAKE_CURRENT_SRC_DIR}/tests") endif() @@ -167,10 +191,10 @@ endif() #------ # Uncoment this section to build your binnaries with this CMake # NOTE: This section is temporary!! -# It will persist until the maintainer solve problems with outside inclusion by "include_subdirectory" mode. +# It will persist until the maintainer solve problems with outside inclusion by "include_subdirectory" mode. # # -#add_executable(sample ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) +#add_executable(sample ${CMAKE_CURRENT_SRC_DIR}/main.cpp) #target_link_libraries(sample ${CONAN_LIBS} frameworkd) From 5f8642e18c2d1f6d9587bbfc10673cb6058c0c90 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 04:17:28 -0300 Subject: [PATCH 048/147] spliting public-headers dependencies from src deps --- CMakeLists.txt | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c7b40ec..c1a33d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,6 +60,19 @@ set(ZFKD_UTILITIES locked-storage ) +set(ZFKD_PUBLIC_CLASSES + + daemon + service +) + +set(ZFKD_PUBLIC_UTILITIES + +) + + + + #---------------------------- # SOURCE FILES CONFIGURATION #---------------------------- @@ -81,8 +94,8 @@ ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_HDR_SRCS ${ZFKD_SRC_DIR} ${ZFKD_UTIL_SUBDIR} ZFK set(ZFKD_PUBLIC_HDRS) -ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_PUBLIC_HDRS ${ZFKD_INCLUDE_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_CLASSES hpp) -ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_PUBLIC_HDRS ${ZFKD_INCLUDE_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_UTILITIES hpp) +ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_PUBLIC_HDRS ${ZFKD_INCLUDE_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_PUBLIC_CLASSES hpp) +ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_PUBLIC_HDRS ${ZFKD_INCLUDE_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_PUBLIC_UTILITIES hpp) set(ZFKD_SRCS ${ZFKD_CPP_SRCS} ${ZFKD_HDR_SRCS} ${ZFKD_PUBLIC_HDRS}) From 964a9dfd4a31be0b07c0591e680e2ab99d70a45e Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 04:18:38 -0300 Subject: [PATCH 049/147] erasing spaces --- CMakeLists.txt | 3 --- 1 file changed, 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c1a33d7..8bef19a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -70,9 +70,6 @@ set(ZFKD_PUBLIC_UTILITIES ) - - - #---------------------------- # SOURCE FILES CONFIGURATION #---------------------------- From f589334d25907351ec9cf6d094bb1f20672167b5 Mon Sep 17 00:00:00 2001 From: math-42 Date: Thu, 7 Oct 2021 04:36:26 -0300 Subject: [PATCH 050/147] hot fix: changing the code style to webkit --- .clang-format | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.clang-format b/.clang-format index d4f347b..202e2c1 100644 --- a/.clang-format +++ b/.clang-format @@ -1 +1 @@ -BasedOnStyle: Microsoft +BasedOnStyle: Webkit From 8a205509eb57f672beff482319c736d69e60940c Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 05:37:04 -0300 Subject: [PATCH 051/147] Fixing some bugs --- CMakeLists.txt | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8bef19a..b63c3e8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -74,8 +74,8 @@ set(ZFKD_PUBLIC_UTILITIES # SOURCE FILES CONFIGURATION #---------------------------- -set(ZFKD_SRC_DIR ${CMAKE_CURRENT_SRC_DIR}/src) -set(ZFKD_INCLUDE_DIR ${CMAKE_CURRENT_SRC_DIR}/include) +set(ZFKD_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) +set(ZFKD_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include) set(ZFKD_UTIL_SUBDIR utilities) set(ZFKD_CLSS_SUBDIR classes) @@ -109,7 +109,7 @@ set(CMAKE_CXX_STANDARD 17) option(ZFKD_USING_CONAN_FOR_DEV "(default ON)" ON) if(ZFKD_USING_CONAN_FOR_DEV) - include(frameworkd-objlib ${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) + include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) conan_basic_setup() endif() @@ -192,7 +192,7 @@ option(BUILD_TESTS "Build and install tests (default OFF)" OFF) if(BUILD_TESTS) message(STATUS "Building with tests") enable_testing() - add_subdirectory("${CMAKE_CURRENT_SRC_DIR}/tests") + add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/tests") endif() @@ -204,7 +204,8 @@ endif() # It will persist until the maintainer solve problems with outside inclusion by "include_subdirectory" mode. # # -#add_executable(sample ${CMAKE_CURRENT_SRC_DIR}/main.cpp) +#add_executable(sample ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) + #target_link_libraries(sample ${CONAN_LIBS} frameworkd) From 7da7893487f1cb24097a3c3e698e6b71790573a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Thu, 7 Oct 2021 08:35:42 -0300 Subject: [PATCH 052/147] config: updating .gitignore --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 0991ed6..193da6a 100644 --- a/.gitignore +++ b/.gitignore @@ -1038,4 +1038,3 @@ modules.order Module.symvers Mkfile.old dkms.conf -tests/test-environment/* \ No newline at end of file From 1e0c3f996dcc90936f2172a0382621fde9745552 Mon Sep 17 00:00:00 2001 From: math-42 Date: Thu, 7 Oct 2021 08:35:54 -0300 Subject: [PATCH 053/147] =?UTF-8?q?removendo=20arquivos=20n=C3=A3o=20utili?= =?UTF-8?q?zados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/classes/config-handler/config-handler.cpp | 0 src/classes/config-handler/config-handler.hpp | 0 .../dbus-controller/dbus-controller.cpp | 5 ----- .../dbus-controller/dbus-controller.hpp | 20 ------------------- 4 files changed, 25 deletions(-) delete mode 100644 src/classes/config-handler/config-handler.cpp delete mode 100644 src/classes/config-handler/config-handler.hpp delete mode 100644 src/classes/dbus-controller/dbus-controller.cpp delete mode 100644 src/classes/dbus-controller/dbus-controller.hpp diff --git a/src/classes/config-handler/config-handler.cpp b/src/classes/config-handler/config-handler.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/config-handler/config-handler.hpp b/src/classes/config-handler/config-handler.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/dbus-controller/dbus-controller.cpp b/src/classes/dbus-controller/dbus-controller.cpp deleted file mode 100644 index 77ba9cf..0000000 --- a/src/classes/dbus-controller/dbus-controller.cpp +++ /dev/null @@ -1,5 +0,0 @@ -#include "./dbus-controller.hpp" - -DBusController::DBusController(std::string serviceName) : serviceName{serviceName} { - connection = sdbus::createSystemBusConnection(serviceName); -} \ No newline at end of file diff --git a/src/classes/dbus-controller/dbus-controller.hpp b/src/classes/dbus-controller/dbus-controller.hpp deleted file mode 100644 index 42d5488..0000000 --- a/src/classes/dbus-controller/dbus-controller.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#include - -#include -#include -class DBusController { - private: - std::string serviceName; - - std::unique_ptr connection; - std::map> DBusObjects; - - public: - DBusController(std::string serviceName); - - void bindSignal(std::string signalName, void (*signalHandler)(std::string json)); - void bindEndpoint(std::string endpointName, sdbus::method_callback signalHandler); - void startListen(); - - ~DBusController(); -}; From e1c8a9caeaddb8ae3f855fc4044bba8e0bb77b85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Thu, 7 Oct 2021 08:50:13 -0300 Subject: [PATCH 054/147] dbus-handler: adding traling functions --- src/classes/dbus-handler/dbus-handler.cpp | 41 +++++++++++++---------- src/classes/dbus-handler/dbus-handler.hpp | 12 +++---- 2 files changed, 30 insertions(+), 23 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index 5e43280..54dd8d1 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,25 +1,22 @@ #include "dbus-handler.hpp" -sdbus::IObject* DBusHandler::findObject(const DBusHandler::Path& path) +auto DBusHandler::findObject(const DBusHandler::Path& path) -> sdbus::IObject* { try { return m_DBusObjects.at(path.objectPath).get(); } catch (std::out_of_range& e) { - m_DBusObjects[path.objectPath] = sdbus::createObject(*m_connection, path.objectPath); return m_DBusObjects[path.objectPath].get(); } } -sdbus::IProxy* DBusHandler::findProxy(const DBusHandler::Path& path) +auto DBusHandler::findProxy(const DBusHandler::Path& path) -> sdbus::IProxy* { const std::string uniqueId = path.service + path.objectPath; try { - return m_DBusProxys.at(uniqueId).get(); } catch (std::out_of_range& e) { - m_DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); return m_DBusProxys[uniqueId].get(); } @@ -29,7 +26,6 @@ DBusHandler::DBusHandler(const std::string& serviceName) : m_isServer { true } , m_serviceName { serviceName } { - m_connection = sdbus::createSystemBusConnection(serviceName); } @@ -38,10 +34,13 @@ DBusHandler::DBusHandler() void DBusHandler::registerMethod(const DBusHandler::Path& path, DBusCallback&& callback) { - if (!m_isServer) + if (!m_isServer) { throw std::logic_error("Only servers can register methods"); - if (m_started) + } + + if (m_started) { throw std::logic_error("methods should be register before finishing the handler"); + } sdbus::IObject* object = findObject(path); @@ -77,16 +76,19 @@ void DBusHandler::subscribeToSignal(const DBusHandler::Path& path, DBusVoidCallb void DBusHandler::registerSignal(const DBusHandler::Path& path) { - if (!m_isServer) + if (!m_isServer) { throw std::logic_error("Only servers can register signals"); - if (m_started) + } + + if (m_started) { throw std::logic_error("register signals is only possible before finishing the handler"); + } sdbus::IObject* object = findObject(path); object->registerSignal(path.interface, path.functionality, "ay"); } -nlohmann::json DBusHandler::callMethod(const DBusHandler::Path& path, nlohmann::json arg) +auto DBusHandler::callMethod(const DBusHandler::Path& path, nlohmann::json arg) -> nlohmann::json { sdbus::IProxy* proxy = findProxy(path); auto method = proxy->createMethodCall(path.interface, path.functionality); @@ -119,10 +121,13 @@ void DBusHandler::callMethodAsync(const DBusHandler::Path& path, nlohmann::json void DBusHandler::emitSignal(const DBusHandler::Path& path, nlohmann::json arg) { - if (!m_isServer) + if (!m_isServer) { throw std::logic_error("Only servers can emit signals"); - if (!m_started) + } + + if (!m_started) { throw std::logic_error("emit a signal is only possible after finishing the handler"); + } sdbus::IObject* object = findObject(path); @@ -136,10 +141,13 @@ void DBusHandler::exposeProperty(const DBusHandler::Path& path, std::function nlohmann::json { sdbus::IProxy* proxy = findProxy(path); std::vector property = proxy->getProperty(path.functionality).onInterface(path.interface); @@ -188,7 +196,6 @@ void DBusHandler::finish() } if (m_isServer) { - m_connection->enterEventLoop(); } } diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 3433880..5c52485 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -48,14 +48,14 @@ class DBusHandler { DBusObjectMap m_DBusObjects; DBusProxyMap m_DBusProxys; - sdbus::IProxy* findProxy(const DBusHandler::Path& path); + auto findProxy(const DBusHandler::Path& path) -> sdbus::IProxy*; - sdbus::IObject* findObject(const DBusHandler::Path& path); + auto findObject(const DBusHandler::Path& path) -> sdbus::IObject*; public: - DBusHandler(); + DBusHandler() = default; - DBusHandler(const std::string& serviceName); + explicit DBusHandler(const std::string& serviceName); DBusHandler(const std::string& serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys); @@ -68,7 +68,7 @@ class DBusHandler { void registerSignal(const DBusHandler::Path& path); - nlohmann::json callMethod(const DBusHandler::Path& path, nlohmann::json arg); + auto callMethod(const DBusHandler::Path& path, nlohmann::json arg) -> nlohmann::json; void callMethodAsync(const DBusHandler::Path& path, nlohmann::json arg, DBusVoidCallback&& callback); @@ -77,7 +77,7 @@ class DBusHandler { void exposeProperty(const DBusHandler::Path& path, std::function&& getter, DBusVoidCallback&& setter); - nlohmann::json getProperty(const DBusHandler::Path& path); + auto getProperty(const DBusHandler::Path& path) -> nlohmann::json; void getProperty(const DBusHandler::Path& path, DBusVoidCallback&& callback); From 73b90f1894b8e53cdc4c2ddfd8a3b269be33efb5 Mon Sep 17 00:00:00 2001 From: math-42 Date: Thu, 7 Oct 2021 09:13:09 -0300 Subject: [PATCH 055/147] =?UTF-8?q?removendo=20arquivos=20n=C3=A3o=20utili?= =?UTF-8?q?zados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/classes/config-handler/config-handler.cpp | 0 src/classes/config-handler/config-handler.hpp | 0 .../DBusNameHandler/dbus-name-handler.cpp | 37 ------------------- .../DBusNameHandler/dbus-name-handler.hpp | 24 ------------ 4 files changed, 61 deletions(-) delete mode 100644 src/classes/config-handler/config-handler.cpp delete mode 100644 src/classes/config-handler/config-handler.hpp delete mode 100644 src/utilities/DBusNameHandler/dbus-name-handler.cpp delete mode 100644 src/utilities/DBusNameHandler/dbus-name-handler.hpp diff --git a/src/classes/config-handler/config-handler.cpp b/src/classes/config-handler/config-handler.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/config-handler/config-handler.hpp b/src/classes/config-handler/config-handler.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/utilities/DBusNameHandler/dbus-name-handler.cpp b/src/utilities/DBusNameHandler/dbus-name-handler.cpp deleted file mode 100644 index ab74b7f..0000000 --- a/src/utilities/DBusNameHandler/dbus-name-handler.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "./dbus-name-handler.hpp" - -DBusName::DBusName(std::string serviceId) { - serviceIdDots = "org.frameworkd." + serviceId; - serviceIdSlashes = "/" + serviceIdDots; - std::replace(serviceIdSlashes.begin(), serviceIdSlashes.end(), '.', '/'); -} - -std::string DBusName::getDaemonId() { - return serviceIdDots; -} - -std::string DBusName::getObjectPath(std::string objectName) { - return serviceIdSlashes + "/" + objectName; -} - -std::string DBusName::getInterfaceName(std::string interfaceName) { - return serviceIdDots + "." + interfaceName; -} - -nlohmann::json DBusName::parseFuncionalityPath(std::string functionalityPath) { - std::replace(functionalityPath.begin(), functionalityPath.end(), '/', ' '); - std::vector array; - std::stringstream ss(functionalityPath); - - std::string word; - while (ss >> word) array.push_back(word); - - nlohmann::json parsedResponse; - - parsedResponse["serviceId"] = array[0] + "." + array[1] + "." + array[2]; - parsedResponse["objectPath"] = "/" + array[0] + "/" + array[1] + "/" + array[2] + "/" + array[3]; - parsedResponse["interfaceName"] = array[0] + "." + array[1] + "." + array[2] +"." + array[3]; - parsedResponse["functionalityName"] = array[4]; - - return parsedResponse; -} diff --git a/src/utilities/DBusNameHandler/dbus-name-handler.hpp b/src/utilities/DBusNameHandler/dbus-name-handler.hpp deleted file mode 100644 index a477adb..0000000 --- a/src/utilities/DBusNameHandler/dbus-name-handler.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -class DBusName { - private: - - std::string serviceIdDots; - std::string serviceIdSlashes; - - public: - - DBusName(std::string serviceId); - std::string getObjectPath(std::string objectName); - std::string getDaemonId(); - std::string getInterfaceName(std::string interfaceName); - - static nlohmann::json parseFuncionalityPath(std::string funcionalityPath); - -}; \ No newline at end of file From 051793de00535b1783d536c543a3b7985b3963d0 Mon Sep 17 00:00:00 2001 From: math-42 Date: Thu, 7 Oct 2021 09:13:37 -0300 Subject: [PATCH 056/147] criando header file do config handler --- .../config-handler/config-handler.hpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/utilities/config-handler/config-handler.hpp diff --git a/src/utilities/config-handler/config-handler.hpp b/src/utilities/config-handler/config-handler.hpp new file mode 100644 index 0000000..d59b880 --- /dev/null +++ b/src/utilities/config-handler/config-handler.hpp @@ -0,0 +1,22 @@ +#include +#include +#include + +class ConfigHandler { +private: + static nlohmann::json m_config; + std::string m_fileName; + std::vector m_requiredFields { + "data", "services", "serviceId" + }; + +public: + explicit ConfigHandler(std::string fileName); + void read(std::string fileName); + void read(); + auto operator[](std::string field) const -> const nlohmann::json; + +private: + [[nodiscard]] auto getConfig(std::string field) const -> const nlohmann::json; + void validateConfig(); +}; From 5acd61591bc63afda9afa442afdc7e2a820834fe Mon Sep 17 00:00:00 2001 From: math-42 Date: Thu, 7 Oct 2021 09:15:02 -0300 Subject: [PATCH 057/147] adicionando funcionalidades do config handler --- .../config-handler/config-handler.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/utilities/config-handler/config-handler.cpp diff --git a/src/utilities/config-handler/config-handler.cpp b/src/utilities/config-handler/config-handler.cpp new file mode 100644 index 0000000..4facac2 --- /dev/null +++ b/src/utilities/config-handler/config-handler.cpp @@ -0,0 +1,62 @@ +#include "config-handler.hpp" + +ConfigHandler::ConfigHandler(std::string fileName) + : m_fileName(fileName) +{ +} + +/** + * @brief Validate the json + */ +void ConfigHandler::validateConfig() +{ + for (const auto& it : m_requiredFields) { + if (!m_config.contains(it)) { + throw std::runtime_error("Config file dosen't have all the required fields"); + } + } +} + +/** + * @brief Reads a file and turn them into a json object + */ +void ConfigHandler::read() +{ + std::ifstream file(m_fileName); + if (!file.is_open()) { + throw std::invalid_argument("File not found"); + } + + file >> m_config; + + validateConfig(); + + file.close(); +} + +/** + * @brief Reads a file and turn them into a json object + * @param fileName Name of the file to read + */ +void ConfigHandler::read(std::string fileName) +{ + m_fileName = fileName; + read(); +} + +/** + * @brief Gets a value from the json object + * @param field Field to get the value + */ +auto ConfigHandler::getConfig(std::string field) const -> const nlohmann::json +{ + return m_config[field]; +} + +/** + * @brief Operator overload that encapsulates the getConfig() + */ +auto ConfigHandler::operator[](std::string field) const -> const nlohmann::json +{ + return getConfig(field); +} From 635f6f8fb00f9b50985ef2f0c1a0fdaa29b122aa Mon Sep 17 00:00:00 2001 From: math-42 Date: Thu, 7 Oct 2021 09:23:55 -0300 Subject: [PATCH 058/147] =?UTF-8?q?adicionando=20const=20por=20boas=20pr?= =?UTF-8?q?=C3=A1ticas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utilities/config-handler/config-handler.cpp | 8 ++++---- src/utilities/config-handler/config-handler.hpp | 11 +++++------ 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/utilities/config-handler/config-handler.cpp b/src/utilities/config-handler/config-handler.cpp index 4facac2..8371e0c 100644 --- a/src/utilities/config-handler/config-handler.cpp +++ b/src/utilities/config-handler/config-handler.cpp @@ -1,6 +1,6 @@ #include "config-handler.hpp" -ConfigHandler::ConfigHandler(std::string fileName) +ConfigHandler::ConfigHandler(const std::string& fileName) : m_fileName(fileName) { } @@ -38,7 +38,7 @@ void ConfigHandler::read() * @brief Reads a file and turn them into a json object * @param fileName Name of the file to read */ -void ConfigHandler::read(std::string fileName) +void ConfigHandler::read(const std::string& fileName) { m_fileName = fileName; read(); @@ -48,7 +48,7 @@ void ConfigHandler::read(std::string fileName) * @brief Gets a value from the json object * @param field Field to get the value */ -auto ConfigHandler::getConfig(std::string field) const -> const nlohmann::json +auto ConfigHandler::getConfig(const std::string& field) const -> const nlohmann::json { return m_config[field]; } @@ -56,7 +56,7 @@ auto ConfigHandler::getConfig(std::string field) const -> const nlohmann::json /** * @brief Operator overload that encapsulates the getConfig() */ -auto ConfigHandler::operator[](std::string field) const -> const nlohmann::json +auto ConfigHandler::operator[](const std::string& field) const -> const nlohmann::json { return getConfig(field); } diff --git a/src/utilities/config-handler/config-handler.hpp b/src/utilities/config-handler/config-handler.hpp index d59b880..638993a 100644 --- a/src/utilities/config-handler/config-handler.hpp +++ b/src/utilities/config-handler/config-handler.hpp @@ -1,22 +1,21 @@ #include -#include #include class ConfigHandler { private: static nlohmann::json m_config; std::string m_fileName; - std::vector m_requiredFields { + const std::vector m_requiredFields { "data", "services", "serviceId" }; public: - explicit ConfigHandler(std::string fileName); - void read(std::string fileName); + explicit ConfigHandler(const std::string& fileName); + void read(const std::string& fileName); void read(); - auto operator[](std::string field) const -> const nlohmann::json; + auto operator[](const std::string& field) const -> const nlohmann::json; private: - [[nodiscard]] auto getConfig(std::string field) const -> const nlohmann::json; + [[nodiscard]] auto getConfig(const std::string& field) const -> const nlohmann::json; void validateConfig(); }; From f768b1e7d8d00999233b92820c79ef41fb5200a4 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 10:41:00 -0300 Subject: [PATCH 059/147] Implementing the IService --- src/classes/service/service.hpp | 41 +++++++++++++-------------------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/src/classes/service/service.hpp b/src/classes/service/service.hpp index fadb445..781b6dc 100644 --- a/src/classes/service/service.hpp +++ b/src/classes/service/service.hpp @@ -1,33 +1,24 @@ -/* -* routine.hpp -* -* Author: Carlos Craveiro (@CarlosCraveiro) -* Created On: September 11, 2021 -* -*/ #pragma once -#include #include +#include -class Status { - public: - enum stateT { - MISSINGDEPENDENCIES = 0, UNINITIALIZED, INITIALIZED, RUNNING, STOPED, DEAD +class IService { +public: + std::string m_serviceId; - }; - stateT state; - std::mutex mtx; -}; +protected: + // DBusHandler::DBusHandler m_dbus; + +public: + virtual void setup() = 0; + virtual void routine() = 0; + virtual void destroy() = 0; + explicit IService(std::string serviceId) + : m_serviceId { serviceId } + { + } -class IRoutine { - public: - std::string id; - public: - virtual void onLoad()=0; - virtual void loop()=0; - virtual void unload()=0; - IRoutine(std::string id): id{id} {} - ~IRoutine(void){}; + virtual ~IService() = default; }; From 851e9e15991ca3f6cb2030c03bf36a35215381bc Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 10:42:03 -0300 Subject: [PATCH 060/147] Implementing the service-proxy --- src/classes/service-proxy/service-proxy.cpp | 133 ++++++++------------ src/classes/service-proxy/service-proxy.hpp | 79 +++++++----- 2 files changed, 100 insertions(+), 112 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index d2bd9f3..b2fa684 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -1,95 +1,68 @@ -/* -* routine-handler.cpp -* -* Author: Carlos Craveiro (@CarlosCraveiro) -* Created On: September 11, 2021 -*/ - -#include "routine-handler.hpp" - -void routineModule(IRoutine& routine, Status& status) { - routine.onLoad(); - status.mtx.lock(); - status.state = Status::RUNNING; - while(status.state == Status::STOPED){ - status.mtx.unlock(); - routine.loop(); - status.mtx.lock(); - } - status.mtx.unlock(); +#include "service-proxy.hpp" + +auto Status::getState() -> Status::stateT +{ + + const std::lock_guard lock(m_mtx); + + return m_state; } -RoutineHandler::RoutineHandler(IRoutine& routine, nlohmann::json& configs) { - (*this->routine) = routine; - this->status.mtx.lock(); - this->status.state = Status::MISSINGDEPENDENCIES; - this->status.mtx.unlock(); - this->depsRefState = configs["dependencies"]; - this->depsCrntState = configs["dependencies"]; - for(nlohmann::json& dependencie : this->depsCrntState) { - dependencie["status"] = Status::MISSINGDEPENDENCIES; - } - this->info.data = configs; - +void Status::setState(Status::stateT newState) +{ + + const std::lock_guard lock(m_mtx); + + m_state = newState; } -RoutineHandler::~RoutineHandler() { - //DO NOTHING +void ServiceProxy::servicePod(std::unique_ptr service, Status& status) +{ + + service->setup(); + status.setState(Status::RUNNING); + + while (status.getState() == Status::STOPED) { + + service->routine(); + } + + service->destroy(); } -void RoutineHandler::run(void) { - std::thread thread(routineModule, std::ref(*routine), std::ref(status)); - status.mtx.lock(); - status.state = Status::INITIALIZED; - status.mtx.unlock(); - std::swap(thread, innerThread); +ServiceProxy::ServiceProxy(IService& service, nlohmann::json configs) + : m_innerService(std::make_unique(service)) +{ + m_dependencies.data = configs; //DETAILS ABOUT DEPENDENCIES } -void RoutineHandler::stop(void) { - status.mtx.lock(); - status.state = Status::STOPED; - status.mtx.unlock(); - innerThread.join(); - status.mtx.lock(); - status.state = Status::DEAD; - status.mtx.unlock(); +ServiceProxy::~ServiceProxy() +{ + auto currState = m_status.getState(); + if (currState == Status::RUNNING) { + stop(); + } } -nlohmann::json RoutineHandler::getStatus(void) { - std::lock_guard lck(info.occupied); - status.mtx.lock(); - info.data["state"] = status.state; - status.mtx.unlock(); - return info.data; +void ServiceProxy::run() +{ + std::thread thread(servicePod, std::ref(m_innerService), std::ref(m_status)); //WARNINGGG!!!!!!!!!!!!!!!!!!! + m_status.setState(Status::INITIALIZED); + std::swap(thread, m_innerThread); +} +void ServiceProxy::stop() +{ + m_status.setState(Status::STOPED); + m_innerThread.join(); + m_status.setState(Status::DEAD); } -nlohmann::json RoutineHandler::update(void) { - int missingDeps = depsRefState["lenght"]; - for(int i = 0; i < depsRefState["lenght"]; i++) { - using namespace nlohmann; - const json& dependencie = depsCrntState[i]; - const json& dependencieRef = depsRefState[i]; - if(dependencie["status"] == dependencieRef["status"]) { - missingDeps--; - } - } - if(!missingDeps) { - run(); - nlohmann::json changes = getStatus(); - return (nlohmann::json) {{{"changed", true}}, changes}; - } - status.mtx.lock(); - if(status.state == Status::RUNNING) { - status.mtx.unlock(); - stop(); - status.mtx.lock(); - status.state = Status::MISSINGDEPENDENCIES; - status.mtx.unlock(); - nlohmann::json changes = getStatus(); - return (nlohmann::json) {{{"changed", true}}, changes}; - } - status.mtx.unlock(); - return (nlohmann::json) {{"changed", false}}; +auto ServiceProxy::getStatus() -> nlohmann::json +{ + auto currStatus = m_status.getState(); + std::lock_guard lock(m_dependencies.mtx); + + return { m_dependencies.data["serviceId"], { "State", currStatus } }; } diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index e9f183c..1c4eabf 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -1,36 +1,51 @@ -/* -* routine-handler.hpp -* -* Author: Carlos Craveiro (@CarlosCraveiro) -* Created On: September 11, 2021 -*/ - #pragma once -#include +#include "../service/service.hpp" #include -#include "../routine/routine.hpp" - -void routineModule(IRoutine& routine, Status& status); - -class RoutineHandler { - public: - IRoutine* routine; - struct Info { - nlohmann::json data; - std::mutex occupied; - }; - Info info; - Status status; - std::thread innerThread; - nlohmann::json depsRefState; - nlohmann::json depsCrntState; - - public: - void run(void); - void stop(void); - nlohmann::json getStatus(void); - nlohmann::json update(void); - RoutineHandler(IRoutine& routine, nlohmann::json& configs); - ~RoutineHandler(void); +#include +#include +#include + +class Status { +public: + enum stateT { + MISSINGDEPENDENCIES = 0, + UNINITIALIZED, + INITIALIZED, + RUNNING, + STOPED, + DEAD + }; + +private: + stateT m_state; + std::mutex m_mtx; + +public: + auto getState()->stateT; + void setState(stateT newState); +}; + + +class ServiceProxy { +private: + std::unique_ptr m_innerService; + struct SafeJson { + nlohmann::json data; + std::mutex mtx; + }; + SafeJson m_dependencies; + Status m_status; + std::thread m_innerThread; + +public: + auto getStatus()->nlohmann::json; + // nlohmann::json update(void); + ServiceProxy(IService& service, nlohmann::json configs); + ~ServiceProxy(); + +private: + void run(); + void stop(); + void servicePod(IService& service, Status& status); }; From f8a715c363ec3e13e234d587163d9c7f43eef09a Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 14:08:41 -0300 Subject: [PATCH 061/147] Hot fix: adding -pthread flag to the compile command --- CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index b63c3e8..6f58e15 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -102,6 +102,8 @@ set(ZFKD_SRCS ${ZFKD_CPP_SRCS} ${ZFKD_HDR_SRCS} ${ZFKD_PUBLIC_HDRS}) set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_FLAGS "-pthread ${CMAKE_CXX_FLAGS}") + #----------------------------------- # INCLUDE CONAN SETINGS FOR DEVELOPERS #----------------------------------- From 08ccce5af77f05c213a2f69cc3845ff94bc4b249 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 14:14:33 -0300 Subject: [PATCH 062/147] fixing inheritance problems in IService --- src/classes/service/service.cpp | 2 +- src/classes/service/service.hpp | 39 ++++++++++++++++++++++++++++----- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/classes/service/service.cpp b/src/classes/service/service.cpp index 83c6aef..c4d5b28 100644 --- a/src/classes/service/service.cpp +++ b/src/classes/service/service.cpp @@ -6,5 +6,5 @@ * */ -#include "routine.hpp" +#include "service.hpp" diff --git a/src/classes/service/service.hpp b/src/classes/service/service.hpp index 781b6dc..8d7a3be 100644 --- a/src/classes/service/service.hpp +++ b/src/classes/service/service.hpp @@ -5,20 +5,49 @@ class IService { public: - std::string m_serviceId; + /* Id of the service */ + std::string m_serviceId; protected: // DBusHandler::DBusHandler m_dbus; public: - virtual void setup() = 0; - virtual void routine() = 0; - virtual void destroy() = 0; - explicit IService(std::string serviceId) + + /** + * @brief An interface function to be implemented + * by the user to make the "setup" of its + * class' parameter members. + */ + virtual void setup() = 0; + + /** + * @brief An interface function to be implemented + * by the user to make the "setup" of its + * class' parameter members. + */ + virtual void routine() = 0; + + /** + * @brief An interface function to be implemented + * by the user to make the "setup" of its + * class' parameter members. + */ + virtual void destroy() = 0; + + /** + * @brief An interface function to be implemented + * by the user to make the "setup" of its + * class' parameter members. + */ + explicit IService(std::string serviceId) : m_serviceId { serviceId } { } + /** + * @brief A virtual destructor to ensure + * inheriance compatibility. + */ virtual ~IService() = default; }; From 079592ac4684b43d4b8e60c16e31ad84978a019e Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 14:21:57 -0300 Subject: [PATCH 063/147] implementing an alpha version of class ServiceProxy --- src/classes/service-proxy/service-proxy.cpp | 21 +++++++++++++-------- src/classes/service-proxy/service-proxy.hpp | 7 ++++--- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index b2fa684..d3ed134 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -16,24 +16,29 @@ void Status::setState(Status::stateT newState) m_state = newState; } -void ServiceProxy::servicePod(std::unique_ptr service, Status& status) +void ServiceProxy::servicePod(IService& service, Status& status) { - service->setup(); + service.setup(); status.setState(Status::RUNNING); - while (status.getState() == Status::STOPED) { + while (status.getState() != Status::STOPED) { - service->routine(); + service.routine(); } - service->destroy(); + service.destroy(); } ServiceProxy::ServiceProxy(IService& service, nlohmann::json configs) - : m_innerService(std::make_unique(service)) + : m_innerService(service) { m_dependencies.data = configs; //DETAILS ABOUT DEPENDENCIES + + m_status.setState(Status::UNINITIALIZED); + if (configs["dependencies"] == 0) { + run(); + } } ServiceProxy::~ServiceProxy() @@ -46,7 +51,7 @@ ServiceProxy::~ServiceProxy() void ServiceProxy::run() { - std::thread thread(servicePod, std::ref(m_innerService), std::ref(m_status)); //WARNINGGG!!!!!!!!!!!!!!!!!!! + std::thread thread(servicePod, std::ref(m_innerService), std::ref(m_status)); m_status.setState(Status::INITIALIZED); std::swap(thread, m_innerThread); } @@ -63,6 +68,6 @@ auto ServiceProxy::getStatus() -> nlohmann::json auto currStatus = m_status.getState(); std::lock_guard lock(m_dependencies.mtx); - return { m_dependencies.data["serviceId"], { "State", currStatus } }; + return (nlohmann::json) { { "serviceId", m_dependencies.data["serviceId"] }, { "State", currStatus } }; } diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index 1c4eabf..b9251eb 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -28,7 +28,7 @@ class Status { class ServiceProxy { private: - std::unique_ptr m_innerService; + IService& m_innerService; struct SafeJson { nlohmann::json data; std::mutex mtx; @@ -43,9 +43,10 @@ class ServiceProxy { ServiceProxy(IService& service, nlohmann::json configs); ~ServiceProxy(); -private: +//private: void run(); void stop(); - void servicePod(IService& service, Status& status); +private: + static void servicePod(IService& service, Status& status); }; From 070d60f8b1581c24dbcb73af8e23176151dacd94 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 17:11:24 -0300 Subject: [PATCH 064/147] adding JavaDoc --- src/classes/service/service.hpp | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/classes/service/service.hpp b/src/classes/service/service.hpp index 8d7a3be..b514e19 100644 --- a/src/classes/service/service.hpp +++ b/src/classes/service/service.hpp @@ -9,35 +9,39 @@ class IService { std::string m_serviceId; protected: + // DBusHandler::DBusHandler m_dbus; public: /** - * @brief An interface function to be implemented - * by the user to make the "setup" of its - * class' parameter members. + * @brief An interface function to be implemented by + * the user to make the "setup"/configuration + * of its class' parameter-members. */ virtual void setup() = 0; /** * @brief An interface function to be implemented - * by the user to make the "setup" of its - * class' parameter members. + * by the user. This function is going to + * run in a loop, so its instructions are + * going to be executed "routinely". */ virtual void routine() = 0; /** - * @brief An interface function to be implemented - * by the user to make the "setup" of its - * class' parameter members. + * @brief An interface function to be implemented by + * the user to execute the needed instructions + * to safely "destroy" the resources used by the + * class' previous functions. */ virtual void destroy() = 0; /** - * @brief An interface function to be implemented - * by the user to make the "setup" of its - * class' parameter members. + * @brief The constructor of this interface. + * + * @param serviceId std::string that is the id related + * to the instantiated class. */ explicit IService(std::string serviceId) : m_serviceId { serviceId } From 0f8c526ef38168523d5fb8086b49898eb2e401b3 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Thu, 7 Oct 2021 18:34:24 -0300 Subject: [PATCH 065/147] Adding JavDocs for service-proxy --- src/classes/service-proxy/service-proxy.hpp | 82 ++++++++++++++++++--- 1 file changed, 72 insertions(+), 10 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index b9251eb..f3eab27 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -1,12 +1,13 @@ #pragma once #include "../service/service.hpp" +#include #include #include #include -#include class Status { public: + /*enum for the possible service-thread states*/ enum stateT { MISSINGDEPENDENCIES = 0, UNINITIALIZED, @@ -17,36 +18,97 @@ class Status { }; private: + /*state from @ref stateT enum*/ stateT m_state; + + /*class' mutex to ensure it's thread safe*/ std::mutex m_mtx; public: - auto getState()->stateT; - void setState(stateT newState); -}; + /** + * @brief thread-safe getter to inside member @ref m_state + * + * @return stateT state that's inside the class. + */ + auto getState() -> stateT; + /** + * @brief thread-safe setter to the inside member @ref m_state + * + * @param stateT state that will be the new state of the class. + */ + void setState(stateT newState); +}; class ServiceProxy { private: - IService& m_innerService; + /* a reference for a Service implemented by the user */ + IService& m_innerService; + + /* structure made to allow the use of the service-proxy + * conf-file in multiples threads. + */ struct SafeJson { nlohmann::json data; std::mutex mtx; }; + + /* json thread-safe that will contain the service-proxy conf-file */ SafeJson m_dependencies; + + /* class made to keep track of innerThread current state */ Status m_status; + + /* thread object that will contain the running thread */ std::thread m_innerThread; public: - auto getStatus()->nlohmann::json; + /** + * @brief returns a json with the general status + information + * about the service-proxy's innerThread and its innerService. + */ + auto getStatus() -> nlohmann::json; + + /* Function that will update the inner dependencies along changes in their states */ // nlohmann::json update(void); - ServiceProxy(IService& service, nlohmann::json configs); + + /** + * @brief class' constructor + * + * @param service IService class passed by reference + * + * @param configs nlohmann::json that contains the configure + * files that refer to the service-proxy and + * its @ref innerService + */ + ServiceProxy(IService& service, nlohmann::json configs); + + /** + * @brief class' destructor + */ ~ServiceProxy(); -//private: + //private: + + /** + * @brief starts running the @ref m_innerService in + * a thread that will be in @ref m_innerThread, + * and that is encapsulated with @ref servicePod. + */ void run(); + + /** + * @brief stops a running thread "located" in + * @ref m_innerThread that contains an @ref m_innerService + * and that is encapsulated with @ref servicePod + */ void stop(); -private: - static void servicePod(IService& service, Status& status); + +private: + /** + * @brief function that encapsulates the class @ref IService + * to be runned in a thread as explicit in @ref run + */ + static void servicePod(IService& service, Status& status); }; From 2717731b1a80ca398963b94de35f988b54dd8538 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Fri, 8 Oct 2021 14:06:34 -0300 Subject: [PATCH 066/147] Removed the "default" assignment to the constructor --- src/classes/dbus-handler/dbus-handler.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 5c52485..929e387 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -53,7 +53,7 @@ class DBusHandler { auto findObject(const DBusHandler::Path& path) -> sdbus::IObject*; public: - DBusHandler() = default; + DBusHandler(); explicit DBusHandler(const std::string& serviceName); From 0765de48c0f25afc55a353a1e1a97e0d32fdafc6 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Fri, 8 Oct 2021 14:08:11 -0300 Subject: [PATCH 067/147] Moved all the global variables to the class as static members --- tests/daemon-test.cpp | 54 ++++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/tests/daemon-test.cpp b/tests/daemon-test.cpp index a856e55..0c47840 100644 --- a/tests/daemon-test.cpp +++ b/tests/daemon-test.cpp @@ -6,34 +6,16 @@ #include #include -DBusHandler::Path m_methodPath { - "org.sdbuscpp.concatenator", - "/org/sdbuscpp/concatenator", - "org.sdbuscpp.Concatenator", - "concatenate" -}; - -DBusHandler::Path m_signalPath { - "org.sdbuscpp.concatenator", - "/org/sdbuscpp/concatenator", - "org.sdbuscpp.Concatenator", - "concatenated" -}; - -DBusHandler::Path m_propertiesPath { - "org.sdbuscpp.concatenator", - "/org/sdbuscpp/concatenator", - "org.sdbuscpp.Concatenator", - "properties" -}; - -bool isServerConfig; -nlohmann::json m_properties; - class ServerClient : public ::testing::Test { public: DBusHandler m_client {}; + static DBusHandler::Path m_methodPath; + static DBusHandler::Path m_signalPath; + static DBusHandler::Path m_propertiesPath; + static bool isServerConfig; + static nlohmann::json m_properties; + static void SetUpTestSuite() { isServerConfig = true; @@ -66,6 +48,30 @@ class ServerClient : public ::testing::Test { } }; +DBusHandler::Path ServerClient::m_methodPath { + "org.sdbuscpp.concatenator", + "/org/sdbuscpp/concatenator", + "org.sdbuscpp.Concatenator", + "concatenate" +}; + +DBusHandler::Path ServerClient::m_signalPath { + "org.sdbuscpp.concatenator", + "/org/sdbuscpp/concatenator", + "org.sdbuscpp.Concatenator", + "concatenated" +}; + +DBusHandler::Path ServerClient::m_propertiesPath { + "org.sdbuscpp.concatenator", + "/org/sdbuscpp/concatenator", + "org.sdbuscpp.Concatenator", + "properties" +}; + +bool ServerClient::isServerConfig; +nlohmann::json ServerClient::m_properties; + TEST_F(ServerClient, Method) { nlohmann::json arg; From 61caf16564c8d8b17c232bc0081e664af9d2061f Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Sat, 9 Oct 2021 19:54:00 -0300 Subject: [PATCH 068/147] deleting unnecessary header --- src/classes/service/service.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/classes/service/service.cpp b/src/classes/service/service.cpp index c4d5b28..bdc179b 100644 --- a/src/classes/service/service.cpp +++ b/src/classes/service/service.cpp @@ -1,10 +1,3 @@ -/* -* service.cpp -* -* Author: Carlos Craveiro (@CarlosCraveiro) -* Created On: September 11, 2021 -* -*/ #include "service.hpp" From f247b1a2084270415723a4c09c6e2c2f073ac805 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Tue, 12 Oct 2021 23:35:40 -0300 Subject: [PATCH 069/147] fix: STOPPED syntax --- src/classes/service-handler/service-handler.hpp | 9 ++------- src/classes/service-proxy/service-proxy.cpp | 6 +++--- src/classes/service-proxy/service-proxy.hpp | 4 ++-- 3 files changed, 7 insertions(+), 12 deletions(-) diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index 9bce00b..9c2b048 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -1,14 +1,9 @@ -/* - * service.hpp - * - * Author: Carlos Craveiro (@CarlosCraveiro) - * Created On: September 15, 2021 - */ #pragma once #include #include -#include "../routine-handler/routine-handler.hpp" +#include "../service-proxy/service-proxy.hpp" +#include "../service/service.hpp" class Service { public: diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index d3ed134..044c958 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -22,7 +22,7 @@ void ServiceProxy::servicePod(IService& service, Status& status) service.setup(); status.setState(Status::RUNNING); - while (status.getState() != Status::STOPED) { + while (status.getState() != Status::STOPPED) { service.routine(); } @@ -51,14 +51,14 @@ ServiceProxy::~ServiceProxy() void ServiceProxy::run() { - std::thread thread(servicePod, std::ref(m_innerService), std::ref(m_status)); + std::thread thread(&servicePod, std::ref(m_innerService), std::ref(m_status), this); m_status.setState(Status::INITIALIZED); std::swap(thread, m_innerThread); } void ServiceProxy::stop() { - m_status.setState(Status::STOPED); + m_status.setState(Status::STOPPED); m_innerThread.join(); m_status.setState(Status::DEAD); } diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index f3eab27..d5470cc 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -13,7 +13,7 @@ class Status { UNINITIALIZED, INITIALIZED, RUNNING, - STOPED, + STOPPED, DEAD }; @@ -109,6 +109,6 @@ class ServiceProxy { * @brief function that encapsulates the class @ref IService * to be runned in a thread as explicit in @ref run */ - static void servicePod(IService& service, Status& status); + void servicePod(IService& service, Status& status); }; From 09015faf65880d5d45bbc8666be3e693ee14a28f Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Wed, 13 Oct 2021 02:26:21 -0300 Subject: [PATCH 070/147] improve: SafeJson with standard C++ inline constructor --- src/classes/service-proxy/service-proxy.cpp | 23 +++--- src/classes/service-proxy/service-proxy.hpp | 18 +++-- src/classes/service/service.hpp | 83 ++++++++++----------- 3 files changed, 62 insertions(+), 62 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index 044c958..bb5f569 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -16,25 +16,24 @@ void Status::setState(Status::stateT newState) m_state = newState; } -void ServiceProxy::servicePod(IService& service, Status& status) +void ServiceProxy::servicePod() { - service.setup(); - status.setState(Status::RUNNING); + m_realService.setup(); + m_status.setState(Status::RUNNING); - while (status.getState() != Status::STOPPED) { + while (m_status.getState() != Status::STOPPED) { - service.routine(); + m_realService.routine(); } - service.destroy(); + m_realService.destroy(); } ServiceProxy::ServiceProxy(IService& service, nlohmann::json configs) - : m_innerService(service) + : m_realService(service) + , m_dependencies(configs) { - m_dependencies.data = configs; //DETAILS ABOUT DEPENDENCIES - m_status.setState(Status::UNINITIALIZED); if (configs["dependencies"] == 0) { run(); @@ -51,7 +50,7 @@ ServiceProxy::~ServiceProxy() void ServiceProxy::run() { - std::thread thread(&servicePod, std::ref(m_innerService), std::ref(m_status), this); + std::thread thread(&ServiceProxy::servicePod, this); m_status.setState(Status::INITIALIZED); std::swap(thread, m_innerThread); } @@ -66,8 +65,8 @@ void ServiceProxy::stop() auto ServiceProxy::getStatus() -> nlohmann::json { auto currStatus = m_status.getState(); - std::lock_guard lock(m_dependencies.mtx); + std::lock_guard lock(m_dependencies.m_mtx); - return (nlohmann::json) { { "serviceId", m_dependencies.data["serviceId"] }, { "State", currStatus } }; + return (nlohmann::json) { { "serviceId", m_dependencies.m_data["serviceId"] }, { "State", currStatus } }; } diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index d5470cc..8b606a6 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -4,12 +4,13 @@ #include #include #include +#include class Status { public: /*enum for the possible service-thread states*/ enum stateT { - MISSINGDEPENDENCIES = 0, + MISSING_DEPENDENCIES = 0, UNINITIALIZED, INITIALIZED, RUNNING, @@ -43,14 +44,19 @@ class Status { class ServiceProxy { private: /* a reference for a Service implemented by the user */ - IService& m_innerService; + IService& m_realService; /* structure made to allow the use of the service-proxy * conf-file in multiples threads. */ - struct SafeJson { - nlohmann::json data; - std::mutex mtx; + class SafeJson { + public: + nlohmann::json m_data; + std::mutex m_mtx; + SafeJson(nlohmann::json data) + : m_data(data) + { + } }; /* json thread-safe that will contain the service-proxy conf-file */ @@ -109,6 +115,6 @@ class ServiceProxy { * @brief function that encapsulates the class @ref IService * to be runned in a thread as explicit in @ref run */ - void servicePod(IService& service, Status& status); + void servicePod(); }; diff --git a/src/classes/service/service.hpp b/src/classes/service/service.hpp index b514e19..5ac540a 100644 --- a/src/classes/service/service.hpp +++ b/src/classes/service/service.hpp @@ -5,53 +5,48 @@ class IService { public: - /* Id of the service */ - std::string m_serviceId; + /* Id of the service */ + std::string m_serviceId; protected: - - // DBusHandler::DBusHandler m_dbus; + // DBusHandler::DBusHandler m_dbus; public: - - /** - * @brief An interface function to be implemented by - * the user to make the "setup"/configuration - * of its class' parameter-members. - */ - virtual void setup() = 0; - - /** - * @brief An interface function to be implemented - * by the user. This function is going to - * run in a loop, so its instructions are - * going to be executed "routinely". - */ - virtual void routine() = 0; - - /** - * @brief An interface function to be implemented by - * the user to execute the needed instructions - * to safely "destroy" the resources used by the - * class' previous functions. - */ - virtual void destroy() = 0; - - /** - * @brief The constructor of this interface. - * - * @param serviceId std::string that is the id related - * to the instantiated class. - */ - explicit IService(std::string serviceId) - : m_serviceId { serviceId } - { - } - - /** - * @brief A virtual destructor to ensure - * inheriance compatibility. - */ - virtual ~IService() = default; + /** + * @brief An interface function to be implemented by + * the user to make the "setup"/configuration + * of its class' parameter-members. + */ + virtual void setup() = 0; + + /** + * @brief An interface function to be implemented + * by the user. This function is going to + * run in a loop, so its instructions are + * going to be executed "routinely". + */ + virtual void routine() = 0; + + /** + * @brief An interface function to be implemented by + * the user to execute the needed instructions + * to safely "destroy" the resources used by the + * class' previous functions. + */ + virtual void destroy() = 0; + + /** + * @brief The constructor of this interface. + * + * @param serviceId std::string that is the id related + * to the instantiated class. + */ + explicit IService(std::string serviceId) : m_serviceId{serviceId} {} + + /** + * @brief A virtual destructor to ensure + * inheriance compatibility. + */ + virtual ~IService() = default; }; From 23beb5648fda76aed1a423c71349dea5bef2c5c1 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Fri, 15 Oct 2021 00:11:53 -0300 Subject: [PATCH 071/147] Adding get status methods to ServiceHandler --- .../service-handler/service-handler.cpp | 37 +++++++++++++++++++ .../service-handler/service-handler.hpp | 28 +++++++------- 2 files changed, 51 insertions(+), 14 deletions(-) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index e69de29..0d722f9 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -0,0 +1,37 @@ +#include "service-handler.hpp" + +// +// void buildServiceProxy(IService& userService); +// explicit ServiceHandler(nlohmann::json servicesConfigs); + +ServiceHandler::ServiceHandler(nlohmann::json servicesConfigs) + : m_servicesConfigs(servicesConfigs) + +{ +} + +void ServiceHandler::buildServiceProxy(IService& userService) +{ + + m_serviceMap.emplace(std::piecewise_construct, + std::forward_as_tuple(userService.m_serviceId), + std::forward_as_tuple(userService, m_servicesConfigs)); +} + +auto ServiceHandler::getProxyStatus(std::string serviceId) -> nlohmann::json +{ + nlohmann::json requiredStatus = m_serviceMap.at(serviceId).getStatus(); + return requiredStatus; +} + +auto ServiceHandler::getAllProxyStatus() -> nlohmann::json +{ + std::map::iterator itr; + nlohmann::json allStatus; + for(itr = m_serviceMap.begin(); itr != m_serviceMap.end(); itr++) { + allStatus[itr->first] = itr->second.getStatus(); + } + + return allStatus; +} + diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index 9c2b048..6ff338a 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -1,21 +1,21 @@ - #pragma once -#include -#include #include "../service-proxy/service-proxy.hpp" #include "../service/service.hpp" +#include +#include +#include + +class ServiceHandler { +//private: +public: + std::map m_serviceMap; + nlohmann::json m_servicesConfigs; -class Service { - public: - std::vector routines; - std::vector endpoints; - public: - nlohmann::json getServiceStatus(void); - nlohmann::json updateAll(nlohmann::json updateList); - nlohmann::json registerEndpoints(void); - nlohmann::json registerRoutines(void); +public: + auto getProxyStatus(std::string serviceId) -> nlohmann::json; + auto getAllProxyStatus() -> nlohmann::json; - void buildEndpoint(/*IEndpoint& newEndpoint*/); - void buildRoutine(IRoutine& newRoutine); + void buildServiceProxy(IService& userService); + explicit ServiceHandler(nlohmann::json servicesConfigs); }; From 369f08cbabb75a607b6b777cf9f957fcb730d797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= <61601791+mairacanal@users.noreply.github.com> Date: Sat, 16 Oct 2021 19:59:42 -0300 Subject: [PATCH 072/147] dbus-handler: fix misspelling Co-authored-by: Arthur Grillo Queiroz Cabral <53825439+Grillo-0@users.noreply.github.com> --- src/classes/dbus-handler/dbus-handler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index 54dd8d1..54c24ca 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -39,7 +39,7 @@ void DBusHandler::registerMethod(const DBusHandler::Path& path, DBusCallback&& c } if (m_started) { - throw std::logic_error("methods should be register before finishing the handler"); + throw std::logic_error("Methods should be register before finishing the handler"); } sdbus::IObject* object = findObject(path); From 3894a545a15e63521be5d557440d17d5c9c8a2c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Sat, 16 Oct 2021 21:47:21 -0300 Subject: [PATCH 073/147] dbus-handler: changing DBusHandler construtor order --- src/classes/dbus-handler/dbus-handler.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index 54dd8d1..c72eaa4 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,5 +1,15 @@ #include "dbus-handler.hpp" +DBusHandler::DBusHandler(const std::string& serviceName) + : m_isServer { true } + , m_serviceName { serviceName } +{ + m_connection = sdbus::createSystemBusConnection(serviceName); +} + +DBusHandler::DBusHandler() + : m_isServer { false } {}; + auto DBusHandler::findObject(const DBusHandler::Path& path) -> sdbus::IObject* { try { @@ -22,16 +32,6 @@ auto DBusHandler::findProxy(const DBusHandler::Path& path) -> sdbus::IProxy* } } -DBusHandler::DBusHandler(const std::string& serviceName) - : m_isServer { true } - , m_serviceName { serviceName } -{ - m_connection = sdbus::createSystemBusConnection(serviceName); -} - -DBusHandler::DBusHandler() - : m_isServer { false } {}; - void DBusHandler::registerMethod(const DBusHandler::Path& path, DBusCallback&& callback) { if (!m_isServer) { From b2d4e4e5fdc2aaef087e43819dd7978e9f489ab7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= Date: Sat, 16 Oct 2021 22:04:27 -0300 Subject: [PATCH 074/147] dbus-handler: removing unecessary library --- src/classes/dbus-handler/dbus-handler.hpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 929e387..41d82f7 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -4,7 +4,6 @@ #include #include #include -#include #include #include From f7f98810f0241847ce10dd735c9285fd2f3b123e Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Sat, 23 Oct 2021 03:56:35 -0300 Subject: [PATCH 075/147] service-proxy: Beginning the refactor of class' header-file --- src/classes/service-proxy/service-proxy.hpp | 144 +++++++------------- 1 file changed, 49 insertions(+), 95 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index 8b606a6..0bdf81d 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -1,120 +1,74 @@ #pragma once #include "../service/service.hpp" -#include +#include #include #include #include -#include + +class ServiceProxy; class Status { public: - /*enum for the possible service-thread states*/ - enum stateT { - MISSING_DEPENDENCIES = 0, + enum statusT { MISSING_DEPENDENCIES = 0, UNINITIALIZED, - INITIALIZED, RUNNING, STOPPED, - DEAD - }; - -private: - /*state from @ref stateT enum*/ - stateT m_state; - - /*class' mutex to ensure it's thread safe*/ - std::mutex m_mtx; + FINISHED, + STAND_BY, + UNKNOWN }; + +protected: + statusT m_state; + ServiceProxy* m_upperProxy; + std::mutex m_statusMtx; + + virtual void someThingIsMissing() { } + virtual void allFine() { } + auto getStatus() -> statusT; +}; +class ServiceProxy { public: - /** - * @brief thread-safe getter to inside member @ref m_state - * - * @return stateT state that's inside the class. - */ - auto getState() -> stateT; + enum proxyT { staticService = 0, + routineService }; - /** - * @brief thread-safe setter to the inside member @ref m_state - * - * @param stateT state that will be the new state of the class. - */ - void setState(stateT newState); -}; +protected: + class ProxyConfigs { + struct Dependencie { + Status::statusT m_reqrState; + Status::statusT m_currState; + }; -class ServiceProxy { -private: - /* a reference for a Service implemented by the user */ - IService& m_realService; + std::map m_depsMap; - /* structure made to allow the use of the service-proxy - * conf-file in multiples threads. - */ - class SafeJson { public: - nlohmann::json m_data; - std::mutex m_mtx; - SafeJson(nlohmann::json data) - : m_data(data) - { - } + void changeDep(std::string dependencieId, Status::statusT currState); + explicit ProxyConfigs(std::map depsMap); }; - /* json thread-safe that will contain the service-proxy conf-file */ - SafeJson m_dependencies; - - /* class made to keep track of innerThread current state */ - Status m_status; - - /* thread object that will contain the running thread */ - std::thread m_innerThread; - -public: - /** - * @brief returns a json with the general status + information - * about the service-proxy's innerThread and its innerService. - */ - auto getStatus() -> nlohmann::json; - - /* Function that will update the inner dependencies along changes in their states */ - // nlohmann::json update(void); - - /** - * @brief class' constructor - * - * @param service IService class passed by reference - * - * @param configs nlohmann::json that contains the configure - * files that refer to the service-proxy and - * its @ref innerService - */ - ServiceProxy(IService& service, nlohmann::json configs); - - /** - * @brief class' destructor - */ - ~ServiceProxy(); + proxyT m_proxyType; + ProxyConfigs m_proxyConfigs; + Status* m_state; + IService& m_realService; - //private: + virtual void serviceCycle() { } + virtual void changeState() { } + virtual void autoUpdate() { } + auto reportStatus() -> nlohmann::json; - /** - * @brief starts running the @ref m_innerService in - * a thread that will be in @ref m_innerThread, - * and that is encapsulated with @ref servicePod. - */ - void run(); + explicit ServiceProxy(IService& realService, std::map depsMap); +}; - /** - * @brief stops a running thread "located" in - * @ref m_innerThread that contains an @ref m_innerService - * and that is encapsulated with @ref servicePod - */ - void stop(); +namespace staticService { +class Proxy; -private: - /** - * @brief function that encapsulates the class @ref IService - * to be runned in a thread as explicit in @ref run - */ - void servicePod(); +class Proxy : public ServiceProxy { +public: }; +} +namespace routineService { +class Proxy : public ServiceProxy { +public: +}; +} From 0ef297f4251443721e08db9ef46105f032df7072 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Sun, 24 Oct 2021 18:18:51 -0300 Subject: [PATCH 076/147] IService: updating to allow "override" detection --- src/classes/service/service.hpp | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/classes/service/service.hpp b/src/classes/service/service.hpp index 5ac540a..ceea973 100644 --- a/src/classes/service/service.hpp +++ b/src/classes/service/service.hpp @@ -5,11 +5,11 @@ class IService { public: - /* Id of the service */ - std::string m_serviceId; + /* Id of the service */ + std::string m_serviceId; protected: - // DBusHandler::DBusHandler m_dbus; +// DBusHandler::DBusHandler m_dbus; public: /** @@ -17,15 +17,16 @@ class IService { * the user to make the "setup"/configuration * of its class' parameter-members. */ - virtual void setup() = 0; + virtual void setup() = 0; /** - * @brief An interface function to be implemented - * by the user. This function is going to - * run in a loop, so its instructions are - * going to be executed "routinely". + * @brief An interface function to be implemented by + * the user if it wants to create a + * Routine Service. If it's implemented, + * this function is going to run in a loop, so its + * instructions are going to be executed "routinely". */ - virtual void routine() = 0; + void routine() { } /** * @brief An interface function to be implemented by @@ -33,7 +34,7 @@ class IService { * to safely "destroy" the resources used by the * class' previous functions. */ - virtual void destroy() = 0; + virtual void destroy() = 0; /** * @brief The constructor of this interface. @@ -41,12 +42,16 @@ class IService { * @param serviceId std::string that is the id related * to the instantiated class. */ - explicit IService(std::string serviceId) : m_serviceId{serviceId} {} + + explicit IService(std::string serviceId) + : m_serviceId { serviceId } + { + } /** * @brief A virtual destructor to ensure * inheriance compatibility. */ - virtual ~IService() = default; + virtual ~IService() = default; }; From 8aedc92e685e5ce3ac7ca2a873c8e530fa0b472f Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Sun, 24 Oct 2021 20:24:55 -0300 Subject: [PATCH 077/147] ServiceProxy: refactoring ".h" with state design pattern --- src/classes/service-proxy/service-proxy.hpp | 143 ++++++++++++++++++-- 1 file changed, 128 insertions(+), 15 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index 0bdf81d..f7b4171 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -9,7 +9,7 @@ class ServiceProxy; class Status { public: - enum statusT { MISSING_DEPENDENCIES = 0, + enum stateT { MISSING_DEPENDENCIES = 0, UNINITIALIZED, RUNNING, STOPPED, @@ -18,13 +18,16 @@ class Status { UNKNOWN }; protected: - statusT m_state; - ServiceProxy* m_upperProxy; + const stateT m_state; std::mutex m_statusMtx; - virtual void someThingIsMissing() { } + virtual void somethingIsMissing() { } virtual void allFine() { } - auto getStatus() -> statusT; + auto getState() -> stateT; + explicit Status(stateT state) + : m_state(state) + { + } }; class ServiceProxy { @@ -35,40 +38,150 @@ class ServiceProxy { protected: class ProxyConfigs { struct Dependencie { - Status::statusT m_reqrState; - Status::statusT m_currState; + Status::stateT m_reqrState; + Status::stateT m_currState; }; std::map m_depsMap; public: - void changeDep(std::string dependencieId, Status::statusT currState); - explicit ProxyConfigs(std::map depsMap); + void changeDep(std::string dependencieId, Status::stateT currState); + explicit ProxyConfigs(std::map depsMap); }; proxyT m_proxyType; ProxyConfigs m_proxyConfigs; - Status* m_state; IService& m_realService; virtual void serviceCycle() { } virtual void changeState() { } virtual void autoUpdate() { } - auto reportStatus() -> nlohmann::json; + auto reportStatus() -> nlohmann::json { return { {} }; } - explicit ServiceProxy(IService& realService, std::map depsMap); + explicit ServiceProxy(IService& realService, std::map depsMap); }; namespace staticService { class Proxy; +class SStatus : public Status { +protected: + const Proxy* m_upperProxy; + +public: + explicit SStatus(stateT state) + : Status(state) + { + } +}; + +class MissingDependencies : public SStatus { +public: + explicit MissingDependencies() + : SStatus(MISSING_DEPENDENCIES) + { + } + void allFine() override; +}; + +class Uninitialized : public SStatus { +public: + explicit Uninitialized() + : SStatus(UNINITIALIZED) + { + } + void somethingIsMissing() override; +}; + +class Running : public SStatus { +public: + explicit Running() + : SStatus(RUNNING) + { + } +}; + +class StandBy : public SStatus { +public: + explicit StandBy() + : SStatus(STAND_BY) + { + } + void somethingIsMissing() override; +}; + class Proxy : public ServiceProxy { +protected: + bool m_runnedOnce; + SStatus* m_status; + public: + void execute() { serviceCycle(); } // Temporary!!! }; -} +} // namespace staticService namespace routineService { -class Proxy : public ServiceProxy { +class Proxy; +class RStatus : public Status { public: + std::mutex m_borrowMtx; + Proxy* m_upperProxy; + + explicit RStatus(stateT state) + : Status(state) + { + } }; -} + +class MissingDependencies : public RStatus { +public: + explicit MissingDependencies() + : RStatus(MISSING_DEPENDENCIES) + { + } + + void allFine() override; +}; + +class StandBy : public RStatus { +public: + explicit StandBy() + : RStatus(STAND_BY) + { + } +}; + +class Running : public RStatus { +public: + explicit Running() + : RStatus(RUNNING) + { + } + + void somethingIsMissing() override; +}; + +class Stopped : public RStatus { +public: + explicit Stopped() + : RStatus(STOPPED) + { + } +}; + +class Finished : public RStatus { +public: + explicit Finished() + : RStatus(FINISHED) + { + } +}; + +class Proxy : public ServiceProxy { +protected: + std::thread m_thread; + void weave(); + void cut(); +}; +} // namespace routineService + From 2b63525aad45fd9950da7b2a98a1c6e1651bd17e Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Tue, 26 Oct 2021 02:48:19 -0300 Subject: [PATCH 078/147] ServiceProxy: finishing refactoring process --- src/classes/service-proxy/service-proxy.cpp | 239 +++++++++++++++++--- src/classes/service-proxy/service-proxy.hpp | 122 +++++++--- 2 files changed, 294 insertions(+), 67 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index bb5f569..5fd7743 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -1,72 +1,247 @@ #include "service-proxy.hpp" +#include +#include auto Status::getState() -> Status::stateT { + return m_state; +} - const std::lock_guard lock(m_mtx); +ServiceProxy::ProxyConfigs::ProxyConfigs(std::map depsMap) +{ + std::map::iterator itr; - return m_state; + for (itr = depsMap.begin(); itr != depsMap.end(); itr++) { + + m_depsMap.emplace(itr->first, Dependencie(itr->second, Status::UNKNOWN)); + } +} + +void ServiceProxy::ProxyConfigs::changeDep(std::string dependencieId, Status::stateT currState) +{ + m_depsMap[dependencieId].m_currState = currState; +} + +void staticService::MissingDependencies::allFine() +{ + + stateT newState = UNINITIALIZED; + if (m_upperProxy->m_runnedOnce) { + + newState = STAND_BY; + } + + m_upperProxy->changeState(newState); +} + + +// Uninitialized and StandBy Constructor will expose the endpoint on the DBUS + +void staticService::Uninitialized::somethingIsMissing() +{ + // Unexpose/Hide the endpoint on the DBUS and THEN.. + m_upperProxy->changeState(MISSING_DEPENDENCIES); } -void Status::setState(Status::stateT newState) +void staticService::StandBy::somethingIsMissing() { + // Unexpose/Hide the endpoint on the DBUS and THEN... + m_upperProxy->changeState(MISSING_DEPENDENCIES); +} - const std::lock_guard lock(m_mtx); +staticService::Proxy::Proxy(IService& realService, std::map depsMap) + : ServiceProxy(realService, STATIC_SERVICE, depsMap) +{ + autoUpdate(); +} - m_state = newState; +staticService::Proxy::~Proxy() +{ + delete m_status; } -void ServiceProxy::servicePod() +void staticService::Proxy::autoUpdate() { + bool noMissingDependencies = true; + + std::map::iterator itr; + for (itr = m_proxyConfigs.m_depsMap.begin(); itr != m_proxyConfigs.m_depsMap.end(); itr++) { + if (itr->second.m_currState != itr->second.m_reqrState) { + noMissingDependencies = false; + } + } + + (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); +} + +void staticService::Proxy::serviceCycle() +{ + changeState(Status::RUNNING); m_realService.setup(); - m_status.setState(Status::RUNNING); + m_realService.destroy(); + changeState(Status::STAND_BY); +} - while (m_status.getState() != Status::STOPPED) { +void staticService::Proxy::changeState(Status::stateT newState) +{ + const std::lock_guard lock(m_statusMtx); + + switch (newState) { + case Status::MISSING_DEPENDENCIES: + delete m_status; + m_status = new MissingDependencies(this, &m_statusMtx); + break; + case Status::UNINITIALIZED: + delete m_status; + m_status = new Uninitialized(this, &m_statusMtx); + break; + case Status::RUNNING: + delete m_status; + m_status = new Running(this, &m_statusMtx); + break; + case Status::STAND_BY: + delete m_status; + m_status = new StandBy(this, &m_statusMtx); + break; + case Status::STOPPED: + case Status::UNKNOWN: + case Status::FINISHED: + std::cout << "ERROR!! This was not supose to happen!! - Static Service" << std::endl; + }; +} + +auto staticService::Proxy::checkState() -> Status::stateT +{ + const std::lock_guard lock(m_statusMtx); + return m_status->getState(); +} + +auto staticService::Proxy::reportStatus() -> nlohmann::json +{ + Status::stateT currStatus = checkState(); + + return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; +} + + + + + + + + +routineService::Proxy::Proxy(IService& realService, std::map depsMap) + : ServiceProxy(realService, ROUTINE_SERVICE, depsMap) +{ + autoUpdate(); +} + +routineService::Proxy::~Proxy() +{ + delete m_status; +} + + +void routineService::MissingDependencies::allFine() +{ + // Expose/Hide the endpoint on the DBUS and THEN.. + m_upperProxy->weave(); +} + +void routineService::Running::somethingIsMissing() +{ + // Unexpose/Hide the endpoint on the DBUS and THEN.. + m_upperProxy->cut(); +} + +void routineService::Proxy::serviceCycle() +{ + changeState(Status::RUNNING); + m_realService.setup(); + + while (checkState() != Status::STOPPED) { m_realService.routine(); } m_realService.destroy(); + + changeState(Status::FINISHED); } -ServiceProxy::ServiceProxy(IService& service, nlohmann::json configs) - : m_realService(service) - , m_dependencies(configs) +void routineService::Proxy::weave() { - m_status.setState(Status::UNINITIALIZED); - if (configs["dependencies"] == 0) { - run(); - } + const std::lock_guard lock(m_updateMtx); + changeState(Status::STAND_BY); + std::thread thread(&routineService::Proxy::serviceCycle, this); + std::swap(thread, m_thread); } -ServiceProxy::~ServiceProxy() +void routineService::Proxy::cut() { - auto currState = m_status.getState(); - if (currState == Status::RUNNING) { - stop(); - } + const std::lock_guard lock(m_updateMtx); + changeState(Status::STOPPED); + m_thread.join(); + changeState(Status::MISSING_DEPENDENCIES); +} + +void routineService::Proxy::autoUpdate() +{ + bool noMissingDependencies = true; + + std::map::iterator itr; + + for (itr = m_proxyConfigs.m_depsMap.begin(); itr != m_proxyConfigs.m_depsMap.end(); itr++) { + if (itr->second.m_currState != itr->second.m_reqrState) { + noMissingDependencies = false; + } + } + + (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); } -void ServiceProxy::run() +void routineService::Proxy::changeState(Status::stateT newState) { - std::thread thread(&ServiceProxy::servicePod, this); - m_status.setState(Status::INITIALIZED); - std::swap(thread, m_innerThread); + const std::lock_guard lock(m_statusMtx); + + switch (newState) { + case Status::MISSING_DEPENDENCIES: + delete m_status; + m_status = new MissingDependencies(this, &m_statusMtx, &m_updateMtx); + break; + case Status::RUNNING: + delete m_status; + m_status = new Running(this, &m_statusMtx, &m_updateMtx); + break; + case Status::STAND_BY: + delete m_status; + m_status = new StandBy(this, &m_statusMtx, &m_updateMtx); + break; + case Status::STOPPED: + delete m_status; + m_status = new Stopped(this, &m_statusMtx, &m_updateMtx); + break; + case Status::FINISHED: + delete m_status; + m_status = new Finished(this, &m_statusMtx, &m_updateMtx); + break; + case Status::UNINITIALIZED: + case Status::UNKNOWN: + std::cout << "ERROR!! This was not supose to happen!! - Routine Service" << std::endl; + }; } -void ServiceProxy::stop() +auto routineService::Proxy::checkState() -> Status::stateT { - m_status.setState(Status::STOPPED); - m_innerThread.join(); - m_status.setState(Status::DEAD); + const std::lock_guard lock(m_statusMtx); + return m_status->getState(); } -auto ServiceProxy::getStatus() -> nlohmann::json +auto routineService::Proxy::reportStatus() -> nlohmann::json { - auto currStatus = m_status.getState(); - std::lock_guard lock(m_dependencies.m_mtx); + Status::stateT currStatus = checkState(); - return (nlohmann::json) { { "serviceId", m_dependencies.m_data["serviceId"] }, { "State", currStatus } }; + return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; } diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index f7b4171..f8f1170 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -19,66 +19,84 @@ class Status { protected: const stateT m_state; - std::mutex m_statusMtx; + std::mutex* const m_statusMtx; virtual void somethingIsMissing() { } virtual void allFine() { } auto getState() -> stateT; - explicit Status(stateT state) - : m_state(state) + Status(stateT state, std::mutex* const statusMtx) + : m_state(state), m_statusMtx(statusMtx) { } }; class ServiceProxy { public: - enum proxyT { staticService = 0, - routineService }; + enum proxyT { STATIC_SERVICE = 0, + ROUTINE_SERVICE }; protected: class ProxyConfigs { + public: struct Dependencie { Status::stateT m_reqrState; Status::stateT m_currState; + Dependencie(Status::stateT reqrState, Status::stateT currState) + : m_reqrState(reqrState) + , m_currState(currState) + { + } + + Dependencie() = default; }; std::map m_depsMap; - public: void changeDep(std::string dependencieId, Status::stateT currState); explicit ProxyConfigs(std::map depsMap); }; proxyT m_proxyType; + std::mutex m_statusMtx; ProxyConfigs m_proxyConfigs; + std::string m_realServiceId; IService& m_realService; virtual void serviceCycle() { } - virtual void changeState() { } + virtual void changeState(Status::stateT newState) { } virtual void autoUpdate() { } - auto reportStatus() -> nlohmann::json { return { {} }; } + virtual auto reportStatus() -> nlohmann::json { return { {} }; } - explicit ServiceProxy(IService& realService, std::map depsMap); + ServiceProxy(IService& realService, proxyT proxyType, std::map depsMap) + : m_realService(realService) + , m_proxyType(proxyType) + , m_proxyConfigs(depsMap), + m_realServiceId(realService.m_serviceId) + { + } }; namespace staticService { class Proxy; class SStatus : public Status { + friend class Proxy; + protected: - const Proxy* m_upperProxy; + Proxy* const m_upperProxy; public: - explicit SStatus(stateT state) - : Status(state) + SStatus(stateT state, Proxy* const upperProxy, std::mutex* const statusMtx) + : Status(state, statusMtx) + , m_upperProxy(upperProxy) { } }; class MissingDependencies : public SStatus { public: - explicit MissingDependencies() - : SStatus(MISSING_DEPENDENCIES) + explicit MissingDependencies(Proxy* const upperProxy, std::mutex* const statusMtx) + : SStatus(MISSING_DEPENDENCIES, upperProxy, statusMtx) { } void allFine() override; @@ -86,8 +104,8 @@ class MissingDependencies : public SStatus { class Uninitialized : public SStatus { public: - explicit Uninitialized() - : SStatus(UNINITIALIZED) + explicit Uninitialized(Proxy* const upperProxy, std::mutex* const statusMtx) + : SStatus(UNINITIALIZED, upperProxy, statusMtx) { } void somethingIsMissing() override; @@ -95,27 +113,40 @@ class Uninitialized : public SStatus { class Running : public SStatus { public: - explicit Running() - : SStatus(RUNNING) + explicit Running(Proxy* const upperProxy, std::mutex* const statusMtx) + : SStatus(RUNNING, upperProxy, statusMtx) { } }; class StandBy : public SStatus { public: - explicit StandBy() - : SStatus(STAND_BY) + explicit StandBy(Proxy* const upperProxy, std::mutex* const statusMtx) + : SStatus(STAND_BY, upperProxy, statusMtx) { } void somethingIsMissing() override; }; class Proxy : public ServiceProxy { + friend class MissingDependencies; + friend class Uninitialized; + friend class Running; + friend class StandBy; + protected: bool m_runnedOnce; SStatus* m_status; + void changeState(Status::stateT newState) override; + void serviceCycle() override; + void autoUpdate() override; + auto checkState() -> Status::stateT; + Proxy(IService& realService, std::map depsMap); + ~Proxy(); + public: + auto reportStatus()-> nlohmann::json override; void execute() { serviceCycle(); } // Temporary!!! }; } // namespace staticService @@ -123,20 +154,24 @@ class Proxy : public ServiceProxy { namespace routineService { class Proxy; class RStatus : public Status { + friend class Proxy; + public: - std::mutex m_borrowMtx; - Proxy* m_upperProxy; + std::mutex* const m_updateMtx; + Proxy* const m_upperProxy; - explicit RStatus(stateT state) - : Status(state) + RStatus(stateT state, Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) + : m_upperProxy(upperProxy), + m_updateMtx(updateMtx) + , Status(state, statusMtx) { } }; class MissingDependencies : public RStatus { public: - explicit MissingDependencies() - : RStatus(MISSING_DEPENDENCIES) + explicit MissingDependencies(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) + : RStatus(MISSING_DEPENDENCIES, upperProxy, statusMtx, updateMtx) { } @@ -145,43 +180,60 @@ class MissingDependencies : public RStatus { class StandBy : public RStatus { public: - explicit StandBy() - : RStatus(STAND_BY) + explicit StandBy(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) + : RStatus(STAND_BY, upperProxy, statusMtx, updateMtx) { } }; class Running : public RStatus { public: - explicit Running() - : RStatus(RUNNING) + explicit Running(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) + : RStatus(RUNNING, upperProxy, statusMtx, updateMtx) { } - + void somethingIsMissing() override; }; class Stopped : public RStatus { public: - explicit Stopped() - : RStatus(STOPPED) + explicit Stopped(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) + : RStatus(STOPPED, upperProxy, statusMtx, updateMtx) { } }; class Finished : public RStatus { public: - explicit Finished() - : RStatus(FINISHED) + explicit Finished(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) + : RStatus(FINISHED, upperProxy, statusMtx, updateMtx) { } }; class Proxy : public ServiceProxy { + friend class MissingDependencies; + friend class StandBy; + friend class Running; + friend class Stopped; + friend class Finished; + protected: std::thread m_thread; + RStatus* m_status; + std::mutex m_updateMtx; + + void serviceCycle() override; + void autoUpdate() override; + void changeState(Status::stateT newState) override; + auto checkState() -> Status::stateT; void weave(); void cut(); + Proxy(IService& realService, std::map depsMap); + ~Proxy(); +public: + auto reportStatus()-> nlohmann::json override; }; } // namespace routineService From fed06fb92459a0128697a1b00616c79e2a0b2d4b Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Tue, 26 Oct 2021 20:21:40 -0300 Subject: [PATCH 079/147] ServiceProxy: Fixing bugs, leak errors, etc... --- src/classes/service-proxy/service-proxy.cpp | 30 +++++++------- src/classes/service-proxy/service-proxy.hpp | 43 ++++++++++++++------- 2 files changed, 43 insertions(+), 30 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index 5fd7743..2dfaedf 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -13,7 +13,10 @@ ServiceProxy::ProxyConfigs::ProxyConfigs(std::map d for (itr = depsMap.begin(); itr != depsMap.end(); itr++) { - m_depsMap.emplace(itr->first, Dependencie(itr->second, Status::UNKNOWN)); + //m_depsMap.emplace(itr->first, Dependencie(itr->second, Status::UNKNOWN)); + m_depsMap.emplace(std::piecewise_construct, + std::forward_as_tuple(itr->first), + std::forward_as_tuple(itr->second, Status::UNKNOWN)); } } @@ -34,7 +37,6 @@ void staticService::MissingDependencies::allFine() m_upperProxy->changeState(newState); } - // Uninitialized and StandBy Constructor will expose the endpoint on the DBUS void staticService::Uninitialized::somethingIsMissing() @@ -52,6 +54,7 @@ void staticService::StandBy::somethingIsMissing() staticService::Proxy::Proxy(IService& realService, std::map depsMap) : ServiceProxy(realService, STATIC_SERVICE, depsMap) { + changeState(Status::MISSING_DEPENDENCIES); autoUpdate(); } @@ -85,7 +88,7 @@ void staticService::Proxy::serviceCycle() void staticService::Proxy::changeState(Status::stateT newState) { - const std::lock_guard lock(m_statusMtx); + const std::lock_guard lock(m_statusMtx); switch (newState) { case Status::MISSING_DEPENDENCIES: @@ -124,16 +127,10 @@ auto staticService::Proxy::reportStatus() -> nlohmann::json return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; } - - - - - - - routineService::Proxy::Proxy(IService& realService, std::map depsMap) : ServiceProxy(realService, ROUTINE_SERVICE, depsMap) { + changeState(Status::MISSING_DEPENDENCIES); autoUpdate(); } @@ -142,7 +139,6 @@ routineService::Proxy::~Proxy() delete m_status; } - void routineService::MissingDependencies::allFine() { // Expose/Hide the endpoint on the DBUS and THEN.. @@ -190,20 +186,20 @@ void routineService::Proxy::autoUpdate() { bool noMissingDependencies = true; - std::map::iterator itr; + std::map::iterator itr; - for (itr = m_proxyConfigs.m_depsMap.begin(); itr != m_proxyConfigs.m_depsMap.end(); itr++) { - if (itr->second.m_currState != itr->second.m_reqrState) { - noMissingDependencies = false; - } + for (itr = m_proxyConfigs.m_depsMap.begin(); itr != m_proxyConfigs.m_depsMap.end(); itr++) { + if (itr->second.m_currState != itr->second.m_reqrState) { + noMissingDependencies = false; } + } (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); } void routineService::Proxy::changeState(Status::stateT newState) { - const std::lock_guard lock(m_statusMtx); + const std::lock_guard lock(m_statusMtx); switch (newState) { case Status::MISSING_DEPENDENCIES: diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index f8f1170..6ff6a71 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -25,7 +25,8 @@ class Status { virtual void allFine() { } auto getState() -> stateT; Status(stateT state, std::mutex* const statusMtx) - : m_state(state), m_statusMtx(statusMtx) + : m_state(state) + , m_statusMtx(statusMtx) { } }; @@ -58,22 +59,33 @@ class ServiceProxy { proxyT m_proxyType; std::mutex m_statusMtx; + +public://temporary ProxyConfigs m_proxyConfigs; +protected: std::string m_realServiceId; IService& m_realService; - virtual void serviceCycle() { } virtual void changeState(Status::stateT newState) { } + +public://temporary virtual void autoUpdate() { } + virtual void serviceCycle() { } + +protected: + +public: virtual auto reportStatus() -> nlohmann::json { return { {} }; } ServiceProxy(IService& realService, proxyT proxyType, std::map depsMap) : m_realService(realService) , m_proxyType(proxyType) - , m_proxyConfigs(depsMap), - m_realServiceId(realService.m_serviceId) + , m_proxyConfigs(depsMap) + , m_realServiceId(realService.m_serviceId) { } + + virtual ~ServiceProxy() = default; }; namespace staticService { @@ -137,16 +149,19 @@ class Proxy : public ServiceProxy { protected: bool m_runnedOnce; SStatus* m_status; + void changeState(Status::stateT newState) override; +public: void serviceCycle() override; +protected: void autoUpdate() override; auto checkState() -> Status::stateT; - Proxy(IService& realService, std::map depsMap); - ~Proxy(); - public: - auto reportStatus()-> nlohmann::json override; + Proxy(IService& realService, std::map depsMap); + ~Proxy() override; + + auto reportStatus() -> nlohmann::json override; void execute() { serviceCycle(); } // Temporary!!! }; } // namespace staticService @@ -161,8 +176,8 @@ class RStatus : public Status { Proxy* const m_upperProxy; RStatus(stateT state, Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) - : m_upperProxy(upperProxy), - m_updateMtx(updateMtx) + : m_upperProxy(upperProxy) + , m_updateMtx(updateMtx) , Status(state, statusMtx) { } @@ -230,10 +245,12 @@ class Proxy : public ServiceProxy { auto checkState() -> Status::stateT; void weave(); void cut(); - Proxy(IService& realService, std::map depsMap); - ~Proxy(); + public: - auto reportStatus()-> nlohmann::json override; + Proxy(IService& realService, std::map depsMap); + ~Proxy() override; + + auto reportStatus() -> nlohmann::json override; }; } // namespace routineService From 1740a1c8d3341344022d3e079f35b982dd83a38f Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Tue, 26 Oct 2021 20:22:44 -0300 Subject: [PATCH 080/147] ServiceHandler: Refactoring to combine with the new ServiceProxys --- .../service-handler/service-handler.cpp | 39 ++++++++++++------- .../service-handler/service-handler.hpp | 7 ++-- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index 0d722f9..8fa5a6e 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -1,37 +1,48 @@ #include "service-handler.hpp" -// -// void buildServiceProxy(IService& userService); -// explicit ServiceHandler(nlohmann::json servicesConfigs); - ServiceHandler::ServiceHandler(nlohmann::json servicesConfigs) - : m_servicesConfigs(servicesConfigs) - { + //JSON DE CONFIGS + for (nlohmann::json::iterator it = servicesConfigs["proxys"].begin(); it != servicesConfigs["proxys"].end(); it++) { + std::map depsMap; + + for (nlohmann::json::iterator itr = it.value().begin(); itr != it.value().end(); itr++) { + depsMap.insert(std::pair(itr.key(), itr.value())); + } + m_proxyDepsMap.insert(std::pair>(it.key(), depsMap)); + } } -void ServiceHandler::buildServiceProxy(IService& userService) +void ServiceHandler::buildServiceProxy(IService& userService, ServiceProxy::proxyT proxyType) { + if (proxyType == ServiceProxy::STATIC_SERVICE) { + m_serviceMap.insert(std::pair(userService.m_serviceId, new staticService::Proxy(userService, m_proxyDepsMap.at(userService.m_serviceId)))); - m_serviceMap.emplace(std::piecewise_construct, - std::forward_as_tuple(userService.m_serviceId), - std::forward_as_tuple(userService, m_servicesConfigs)); + } else { + m_serviceMap.insert(std::pair(userService.m_serviceId, new routineService::Proxy(userService, m_proxyDepsMap.at(userService.m_serviceId)))); + } } auto ServiceHandler::getProxyStatus(std::string serviceId) -> nlohmann::json { - nlohmann::json requiredStatus = m_serviceMap.at(serviceId).getStatus(); + nlohmann::json requiredStatus = m_serviceMap.at(serviceId)->reportStatus(); return requiredStatus; } auto ServiceHandler::getAllProxyStatus() -> nlohmann::json { - std::map::iterator itr; + std::map::iterator itr; nlohmann::json allStatus; - for(itr = m_serviceMap.begin(); itr != m_serviceMap.end(); itr++) { - allStatus[itr->first] = itr->second.getStatus(); + for (itr = m_serviceMap.begin(); itr != m_serviceMap.end(); itr++) { + allStatus[itr->first] = itr->second->reportStatus(); } return allStatus; } +ServiceHandler::~ServiceHandler() { + std::map::iterator itr; + for (itr = m_serviceMap.begin(); itr != m_serviceMap.end(); itr++) { + delete itr->second; + } +} diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index 6ff338a..ac7cf29 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -8,14 +8,15 @@ class ServiceHandler { //private: public: - std::map m_serviceMap; - nlohmann::json m_servicesConfigs; + std::map m_serviceMap; + std::map> m_proxyDepsMap; public: auto getProxyStatus(std::string serviceId) -> nlohmann::json; auto getAllProxyStatus() -> nlohmann::json; - void buildServiceProxy(IService& userService); + void buildServiceProxy(IService& userService, ServiceProxy::proxyT proxyType); explicit ServiceHandler(nlohmann::json servicesConfigs); + ~ServiceHandler(); }; From ba671c47bcaff8f7d8196993637ed27c9a894052 Mon Sep 17 00:00:00 2001 From: CarlosCraveiro Date: Tue, 26 Oct 2021 22:21:06 -0300 Subject: [PATCH 081/147] IService: fixing override bug --- src/classes/service/service.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/classes/service/service.hpp b/src/classes/service/service.hpp index ceea973..73bae2f 100644 --- a/src/classes/service/service.hpp +++ b/src/classes/service/service.hpp @@ -2,7 +2,7 @@ #pragma once #include #include - +#include class IService { public: /* Id of the service */ @@ -26,7 +26,7 @@ class IService { * this function is going to run in a loop, so its * instructions are going to be executed "routinely". */ - void routine() { } + virtual void routine() {} /** * @brief An interface function to be implemented by From 3e1c20cf6a1d0e122b32cd3c14eec6218312747f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ADra=20Canal?= <61601791+mairacanal@users.noreply.github.com> Date: Thu, 28 Oct 2021 19:53:24 -0300 Subject: [PATCH 082/147] readme: changing project's name to "Frameword" --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 65f9ac5..4078aaf 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

Daemons Framework

+

Frameworkd

A framework for creating daemons in our architecture

From 259dcb9413adfee9df66e56d3af8ff53547a78d5 Mon Sep 17 00:00:00 2001 From: Carlos Henrique Craveiro Aquino Veras Date: Sat, 6 Nov 2021 16:06:09 -0300 Subject: [PATCH 083/147] IService: renames directory and erases empty .cpp Due to the fact that "IService" is just a interface it doesn't need a .ccp file, also the directory "service/" and the file "service.hpp" were renamed to have the same name of "IService". --- src/classes/{service/service.hpp => iservice/iservice.hpp} | 0 src/classes/service/service.cpp | 3 --- 2 files changed, 3 deletions(-) rename src/classes/{service/service.hpp => iservice/iservice.hpp} (100%) delete mode 100644 src/classes/service/service.cpp diff --git a/src/classes/service/service.hpp b/src/classes/iservice/iservice.hpp similarity index 100% rename from src/classes/service/service.hpp rename to src/classes/iservice/iservice.hpp diff --git a/src/classes/service/service.cpp b/src/classes/service/service.cpp deleted file mode 100644 index bdc179b..0000000 --- a/src/classes/service/service.cpp +++ /dev/null @@ -1,3 +0,0 @@ - -#include "service.hpp" - From f4619c22c87e047e9a3c739b7d2132708353bea8 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 8 Nov 2021 03:02:00 -0300 Subject: [PATCH 084/147] StaticService & RoutineService: creates both Creates the classes StaticService and RoutineService in file iservice.hpp, both were inherited from iservice, located in the same file. The idea is to allow function overloading on the method "deploy" at the daemon class, when the user decides to choose between the two options. --- src/classes/iservice/iservice.hpp | 47 ++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/src/classes/iservice/iservice.hpp b/src/classes/iservice/iservice.hpp index 73bae2f..46f2d4c 100644 --- a/src/classes/iservice/iservice.hpp +++ b/src/classes/iservice/iservice.hpp @@ -1,21 +1,20 @@ #pragma once -#include -#include #include +#include class IService { public: /* Id of the service */ std::string m_serviceId; protected: -// DBusHandler::DBusHandler m_dbus; + // DBusHandler::DBusHandler m_dbus; public: /** * @brief An interface function to be implemented by - * the user to make the "setup"/configuration - * of its class' parameter-members. + * the user to make the "setup"/configuration + * of its class' parameter-members. */ virtual void setup() = 0; @@ -26,21 +25,21 @@ class IService { * this function is going to run in a loop, so its * instructions are going to be executed "routinely". */ - virtual void routine() {} + virtual void routine() = 0; /** - * @brief An interface function to be implemented by - * the user to execute the needed instructions - * to safely "destroy" the resources used by the - * class' previous functions. + * @brief An interface function to be implemented by + * the user to execute the needed instructions + * to safely "destroy" the resources used by the + * class' previous functions. */ virtual void destroy() = 0; /** * @brief The constructor of this interface. * - * @param serviceId std::string that is the id related - * to the instantiated class. + * @param serviceId std::string that is the id related + * to the instantiated class. */ explicit IService(std::string serviceId) @@ -50,8 +49,30 @@ class IService { /** * @brief A virtual destructor to ensure - * inheriance compatibility. + * inheritance compatibility. */ virtual ~IService() = default; }; +class StaticService : public IService { +public: + explicit StaticService(std::string serviceId) + : IService(serviceId) + { + } + + void routine() final { } + + ~StaticService() override = default; +}; + +class RoutineService : public IService { +public: + explicit RoutineService(std::string serviceId) + : IService(serviceId) + { + } + + ~RoutineService() override = default; +}; + From 636ba83849ab9a085337f43a227b0b8981fa75ac Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 8 Nov 2021 03:11:29 -0300 Subject: [PATCH 085/147] ServiceProxy: splits the class and ties up loose ends This commit will be followed by other two, because the gigantic file service-proxy.hpp and its .cpp was cut each one in three. Basically the classes staticService::Proxy and routineService::Proxy and their states now exists in their own files. The staticService::Proxy now is StaticServiceProxy and routineService::Proxy RoutineServiceProxy, the external namespaces was erased and now the states uses the namespace of their own classes. Besides these changes, the new sliced files had their "loose ends" tied up, with "loose ends" meaning the several "public", "protected" tags that haunted the three classes before, despises the other several "//Temporary!" comments which made the life of code reviewers an endless nightmare. The solution for all these problems came from turning the inherited proxys friends of ServiceHandler, and those friends of an test class that I uses as an "unit test" class, so I could test the features without spreading MacGyvers through the classes. --- src/classes/service-proxy/service-proxy.cpp | 233 +------------------ src/classes/service-proxy/service-proxy.hpp | 243 +++----------------- 2 files changed, 41 insertions(+), 435 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index 2dfaedf..5b73a9e 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -1,243 +1,22 @@ #include "service-proxy.hpp" #include -#include -auto Status::getState() -> Status::stateT +auto ServiceProxy::ServiceState::getState() const -> stateT { return m_state; } -ServiceProxy::ProxyConfigs::ProxyConfigs(std::map depsMap) +ServiceProxy::ProxyConfigs::ProxyConfigs(std::map depsMap) { - std::map::iterator itr; - - for (itr = depsMap.begin(); itr != depsMap.end(); itr++) { - - //m_depsMap.emplace(itr->first, Dependencie(itr->second, Status::UNKNOWN)); + for (auto& [depId, depReqState] : depsMap) { m_depsMap.emplace(std::piecewise_construct, - std::forward_as_tuple(itr->first), - std::forward_as_tuple(itr->second, Status::UNKNOWN)); + std::forward_as_tuple(depId), + std::forward_as_tuple(depReqState, ServiceState::UNKNOWN)); } } -void ServiceProxy::ProxyConfigs::changeDep(std::string dependencieId, Status::stateT currState) +void ServiceProxy::ProxyConfigs::changeDep(std::string dependencieId, ServiceState::stateT currState) { m_depsMap[dependencieId].m_currState = currState; } -void staticService::MissingDependencies::allFine() -{ - - stateT newState = UNINITIALIZED; - if (m_upperProxy->m_runnedOnce) { - - newState = STAND_BY; - } - - m_upperProxy->changeState(newState); -} - -// Uninitialized and StandBy Constructor will expose the endpoint on the DBUS - -void staticService::Uninitialized::somethingIsMissing() -{ - // Unexpose/Hide the endpoint on the DBUS and THEN.. - m_upperProxy->changeState(MISSING_DEPENDENCIES); -} - -void staticService::StandBy::somethingIsMissing() -{ - // Unexpose/Hide the endpoint on the DBUS and THEN... - m_upperProxy->changeState(MISSING_DEPENDENCIES); -} - -staticService::Proxy::Proxy(IService& realService, std::map depsMap) - : ServiceProxy(realService, STATIC_SERVICE, depsMap) -{ - changeState(Status::MISSING_DEPENDENCIES); - autoUpdate(); -} - -staticService::Proxy::~Proxy() -{ - delete m_status; -} - -void staticService::Proxy::autoUpdate() -{ - bool noMissingDependencies = true; - - std::map::iterator itr; - - for (itr = m_proxyConfigs.m_depsMap.begin(); itr != m_proxyConfigs.m_depsMap.end(); itr++) { - if (itr->second.m_currState != itr->second.m_reqrState) { - noMissingDependencies = false; - } - } - - (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); -} - -void staticService::Proxy::serviceCycle() -{ - changeState(Status::RUNNING); - m_realService.setup(); - m_realService.destroy(); - changeState(Status::STAND_BY); -} - -void staticService::Proxy::changeState(Status::stateT newState) -{ - const std::lock_guard lock(m_statusMtx); - - switch (newState) { - case Status::MISSING_DEPENDENCIES: - delete m_status; - m_status = new MissingDependencies(this, &m_statusMtx); - break; - case Status::UNINITIALIZED: - delete m_status; - m_status = new Uninitialized(this, &m_statusMtx); - break; - case Status::RUNNING: - delete m_status; - m_status = new Running(this, &m_statusMtx); - break; - case Status::STAND_BY: - delete m_status; - m_status = new StandBy(this, &m_statusMtx); - break; - case Status::STOPPED: - case Status::UNKNOWN: - case Status::FINISHED: - std::cout << "ERROR!! This was not supose to happen!! - Static Service" << std::endl; - }; -} - -auto staticService::Proxy::checkState() -> Status::stateT -{ - const std::lock_guard lock(m_statusMtx); - return m_status->getState(); -} - -auto staticService::Proxy::reportStatus() -> nlohmann::json -{ - Status::stateT currStatus = checkState(); - - return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; -} - -routineService::Proxy::Proxy(IService& realService, std::map depsMap) - : ServiceProxy(realService, ROUTINE_SERVICE, depsMap) -{ - changeState(Status::MISSING_DEPENDENCIES); - autoUpdate(); -} - -routineService::Proxy::~Proxy() -{ - delete m_status; -} - -void routineService::MissingDependencies::allFine() -{ - // Expose/Hide the endpoint on the DBUS and THEN.. - m_upperProxy->weave(); -} - -void routineService::Running::somethingIsMissing() -{ - // Unexpose/Hide the endpoint on the DBUS and THEN.. - m_upperProxy->cut(); -} - -void routineService::Proxy::serviceCycle() -{ - changeState(Status::RUNNING); - m_realService.setup(); - - while (checkState() != Status::STOPPED) { - - m_realService.routine(); - } - - m_realService.destroy(); - - changeState(Status::FINISHED); -} - -void routineService::Proxy::weave() -{ - const std::lock_guard lock(m_updateMtx); - changeState(Status::STAND_BY); - std::thread thread(&routineService::Proxy::serviceCycle, this); - std::swap(thread, m_thread); -} - -void routineService::Proxy::cut() -{ - const std::lock_guard lock(m_updateMtx); - changeState(Status::STOPPED); - m_thread.join(); - changeState(Status::MISSING_DEPENDENCIES); -} - -void routineService::Proxy::autoUpdate() -{ - bool noMissingDependencies = true; - - std::map::iterator itr; - - for (itr = m_proxyConfigs.m_depsMap.begin(); itr != m_proxyConfigs.m_depsMap.end(); itr++) { - if (itr->second.m_currState != itr->second.m_reqrState) { - noMissingDependencies = false; - } - } - - (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); -} - -void routineService::Proxy::changeState(Status::stateT newState) -{ - const std::lock_guard lock(m_statusMtx); - - switch (newState) { - case Status::MISSING_DEPENDENCIES: - delete m_status; - m_status = new MissingDependencies(this, &m_statusMtx, &m_updateMtx); - break; - case Status::RUNNING: - delete m_status; - m_status = new Running(this, &m_statusMtx, &m_updateMtx); - break; - case Status::STAND_BY: - delete m_status; - m_status = new StandBy(this, &m_statusMtx, &m_updateMtx); - break; - case Status::STOPPED: - delete m_status; - m_status = new Stopped(this, &m_statusMtx, &m_updateMtx); - break; - case Status::FINISHED: - delete m_status; - m_status = new Finished(this, &m_statusMtx, &m_updateMtx); - break; - case Status::UNINITIALIZED: - case Status::UNKNOWN: - std::cout << "ERROR!! This was not supose to happen!! - Routine Service" << std::endl; - }; -} - -auto routineService::Proxy::checkState() -> Status::stateT -{ - const std::lock_guard lock(m_statusMtx); - return m_status->getState(); -} - -auto routineService::Proxy::reportStatus() -> nlohmann::json -{ - Status::stateT currStatus = checkState(); - - return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; -} - diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index 6ff6a71..a002b77 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -1,48 +1,48 @@ #pragma once -#include "../service/service.hpp" +#include "../iservice/iservice.hpp" #include #include #include #include -class ServiceProxy; - -class Status { -public: - enum stateT { MISSING_DEPENDENCIES = 0, - UNINITIALIZED, - RUNNING, - STOPPED, - FINISHED, - STAND_BY, - UNKNOWN }; - +class ServiceProxy { protected: - const stateT m_state; - std::mutex* const m_statusMtx; - virtual void somethingIsMissing() { } - virtual void allFine() { } - auto getState() -> stateT; - Status(stateT state, std::mutex* const statusMtx) - : m_state(state) - , m_statusMtx(statusMtx) - { - } -}; + friend class ServiceHandler; + friend class Tester; -class ServiceProxy { -public: enum proxyT { STATIC_SERVICE = 0, ROUTINE_SERVICE }; -protected: + class ServiceState { + public: + enum stateT { MISSING_DEPENDENCIES = 0, + UNINITIALIZED, + RUNNING, + STOPPED, + FINISHED, + STAND_BY, + UNKNOWN }; + + // protected: + const stateT m_state; + + virtual void somethingIsMissing() { } + virtual void allFine() { } + [[nodiscard]] auto getState() const -> stateT; + + explicit ServiceState(stateT state) + : m_state(state) + { + } + }; + class ProxyConfigs { public: struct Dependencie { - Status::stateT m_reqrState; - Status::stateT m_currState; - Dependencie(Status::stateT reqrState, Status::stateT currState) + ServiceState::stateT m_reqrState; + ServiceState::stateT m_currState; + Dependencie(ServiceState::stateT reqrState, ServiceState::stateT currState) : m_reqrState(reqrState) , m_currState(currState) { @@ -53,31 +53,24 @@ class ServiceProxy { std::map m_depsMap; - void changeDep(std::string dependencieId, Status::stateT currState); - explicit ProxyConfigs(std::map depsMap); + void changeDep(std::string dependencieId, ServiceState::stateT currState); + explicit ProxyConfigs(std::map depsMap); }; proxyT m_proxyType; std::mutex m_statusMtx; - -public://temporary ProxyConfigs m_proxyConfigs; -protected: std::string m_realServiceId; IService& m_realService; - virtual void changeState(Status::stateT newState) { } - -public://temporary + virtual void changeState(ServiceState::stateT newState) { } virtual void autoUpdate() { } virtual void serviceCycle() { } -protected: - public: - virtual auto reportStatus() -> nlohmann::json { return { {} }; } + virtual auto reportState() -> nlohmann::json { return { {} }; } - ServiceProxy(IService& realService, proxyT proxyType, std::map depsMap) + ServiceProxy(IService& realService, proxyT proxyType, std::map depsMap) : m_realService(realService) , m_proxyType(proxyType) , m_proxyConfigs(depsMap) @@ -88,169 +81,3 @@ class ServiceProxy { virtual ~ServiceProxy() = default; }; -namespace staticService { -class Proxy; - -class SStatus : public Status { - friend class Proxy; - -protected: - Proxy* const m_upperProxy; - -public: - SStatus(stateT state, Proxy* const upperProxy, std::mutex* const statusMtx) - : Status(state, statusMtx) - , m_upperProxy(upperProxy) - { - } -}; - -class MissingDependencies : public SStatus { -public: - explicit MissingDependencies(Proxy* const upperProxy, std::mutex* const statusMtx) - : SStatus(MISSING_DEPENDENCIES, upperProxy, statusMtx) - { - } - void allFine() override; -}; - -class Uninitialized : public SStatus { -public: - explicit Uninitialized(Proxy* const upperProxy, std::mutex* const statusMtx) - : SStatus(UNINITIALIZED, upperProxy, statusMtx) - { - } - void somethingIsMissing() override; -}; - -class Running : public SStatus { -public: - explicit Running(Proxy* const upperProxy, std::mutex* const statusMtx) - : SStatus(RUNNING, upperProxy, statusMtx) - { - } -}; - -class StandBy : public SStatus { -public: - explicit StandBy(Proxy* const upperProxy, std::mutex* const statusMtx) - : SStatus(STAND_BY, upperProxy, statusMtx) - { - } - void somethingIsMissing() override; -}; - -class Proxy : public ServiceProxy { - friend class MissingDependencies; - friend class Uninitialized; - friend class Running; - friend class StandBy; - -protected: - bool m_runnedOnce; - SStatus* m_status; - - void changeState(Status::stateT newState) override; -public: - void serviceCycle() override; -protected: - void autoUpdate() override; - auto checkState() -> Status::stateT; - -public: - Proxy(IService& realService, std::map depsMap); - ~Proxy() override; - - auto reportStatus() -> nlohmann::json override; - void execute() { serviceCycle(); } // Temporary!!! -}; -} // namespace staticService - -namespace routineService { -class Proxy; -class RStatus : public Status { - friend class Proxy; - -public: - std::mutex* const m_updateMtx; - Proxy* const m_upperProxy; - - RStatus(stateT state, Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) - : m_upperProxy(upperProxy) - , m_updateMtx(updateMtx) - , Status(state, statusMtx) - { - } -}; - -class MissingDependencies : public RStatus { -public: - explicit MissingDependencies(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) - : RStatus(MISSING_DEPENDENCIES, upperProxy, statusMtx, updateMtx) - { - } - - void allFine() override; -}; - -class StandBy : public RStatus { -public: - explicit StandBy(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) - : RStatus(STAND_BY, upperProxy, statusMtx, updateMtx) - { - } -}; - -class Running : public RStatus { -public: - explicit Running(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) - : RStatus(RUNNING, upperProxy, statusMtx, updateMtx) - { - } - - void somethingIsMissing() override; -}; - -class Stopped : public RStatus { -public: - explicit Stopped(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) - : RStatus(STOPPED, upperProxy, statusMtx, updateMtx) - { - } -}; - -class Finished : public RStatus { -public: - explicit Finished(Proxy* const upperProxy, std::mutex* const statusMtx, std::mutex* const updateMtx) - : RStatus(FINISHED, upperProxy, statusMtx, updateMtx) - { - } -}; - -class Proxy : public ServiceProxy { - friend class MissingDependencies; - friend class StandBy; - friend class Running; - friend class Stopped; - friend class Finished; - -protected: - std::thread m_thread; - RStatus* m_status; - std::mutex m_updateMtx; - - void serviceCycle() override; - void autoUpdate() override; - void changeState(Status::stateT newState) override; - auto checkState() -> Status::stateT; - void weave(); - void cut(); - -public: - Proxy(IService& realService, std::map depsMap); - ~Proxy() override; - - auto reportStatus() -> nlohmann::json override; -}; -} // namespace routineService - From fb14dcf945614ddcd9463f00abbfa3d86e3067bf Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 8 Nov 2021 04:13:03 -0300 Subject: [PATCH 086/147] RoutineServiceProxy: creates the class This commits adds the files routine-service-proxy.hpp and its .cpp with the declaration and definition of the class RoutineServiceProxy and its states. Just to be more explicit, RoutineServiceProxy is the old routineService::Proxy class with some improvements. Some of news are the adoption of modern iterators (range based "fors") "for(auto& [key, value] : thingtobeiterated)" and the adoption of smart pointers. --- .../routine-service-proxy.cpp | 102 ++++++++++++++++++ .../routine-service-proxy.hpp | 83 ++++++++++++++ 2 files changed, 185 insertions(+) create mode 100644 src/classes/routine-service-proxy/routine-service-proxy.cpp create mode 100644 src/classes/routine-service-proxy/routine-service-proxy.hpp diff --git a/src/classes/routine-service-proxy/routine-service-proxy.cpp b/src/classes/routine-service-proxy/routine-service-proxy.cpp new file mode 100644 index 0000000..3257007 --- /dev/null +++ b/src/classes/routine-service-proxy/routine-service-proxy.cpp @@ -0,0 +1,102 @@ +#include "routine-service-proxy.hpp" + +RoutineServiceProxy::RoutineServiceProxy(IService& realService, std::map depsMap) + : ServiceProxy(realService, ROUTINE_SERVICE, depsMap) +{ + changeState(RoutineState::MISSING_DEPENDENCIES); +} + +void RoutineServiceProxy::MissingDependencies::allFine() +{ + // Expose/Hide the endpoint on the DBUS and THEN.. + m_upperProxy.weave(); +} + +void RoutineServiceProxy::Running::somethingIsMissing() +{ + // Unexpose/Hide the endpoint on the DBUS and THEN.. + m_upperProxy.cut(); +} + +void RoutineServiceProxy::serviceCycle() +{ + changeState(RoutineState::RUNNING); + m_realService.setup(); + + while (checkState() != RoutineState::STOPPED) { + + m_realService.routine(); + } + + m_realService.destroy(); + + changeState(RoutineState::FINISHED); +} + +void RoutineServiceProxy::weave() +{ + const std::lock_guard lock(m_updateMtx); + changeState(RoutineState::STAND_BY); + std::thread thread(&RoutineServiceProxy::serviceCycle, this); + std::swap(thread, m_thread); +} + +void RoutineServiceProxy::cut() +{ + const std::lock_guard lock(m_updateMtx); + changeState(RoutineState::STOPPED); + m_thread.join(); + changeState(RoutineState::MISSING_DEPENDENCIES); +} + +void RoutineServiceProxy::autoUpdate() +{ + bool noMissingDependencies = true; + + for (auto& [depId, dependency] : m_proxyConfigs.m_depsMap) { + if (dependency.m_currState != dependency.m_reqrState) { + noMissingDependencies = false; + } + } + + (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); +} + +void RoutineServiceProxy::changeState(RoutineState::stateT newState) +{ + const std::lock_guard lock(m_statusMtx); + + switch (newState) { + case RoutineState::MISSING_DEPENDENCIES: + m_status = std::make_unique(*this); + break; + case RoutineState::RUNNING: + m_status = std::make_unique(*this); + break; + case RoutineState::STAND_BY: + m_status = std::make_unique(*this); + break; + case RoutineState::STOPPED: + m_status = std::make_unique(*this); + break; + case RoutineState::FINISHED: + m_status = std::make_unique(*this); + break; + default: + std::cout << "ERROR!! This was not supose to happen!! - Routine Service" << std::endl; + } +} + +auto RoutineServiceProxy::checkState() -> RoutineState::stateT +{ + const std::lock_guard lock(m_statusMtx); + return m_status->getState(); +} + +auto RoutineServiceProxy::reportState() -> nlohmann::json +{ + RoutineState::stateT currStatus = checkState(); + + return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; +} + diff --git a/src/classes/routine-service-proxy/routine-service-proxy.hpp b/src/classes/routine-service-proxy/routine-service-proxy.hpp new file mode 100644 index 0000000..862ad1b --- /dev/null +++ b/src/classes/routine-service-proxy/routine-service-proxy.hpp @@ -0,0 +1,83 @@ +#pragma once +#include "../service-proxy/service-proxy.hpp" +#include + +class RoutineServiceProxy : public ServiceProxy { +protected: + friend class ServiceHandler; + friend class Tester; + + class RoutineState : public ServiceState { + + public: + RoutineServiceProxy& m_upperProxy; + + RoutineState(stateT state, RoutineServiceProxy& upperProxy) + : m_upperProxy(upperProxy) + , ServiceState(state) + { + } + }; + + class MissingDependencies : public RoutineState { + public: + explicit MissingDependencies(RoutineServiceProxy& upperProxy) + : RoutineState(MISSING_DEPENDENCIES, upperProxy) + { + } + + void allFine() override; + }; + + class StandBy : public RoutineState { + public: + explicit StandBy(RoutineServiceProxy& upperProxy) + : RoutineState(STAND_BY, upperProxy) + { + } + }; + + class Running : public RoutineState { + public: + explicit Running(RoutineServiceProxy& upperProxy) + : RoutineState(RUNNING, upperProxy) + { + } + + void somethingIsMissing() override; + }; + + class Stopped : public RoutineState { + public: + explicit Stopped(RoutineServiceProxy& upperProxy) + : RoutineState(STOPPED, upperProxy) + { + } + }; + + class Finished : public RoutineState { + public: + explicit Finished(RoutineServiceProxy& upperProxy) + : RoutineState(FINISHED, upperProxy) + { + } + }; + + std::thread m_thread; + std::unique_ptr m_status; + std::mutex m_updateMtx; + + void serviceCycle() override; + void autoUpdate() override; + void changeState(ServiceState::stateT newState) override; + auto checkState() -> ServiceState::stateT; + void weave(); + void cut(); + +public: + RoutineServiceProxy(IService& realService, std::map depsMap); + ~RoutineServiceProxy() override = default; + + auto reportState() -> nlohmann::json override; +}; + From 5767af19bf147ba19d21589ac1d5e8dd7f6e2dd1 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 8 Nov 2021 04:22:27 -0300 Subject: [PATCH 087/147] StaticServiceProxy: creates the class This commits adds the files static-service-proxy.hpp and its .cpp with the declaration and definition of the class StaticServiceProxy and its states. Just to be more explicit, StaticServiceProxy is the old staticService::Proxy class with some improvements. Some of news are the adoption of modern iterators (range based "fors") "for(auto& [key, value] : thingToBeIterated)" and the adoption of smart pointers. --- .../static-service-proxy.cpp | 85 +++++++++++++++++++ .../static-service-proxy.hpp | 71 ++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 src/classes/static-service-proxy/static-service-proxy.cpp create mode 100644 src/classes/static-service-proxy/static-service-proxy.hpp diff --git a/src/classes/static-service-proxy/static-service-proxy.cpp b/src/classes/static-service-proxy/static-service-proxy.cpp new file mode 100644 index 0000000..8ba42b8 --- /dev/null +++ b/src/classes/static-service-proxy/static-service-proxy.cpp @@ -0,0 +1,85 @@ +#include "static-service-proxy.hpp" + +void StaticServiceProxy::MissingDependencies::allFine() +{ + stateT newState = (m_upperProxy.m_runnedOnce) ? STAND_BY : UNINITIALIZED; + + m_upperProxy.changeState(newState); +} + +// Uninitialized and StandBy Constructor will expose the endpoint on the DBUS + +void StaticServiceProxy::Uninitialized::somethingIsMissing() +{ + // Unexpose/Hide the endpoint on the DBUS and THEN.. + m_upperProxy.changeState(MISSING_DEPENDENCIES); +} + +void StaticServiceProxy::StandBy::somethingIsMissing() +{ + // Unexpose/Hide the endpoint on the DBUS and THEN... + m_upperProxy.changeState(MISSING_DEPENDENCIES); +} + +StaticServiceProxy::StaticServiceProxy(IService& realService, std::map depsMap) + : m_runnedOnce(false) + , ServiceProxy(realService, STATIC_SERVICE, depsMap) +{ + changeState(ServiceState::MISSING_DEPENDENCIES); +} + +void StaticServiceProxy::StaticServiceProxy::autoUpdate() +{ + bool noMissingDependencies = true; + + for (auto& [depId, dependency] : m_proxyConfigs.m_depsMap) { + if (dependency.m_currState != dependency.m_reqrState) { + noMissingDependencies = false; + } + } + + (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); +} + +void StaticServiceProxy::StaticServiceProxy::serviceCycle() +{ + changeState(ServiceState::RUNNING); + m_realService.setup(); + m_realService.destroy(); + changeState(ServiceState::STAND_BY); +} + +void StaticServiceProxy::StaticServiceProxy::changeState(ServiceState::stateT newState) +{ + const std::lock_guard lock(m_statusMtx); + + switch (newState) { + case ServiceState::MISSING_DEPENDENCIES: + m_status = std::make_unique(*this); + break; + case ServiceState::UNINITIALIZED: + m_status = std::make_unique(*this); + break; + case ServiceState::RUNNING: + m_status = std::make_unique(*this); + break; + case ServiceState::STAND_BY: + m_status = std::make_unique(*this); + break; + default: + std::cout << "ERROR!! This was not supposed to happen!! - Static Service" << std::endl; + } +} + +auto StaticServiceProxy::StaticServiceProxy::checkState() -> ServiceState::stateT +{ + const std::lock_guard lock(m_statusMtx); + return m_status->getState(); +} + +auto StaticServiceProxy::StaticServiceProxy::reportState() -> nlohmann::json +{ + ServiceState::stateT currStatus = checkState(); + + return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; +} diff --git a/src/classes/static-service-proxy/static-service-proxy.hpp b/src/classes/static-service-proxy/static-service-proxy.hpp new file mode 100644 index 0000000..7956789 --- /dev/null +++ b/src/classes/static-service-proxy/static-service-proxy.hpp @@ -0,0 +1,71 @@ +#pragma once +#include "../service-proxy/service-proxy.hpp" +#include + +class StaticServiceProxy : public ServiceProxy { +protected: + friend class ServiceHandler; + friend class Tester; + + class StaticState : public ServiceState { + protected: + StaticServiceProxy& m_upperProxy; + + public: + StaticState(stateT state, StaticServiceProxy& upperProxy) + : ServiceState(state) + , m_upperProxy(upperProxy) + { + } + }; + + class MissingDependencies : public StaticState { + public: + explicit MissingDependencies(StaticServiceProxy& upperProxy) + : StaticState(MISSING_DEPENDENCIES, upperProxy) + { + } + void allFine() override; + }; + + class Uninitialized : public StaticState { + public: + explicit Uninitialized(StaticServiceProxy& upperProxy) + : StaticState(UNINITIALIZED, upperProxy) + { + } + void somethingIsMissing() override; + }; + + class Running : public StaticState { + public: + explicit Running(StaticServiceProxy& upperProxy) + : StaticState(RUNNING, upperProxy) + { + } + }; + + class StandBy : public StaticState { + public: + explicit StandBy(StaticServiceProxy& upperProxy) + : StaticState(STAND_BY, upperProxy) + { + } + void somethingIsMissing() override; + }; + + bool m_runnedOnce; + std::unique_ptr m_status; + + void changeState(ServiceState::stateT newState) override; + void serviceCycle() override; + void autoUpdate() override; + auto checkState() -> ServiceState::stateT; + +public: + StaticServiceProxy(IService& realService, std::map depsMap); + ~StaticServiceProxy() override = default; + + auto reportState() -> nlohmann::json override; +}; + From 0becd5655779520835ecf6026e751b76f2d9222a Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 8 Nov 2021 04:27:49 -0300 Subject: [PATCH 088/147] ServiceHandler: improves syntax and fits the changes Adoption of modern iterators for std::maps and smart-pointers, besides fitting the changes of the "Service Proxys" classes. --- .../service-handler/service-handler.cpp | 44 +++++++++---------- .../service-handler/service-handler.hpp | 19 ++++---- 2 files changed, 31 insertions(+), 32 deletions(-) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index 8fa5a6e..abd861f 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -2,47 +2,43 @@ ServiceHandler::ServiceHandler(nlohmann::json servicesConfigs) { - //JSON DE CONFIGS - for (nlohmann::json::iterator it = servicesConfigs["proxys"].begin(); it != servicesConfigs["proxys"].end(); it++) { - std::map depsMap; + for(auto& [serviceId, dependencies] : servicesConfigs["proxys"].items()) { + std::map depsMap; - for (nlohmann::json::iterator itr = it.value().begin(); itr != it.value().end(); itr++) { - depsMap.insert(std::pair(itr.key(), itr.value())); + for(auto& [dependencyId, currState] : dependencies.items()) { + depsMap.emplace(std::pair(dependencyId, currState)); } - m_proxyDepsMap.insert(std::pair>(it.key(), depsMap)); + m_proxyDepsMap.emplace(std::pair>(serviceId, depsMap)); } } void ServiceHandler::buildServiceProxy(IService& userService, ServiceProxy::proxyT proxyType) { if (proxyType == ServiceProxy::STATIC_SERVICE) { - m_serviceMap.insert(std::pair(userService.m_serviceId, new staticService::Proxy(userService, m_proxyDepsMap.at(userService.m_serviceId)))); - + m_serviceMap.emplace(std::make_pair( + std::string(userService.m_serviceId), + std::make_unique(userService, m_proxyDepsMap.at(userService.m_serviceId)))); } else { - m_serviceMap.insert(std::pair(userService.m_serviceId, new routineService::Proxy(userService, m_proxyDepsMap.at(userService.m_serviceId)))); + m_serviceMap.emplace(std::make_pair( + std::string(userService.m_serviceId), + std::make_unique(userService, m_proxyDepsMap.at(userService.m_serviceId)))); } } -auto ServiceHandler::getProxyStatus(std::string serviceId) -> nlohmann::json +auto ServiceHandler::getProxyState(std::string serviceId) -> nlohmann::json { - nlohmann::json requiredStatus = m_serviceMap.at(serviceId)->reportStatus(); - return requiredStatus; + nlohmann::json requiredState = m_serviceMap.at(serviceId)->reportState(); + return requiredState; } -auto ServiceHandler::getAllProxyStatus() -> nlohmann::json +auto ServiceHandler::getAllProxyState() -> nlohmann::json { - std::map::iterator itr; - nlohmann::json allStatus; - for (itr = m_serviceMap.begin(); itr != m_serviceMap.end(); itr++) { - allStatus[itr->first] = itr->second->reportStatus(); + nlohmann::json allStates; + + for (auto& [serviceId, proxy] : m_serviceMap) { + allStates[serviceId] = proxy->reportState(); } - return allStatus; + return allStates; } -ServiceHandler::~ServiceHandler() { - std::map::iterator itr; - for (itr = m_serviceMap.begin(); itr != m_serviceMap.end(); itr++) { - delete itr->second; - } -} diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index ac7cf29..a4e9309 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -1,22 +1,25 @@ #pragma once +#include "../iservice/iservice.hpp" +#include "../routine-service-proxy/routine-service-proxy.hpp" #include "../service-proxy/service-proxy.hpp" -#include "../service/service.hpp" +#include "../static-service-proxy/static-service-proxy.hpp" #include +#include #include #include class ServiceHandler { -//private: -public: - std::map m_serviceMap; - std::map> m_proxyDepsMap; +protected: + friend class Tester; + + std::map> m_serviceMap; + std::map> m_proxyDepsMap; public: - auto getProxyStatus(std::string serviceId) -> nlohmann::json; - auto getAllProxyStatus() -> nlohmann::json; + auto getProxyState(std::string serviceId) -> nlohmann::json; + auto getAllProxyState() -> nlohmann::json; void buildServiceProxy(IService& userService, ServiceProxy::proxyT proxyType); explicit ServiceHandler(nlohmann::json servicesConfigs); - ~ServiceHandler(); }; From dd4262b9a9c82b19a475ba103eee6a79a9ecfc51 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 8 Nov 2021 05:17:05 -0300 Subject: [PATCH 089/147] ServiceProxy: adds the standard dependency "THIS" The special dependency "THIS", that all proxys now have, allows the daemon class to choose the best time to start/expose their services on the DBUS. Now when the daemon are ready to expose its services, it changes the dependency "THIS" to state "RUNNING", so if "THIS" is the only dependency of a specific service, now it can starts running. --- src/classes/service-proxy/service-proxy.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index 5b73a9e..54f5672 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -13,6 +13,10 @@ ServiceProxy::ProxyConfigs::ProxyConfigs(std::map Date: Mon, 8 Nov 2021 05:29:19 -0300 Subject: [PATCH 090/147] ServiceHandler: adds the method run, overloads build method The method run changes the dependency "THIS" to state RUNNING in all proxys handled by a ServiceHandler. Also, now the method buildProxy instead of requiring an argument with the "proxy-type", it detects the "proxy-type" by function overload. --- src/classes/service-handler/service-handler.cpp | 16 ++++++++++++---- src/classes/service-handler/service-handler.hpp | 4 +++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index abd861f..af1f796 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -12,17 +12,18 @@ ServiceHandler::ServiceHandler(nlohmann::json servicesConfigs) } } -void ServiceHandler::buildServiceProxy(IService& userService, ServiceProxy::proxyT proxyType) +void ServiceHandler::buildServiceProxy(StaticService& userService) { - if (proxyType == ServiceProxy::STATIC_SERVICE) { m_serviceMap.emplace(std::make_pair( std::string(userService.m_serviceId), std::make_unique(userService, m_proxyDepsMap.at(userService.m_serviceId)))); - } else { +} + +void ServiceHandler::buildServiceProxy(RoutineService& userService) +{ m_serviceMap.emplace(std::make_pair( std::string(userService.m_serviceId), std::make_unique(userService, m_proxyDepsMap.at(userService.m_serviceId)))); - } } auto ServiceHandler::getProxyState(std::string serviceId) -> nlohmann::json @@ -42,3 +43,10 @@ auto ServiceHandler::getAllProxyState() -> nlohmann::json return allStates; } +void ServiceHandler::run() { + + for (auto& [serviceId , proxy] : m_serviceMap) { + proxy->m_proxyConfigs.changeDep("THIS", ServiceProxy::ServiceState::RUNNING); + proxy->autoUpdate(); + } +} diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index a4e9309..220e4c4 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -18,8 +18,10 @@ class ServiceHandler { public: auto getProxyState(std::string serviceId) -> nlohmann::json; auto getAllProxyState() -> nlohmann::json; + void buildServiceProxy(StaticService& userService); + void buildServiceProxy(RoutineService& userService); + void run(); - void buildServiceProxy(IService& userService, ServiceProxy::proxyT proxyType); explicit ServiceHandler(nlohmann::json servicesConfigs); }; From 41af22e4dcf49bf472c9bd29955c9975575d3e0c Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Wed, 10 Nov 2021 22:42:51 -0300 Subject: [PATCH 091/147] ServiceProxy: Improves clarity and reduces code repetition To improve the clarity of the code, some grammar errors were fixed, like "dependency" instead of "dependencie", some ternary operators were converted in if/else statements, the names of the enums' have been changed to make clearer their meaning and last but not least, some functions from StaticServiceProxy and RoutineServiceProxy were transferred to ServiceProxy. --- src/classes/service-proxy/service-proxy.cpp | 45 ++++++++++++++++--- src/classes/service-proxy/service-proxy.hpp | 49 +++++++++++---------- 2 files changed, 63 insertions(+), 31 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index 54f5672..687696f 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -1,12 +1,7 @@ #include "service-proxy.hpp" #include -auto ServiceProxy::ServiceState::getState() const -> stateT -{ - return m_state; -} - -ServiceProxy::ProxyConfigs::ProxyConfigs(std::map depsMap) +ServiceProxy::ProxyConfigs::ProxyConfigs(std::map depsMap) { for (auto& [depId, depReqState] : depsMap) { m_depsMap.emplace(std::piecewise_construct, @@ -19,7 +14,43 @@ ServiceProxy::ProxyConfigs::ProxyConfigs(std::map state_t +{ + return m_state; +} + +void ServiceProxy::ServiceProxy::autoUpdate() +{ + bool noMissingDependencies = true; + + for (auto& [depId, dependency] : m_proxyConfigs.m_depsMap) { + if (dependency.m_currState != dependency.m_reqrState) { + noMissingDependencies = false; + } + } + + if (noMissingDependencies) { + m_state->allFine(); + + } else { + m_state->somethingIsMissing(); + } +} + +auto ServiceProxy::ServiceProxy::checkState() -> ServiceState::state_t +{ + const std::lock_guard lock(m_stateMtx); + return m_state->getState(); +} + +auto ServiceProxy::ServiceProxy::reportState() -> nlohmann::json +{ + ServiceState::state_t currStatus = checkState(); + + return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; +} + +void ServiceProxy::ProxyConfigs::changeDep(std::string dependencieId, ServiceState::state_t currState) { m_depsMap[dependencieId].m_currState = currState; } diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index a002b77..4c33065 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -5,18 +5,17 @@ #include #include -class ServiceProxy { +class ServiceProxy { protected: - friend class ServiceHandler; friend class Tester; - enum proxyT { STATIC_SERVICE = 0, + enum proxy_t { STATIC_SERVICE = 0, ROUTINE_SERVICE }; class ServiceState { public: - enum stateT { MISSING_DEPENDENCIES = 0, + enum state_t { MISSING_DEPENDENCIES = 0, UNINITIALIZED, RUNNING, STOPPED, @@ -24,14 +23,13 @@ class ServiceProxy { STAND_BY, UNKNOWN }; - // protected: - const stateT m_state; + const state_t m_state; virtual void somethingIsMissing() { } virtual void allFine() { } - [[nodiscard]] auto getState() const -> stateT; + [[nodiscard]] auto getState() const -> state_t; - explicit ServiceState(stateT state) + explicit ServiceState(state_t state) : m_state(state) { } @@ -39,38 +37,39 @@ class ServiceProxy { class ProxyConfigs { public: - struct Dependencie { - ServiceState::stateT m_reqrState; - ServiceState::stateT m_currState; - Dependencie(ServiceState::stateT reqrState, ServiceState::stateT currState) + struct Dependency { + ServiceState::state_t m_reqrState; + ServiceState::state_t m_currState; + Dependency(ServiceState::state_t reqrState, ServiceState::state_t currState) : m_reqrState(reqrState) , m_currState(currState) { } - Dependencie() = default; + Dependency() = default; }; - std::map m_depsMap; + std::map m_depsMap; - void changeDep(std::string dependencieId, ServiceState::stateT currState); - explicit ProxyConfigs(std::map depsMap); + void changeDep(std::string dependencieId, ServiceState::state_t currState); + explicit ProxyConfigs(std::map depsMap); }; - proxyT m_proxyType; - std::mutex m_statusMtx; + proxy_t m_proxyType; + std::mutex m_stateMtx; + IService& m_realService; ProxyConfigs m_proxyConfigs; std::string m_realServiceId; - IService& m_realService; + std::unique_ptr m_state; - virtual void changeState(ServiceState::stateT newState) { } - virtual void autoUpdate() { } + auto checkState() -> ServiceState::state_t; + + virtual void autoUpdate(); virtual void serviceCycle() { } + virtual void changeState(ServiceState::state_t newState) { } public: - virtual auto reportState() -> nlohmann::json { return { {} }; } - - ServiceProxy(IService& realService, proxyT proxyType, std::map depsMap) + ServiceProxy(IService& realService, proxy_t proxyType, std::map depsMap) : m_realService(realService) , m_proxyType(proxyType) , m_proxyConfigs(depsMap) @@ -78,6 +77,8 @@ class ServiceProxy { { } + virtual auto reportState() -> nlohmann::json; + virtual ~ServiceProxy() = default; }; From 05c529d2dc76291f752e2c028f468c84431109cb Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Wed, 10 Nov 2021 23:00:07 -0300 Subject: [PATCH 092/147] StaticServiceProxy: improves clarity of the code Besides fitting the changes made on the ServiceProxy, two functions that were repeated in the two child proxys, "reportState" and "checkState" were transfered to the parent proxy. --- .../static-service-proxy.cpp | 57 ++++++------------- .../static-service-proxy.hpp | 17 ++---- 2 files changed, 22 insertions(+), 52 deletions(-) diff --git a/src/classes/static-service-proxy/static-service-proxy.cpp b/src/classes/static-service-proxy/static-service-proxy.cpp index 8ba42b8..d5c97bc 100644 --- a/src/classes/static-service-proxy/static-service-proxy.cpp +++ b/src/classes/static-service-proxy/static-service-proxy.cpp @@ -1,8 +1,15 @@ #include "static-service-proxy.hpp" +StaticServiceProxy::StaticServiceProxy(IService& realService, std::map depsMap) + : m_runnedOnce(false) + , ServiceProxy(realService, STATIC_SERVICE, depsMap) +{ + changeState(ServiceState::MISSING_DEPENDENCIES); +} + void StaticServiceProxy::MissingDependencies::allFine() { - stateT newState = (m_upperProxy.m_runnedOnce) ? STAND_BY : UNINITIALIZED; + state_t newState = (m_upperProxy.m_runnedOnce) ? STAND_BY : UNINITIALIZED; m_upperProxy.changeState(newState); } @@ -12,33 +19,13 @@ void StaticServiceProxy::MissingDependencies::allFine() void StaticServiceProxy::Uninitialized::somethingIsMissing() { // Unexpose/Hide the endpoint on the DBUS and THEN.. - m_upperProxy.changeState(MISSING_DEPENDENCIES); + m_upperProxy.changeState(ServiceState::MISSING_DEPENDENCIES); } void StaticServiceProxy::StandBy::somethingIsMissing() { // Unexpose/Hide the endpoint on the DBUS and THEN... - m_upperProxy.changeState(MISSING_DEPENDENCIES); -} - -StaticServiceProxy::StaticServiceProxy(IService& realService, std::map depsMap) - : m_runnedOnce(false) - , ServiceProxy(realService, STATIC_SERVICE, depsMap) -{ - changeState(ServiceState::MISSING_DEPENDENCIES); -} - -void StaticServiceProxy::StaticServiceProxy::autoUpdate() -{ - bool noMissingDependencies = true; - - for (auto& [depId, dependency] : m_proxyConfigs.m_depsMap) { - if (dependency.m_currState != dependency.m_reqrState) { - noMissingDependencies = false; - } - } - - (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); + m_upperProxy.changeState(ServiceState::MISSING_DEPENDENCIES); } void StaticServiceProxy::StaticServiceProxy::serviceCycle() @@ -49,37 +36,25 @@ void StaticServiceProxy::StaticServiceProxy::serviceCycle() changeState(ServiceState::STAND_BY); } -void StaticServiceProxy::StaticServiceProxy::changeState(ServiceState::stateT newState) +void StaticServiceProxy::StaticServiceProxy::changeState(ServiceState::state_t newState) { - const std::lock_guard lock(m_statusMtx); + const std::lock_guard lock(m_stateMtx); switch (newState) { case ServiceState::MISSING_DEPENDENCIES: - m_status = std::make_unique(*this); + m_state = std::make_unique(*this); break; case ServiceState::UNINITIALIZED: - m_status = std::make_unique(*this); + m_state = std::make_unique(*this); break; case ServiceState::RUNNING: - m_status = std::make_unique(*this); + m_state = std::make_unique(*this); break; case ServiceState::STAND_BY: - m_status = std::make_unique(*this); + m_state = std::make_unique(*this); break; default: std::cout << "ERROR!! This was not supposed to happen!! - Static Service" << std::endl; } } -auto StaticServiceProxy::StaticServiceProxy::checkState() -> ServiceState::stateT -{ - const std::lock_guard lock(m_statusMtx); - return m_status->getState(); -} - -auto StaticServiceProxy::StaticServiceProxy::reportState() -> nlohmann::json -{ - ServiceState::stateT currStatus = checkState(); - - return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; -} diff --git a/src/classes/static-service-proxy/static-service-proxy.hpp b/src/classes/static-service-proxy/static-service-proxy.hpp index 7956789..b4648be 100644 --- a/src/classes/static-service-proxy/static-service-proxy.hpp +++ b/src/classes/static-service-proxy/static-service-proxy.hpp @@ -3,6 +3,10 @@ #include class StaticServiceProxy : public ServiceProxy { +public: + StaticServiceProxy(IService& realService, std::map depsMap); + ~StaticServiceProxy() override = default; + protected: friend class ServiceHandler; friend class Tester; @@ -12,7 +16,7 @@ class StaticServiceProxy : public ServiceProxy { StaticServiceProxy& m_upperProxy; public: - StaticState(stateT state, StaticServiceProxy& upperProxy) + StaticState(state_t state, StaticServiceProxy& upperProxy) : ServiceState(state) , m_upperProxy(upperProxy) { @@ -55,17 +59,8 @@ class StaticServiceProxy : public ServiceProxy { }; bool m_runnedOnce; - std::unique_ptr m_status; - void changeState(ServiceState::stateT newState) override; + void changeState(ServiceState::state_t newState) override; void serviceCycle() override; - void autoUpdate() override; - auto checkState() -> ServiceState::stateT; - -public: - StaticServiceProxy(IService& realService, std::map depsMap); - ~StaticServiceProxy() override = default; - - auto reportState() -> nlohmann::json override; }; From 45f172a25b5cbde55c93a3a8537a3ad11ab7a2eb Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Wed, 10 Nov 2021 23:06:40 -0300 Subject: [PATCH 093/147] RoutineServiceProxy: improves clarity of the code Besides fitting the changes made on the ServiceProxy, two functions that were repeated in the two child proxys, "reportState" and "checkState" were transfered to the parent proxy. --- .../routine-service-proxy.cpp | 66 ++++++------------- .../routine-service-proxy.hpp | 17 ++--- 2 files changed, 26 insertions(+), 57 deletions(-) diff --git a/src/classes/routine-service-proxy/routine-service-proxy.cpp b/src/classes/routine-service-proxy/routine-service-proxy.cpp index 3257007..130d80c 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.cpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.cpp @@ -1,9 +1,9 @@ #include "routine-service-proxy.hpp" -RoutineServiceProxy::RoutineServiceProxy(IService& realService, std::map depsMap) +RoutineServiceProxy::RoutineServiceProxy(IService& realService, std::map depsMap) : ServiceProxy(realService, ROUTINE_SERVICE, depsMap) { - changeState(RoutineState::MISSING_DEPENDENCIES); + changeState(ServiceState::MISSING_DEPENDENCIES); } void RoutineServiceProxy::MissingDependencies::allFine() @@ -20,23 +20,23 @@ void RoutineServiceProxy::Running::somethingIsMissing() void RoutineServiceProxy::serviceCycle() { - changeState(RoutineState::RUNNING); + changeState(ServiceState::RUNNING); m_realService.setup(); - while (checkState() != RoutineState::STOPPED) { + while (checkState() != ServiceState::STOPPED) { m_realService.routine(); } m_realService.destroy(); - changeState(RoutineState::FINISHED); + changeState(ServiceState::FINISHED); } void RoutineServiceProxy::weave() { const std::lock_guard lock(m_updateMtx); - changeState(RoutineState::STAND_BY); + changeState(ServiceState::STAND_BY); std::thread thread(&RoutineServiceProxy::serviceCycle, this); std::swap(thread, m_thread); } @@ -44,59 +44,33 @@ void RoutineServiceProxy::weave() void RoutineServiceProxy::cut() { const std::lock_guard lock(m_updateMtx); - changeState(RoutineState::STOPPED); + changeState(ServiceState::STOPPED); m_thread.join(); - changeState(RoutineState::MISSING_DEPENDENCIES); + changeState(ServiceState::MISSING_DEPENDENCIES); } -void RoutineServiceProxy::autoUpdate() +void RoutineServiceProxy::changeState(ServiceState::state_t newState) { - bool noMissingDependencies = true; - - for (auto& [depId, dependency] : m_proxyConfigs.m_depsMap) { - if (dependency.m_currState != dependency.m_reqrState) { - noMissingDependencies = false; - } - } - - (noMissingDependencies) ? m_status->allFine() : m_status->somethingIsMissing(); -} - -void RoutineServiceProxy::changeState(RoutineState::stateT newState) -{ - const std::lock_guard lock(m_statusMtx); + const std::lock_guard lock(m_stateMtx); switch (newState) { - case RoutineState::MISSING_DEPENDENCIES: - m_status = std::make_unique(*this); + case ServiceState::MISSING_DEPENDENCIES: + m_state = std::make_unique(*this); break; - case RoutineState::RUNNING: - m_status = std::make_unique(*this); + case ServiceState::RUNNING: + m_state = std::make_unique(*this); break; - case RoutineState::STAND_BY: - m_status = std::make_unique(*this); + case ServiceState::STAND_BY: + m_state = std::make_unique(*this); break; - case RoutineState::STOPPED: - m_status = std::make_unique(*this); + case ServiceState::STOPPED: + m_state = std::make_unique(*this); break; - case RoutineState::FINISHED: - m_status = std::make_unique(*this); + case ServiceState::FINISHED: + m_state = std::make_unique(*this); break; default: std::cout << "ERROR!! This was not supose to happen!! - Routine Service" << std::endl; } } -auto RoutineServiceProxy::checkState() -> RoutineState::stateT -{ - const std::lock_guard lock(m_statusMtx); - return m_status->getState(); -} - -auto RoutineServiceProxy::reportState() -> nlohmann::json -{ - RoutineState::stateT currStatus = checkState(); - - return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; -} - diff --git a/src/classes/routine-service-proxy/routine-service-proxy.hpp b/src/classes/routine-service-proxy/routine-service-proxy.hpp index 862ad1b..6421187 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.hpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.hpp @@ -3,6 +3,10 @@ #include class RoutineServiceProxy : public ServiceProxy { +public: + RoutineServiceProxy(IService& realService, std::map depsMap); + ~RoutineServiceProxy() override = default; + protected: friend class ServiceHandler; friend class Tester; @@ -12,7 +16,7 @@ class RoutineServiceProxy : public ServiceProxy { public: RoutineServiceProxy& m_upperProxy; - RoutineState(stateT state, RoutineServiceProxy& upperProxy) + RoutineState(state_t state, RoutineServiceProxy& upperProxy) : m_upperProxy(upperProxy) , ServiceState(state) { @@ -64,20 +68,11 @@ class RoutineServiceProxy : public ServiceProxy { }; std::thread m_thread; - std::unique_ptr m_status; std::mutex m_updateMtx; void serviceCycle() override; - void autoUpdate() override; - void changeState(ServiceState::stateT newState) override; - auto checkState() -> ServiceState::stateT; + void changeState(ServiceState::state_t newState) override; void weave(); void cut(); - -public: - RoutineServiceProxy(IService& realService, std::map depsMap); - ~RoutineServiceProxy() override = default; - - auto reportState() -> nlohmann::json override; }; From 7922c57035796cb7e628104f13bc27bb97954d16 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Wed, 10 Nov 2021 23:07:29 -0300 Subject: [PATCH 094/147] ServiceHandler: fits the changes on enums's name Due to the change of the enum's name, from "stateT" to "state_t" and from "proxyT" to "state_t", little changes like expected output type of functions "getProxyState" and "getAllProxyState" required changes to compile. --- src/classes/service-handler/service-handler.cpp | 6 +++--- src/classes/service-handler/service-handler.hpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index af1f796..8b61e4f 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -3,12 +3,12 @@ ServiceHandler::ServiceHandler(nlohmann::json servicesConfigs) { for(auto& [serviceId, dependencies] : servicesConfigs["proxys"].items()) { - std::map depsMap; + std::map depsMap; for(auto& [dependencyId, currState] : dependencies.items()) { - depsMap.emplace(std::pair(dependencyId, currState)); + depsMap.emplace(std::pair(dependencyId, currState)); } - m_proxyDepsMap.emplace(std::pair>(serviceId, depsMap)); + m_proxyDepsMap.emplace(std::pair>(serviceId, depsMap)); } } diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index 220e4c4..4e7d4f2 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -13,7 +13,7 @@ class ServiceHandler { friend class Tester; std::map> m_serviceMap; - std::map> m_proxyDepsMap; + std::map> m_proxyDepsMap; public: auto getProxyState(std::string serviceId) -> nlohmann::json; From 518355edbe718922513dafdf1787dd7fb3db9637 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Wed, 10 Nov 2021 23:28:32 -0300 Subject: [PATCH 095/147] StaticServiceProxy: allows only StaticServices Now the class StaticServiceProxy allows only classes inherited from StaticService instead of allowing classes inherited directly from IService. --- src/classes/static-service-proxy/static-service-proxy.cpp | 2 +- src/classes/static-service-proxy/static-service-proxy.hpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/classes/static-service-proxy/static-service-proxy.cpp b/src/classes/static-service-proxy/static-service-proxy.cpp index d5c97bc..ecda60c 100644 --- a/src/classes/static-service-proxy/static-service-proxy.cpp +++ b/src/classes/static-service-proxy/static-service-proxy.cpp @@ -1,6 +1,6 @@ #include "static-service-proxy.hpp" -StaticServiceProxy::StaticServiceProxy(IService& realService, std::map depsMap) +StaticServiceProxy::StaticServiceProxy(StaticService& realService, std::map depsMap) : m_runnedOnce(false) , ServiceProxy(realService, STATIC_SERVICE, depsMap) { diff --git a/src/classes/static-service-proxy/static-service-proxy.hpp b/src/classes/static-service-proxy/static-service-proxy.hpp index b4648be..9252567 100644 --- a/src/classes/static-service-proxy/static-service-proxy.hpp +++ b/src/classes/static-service-proxy/static-service-proxy.hpp @@ -4,7 +4,7 @@ class StaticServiceProxy : public ServiceProxy { public: - StaticServiceProxy(IService& realService, std::map depsMap); + StaticServiceProxy(StaticService& realService, std::map depsMap); ~StaticServiceProxy() override = default; protected: From 0cfb6b8b9e4629d8eb4ee1bb4243fd00ca39746f Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Wed, 10 Nov 2021 23:31:18 -0300 Subject: [PATCH 096/147] RoutineServiceProxy: allows only RoutineServices Now the class RoutineServiceProxy allows only classes inherited from RoutineService instead of allowing classes inherited directly from IService. --- src/classes/routine-service-proxy/routine-service-proxy.cpp | 2 +- src/classes/routine-service-proxy/routine-service-proxy.hpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/classes/routine-service-proxy/routine-service-proxy.cpp b/src/classes/routine-service-proxy/routine-service-proxy.cpp index 130d80c..c1ce02d 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.cpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.cpp @@ -1,6 +1,6 @@ #include "routine-service-proxy.hpp" -RoutineServiceProxy::RoutineServiceProxy(IService& realService, std::map depsMap) +RoutineServiceProxy::RoutineServiceProxy(RoutineService& realService, std::map depsMap) : ServiceProxy(realService, ROUTINE_SERVICE, depsMap) { changeState(ServiceState::MISSING_DEPENDENCIES); diff --git a/src/classes/routine-service-proxy/routine-service-proxy.hpp b/src/classes/routine-service-proxy/routine-service-proxy.hpp index 6421187..d9c8e3e 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.hpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.hpp @@ -4,7 +4,7 @@ class RoutineServiceProxy : public ServiceProxy { public: - RoutineServiceProxy(IService& realService, std::map depsMap); + RoutineServiceProxy(RoutineService& realService, std::map depsMap); ~RoutineServiceProxy() override = default; protected: From b3f20ea4b22e44ca7f9926c9dbe27538d4dc2b05 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Wed, 10 Nov 2021 23:36:50 -0300 Subject: [PATCH 097/147] ServiceHandler: brings the class' constructor to the begin Brings the class' constructor to the begin of class' definition in order to improve the clarity of the code. --- src/classes/service-handler/service-handler.hpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index 4e7d4f2..457fd35 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -9,6 +9,9 @@ #include class ServiceHandler { +public: + explicit ServiceHandler(nlohmann::json servicesConfigs); + protected: friend class Tester; @@ -21,7 +24,5 @@ class ServiceHandler { void buildServiceProxy(StaticService& userService); void buildServiceProxy(RoutineService& userService); void run(); - - explicit ServiceHandler(nlohmann::json servicesConfigs); }; From 36414753ea09fb5a7892785763cd5f39e5627723 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Thu, 11 Nov 2021 00:00:26 -0300 Subject: [PATCH 098/147] ServiceProxy: brings some constructors to the top Improves clarity of the code. --- src/classes/service-proxy/service-proxy.hpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index 4c33065..93360d1 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -25,14 +25,15 @@ class ServiceProxy { const state_t m_state; - virtual void somethingIsMissing() { } - virtual void allFine() { } - [[nodiscard]] auto getState() const -> state_t; - explicit ServiceState(state_t state) : m_state(state) { } + + virtual void somethingIsMissing() { } + virtual void allFine() { } + [[nodiscard]] auto getState() const -> state_t; + }; class ProxyConfigs { @@ -40,6 +41,7 @@ class ServiceProxy { struct Dependency { ServiceState::state_t m_reqrState; ServiceState::state_t m_currState; + Dependency(ServiceState::state_t reqrState, ServiceState::state_t currState) : m_reqrState(reqrState) , m_currState(currState) From 788cd10d251c9574e1c4e3f4b18d6f9f9518946e Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Thu, 11 Nov 2021 00:14:51 -0300 Subject: [PATCH 099/147] StaticServiceProxy: throws exception on the "changeState" method Throws exception on the method "changeState" instead of outputting an error message in the screen. --- src/classes/static-service-proxy/static-service-proxy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/classes/static-service-proxy/static-service-proxy.cpp b/src/classes/static-service-proxy/static-service-proxy.cpp index ecda60c..b402c30 100644 --- a/src/classes/static-service-proxy/static-service-proxy.cpp +++ b/src/classes/static-service-proxy/static-service-proxy.cpp @@ -54,7 +54,7 @@ void StaticServiceProxy::StaticServiceProxy::changeState(ServiceState::state_t n m_state = std::make_unique(*this); break; default: - std::cout << "ERROR!! This was not supposed to happen!! - Static Service" << std::endl; + throw std::logic_error("Static Services should not have other States!"); } } From 90b1b679b2328b9ab364908fb99f8a9163180096 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Thu, 11 Nov 2021 00:52:16 -0300 Subject: [PATCH 100/147] RoutineServiceProxy: throws exception on the "changeState" method Throws exception on the method "changeState" instead of outputting an error message in the screen. --- src/classes/routine-service-proxy/routine-service-proxy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/classes/routine-service-proxy/routine-service-proxy.cpp b/src/classes/routine-service-proxy/routine-service-proxy.cpp index c1ce02d..1245c5f 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.cpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.cpp @@ -70,7 +70,7 @@ void RoutineServiceProxy::changeState(ServiceState::state_t newState) m_state = std::make_unique(*this); break; default: - std::cout << "ERROR!! This was not supose to happen!! - Routine Service" << std::endl; + throw std::logic_error("Routine Services should not have other States!"); } } From b254bf24919ac1b4c5ba5296b46481ddd430c743 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Thu, 11 Nov 2021 19:40:05 -0300 Subject: [PATCH 101/147] CMakeLists: Allows compilation Hot fix to allows compilation of service-classes. --- CMakeLists.txt | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f58e15..08034ad 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,23 +47,24 @@ endmacro(ZFKD_CREATE_DICT) set(ZFKD_CLASSES - daemon - service + #daemon service-handler service-proxy + static-service-proxy + routine-service-proxy ) set(ZFKD_UTILITIES - dbus-handler - config-handler - locked-storage + #dbus-handler + #config-handler + #locked-storage ) set(ZFKD_PUBLIC_CLASSES - daemon - service + #daemon + #service ) set(ZFKD_PUBLIC_UTILITIES From f03965d36a81cff8ac075b732f1ed6f6b071e9ec Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 15 Nov 2021 19:19:15 -0300 Subject: [PATCH 102/147] IService: improves clarity of the code Empty spaces were removed and syntax were changed to improve code aesthetic and improve the clarity of the code. --- src/classes/iservice/iservice.hpp | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/src/classes/iservice/iservice.hpp b/src/classes/iservice/iservice.hpp index 46f2d4c..b6d8622 100644 --- a/src/classes/iservice/iservice.hpp +++ b/src/classes/iservice/iservice.hpp @@ -1,16 +1,11 @@ - #pragma once -#include + #include + class IService { public: - /* Id of the service */ std::string m_serviceId; -protected: - // DBusHandler::DBusHandler m_dbus; - -public: /** * @brief An interface function to be implemented by * the user to make the "setup"/configuration @@ -41,11 +36,8 @@ class IService { * @param serviceId std::string that is the id related * to the instantiated class. */ - explicit IService(std::string serviceId) - : m_serviceId { serviceId } - { - } + : m_serviceId { serviceId } {}; /** * @brief A virtual destructor to ensure @@ -57,9 +49,7 @@ class IService { class StaticService : public IService { public: explicit StaticService(std::string serviceId) - : IService(serviceId) - { - } + : IService { serviceId } {}; void routine() final { } @@ -69,9 +59,7 @@ class StaticService : public IService { class RoutineService : public IService { public: explicit RoutineService(std::string serviceId) - : IService(serviceId) - { - } + : IService { serviceId } {}; ~RoutineService() override = default; }; From 579f82aec2c7c49d6658ffd723a7ce4ac8f69b73 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 15 Nov 2021 19:27:26 -0300 Subject: [PATCH 103/147] ServiceProxy: improves clarity of the code Empty spaces were removed and syntax were changed to improve code aesthetic and the clarity of the code . --- src/classes/service-proxy/service-proxy.cpp | 10 +++----- src/classes/service-proxy/service-proxy.hpp | 26 +++++++-------------- 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index 687696f..17cccac 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -1,5 +1,4 @@ #include "service-proxy.hpp" -#include ServiceProxy::ProxyConfigs::ProxyConfigs(std::map depsMap) { @@ -31,7 +30,6 @@ void ServiceProxy::ServiceProxy::autoUpdate() if (noMissingDependencies) { m_state->allFine(); - } else { m_state->somethingIsMissing(); } @@ -39,19 +37,17 @@ void ServiceProxy::ServiceProxy::autoUpdate() auto ServiceProxy::ServiceProxy::checkState() -> ServiceState::state_t { - const std::lock_guard lock(m_stateMtx); + const std::lock_guard lock { m_stateMtx }; return m_state->getState(); } auto ServiceProxy::ServiceProxy::reportState() -> nlohmann::json { - ServiceState::state_t currStatus = checkState(); - - return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", currStatus } }; + return (nlohmann::json) { { "serviceId", m_realServiceId }, { "State", checkState() } }; } void ServiceProxy::ProxyConfigs::changeDep(std::string dependencieId, ServiceState::state_t currState) { - m_depsMap[dependencieId].m_currState = currState; + m_depsMap.at(dependencieId).m_currState = currState; } diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index 93360d1..23a59f7 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -5,10 +5,9 @@ #include #include -class ServiceProxy { +class ServiceProxy { protected: friend class ServiceHandler; - friend class Tester; enum proxy_t { STATIC_SERVICE = 0, ROUTINE_SERVICE }; @@ -26,14 +25,11 @@ class ServiceProxy { const state_t m_state; explicit ServiceState(state_t state) - : m_state(state) - { - } + : m_state { state } {}; virtual void somethingIsMissing() { } virtual void allFine() { } [[nodiscard]] auto getState() const -> state_t; - }; class ProxyConfigs { @@ -41,12 +37,10 @@ class ServiceProxy { struct Dependency { ServiceState::state_t m_reqrState; ServiceState::state_t m_currState; - + Dependency(ServiceState::state_t reqrState, ServiceState::state_t currState) - : m_reqrState(reqrState) - , m_currState(currState) - { - } + : m_reqrState { reqrState } + , m_currState { currState } {}; Dependency() = default; }; @@ -72,12 +66,10 @@ class ServiceProxy { public: ServiceProxy(IService& realService, proxy_t proxyType, std::map depsMap) - : m_realService(realService) - , m_proxyType(proxyType) - , m_proxyConfigs(depsMap) - , m_realServiceId(realService.m_serviceId) - { - } + : m_realService { realService } + , m_proxyType { proxyType } + , m_proxyConfigs { depsMap } + , m_realServiceId { realService.m_serviceId } {}; virtual auto reportState() -> nlohmann::json; From 6a9d3c19b1e301f8d0700e5f99c5e534abf938f8 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 15 Nov 2021 19:43:28 -0300 Subject: [PATCH 104/147] RoutineServiceProxy: improves clarity of the code Empty spaces were removed, syntax and error messages were changed to improve code aesthetic and the clarity of the code. --- .../routine-service-proxy.cpp | 22 +++++++++---- .../routine-service-proxy.hpp | 33 ++++++------------- 2 files changed, 25 insertions(+), 30 deletions(-) diff --git a/src/classes/routine-service-proxy/routine-service-proxy.cpp b/src/classes/routine-service-proxy/routine-service-proxy.cpp index 1245c5f..e97f0ac 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.cpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.cpp @@ -1,20 +1,26 @@ #include "routine-service-proxy.hpp" RoutineServiceProxy::RoutineServiceProxy(RoutineService& realService, std::map depsMap) - : ServiceProxy(realService, ROUTINE_SERVICE, depsMap) + : ServiceProxy { realService, ROUTINE_SERVICE, depsMap } { changeState(ServiceState::MISSING_DEPENDENCIES); } +/** + * @brief: Exposes the routine-service from the DBUS and then + * calls m_upperProxy's method weave. + */ void RoutineServiceProxy::MissingDependencies::allFine() { - // Expose/Hide the endpoint on the DBUS and THEN.. m_upperProxy.weave(); } +/** + * @brief: Hides the routine-service from the DBUS and then calls + * the m_upperProxy's method cut. + */ void RoutineServiceProxy::Running::somethingIsMissing() { - // Unexpose/Hide the endpoint on the DBUS and THEN.. m_upperProxy.cut(); } @@ -35,7 +41,7 @@ void RoutineServiceProxy::serviceCycle() void RoutineServiceProxy::weave() { - const std::lock_guard lock(m_updateMtx); + const std::lock_guard lock { m_updateMtx }; changeState(ServiceState::STAND_BY); std::thread thread(&RoutineServiceProxy::serviceCycle, this); std::swap(thread, m_thread); @@ -43,7 +49,7 @@ void RoutineServiceProxy::weave() void RoutineServiceProxy::cut() { - const std::lock_guard lock(m_updateMtx); + const std::lock_guard lock { m_updateMtx }; changeState(ServiceState::STOPPED); m_thread.join(); changeState(ServiceState::MISSING_DEPENDENCIES); @@ -51,7 +57,7 @@ void RoutineServiceProxy::cut() void RoutineServiceProxy::changeState(ServiceState::state_t newState) { - const std::lock_guard lock(m_stateMtx); + const std::lock_guard lock { m_stateMtx }; switch (newState) { case ServiceState::MISSING_DEPENDENCIES: @@ -70,7 +76,9 @@ void RoutineServiceProxy::changeState(ServiceState::state_t newState) m_state = std::make_unique(*this); break; default: - throw std::logic_error("Routine Services should not have other States!"); + std::string errorMessage = "Unknown State! State Read = "; + errorMessage.append(std::to_string(newState)); + throw std::logic_error(errorMessage); } } diff --git a/src/classes/routine-service-proxy/routine-service-proxy.hpp b/src/classes/routine-service-proxy/routine-service-proxy.hpp index d9c8e3e..fd94797 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.hpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.hpp @@ -9,7 +9,9 @@ class RoutineServiceProxy : public ServiceProxy { protected: friend class ServiceHandler; - friend class Tester; + + std::thread m_thread; + std::mutex m_updateMtx; class RoutineState : public ServiceState { @@ -17,18 +19,14 @@ class RoutineServiceProxy : public ServiceProxy { RoutineServiceProxy& m_upperProxy; RoutineState(state_t state, RoutineServiceProxy& upperProxy) - : m_upperProxy(upperProxy) - , ServiceState(state) - { - } + : m_upperProxy { upperProxy } + , ServiceState { state } {}; }; class MissingDependencies : public RoutineState { public: explicit MissingDependencies(RoutineServiceProxy& upperProxy) - : RoutineState(MISSING_DEPENDENCIES, upperProxy) - { - } + : RoutineState { MISSING_DEPENDENCIES, upperProxy } {}; void allFine() override; }; @@ -36,17 +34,13 @@ class RoutineServiceProxy : public ServiceProxy { class StandBy : public RoutineState { public: explicit StandBy(RoutineServiceProxy& upperProxy) - : RoutineState(STAND_BY, upperProxy) - { - } + : RoutineState { STAND_BY, upperProxy } {}; }; class Running : public RoutineState { public: explicit Running(RoutineServiceProxy& upperProxy) - : RoutineState(RUNNING, upperProxy) - { - } + : RoutineState { RUNNING, upperProxy } {}; void somethingIsMissing() override; }; @@ -54,22 +48,15 @@ class RoutineServiceProxy : public ServiceProxy { class Stopped : public RoutineState { public: explicit Stopped(RoutineServiceProxy& upperProxy) - : RoutineState(STOPPED, upperProxy) - { - } + : RoutineState { STOPPED, upperProxy } {}; }; class Finished : public RoutineState { public: explicit Finished(RoutineServiceProxy& upperProxy) - : RoutineState(FINISHED, upperProxy) - { - } + : RoutineState { FINISHED, upperProxy } {}; }; - std::thread m_thread; - std::mutex m_updateMtx; - void serviceCycle() override; void changeState(ServiceState::state_t newState) override; void weave(); From d1546c0336d6cdca0a458a1da80fb99ca087f10e Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 15 Nov 2021 19:55:04 -0300 Subject: [PATCH 105/147] StaticServiceProxy: improves clarity of the code Empty spaces were removed, syntax and error messages were changed to improve code aesthetic and the clarity of the code. --- .../static-service-proxy.cpp | 30 ++++++++++++++----- .../static-service-proxy.hpp | 29 +++++++----------- 2 files changed, 32 insertions(+), 27 deletions(-) diff --git a/src/classes/static-service-proxy/static-service-proxy.cpp b/src/classes/static-service-proxy/static-service-proxy.cpp index b402c30..d2914bd 100644 --- a/src/classes/static-service-proxy/static-service-proxy.cpp +++ b/src/classes/static-service-proxy/static-service-proxy.cpp @@ -1,12 +1,18 @@ #include "static-service-proxy.hpp" StaticServiceProxy::StaticServiceProxy(StaticService& realService, std::map depsMap) - : m_runnedOnce(false) - , ServiceProxy(realService, STATIC_SERVICE, depsMap) + : m_runnedOnce { false } + , ServiceProxy { realService, STATIC_SERVICE, depsMap } { changeState(ServiceState::MISSING_DEPENDENCIES); } +/* + * @brief: Exposes the static-service on the DBUS and then + * changes m_upperProxy's StaticState to state + * StandBy if the static-service already had run + * once, or to state Uninitialized if its doesn't. + */ void StaticServiceProxy::MissingDependencies::allFine() { state_t newState = (m_upperProxy.m_runnedOnce) ? STAND_BY : UNINITIALIZED; @@ -14,17 +20,23 @@ void StaticServiceProxy::MissingDependencies::allFine() m_upperProxy.changeState(newState); } -// Uninitialized and StandBy Constructor will expose the endpoint on the DBUS - +/* + * @brief: Hides the static-service from the DBUS and then + * changes m_upperProxy's StaticState to state + * MissingDependencies. + */ void StaticServiceProxy::Uninitialized::somethingIsMissing() { - // Unexpose/Hide the endpoint on the DBUS and THEN.. m_upperProxy.changeState(ServiceState::MISSING_DEPENDENCIES); } +/* + * @brief: Hides the static-service from the DBUS and then + * changes m_upperProxy's StaticState to state + * MissingDependencies. + */ void StaticServiceProxy::StandBy::somethingIsMissing() { - // Unexpose/Hide the endpoint on the DBUS and THEN... m_upperProxy.changeState(ServiceState::MISSING_DEPENDENCIES); } @@ -38,7 +50,7 @@ void StaticServiceProxy::StaticServiceProxy::serviceCycle() void StaticServiceProxy::StaticServiceProxy::changeState(ServiceState::state_t newState) { - const std::lock_guard lock(m_stateMtx); + const std::lock_guard lock { m_stateMtx }; switch (newState) { case ServiceState::MISSING_DEPENDENCIES: @@ -54,7 +66,9 @@ void StaticServiceProxy::StaticServiceProxy::changeState(ServiceState::state_t n m_state = std::make_unique(*this); break; default: - throw std::logic_error("Static Services should not have other States!"); + std::string errorMessage = "Unknown State! State Read = "; + errorMessage.append(std::to_string(newState)); + throw std::logic_error(errorMessage); } } diff --git a/src/classes/static-service-proxy/static-service-proxy.hpp b/src/classes/static-service-proxy/static-service-proxy.hpp index 9252567..e6ef6fb 100644 --- a/src/classes/static-service-proxy/static-service-proxy.hpp +++ b/src/classes/static-service-proxy/static-service-proxy.hpp @@ -1,6 +1,8 @@ #pragma once #include "../service-proxy/service-proxy.hpp" +#include #include +#include class StaticServiceProxy : public ServiceProxy { public: @@ -9,7 +11,8 @@ class StaticServiceProxy : public ServiceProxy { protected: friend class ServiceHandler; - friend class Tester; + + bool m_runnedOnce; class StaticState : public ServiceState { protected: @@ -17,49 +20,37 @@ class StaticServiceProxy : public ServiceProxy { public: StaticState(state_t state, StaticServiceProxy& upperProxy) - : ServiceState(state) - , m_upperProxy(upperProxy) - { - } + : ServiceState { state } + , m_upperProxy { upperProxy } {}; }; class MissingDependencies : public StaticState { public: explicit MissingDependencies(StaticServiceProxy& upperProxy) - : StaticState(MISSING_DEPENDENCIES, upperProxy) - { - } + : StaticState { MISSING_DEPENDENCIES, upperProxy } {}; void allFine() override; }; class Uninitialized : public StaticState { public: explicit Uninitialized(StaticServiceProxy& upperProxy) - : StaticState(UNINITIALIZED, upperProxy) - { - } + : StaticState { UNINITIALIZED, upperProxy } {}; void somethingIsMissing() override; }; class Running : public StaticState { public: explicit Running(StaticServiceProxy& upperProxy) - : StaticState(RUNNING, upperProxy) - { - } + : StaticState { RUNNING, upperProxy } {}; }; class StandBy : public StaticState { public: explicit StandBy(StaticServiceProxy& upperProxy) - : StaticState(STAND_BY, upperProxy) - { - } + : StaticState { STAND_BY, upperProxy } {}; void somethingIsMissing() override; }; - bool m_runnedOnce; - void changeState(ServiceState::state_t newState) override; void serviceCycle() override; }; From 132378664ffd75202d9a888dc330f8c8462f2d1b Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 15 Nov 2021 19:56:25 -0300 Subject: [PATCH 106/147] ServiceHandler: improves clarity of the code Empty spaces were removed and syntax were changed to improve code aesthetic and the clarity of the code. --- .../service-handler/service-handler.cpp | 22 +++++++++---------- .../service-handler/service-handler.hpp | 2 -- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index 8b61e4f..8310376 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -2,10 +2,10 @@ ServiceHandler::ServiceHandler(nlohmann::json servicesConfigs) { - for(auto& [serviceId, dependencies] : servicesConfigs["proxys"].items()) { + for (auto& [serviceId, dependencies] : servicesConfigs["proxys"].items()) { std::map depsMap; - for(auto& [dependencyId, currState] : dependencies.items()) { + for (auto& [dependencyId, currState] : dependencies.items()) { depsMap.emplace(std::pair(dependencyId, currState)); } m_proxyDepsMap.emplace(std::pair>(serviceId, depsMap)); @@ -14,16 +14,16 @@ ServiceHandler::ServiceHandler(nlohmann::json servicesConfigs) void ServiceHandler::buildServiceProxy(StaticService& userService) { - m_serviceMap.emplace(std::make_pair( - std::string(userService.m_serviceId), - std::make_unique(userService, m_proxyDepsMap.at(userService.m_serviceId)))); + m_serviceMap.emplace(std::make_pair( + std::string(userService.m_serviceId), + std::make_unique(userService, m_proxyDepsMap.at(userService.m_serviceId)))); } void ServiceHandler::buildServiceProxy(RoutineService& userService) { - m_serviceMap.emplace(std::make_pair( - std::string(userService.m_serviceId), - std::make_unique(userService, m_proxyDepsMap.at(userService.m_serviceId)))); + m_serviceMap.emplace(std::make_pair( + std::string(userService.m_serviceId), + std::make_unique(userService, m_proxyDepsMap.at(userService.m_serviceId)))); } auto ServiceHandler::getProxyState(std::string serviceId) -> nlohmann::json @@ -43,9 +43,9 @@ auto ServiceHandler::getAllProxyState() -> nlohmann::json return allStates; } -void ServiceHandler::run() { - - for (auto& [serviceId , proxy] : m_serviceMap) { +void ServiceHandler::run() +{ + for (auto& [serviceId, proxy] : m_serviceMap) { proxy->m_proxyConfigs.changeDep("THIS", ServiceProxy::ServiceState::RUNNING); proxy->autoUpdate(); } diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index 457fd35..593db5a 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -13,8 +13,6 @@ class ServiceHandler { explicit ServiceHandler(nlohmann::json servicesConfigs); protected: - friend class Tester; - std::map> m_serviceMap; std::map> m_proxyDepsMap; From 36962f6c278440b1b1a2d7c2f605ab2315d585b9 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 15 Nov 2021 21:36:17 -0300 Subject: [PATCH 107/147] CMakeLists: Erases commented lines Some unused classes were commented because they're not used on the compilation of the "service-classes", such as "daemon" and "config-handler", so this commit erases this lines to improve clarity. --- CMakeLists.txt | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 08034ad..9926a98 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,25 +46,23 @@ endmacro(ZFKD_CREATE_DICT) #------------------ set(ZFKD_CLASSES - - #daemon - service-handler - service-proxy + + daemon + service-handler + service-proxy static-service-proxy routine-service-proxy ) set(ZFKD_UTILITIES - - #dbus-handler - #config-handler - #locked-storage + + dbus-handler + config-handler + locked-storage ) set(ZFKD_PUBLIC_CLASSES - - #daemon - #service + daemon ) set(ZFKD_PUBLIC_UTILITIES @@ -207,8 +205,7 @@ endif() # It will persist until the maintainer solve problems with outside inclusion by "include_subdirectory" mode. # # -#add_executable(sample ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) - -#target_link_libraries(sample ${CONAN_LIBS} frameworkd) +# add_executable(sample ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) +# target_link_libraries(sample ${CONAN_LIBS} frameworkd) From de5615b51d101bf39a532794f411148e350a8a20 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 29 Nov 2021 01:30:08 -0300 Subject: [PATCH 108/147] ServiceProxy: Hotfix - turns enums into public members A quick Hotfix to available the usage of some methods from ServiceHandler that requires access to the enums that specify the types of the proxy's states. --- src/classes/service-proxy/service-proxy.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index 23a59f7..1a65584 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -6,7 +6,7 @@ #include class ServiceProxy { -protected: +public: friend class ServiceHandler; enum proxy_t { STATIC_SERVICE = 0, @@ -31,7 +31,7 @@ class ServiceProxy { virtual void allFine() { } [[nodiscard]] auto getState() const -> state_t; }; - +protected: class ProxyConfigs { public: struct Dependency { From 307c7f77ea96b00af30ba5436d9ee29d19fa1801 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 29 Nov 2021 01:41:59 -0300 Subject: [PATCH 109/147] ServiceHandler: Implements methods to change proxys dependencies New methods of the ServiceHandler class were required to allow unit testing of the collection of service classes. This methods simply provides an API to change the dependencies states of each proxy stored inside the ServiceHandler. --- .../service-handler/service-handler.cpp | 47 ++++++++++++++++++- .../service-handler/service-handler.hpp | 4 ++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index 8310376..e8b1e79 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -28,7 +28,17 @@ void ServiceHandler::buildServiceProxy(RoutineService& userService) auto ServiceHandler::getProxyState(std::string serviceId) -> nlohmann::json { - nlohmann::json requiredState = m_serviceMap.at(serviceId)->reportState(); + nlohmann::json requiredState; + + try { + requiredState = m_serviceMap.at(serviceId)->reportState(); + } catch (const std::out_of_range) { + std::string errorMessage = "Get dependency state request from a not built service! Unknown Service = "; + errorMessage.append(serviceId); + + throw std::invalid_argument(errorMessage); + } + return requiredState; } @@ -43,6 +53,41 @@ auto ServiceHandler::getAllProxyState() -> nlohmann::json return allStates; } +void ServiceHandler::changeDependencyState(std::string serviceId, std::string dependencyId, ServiceProxy::ServiceState::state_t newState) +{ + if (dependencyId == "THIS") { + throw std::invalid_argument("THIS is a specially reserved dependency and don't accept outside changes of its state"); + } + + try { + m_serviceMap.at(serviceId)->m_proxyConfigs.changeDep(dependencyId, newState); + } catch (const std::out_of_range) { + std::string errorMessage = "Change dependency state request from a not built service! Unknown Service = "; + errorMessage.append(serviceId); + + throw std::invalid_argument(errorMessage); + } +} + +void ServiceHandler::updateServiceProxy(std::string serviceId) +{ + try { + m_serviceMap.at(serviceId)->autoUpdate(); + } catch (const std::out_of_range) { + std::string errorMessage = "Update request from a not built service! Unknown Service = "; + errorMessage.append(serviceId); + + throw std::invalid_argument(errorMessage); + } +} + +void ServiceHandler::updateAllServiceProxys() +{ + for (auto& [serviceId, proxy] : m_serviceMap) { + proxy->autoUpdate(); + } +} + void ServiceHandler::run() { for (auto& [serviceId, proxy] : m_serviceMap) { diff --git a/src/classes/service-handler/service-handler.hpp b/src/classes/service-handler/service-handler.hpp index 593db5a..1dc205c 100644 --- a/src/classes/service-handler/service-handler.hpp +++ b/src/classes/service-handler/service-handler.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include class ServiceHandler { @@ -21,6 +22,9 @@ class ServiceHandler { auto getAllProxyState() -> nlohmann::json; void buildServiceProxy(StaticService& userService); void buildServiceProxy(RoutineService& userService); + void changeDependencyState(std::string serviceId, std::string dependencyId, ServiceProxy::ServiceState::state_t newState); + void updateServiceProxy(std::string serviceId); + void updateAllServiceProxys(); void run(); }; From 0c53c7558f67f1a89f5f3a31483e76e471819a47 Mon Sep 17 00:00:00 2001 From: Carlos Henrique Craveiro Aquino Veras <85318248+CarlosCraveiro@users.noreply.github.com> Date: Mon, 29 Nov 2021 13:49:24 -0300 Subject: [PATCH 110/147] ServiceHandler: Improves syntax MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adopts the overload of the "+" operator to concatenate two strings instead of using ".append()". Co-authored-by: MaĂ­ra Canal <61601791+mairacanal@users.noreply.github.com> --- src/classes/service-handler/service-handler.cpp | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index e8b1e79..fbf4157 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -28,18 +28,13 @@ void ServiceHandler::buildServiceProxy(RoutineService& userService) auto ServiceHandler::getProxyState(std::string serviceId) -> nlohmann::json { - nlohmann::json requiredState; - try { - requiredState = m_serviceMap.at(serviceId)->reportState(); + return m_serviceMap.at(serviceId)->reportState(); } catch (const std::out_of_range) { - std::string errorMessage = "Get dependency state request from a not built service! Unknown Service = "; - errorMessage.append(serviceId); + std::string errorMessage = "Get dependency state request from a not built service! Unknown Service = " + serviceId; throw std::invalid_argument(errorMessage); } - - return requiredState; } auto ServiceHandler::getAllProxyState() -> nlohmann::json @@ -62,8 +57,7 @@ void ServiceHandler::changeDependencyState(std::string serviceId, std::string de try { m_serviceMap.at(serviceId)->m_proxyConfigs.changeDep(dependencyId, newState); } catch (const std::out_of_range) { - std::string errorMessage = "Change dependency state request from a not built service! Unknown Service = "; - errorMessage.append(serviceId); + std::string errorMessage = "Change dependency state request from a not built service! Unknown Service = " + serviceId; throw std::invalid_argument(errorMessage); } @@ -74,8 +68,7 @@ void ServiceHandler::updateServiceProxy(std::string serviceId) try { m_serviceMap.at(serviceId)->autoUpdate(); } catch (const std::out_of_range) { - std::string errorMessage = "Update request from a not built service! Unknown Service = "; - errorMessage.append(serviceId); + std::string errorMessage = "Update request from a not built service! Unknown Service = " + serviceId; throw std::invalid_argument(errorMessage); } From 25e6d0acbc8e7c4f6746bc6212f21f03b02f3188 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Tue, 16 Nov 2021 20:36:59 -0300 Subject: [PATCH 111/147] template: add the raw template from https://github.com/zenitheesc/modern-cpp-template --- CMakeLists.txt | 452 +++++++++++++++++++++++----------- CONTRIBUTING.md | 203 +++++++++++++++ PULL_REQUEST_TEMPLATE.md | 72 ++++++ cmake/CompilerWarnings.cmake | 99 ++++++++ cmake/Conan.cmake | 46 ++++ cmake/Doxygen.cmake | 11 + cmake/ProjectConfig.cmake.in | 9 + cmake/SourcesAndHeaders.cmake | 16 ++ cmake/StandardSettings.cmake | 89 +++++++ cmake/StaticAnalyzers.cmake | 20 ++ cmake/Utils.cmake | 40 +++ cmake/Vcpkg.cmake | 20 ++ cmake/version.hpp.in | 11 + include/project/tmp.hpp | 9 + src/tmp.cpp | 3 + test/CMakeLists.txt | 84 +++++++ test/src/tmp_test.cpp | 15 ++ 17 files changed, 1049 insertions(+), 150 deletions(-) create mode 100644 CONTRIBUTING.md create mode 100644 PULL_REQUEST_TEMPLATE.md create mode 100644 cmake/CompilerWarnings.cmake create mode 100644 cmake/Conan.cmake create mode 100644 cmake/Doxygen.cmake create mode 100644 cmake/ProjectConfig.cmake.in create mode 100644 cmake/SourcesAndHeaders.cmake create mode 100644 cmake/StandardSettings.cmake create mode 100644 cmake/StaticAnalyzers.cmake create mode 100644 cmake/Utils.cmake create mode 100644 cmake/Vcpkg.cmake create mode 100644 cmake/version.hpp.in create mode 100644 include/project/tmp.hpp create mode 100644 src/tmp.cpp create mode 100644 test/CMakeLists.txt create mode 100644 test/src/tmp_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9926a98..d0d903a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,211 +1,363 @@ -#------------------------------- -# PROJECT INFORMATION -#------------------------------- +cmake_minimum_required(VERSION 3.15) -cmake_minimum_required(VERSION 3.16.3) -project(frameworkd VERSION 0.1 LANGUAGES CXX) - -include(GNUInstallDirs) # Installation directories for `install` command and pkgconfig file +# +# Project details +# -#------------------------------- -# PROJECT MACROS DEFINITION -#------------------------------- +project( + "Project" + VERSION 0.1.0 + LANGUAGES CXX +) -macro(ZFKD_ADD_DEPS_FILEPATHS_TO outputList baseDir subDir depsList fileExt) - - foreach(dependency IN LISTS ${depsList}) - list(APPEND ${outputList} ${baseDir}/${subDir}/${dependency}/${dependency}.${fileExt}) - endforeach() +# +# Set project options +# -endmacro(ZFKD_ADD_DEPS_FILEPATHS_TO) +include(cmake/StandardSettings.cmake) +include(cmake/StaticAnalyzers.cmake) +include(cmake/Utils.cmake) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Debug") +endif() +message(STATUS "Started CMake for ${PROJECT_NAME} v${PROJECT_VERSION}...\n") +if (UNIX) + add_compile_options("$<$:-D_DEBUG>") #this will allow to use same _DEBUG macro available in both Linux as well as Windows - MSCV environment. Easy to put Debug specific code. +endif (UNIX) -macro(ZFKD_ADD_DEPS_DIRPATHS_TO outputList baseDir subDir depsList) - - foreach(dependency IN LISTS ${depsList}) - list(APPEND ${outputList} ${baseDir}/${subDir}/${dependency}/) - endforeach() -endmacro(ZFKD_ADD_DEPS_DIRPATHS_TO) +# +# Setup alternative names +# +if(${PROJECT_NAME}_USE_ALT_NAMES) + string(TOLOWER ${PROJECT_NAME} PROJECT_NAME_LOWERCASE) + string(TOUPPER ${PROJECT_NAME} PROJECT_NAME_UPPERCASE) +else() + set(PROJECT_NAME_LOWERCASE ${PROJECT_NAME}) + set(PROJECT_NAME_UPPERCASE ${PROJECT_NAME}) +endif() -macro(ZFKD_CREATE_DICT contentList indexList dictName) - - set(i 0) - foreach(element IN LISTS ${contentList}) - list(GET ${indexList} ${i} index) - set(${dictName}-${index} ${element}) - math(EXPR i "${i} + 1") - endforeach() +# +# Prevent building in the source directory +# -endmacro(ZFKD_CREATE_DICT) +if(PROJECT_SOURCE_DIR STREQUAL PROJECT_BINARY_DIR) + message(FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there.\n") +endif() +# +# Enable package managers +# -#------------------ -# SET SOURCE FILES -#------------------ +include(cmake/Conan.cmake) +include(cmake/Vcpkg.cmake) -set(ZFKD_CLASSES - - daemon - service-handler - service-proxy - static-service-proxy - routine-service-proxy -) +# +# Create library, setup header and source files +# -set(ZFKD_UTILITIES +# Find all headers and implementation files +include(cmake/SourcesAndHeaders.cmake) - dbus-handler - config-handler - locked-storage -) +if(${PROJECT_NAME}_BUILD_EXECUTABLE) + add_executable(${PROJECT_NAME} ${exe_sources}) -set(ZFKD_PUBLIC_CLASSES - daemon -) + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + verbose_message("Found the following sources:") + foreach(source IN LISTS exe_sources) + verbose_message("* ${source}") + endforeach() + endif() + + if(${PROJECT_NAME}_ENABLE_UNIT_TESTING) + add_library(${PROJECT_NAME}_LIB ${headers} ${sources}) + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + verbose_message("Found the following headers:") + foreach(header IN LISTS headers) + verbose_message("* ${header}") + endforeach() + endif() + endif() +elseif(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + add_library(${PROJECT_NAME} INTERFACE) + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + verbose_message("Found the following headers:") + foreach(header IN LIST headers) + verbose_message("* ${header}") + endforeach() + endif() +else() + add_library( + ${PROJECT_NAME} + ${headers} + ${sources} + ) + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + verbose_message("Found the following sources:") + foreach(source IN LISTS sources) + verbose_message("* ${source}") + endforeach() + verbose_message("Found the following headers:") + foreach(header IN LISTS headers) + verbose_message("* ${header}") + endforeach() + endif() +endif() -set(ZFKD_PUBLIC_UTILITIES - +set_target_properties( + ${PROJECT_NAME} + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}" ) +if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) + set_target_properties( + ${PROJECT_NAME}_LIB + PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}" + OUTPUT_NAME ${PROJECT_NAME} + ) +endif() -#---------------------------- -# SOURCE FILES CONFIGURATION -#---------------------------- +message(STATUS "Added all header and implementation files.\n") -set(ZFKD_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) -set(ZFKD_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include) -set(ZFKD_UTIL_SUBDIR utilities) -set(ZFKD_CLSS_SUBDIR classes) +# +# Set the project standard and warnings +# -set(ZFKD_CPP_SRCS) +if(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + target_compile_features(${PROJECT_NAME} INTERFACE cxx_std_17) +else() + target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17) -ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_CPP_SRCS ${ZFKD_SRC_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_CLASSES cpp) -ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_CPP_SRCS ${ZFKD_SRC_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_UTILITIES cpp) + if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) + target_compile_features(${PROJECT_NAME}_LIB PUBLIC cxx_std_17) + endif() +endif() +include(cmake/CompilerWarnings.cmake) +set_project_warnings(${PROJECT_NAME}) -set(ZFKD_HDR_SRCS) +verbose_message("Applied compiler warnings. Using standard ${CMAKE_CXX_STANDARD}.\n") -ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_HDR_SRCS ${ZFKD_SRC_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_CLASSES hpp) -ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_HDR_SRCS ${ZFKD_SRC_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_UTILITIES hpp) +# +# Enable Doxygen +# -set(ZFKD_PUBLIC_HDRS) +include(cmake/Doxygen.cmake) -ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_PUBLIC_HDRS ${ZFKD_INCLUDE_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_PUBLIC_CLASSES hpp) -ZFKD_ADD_DEPS_FILEPATHS_TO(ZFKD_PUBLIC_HDRS ${ZFKD_INCLUDE_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_PUBLIC_UTILITIES hpp) +# +# Model project dependencies +# -set(ZFKD_SRCS ${ZFKD_CPP_SRCS} ${ZFKD_HDR_SRCS} ${ZFKD_PUBLIC_HDRS}) +# Identify and link with the specific "packages" the project uses +#find_package(package_name package_version REQUIRED package_type [other_options]) +#target_link_libraries( +# ${PROJECT_NAME} +# PUBLIC +# dependency1 ... +# PRIVATE +# dependency2 ... +# ${PROJECT_NAME}_PROJECT_OPTIONS +# ${PROJECT_NAME}_PROJECT_WARNINGS +#) +#if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) +# target_link_libraries( +# ${PROJECT_NAME}_LIB +# PUBLIC +# dependency1 ... +# ) +#endif() + +# For Windows, it is necessary to link with the MultiThreaded library. +# Depending on how the rest of the project's dependencies are linked, it might be necessary +# to change the line to statically link with the library. +# +# This is done as follows: +# +# set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +# +# On Linux and Mac this variable is ignored. If any issues rise from it, try commenting it out +# and letting CMake decide how to link with it. +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>DLL") -#------------------------------- -# GENERAL COMPILER CONFIGURATION -#------------------------------- +verbose_message("Successfully added all dependencies and linked against them.") -set(CMAKE_CXX_STANDARD 17) +# +# Set the build/user include directories +# -set(CMAKE_CXX_FLAGS "-pthread ${CMAKE_CXX_FLAGS}") +# Allow usage of header files in the `src` directory, but only for utilities +if(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ + ) +else() + target_include_directories( + ${PROJECT_NAME} + PUBLIC + $ + $ + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) + target_include_directories( + ${PROJECT_NAME}_LIB + PUBLIC + $ + $ + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + endif() +endif() -#----------------------------------- -# INCLUDE CONAN SETINGS FOR DEVELOPERS -#----------------------------------- +message(STATUS "Finished setting up include directories.") -option(ZFKD_USING_CONAN_FOR_DEV "(default ON)" ON) +# +# Provide alias to library for +# -if(ZFKD_USING_CONAN_FOR_DEV) - include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) - conan_basic_setup() +if(${PROJECT_NAME}_BUILD_EXECUTABLE) + add_executable(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME}) +else() + add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME}) endif() -#---------------------------------- -# LIBRARY BUILD INFORMATION -#---------------------------------- +verbose_message("Project is now aliased as ${PROJECT_NAME}::${PROJECT_NAME}.\n") -set(ZFKD_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}") -set(ZFKD_VERSION "${PROJECT_VERSION}") +# +# Format the project using the `clang-format` target (i.e: cmake --build build --target clang-format) +# -set(ZFKD_SRC_DIRS) -ZFKD_ADD_DEPS_DIRPATHS_TO(ZFKD_SRC_DIRS ${ZFKD_SRC_DIR} ${ZFKD_CLSS_SUBDIR} ZFKD_CLASSES) -ZFKD_ADD_DEPS_DIRPATHS_TO(ZFKD_SRC_DIRS ${ZFKD_SRC_DIR} ${ZFKD_UTIL_SUBDIR} ZFKD_UTILITIES) +add_clang_format_target() -ZFKD_CREATE_DICT(ZFKD_SRC_DIRS ZFKD_DEPS ZFKD_DIR) +# +# Install library for easy downstream inclusion +# -add_library(frameworkd-objlib OBJECT ${ZFKD_SRCS}) -target_compile_definitions(frameworkd-objlib PRIVATE BUILD_LIB=1) +include(GNUInstallDirs) +install( + TARGETS + ${PROJECT_NAME} + EXPORT + ${PROJECT_NAME}Targets + LIBRARY DESTINATION + ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION + ${CMAKE_INSTALL_BINDIR} + ARCHIVE DESTINATION + ${CMAKE_INSTALL_LIBDIR} + INCLUDES DESTINATION + include + PUBLIC_HEADER DESTINATION + include +) -target_include_directories(frameworkd-objlib PUBLIC - - $ - $ - $ - $ - $ - $ - $ +install( + EXPORT + ${PROJECT_NAME}Targets + FILE + ${PROJECT_NAME}Targets.cmake + NAMESPACE + ${PROJECT_NAME}:: + DESTINATION + ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} ) -if(DEFINED BUILD_SHARED_LIBS) - set_target_properties(frameworkd-objlib PROPERTIES POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS}) -endif() +# +# Add version header +# -add_library(frameworkd) -target_include_directories(frameworkd PUBLIC - - $ - $ - $ - $ - $ - $ - $ - $ +configure_file( + ${CMAKE_CURRENT_LIST_DIR}/cmake/version.hpp.in + include/${PROJECT_NAME_LOWERCASE}/version.hpp + @ONLY ) -set_target_properties(frameworkd - - PROPERTIES PUBLIC_HEADER "${ZFKD_PUBLIC_HDRS}" - VERSION "${ZFKD_VERSION}" - OUTPUT_NAME "frameworkd" +install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/include/${PROJECT_NAME_LOWERCASE}/version.hpp + DESTINATION + include/${PROJECT_NAME_LOWERCASE} ) -if(ZFKD_USING_CONAN_FOR_DEV) - - target_link_libraries(frameworkd PRIVATE frameworkd-objlib ${CONANLIBS}) - -else() - - target_link_libraries(frameworkd PRIVATE frameworkd-objlib) +# +# Install the `include` directory +# -endif() +install( + DIRECTORY + include/${PROJECT_NAME_LOWERCASE} + DESTINATION + include +) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +verbose_message("Install targets succesfully build. Install with `cmake --build --target install --config `.") -#---------------------------------- -# INSTALLATION -#---------------------------------- +# +# Quick `ConfigVersion.cmake` creation +# -# COMMING SOON... +include(CMakePackageConfigHelpers) +write_basic_package_version_file( + ${PROJECT_NAME}ConfigVersion.cmake + VERSION + ${PROJECT_VERSION} + COMPATIBILITY + SameMajorVersion +) +configure_package_config_file( + ${CMAKE_CURRENT_LIST_DIR}/cmake/${PROJECT_NAME}Config.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + INSTALL_DESTINATION + ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) -#---------------------------------- -# TESTS -#---------------------------------- +install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + DESTINATION + ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) -option(BUILD_TESTS "Build and install tests (default OFF)" OFF) +# +# Generate export header if specified +# -if(BUILD_TESTS) - message(STATUS "Building with tests") - enable_testing() - add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/tests") +if(${PROJECT_NAME}_GENERATE_EXPORT_HEADER) + include(GenerateExportHeader) + generate_export_header(${PROJECT_NAME}) + install( + FILES + ${PROJECT_BINARY_DIR}/${PROJECT_NAME_LOWERCASE}_export.h + DESTINATION + include + ) + + message(STATUS "Generated the export header `${PROJECT_NAME_LOWERCASE}_export.h` and installed it.") endif() +message(STATUS "Finished building requirements for installing the package.\n") -#------ -# BIN -#------ -# Uncoment this section to build your binnaries with this CMake -# NOTE: This section is temporary!! -# It will persist until the maintainer solve problems with outside inclusion by "include_subdirectory" mode. # +# Unit testing setup # -# add_executable(sample ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) -# target_link_libraries(sample ${CONAN_LIBS} frameworkd) - +if(${PROJECT_NAME}_ENABLE_UNIT_TESTING) + enable_testing() + message(STATUS "Build unit tests for the project. Tests should always be found in the test folder\n") + add_subdirectory(test) +endif() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..8743dc3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,203 @@ +# Contributing to [INSERT PROJECT NAME] + +The [INSERT PROJECT NAME] team encourages community feedback and contributions. +Thank you for your interest in making [INSERT PROJECT NAME] better! There are several +ways you can get involved. + +If you are looking for a good way to contribute to the project, please: + +* have a look at the [available issue templates](https://github.com/filipdutescu/modern-cpp-template/issues/new/choose) +and checkout the [examples of good first issues](https://github.com/filipdutescu/modern-cpp-template/contribute) +(or [click here](https://github.com/filipdutescu/modern-cpp-template/labels/good%20first%20issue)). + +* look through the [issues that need help](https://github.com/filipdutescu/modern-cpp-template/labels/help%20wanted). + +* take a look at a [Pull Request template](PULL_REQUEST_TEMPLATE.md) to get yourself +started. + +## Reporting issues and suggesting new features + +If you find that the project is not working properly, please file a report using +the [Bug Report template](https://github.com/filipdutescu/modern-cpp-template/issues/new?assignees=&labels=bug&template=bug_report.md&title=[BUG]). +Should the template provided not suit your needs, feel free to make a +[custom Bug Report](https://github.com/filipdutescu/modern-cpp-template/issues/new/choose), +but please label it accordingly. + +We are happy to hear your ideas for how to further improve [INSERT PROJECT NAME], +ensuring it suits your needs. Check the [Issues](https://github.com/filipdutescu/modern-cpp-template/issues) +and see if others have submitted similar feedback. You can upvote existing feedback +(using the thumbs up reaction/by commenting) or [submit a new suggestion](https://github.com/filipdutescu/modern-cpp-template/labels/feature). + +We always look at upvoted items in [Issues](https://github.com/filipdutescu/modern-cpp-template/issues) +when we decide what to work on next. We read the comments and we look forward to +hearing your input. + +## Finding issues you can help with + +Looking for something to work on? +Issues marked [`good first issue`](https://github.com/filipdutescu/modern-cpp-template/labels/good%20first%20issue) +are a good place to start. + +You can also check the [`help wanted`](https://github.com/filipdutescu/modern-cpp-template/labels/help%20wanted) +tag to find other issues to help with. If you're interested in working on a fix, +leave a comment to let everyone know and to help avoid duplicated effort from others. + +## Contributions we accept + +We highly appreciate any contributions that help us improve the end product, with +a high emphasis being put on any bug fixes you can manage to create and direct +improvements which address the top issues reported by Calculator users. Some general +guidelines: + +### DOs + +* **DO** create one pull request per Issue, and ensure that the Issue is linked +in the pull request. You can follow the [Pull Request Template](PULL_REQUEST_TEMPLATE.md) +for this. + +* **DO** follow our [Coding and Style](#style-guidelines) guidelines, and keep code +changes as small as possible. + +* **DO** include corresponding tests whenever possible. + +* **DO** check for additional occurrences of the same problem in other parts of the +codebase before submitting your PR. + +* **DO** link the issue you are addressing in the pull request. + +* **DO** write a good description for your pull request. More detail is better. +Describe *why* the change is being made and *why* you have chosen a particular solution. +Describe any manual testing you performed to validate your change. + +### DO NOTs + +* **DO NOT** merge multiple changes into one PR unless they have the same root cause. +* **DO NOT** merge directly into the master branch. + +> Submitting a pull request for an approved Issue is not a guarantee it will be approved. +> The change must meet our high bar for code quality, architecture and performance. + +## Making changes to the code + +### Preparing your development environment + +To learn how to build the code and run tests, follow the instructions in the [README](README.md). + +### Style guidelines + +The code in this project uses several different coding styles, depending on the +age and history of the code. Please attempt to match the style of surrounding +code as much as possible. In new components, prefer the patterns described in the +[C++ core guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines). + +### Code formatting + +***Run clang-format*** + +Use the following commands from the project's root directory to run clang-format +(must be installed on the host system). + +**1. Run the CMake target for `clang-format`:** + +```bash +cmake --build build --target clang-format +``` + +**2. Using clang-format:** + +```bash +# !!! clang-format does not run recursively in subdirectories !!! +# for each .cpp file modified +clang-format -i *.cpp + +# for each .h file modified +clang-format -i *.h + +# for each .hpp file modified +clang-format -i *.hpp +``` + +**3. Using TheLartians' Format.cmake:** + +```bash +cmake -Htest -Bbuild/test + +# view changes +cmake --build build/test --target format + +# apply changes +cmake --build build/test --target fix-format +``` + +See [Format.cmake](https://github.com/TheLartians/Format.cmake) for more options. + +### Testing + +Your change should include tests to verify new functionality wherever possible. +Code should be structured so that it can be unit tested independently of the UI. +Manual test cases should be used where automated testing is not feasible. + +### Git workflow + +The core principle of the project, when it comes to Git workflows is that the +`master` branch should always be in a healthy state which is ready for release. +Every commit on master should be deployable on push. To ensure this, pull request +**must not** be made directly on master. **Each change** should either be made in +the **development branch** (named a variation of development, i.e. `dev`) or in a +separate branch, named as a short summary of the change. + +If your change is complex, please clean up the branch history before submitting a +pull request. You can use [git rebase](https://git-scm.com/book/en/v2/Git-Branching-Rebasing) +to group your changes into a small number of commits which we can review one at a +time. + +When completing a pull request, we will generally squash your changes into a single +commit. After confirming that the change works as intended, the branch *might* be +deleted, in order to prevent branch polluting. Please let us know if your pull request +needs to be merged as separate commits. + +### Continuous Integration + +For this project, CI is provided by [GitHub Actions](https://github.com/features/actions), +with workflows found in the [`.github/workflows` folder](.github/workflows). Workflows +are run automatically on every commit made on the master branch, unless told to skip +for that particular commit. + +To skip CI runs on a particular commit, include either `[skip ci]` or `[ci skip]` +in the commit message. + +```bash +# an example of a commit message that would not trigger CI workflows +git commit -m "my normal commit message [skip ci]" +# or +git commit -m "my normal commit message [ci skip]" +``` + +## Review process + +After submitting a pull request, members of the team will review your code. We will +assign the request to an appropriate reviewer (if applicable). Any member of the +community may participate in the review, but at least one member of the project team +will ultimately approve the request. + +Often, multiple iterations or discussions will be needed to responding to feedback +from reviewers. Try looking at [past pull requests](https://github.com/filipdutescu/modern-cpp-template/pulls?q=is%3Apr+is%3Aclosed) +to see what the experience might be like. + +## Contributor License Agreement + +Before we can review and accept a pull request from you, you'll need to sign a +Contributor License Agreement (CLA). The CLA ensures that the community is free +to use your contributions. Signing the CLA is a manual process, and you need to +do it for each pull request made. This is done by checking the boxes in the +[Pull Request Readiness Checklist of a Pull Request](PULL_REQUEST_TEMPLATE.md#Pull-Request-Readiness-Checklist). + +### IMPORTANT + +***Checking the aforementioned boxes means that you agree to provide your change +and/or code FREE TO USE and SUBJECT TO CHANGES for the entire community!*** + +You don't need to sign a CLA until you're ready to create a pull request. When your +pull request is created, it is reviewed by a team member which, if the change is +trivial (i.e. you just fixed a typo) will be labelled as `cla-not-required`. +Otherwise, it's classified as `cla-required`, if not already signed. diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..85a2582 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,72 @@ +**IMPORTANT: Please do not create a Pull Request without creating an issue first.** + +*Any change needs to be discussed before proceeding. Failure to do so may result +in the rejection of the pull request.* + +Please provide enough information so that others can review your pull request. You +can skip this if you're fixing a typo or adding an app to the Showcase. + +Explain the **details** for making this change. What existing problem does the pull +request solve? + +Ex: + +1. If you "Added a/changed the function to do X", explain why: + + * it is necessary to have a way to do X. + * if there already exists a way, why is your implementation better + +2. If you "Fixed bug/error in X", explain: + + * what was the bug/error (if you already made an issue, please link to it here) + * how does your implementation fix the issue + +### Code style and formatting + +Check the [Contributors Style Guidelines section](CONTRIBUTING.md#Style-guidelines) +for how to write your code and the [Contributors Code Formatting section](CONTRIBUTING.md#Code-formatting) +for how to format your code. + +#### Closing Issues + +Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes +(if such). + +--- + +Fixes #XXXX + +## Proposed changes + +* +* +* + +## Motivation behind changes + +### Test plan + +Demonstrate the code is solid. Example: The exact commands you ran and their output, +screenshots / videos if the pull request changes UI. + +*Make sure tests pass on all of the [relevant CI workflows](https://github.com/filipdutescu/modern-cpp-template/actions).* + +### Pull Request Readiness Checklist + +See details at [CONTRIBUTING.md](https://github.com/filipdutescu/modern-cpp-template/blob/master/CONTRIBUTING.md). + +* [ ] I agree to contribute to the project under [INSERT PROJECT NAME] (Unlicense) +[License](LICENSE). + +* [ ] To the best of my knowledge, the proposed patch is not based on a code under +GPL or other license that is incompatible with [INSERT PROJECT NAME] + +* [ ] The PR is proposed to proper branch + +* [ ] There is reference to original bug report and related work + +* [ ] There is accuracy test, performance test and test data in the repository, +if applicable + +* [ ] The feature is well documented and sample code can be built with the project +CMake diff --git a/cmake/CompilerWarnings.cmake b/cmake/CompilerWarnings.cmake new file mode 100644 index 0000000..2b5d58e --- /dev/null +++ b/cmake/CompilerWarnings.cmake @@ -0,0 +1,99 @@ +# from here: +# +# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Avai +# lable.md +# Courtesy of Jason Turner + +function(set_project_warnings project_name) + set(MSVC_WARNINGS + /W4 # Baseline reasonable warnings + /w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss + # of data + /w14254 # 'operator': conversion from 'type1:field_bits' to + # 'type2:field_bits', possible loss of data + /w14263 # 'function': member function does not override any base class + # virtual member function + /w14265 # 'classname': class has virtual functions, but destructor is not + # virtual instances of this class may not be destructed correctly + /w14287 # 'operator': unsigned/negative constant mismatch + /we4289 # nonstandard extension used: 'variable': loop control variable + # declared in the for-loop is used outside the for-loop scope + /w14296 # 'operator': expression is always 'boolean_value' + /w14311 # 'variable': pointer truncation from 'type1' to 'type2' + /w14545 # expression before comma evaluates to a function which is missing + # an argument list + /w14546 # function call before comma missing argument list + /w14547 # 'operator': operator before comma has no effect; expected + # operator with side-effect + /w14549 # 'operator': operator before comma has no effect; did you intend + # 'operator'? + /w14555 # expression has no effect; expected expression with side- effect + /w14619 # pragma warning: there is no warning number 'number' + /w14640 # Enable warning on thread un-safe static member initialization + /w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may + # cause unexpected runtime behavior. + /w14905 # wide string literal cast to 'LPSTR' + /w14906 # string literal cast to 'LPWSTR' + /w14928 # illegal copy-initialization; more than one user-defined + # conversion has been implicitly applied + /permissive- # standards conformance mode for MSVC compiler. + ) + + set(CLANG_WARNINGS + -Wall + -Wextra # reasonable and standard + -Wshadow # warn the user if a variable declaration shadows one from a + # parent context + -Wnon-virtual-dtor # warn the user if a class with virtual functions has a + # non-virtual destructor. This helps catch hard to + # track down memory errors + -Wold-style-cast # warn for c-style casts + -Wcast-align # warn for potential performance problem casts + -Wunused # warn on anything being unused + -Woverloaded-virtual # warn if you overload (not override) a virtual + # function + -Wpedantic # warn if non-standard C++ is used + -Wconversion # warn on type conversions that may lose data + -Wsign-conversion # warn on sign conversions + -Wnull-dereference # warn if a null dereference is detected + -Wdouble-promotion # warn if float is implicit promoted to double + -Wformat=2 # warn on security issues around functions that format output + # (ie printf) + ) + + if (${PROJECT_NAME}_WARNINGS_AS_ERRORS) + set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror) + set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX) + endif() + + set(GCC_WARNINGS + ${CLANG_WARNINGS} + -Wmisleading-indentation # warn if indentation implies blocks where blocks + # do not exist + -Wduplicated-cond # warn if if / else chain has duplicated conditions + -Wduplicated-branches # warn if if / else branches have duplicated code + -Wlogical-op # warn about logical operations being used where bitwise were + # probably wanted + -Wuseless-cast # warn if you perform a cast to the same type + ) + + if(MSVC) + set(PROJECT_WARNINGS ${MSVC_WARNINGS}) + elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") + set(PROJECT_WARNINGS ${CLANG_WARNINGS}) + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(PROJECT_WARNINGS ${GCC_WARNINGS}) + else() + message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.") + endif() + + if(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + target_compile_options(${project_name} INTERFACE ${PROJECT_WARNINGS}) + else() + target_compile_options(${project_name} PUBLIC ${PROJECT_WARNINGS}) + endif() + + if(NOT TARGET ${project_name}) + message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.") + endif() +endfunction() diff --git a/cmake/Conan.cmake b/cmake/Conan.cmake new file mode 100644 index 0000000..b844e2a --- /dev/null +++ b/cmake/Conan.cmake @@ -0,0 +1,46 @@ +if(${PROJECT_NAME}_ENABLE_CONAN) + # + # Setup Conan requires and options here: + # + + set(${PROJECT_NAME}_CONAN_REQUIRES "") + set(${PROJECT_NAME}_CONAN_OPTIONS "") + + # + # If `conan.cmake` (from https://github.com/conan-io/cmake-conan) does not exist, download it. + # + if(NOT EXISTS "${CMAKE_BINARY_DIR}/conan.cmake") + message( + STATUS + "Downloading conan.cmake from https://github.com/conan-io/cmake-conan..." + ) + file( + DOWNLOAD "https://github.com/conan-io/cmake-conan/raw/v0.15/conan.cmake" + "${CMAKE_BINARY_DIR}/conan.cmake" + ) + message(STATUS "Cmake-Conan downloaded succesfully.") + endif() + + include(${CMAKE_BINARY_DIR}/conan.cmake) + + conan_add_remote( + NAME bincrafters + URL + https://api.bintray.com/conan/bincrafters/public-conan + ) + + conan_cmake_run( + REQUIRES + ${${PROJECT_NAME}_CONAN_REQUIRES} + OPTIONS + ${${PROJECT_NAME}_CONAN_OPTIONS} + BASIC_SETUP + CMAKE_TARGETS # Individual targets to link to + BUILD + missing + ) + + conan_basic_setup() + + verbose_message("Conan is setup and all requires have been installed.") +endif() diff --git a/cmake/Doxygen.cmake b/cmake/Doxygen.cmake new file mode 100644 index 0000000..bd6fe45 --- /dev/null +++ b/cmake/Doxygen.cmake @@ -0,0 +1,11 @@ +if(${PROJECT_NAME}_ENABLE_DOXYGEN) + set(DOXYGEN_CALLER_GRAPH YES) + set(DOXYGEN_CALL_GRAPH YES) + set(DOXYGEN_EXTRACT_ALL YES) + set(DOXYGEN_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/docs) + + find_package(Doxygen REQUIRED dot) + doxygen_add_docs(doxygen-docs ${PROJECT_SOURCE_DIR}) + + verbose_message("Doxygen has been setup and documentation is now available.") +endif() diff --git a/cmake/ProjectConfig.cmake.in b/cmake/ProjectConfig.cmake.in new file mode 100644 index 0000000..2ac739c --- /dev/null +++ b/cmake/ProjectConfig.cmake.in @@ -0,0 +1,9 @@ +set(@PROJECT_NAME@_VERSION @PROJECT_VERSION@) + +@PACKAGE_INIT@ + +set_and_check(@PROJECT_NAME@_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake") + +check_required_components(@PROJECT_NAME@) diff --git a/cmake/SourcesAndHeaders.cmake b/cmake/SourcesAndHeaders.cmake new file mode 100644 index 0000000..b637967 --- /dev/null +++ b/cmake/SourcesAndHeaders.cmake @@ -0,0 +1,16 @@ +set(sources + src/tmp.cpp +) + +set(exe_sources + src/main.cpp + ${sources} +) + +set(headers + include/project/tmp.hpp +) + +set(test_sources + src/tmp_test.cpp +) diff --git a/cmake/StandardSettings.cmake b/cmake/StandardSettings.cmake new file mode 100644 index 0000000..caa8a19 --- /dev/null +++ b/cmake/StandardSettings.cmake @@ -0,0 +1,89 @@ +# +# Project settings +# + +option(${PROJECT_NAME}_BUILD_EXECUTABLE "Build the project as an executable, rather than a library." OFF) +option(${PROJECT_NAME}_BUILD_HEADERS_ONLY "Build the project as a header-only library." OFF) +option(${PROJECT_NAME}_USE_ALT_NAMES "Use alternative names for the project, such as naming the include directory all lowercase." ON) + +# +# Compiler options +# + +option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF) + +# +# Package managers +# +# Currently supporting: Conan, Vcpkg. + +option(${PROJECT_NAME}_ENABLE_CONAN "Enable the Conan package manager for this project." OFF) +option(${PROJECT_NAME}_ENABLE_VCPKG "Enable the Vcpkg package manager for this project." OFF) + +# +# Unit testing +# +# Currently supporting: GoogleTest, Catch2. + +option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON) + +option(${PROJECT_NAME}_USE_GTEST "Use the GoogleTest project for creating unit tests." ON) +option(${PROJECT_NAME}_USE_GOOGLE_MOCK "Use the GoogleMock project for extending the unit tests." OFF) + +option(${PROJECT_NAME}_USE_CATCH2 "Use the Catch2 project for creating unit tests." OFF) + +# +# Static analyzers +# +# Currently supporting: Clang-Tidy, Cppcheck. + +option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF) +option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF) + +# +# Code coverage +# + +option(${PROJECT_NAME}_ENABLE_CODE_COVERAGE "Enable code coverage through GCC." OFF) + +# +# Doxygen +# + +option(${PROJECT_NAME}_ENABLE_DOXYGEN "Enable Doxygen documentation builds of source." OFF) + +# +# Miscelanious options +# + +# Generate compile_commands.json for clang based tools +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +option(${PROJECT_NAME}_VERBOSE_OUTPUT "Enable verbose output, allowing for a better understanding of each step taken." ON) +option(${PROJECT_NAME}_GENERATE_EXPORT_HEADER "Create a `project_export.h` file containing all exported symbols." OFF) + +# Export all symbols when building a shared library +if(BUILD_SHARED_LIBS) + set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF) + set(CMAKE_CXX_VISIBILITY_PRESET hidden) + set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) +endif() + +option(${PROJECT_NAME}_ENABLE_LTO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)." OFF) +if(${PROJECT_NAME}_ENABLE_LTO) + include(CheckIPOSupported) + check_ipo_supported(RESULT result OUTPUT output) + if(result) + set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) + else() + message(SEND_ERROR "IPO is not supported: ${output}.") + endif() +endif() + + +option(${PROJECT_NAME}_ENABLE_CCACHE "Enable the usage of Ccache, in order to speed up rebuild times." ON) +find_program(CCACHE_FOUND ccache) +if(CCACHE_FOUND) + set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) + set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) +endif() diff --git a/cmake/StaticAnalyzers.cmake b/cmake/StaticAnalyzers.cmake new file mode 100644 index 0000000..10e4da4 --- /dev/null +++ b/cmake/StaticAnalyzers.cmake @@ -0,0 +1,20 @@ +if(${PROJECT_NAME}_ENABLE_CLANG_TIDY) + find_program(CLANGTIDY clang-tidy) + if(CLANGTIDY) + set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option) + message("Clang-Tidy finished setting up.") + else() + message(SEND_ERROR "Clang-Tidy requested but executable not found.") + endif() +endif() + +if(${PROJECT_NAME}_ENABLE_CPPCHECK) + find_program(CPPCHECK cppcheck) + if(CPPCHECK) + set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all + --inline-suppr --inconclusive -i ${CMAKE_SOURCE_DIR}/imgui/lib) + message("Cppcheck finished setting up.") + else() + message(SEND_ERROR "Cppcheck requested but executable not found.") + endif() +endif() diff --git a/cmake/Utils.cmake b/cmake/Utils.cmake new file mode 100644 index 0000000..754c7cd --- /dev/null +++ b/cmake/Utils.cmake @@ -0,0 +1,40 @@ +# +# Print a message only if the `VERBOSE_OUTPUT` option is on +# + +function(verbose_message content) + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + message(STATUS ${content}) + endif() +endfunction() + +# +# Add a target for formating the project using `clang-format` (i.e: cmake --build build --target clang-format) +# + +function(add_clang_format_target) + if(NOT ${PROJECT_NAME}_CLANG_FORMAT_BINARY) + find_program(${PROJECT_NAME}_CLANG_FORMAT_BINARY clang-format) + endif() + + if(${PROJECT_NAME}_CLANG_FORMAT_BINARY) + if(${PROJECT_NAME}_BUILD_EXECUTABLE) + add_custom_target(clang-format + COMMAND ${${PROJECT_NAME}_CLANG_FORMAT_BINARY} + -i ${exe_sources} ${headers} + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) + elseif(${PROJECT_NAME}_BUILD_HEADERS_ONLY) + add_custom_target(clang-format + COMMAND ${${PROJECT_NAME}_CLANG_FORMAT_BINARY} + -i ${headers} + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) + else() + add_custom_target(clang-format + COMMAND ${${PROJECT_NAME}_CLANG_FORMAT_BINARY} + -i ${sources} ${headers} + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) + endif() + + message(STATUS "Format the project using the `clang-format` target (i.e: cmake --build build --target clang-format).\n") + endif() +endfunction() diff --git a/cmake/Vcpkg.cmake b/cmake/Vcpkg.cmake new file mode 100644 index 0000000..1c13e38 --- /dev/null +++ b/cmake/Vcpkg.cmake @@ -0,0 +1,20 @@ +if(${PROJECT_NAME}_ENABLE_VCPKG) + # + # If `vcpkg.cmake` (from https://github.com/microsoft/vcpkg) does not exist, download it. + # + if(NOT EXISTS "${CMAKE_BINARY_DIR}/vcpkg.cmake") + message( + STATUS + "Downloading `vcpkg.cmake` from https://github.com/microsoft/vcpkg..." + ) + file(DOWNLOAD "https://github.com/microsoft/vcpkg/raw/master/scripts/buildsystems/vcpkg.cmake" + "${CMAKE_BINARY_DIR}/vcpkg.cmake" + ) + message(STATUS "Vcpkg config downloaded succesfully.") + endif() + + if(${PROJECT_NAME}_VERBOSE_OUTPUT) + set(VCPKG_VERBOSE ON) + endif() + set(CMAKE_TOOLCHAIN_FILE "${CMAKE_TOOLCHAIN_FILE}" "${CMAKE_BINARY_DIR}/vcpkg.cmake") +endif() diff --git a/cmake/version.hpp.in b/cmake/version.hpp.in new file mode 100644 index 0000000..985bad6 --- /dev/null +++ b/cmake/version.hpp.in @@ -0,0 +1,11 @@ +#ifndef @PROJECT_NAME_UPPERCASE@_VERSION_H_ +#define @PROJECT_NAME_UPPERCASE@_VERSION_H_ + +#define @PROJECT_NAME_UPPERCASE@_VERSION "@PROJECT_VERSION@" + +#define @PROJECT_NAME_UPPERCASE@_MAJOR_VERSION @PROJECT_VERSION_MAJOR@ +#define @PROJECT_NAME_UPPERCASE@_MINOR_VERSION @PROJECT_VERSION_MINOR@ +#define @PROJECT_NAME_UPPERCASE@_PATCH_VERSION @PROJECT_VERSION_PATCH@ + +#endif // @PROJECT_NAME_UPPERCASE@_VERSION_H_ + diff --git a/include/project/tmp.hpp b/include/project/tmp.hpp new file mode 100644 index 0000000..a7af7ae --- /dev/null +++ b/include/project/tmp.hpp @@ -0,0 +1,9 @@ +#ifndef TMP_TMP_H_ +#define TMP_TMP_H_ + +namespace tmp +{ + int add(int, int); +} + +#endif // TMP_TMP_H_ diff --git a/src/tmp.cpp b/src/tmp.cpp new file mode 100644 index 0000000..7a4f8fe --- /dev/null +++ b/src/tmp.cpp @@ -0,0 +1,3 @@ +#include "project/tmp.hpp" + +int tmp::add(int a, int b) { return a + b; } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt new file mode 100644 index 0000000..71f07af --- /dev/null +++ b/test/CMakeLists.txt @@ -0,0 +1,84 @@ +cmake_minimum_required(VERSION 3.15) + +# +# Project details +# + +project( + ${CMAKE_PROJECT_NAME}Tests + LANGUAGES CXX +) + +verbose_message("Adding tests under ${CMAKE_PROJECT_NAME}Tests...") + +foreach(file ${test_sources}) + string(REGEX REPLACE "(.*/)([a-zA-Z0-9_ ]+)(\.cpp)" "\\2" test_name ${file}) + add_executable(${test_name}_Tests ${file}) + + # + # Set the compiler standard + # + + target_compile_features(${test_name}_Tests PUBLIC cxx_std_17) + + # + # Setup code coverage if enabled + # + + if (${CMAKE_PROJECT_NAME}_ENABLE_CODE_COVERAGE) + target_compile_options(${CMAKE_PROJECT_NAME} PUBLIC -O0 -g -fprofile-arcs -ftest-coverage) + target_link_options(${CMAKE_PROJECT_NAME} PUBLIC -fprofile-arcs -ftest-coverage) + verbose_message("Code coverage is enabled and provided with GCC.") + endif() + + # + # Load the desired unit testing framework + # + # Currently supported: GoogleTest (and GoogleMock), Catch2. + + if(${CMAKE_PROJECT_NAME}_BUILD_EXECUTABLE) + set(${CMAKE_PROJECT_NAME}_TEST_LIB ${CMAKE_PROJECT_NAME}_LIB) + else() + set(${CMAKE_PROJECT_NAME}_TEST_LIB ${CMAKE_PROJECT_NAME}) + endif() + + if(${CMAKE_PROJECT_NAME}_USE_GTEST) + find_package(GTest REQUIRED) + + if(${CMAKE_PROJECT_NAME}_USE_GOOGLE_MOCK) + set(GOOGLE_MOCK_LIBRARIES GTest::gmock GTest::gmock_main) + endif() + + target_link_libraries( + ${test_name}_Tests + PUBLIC + GTest::GTest + GTest::Main + ${GOOGLE_MOCK_LIBRARIES} + ${${CMAKE_PROJECT_NAME}_TEST_LIB} + ) + elseif(${CMAKE_PROJECT_NAME}_USE_CATCH2) + find_package(Catch2 REQUIRED) + target_link_libraries( + ${test_name}_Tests + PUBLIC + Catch2::Catch2 + ${${CMAKE_PROJECT_NAME}_TEST_LIB} + ) + else() + message(FATAL_ERROR "Unknown testing library. Please setup your desired unit testing library by using `target_link_libraries`.") + endif() + + # + # Add the unit tests + # + + add_test( + NAME + ${test_name} + COMMAND + ${test_name}_Tests + ) +endforeach() + +verbose_message("Finished adding unit tests for ${CMAKE_PROJECT_NAME}.") diff --git a/test/src/tmp_test.cpp b/test/src/tmp_test.cpp new file mode 100644 index 0000000..eb88881 --- /dev/null +++ b/test/src/tmp_test.cpp @@ -0,0 +1,15 @@ +#include "project/tmp.hpp" + +#include + +TEST(TmpAddTest, CheckValues) +{ + ASSERT_EQ(tmp::add(1, 2), 3); + EXPECT_TRUE(true); +} + +int main(int argc, char **argv) +{ + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From 544d3d2ae03a8a322454b897458ee234eae1d17d Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Tue, 16 Nov 2021 20:55:55 -0300 Subject: [PATCH 112/147] template: remove all tmp files --- cmake/SourcesAndHeaders.cmake | 4 ---- include/project/tmp.hpp | 9 --------- src/tmp.cpp | 3 --- test/src/tmp_test.cpp | 15 --------------- 4 files changed, 31 deletions(-) delete mode 100644 include/project/tmp.hpp delete mode 100644 src/tmp.cpp delete mode 100644 test/src/tmp_test.cpp diff --git a/cmake/SourcesAndHeaders.cmake b/cmake/SourcesAndHeaders.cmake index b637967..14dac3f 100644 --- a/cmake/SourcesAndHeaders.cmake +++ b/cmake/SourcesAndHeaders.cmake @@ -1,16 +1,12 @@ set(sources - src/tmp.cpp ) set(exe_sources - src/main.cpp ${sources} ) set(headers - include/project/tmp.hpp ) set(test_sources - src/tmp_test.cpp ) diff --git a/include/project/tmp.hpp b/include/project/tmp.hpp deleted file mode 100644 index a7af7ae..0000000 --- a/include/project/tmp.hpp +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef TMP_TMP_H_ -#define TMP_TMP_H_ - -namespace tmp -{ - int add(int, int); -} - -#endif // TMP_TMP_H_ diff --git a/src/tmp.cpp b/src/tmp.cpp deleted file mode 100644 index 7a4f8fe..0000000 --- a/src/tmp.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include "project/tmp.hpp" - -int tmp::add(int a, int b) { return a + b; } diff --git a/test/src/tmp_test.cpp b/test/src/tmp_test.cpp deleted file mode 100644 index eb88881..0000000 --- a/test/src/tmp_test.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "project/tmp.hpp" - -#include - -TEST(TmpAddTest, CheckValues) -{ - ASSERT_EQ(tmp::add(1, 2), 3); - EXPECT_TRUE(true); -} - -int main(int argc, char **argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} From 77cb2b57ee361fe4af3d4cda3f68c06434207b96 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Tue, 16 Nov 2021 21:10:31 -0300 Subject: [PATCH 113/147] template: change project name to Frameworkd --- CMakeLists.txt | 2 +- cmake/{ProjectConfig.cmake.in => FrameworkdConfig.cmake.in} | 0 tests/CMakeLists.txt | 6 ------ 3 files changed, 1 insertion(+), 7 deletions(-) rename cmake/{ProjectConfig.cmake.in => FrameworkdConfig.cmake.in} (100%) delete mode 100644 tests/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index d0d903a..0c88eb7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,7 +5,7 @@ cmake_minimum_required(VERSION 3.15) # project( - "Project" + Frameworkd VERSION 0.1.0 LANGUAGES CXX ) diff --git a/cmake/ProjectConfig.cmake.in b/cmake/FrameworkdConfig.cmake.in similarity index 100% rename from cmake/ProjectConfig.cmake.in rename to cmake/FrameworkdConfig.cmake.in diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt deleted file mode 100644 index b78d62c..0000000 --- a/tests/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_executable(daemon-test daemon-test.cpp ../src/classes/dbus-handler/dbus-handler.cpp) - -target_link_libraries(daemon-test ${CONAN_LIBS}) - -include(GoogleTest) -gtest_discover_tests(daemon-test) From 52ce7a203462f62a4da2a0081e74041a1135c681 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Tue, 16 Nov 2021 21:17:39 -0300 Subject: [PATCH 114/147] template: add sbus library --- CMakeLists.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0c88eb7..fccb049 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -157,16 +157,16 @@ include(cmake/Doxygen.cmake) # # Identify and link with the specific "packages" the project uses -#find_package(package_name package_version REQUIRED package_type [other_options]) -#target_link_libraries( -# ${PROJECT_NAME} +find_package(sdbus-c++ REQUIRED) +target_link_libraries( + ${PROJECT_NAME} # PUBLIC # dependency1 ... -# PRIVATE -# dependency2 ... + PRIVATE + SDBusCpp::sdbus-c++ # ${PROJECT_NAME}_PROJECT_OPTIONS # ${PROJECT_NAME}_PROJECT_WARNINGS -#) +) #if(${PROJECT_NAME}_BUILD_EXECUTABLE AND ${PROJECT_NAME}_ENABLE_UNIT_TESTING) # target_link_libraries( # ${PROJECT_NAME}_LIB From 759bc6fef827fa3f35e9d203047100a103bb863b Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Tue, 16 Nov 2021 21:28:35 -0300 Subject: [PATCH 115/147] template: add nlohmann library --- CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index fccb049..c06a0b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -158,12 +158,14 @@ include(cmake/Doxygen.cmake) # Identify and link with the specific "packages" the project uses find_package(sdbus-c++ REQUIRED) +find_package(nlohmann_json REQUIRED) target_link_libraries( ${PROJECT_NAME} # PUBLIC # dependency1 ... PRIVATE SDBusCpp::sdbus-c++ + nlohmann_json::nlohmann_json # ${PROJECT_NAME}_PROJECT_OPTIONS # ${PROJECT_NAME}_PROJECT_WARNINGS ) From cfedae1e918f459be0f9182d9d943132eb427192 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Tue, 16 Nov 2021 21:39:38 -0300 Subject: [PATCH 116/147] template: move tests to test/src --- tests/daemon-test.cpp => test/src/daemon_test.cpp | 0 tests/.gitkeep | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename tests/daemon-test.cpp => test/src/daemon_test.cpp (100%) delete mode 100644 tests/.gitkeep diff --git a/tests/daemon-test.cpp b/test/src/daemon_test.cpp similarity index 100% rename from tests/daemon-test.cpp rename to test/src/daemon_test.cpp diff --git a/tests/.gitkeep b/tests/.gitkeep deleted file mode 100644 index e69de29..0000000 From 4859d6802fc2edfc8f7a64ff04209dcbe6b118de Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Tue, 16 Nov 2021 21:50:07 -0300 Subject: [PATCH 117/147] template: add files to SourcesAndHeaders --- cmake/SourcesAndHeaders.cmake | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/cmake/SourcesAndHeaders.cmake b/cmake/SourcesAndHeaders.cmake index 14dac3f..d12b4b1 100644 --- a/cmake/SourcesAndHeaders.cmake +++ b/cmake/SourcesAndHeaders.cmake @@ -1,12 +1,30 @@ set(sources + src/utilities/config-handler/config-handler.cpp + src/classes/daemon/daemon.cpp + src/classes/static-service-proxy/static-service-proxy.cpp + src/classes/locked-storage/locked-storage.cpp + src/classes/dbus-handler/dbus-handler.cpp + src/classes/service-proxy/service-proxy.cpp + src/classes/routine-service-proxy/routine-service-proxy.cpp + src/classes/service-handler/service-handler.cpp ) set(exe_sources - ${sources} + ${sources} ) set(headers + src/utilities/config-handler/config-handler.hpp + src/classes/daemon/daemon.hpp + src/classes/iservice/iservice.hpp + src/classes/static-service-proxy/static-service-proxy.hpp + src/classes/locked-storage/locked-storage.hpp + src/classes/dbus-handler/dbus-handler.hpp + src/classes/service-proxy/service-proxy.hpp + src/classes/routine-service-proxy/routine-service-proxy.hpp + src/classes/service-handler/service-handler.hpp ) set(test_sources + src/daemon_test.cpp ) From 7f3252a800152ccd2f4b98da01e611319482eaed Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Tue, 4 Jan 2022 16:45:21 -0300 Subject: [PATCH 118/147] template: remove package managers --- CMakeLists.txt | 2 -- cmake/Conan.cmake | 46 ------------------------------------ cmake/StandardSettings.cmake | 8 ------- cmake/Vcpkg.cmake | 20 ---------------- 4 files changed, 76 deletions(-) delete mode 100644 cmake/Conan.cmake delete mode 100644 cmake/Vcpkg.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index c06a0b6..3b14d23 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,8 +51,6 @@ endif() # Enable package managers # -include(cmake/Conan.cmake) -include(cmake/Vcpkg.cmake) # # Create library, setup header and source files diff --git a/cmake/Conan.cmake b/cmake/Conan.cmake deleted file mode 100644 index b844e2a..0000000 --- a/cmake/Conan.cmake +++ /dev/null @@ -1,46 +0,0 @@ -if(${PROJECT_NAME}_ENABLE_CONAN) - # - # Setup Conan requires and options here: - # - - set(${PROJECT_NAME}_CONAN_REQUIRES "") - set(${PROJECT_NAME}_CONAN_OPTIONS "") - - # - # If `conan.cmake` (from https://github.com/conan-io/cmake-conan) does not exist, download it. - # - if(NOT EXISTS "${CMAKE_BINARY_DIR}/conan.cmake") - message( - STATUS - "Downloading conan.cmake from https://github.com/conan-io/cmake-conan..." - ) - file( - DOWNLOAD "https://github.com/conan-io/cmake-conan/raw/v0.15/conan.cmake" - "${CMAKE_BINARY_DIR}/conan.cmake" - ) - message(STATUS "Cmake-Conan downloaded succesfully.") - endif() - - include(${CMAKE_BINARY_DIR}/conan.cmake) - - conan_add_remote( - NAME bincrafters - URL - https://api.bintray.com/conan/bincrafters/public-conan - ) - - conan_cmake_run( - REQUIRES - ${${PROJECT_NAME}_CONAN_REQUIRES} - OPTIONS - ${${PROJECT_NAME}_CONAN_OPTIONS} - BASIC_SETUP - CMAKE_TARGETS # Individual targets to link to - BUILD - missing - ) - - conan_basic_setup() - - verbose_message("Conan is setup and all requires have been installed.") -endif() diff --git a/cmake/StandardSettings.cmake b/cmake/StandardSettings.cmake index caa8a19..ff7ede1 100644 --- a/cmake/StandardSettings.cmake +++ b/cmake/StandardSettings.cmake @@ -12,14 +12,6 @@ option(${PROJECT_NAME}_USE_ALT_NAMES "Use alternative names for the project, suc option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF) -# -# Package managers -# -# Currently supporting: Conan, Vcpkg. - -option(${PROJECT_NAME}_ENABLE_CONAN "Enable the Conan package manager for this project." OFF) -option(${PROJECT_NAME}_ENABLE_VCPKG "Enable the Vcpkg package manager for this project." OFF) - # # Unit testing # diff --git a/cmake/Vcpkg.cmake b/cmake/Vcpkg.cmake deleted file mode 100644 index 1c13e38..0000000 --- a/cmake/Vcpkg.cmake +++ /dev/null @@ -1,20 +0,0 @@ -if(${PROJECT_NAME}_ENABLE_VCPKG) - # - # If `vcpkg.cmake` (from https://github.com/microsoft/vcpkg) does not exist, download it. - # - if(NOT EXISTS "${CMAKE_BINARY_DIR}/vcpkg.cmake") - message( - STATUS - "Downloading `vcpkg.cmake` from https://github.com/microsoft/vcpkg..." - ) - file(DOWNLOAD "https://github.com/microsoft/vcpkg/raw/master/scripts/buildsystems/vcpkg.cmake" - "${CMAKE_BINARY_DIR}/vcpkg.cmake" - ) - message(STATUS "Vcpkg config downloaded succesfully.") - endif() - - if(${PROJECT_NAME}_VERBOSE_OUTPUT) - set(VCPKG_VERBOSE ON) - endif() - set(CMAKE_TOOLCHAIN_FILE "${CMAKE_TOOLCHAIN_FILE}" "${CMAKE_BINARY_DIR}/vcpkg.cmake") -endif() From 4e5660714196f50f575f1bc1ad59574de94f6a4a Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Thu, 10 Feb 2022 14:41:44 -0300 Subject: [PATCH 119/147] cmake: remove windows's optional variable --- CMakeLists.txt | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3b14d23..c08995e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -175,18 +175,6 @@ target_link_libraries( # ) #endif() -# For Windows, it is necessary to link with the MultiThreaded library. -# Depending on how the rest of the project's dependencies are linked, it might be necessary -# to change the line to statically link with the library. -# -# This is done as follows: -# -# set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -# -# On Linux and Mac this variable is ignored. If any issues rise from it, try commenting it out -# and letting CMake decide how to link with it. -set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>DLL") - verbose_message("Successfully added all dependencies and linked against them.") # From 6169d5261b96d3de22b919b77f50baa1857eb6c6 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Thu, 10 Feb 2022 15:00:23 -0300 Subject: [PATCH 120/147] fix: remove unnecessary files --- CONTRIBUTING.md | 203 --------------------------------------- PULL_REQUEST_TEMPLATE.md | 72 -------------- conanfile.txt | 7 -- 3 files changed, 282 deletions(-) delete mode 100644 CONTRIBUTING.md delete mode 100644 PULL_REQUEST_TEMPLATE.md delete mode 100644 conanfile.txt diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 8743dc3..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,203 +0,0 @@ -# Contributing to [INSERT PROJECT NAME] - -The [INSERT PROJECT NAME] team encourages community feedback and contributions. -Thank you for your interest in making [INSERT PROJECT NAME] better! There are several -ways you can get involved. - -If you are looking for a good way to contribute to the project, please: - -* have a look at the [available issue templates](https://github.com/filipdutescu/modern-cpp-template/issues/new/choose) -and checkout the [examples of good first issues](https://github.com/filipdutescu/modern-cpp-template/contribute) -(or [click here](https://github.com/filipdutescu/modern-cpp-template/labels/good%20first%20issue)). - -* look through the [issues that need help](https://github.com/filipdutescu/modern-cpp-template/labels/help%20wanted). - -* take a look at a [Pull Request template](PULL_REQUEST_TEMPLATE.md) to get yourself -started. - -## Reporting issues and suggesting new features - -If you find that the project is not working properly, please file a report using -the [Bug Report template](https://github.com/filipdutescu/modern-cpp-template/issues/new?assignees=&labels=bug&template=bug_report.md&title=[BUG]). -Should the template provided not suit your needs, feel free to make a -[custom Bug Report](https://github.com/filipdutescu/modern-cpp-template/issues/new/choose), -but please label it accordingly. - -We are happy to hear your ideas for how to further improve [INSERT PROJECT NAME], -ensuring it suits your needs. Check the [Issues](https://github.com/filipdutescu/modern-cpp-template/issues) -and see if others have submitted similar feedback. You can upvote existing feedback -(using the thumbs up reaction/by commenting) or [submit a new suggestion](https://github.com/filipdutescu/modern-cpp-template/labels/feature). - -We always look at upvoted items in [Issues](https://github.com/filipdutescu/modern-cpp-template/issues) -when we decide what to work on next. We read the comments and we look forward to -hearing your input. - -## Finding issues you can help with - -Looking for something to work on? -Issues marked [`good first issue`](https://github.com/filipdutescu/modern-cpp-template/labels/good%20first%20issue) -are a good place to start. - -You can also check the [`help wanted`](https://github.com/filipdutescu/modern-cpp-template/labels/help%20wanted) -tag to find other issues to help with. If you're interested in working on a fix, -leave a comment to let everyone know and to help avoid duplicated effort from others. - -## Contributions we accept - -We highly appreciate any contributions that help us improve the end product, with -a high emphasis being put on any bug fixes you can manage to create and direct -improvements which address the top issues reported by Calculator users. Some general -guidelines: - -### DOs - -* **DO** create one pull request per Issue, and ensure that the Issue is linked -in the pull request. You can follow the [Pull Request Template](PULL_REQUEST_TEMPLATE.md) -for this. - -* **DO** follow our [Coding and Style](#style-guidelines) guidelines, and keep code -changes as small as possible. - -* **DO** include corresponding tests whenever possible. - -* **DO** check for additional occurrences of the same problem in other parts of the -codebase before submitting your PR. - -* **DO** link the issue you are addressing in the pull request. - -* **DO** write a good description for your pull request. More detail is better. -Describe *why* the change is being made and *why* you have chosen a particular solution. -Describe any manual testing you performed to validate your change. - -### DO NOTs - -* **DO NOT** merge multiple changes into one PR unless they have the same root cause. -* **DO NOT** merge directly into the master branch. - -> Submitting a pull request for an approved Issue is not a guarantee it will be approved. -> The change must meet our high bar for code quality, architecture and performance. - -## Making changes to the code - -### Preparing your development environment - -To learn how to build the code and run tests, follow the instructions in the [README](README.md). - -### Style guidelines - -The code in this project uses several different coding styles, depending on the -age and history of the code. Please attempt to match the style of surrounding -code as much as possible. In new components, prefer the patterns described in the -[C++ core guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines). - -### Code formatting - -***Run clang-format*** - -Use the following commands from the project's root directory to run clang-format -(must be installed on the host system). - -**1. Run the CMake target for `clang-format`:** - -```bash -cmake --build build --target clang-format -``` - -**2. Using clang-format:** - -```bash -# !!! clang-format does not run recursively in subdirectories !!! -# for each .cpp file modified -clang-format -i *.cpp - -# for each .h file modified -clang-format -i *.h - -# for each .hpp file modified -clang-format -i *.hpp -``` - -**3. Using TheLartians' Format.cmake:** - -```bash -cmake -Htest -Bbuild/test - -# view changes -cmake --build build/test --target format - -# apply changes -cmake --build build/test --target fix-format -``` - -See [Format.cmake](https://github.com/TheLartians/Format.cmake) for more options. - -### Testing - -Your change should include tests to verify new functionality wherever possible. -Code should be structured so that it can be unit tested independently of the UI. -Manual test cases should be used where automated testing is not feasible. - -### Git workflow - -The core principle of the project, when it comes to Git workflows is that the -`master` branch should always be in a healthy state which is ready for release. -Every commit on master should be deployable on push. To ensure this, pull request -**must not** be made directly on master. **Each change** should either be made in -the **development branch** (named a variation of development, i.e. `dev`) or in a -separate branch, named as a short summary of the change. - -If your change is complex, please clean up the branch history before submitting a -pull request. You can use [git rebase](https://git-scm.com/book/en/v2/Git-Branching-Rebasing) -to group your changes into a small number of commits which we can review one at a -time. - -When completing a pull request, we will generally squash your changes into a single -commit. After confirming that the change works as intended, the branch *might* be -deleted, in order to prevent branch polluting. Please let us know if your pull request -needs to be merged as separate commits. - -### Continuous Integration - -For this project, CI is provided by [GitHub Actions](https://github.com/features/actions), -with workflows found in the [`.github/workflows` folder](.github/workflows). Workflows -are run automatically on every commit made on the master branch, unless told to skip -for that particular commit. - -To skip CI runs on a particular commit, include either `[skip ci]` or `[ci skip]` -in the commit message. - -```bash -# an example of a commit message that would not trigger CI workflows -git commit -m "my normal commit message [skip ci]" -# or -git commit -m "my normal commit message [ci skip]" -``` - -## Review process - -After submitting a pull request, members of the team will review your code. We will -assign the request to an appropriate reviewer (if applicable). Any member of the -community may participate in the review, but at least one member of the project team -will ultimately approve the request. - -Often, multiple iterations or discussions will be needed to responding to feedback -from reviewers. Try looking at [past pull requests](https://github.com/filipdutescu/modern-cpp-template/pulls?q=is%3Apr+is%3Aclosed) -to see what the experience might be like. - -## Contributor License Agreement - -Before we can review and accept a pull request from you, you'll need to sign a -Contributor License Agreement (CLA). The CLA ensures that the community is free -to use your contributions. Signing the CLA is a manual process, and you need to -do it for each pull request made. This is done by checking the boxes in the -[Pull Request Readiness Checklist of a Pull Request](PULL_REQUEST_TEMPLATE.md#Pull-Request-Readiness-Checklist). - -### IMPORTANT - -***Checking the aforementioned boxes means that you agree to provide your change -and/or code FREE TO USE and SUBJECT TO CHANGES for the entire community!*** - -You don't need to sign a CLA until you're ready to create a pull request. When your -pull request is created, it is reviewed by a team member which, if the change is -trivial (i.e. you just fixed a typo) will be labelled as `cla-not-required`. -Otherwise, it's classified as `cla-required`, if not already signed. diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 85a2582..0000000 --- a/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,72 +0,0 @@ -**IMPORTANT: Please do not create a Pull Request without creating an issue first.** - -*Any change needs to be discussed before proceeding. Failure to do so may result -in the rejection of the pull request.* - -Please provide enough information so that others can review your pull request. You -can skip this if you're fixing a typo or adding an app to the Showcase. - -Explain the **details** for making this change. What existing problem does the pull -request solve? - -Ex: - -1. If you "Added a/changed the function to do X", explain why: - - * it is necessary to have a way to do X. - * if there already exists a way, why is your implementation better - -2. If you "Fixed bug/error in X", explain: - - * what was the bug/error (if you already made an issue, please link to it here) - * how does your implementation fix the issue - -### Code style and formatting - -Check the [Contributors Style Guidelines section](CONTRIBUTING.md#Style-guidelines) -for how to write your code and the [Contributors Code Formatting section](CONTRIBUTING.md#Code-formatting) -for how to format your code. - -#### Closing Issues - -Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes -(if such). - ---- - -Fixes #XXXX - -## Proposed changes - -* -* -* - -## Motivation behind changes - -### Test plan - -Demonstrate the code is solid. Example: The exact commands you ran and their output, -screenshots / videos if the pull request changes UI. - -*Make sure tests pass on all of the [relevant CI workflows](https://github.com/filipdutescu/modern-cpp-template/actions).* - -### Pull Request Readiness Checklist - -See details at [CONTRIBUTING.md](https://github.com/filipdutescu/modern-cpp-template/blob/master/CONTRIBUTING.md). - -* [ ] I agree to contribute to the project under [INSERT PROJECT NAME] (Unlicense) -[License](LICENSE). - -* [ ] To the best of my knowledge, the proposed patch is not based on a code under -GPL or other license that is incompatible with [INSERT PROJECT NAME] - -* [ ] The PR is proposed to proper branch - -* [ ] There is reference to original bug report and related work - -* [ ] There is accuracy test, performance test and test data in the repository, -if applicable - -* [ ] The feature is well documented and sample code can be built with the project -CMake diff --git a/conanfile.txt b/conanfile.txt deleted file mode 100644 index cba8f69..0000000 --- a/conanfile.txt +++ /dev/null @@ -1,7 +0,0 @@ -[requires] -nlohmann_json/3.10.2 -sdbus-cpp/0.8.3 -gtest/cci.20210126 - -[generators] -cmake From ff12cb9ae3f8ea99c473eca53f25a375abf32f29 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Thu, 10 Feb 2022 15:03:54 -0300 Subject: [PATCH 121/147] test: remove Catch2 support --- cmake/StandardSettings.cmake | 4 +--- test/CMakeLists.txt | 10 +--------- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/cmake/StandardSettings.cmake b/cmake/StandardSettings.cmake index ff7ede1..754428d 100644 --- a/cmake/StandardSettings.cmake +++ b/cmake/StandardSettings.cmake @@ -15,15 +15,13 @@ option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." O # # Unit testing # -# Currently supporting: GoogleTest, Catch2. +# Currently supporting: GoogleTest. option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON) option(${PROJECT_NAME}_USE_GTEST "Use the GoogleTest project for creating unit tests." ON) option(${PROJECT_NAME}_USE_GOOGLE_MOCK "Use the GoogleMock project for extending the unit tests." OFF) -option(${PROJECT_NAME}_USE_CATCH2 "Use the Catch2 project for creating unit tests." OFF) - # # Static analyzers # diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 71f07af..516aa59 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -34,7 +34,7 @@ foreach(file ${test_sources}) # # Load the desired unit testing framework # - # Currently supported: GoogleTest (and GoogleMock), Catch2. + # Currently supported: GoogleTest (and GoogleMock). if(${CMAKE_PROJECT_NAME}_BUILD_EXECUTABLE) set(${CMAKE_PROJECT_NAME}_TEST_LIB ${CMAKE_PROJECT_NAME}_LIB) @@ -57,14 +57,6 @@ foreach(file ${test_sources}) ${GOOGLE_MOCK_LIBRARIES} ${${CMAKE_PROJECT_NAME}_TEST_LIB} ) - elseif(${CMAKE_PROJECT_NAME}_USE_CATCH2) - find_package(Catch2 REQUIRED) - target_link_libraries( - ${test_name}_Tests - PUBLIC - Catch2::Catch2 - ${${CMAKE_PROJECT_NAME}_TEST_LIB} - ) else() message(FATAL_ERROR "Unknown testing library. Please setup your desired unit testing library by using `target_link_libraries`.") endif() From ba97b972e616f2bd5abe3467e44e60920a46af1a Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Thu, 10 Feb 2022 15:06:08 -0300 Subject: [PATCH 122/147] static-analyzers: remove cpp check support --- cmake/StandardSettings.cmake | 3 +-- cmake/StaticAnalyzers.cmake | 11 ----------- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/cmake/StandardSettings.cmake b/cmake/StandardSettings.cmake index 754428d..7b7bedc 100644 --- a/cmake/StandardSettings.cmake +++ b/cmake/StandardSettings.cmake @@ -25,10 +25,9 @@ option(${PROJECT_NAME}_USE_GOOGLE_MOCK "Use the GoogleMock project for extending # # Static analyzers # -# Currently supporting: Clang-Tidy, Cppcheck. +# Currently supporting: Clang-Tidy. option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF) -option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF) # # Code coverage diff --git a/cmake/StaticAnalyzers.cmake b/cmake/StaticAnalyzers.cmake index 10e4da4..7943ab4 100644 --- a/cmake/StaticAnalyzers.cmake +++ b/cmake/StaticAnalyzers.cmake @@ -7,14 +7,3 @@ if(${PROJECT_NAME}_ENABLE_CLANG_TIDY) message(SEND_ERROR "Clang-Tidy requested but executable not found.") endif() endif() - -if(${PROJECT_NAME}_ENABLE_CPPCHECK) - find_program(CPPCHECK cppcheck) - if(CPPCHECK) - set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all - --inline-suppr --inconclusive -i ${CMAKE_SOURCE_DIR}/imgui/lib) - message("Cppcheck finished setting up.") - else() - message(SEND_ERROR "Cppcheck requested but executable not found.") - endif() -endif() From ca7ccaf96952c470a79799292c20cdcfe6d2ee49 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Thu, 10 Feb 2022 19:57:16 -0300 Subject: [PATCH 123/147] fix: ignore doxygen directorie --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 193da6a..1346eeb 100644 --- a/.gitignore +++ b/.gitignore @@ -1038,3 +1038,6 @@ modules.order Module.symvers Mkfile.old dkms.conf + +# Doxygen dir +docs/html/ From ebd4a32a76036ab4e05914e09f5d356450314ca8 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Fri, 18 Feb 2022 16:52:31 -0300 Subject: [PATCH 124/147] config-handler: add a method to retrieve all the config --- src/utilities/config-handler/config-handler.cpp | 7 ++++++- src/utilities/config-handler/config-handler.hpp | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/utilities/config-handler/config-handler.cpp b/src/utilities/config-handler/config-handler.cpp index 8371e0c..d8d4f65 100644 --- a/src/utilities/config-handler/config-handler.cpp +++ b/src/utilities/config-handler/config-handler.cpp @@ -46,7 +46,7 @@ void ConfigHandler::read(const std::string& fileName) /** * @brief Gets a value from the json object - * @param field Field to get the value + * @param field Field to get the value */ auto ConfigHandler::getConfig(const std::string& field) const -> const nlohmann::json { @@ -60,3 +60,8 @@ auto ConfigHandler::operator[](const std::string& field) const -> const nlohmann { return getConfig(field); } + +auto ConfigHandler::getAllConfig() const -> const nlohmann::json +{ + return m_config; +} diff --git a/src/utilities/config-handler/config-handler.hpp b/src/utilities/config-handler/config-handler.hpp index 638993a..c7ab4fb 100644 --- a/src/utilities/config-handler/config-handler.hpp +++ b/src/utilities/config-handler/config-handler.hpp @@ -14,6 +14,7 @@ class ConfigHandler { void read(const std::string& fileName); void read(); auto operator[](const std::string& field) const -> const nlohmann::json; + auto getAllConfig() const -> const nlohmann::json; private: [[nodiscard]] auto getConfig(const std::string& field) const -> const nlohmann::json; From fed92b3e0be5519347139c2882acff2688d41c5b Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Fri, 18 Feb 2022 16:53:24 -0300 Subject: [PATCH 125/147] daemon: add the daemon class --- src/classes/daemon/daemon.cpp | 22 ++++++++++++++++++++++ src/classes/daemon/daemon.hpp | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/classes/daemon/daemon.cpp b/src/classes/daemon/daemon.cpp index e69de29..165897f 100644 --- a/src/classes/daemon/daemon.cpp +++ b/src/classes/daemon/daemon.cpp @@ -0,0 +1,22 @@ +#include "daemon.hpp" + +Daemon::Daemon(const std::string& filePath) + : m_configHandler(filePath) + , m_serviceHandler(m_configHandler.getAllConfig()) +{ +} + +void Daemon::deploy(StaticService& userService) +{ + m_serviceHandler.buildServiceProxy(userService); +} + +void Daemon::deploy(RoutineService& userService) +{ + m_serviceHandler.buildServiceProxy(userService); +} + +void Daemon::run() +{ + m_serviceHandler.run(); +} diff --git a/src/classes/daemon/daemon.hpp b/src/classes/daemon/daemon.hpp index e69de29..db88618 100644 --- a/src/classes/daemon/daemon.hpp +++ b/src/classes/daemon/daemon.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include "../../utilities/config-handler/config-handler.hpp" +#include "../dbus-handler/dbus-handler.hpp" +#include "../service-handler/service-handler.hpp" + +class Daemon { +public: + explicit Daemon(const std::string& filePath); + + void deploy(StaticService& userService); + void deploy(RoutineService& userService); + + void run(); + + void getDaemonStatus(); + +private: + ConfigHandler m_configHandler; + ServiceHandler m_serviceHandler; + DBusHandler m_dbusHandler; +}; From 91c07655d30b7afa7c852f3fa4200e787645d2a4 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Mon, 14 Mar 2022 14:49:28 -0300 Subject: [PATCH 126/147] dbus-handler: convert to static class --- src/classes/dbus-handler/dbus-handler.cpp | 62 +++++++++++++---------- src/classes/dbus-handler/dbus-handler.hpp | 58 ++++++++++----------- 2 files changed, 65 insertions(+), 55 deletions(-) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index ce4c241..b8a7b31 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,22 +1,31 @@ #include "dbus-handler.hpp" -DBusHandler::DBusHandler(const std::string& serviceName) - : m_isServer { true } - , m_serviceName { serviceName } -{ - m_connection = sdbus::createSystemBusConnection(serviceName); +std::string DBusHandler::s_serviceName = ""; +bool DBusHandler::s_started = false; +bool DBusHandler::s_isServer = false; + +std::unique_ptr DBusHandler::s_connection; + +DBusHandler::DBusObjectMap DBusHandler::s_DBusObjects; +DBusHandler::DBusProxyMap DBusHandler::s_DBusProxys; + +void DBusHandler::start(const std::string& serviceName) { + s_isServer = true; + s_serviceName = "zfkd.dbus." + serviceName; + s_connection = sdbus::createSystemBusConnection(s_serviceName); } -DBusHandler::DBusHandler() - : m_isServer { false } {}; +void DBusHandler::start() { + s_isServer = false; +}; auto DBusHandler::findObject(const DBusHandler::Path& path) -> sdbus::IObject* { try { - return m_DBusObjects.at(path.objectPath).get(); + return s_DBusObjects.at(path.objectPath).get(); } catch (std::out_of_range& e) { - m_DBusObjects[path.objectPath] = sdbus::createObject(*m_connection, path.objectPath); - return m_DBusObjects[path.objectPath].get(); + s_DBusObjects[path.objectPath] = sdbus::createObject(*s_connection, path.objectPath); + return s_DBusObjects[path.objectPath].get(); } } @@ -25,20 +34,20 @@ auto DBusHandler::findProxy(const DBusHandler::Path& path) -> sdbus::IProxy* const std::string uniqueId = path.service + path.objectPath; try { - return m_DBusProxys.at(uniqueId).get(); + return s_DBusProxys.at(uniqueId).get(); } catch (std::out_of_range& e) { - m_DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); - return m_DBusProxys[uniqueId].get(); + s_DBusProxys[uniqueId] = sdbus::createProxy(path.service, path.objectPath); + return s_DBusProxys[uniqueId].get(); } } void DBusHandler::registerMethod(const DBusHandler::Path& path, DBusCallback&& callback) { - if (!m_isServer) { + if (!s_isServer) { throw std::logic_error("Only servers can register methods"); } - if (m_started) { + if (s_started) { throw std::logic_error("Methods should be register before finishing the handler"); } @@ -76,11 +85,11 @@ void DBusHandler::subscribeToSignal(const DBusHandler::Path& path, DBusVoidCallb void DBusHandler::registerSignal(const DBusHandler::Path& path) { - if (!m_isServer) { + if (!s_isServer) { throw std::logic_error("Only servers can register signals"); } - if (m_started) { + if (s_started) { throw std::logic_error("register signals is only possible before finishing the handler"); } @@ -121,11 +130,11 @@ void DBusHandler::callMethodAsync(const DBusHandler::Path& path, nlohmann::json void DBusHandler::emitSignal(const DBusHandler::Path& path, nlohmann::json arg) { - if (!m_isServer) { + if (!s_isServer) { throw std::logic_error("Only servers can emit signals"); } - if (!m_started) { + if (!s_started) { throw std::logic_error("emit a signal is only possible after finishing the handler"); } @@ -141,11 +150,11 @@ void DBusHandler::exposeProperty(const DBusHandler::Path& path, std::functionfinishRegistration(); } - for (auto const& proxy : m_DBusProxys) { + for (auto const& proxy : s_DBusProxys) { proxy.second->finishRegistration(); } - if (m_isServer) { - m_connection->enterEventLoop(); + if (s_isServer) { + s_connection->enterEventLoop(); } } diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/src/classes/dbus-handler/dbus-handler.hpp index 41d82f7..1642391 100644 --- a/src/classes/dbus-handler/dbus-handler.hpp +++ b/src/classes/dbus-handler/dbus-handler.hpp @@ -24,12 +24,12 @@ class DBusHandler { Path() = default; - Path(const std::string& service, const std::string& objectPath, const std::string& interface, - const std::string& functionality) - : service { std::move(service) } - , objectPath { std::move(objectPath) } - , interface { std::move(interface) } - , functionality { std::move(functionality) } + Path(const std::string& serviceName, const std::string& serviceObjectPath, const std::string& serviceInterface, + const std::string& serviceFunctionality) + : service { std::move(serviceName) } + , objectPath { std::move(serviceObjectPath) } + , interface { std::move(serviceInterface) } + , functionality { std::move(serviceFunctionality) } { if (service.empty() || objectPath.empty() || interface.empty() || functionality.empty()) { throw std::invalid_argument("Invalid path: empty string doesn't satisfies path format"); @@ -38,49 +38,49 @@ class DBusHandler { }; private: - std::string m_serviceName; - bool m_started; - bool m_isServer; + static std::string s_serviceName; + static bool s_started; + static bool s_isServer; - std::unique_ptr m_connection; + static std::unique_ptr s_connection; - DBusObjectMap m_DBusObjects; - DBusProxyMap m_DBusProxys; + static DBusObjectMap s_DBusObjects; + static DBusProxyMap s_DBusProxys; - auto findProxy(const DBusHandler::Path& path) -> sdbus::IProxy*; + static auto findProxy(const DBusHandler::Path& path) -> sdbus::IProxy*; - auto findObject(const DBusHandler::Path& path) -> sdbus::IObject*; + static auto findObject(const DBusHandler::Path& path) -> sdbus::IObject*; public: - DBusHandler(); + static void start(); - explicit DBusHandler(const std::string& serviceName); + static void start(const std::string& serviceName); - DBusHandler(const std::string& serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys); + static void start(const std::string& serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys); - DBusHandler(const std::string& serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys, + static void start(const std::string& serviceName, DBusObjectMap DBusObjects, DBusProxyMap DBusProxys, std::unique_ptr connection); - void registerMethod(const DBusHandler::Path& path, DBusCallback&& callback); + static void registerMethod(const DBusHandler::Path& path, DBusCallback&& callback); - void subscribeToSignal(const DBusHandler::Path& path, DBusVoidCallback&& callback); + static void subscribeToSignal(const DBusHandler::Path& path, DBusVoidCallback&& callback); - void registerSignal(const DBusHandler::Path& path); + static void registerSignal(const DBusHandler::Path& path); - auto callMethod(const DBusHandler::Path& path, nlohmann::json arg) -> nlohmann::json; + static auto callMethod(const DBusHandler::Path& path, nlohmann::json arg) -> nlohmann::json; - void callMethodAsync(const DBusHandler::Path& path, nlohmann::json arg, DBusVoidCallback&& callback); + static void callMethodAsync(const DBusHandler::Path& path, nlohmann::json arg, DBusVoidCallback&& callback); - void emitSignal(const DBusHandler::Path& path, nlohmann::json arg); + static void emitSignal(const DBusHandler::Path& path, nlohmann::json arg); - void exposeProperty(const DBusHandler::Path& path, std::function&& getter, + static void exposeProperty(const DBusHandler::Path& path, std::function&& getter, DBusVoidCallback&& setter); - auto getProperty(const DBusHandler::Path& path) -> nlohmann::json; + static auto getProperty(const DBusHandler::Path& path) -> nlohmann::json; - void getProperty(const DBusHandler::Path& path, DBusVoidCallback&& callback); + static void getProperty(const DBusHandler::Path& path, DBusVoidCallback&& callback); - void setProperty(const DBusHandler::Path& path, nlohmann::json arg); + static void setProperty(const DBusHandler::Path& path, nlohmann::json arg); - void finish(); + static void finish(); }; From 13f9c36a03964aef2ecb344e51d88eb8eeb27ccc Mon Sep 17 00:00:00 2001 From: Math-42 Date: Mon, 14 Mar 2022 15:08:45 -0300 Subject: [PATCH 127/147] daemon_test: remove the unit test --- test/src/daemon_test.cpp | 142 --------------------------------------- 1 file changed, 142 deletions(-) delete mode 100644 test/src/daemon_test.cpp diff --git a/test/src/daemon_test.cpp b/test/src/daemon_test.cpp deleted file mode 100644 index 0c47840..0000000 --- a/test/src/daemon_test.cpp +++ /dev/null @@ -1,142 +0,0 @@ -#include "../src/classes/dbus-handler/dbus-handler.hpp" - -#include -#include -#include -#include -#include - -class ServerClient : public ::testing::Test { -public: - DBusHandler m_client {}; - - static DBusHandler::Path m_methodPath; - static DBusHandler::Path m_signalPath; - static DBusHandler::Path m_propertiesPath; - static bool isServerConfig; - static nlohmann::json m_properties; - - static void SetUpTestSuite() - { - isServerConfig = true; - - m_properties["num"] = 9; - - std::thread t1(&ServerClient::server); - t1.detach(); - while (isServerConfig) { }; - } - - static void server() - { - DBusHandler server(m_methodPath.service); - - server.registerSignal(m_signalPath); - server.registerMethod(m_methodPath, [&](nlohmann::json req) { - nlohmann::json res; - int num = req["num"]; - - res["num"] = num * 2; - server.emitSignal(m_signalPath, res); - return res; - }); - server.exposeProperty( - m_propertiesPath, [&]() { return m_properties; }, [&](nlohmann::json req) { m_properties = req; }); - - isServerConfig = false; - server.finish(); - } -}; - -DBusHandler::Path ServerClient::m_methodPath { - "org.sdbuscpp.concatenator", - "/org/sdbuscpp/concatenator", - "org.sdbuscpp.Concatenator", - "concatenate" -}; - -DBusHandler::Path ServerClient::m_signalPath { - "org.sdbuscpp.concatenator", - "/org/sdbuscpp/concatenator", - "org.sdbuscpp.Concatenator", - "concatenated" -}; - -DBusHandler::Path ServerClient::m_propertiesPath { - "org.sdbuscpp.concatenator", - "/org/sdbuscpp/concatenator", - "org.sdbuscpp.Concatenator", - "properties" -}; - -bool ServerClient::isServerConfig; -nlohmann::json ServerClient::m_properties; - -TEST_F(ServerClient, Method) -{ - nlohmann::json arg; - nlohmann::json res; - - int num = 4; - arg["num"] = num; - res = m_client.callMethod(m_methodPath, arg); - - EXPECT_EQ(num * 2, res["num"]); -} - -TEST_F(ServerClient, AsyncMethod) -{ - nlohmann::json arg; - int num = 4; - - arg["num"] = num; - - m_client.finish(); - m_client.callMethodAsync(m_methodPath, arg, [&](nlohmann::json res) { - EXPECT_EQ(num * 2, res["num"]); - }); -} - -TEST_F(ServerClient, Signal) -{ - nlohmann::json arg; - nlohmann::json res; - int num = 4; - - m_client.subscribeToSignal(m_signalPath, [&](nlohmann::json rec) { - EXPECT_EQ(num * 2, rec["num"]); - }); - - m_client.finish(); - arg["num"] = num; - - res = m_client.callMethod(m_methodPath, arg); -} - -TEST_F(ServerClient, Get) -{ - m_client.finish(); - - nlohmann::json res = m_client.getProperty(m_propertiesPath); - EXPECT_EQ(res, m_properties); -} - -TEST_F(ServerClient, AsyncGet) -{ - m_client.finish(); - - m_client.getProperty(m_propertiesPath, [&](nlohmann::json arg) { - EXPECT_EQ(arg, m_properties); - }); -} - -TEST_F(ServerClient, Set) -{ - nlohmann::json arg; - arg["num"] = static_cast(m_properties["num"]) * 4; - - m_client.finish(); - m_client.setProperty(m_propertiesPath, arg); - - EXPECT_EQ(arg, m_properties); -} From 1c9566ddd8c31461dfc30c18ecf85257849543cd Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 14 Mar 2022 23:27:30 -0300 Subject: [PATCH 128/147] ServiceProxy: adds configure option to proxy API --- src/classes/service-proxy/service-proxy.cpp | 4 ++++ src/classes/service-proxy/service-proxy.hpp | 2 ++ 2 files changed, 6 insertions(+) diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index 17cccac..1d495c0 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -51,3 +51,7 @@ void ServiceProxy::ProxyConfigs::changeDep(std::string dependencieId, ServiceSta m_depsMap.at(dependencieId).m_currState = currState; } +void ServiceProxy::configure() +{ + m_realService.setup(); +} diff --git a/src/classes/service-proxy/service-proxy.hpp b/src/classes/service-proxy/service-proxy.hpp index 1a65584..bb49a3d 100644 --- a/src/classes/service-proxy/service-proxy.hpp +++ b/src/classes/service-proxy/service-proxy.hpp @@ -31,6 +31,7 @@ class ServiceProxy { virtual void allFine() { } [[nodiscard]] auto getState() const -> state_t; }; + protected: class ProxyConfigs { public: @@ -59,6 +60,7 @@ class ServiceProxy { std::unique_ptr m_state; auto checkState() -> ServiceState::state_t; + void configure(); virtual void autoUpdate(); virtual void serviceCycle() { } From a99e9d9eccf5862688317836a0fe30c83d1f4c2d Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 14 Mar 2022 23:31:01 -0300 Subject: [PATCH 129/147] StaticService: removes the setup from serviceCycle --- src/classes/static-service-proxy/static-service-proxy.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/classes/static-service-proxy/static-service-proxy.cpp b/src/classes/static-service-proxy/static-service-proxy.cpp index d2914bd..93daee6 100644 --- a/src/classes/static-service-proxy/static-service-proxy.cpp +++ b/src/classes/static-service-proxy/static-service-proxy.cpp @@ -43,7 +43,6 @@ void StaticServiceProxy::StandBy::somethingIsMissing() void StaticServiceProxy::StaticServiceProxy::serviceCycle() { changeState(ServiceState::RUNNING); - m_realService.setup(); m_realService.destroy(); changeState(ServiceState::STAND_BY); } From 26a730e99de6a58cdd0d36b8c26c47befbfa5352 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 14 Mar 2022 23:33:21 -0300 Subject: [PATCH 130/147] RoutineService: removes the setup from serviceCycle --- src/classes/routine-service-proxy/routine-service-proxy.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/classes/routine-service-proxy/routine-service-proxy.cpp b/src/classes/routine-service-proxy/routine-service-proxy.cpp index e97f0ac..5c4f4b6 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.cpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.cpp @@ -27,7 +27,6 @@ void RoutineServiceProxy::Running::somethingIsMissing() void RoutineServiceProxy::serviceCycle() { changeState(ServiceState::RUNNING); - m_realService.setup(); while (checkState() != ServiceState::STOPPED) { From cbe664f4f800d351b8e50bc18b7ee4adf0f54fe6 Mon Sep 17 00:00:00 2001 From: Carlos Veras Date: Mon, 14 Mar 2022 23:54:26 -0300 Subject: [PATCH 131/147] ServiceHandler: calls proxy's configure at method run --- src/classes/service-handler/service-handler.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index fbf4157..5b65965 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -85,6 +85,7 @@ void ServiceHandler::run() { for (auto& [serviceId, proxy] : m_serviceMap) { proxy->m_proxyConfigs.changeDep("THIS", ServiceProxy::ServiceState::RUNNING); + proxy->configure(); proxy->autoUpdate(); } } From e881761ee0525e8a0be92b0f0d6b9e20d86b0cdf Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 14:41:53 -0300 Subject: [PATCH 132/147] cmake: remove daemon_test from the test_sources --- cmake/SourcesAndHeaders.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/SourcesAndHeaders.cmake b/cmake/SourcesAndHeaders.cmake index d12b4b1..55a27c6 100644 --- a/cmake/SourcesAndHeaders.cmake +++ b/cmake/SourcesAndHeaders.cmake @@ -26,5 +26,5 @@ set(headers ) set(test_sources - src/daemon_test.cpp + #src/daemon_test.cpp ) From 640dfc4f1398066974abf1ccb8e52b8cc912395c Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:02:56 -0300 Subject: [PATCH 133/147] daemon: add the DBusHandler to the daemon class --- src/classes/daemon/daemon.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/classes/daemon/daemon.cpp b/src/classes/daemon/daemon.cpp index 165897f..0d4d13b 100644 --- a/src/classes/daemon/daemon.cpp +++ b/src/classes/daemon/daemon.cpp @@ -4,6 +4,7 @@ Daemon::Daemon(const std::string& filePath) : m_configHandler(filePath) , m_serviceHandler(m_configHandler.getAllConfig()) { + DBusHandler::start(m_configHandler["serviceId"]); } void Daemon::deploy(StaticService& userService) @@ -19,4 +20,5 @@ void Daemon::deploy(RoutineService& userService) void Daemon::run() { m_serviceHandler.run(); + DBusHandler::finish(); } From 9284b35b01526459b7c0714d182f831169fa88f7 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:04:12 -0300 Subject: [PATCH 134/147] config-handler: get the DBusHandler configs from the ConfigHandler. --- src/utilities/config-handler/config-handler.cpp | 14 +++++++++----- src/utilities/config-handler/config-handler.hpp | 2 +- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/utilities/config-handler/config-handler.cpp b/src/utilities/config-handler/config-handler.cpp index d8d4f65..23f722c 100644 --- a/src/utilities/config-handler/config-handler.cpp +++ b/src/utilities/config-handler/config-handler.cpp @@ -1,8 +1,12 @@ #include "config-handler.hpp" +#include + +nlohmann::json ConfigHandler::m_config; ConfigHandler::ConfigHandler(const std::string& fileName) : m_fileName(fileName) { + read(); } /** @@ -11,8 +15,8 @@ ConfigHandler::ConfigHandler(const std::string& fileName) void ConfigHandler::validateConfig() { for (const auto& it : m_requiredFields) { - if (!m_config.contains(it)) { - throw std::runtime_error("Config file dosen't have all the required fields"); + if (!ConfigHandler::m_config.contains(it)) { + throw std::runtime_error("Config file doesn't have all the required fields"); } } } @@ -24,10 +28,10 @@ void ConfigHandler::read() { std::ifstream file(m_fileName); if (!file.is_open()) { - throw std::invalid_argument("File not found"); + throw std::invalid_argument("Configuration file not found"); } - file >> m_config; + file >> ConfigHandler::m_config; validateConfig(); @@ -50,7 +54,7 @@ void ConfigHandler::read(const std::string& fileName) */ auto ConfigHandler::getConfig(const std::string& field) const -> const nlohmann::json { - return m_config[field]; + return ConfigHandler::m_config[field]; } /** diff --git a/src/utilities/config-handler/config-handler.hpp b/src/utilities/config-handler/config-handler.hpp index c7ab4fb..b2d59ee 100644 --- a/src/utilities/config-handler/config-handler.hpp +++ b/src/utilities/config-handler/config-handler.hpp @@ -6,7 +6,7 @@ class ConfigHandler { static nlohmann::json m_config; std::string m_fileName; const std::vector m_requiredFields { - "data", "services", "serviceId" + "data", "proxys", "serviceId" }; public: From d9c016194c1083b6c100eb1363603a8fbfc3a111 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:04:36 -0300 Subject: [PATCH 135/147] cmake: add the -pthread flag to the cmake list file --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index c08995e..766ec05 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,6 +10,7 @@ project( LANGUAGES CXX ) +string(APPEND CMAKE_CXX_FLAGS " -pthread") # # Set project options # From b4e24576897f356f9f4decf4ac4e61cbfd7167b8 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:06:20 -0300 Subject: [PATCH 136/147] configModel: remove the old config template file. --- examples/configModel.json | 36 ------------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 examples/configModel.json diff --git a/examples/configModel.json b/examples/configModel.json deleted file mode 100644 index 02c66bb..0000000 --- a/examples/configModel.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "daemonId": "DaemonIdExample", - "endpoints": [{ - "id": "endpoint1Name", - "type": "signal", - "triggers": ["trigger1", "trigger2", "..."], - "dependencies": [{ - "type": "routine", - "name": "org.zenith.daemons.daemon1.routineA", - "status": 0 - }] - }, - { - "id": "endpoint2Name", - "type": "method", - "triggers": ["trigger1"], - "dependencies": [{ - "type": "daemon", - "name": "org.zenith.daemons.daemon2", - "status": 1 - }] - } - ], - "routines": [{ - "id": "routine1Name", - "signals": ["mySignal1, mySignal2"], - "dependencies": [{ - "type": "endpoint", - "name": "org.zenith.daemons.daemon3.endpointB", - "status": 2 - }] - }], - "data": { - "anything": "anything" - } -} \ No newline at end of file From e7b8da9e7c4977be2837c49ee4d2c316aeb22f0c Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:06:43 -0300 Subject: [PATCH 137/147] examples: add two new config file templates --- examples/PING.json | 9 +++++++++ examples/PONG.json | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 examples/PING.json create mode 100644 examples/PONG.json diff --git a/examples/PING.json b/examples/PING.json new file mode 100644 index 0000000..c9d7d6c --- /dev/null +++ b/examples/PING.json @@ -0,0 +1,9 @@ +{ + "serviceId": "ping", + "proxys": { + "PING":{} + }, + "data": { + "anything": "anything" + } +} \ No newline at end of file diff --git a/examples/PONG.json b/examples/PONG.json new file mode 100644 index 0000000..1e2dbba --- /dev/null +++ b/examples/PONG.json @@ -0,0 +1,9 @@ +{ + "serviceId": "pong", + "proxys": { + "PING":{} + }, + "data": { + "anything": "anything" + } +} \ No newline at end of file From c77a8575b9aec57b3ee33c66c4a4ff80becd73db Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:07:36 -0300 Subject: [PATCH 138/147] ping: create a ping routine service --- examples/ping.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 examples/ping.cpp diff --git a/examples/ping.cpp b/examples/ping.cpp new file mode 100644 index 0000000..d266ae8 --- /dev/null +++ b/examples/ping.cpp @@ -0,0 +1,60 @@ +#include "../src/classes/daemon/daemon.hpp" +#include + +class PingService : public RoutineService { + int pingCounter = 0; + std::chrono::nanoseconds pongDelay; + +public: + PingService(std::string serviceId) + : RoutineService { serviceId } + { + } + + const DBusHandler::Path pongMethodPath { + "zfkd.dbus.pong", + "/zfkd/dbus/pong", + "zfkd.dbus.pong", + "pong" + }; + + const DBusHandler::Path pongSignalPath { + "zfkd.dbus.pong", + "/zfkd/dbus/pong", + "zfkd.dbus.pong", + "pongDelay" + }; + + void setup() override + { + + DBusHandler::subscribeToSignal(pongSignalPath, [&](nlohmann::json pongWrapper) { + std::chrono::nanoseconds finalTime; + finalTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); + + pongDelay = finalTime - pongDelay; + std::cout << "Delay: " << pongDelay.count() << "ns" << std::endl; + }); + + } + + void routine() override + { + std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 2000 + 200)); + pongDelay = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); + + nlohmann::json pingWrapper; + pingWrapper["ping"] = pingCounter; + + nlohmann::json pongWrapper = DBusHandler::callMethod(pongMethodPath, pingWrapper); + pingCounter = pongWrapper["ping"]; + + pingCounter++; + + std::cout << "Ping: " << pingCounter << std::endl; + } + + void destroy() override + { + } +}; From 520a2fbb04c8dc69bb9470b62cdb4f80d07efeac Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:07:48 -0300 Subject: [PATCH 139/147] ping: expose the ping service --- examples/ping.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/examples/ping.cpp b/examples/ping.cpp index d266ae8..1fcece3 100644 --- a/examples/ping.cpp +++ b/examples/ping.cpp @@ -58,3 +58,12 @@ class PingService : public RoutineService { { } }; + +int main() +{ + Daemon newDaemon("PING.json"); + PingService pingService("PING"); + newDaemon.deploy(pingService); + newDaemon.run(); + return 0; +} \ No newline at end of file From 342b97feecb96a34ec16e5bb14002eea5178ec15 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:09:33 -0300 Subject: [PATCH 140/147] pong: create the pong example service --- examples/pong.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 examples/pong.cpp diff --git a/examples/pong.cpp b/examples/pong.cpp new file mode 100644 index 0000000..9e30420 --- /dev/null +++ b/examples/pong.cpp @@ -0,0 +1,47 @@ +#include "../src/classes/daemon/daemon.hpp" +#include + +class PongService : public StaticService { + int pongCounter = 0; + +public: + PongService(std::string serviceId) + : StaticService { serviceId } + { + } + + const DBusHandler::Path pongMethodPath { + "zfkd.dbus.pong", + "/zfkd/dbus/pong", + "zfkd.dbus.pong", + "pong" + }; + + const DBusHandler::Path pongSignalPath { + "zfkd.dbus.pong", + "/zfkd/dbus/pong", + "zfkd.dbus.pong", + "pongDelay" + }; + + void setup() override + { + DBusHandler::registerSignal(pongSignalPath); + + DBusHandler::registerMethod(pongMethodPath, [&](nlohmann::json pingWrapper) { + pongCounter = pingWrapper["ping"]; + pongCounter++; + pingWrapper["ping"] = pongCounter; + + std::cout << "Pong: " << pongCounter << std::endl; + + DBusHandler::emitSignal(pongSignalPath, pingWrapper); + + return pingWrapper; + }); + } + + void destroy() override + { + } +}; From 1e6b2f0a4e7a5baa20ee1be4a6655f18ab128c77 Mon Sep 17 00:00:00 2001 From: Math-42 Date: Tue, 15 Mar 2022 15:09:53 -0300 Subject: [PATCH 141/147] pong: expose the pong example service --- examples/pong.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/examples/pong.cpp b/examples/pong.cpp index 9e30420..8a761ec 100644 --- a/examples/pong.cpp +++ b/examples/pong.cpp @@ -45,3 +45,12 @@ class PongService : public StaticService { { } }; + +int main() +{ + Daemon newDaemon("PONG.json"); + PongService pongService("PONG"); + newDaemon.deploy(pongService); + newDaemon.run(); + return 0; +} \ No newline at end of file From 55c6c08679bd2bf328e0fb4cee7302b0b69a5d4b Mon Sep 17 00:00:00 2001 From: grillo Date: Sun, 10 Apr 2022 15:29:57 -0300 Subject: [PATCH 142/147] include: change .hpp location for correct library installation --- cmake/SourcesAndHeaders.cmake | 18 +++++++++--------- include/classes/daemon/daemon.hpp | 0 include/classes/endpoint/endpoint.hpp | 0 include/classes/routine/routine.hpp | 0 .../frameworkd}/classes/daemon/daemon.hpp | 0 .../classes/dbus-handler/dbus-handler.hpp | 0 .../frameworkd}/classes/iservice/iservice.hpp | 0 .../classes/locked-storage/locked-storage.hpp | 0 .../routine-service-proxy.hpp | 0 .../service-handler/service-handler.hpp | 0 .../classes/service-proxy/service-proxy.hpp | 0 .../static-service-proxy.hpp | 0 .../config-handler/config-handler.hpp | 0 src/classes/daemon/daemon.cpp | 2 +- src/classes/dbus-handler/dbus-handler.cpp | 2 +- .../routine-service-proxy.cpp | 2 +- .../service-handler/service-handler.cpp | 2 +- src/classes/service-proxy/service-proxy.cpp | 2 +- .../static-service-proxy.cpp | 2 +- .../config-handler/config-handler.cpp | 2 +- 20 files changed, 16 insertions(+), 16 deletions(-) delete mode 100644 include/classes/daemon/daemon.hpp delete mode 100644 include/classes/endpoint/endpoint.hpp delete mode 100644 include/classes/routine/routine.hpp rename {src => include/frameworkd}/classes/daemon/daemon.hpp (100%) rename {src => include/frameworkd}/classes/dbus-handler/dbus-handler.hpp (100%) rename {src => include/frameworkd}/classes/iservice/iservice.hpp (100%) rename {src => include/frameworkd}/classes/locked-storage/locked-storage.hpp (100%) rename {src => include/frameworkd}/classes/routine-service-proxy/routine-service-proxy.hpp (100%) rename {src => include/frameworkd}/classes/service-handler/service-handler.hpp (100%) rename {src => include/frameworkd}/classes/service-proxy/service-proxy.hpp (100%) rename {src => include/frameworkd}/classes/static-service-proxy/static-service-proxy.hpp (100%) rename {src => include/frameworkd}/utilities/config-handler/config-handler.hpp (100%) diff --git a/cmake/SourcesAndHeaders.cmake b/cmake/SourcesAndHeaders.cmake index 55a27c6..7878be5 100644 --- a/cmake/SourcesAndHeaders.cmake +++ b/cmake/SourcesAndHeaders.cmake @@ -14,15 +14,15 @@ set(exe_sources ) set(headers - src/utilities/config-handler/config-handler.hpp - src/classes/daemon/daemon.hpp - src/classes/iservice/iservice.hpp - src/classes/static-service-proxy/static-service-proxy.hpp - src/classes/locked-storage/locked-storage.hpp - src/classes/dbus-handler/dbus-handler.hpp - src/classes/service-proxy/service-proxy.hpp - src/classes/routine-service-proxy/routine-service-proxy.hpp - src/classes/service-handler/service-handler.hpp + include/frameworkd/utilities/config-handler/config-handler.hpp + include/frameworkd/classes/daemon/daemon.hpp + include/frameworkd/classes/iservice/iservice.hpp + include/frameworkd/classes/static-service-proxy/static-service-proxy.hpp + include/frameworkd/classes/locked-storage/locked-storage.hpp + include/frameworkd/classes/dbus-handler/dbus-handler.hpp + include/frameworkd/classes/service-proxy/service-proxy.hpp + include/frameworkd/classes/routine-service-proxy/routine-service-proxy.hpp + include/frameworkd/classes/service-handler/service-handler.hpp ) set(test_sources diff --git a/include/classes/daemon/daemon.hpp b/include/classes/daemon/daemon.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/include/classes/endpoint/endpoint.hpp b/include/classes/endpoint/endpoint.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/include/classes/routine/routine.hpp b/include/classes/routine/routine.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/classes/daemon/daemon.hpp b/include/frameworkd/classes/daemon/daemon.hpp similarity index 100% rename from src/classes/daemon/daemon.hpp rename to include/frameworkd/classes/daemon/daemon.hpp diff --git a/src/classes/dbus-handler/dbus-handler.hpp b/include/frameworkd/classes/dbus-handler/dbus-handler.hpp similarity index 100% rename from src/classes/dbus-handler/dbus-handler.hpp rename to include/frameworkd/classes/dbus-handler/dbus-handler.hpp diff --git a/src/classes/iservice/iservice.hpp b/include/frameworkd/classes/iservice/iservice.hpp similarity index 100% rename from src/classes/iservice/iservice.hpp rename to include/frameworkd/classes/iservice/iservice.hpp diff --git a/src/classes/locked-storage/locked-storage.hpp b/include/frameworkd/classes/locked-storage/locked-storage.hpp similarity index 100% rename from src/classes/locked-storage/locked-storage.hpp rename to include/frameworkd/classes/locked-storage/locked-storage.hpp diff --git a/src/classes/routine-service-proxy/routine-service-proxy.hpp b/include/frameworkd/classes/routine-service-proxy/routine-service-proxy.hpp similarity index 100% rename from src/classes/routine-service-proxy/routine-service-proxy.hpp rename to include/frameworkd/classes/routine-service-proxy/routine-service-proxy.hpp diff --git a/src/classes/service-handler/service-handler.hpp b/include/frameworkd/classes/service-handler/service-handler.hpp similarity index 100% rename from src/classes/service-handler/service-handler.hpp rename to include/frameworkd/classes/service-handler/service-handler.hpp diff --git a/src/classes/service-proxy/service-proxy.hpp b/include/frameworkd/classes/service-proxy/service-proxy.hpp similarity index 100% rename from src/classes/service-proxy/service-proxy.hpp rename to include/frameworkd/classes/service-proxy/service-proxy.hpp diff --git a/src/classes/static-service-proxy/static-service-proxy.hpp b/include/frameworkd/classes/static-service-proxy/static-service-proxy.hpp similarity index 100% rename from src/classes/static-service-proxy/static-service-proxy.hpp rename to include/frameworkd/classes/static-service-proxy/static-service-proxy.hpp diff --git a/src/utilities/config-handler/config-handler.hpp b/include/frameworkd/utilities/config-handler/config-handler.hpp similarity index 100% rename from src/utilities/config-handler/config-handler.hpp rename to include/frameworkd/utilities/config-handler/config-handler.hpp diff --git a/src/classes/daemon/daemon.cpp b/src/classes/daemon/daemon.cpp index 0d4d13b..e01304a 100644 --- a/src/classes/daemon/daemon.cpp +++ b/src/classes/daemon/daemon.cpp @@ -1,4 +1,4 @@ -#include "daemon.hpp" +#include "frameworkd/classes/daemon/daemon.hpp" Daemon::Daemon(const std::string& filePath) : m_configHandler(filePath) diff --git a/src/classes/dbus-handler/dbus-handler.cpp b/src/classes/dbus-handler/dbus-handler.cpp index b8a7b31..e032e74 100644 --- a/src/classes/dbus-handler/dbus-handler.cpp +++ b/src/classes/dbus-handler/dbus-handler.cpp @@ -1,4 +1,4 @@ -#include "dbus-handler.hpp" +#include "frameworkd/classes/dbus-handler/dbus-handler.hpp" std::string DBusHandler::s_serviceName = ""; bool DBusHandler::s_started = false; diff --git a/src/classes/routine-service-proxy/routine-service-proxy.cpp b/src/classes/routine-service-proxy/routine-service-proxy.cpp index 5c4f4b6..5e3ca78 100644 --- a/src/classes/routine-service-proxy/routine-service-proxy.cpp +++ b/src/classes/routine-service-proxy/routine-service-proxy.cpp @@ -1,4 +1,4 @@ -#include "routine-service-proxy.hpp" +#include "frameworkd/classes/routine-service-proxy/routine-service-proxy.hpp" RoutineServiceProxy::RoutineServiceProxy(RoutineService& realService, std::map depsMap) : ServiceProxy { realService, ROUTINE_SERVICE, depsMap } diff --git a/src/classes/service-handler/service-handler.cpp b/src/classes/service-handler/service-handler.cpp index 5b65965..843f5a4 100644 --- a/src/classes/service-handler/service-handler.cpp +++ b/src/classes/service-handler/service-handler.cpp @@ -1,4 +1,4 @@ -#include "service-handler.hpp" +#include "frameworkd/classes/service-handler/service-handler.hpp" ServiceHandler::ServiceHandler(nlohmann::json servicesConfigs) { diff --git a/src/classes/service-proxy/service-proxy.cpp b/src/classes/service-proxy/service-proxy.cpp index 1d495c0..6f69831 100644 --- a/src/classes/service-proxy/service-proxy.cpp +++ b/src/classes/service-proxy/service-proxy.cpp @@ -1,4 +1,4 @@ -#include "service-proxy.hpp" +#include "frameworkd/classes/service-proxy/service-proxy.hpp" ServiceProxy::ProxyConfigs::ProxyConfigs(std::map depsMap) { diff --git a/src/classes/static-service-proxy/static-service-proxy.cpp b/src/classes/static-service-proxy/static-service-proxy.cpp index 93daee6..4a207ce 100644 --- a/src/classes/static-service-proxy/static-service-proxy.cpp +++ b/src/classes/static-service-proxy/static-service-proxy.cpp @@ -1,4 +1,4 @@ -#include "static-service-proxy.hpp" +#include "frameworkd/classes/static-service-proxy/static-service-proxy.hpp" StaticServiceProxy::StaticServiceProxy(StaticService& realService, std::map depsMap) : m_runnedOnce { false } diff --git a/src/utilities/config-handler/config-handler.cpp b/src/utilities/config-handler/config-handler.cpp index 23f722c..01ce946 100644 --- a/src/utilities/config-handler/config-handler.cpp +++ b/src/utilities/config-handler/config-handler.cpp @@ -1,4 +1,4 @@ -#include "config-handler.hpp" +#include "frameworkd/utilities/config-handler/config-handler.hpp" #include nlohmann::json ConfigHandler::m_config; From 2f21b3674f2a6791065ef3f0d106c2f932e4ba79 Mon Sep 17 00:00:00 2001 From: grillo Date: Sun, 10 Apr 2022 15:48:18 -0300 Subject: [PATCH 143/147] fix: change project name to lower case --- CMakeLists.txt | 2 +- cmake/{FrameworkdConfig.cmake.in => frameworkdConfig.cmake.in} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename cmake/{FrameworkdConfig.cmake.in => frameworkdConfig.cmake.in} (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 766ec05..2cb061b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,7 +5,7 @@ cmake_minimum_required(VERSION 3.15) # project( - Frameworkd + frameworkd VERSION 0.1.0 LANGUAGES CXX ) diff --git a/cmake/FrameworkdConfig.cmake.in b/cmake/frameworkdConfig.cmake.in similarity index 100% rename from cmake/FrameworkdConfig.cmake.in rename to cmake/frameworkdConfig.cmake.in From 1213dc95b3fb91fd09b11fed88f7801b6ee7db14 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Wed, 29 Jun 2022 11:08:56 -0300 Subject: [PATCH 144/147] fix: make m_configHandler accessible This needed to be done to make the fkd work properly when a service needs to access a certain configuration in the json --- include/frameworkd/classes/daemon/daemon.hpp | 2 ++ src/classes/daemon/daemon.cpp | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/include/frameworkd/classes/daemon/daemon.hpp b/include/frameworkd/classes/daemon/daemon.hpp index db88618..546b058 100644 --- a/include/frameworkd/classes/daemon/daemon.hpp +++ b/include/frameworkd/classes/daemon/daemon.hpp @@ -15,6 +15,8 @@ class Daemon { void getDaemonStatus(); + auto getConfigHandler() -> ConfigHandler; + private: ConfigHandler m_configHandler; ServiceHandler m_serviceHandler; diff --git a/src/classes/daemon/daemon.cpp b/src/classes/daemon/daemon.cpp index e01304a..9bc4330 100644 --- a/src/classes/daemon/daemon.cpp +++ b/src/classes/daemon/daemon.cpp @@ -22,3 +22,7 @@ void Daemon::run() m_serviceHandler.run(); DBusHandler::finish(); } + +auto Daemon::getConfigHandler() -> ConfigHandler { + return m_configHandler; +} From 75e689db1bd987cada3a1295e00de77abd5dbead Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Fri, 22 Jul 2022 10:32:23 -0300 Subject: [PATCH 145/147] fix: add better error msg when the config file was not found --- src/utilities/config-handler/config-handler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utilities/config-handler/config-handler.cpp b/src/utilities/config-handler/config-handler.cpp index 01ce946..7c580db 100644 --- a/src/utilities/config-handler/config-handler.cpp +++ b/src/utilities/config-handler/config-handler.cpp @@ -28,7 +28,7 @@ void ConfigHandler::read() { std::ifstream file(m_fileName); if (!file.is_open()) { - throw std::invalid_argument("Configuration file not found"); + throw std::invalid_argument("Configuration file '"+ m_fileName + "' not found"); } file >> ConfigHandler::m_config; From fca4e7a30873997f3dcc16ba9bf59aa560302da2 Mon Sep 17 00:00:00 2001 From: Arthur Grillo Date: Fri, 22 Jul 2022 10:36:36 -0300 Subject: [PATCH 146/147] fix: make the config file a fixed position before the user could chose where to place the onfig file and it's name, now it's positioned in '/etc/frameworkd/.json' --- src/classes/daemon/daemon.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/classes/daemon/daemon.cpp b/src/classes/daemon/daemon.cpp index 9bc4330..ee3ad42 100644 --- a/src/classes/daemon/daemon.cpp +++ b/src/classes/daemon/daemon.cpp @@ -1,7 +1,7 @@ #include "frameworkd/classes/daemon/daemon.hpp" -Daemon::Daemon(const std::string& filePath) - : m_configHandler(filePath) +Daemon::Daemon(const std::string& name) + : m_configHandler("/etc/frameworkd/" + name + ".json") , m_serviceHandler(m_configHandler.getAllConfig()) { DBusHandler::start(m_configHandler["serviceId"]); @@ -23,6 +23,7 @@ void Daemon::run() DBusHandler::finish(); } -auto Daemon::getConfigHandler() -> ConfigHandler { - return m_configHandler; +auto Daemon::getConfigHandler() -> ConfigHandler +{ + return m_configHandler; } From f300a5f2877814ae97615ac3a8039719c9a3e509 Mon Sep 17 00:00:00 2001 From: Arthur Date: Thu, 22 Sep 2022 09:19:21 -0300 Subject: [PATCH 147/147] examples: update to the current fkd workflow The examples were outdated. This commit changes the daemon initialization code and json configs, also it's adds the .conf files for dbus --- examples/ping.cpp | 8 ++++---- examples/{PING.json => ping.json} | 4 ++-- examples/pong.cpp | 8 ++++---- examples/{PONG.json => pong.json} | 4 ++-- examples/zfkd.dbus.ping.conf | 10 ++++++++++ examples/zfkd.dbus.pong.conf | 10 ++++++++++ 6 files changed, 32 insertions(+), 12 deletions(-) rename examples/{PING.json => ping.json} (85%) rename examples/{PONG.json => pong.json} (85%) create mode 100644 examples/zfkd.dbus.ping.conf create mode 100644 examples/zfkd.dbus.pong.conf diff --git a/examples/ping.cpp b/examples/ping.cpp index 1fcece3..8c3a816 100644 --- a/examples/ping.cpp +++ b/examples/ping.cpp @@ -1,4 +1,4 @@ -#include "../src/classes/daemon/daemon.hpp" +#include #include class PingService : public RoutineService { @@ -61,9 +61,9 @@ class PingService : public RoutineService { int main() { - Daemon newDaemon("PING.json"); - PingService pingService("PING"); + Daemon newDaemon("ping"); + PingService pingService("ping"); newDaemon.deploy(pingService); newDaemon.run(); return 0; -} \ No newline at end of file +} diff --git a/examples/PING.json b/examples/ping.json similarity index 85% rename from examples/PING.json rename to examples/ping.json index c9d7d6c..c8b9de2 100644 --- a/examples/PING.json +++ b/examples/ping.json @@ -1,9 +1,9 @@ { "serviceId": "ping", "proxys": { - "PING":{} + "ping":{} }, "data": { "anything": "anything" } -} \ No newline at end of file +} diff --git a/examples/pong.cpp b/examples/pong.cpp index 8a761ec..e5931e0 100644 --- a/examples/pong.cpp +++ b/examples/pong.cpp @@ -1,4 +1,4 @@ -#include "../src/classes/daemon/daemon.hpp" +#include #include class PongService : public StaticService { @@ -48,9 +48,9 @@ class PongService : public StaticService { int main() { - Daemon newDaemon("PONG.json"); - PongService pongService("PONG"); + Daemon newDaemon("pong"); + PongService pongService("pong"); newDaemon.deploy(pongService); newDaemon.run(); return 0; -} \ No newline at end of file +} diff --git a/examples/PONG.json b/examples/pong.json similarity index 85% rename from examples/PONG.json rename to examples/pong.json index 1e2dbba..a454221 100644 --- a/examples/PONG.json +++ b/examples/pong.json @@ -1,9 +1,9 @@ { "serviceId": "pong", "proxys": { - "PING":{} + "pong":{} }, "data": { "anything": "anything" } -} \ No newline at end of file +} diff --git a/examples/zfkd.dbus.ping.conf b/examples/zfkd.dbus.ping.conf new file mode 100644 index 0000000..c920fc7 --- /dev/null +++ b/examples/zfkd.dbus.ping.conf @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/examples/zfkd.dbus.pong.conf b/examples/zfkd.dbus.pong.conf new file mode 100644 index 0000000..be620f9 --- /dev/null +++ b/examples/zfkd.dbus.pong.conf @@ -0,0 +1,10 @@ + + + + + + + +