diff --git a/source/RobotAPI/components/ArViz/Client/Client.h b/source/RobotAPI/components/ArViz/Client/Client.h index f2d406fece5753b91d89cc56f26c824711efde62..84dcad9ce36dc40c34553afb085aa3cdd1925460 100644 --- a/source/RobotAPI/components/ArViz/Client/Client.h +++ b/source/RobotAPI/components/ArViz/Client/Client.h @@ -80,8 +80,8 @@ namespace viz InteractionFeedbackRange interactions() const { - InteractionFeedback* begin = (InteractionFeedback*) data_.interactions.data(); - InteractionFeedback* end = begin + data_.interactions.size(); + const InteractionFeedback* begin = reinterpret_cast<const InteractionFeedback*>(data_.interactions.data()); + const InteractionFeedback* end = begin + data_.interactions.size(); return InteractionFeedbackRange{begin, end}; } diff --git a/source/RobotAPI/components/ArViz/Client/elements/MeshCGALExtensions.h b/source/RobotAPI/components/ArViz/Client/elements/MeshCGALExtensions.h index f00061ea4c9114c06981863032cca209a4240806..b4a45c3a361cbd0cc9bb6a9889f102828fdfe18a 100644 --- a/source/RobotAPI/components/ArViz/Client/elements/MeshCGALExtensions.h +++ b/source/RobotAPI/components/ArViz/Client/elements/MeshCGALExtensions.h @@ -82,7 +82,7 @@ namespace armarx::viz vertices.reserve(p3.size_of_vertices()); faces.reserve(p3.size_of_facets()); auto vbeg = p3.vertices_begin(); - for (const auto& v : IteratorRange{vbeg, p3.vertices_end()}) + for (const auto& v : CGAL::Iterator_range{vbeg, p3.vertices_end()}) { const auto& p = v.point(); armarx::Vector3f visp; @@ -91,7 +91,7 @@ namespace armarx::viz visp.e2 = p.z(); vertices.emplace_back(visp); } - for (const auto& fidx : IteratorRange{p3.facets_begin(), p3.facets_end()}) + for (const auto& fidx : CGAL::Iterator_range{p3.facets_begin(), p3.facets_end()}) { auto circ = fidx.facet_begin(); ARMARX_CHECK_EQUAL(3, CGAL::circulator_size(circ)) diff --git a/source/RobotAPI/components/ArViz/Client/elements/PointCloud.h b/source/RobotAPI/components/ArViz/Client/elements/PointCloud.h index a77f79632d3f29955f46773d0aea5c5602dfd0f9..78591128d2daddab633ef3fd04139a4c46ba2340 100644 --- a/source/RobotAPI/components/ArViz/Client/elements/PointCloud.h +++ b/source/RobotAPI/components/ArViz/Client/elements/PointCloud.h @@ -71,8 +71,8 @@ namespace armarx::viz PointCloud& points(std::vector<ColoredPoint> const& ps) { std::size_t memorySize = ps.size() * sizeof(ps[0]); - Ice::Byte* begin = (Ice::Byte*)ps.data(); - Ice::Byte* end = begin + memorySize; + const Ice::Byte* const begin = reinterpret_cast<const Ice::Byte*>(ps.data()); + const Ice::Byte* const end = begin + memorySize; data_->points.assign(begin, end); return *this; } @@ -92,8 +92,8 @@ namespace armarx::viz PointCloud& addPointUnchecked(ColoredPoint const& p) { - Ice::Byte* begin = (Ice::Byte*)&p; - Ice::Byte* end = begin + sizeof(p); + const Ice::Byte* const begin = reinterpret_cast<const Ice::Byte*>(&p); + const Ice::Byte* const end = begin + sizeof(p); data_->points.insert(data_->points.end(), begin, end); return *this; } @@ -391,5 +391,3 @@ namespace armarx::viz }; } - - diff --git a/source/RobotAPI/components/GamepadControlUnit/CMakeLists.txt b/source/RobotAPI/components/GamepadControlUnit/CMakeLists.txt index c3b764a153b15400568f67eb1dc9c2813874b921..8154ff69af2b057c18189c6ad07262e2a6f33142 100644 --- a/source/RobotAPI/components/GamepadControlUnit/CMakeLists.txt +++ b/source/RobotAPI/components/GamepadControlUnit/CMakeLists.txt @@ -1,6 +1,6 @@ armarx_component_set_name("GamepadControlUnit") -set(COMPONENT_LIBS ArmarXCoreInterfaces ArmarXCore ArmarXCoreObservers RobotAPIInterfaces ) +set(COMPONENT_LIBS ArmarXCoreInterfaces ArmarXCore ArmarXCoreObservers RobotAPIComponentPlugins RobotAPIInterfaces ) set(SOURCES GamepadControlUnit.cpp) set(HEADERS GamepadControlUnit.h) diff --git a/source/RobotAPI/components/GamepadControlUnit/GamepadControlUnit.cpp b/source/RobotAPI/components/GamepadControlUnit/GamepadControlUnit.cpp index 5227bee38e728999d4a0f7fed6809913144573b6..5113961eeebb95c1af593714fbb1eca93ea84909 100644 --- a/source/RobotAPI/components/GamepadControlUnit/GamepadControlUnit.cpp +++ b/source/RobotAPI/components/GamepadControlUnit/GamepadControlUnit.cpp @@ -22,15 +22,15 @@ #include "GamepadControlUnit.h" +#include <ArmarXCore/core/time/DateTime.h> +#include <ArmarXCore/core/time/Duration.h> +#include <ArmarXCore/core/time/ice_conversions.h> #include <ArmarXCore/observers/variant/TimestampVariant.h> - - - - namespace armarx { - void GamepadControlUnit::onInitComponent() + void + GamepadControlUnit::onInitComponent() { ARMARX_INFO << "oninit GamepadControlUnit"; usingProxy(getProperty<std::string>("PlatformUnitName").getValue()); @@ -41,67 +41,80 @@ namespace armarx scaleY = getProperty<float>("ScaleY").getValue(); scaleRotation = getProperty<float>("ScaleAngle").getValue(); ARMARX_INFO << "oninit GamepadControlUnit end"; - - - } - - void GamepadControlUnit::onConnectComponent() + void + GamepadControlUnit::onConnectComponent() { ARMARX_INFO << "onConnect GamepadControlUnit"; - platformUnitPrx = getProxy<PlatformUnitInterfacePrx>(getProperty<std::string>("PlatformUnitName").getValue()); + platformUnitPrx = getProxy<PlatformUnitInterfacePrx>( + getProperty<std::string>("PlatformUnitName").getValue()); emergencyStop = getProxy<EmergencyStopMasterInterfacePrx>("EmergencyStopMaster"); - } - void GamepadControlUnit::onDisconnectComponent() - { - + if (enableHeartBeat) + { + this->heartbeatPlugin->signUp(armarx::core::time::Duration::MilliSeconds(1000), + armarx::core::time::Duration::MilliSeconds(1500), + {"Gamepad"}, + "The GamepadControlUnit"); + } } + void + GamepadControlUnit::onDisconnectComponent() + { + } - void GamepadControlUnit::onExitComponent() + void + GamepadControlUnit::onExitComponent() { ARMARX_INFO << "exit GamepadControlUnit"; } - armarx::PropertyDefinitionsPtr GamepadControlUnit::createPropertyDefinitions() + armarx::PropertyDefinitionsPtr + GamepadControlUnit::createPropertyDefinitions() { - auto defs = armarx::PropertyDefinitionsPtr(new GamepadControlUnitPropertyDefinitions( - getConfigIdentifier())); - defs->topic(robotHealthTopic); - defs->optional(enableHeartBeat, "EnableHeartBeat", "Flag to enable send a heart beat to the robot healh topic"); - return defs; + auto defs = armarx::PropertyDefinitionsPtr( + new GamepadControlUnitPropertyDefinitions(getConfigIdentifier())); + defs->optional(enableHeartBeat, + "EnableHeartBeat", + "Flag to enable send a heart beat to the robot healh topic"); + return defs; } - void GamepadControlUnit::reportGamepadState(const std::string& device, const std::string& name, const GamepadData& data, const TimestampBasePtr& timestamp, const Ice::Current& c) + void + GamepadControlUnit::reportGamepadState(const std::string& device, + const std::string& name, + const GamepadData& data, + const TimestampBasePtr& timestamp, + const Ice::Current& c) { - // struct GamepadData { - // float leftStickX; - // float leftStickY; - // float rightStickX; - // float rightStickY; - // float dPadX; - // float dPadY; - // float leftTrigger; - // float rightTrigger; - // - // bool leftButton; - // bool rightButton; - // bool backButton; - // bool startButton; - // bool xButton; - // bool yButton; - // bool aButton; - // bool bButton; - // bool theMiddleButton; - // bool leftStickButton; - // bool rightStickButton; - // - // }; + // struct GamepadData { + // float leftStickX; + // float leftStickY; + // float rightStickX; + // float rightStickY; + // float dPadX; + // float dPadY; + // float leftTrigger; + // float rightTrigger; + // + // bool leftButton; + // bool rightButton; + // bool backButton; + // bool startButton; + // bool xButton; + // bool yButton; + // bool aButton; + // bool bButton; + // bool theMiddleButton; + // bool leftStickButton; + // bool rightStickButton; + // + // }; if (data.leftTrigger > 0) @@ -116,7 +129,9 @@ namespace armarx //scales are for the robot axis if (data.rightTrigger > 0) { - platformUnitPrx->move(data.leftStickY * scaleX, data. leftStickX * scaleY, data.rightStickX * scaleRotation); + platformUnitPrx->move(data.leftStickY * scaleX, + data.leftStickX * scaleY, + data.rightStickX * scaleRotation); } else { @@ -124,64 +139,68 @@ namespace armarx } - if (data.leftButton) - { - - if(leftHandTime <= 0.0) - { - leftHandTime = IceUtil::Time::now().toMicroSeconds(); - } - else if ((IceUtil::Time::now().toMicroSeconds() - leftHandTime) > 1000* 1000) - { - - HandUnitInterfacePrx handUnit = getProxy<HandUnitInterfacePrx>("LeftHandUnit"); - if (handUnit) - { - std::string shapeName = (leftHandOpen) ? "Close" : "Open"; - handUnit->setShape(shapeName); - leftHandOpen = !leftHandOpen; - leftHandTime = 0.0; - } - } - } - else - { - leftHandTime = 0.0; - } - - if(data.rightButton) - { - - if(rightHandTime <= 0.0) - { - rightHandTime = IceUtil::Time::now().toMicroSeconds(); - } - else if ((IceUtil::Time::now().toMicroSeconds() - rightHandTime) > 1000* 1000) - { - HandUnitInterfacePrx handUnit = getProxy<HandUnitInterfacePrx>("RightHandUnit"); - if (handUnit) - { - std::string shapeName = (rightHandOpen) ? "Close" : "Open"; - handUnit->setShape(shapeName); - rightHandOpen = !rightHandOpen; - rightHandTime = 0.0; - } - } - } - else - { - rightHandTime = 0.0; - } - - - if(enableHeartBeat) - { - RobotHealthHeartbeatArgs args; - args.maximumCycleTimeErrorMS = 1000; - robotHealthTopic->heartbeat(getDefaultName(), args); - - } - + if (data.leftButton) + { + + if (leftHandTime <= 0.0) + { + leftHandTime = IceUtil::Time::now().toMicroSeconds(); + } + else if ((IceUtil::Time::now().toMicroSeconds() - leftHandTime) > 1000 * 1000) + { + + HandUnitInterfacePrx handUnit = getProxy<HandUnitInterfacePrx>("LeftHandUnit"); + if (handUnit) + { + std::string shapeName = (leftHandOpen) ? "Close" : "Open"; + handUnit->setShape(shapeName); + leftHandOpen = !leftHandOpen; + leftHandTime = 0.0; + } + } + } + else + { + leftHandTime = 0.0; + } + + if (data.rightButton) + { + + if (rightHandTime <= 0.0) + { + rightHandTime = IceUtil::Time::now().toMicroSeconds(); + } + else if ((IceUtil::Time::now().toMicroSeconds() - rightHandTime) > 1000 * 1000) + { + HandUnitInterfacePrx handUnit = getProxy<HandUnitInterfacePrx>("RightHandUnit"); + if (handUnit) + { + std::string shapeName = (rightHandOpen) ? "Close" : "Open"; + handUnit->setShape(shapeName); + rightHandOpen = !rightHandOpen; + rightHandTime = 0.0; + } + } + } + else + { + rightHandTime = 0.0; + } + + + if (enableHeartBeat) + { + auto now = armarx::core::time::dto::DateTime(); + armarx::core::time::toIce(now, armarx::core::time::DateTime::Now()); + heartbeatPlugin->heartbeat(); + } + //ARMARX_INFO << "sending targets" << data.leftStickX* scaleX << " " << data.leftStickY* scaleY << " " << data.rightStickX* scaleRotation; } -} + + GamepadControlUnit::GamepadControlUnit() + { + addPlugin(heartbeatPlugin); + } +} // namespace armarx diff --git a/source/RobotAPI/components/GamepadControlUnit/GamepadControlUnit.h b/source/RobotAPI/components/GamepadControlUnit/GamepadControlUnit.h index da5945c44c7e289081df35385ea7e75184d69c90..9438f305fe6a96648eb4d6011112ea637a245369 100644 --- a/source/RobotAPI/components/GamepadControlUnit/GamepadControlUnit.h +++ b/source/RobotAPI/components/GamepadControlUnit/GamepadControlUnit.h @@ -30,6 +30,7 @@ #include <RobotAPI/interface/units/HandUnitInterface.h> +#include <RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.h> #include <RobotAPI/interface/components/RobotHealthInterface.h> #include <RobotAPI/interface/units/PlatformUnitInterface.h> @@ -72,6 +73,8 @@ namespace armarx virtual public GamepadUnitListener { public: + GamepadControlUnit(); + /** * @see armarx::ManagedIceObject::getDefaultName() */ @@ -109,10 +112,11 @@ namespace armarx private: PlatformUnitInterfacePrx platformUnitPrx; + plugins::HeartbeatComponentPlugin* heartbeatPlugin = nullptr; - bool enableHeartBeat = false; - RobotHealthInterfacePrx robotHealthTopic; + + bool enableHeartBeat = false; float scaleX; float scaleY; float scaleRotation; diff --git a/source/RobotAPI/components/RobotHealth/RobotHealth.cpp b/source/RobotAPI/components/RobotHealth/RobotHealth.cpp index 0e4b7f72ac1cc1f5f9b69b678c2d2f790c479184..0b67edc552c9bd77aa0f8ca78d95c2f2a5659282 100644 --- a/source/RobotAPI/components/RobotHealth/RobotHealth.cpp +++ b/source/RobotAPI/components/RobotHealth/RobotHealth.cpp @@ -20,296 +20,541 @@ * GNU General Public License */ -#include <ArmarXCore/util/CPPUtility/trace.h> - #include "RobotHealth.h" +#include "ArmarXCore/core/exceptions/local/ExpressionException.h" +#include "ArmarXCore/core/logging/Logging.h" +#include "ArmarXCore/core/time/Clock.h" +#include "ArmarXCore/core/time/DateTime.h" +#include "ArmarXCore/core/time/Duration.h" + +#include <SimoxUtility/algorithm/get_map_keys_values.h> +#include <SimoxUtility/algorithm/string/string_tools.h> +#include <algorithm> #include <boost/regex.hpp> +#include <ArmarXCore/core/time/ice_conversions.h> +#include <ArmarXCore/util/CPPUtility/trace.h> +#include <optional> namespace armarx { - void RobotHealth::onInitComponent() - { - ARMARX_TRACE; - monitorHealthTask = new PeriodicTask<RobotHealth>(this, &RobotHealth::monitorHealthTaskClb, 10); - defaultMaximumCycleTimeWarn = getProperty<int>("MaximumCycleTimeWarnMS").getValue(); - defaultMaximumCycleTimeErr = getProperty<int>("MaximumCycleTimeErrMS").getValue(); - usingTopic(getProperty<std::string>("RobotHealthTopicName").getValue()); - reportErrorsWithSpeech = getProperty<bool>("ReportErrorsWithSpeech").getValue(); - speechMinimumReportInterval = getProperty<int>("SpeechMinimumReportInterval").getValue(); + inline const std::string PROPERTY_REQUESTER_ID = "required_default"; + void + RobotHealth::onInitComponent() + { ARMARX_TRACE; - //robotUnitRequired = getProperty<bool>("RobotUnitRequired").getValue(); - /*if(robotUnitRequired) - { - ARMARX_IMPORTANT << "RobotUnit is required"; - usingProxy(getProperty<std::string>("RobotUnitName").getValue()); - }*/ + monitorUpdateHealthTask = + new PeriodicTask<RobotHealth>(this, &RobotHealth::monitorHealthUpdateTaskClb, 10); + defaultMaximumCycleTimeWarn = + armarx::core::time::Duration::MilliSeconds(p.maximumCycleTimeWarnMS); + defaultMaximumCycleTimeErr = + armarx::core::time::Duration::MilliSeconds(p.maximumCycleTimeErrMS); - //usingProxy(getProperty<std::string>("RemoteGuiName").getValue()); + const std::vector<std::string> requiredTags = simox::alg::split(p.requiredTags, ","); + // a special requester: cannot be changed during runtime. + tagsPerRequester[PROPERTY_REQUESTER_ID] = std::set<std::string>(requiredTags.begin(), requiredTags.end()); setDebugObserverBatchModeEnabled(true); } - - void RobotHealth::onConnectComponent() + void + RobotHealth::onConnectComponent() { ARMARX_TRACE; - emergencyStopTopicPrx = getTopic<EmergencyStopListenerPrx>(getProperty<std::string>("EmergencyStopTopicName").getValue()); - //remoteGuiPrx = getProxy<RemoteGuiInterfacePrx>(getProperty<std::string>("RemoteGuiName").getValue()); - aggregatedRobotHealthTopicPrx = getTopic<AggregatedRobotHealthInterfacePrx>(getProperty<std::string>("AggregatedRobotHealthTopicName").getValue()); - textToSpeechTopic = getTopic<TextListenerInterfacePrx>(getProperty<std::string>("TextToSpeechTopicName").getValue()); - lastSpeechOutput = TimeUtil::GetTime(); - - /*if(robotUnitRequired) - { - robotUnitPrx = getTopic<RobotUnitInterfacePrx>(getProperty<std::string>("RobotUnitName").getValue()); - robotUnitPrx->enableHeartbeat(); - }*/ - monitorHealthTask->start(); + monitorUpdateHealthTask->start(); } - void RobotHealth::monitorHealthTaskClb() + void + RobotHealth::monitorHealthUpdateTaskClb() { - ARMARX_TRACE; - long now = TimeUtil::GetTime().toMicroSeconds(); - bool hasNewErr = false; + std::shared_lock lock(updateMutex); - RobotHealthState healthState = RobotHealthState::HealthOK; + ARMARX_TRACE; + auto now = armarx::core::time::DateTime::Now(); - for (size_t i = 0; i < validEntries; i++) + for (size_t i = 0; i < updateEntries.size(); i++) { ARMARX_TRACE; - Entry& e = entries.at(i); - long delta = std::max(now - e.lastUpdate, e.lastDelta); - if (e.required && delta > e.maximumCycleTimeErr) + UpdateEntry& e = updateEntries.at(i); + + std::unique_lock elock(e.mutex); + + if (!e.enabled) { - healthState = RobotHealthState::HealthError; + continue; } - if (!e.enabled) + if(e.history.empty()) { continue; } - ARMARX_TRACE; + auto deltaToArrival = now - e.history.back().arrivalTime; - if (delta > e.maximumCycleTimeErr) + ARMARX_TRACE; + + if (deltaToArrival > e.maximumCycleTimeErr) { ARMARX_TRACE; - healthState = RobotHealthState::HealthError; - if (e.isRunning) + + if (e.state != HealthError) // not already in error state { ARMARX_TRACE; - ARMARX_ERROR << deactivateSpam(0.1, e.name) << "Component " << e.name << " has died."; - if (reportErrorsWithSpeech && (TimeUtil::GetTime() - lastSpeechOutput).toSecondsDouble() > speechMinimumReportInterval) - { - ARMARX_TRACE; - lastSpeechOutput = TimeUtil::GetTime(); - - std::string name; - - boost::smatch m; - boost::regex regex("^[a-zA-Z]+"); - if (boost::regex_search(e.name, m, regex)) - { - if (m.empty()) - { - name = "Whatever"; - } - else - { - name = m[0].str(); - } - } - - textToSpeechTopic->reportText("Oh no! Component " + name + " is no longer running."); - } - hasNewErr = true; - e.isRunning = false; + ARMARX_ERROR << deactivateSpam(0.1, e.name) << "Component " << e.name + << " has died."; + e.state = HealthError; } } - else if (e.isRunning && delta > e.maximumCycleTimeWarn) + else if (deltaToArrival > e.maximumCycleTimeWarn) { ARMARX_TRACE; - ARMARX_WARNING << deactivateSpam(0.1, e.name) << "Component " << e.name << " is running too slow."; - if (healthState == RobotHealthState::HealthOK) + ARMARX_WARNING << deactivateSpam(0.1, e.name) << "Component " << e.name + << " is running too slow."; + + e.state = HealthWarning; + } + else + { + // If everything is OK (again), update health + e.state = HealthOK; + } + } + + // update aggregated health + RobotHealthState overallHealthState = RobotHealthState::HealthOK; + + + // get aggregated status + for (size_t i = 0; i < updateEntries.size(); i++) + { + ARMARX_TRACE; + UpdateEntry& e = updateEntries.at(i); + + std::shared_lock elock(e.mutex); + + // trim history + while (e.history.size() > 20) + { + e.history.pop_front(); + } + + if (e.required) + { + if (e.state == HealthWarning && overallHealthState != HealthError) { - healthState = RobotHealthState::HealthWarning; + overallHealthState = RobotHealthState::HealthWarning; + } + else if (e.state == HealthError) + { + overallHealthState = RobotHealthState::HealthError; + } + } + else + { + if (e.state != HealthOK && overallHealthState != HealthError) + { + overallHealthState = RobotHealthState::HealthWarning; } } - } - if (hasNewErr) + + if (overallHealthState == HealthError) { ARMARX_TRACE; - emergencyStopTopicPrx->reportEmergencyStopState(EmergencyStopState::eEmergencyStopActive); + ARMARX_INFO << deactivateSpam(3) << "Requesting emergency stop"; + ARMARX_CHECK_NOT_NULL(p.emergencyStopTopicPrx); + p.emergencyStopTopicPrx->reportEmergencyStopState( + EmergencyStopState::eEmergencyStopActive); } ARMARX_TRACE; - aggregatedRobotHealthTopicPrx->aggregatedHeartbeat(healthState); - /*if(allRequiredRunning && robotUnitPrx) - { - try - { - robotUnitPrx->sendHeartbeat(); - } - catch(...) - {} - }*/ + ARMARX_CHECK_NOT_NULL(p.aggregatedRobotHealthTopicPrx); + p.aggregatedRobotHealthTopicPrx->aggregatedHeartbeat(overallHealthState); reportDebugObserver(); } - void RobotHealth::onDisconnectComponent() + void + RobotHealth::onDisconnectComponent() { //robotUnitPrx = nullptr; - monitorHealthTask->stop(); + monitorUpdateHealthTask->stop(); } + void + RobotHealth::onExitComponent() + { + } - void RobotHealth::onExitComponent() + armarx::PropertyDefinitionsPtr + RobotHealth::createPropertyDefinitions() { + auto defs = armarx::PropertyDefinitionsPtr( + new armarx::ComponentPropertyDefinitions(getConfigIdentifier())); + + defs->topic(p.emergencyStopTopicPrx, "EmergencyStop", + "The name of the topic over which changes of the emergencyStopState are sent."); + defs->topic<RobotHealthInterfacePrx>(p.robotHealthTopicName, "RobotHealthTopic", + "Name of the RobotHealth topic"); + + defs->topic(p.aggregatedRobotHealthTopicPrx, "AggregatedRobotHealthTopic", "Name of the AggregatedRobotHealthTopic"); + + defs->optional(p.maximumCycleTimeWarnMS, "MaximumCycleTimeWarnMS", + "Default value of the maximum cycle time for warnings"); + defs->optional(p.maximumCycleTimeErrMS, "MaximumCycleTimeErrMS", + "Default value of the maximum cycle time for error"); + + defs->optional(p.requiredTags, "RequiredTags", "Tags that should be requested."); + + return defs; } - armarx::PropertyDefinitionsPtr RobotHealth::createPropertyDefinitions() + RobotHealth::UpdateEntry* + RobotHealth::findUpdateEntry(const std::string& name) { - return armarx::PropertyDefinitionsPtr(new RobotHealthPropertyDefinitions( - getConfigIdentifier())); + ARMARX_TRACE; + + for (size_t i = 0; i < updateEntries.size(); i++) + { + if (updateEntries.at(i).name == name) + { + return &updateEntries.at(i); + } + } + + return nullptr; } - RobotHealth::Entry& RobotHealth::findOrCreateEntry(const std::string& name) + std::pair<bool, RobotHealth::UpdateEntry&> + RobotHealth::findOrCreateUpdateEntry(const std::string& name) { ARMARX_TRACE; - for (size_t i = 0; i < entries.size(); i++) { - if (entries.at(i).name == name) + for (size_t i = 0; i < updateEntries.size(); i++) { - return entries.at(i); + if (updateEntries.at(i).name == name) + { + return {false, updateEntries.at(i)}; + } } } - std::unique_lock lock(mutex); - ARMARX_INFO << "registering '" << name << "'"; - entries.emplace_back(name, defaultMaximumCycleTimeWarn * 1000, defaultMaximumCycleTimeErr * 1000); - validEntries++; - return entries.back(); - } + ARMARX_INFO << "registering for heartbeat: '" << name << "'"; + + updateEntries.emplace_back(name, defaultMaximumCycleTimeWarn, defaultMaximumCycleTimeErr); + return {true, updateEntries.back()}; + } - void RobotHealth::heartbeat(const std::string& componentName, const RobotHealthHeartbeatArgs& args, const Ice::Current&) + void + RobotHealth::signUp(const RobotHealthHeartbeatArgs& args, const Ice::Current& current) { ARMARX_TRACE; - Entry& e = findOrCreateEntry(componentName); - long now = TimeUtil::GetTime().toMicroSeconds(); - e.maximumCycleTimeWarn = args.maximumCycleTimeWarningMS * 1000; - e.maximumCycleTimeErr = args.maximumCycleTimeErrorMS * 1000; - if (!e.isRunning) + std::unique_lock lockU(updateMutex); + + auto e = findOrCreateUpdateEntry(args.identifier); + { - ARMARX_INFO << "'" << componentName << "' is now alive and running"; - e.lastDelta = 0; + std::unique_lock lock(e.second.mutex); + + if (e.first) + { + ARMARX_INFO << "Newly registering component " << args.identifier << " for updates."; + } + // else no messsage as components may spam sign up for legacy reasons (when there was no sign up) + + armarx::core::time::fromIce(args.maximumCycleTimeWarning, e.second.maximumCycleTimeWarn); + armarx::core::time::fromIce(args.maximumCycleTimeError, e.second.maximumCycleTimeErr); + + e.second.tags = args.tags; + // e.second.required = args.requiredByDefault; // FIXME + e.second.description = args.description; + e.second.enabled = true; + e.second.state = HealthOK; + e.second.history.clear(); } - else + + updateRequiredElements(); + } + + void + RobotHealth::heartbeat(const std::string& identifier, + const core::time::dto::DateTime& referenceTime, + const Ice::Current& current) + { + ARMARX_TRACE; + ARMARX_VERBOSE << "Finding update entry"; + + const DateTime arrivalTimestamp = Clock::Now(); + + + // We hold a reference to 'o' which is an element in a vector. + // If we don't lock until the end of this scope, the vector size might change and 'o' will be invalidated. + std::shared_lock lockU(updateMutex); + auto* const entry = findUpdateEntry(identifier); + + if (entry == nullptr) { - e.lastDelta = now - e.lastUpdate; - e.history.at(e.historyIndex) = e.lastDelta; - e.historyIndex = (e.historyIndex + 1) % e.history.size(); + ARMARX_WARNING << deactivateSpam() << "Attention. Component `" << identifier + << "` was not signed up for heartbeat. Ignoring heartbeat for now..."; + return; } - ARMARX_TRACE; - e.lastUpdate = now; - e.isRunning = true; - e.enabled = true; + + ARMARX_CHECK_NOT_NULL(entry); + + std::unique_lock lock(entry->mutex); + + if (not entry->enabled) { - std::unique_lock lock(e.messageMutex); - e.message = args.message; + ARMARX_WARNING << deactivateSpam() << "Attention. Component `" << identifier + << "` was not enabled. The heartbeat is ignored... "; + return; } - } - void armarx::RobotHealth::unregister(const std::string& componentName, const Ice::Current&) - { - ARMARX_TRACE; - Entry& e = findOrCreateEntry(componentName); - e.isRunning = false; - e.enabled = false; - ARMARX_INFO << "unregistering " << componentName; + ARMARX_VERBOSE << "Extending history"; + // auto now = armarx::core::time::DateTime::Now(); + + + armarx::core::time::DateTime refTime; + fromIce(referenceTime, refTime); + entry->history.push_back(UpdateEntry::TimeInfo{.referenceTime = refTime, .arrivalTime = arrivalTimestamp}); } - std::string RobotHealth::getSummary(const Ice::Current&) + void + armarx::RobotHealth::unregister(const std::string& componentName, const Ice::Current&) { ARMARX_TRACE; - long now = TimeUtil::GetTime().toMicroSeconds(); - std::stringstream ss; - for (size_t i = 0; i < validEntries; i++) + std::shared_lock lock(updateMutex); + + bool found = false; { - ARMARX_TRACE; - Entry& e = entries.at(i); - long delta = std::max(now - e.lastUpdate, e.lastDelta); + std::shared_lock lock(updateMutex); - long minDelta = delta; - long maxDelta = delta; - for (size_t i = 1; i < e.history.size(); i++) + for (size_t i = 0; i < updateEntries.size(); i++) { - long historicalDelta = e.history.at(i); - if (historicalDelta < 0) + auto& e = updateEntries.at(i); + if (e.name == componentName) { + std::unique_lock elock(e.mutex); + e.required = false; + e.enabled = false; + found = true; break; } - minDelta = std::min(minDelta, historicalDelta); - maxDelta = std::max(maxDelta, historicalDelta); } + // Todo upgrade lock? + } - ss << e.name; - if (e.required) + if (found) + { + ARMARX_INFO << "Component " << componentName << " disabled from heartbeat"; + } + else + { + ARMARX_INFO << "Could not unregister component " << componentName << ". Not found."; + } + + updateRequiredElements(); + } + + void + armarx::RobotHealth::addRequiredTags(const std::string& requesterIdentifier, + const std::vector<std::string>& tags, + const Ice::Current& current) + { + std::shared_lock lock(updateMutex); + + // add newly requested tags + for(const auto& tag : tags) + { + tagsPerRequester[requesterIdentifier].insert(tag); + } + + updateRequiredElements(); + } + + std::set<std::string> + armarx::RobotHealth::requestedTags() const + { + // obtain a list of all tags that are relevant / requested at the moment + std::set<std::string> allRequestedTags; + for(const auto& tgs: simox::alg::get_values(tagsPerRequester)) + { + for(const auto& tag : tgs) { - ss << ", required"; + allRequestedTags.insert(tag); } + } + return allRequestedTags; + } - if (!e.required && !e.enabled) - { - ss << ": disabled"; + // checks whether any element in 'search' is in 'values' + bool containsAnyOf(const std::set<std::string>& values, const std::vector<std::string>& searchKeys) + { + return std::any_of(searchKeys.begin(), searchKeys.end(), [&values](const auto& key){ + return values.count(key) > 0; + }); + } + + void armarx::RobotHealth::updateRequiredElements() + { + ARMARX_IMPORTANT << "updateRequiredElements"; + const std::set<std::string> allRequestedTags = requestedTags(); + + for (auto &e : updateEntries) { + ARMARX_INFO << e.name; + + e.required = false; // if required, will be set in the following + + std::unique_lock lock(e.mutex); + + if (containsAnyOf(allRequestedTags, e.tags)) { + ARMARX_INFO << e.name << " is required."; + e.required = true; + if (not e.enabled) { + ARMARX_WARNING << "You are requiring the disabled component " + << e.name << ". Enabling it..."; + e.enabled = true; + } } - else + } + } + + void + armarx::RobotHealth::removeRequiredTags(const std::string& requesterIdentifier, + const std::vector<std::string>& tags, + const Ice::Current& current) + { + std::shared_lock lock(updateMutex); + + // update the required tags list / map + for(const auto& tag : tags) + { + tagsPerRequester[requesterIdentifier].erase(tag); + } + + updateRequiredElements(); + } + + void + armarx::RobotHealth::resetRequiredTags(const Ice::Current& current) + { + std::shared_lock lock(updateMutex); + + // treat the special provider (see onInitComponent()) appropriately + ARMARX_CHECK(tagsPerRequester.count(PROPERTY_REQUESTER_ID) > 0); + const auto propertyProviderTags = tagsPerRequester.at(PROPERTY_REQUESTER_ID); + + // clear everything except the special provider + tagsPerRequester.clear(); + tagsPerRequester.emplace(PROPERTY_REQUESTER_ID, propertyProviderTags); + } + + RobotHealthInfo + RobotHealth::getSummary(const Ice::Current&) + { + std::shared_lock lock(updateMutex); + + ARMARX_TRACE; + RobotHealthInfo ret; + + auto now = armarx::core::time::DateTime::Now(); + + armarx::core::time::Duration minDelta; + armarx::core::time::Duration maxDelta; + + for (const auto& e : updateEntries) + { + RobotHealthInfoEntry healthEntry; + + for (size_t i = 1; i < e.history.size(); i++) { - if (delta > e.maximumCycleTimeErr) - { - ss << ": ERROR"; - } - else if (delta > e.maximumCycleTimeWarn) + auto later = e.history[i]; + auto pre = e.history[i - 1]; + + auto delta = later.arrivalTime - pre.arrivalTime; + + if (minDelta > delta) { - ss << ": warning"; + minDelta = delta; } - else + + if (maxDelta < delta) { - ss << ": ok"; + maxDelta = delta; } - ss << " (" << (delta / 1000) << "ms, min: " << (minDelta / 1000) << "ms, max: " << (maxDelta / 1000) << "ms)"; } - ARMARX_TRACE; - std::unique_lock lock(e.messageMutex); - if (e.message.size()) - { - ss << " - " << e.message; - } + const Duration timeSinceLastUpdateArrival = e.history.empty() ? Duration() : Clock::Now() - e.history.back().arrivalTime; + const Duration timeSinceLastUpdateReference = e.history.empty() ? Duration() : Clock::Now() - e.history.back().referenceTime; + + const DateTime lastReferenceTime = e.history.empty() ? armarx::core::time::DateTime::Invalid() : e.history.back().referenceTime; + + const Duration timeSyncDelayAndIce = e.history.empty() ? armarx::core::time::Duration() : e.history.back().arrivalTime - e.history.back().referenceTime; - ss << "\n"; + healthEntry.identifier = e.name; + healthEntry.state = e.state; + healthEntry.enabled = e.enabled; + healthEntry.required = e.required; + toIce(healthEntry.minDelta, minDelta); + toIce(healthEntry.maxDelta,maxDelta); + toIce(healthEntry.lastReferenceTimestamp, lastReferenceTime); + toIce(healthEntry.timeSinceLastArrival, timeSinceLastUpdateArrival); + toIce(healthEntry.timeSyncDelayAndIce, timeSyncDelayAndIce); + toIce(healthEntry.timeSinceLastUpdateReference, timeSinceLastUpdateReference); + toIce(healthEntry.maximumCycleTimeWarning, e.maximumCycleTimeWarn); + toIce(healthEntry.maximumCycleTimeError, e.maximumCycleTimeErr); + healthEntry.tags = e.tags; + ret.entries[e.name] = healthEntry; } - return ss.str(); + + const auto tags = requestedTags(); + ret.activeTags = std::vector<std::string>(tags.begin(), tags.end()); + + return ret; } - void RobotHealth::reportDebugObserver() + std::string + RobotHealth::getTopicName(const Ice::Current& current) { - for(const auto& entry: entries) + return p.robotHealthTopicName; + } + + void + RobotHealth::reportDebugObserver() + { + for (const auto& entry : updateEntries) { - setDebugObserverDatafield("RobotHealth_" + entry.name + "_lastDelta", entry.lastDelta); - setDebugObserverDatafield("RobotHealth_" + entry.name + "_maximumCycleTimeWarn", entry.maximumCycleTimeWarn); - setDebugObserverDatafield("RobotHealth_" + entry.name + "_maximumCycleTimeErr", entry.maximumCycleTimeErr); + if (entry.history.size() > 1) + { + auto later = entry.history[entry.history.size() - 1]; + auto pre = entry.history[entry.history.size() - 2]; + const Duration delta = later.arrivalTime - pre.arrivalTime; + + const Duration timeSinceLastArrival = Clock::Now() - entry.history.back().arrivalTime; + const Duration timeToLastReference = Clock::Now() - entry.history.back().referenceTime; + const Duration timeSyncDelay = entry.history.back().arrivalTime - entry.history.back().referenceTime; + + setDebugObserverDatafield("RobotHealth_" + entry.name + "_lastDelta", + delta.toMilliSecondsDouble()); + setDebugObserverDatafield("RobotHealth_" + entry.name + "_timeSinceLastArrival", + timeSinceLastArrival.toMilliSecondsDouble()); + setDebugObserverDatafield("RobotHealth_" + entry.name + "_timeToLastReference", + timeToLastReference.toMilliSecondsDouble()); + setDebugObserverDatafield("RobotHealth_" + entry.name + "_timeSyncDelayAndIce", + timeSyncDelay.toMilliSecondsDouble()); + setDebugObserverDatafield("RobotHealth_" + entry.name + "_maximumCycleTimeWarn", + entry.maximumCycleTimeWarn.toMilliSecondsDouble()); + setDebugObserverDatafield("RobotHealth_" + entry.name + "_maximumCycleTimeErr", + entry.maximumCycleTimeErr.toMilliSecondsDouble()); + } } sendDebugObserverBatch(); } -} +} // namespace armarx diff --git a/source/RobotAPI/components/RobotHealth/RobotHealth.h b/source/RobotAPI/components/RobotHealth/RobotHealth.h index 3da12c1797ffa0afbc9af7310ec40953ecc51309..a27f864e8f639983650ece96ac8d101f709b8618 100644 --- a/source/RobotAPI/components/RobotHealth/RobotHealth.h +++ b/source/RobotAPI/components/RobotHealth/RobotHealth.h @@ -22,54 +22,28 @@ #pragma once -#include <RobotAPI/interface/components/RobotHealthInterface.h> -#include <RobotAPI/interface/units/RobotUnit/RobotUnitInterface.h> -#include <RobotAPI/interface/speech/SpeechInterface.h> - -#include <ArmarXGui/interface/RemoteGuiInterface.h> +#include <array> +#include <atomic> +#include <deque> +#include <mutex> -#include <ArmarXCore/core/time/TimeUtil.h> #include <ArmarXCore/core/Component.h> #include <ArmarXCore/core/services/tasks/PeriodicTask.h> +#include <ArmarXCore/core/time/DateTime.h> +#include <ArmarXCore/core/time/Duration.h> +#include <ArmarXCore/core/time/Frequency.h> +#include <ArmarXCore/core/time/TimeUtil.h> #include <ArmarXCore/interface/components/EmergencyStopInterface.h> #include <ArmarXCore/libraries/ArmarXCoreComponentPlugins/DebugObserverComponentPlugin.h> -#include <atomic> -#include <mutex> +#include <ArmarXGui/interface/RemoteGuiInterface.h> + +#include <RobotAPI/interface/components/RobotHealthInterface.h> +#include <RobotAPI/interface/speech/SpeechInterface.h> +#include <RobotAPI/interface/units/RobotUnit/RobotUnitInterface.h> namespace armarx { - /** - * @class RobotHealthPropertyDefinitions - * @brief - */ - class RobotHealthPropertyDefinitions: - public armarx::ComponentPropertyDefinitions - { - public: - RobotHealthPropertyDefinitions(std::string prefix): - armarx::ComponentPropertyDefinitions(prefix) - { - defineOptionalProperty<std::string>("EmergencyStopTopicName", "EmergencyStop", "The name of the topic over which changes of the emergencyStopState are sent."); - defineOptionalProperty<std::string>("RobotHealthTopicName", "RobotHealthTopic", "Name of the RobotHealth topic"); - defineOptionalProperty<bool>("ReportErrorsWithSpeech", true, ""); - defineOptionalProperty<std::string>("TextToSpeechTopicName", "TextToSpeech", "Name of the TextToSpeech topic"); - defineOptionalProperty<int>("MaximumCycleTimeWarnMS", 50, "Default value of the maximum cycle time for warnings"); - defineOptionalProperty<int>("MaximumCycleTimeErrMS", 100, "Default value of the maximum cycle time for error"); - defineOptionalProperty<std::string>("AggregatedRobotHealthTopicName", "AggregatedRobotHealthTopic", "Name of the AggregatedRobotHealthTopic"); - defineOptionalProperty<std::string>("RequiredComponents", "", "Comma separated list of required components"); - - defineOptionalProperty<int>("SpeechMinimumReportInterval", 60, "Time that has to pass between reported messages in seconds."); - - //defineOptionalProperty<std::string>("RemoteGuiName", "RemoteGuiProvider", "Name of the remote GUI provider"); - //defineOptionalProperty<std::string>("RobotUnitName", "Armar6Unit", "Name of the RobotUnit"); - //defineOptionalProperty<bool>("RobotUnitRequired", true, "Wait for RobotUnit"); - - //defineRequiredProperty<std::string>("PropertyName", "Description"); - //defineOptionalProperty<std::string>("PropertyName", "DefaultValue", "Description"); - } - }; - /** * @defgroup Component-RobotHealth RobotHealth * @ingroup RobotAPI-Components @@ -90,34 +64,12 @@ namespace armarx /** * @see armarx::ManagedIceObject::getDefaultName() */ - std::string getDefaultName() const override + std::string + getDefaultName() const override { return "RobotHealth"; } - struct Entry - { - Entry(std::string name, long maximumCycleTimeWarn, long maximumCycleTimeErr) - : name(name), maximumCycleTimeWarn(maximumCycleTimeWarn), maximumCycleTimeErr(maximumCycleTimeErr), history(100, -1) - {} - Entry(Entry&&) = default; - Entry& operator=(Entry&&) = default; - - std::string name; - long maximumCycleTimeWarn; - long maximumCycleTimeErr; - long lastUpdate = 0; - long lastDelta = 0; - RobotHealthState state = HealthOK; - std::string message = ""; - bool isRunning = false; - bool required = false; - bool enabled = true; - std::mutex messageMutex; - std::vector<long> history; - size_t historyIndex = 0; - }; - protected: /** * @see armarx::ManagedIceObject::onInitComponent() @@ -144,32 +96,100 @@ namespace armarx */ armarx::PropertyDefinitionsPtr createPropertyDefinitions() override; - void monitorHealthTaskClb(); - Entry& findOrCreateEntry(const std::string& name); + private: + struct UpdateEntry + { + UpdateEntry(const std::string& name, + const armarx::core::time::Duration& maximumCycleTimeWarn, + const armarx::core::time::Duration& maximumCycleTimeErr) : + name(name), + maximumCycleTimeWarn(maximumCycleTimeWarn), + maximumCycleTimeErr(maximumCycleTimeErr) + { + } - void reportDebugObserver(); + std::string name; + std::vector<std::string> tags; + RobotHealthState state = HealthOK; + std::string description = ""; + + bool required = false; + bool enabled = false; + + mutable std::shared_mutex mutex; - std::mutex mutex; - std::deque<Entry> entries; - std::atomic_size_t validEntries {0}; - PeriodicTask<RobotHealth>::pointer_type monitorHealthTask; - int defaultMaximumCycleTimeWarn; - int defaultMaximumCycleTimeErr; - EmergencyStopListenerPrx emergencyStopTopicPrx; - //RobotUnitInterfacePrx robotUnitPrx; - //bool robotUnitRequired; - RemoteGuiInterfacePrx remoteGuiPrx; - AggregatedRobotHealthInterfacePrx aggregatedRobotHealthTopicPrx; - TextListenerInterfacePrx textToSpeechTopic; - bool reportErrorsWithSpeech; - int speechMinimumReportInterval; - IceUtil::Time lastSpeechOutput; + struct TimeInfo + { + //< Timestamp sent by component + armarx::core::time::DateTime referenceTime; + + //< Timestamp on this PC, set by this component + armarx::core::time::DateTime arrivalTime; + }; + + std::deque<TimeInfo> history; + + armarx::core::time::Duration maximumCycleTimeWarn; + armarx::core::time::Duration maximumCycleTimeErr; + }; + + void monitorHealthUpdateTaskClb(); + + UpdateEntry* findUpdateEntry(const std::string& name); + std::pair<bool, UpdateEntry&> findOrCreateUpdateEntry(const std::string& name); + + void reportDebugObserver(); // RobotHealthInterface interface public: - void heartbeat(const std::string& componentName, const RobotHealthHeartbeatArgs& args, const Ice::Current&) override; - void unregister(const std::string& componentName, const Ice::Current&) override; - std::string getSummary(const Ice::Current&) override; + void signUp(const RobotHealthHeartbeatArgs& args, const Ice::Current& current) override; + void unregister(const std::string& identifier, const Ice::Current&) override; + + + void addRequiredTags(const std::string& requesterIdentifier, + const std::vector<std::string>& tags, + const Ice::Current& current) override; + void removeRequiredTags(const std::string& requesterIdentifier, + const std::vector<std::string>& tags, + const Ice::Current& current) override; + void resetRequiredTags(const Ice::Current& current) override; + + + void heartbeat(const std::string& identifier, + const core::time::dto::DateTime& referenceTime, + const Ice::Current& current) override; + + std::string getTopicName(const Ice::Current& current) override; + + // RobotHealthComponentInterface interface + public: + RobotHealthInfo getSummary(const Ice::Current& current) override; + private: + void updateRequiredElements(); + std::set<std::string> requestedTags() const; + + mutable std::shared_mutex updateMutex; + + std::deque<UpdateEntry> updateEntries; + + std::map<std::string, std::set<std::string>> tagsPerRequester; + + PeriodicTask<RobotHealth>::pointer_type monitorUpdateHealthTask; + + armarx::core::time::Duration defaultMaximumCycleTimeWarn; + armarx::core::time::Duration defaultMaximumCycleTimeErr; + + struct Properties + { + EmergencyStopListenerPrx emergencyStopTopicPrx; + std::string robotHealthTopicName = "RobotHealthTopic"; + AggregatedRobotHealthInterfacePrx aggregatedRobotHealthTopicPrx; + RemoteGuiInterfacePrx remoteGuiPrx; + long maximumCycleTimeWarnMS = 50; + long maximumCycleTimeErrMS = 100; + + std::string requiredTags; + } p; }; -} +} // namespace armarx diff --git a/source/RobotAPI/components/RobotHealth/RobotHealthDummy.cpp b/source/RobotAPI/components/RobotHealth/RobotHealthDummy.cpp index b239fdd0719716c1e579a803a6a89265168240c3..e028bc55648f02446b5980cc00124950d4564219 100644 --- a/source/RobotAPI/components/RobotHealth/RobotHealthDummy.cpp +++ b/source/RobotAPI/components/RobotHealth/RobotHealthDummy.cpp @@ -21,26 +21,35 @@ */ #include "RobotHealthDummy.h" + #include <time.h> + #include <thread> +#include <ArmarXCore/core/time/DateTime.h> +#include <ArmarXCore/core/time/ice_conversions.h> + namespace armarx { - void RobotHealthDummy::onInitComponent() + void + RobotHealthDummy::onInitComponent() { dummyTask = new RunningTask<RobotHealthDummy>(this, &RobotHealthDummy::runTask); getProperty(sleepmode, "SleepMode"); } - - void RobotHealthDummy::onConnectComponent() + void + RobotHealthDummy::onConnectComponent() { - robotHealthTopicPrx = getTopic<RobotHealthInterfacePrx>(getProperty<std::string>("RobotHealthTopicName").getValue()); + robotHealthTopicPrx = getTopic<RobotHealthInterfacePrx>( + getProperty<std::string>("RobotHealthTopicName").getValue()); dummyTask->start(); } -#define NANOSECS_PER_SEC 1000000000 - int RobotHealthDummy::NanoSleep(long nanosec) +#define NANOSECS_PER_SEC 1000000000 + + int + RobotHealthDummy::NanoSleep(long nanosec) { struct timespec ts; ts.tv_sec = nanosec / NANOSECS_PER_SEC; @@ -48,48 +57,55 @@ namespace armarx return nanosleep(&ts, nullptr); // jitter up to +100ms! } - void RobotHealthDummy::sleepwait(long microseconds) + void + RobotHealthDummy::sleepwait(long microseconds) { long start = TimeUtil::GetTime().toMicroSeconds(); auto end = start + microseconds; do { NanoSleep(1000); - } - while (TimeUtil::GetTime().toMicroSeconds() < end); + } while (TimeUtil::GetTime().toMicroSeconds() < end); } - void RobotHealthDummy::yieldwait(long microseconds) + + void + RobotHealthDummy::yieldwait(long microseconds) { long start = TimeUtil::GetTime().toMicroSeconds(); auto end = start + microseconds; do { std::this_thread::yield(); - } - while (TimeUtil::GetTime().toMicroSeconds() < end); // jitter up to +25ms... + } while (TimeUtil::GetTime().toMicroSeconds() < end); // jitter up to +25ms... } - void RobotHealthDummy::busydwait(long microseconds) + + void + RobotHealthDummy::busydwait(long microseconds) { long start = TimeUtil::GetTime().toMicroSeconds(); auto end = start + microseconds; do { ; - } - while (TimeUtil::GetTime().toMicroSeconds() < end); + } while (TimeUtil::GetTime().toMicroSeconds() < end); } - void RobotHealthDummy::runTask() + void + RobotHealthDummy::runTask() { - - + auto args = RobotHealthHeartbeatArgs(); + args.identifier = getName(); + robotHealthTopicPrx->signUp(args); ARMARX_INFO << "starting rinning task"; while (!dummyTask->isStopped()) { long beforeTopicCall = TimeUtil::GetTime().toMicroSeconds(); //ARMARX_INFO << "send heartbeat"; - robotHealthTopicPrx->heartbeat(getName(), RobotHealthHeartbeatArgs()); + + armarx::core::time::dto::DateTime now; + armarx::core::time::toIce(now, armarx::core::time::DateTime::Now()); + robotHealthTopicPrx->heartbeat(getName(), now); long afterTopicCall = TimeUtil::GetTime().toMicroSeconds(); if (sleepmode == "nanosleep") { @@ -126,23 +142,24 @@ namespace armarx } } - - void RobotHealthDummy::onDisconnectComponent() + void + RobotHealthDummy::onDisconnectComponent() { //ARMARX_IMPORTANT << "onDisconnectComponent"; dummyTask->stop(); } - - void RobotHealthDummy::onExitComponent() + void + RobotHealthDummy::onExitComponent() { //ARMARX_IMPORTANT << "onExitComponent"; dummyTask->stop(); } - armarx::PropertyDefinitionsPtr RobotHealthDummy::createPropertyDefinitions() + armarx::PropertyDefinitionsPtr + RobotHealthDummy::createPropertyDefinitions() { - return armarx::PropertyDefinitionsPtr(new RobotHealthDummyPropertyDefinitions( - getConfigIdentifier())); + return armarx::PropertyDefinitionsPtr( + new RobotHealthDummyPropertyDefinitions(getConfigIdentifier())); } -} +} // namespace armarx diff --git a/source/RobotAPI/components/RobotHealth/RobotHealthDummy.h b/source/RobotAPI/components/RobotHealth/RobotHealthDummy.h index cb9d46377437764fac06cb4a9535d1adabb5534c..cfd8d369d0335768c2e85dd735f1d31d1e30e60d 100644 --- a/source/RobotAPI/components/RobotHealth/RobotHealthDummy.h +++ b/source/RobotAPI/components/RobotHealth/RobotHealthDummy.h @@ -24,10 +24,10 @@ #include <ArmarXCore/core/Component.h> -#include <RobotAPI/interface/components/RobotHealthInterface.h> #include <ArmarXCore/core/services/tasks/RunningTask.h> #include <ArmarXCore/core/time/TimeUtil.h> +#include <RobotAPI/interface/components/RobotHealthInterface.h> namespace armarx { @@ -35,15 +35,18 @@ namespace armarx * @class RobotHealthDummyPropertyDefinitions * @brief */ - class RobotHealthDummyPropertyDefinitions: - public armarx::ComponentPropertyDefinitions + class RobotHealthDummyPropertyDefinitions : public armarx::ComponentPropertyDefinitions { public: - RobotHealthDummyPropertyDefinitions(std::string prefix): + RobotHealthDummyPropertyDefinitions(std::string prefix) : armarx::ComponentPropertyDefinitions(prefix) { - defineOptionalProperty<std::string>("RobotHealthTopicName", "RobotHealthTopic", "Name of the RobotHealth topic"); - defineOptionalProperty<std::string>("SleepMode", "nanosleep", "Which sleep function to use: nanosleep, sleepwait, yieldwait, busywait"); + defineOptionalProperty<std::string>( + "RobotHealthTopicName", "RobotHealthTopic", "Name of the RobotHealth topic"); + defineOptionalProperty<std::string>( + "SleepMode", + "nanosleep", + "Which sleep function to use: nanosleep, sleepwait, yieldwait, busywait"); //defineRequiredProperty<std::string>("PropertyName", "Description"); //defineOptionalProperty<std::string>("PropertyName", "DefaultValue", "Description"); @@ -61,14 +64,14 @@ namespace armarx * * Detailed description of class RobotHealthDummy. */ - class RobotHealthDummy : - virtual public armarx::Component + class RobotHealthDummy : virtual public armarx::Component { public: /** * @see armarx::ManagedIceObject::getDefaultName() */ - std::string getDefaultName() const override + std::string + getDefaultName() const override { return "RobotHealthDummy"; } @@ -77,6 +80,7 @@ namespace armarx void yieldwait(long microseconds); void busydwait(long microseconds); void sleepwait(long microseconds); + protected: /** * @see armarx::ManagedIceObject::onInitComponent() @@ -109,6 +113,5 @@ namespace armarx RunningTask<RobotHealthDummy>::pointer_type dummyTask; std::string sleepmode; - }; -} +} // namespace armarx diff --git a/source/RobotAPI/components/armem/client/ExampleMemoryClient/CMakeLists.txt b/source/RobotAPI/components/armem/client/ExampleMemoryClient/CMakeLists.txt index b9434aeb6575293b01482473f3467403e969ab86..d177d23e37b51f1de6a96ceee909e5f4a4b18819 100644 --- a/source/RobotAPI/components/armem/client/ExampleMemoryClient/CMakeLists.txt +++ b/source/RobotAPI/components/armem/client/ExampleMemoryClient/CMakeLists.txt @@ -10,7 +10,8 @@ set(COMPONENT_LIBS RobotAPICore RobotAPIInterfaces armem aronopencvconverter aronjsonconverter - + # ExampleMemory_aron + ExampleMemory # actually, the aron version is sufficient ${OpenCV_LIBRARIES} ) diff --git a/source/RobotAPI/components/armem/server/ExampleMemory/aron/ExampleData.xml b/source/RobotAPI/components/armem/server/ExampleMemory/aron/ExampleData.xml index 4efce411b680ce9a91afceff7da5523b8f67d6cc..d204c95fac16b40f110555729049a5da632d8846 100644 --- a/source/RobotAPI/components/armem/server/ExampleMemory/aron/ExampleData.xml +++ b/source/RobotAPI/components/armem/server/ExampleMemory/aron/ExampleData.xml @@ -20,13 +20,13 @@ An example data containing different native ARON types. <GenerateTypes> <Object name='armarx::armem::example::InnerClass'> <ObjectChild key='element_int'> - <Int /> + <int32 default="42" /> </ObjectChild> <ObjectChild key='element_float'> - <Float /> + <float32 default="666.66" /> </ObjectChild> <ObjectChild key='element_string'> - <String /> + <String default="foobar" /> </ObjectChild> </Object> diff --git a/source/RobotAPI/components/units/RobotUnit/util/ControlThreadOutputBuffer.cpp b/source/RobotAPI/components/units/RobotUnit/util/ControlThreadOutputBuffer.cpp index 1327e8e353890c42fb2200c253e42ff03325be35..f230d88c16da317777eebc3667d5d1bbff3f9f15 100644 --- a/source/RobotAPI/components/units/RobotUnit/util/ControlThreadOutputBuffer.cpp +++ b/source/RobotAPI/components/units/RobotUnit/util/ControlThreadOutputBuffer.cpp @@ -78,7 +78,7 @@ namespace armarx ARMARX_CHECK_EXPRESSION(isInitialized); if (writePosition - onePastLoggingReadPosition >= numEntries) { - ARMARX_ERROR << "There are " << writePosition - onePastLoggingReadPosition + ARMARX_VERBOSE << "There are " << writePosition - onePastLoggingReadPosition << " unlogged entries, but only the last " << numEntries << " are saved! " "There seems to be something wrong (e.g. the rt logging threw an exception, " "the system load is too high or the logging takes to long). " @@ -89,7 +89,7 @@ namespace armarx auto numNewEntries = writePosition - onePastLoggingReadPosition; if (numNewEntries >= numEntries) { - ARMARX_ERROR << " more new entries (" << numNewEntries << ") than space (" << numEntries << ") -> Skipping everything else"; + ARMARX_VERBOSE << " more new entries (" << numNewEntries << ") than space (" << numEntries << ") -> Skipping everything else"; return; } //consume all @@ -109,7 +109,7 @@ namespace armarx auto newNumNewEntries = writePosition - onePastLoggingReadPosition; if (newNumNewEntries * 2 > numEntries) { - ARMARX_WARNING << deactivateSpam(0.5) + ARMARX_VERBOSE << deactivateSpam(5) << "RT-Logging is slow! " << "The RT-Thread writes faster new data than the RT-Logging thread consumes it! " << " old/new/max number of entries: " @@ -118,7 +118,7 @@ namespace armarx numNewEntries = newNumNewEntries; if (numNewEntries >= numEntries) { - ARMARX_ERROR << " more new entries (" << numNewEntries << ") than space (" << numEntries << ") -> Skipping everything else"; + ARMARX_VERBOSE << " more new entries (" << numNewEntries << ") than space (" << numEntries << ") -> Skipping everything else"; return; } } @@ -132,7 +132,7 @@ namespace armarx ARMARX_CHECK_EXPRESSION(isInitialized); if (writePosition - onePastLoggingReadPosition >= numEntries) { - ARMARX_ERROR << "There are " << writePosition - onePastLoggingReadPosition + ARMARX_VERBOSE << "There are " << writePosition - onePastLoggingReadPosition << " unlogged entries, but only the last " << numEntries << " are saved! " "There seems to be something wrong (e.g. the rt logging threw an exception, " "the system load is too high or the logging takes to long). " diff --git a/source/RobotAPI/drivers/HokuyoLaserUnit/HokuyoLaserUnit.cpp b/source/RobotAPI/drivers/HokuyoLaserUnit/HokuyoLaserUnit.cpp index 52af2c8dd81679509f7aaf965caa91e3b49349eb..2a1f02718bb8b1fa9465445086238a4e04ba92dd 100644 --- a/source/RobotAPI/drivers/HokuyoLaserUnit/HokuyoLaserUnit.cpp +++ b/source/RobotAPI/drivers/HokuyoLaserUnit/HokuyoLaserUnit.cpp @@ -22,17 +22,25 @@ #include "HokuyoLaserUnit.h" -#include <ArmarXCore/observers/variant/TimestampVariant.h> - #include <SimoxUtility/algorithm/string/string_tools.h> -#include <HokuyoLaserScannerDriver/urg_utils.h> +#include <ArmarXCore/core/time/DateTime.h> +#include <ArmarXCore/core/time/Duration.h> +#include <ArmarXCore/core/time/ice_conversions.h> +#include <ArmarXCore/observers/variant/TimestampVariant.h> +#include <HokuyoLaserScannerDriver/urg_utils.h> using namespace armarx; +HokuyoLaserUnit::HokuyoLaserUnit() +{ + addPlugin(heartbeat); +} + -void HokuyoLaserUnit::onInitComponent() +void +HokuyoLaserUnit::onInitComponent() { offeringTopicFromProperty("RobotHealthTopicName"); offeringTopicFromProperty("DebugObserverName"); @@ -72,19 +80,21 @@ void HokuyoLaserUnit::onInitComponent() } catch (std::exception const& ex) { - ARMARX_WARNING << "Could not convert port to integer for laser scanner device " << deviceString - << " (port is " << deviceInfo[1] << ") : " << ex.what(); + ARMARX_WARNING << "Could not convert port to integer for laser scanner device " + << deviceString << " (port is " << deviceInfo[1] << ") : " << ex.what(); continue; } } } - -void HokuyoLaserUnit::onConnectComponent() +void +HokuyoLaserUnit::onConnectComponent() { - robotHealthTopic = getTopic<RobotHealthInterfacePrx>(getProperty<std::string>("RobotHealthTopicName").getValue()); + ARMARX_TRACE; + topic = getTopic<LaserScannerUnitListenerPrx>(topicName); - debugObserver = getTopic<DebugObserverInterfacePrx>(getProperty<std::string>("DebugObserverName").getValue()); + debugObserver = getTopic<DebugObserverInterfacePrx>( + getProperty<std::string>("DebugObserverName").getValue()); connectedDevices.clear(); for (HokuyoLaserScanDevice& device : devices) @@ -95,12 +105,21 @@ void HokuyoLaserUnit::onConnectComponent() device.task = nullptr; } + // connecting devices for first time if (!device.reconnect()) { - ARMARX_WARNING << "Not starting task for laser scanner with IP: " << device.ip << ", Port: " << device.port; + ARMARX_WARNING << "Not starting task for laser scanner with IP: " << device.ip + << ", Port: " << device.port; continue; } + ARMARX_CHECK_NOT_NULL(heartbeat); + heartbeat->signUp(device.ip, + armarx::core::time::Duration::MilliSeconds(500), + armarx::core::time::Duration::MilliSeconds(800), + {"LaserScanner", "Localization"}, + "HokuyoLaserScanDevice"); + LaserScannerInfo info; info.device = device.ip; info.frame = device.frame; @@ -115,23 +134,22 @@ void HokuyoLaserUnit::onConnectComponent() device.lengthData.resize(lengthDataSize); device.scanTopic = topic; - device.robotHealthTopic = robotHealthTopic; + device.robotHealthPlugin = heartbeat; device.debugObserver = debugObserver; connectedDevices.push_back(info); - ARMARX_INFO << "Connected to " << device.ip << ", " << info.frame << ", " - << info.minAngle << ", " << info.maxAngle << ", " << info.stepSize; + ARMARX_INFO << "Connected to " << device.ip << ", " << info.frame << ", " << info.minAngle + << ", " << info.maxAngle << ", " << info.stepSize; - device.task = new RunningTask<HokuyoLaserScanDevice>(&device, &HokuyoLaserScanDevice::run, - "HokuyoLaserScanUpdate_" + device.ip); + device.task = new RunningTask<HokuyoLaserScanDevice>( + &device, &HokuyoLaserScanDevice::run, "HokuyoLaserScanUpdate_" + device.ip); device.task->start(); } - } - -void HokuyoLaserUnit::onDisconnectComponent() +void +HokuyoLaserUnit::onDisconnectComponent() { for (HokuyoLaserScanDevice& device : devices) { @@ -148,29 +166,32 @@ void HokuyoLaserUnit::onDisconnectComponent() } } - -void HokuyoLaserUnit::onExitComponent() +void +HokuyoLaserUnit::onExitComponent() { - } -armarx::PropertyDefinitionsPtr HokuyoLaserUnit::createPropertyDefinitions() +armarx::PropertyDefinitionsPtr +HokuyoLaserUnit::createPropertyDefinitions() { - return armarx::PropertyDefinitionsPtr(new HokuyoLaserUnitPropertyDefinitions( - getConfigIdentifier())); + return armarx::PropertyDefinitionsPtr( + new HokuyoLaserUnitPropertyDefinitions(getConfigIdentifier())); } -std::string HokuyoLaserUnit::getReportTopicName(const Ice::Current&) const +std::string +HokuyoLaserUnit::getReportTopicName(const Ice::Current&) const { return topicName; } -LaserScannerInfoSeq HokuyoLaserUnit::getConnectedDevices(const Ice::Current&) const +LaserScannerInfoSeq +HokuyoLaserUnit::getConnectedDevices(const Ice::Current&) const { return connectedDevices; } -bool HokuyoLaserScanDevice::reconnect() +bool +HokuyoLaserScanDevice::reconnect() { if (connected) { @@ -183,8 +204,8 @@ bool HokuyoLaserScanDevice::reconnect() connected = (ret == 0); if (!connected) { - ARMARX_WARNING << "Could not connect to laser scanner device using URG driver (IP: " - << ip << ", Port: " << port << ", Error: " << ret << ")"; + ARMARX_WARNING << "Could not connect to laser scanner device using URG driver (IP: " << ip + << ", Port: " << port << ", Error: " << ret << ")"; return false; } ret = urg_start_measurement(&urg, URG_DISTANCE, URG_SCAN_INFINITY, 0); @@ -196,21 +217,24 @@ bool HokuyoLaserScanDevice::reconnect() } else { - ARMARX_WARNING << "Could not start measurement for laser scanner device using URG driver (IP: " - << ip << ", Port: " << port << ", Error: " << ret << ")"; + ARMARX_WARNING + << "Could not start measurement for laser scanner device using URG driver (IP: " << ip + << ", Port: " << port << ", Error: " << ret << ")"; return false; } } -void HokuyoLaserScanDevice::run() +void +HokuyoLaserScanDevice::run() { + ARMARX_TRACE; while (!task->isStopped()) { IceUtil::Time time_start = TimeUtil::GetTime(); if (errorCounter > 10) { - ARMARX_ERROR << "Device " << ip << " has too many consecutive errors!"; + ARMARX_ERROR << "Device " << ip << " has too many consecutive errors!"; // assume dead reconnect(); } @@ -219,8 +243,9 @@ void HokuyoLaserScanDevice::run() int lengthDataSize = urg_get_distance(&urg, lengthData.data(), nullptr); if (lengthDataSize < 0) { - ARMARX_WARNING << deactivateSpam(1) << "Could not get measurement for laser scanner (IP: " - << ip << ", Port: " << port << ", Error: " << lengthDataSize << ")"; + ARMARX_WARNING << deactivateSpam(1) + << "Could not get measurement for laser scanner (IP: " << ip + << ", Port: " << port << ", Error: " << lengthDataSize << ")"; errorCounter++; continue; } @@ -236,7 +261,8 @@ void HokuyoLaserScanDevice::run() // TODO: Extract the min and max valid value for distance into parameters? if (distance >= 21 && distance <= 30000) { - step.angle = angleOffset + (float)urg_index2rad(&urg, stepIndex); // Convert steps to rad + step.angle = + angleOffset + (float)urg_index2rad(&urg, stepIndex); // Convert steps to rad step.distance = (float)distance; // Data is already in mm scan.push_back(step); } @@ -256,16 +282,14 @@ void HokuyoLaserScanDevice::run() } IceUtil::Time time_topicSensor = TimeUtil::GetTime(); - RobotHealthHeartbeatArgs args; - args.maximumCycleTimeWarningMS = 500; - args.maximumCycleTimeErrorMS = 800; - if (robotHealthTopic) + if (robotHealthPlugin != nullptr) { - robotHealthTopic->heartbeat(componentName + "_" + ip, args); + robotHealthPlugin->heartbeatOnChannel(ip); } else { - ARMARX_WARNING << "No robot health topic available: IP: " << ip << ", Port: " << port; + ARMARX_WARNING << "No robot health topic available: IP: " << ip + << ", Port: " << port; } IceUtil::Time time_topicHeartbeat = TimeUtil::GetTime(); @@ -274,20 +298,30 @@ void HokuyoLaserScanDevice::run() StringVariantBaseMap durations; durations["total_ms"] = new Variant(duration.toMilliSecondsDouble()); - durations["measure_ms"] = new Variant((time_measure - time_start).toMilliSecondsDouble()); - durations["update_ms"] = new Variant((time_update - time_measure).toMilliSecondsDouble()); - durations["topic_sensor_ms"] = new Variant((time_topicSensor - time_update).toMilliSecondsDouble()); - durations["topic_health_ms"] = new Variant((time_topicHeartbeat - time_topicSensor).toMilliSecondsDouble()); - debugObserver->setDebugChannel("LaserScannerDuration_" + simox::alg::replace_all(ip, ".", "_"), durations); + durations["measure_ms"] = + new Variant((time_measure - time_start).toMilliSecondsDouble()); + durations["update_ms"] = + new Variant((time_update - time_measure).toMilliSecondsDouble()); + durations["topic_sensor_ms"] = + new Variant((time_topicSensor - time_update).toMilliSecondsDouble()); + durations["topic_health_ms"] = + new Variant((time_topicHeartbeat - time_topicSensor).toMilliSecondsDouble()); + debugObserver->setDebugChannel( + "LaserScannerDuration_" + simox::alg::replace_all(ip, ".", "_"), durations); if (duration.toSecondsDouble() > 0.1) { ARMARX_WARNING << "Laserscanner reports are slow" << "Total time: " << duration.toMilliSecondsDouble() << "ms\n" - << "Measure: " << (time_measure - time_start).toMilliSecondsDouble() << "ms \n" - << "Update: " << (time_update - time_measure).toMilliSecondsDouble() << "ms\n" - << "TopicSensor: " << (time_topicSensor - time_update).toMilliSecondsDouble() << "ms\n" - << "TopicHeart: " << (time_topicHeartbeat - time_topicSensor).toMilliSecondsDouble() << "ms\n"; + << "Measure: " + << (time_measure - time_start).toMilliSecondsDouble() << "ms \n" + << "Update: " + << (time_update - time_measure).toMilliSecondsDouble() << "ms\n" + << "TopicSensor: " + << (time_topicSensor - time_update).toMilliSecondsDouble() << "ms\n" + << "TopicHeart: " + << (time_topicHeartbeat - time_topicSensor).toMilliSecondsDouble() + << "ms\n"; } } } diff --git a/source/RobotAPI/drivers/HokuyoLaserUnit/HokuyoLaserUnit.h b/source/RobotAPI/drivers/HokuyoLaserUnit/HokuyoLaserUnit.h index e9afa8e5b927857a03b171dc615722275d30986f..0b8ad3985e9e3b1825054fe1339cb41a5c59f4cd 100644 --- a/source/RobotAPI/drivers/HokuyoLaserUnit/HokuyoLaserUnit.h +++ b/source/RobotAPI/drivers/HokuyoLaserUnit/HokuyoLaserUnit.h @@ -22,14 +22,17 @@ #pragma once +#include <vector> + #include <ArmarXCore/core/Component.h> #include <ArmarXCore/core/services/tasks/RunningTask.h> + #include <RobotAPI/components/units/SensorActorUnit.h> -#include <RobotAPI/interface/units/LaserScannerUnit.h> #include <RobotAPI/interface/components/RobotHealthInterface.h> +#include <RobotAPI/interface/units/LaserScannerUnit.h> +#include <RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.h> #include <HokuyoLaserScannerDriver/urg_sensor.h> -#include <vector> namespace armarx { @@ -37,19 +40,30 @@ namespace armarx * @class HokuyoLaserUnitPropertyDefinitions * @brief */ - class HokuyoLaserUnitPropertyDefinitions: - public armarx::ComponentPropertyDefinitions + class HokuyoLaserUnitPropertyDefinitions : public armarx::ComponentPropertyDefinitions { public: - HokuyoLaserUnitPropertyDefinitions(std::string prefix): + HokuyoLaserUnitPropertyDefinitions(std::string prefix) : armarx::ComponentPropertyDefinitions(prefix) { - defineOptionalProperty<std::string>("LaserScannerTopicName", "LaserScans", "Name of the laser scan topic."); + defineOptionalProperty<std::string>( + "LaserScannerTopicName", "LaserScans", "Name of the laser scan topic."); defineOptionalProperty<int>("UpdatePeriod", 25, "Update period for laser scans"); - defineOptionalProperty<float>("AngleOffset", -2.3561944902, "Offset is applied the raw angles before reporting them"); - defineOptionalProperty<std::string>("Devices", "", "List of devices in form of 'IP1,port1,frame1;IP2,port2,frame2;...'"); - defineOptionalProperty<std::string>("RobotHealthTopicName", "RobotHealthTopic", "Name of the RobotHealth topic"); - defineOptionalProperty<std::string>("DebugObserverName", "DebugObserver", "Name of the topic the DebugObserver listens on"); + defineOptionalProperty<float>("AngleOffset", + -2.3561944902, + "Offset is applied the raw angles before reporting them"); + defineOptionalProperty<std::string>( + "Devices", + "", + "List of devices in form of 'IP1,port1,frame1;IP2,port2,frame2;...'"); + + defineOptionalProperty<std::string>( + "RobotHealthComponentName", "RobotHealth", "Name of the RobotHealth component"); + defineOptionalProperty<std::string>( + "RobotHealthTopicName", "RobotHealthTopic", "Name of the RobotHealth topic"); + defineOptionalProperty<std::string>("DebugObserverName", + "DebugObserver", + "Name of the topic the DebugObserver listens on"); } }; @@ -66,6 +80,7 @@ namespace armarx bool reconnect(); + void run(); RunningTask<HokuyoLaserScanDevice>::pointer_type task; @@ -73,7 +88,7 @@ namespace armarx std::string componentName; LaserScannerUnitListenerPrx scanTopic; - RobotHealthInterfacePrx robotHealthTopic; + armarx::plugins::HeartbeatComponentPlugin* robotHealthPlugin; DebugObserverInterfacePrx debugObserver; }; @@ -93,10 +108,13 @@ namespace armarx virtual public armarx::SensorActorUnit { public: + HokuyoLaserUnit(); + /** * @see armarx::ManagedIceObject::getDefaultName() */ - std::string getDefaultName() const override + std::string + getDefaultName() const override { return "HokuyoLaserUnit"; } @@ -138,8 +156,8 @@ namespace armarx float angleOffset = 0.0f; std::vector<HokuyoLaserScanDevice> devices; LaserScannerInfoSeq connectedDevices; - RobotHealthInterfacePrx robotHealthTopic; DebugObserverInterfacePrx debugObserver; - }; -} + plugins::HeartbeatComponentPlugin* heartbeat = nullptr; + }; +} // namespace armarx diff --git a/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidget.ui b/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidget.ui index 3c7001134bb60d82eb5017ee2b3d6f86a7bc57ee..2140458dc4fb92ddc0f065178ed4487733d053fa 100644 --- a/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidget.ui +++ b/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidget.ui @@ -1,55 +1,42 @@ <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> - <class>GuiHealthClientWidget</class> - <widget class="QWidget" name="GuiHealthClientWidget"> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>500</width> - <height>71</height> - </rect> - </property> - <property name="windowTitle"> - <string>GuiHealthClientWidget</string> - </property> - <layout class="QGridLayout" name="gridLayout"> - <item row="0" column="1"> - <widget class="QPushButton" name="pushButtonToggleOwnHeartbeats"> - <property name="text"> - <string>Toggle</string> - </property> - </widget> - </item> - <item row="0" column="0"> - <widget class="QLabel" name="labelState"> - <property name="text"> - <string>TextLabel</string> - </property> - </widget> - </item> - <item row="0" column="2"> - <spacer name="horizontalSpacer"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>40</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="1" column="0" colspan="3"> - <widget class="QLabel" name="labelHealthState"> - <property name="text"> - <string>TextLabel</string> - </property> - </widget> - </item> - </layout> - </widget> - <resources/> - <connections/> + <class>GuiHealthClientWidget</class> + <widget class="QWidget" name="GuiHealthClientWidget"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>500</width> + <height>71</height> + </rect> + </property> + <property name="windowTitle"> + <string>GuiHealthClientWidget</string> + </property> + <layout class="QGridLayout" name="gridLayout"> + + <item row="0" column="0" colspan="2"> + <widget class="QLabel" name="labelTags"> + <property name="text"> + <string>...</string> + </property> + </widget> + </item> + + <item row="0" column="2"> + <widget class="QPushButton" name="pushButtonUnrequireAll"> + <property name="text"> + <string>Reset required tags</string> + </property> + </widget> + </item> + + <item row="1" column="0" colspan="3"> + <widget class="QTableWidget" name="tableHealthState"> + </widget> + </item> + </layout> + </widget> + <resources /> + <connections /> </ui> diff --git a/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidgetController.cpp b/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidgetController.cpp index ca95dd07836e035a04019bd2fd1d176c4ca01256..d976d77e6742b63152b172b7a55107929405302d 100644 --- a/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidgetController.cpp +++ b/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidgetController.cpp @@ -22,67 +22,96 @@ #include "GuiHealthClientWidgetController.h" -#include <QLabel> +#include <SimoxUtility/algorithm/get_map_keys_values.h> +#include <qcolor.h> +#include <qnamespace.h> +#include <qrgb.h> +#include <qtablewidget.h> #include <string> + +#include <QLabel> #include <QPushButton> +#include <ArmarXCore/core/time/DateTime.h> +#include <ArmarXCore/core/time/Duration.h> +#include <ArmarXCore/core/time/ice_conversions.h> + namespace armarx { + std::string serializeList(const std::vector<std::string>& l) + { + std::string s; + for(std::size_t i = 0; i < l.size(); i++) + { + const auto& tag = l.at(i); + s += tag; + + if(i != l.size() - 1) + { + s += ", "; + } + } + + return s; + } + GuiHealthClientWidgetController::GuiHealthClientWidgetController() { widget.setupUi(getWidget()); - //ARMARX_IMPORTANT << "ctor start"; - healthTimer = new QTimer(this); - healthTimer->setInterval(10); - connect(healthTimer, SIGNAL(timeout()), this, SLOT(healthTimerClb())); - connect(widget.pushButtonToggleOwnHeartbeats, SIGNAL(clicked()), this, SLOT(toggleSendOwnHeartbeats())); - connect(this, SIGNAL(invokeConnectComponentQt()), this, SLOT(onConnectComponentQt()), Qt::QueuedConnection); - connect(this, SIGNAL(invokeDisconnectComponentQt()), this, SLOT(onDisconnectComponentQt()), Qt::QueuedConnection); + connect(this, + SIGNAL(invokeConnectComponentQt()), + this, + SLOT(onConnectComponentQt()), + Qt::QueuedConnection); + connect(this, + SIGNAL(invokeDisconnectComponentQt()), + this, + SLOT(onDisconnectComponentQt()), + Qt::QueuedConnection); + + connect(widget.pushButtonUnrequireAll, + SIGNAL(clicked()), + this, + SLOT(unrequireAll())); updateSummaryTimer = new QTimer(this); updateSummaryTimer->setInterval(100); connect(updateSummaryTimer, SIGNAL(timeout()), this, SLOT(updateSummaryTimerClb())); - - widget.labelState->setText("idle."); - widget.pushButtonToggleOwnHeartbeats->setText("send own heartbeats"); - - //ARMARX_IMPORTANT << "ctor end"; } - GuiHealthClientWidgetController::~GuiHealthClientWidgetController() { - } - - void GuiHealthClientWidgetController::loadSettings(QSettings* settings) + void + GuiHealthClientWidgetController::loadSettings(QSettings* settings) { - } - void GuiHealthClientWidgetController::saveSettings(QSettings* settings) + void + GuiHealthClientWidgetController::saveSettings(QSettings* settings) { - } - - void GuiHealthClientWidgetController::onInitComponent() + void + GuiHealthClientWidgetController::onInitComponent() { //ARMARX_IMPORTANT << "onInitComponent"; usingProxy("RobotHealth"); offeringTopic("RobotHealthTopic"); } - void GuiHealthClientWidgetController::healthTimerClb() + void + GuiHealthClientWidgetController::healthTimerClb() { - RobotHealthHeartbeatArgs rhha; - rhha.maximumCycleTimeWarningMS = 250; - rhha.maximumCycleTimeErrorMS = 500; - robotHealthTopicPrx->heartbeat(getName(), RobotHealthHeartbeatArgs()); + armarx::core::time::dto::DateTime now; + armarx::core::time::toIce(now, armarx::core::time::DateTime::Now()); + robotHealthTopicPrx->heartbeat(getName(), now); } - void GuiHealthClientWidgetController::updateSummaryTimerClb() + + void + GuiHealthClientWidgetController::updateSummaryTimerClb() { //ARMARX_IMPORTANT << "updateSummaryTimerClb"; if (robotHealthComponentPrx) @@ -90,59 +119,152 @@ namespace armarx //ARMARX_IMPORTANT << "has robotHealthComponentPrx"; try { - //ARMARX_IMPORTANT << "before set text"; - widget.labelHealthState->setText(QString::fromUtf8(robotHealthComponentPrx->getSummary().c_str())); - //ARMARX_IMPORTANT << "after set text"; + auto summary = robotHealthComponentPrx->getSummary(); + + const std::size_t nCols = 10; + + auto& tableWidget = widget.tableHealthState; + tableWidget->setRowCount(summary.entries.size()); + tableWidget->setColumnCount(nCols); + + const auto summaryVals = simox::alg::get_values(summary.entries); + + tableWidget->setHorizontalHeaderLabels({ + "identifier", "required", "keeps frequency", "tags", "time since\nlast arrival [ms]", "time to\nreference [ms]", "time sync \n+ Ice [ms]", "warning\nthreshold [ms]", "error\nthreshold [ms]", "hostname" + }); + + tableWidget->setColumnWidth(0, 250); + tableWidget->setColumnWidth(1, 80); + tableWidget->setColumnWidth(2, 120); + tableWidget->setColumnWidth(3, 180); + tableWidget->setColumnWidth(4, 120); + tableWidget->setColumnWidth(5, 120); + tableWidget->setColumnWidth(6, 120); + tableWidget->setColumnWidth(7, 120); + + for(std::size_t i = 0; i < summary.entries.size(); i++) + { + const auto& entry = summaryVals.at(i); + + std::string stateRepr; + QColor color; + switch(entry.state) + { + case HealthOK: + stateRepr = "yes"; + color.setRgb(0, 255, 0); // green + break; + case HealthWarning: + stateRepr = "yes"; + color.setRgb(255, 165, 0); // orange + break; + case HealthError: + stateRepr = "no"; + color.setRgb(255, 0, 0); // red + break; + } + + const std::string hostname = entry.lastReferenceTimestamp.hostname; + + const std::string timeSinceLastArrivalRepr = std::to_string(entry.timeSinceLastArrival.microSeconds / 1000); + const std::string timeToLastReferenceRepr = std::to_string(entry.timeSinceLastUpdateReference.microSeconds / 1000); + const std::string tagsRepr = serializeList(entry.tags); + + const long syncErrorMilliSeconds = std::abs(entry.timeSinceLastArrival.microSeconds - entry.timeSinceLastUpdateReference.microSeconds) / 1000; + + + tableWidget->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(entry.identifier))); + + auto* requiredItem = new QTableWidgetItem(QString::fromStdString(entry.required ? "yes" : "no")); + requiredItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + tableWidget->setItem(i, 1, requiredItem); + + auto* stateItem = new QTableWidgetItem(QString::fromStdString(stateRepr)); + stateItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + tableWidget->setItem(i, 2, stateItem); + tableWidget->item(i, 2)->setBackgroundColor(color); + + tableWidget->setItem(i, 3, new QTableWidgetItem(QString::fromStdString(tagsRepr))); + + tableWidget->setItem(i, 4, new QTableWidgetItem(QString::fromStdString(timeSinceLastArrivalRepr))); + tableWidget->setItem(i, 5, new QTableWidgetItem(QString::fromStdString(timeToLastReferenceRepr))); + + tableWidget->setItem(i, 6, new QTableWidgetItem(QString::fromStdString(std::to_string(syncErrorMilliSeconds)))); + + if(syncErrorMilliSeconds > 20) + { + QColor timeSyncColor; + timeSyncColor.setRgb(255, 0, 0); + tableWidget->item(i, 6)->setBackgroundColor(timeSyncColor); + }else { + QColor timeSyncColor; + timeSyncColor.setRgb(0, 255, 0); + tableWidget->item(i, 6)->setBackgroundColor(timeSyncColor); + } + + + tableWidget->setItem(i, 7, new QTableWidgetItem(QString::fromStdString(std::to_string(entry.maximumCycleTimeWarning.microSeconds / 1000)))); + tableWidget->setItem(i, 8, new QTableWidgetItem(QString::fromStdString(std::to_string(entry.maximumCycleTimeError.microSeconds / 1000)))); + tableWidget->setItem(i, 9, new QTableWidgetItem(QString::fromStdString(hostname))); + } + + std::string tagsText = "Active tags: ["; + { + std::sort(summary.activeTags.begin(), summary.activeTags.end()); + + tagsText += serializeList(summary.activeTags); + + tagsText += "]"; + } + + widget.labelTags->setText(QString::fromStdString(tagsText)); } catch (...) - {} + { + } } } - void GuiHealthClientWidgetController::toggleSendOwnHeartbeats() + void + GuiHealthClientWidgetController::unrequireAll() { - if (ownHeartbeatsActive) - { - ownHeartbeatsActive = false; - healthTimer->stop(); - robotHealthTopicPrx->unregister(getName()); - widget.labelState->setText("idle."); - //widget.pushButtonToggleOwnHeartbeats->setDisabled(true); - widget.pushButtonToggleOwnHeartbeats->setText("send own heartbeats"); - } - else + ARMARX_INFO << "UnrequireAll."; + if (robotHealthComponentPrx) { - ownHeartbeatsActive = true; - healthTimer->start(); - widget.labelState->setText("sending heartbeats..."); - widget.pushButtonToggleOwnHeartbeats->setText("unregister self"); + try + { + robotHealthComponentPrx->resetRequiredTags(); + } + catch(...){} } - } - - void GuiHealthClientWidgetController::onConnectComponent() + void + GuiHealthClientWidgetController::onConnectComponent() { //ARMARX_IMPORTANT << "onConnectComponent"; robotHealthTopicPrx = getTopic<RobotHealthInterfacePrx>("RobotHealthTopic"); robotHealthComponentPrx = getProxy<RobotHealthComponentInterfacePrx>("RobotHealth"); invokeConnectComponentQt(); } - void GuiHealthClientWidgetController::onConnectComponentQt() + + void + GuiHealthClientWidgetController::onConnectComponentQt() { //healthTimer->start(); - //ARMARX_IMPORTANT << "updateSummaryTimer->start"; + //ARMARX_IMPORTANT <<ame "updateSummaryTimer->start"; updateSummaryTimer->start(); } - - void GuiHealthClientWidgetController::onDisconnectComponent() + void + GuiHealthClientWidgetController::onDisconnectComponent() { invokeDisconnectComponentQt(); } - void GuiHealthClientWidgetController::onDisconnectComponentQt() + + void + GuiHealthClientWidgetController::onDisconnectComponentQt() { - healthTimer->stop(); updateSummaryTimer->stop(); } -} +} // namespace armarx diff --git a/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidgetController.h b/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidgetController.h index 0fed7c1ae22ad51714624a49388e8fec87a2967d..f5bc6ff28a593ba1d5e58bf1a02aabf42cd29bae 100644 --- a/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidgetController.h +++ b/source/RobotAPI/gui-plugins/GuiHealthClient/GuiHealthClientWidgetController.h @@ -110,7 +110,7 @@ namespace armarx void onDisconnectComponentQt(); void healthTimerClb(); void updateSummaryTimerClb(); - void toggleSendOwnHeartbeats(); + void unrequireAll(); signals: /* QT signal declarations */ @@ -122,13 +122,9 @@ namespace armarx * Widget Form */ Ui::GuiHealthClientWidget widget; - bool ownHeartbeatsActive = false; RobotHealthInterfacePrx robotHealthTopicPrx; RobotHealthComponentInterfacePrx robotHealthComponentPrx; - QTimer* healthTimer; QTimer* updateSummaryTimer; }; } - - diff --git a/source/RobotAPI/interface/aron/Aron.ice b/source/RobotAPI/interface/aron/Aron.ice index fb412c46c2409c60ac236ba7579c64fe795dff28..0bfb4fa816c80a1a5cc5768750b2017392aebac8 100644 --- a/source/RobotAPI/interface/aron/Aron.ice +++ b/source/RobotAPI/interface/aron/Aron.ice @@ -4,23 +4,27 @@ * Changelog: * - Update 1.1.0: Allow templates in aron and anyobjects * - Update 1.1.1: Switch to armarx type. Also remove position, orientation and pose types as they are nothing else that matrices or quaternions + * - Update 2.0.0: Add support for aron defaults. Also add marshalling checks in aron variants. **/ #include <ArmarXCore/interface/core/BasicTypes.ice> -#define ARON_MAJOR "1" -#define ARON_MINOR "1" -#define ARON_PATCH "2" -#define ARON_VERSION "1.1.2" +// Those macros stay defined +#define ARON_MAJOR "2" // ice interface changes +#define ARON_MINOR "0" // aron header changes +#define ARON_PATCH "0" // aron cpp changes +#define ARON_VERSION "2.0.0" module armarx { module aron { - + // also make version number available to other languages without a preprocessor + const string MAJOR = ARON_MAJOR; + const string MINOR = ARON_MINOR; + const string PATCH = ARON_PATCH; const string VERSION = ARON_VERSION; - /************************* * Aron Types ************ ************************/ @@ -48,6 +52,13 @@ module armarx FLOAT32, FLOAT64 }; + + module default_value + { + const string ONES = "1"; + const string ZEROS = "0"; + const string DEFAULT = ""; + } }; module image @@ -57,6 +68,14 @@ module armarx RGB24, DEPTH32 }; + + module default_value + { + const string IDENTITY = "identity"; + const string ONES = "1"; + const string ZEROS = "0"; + const string DEFAULT = ""; + } }; module pointcloud @@ -71,6 +90,14 @@ module armarx POINT_XYZRGBA, POINT_XYZHSV }; + + module default_value + { + const string IDENTITY = "identity"; + const string ONES = "1"; + const string ZEROS = "0"; + const string DEFAULT = ""; + } }; module matrix @@ -83,6 +110,14 @@ module armarx FLOAT32, FLOAT64 }; + + module default_value + { + const string IDENTITY = "identity"; + const string ONES = "1"; + const string ZEROS = "0"; + const string DEFAULT = ""; + } }; module quaternion @@ -92,46 +127,154 @@ module armarx FLOAT32, FLOAT64 }; + + module default_value + { + const string ONES = "1"; + const string ZEROS = "0"; + const string DEFAULT = ""; + } }; + module aron_enum + { + module default_value + { + const string DEFAULT = ""; + } + } + module dto { - class GenericType { + class GenericType + { string VERSION = ARON_VERSION; Maybe maybe = Maybe::NONE; - } + }; + sequence<GenericType> GenericTypeSeq; + dictionary<string, GenericType> GenericTypeDict; /* ***** Container types ***** */ - class List extends GenericType { GenericType acceptedType; } - class Tuple extends GenericType { GenericTypeSeq elementTypes; } - class Pair extends GenericType { GenericType acceptedType1; GenericType acceptedType2; } - class AronObject extends GenericType { AronObject parent; Ice::StringSeq templates; string objectName; Ice::StringSeq templateInstantiations; GenericTypeDict elementTypes; } - class Dict extends GenericType { GenericType acceptedType; } + class List extends GenericType + { + GenericType acceptedType; + }; + + class Tuple extends GenericType + + { + GenericTypeSeq elementTypes; + }; + + class Pair extends GenericType + { + GenericType acceptedType1; + GenericType acceptedType2; + }; + + class AronObject extends GenericType + { + Ice::StringSeq templates; + string objectName; + AronObject parent; + Ice::StringSeq templateInstantiations; + GenericTypeDict elementTypes; + }; + + class Dict extends GenericType + { + GenericType acceptedType; + } /* ***** Complex Types (serialize to ndarray) ***** */ - class NDArray extends GenericType { int ndimensions; ndarray::ElementType elementType; } - class Matrix extends GenericType { int rows; int cols; matrix::ElementType elementType; } - class Quaternion extends GenericType { quaternion::ElementType elementType; } - class Image extends GenericType { image::PixelType pixelType; } - class PointCloud extends GenericType { pointcloud::VoxelType voxelType; } + class NDArray extends GenericType + + { + int ndimensions; + ndarray::ElementType elementType; + string defaultValue = type::ndarray::default_value::DEFAULT; + // ONES_DEFAULT_VALUE | ZEROS_DEFAULT_VALUE | <value> | "" + }; + + class Matrix extends GenericType + { + int rows; + int cols; + matrix::ElementType elementType; + string defaultValue = type::matrix::default_value::DEFAULT; + // IDENTITY_DEFAULT_VALUE (if quadratic) | ONES_DEFAULT_VALUE | ZEROS_DEFAULT_VALUE | <value> | "" + }; + + class Quaternion extends GenericType + { + quaternion::ElementType elementType; + string defaultValue = type::quaternion::default_value::DEFAULT; + // ONES_DEFAULT_VALUE | ZEROS_DEFAULT_VALUE | <value sequence> | "" + }; + + class Image extends GenericType + { + image::PixelType pixelType; + string defaultValue = type::image::default_value::DEFAULT; + // IDENTITY_DEFAULT_VALUE (if quadratic) | ONES_DEFAULT_VALUE | ZEROS_DEFAULT_VALUE | <value> | "" + }; + + class PointCloud extends GenericType + { + pointcloud::VoxelType voxelType; + string defaultValue = type::pointcloud::default_value::DEFAULT; + // IDENTITY_DEFAULT_VALUE (if quadratic) | ONES_DEFAULT_VALUE | ZEROS_DEFAULT_VALUE | <value> | "" + }; /* ***** Enum types ***** */ - class IntEnum extends GenericType { string enumName; StringIntDict acceptedValues; } + class IntEnum extends GenericType + { + string enumName; + StringIntDict acceptedValues; + string defaultValue = aron_enum::default_value::DEFAULT; + // in acceptedValues.keys | "" + }; + //class FloatEnum extends GenericType { string enumName; StringFloatDict acceptedValues; } //class StringEnum extends GenericType { string enumName; StringStringDict acceptedValues; } /* ***** Any Types ***** */ - class AnyObject extends GenericType { }; + class AnyObject extends GenericType + { + }; /* ***** Primitive Types ***** */ - class AronInt extends GenericType { }; - class AronLong extends GenericType { }; - class AronDouble extends GenericType { }; - class AronFloat extends GenericType { }; - class AronString extends GenericType { }; - class AronBool extends GenericType { }; + class AronInt extends GenericType + { + int defaultValue = 0; // <value> + }; + + class AronLong extends GenericType + { + long defaultValue = 0; // <value> + }; + + class AronDouble extends GenericType + { + double defaultValue = 0; // <value> + }; + + class AronFloat extends GenericType + { + float defaultValue = 0; // <value> + }; + + class AronString extends GenericType + { + string defaultValue = ""; // <value> + }; + + class AronBool extends GenericType + { + bool defaultValue = false; // <value> + }; }; }; @@ -143,30 +286,67 @@ module armarx { module dto { - class GenericData { + class GenericData + { string VERSION = ARON_VERSION; }; + sequence<GenericData> GenericDataSeq; dictionary<string, GenericData> GenericDataDict; /* ***** Container Data ***** */ - class List extends GenericData { GenericDataSeq elements; }; - class Dict extends GenericData { GenericDataDict elements; }; + class List extends GenericData + { + GenericDataSeq elements; + }; + + class Dict extends GenericData + { + GenericDataDict elements; + }; /* ***** Complex Data ***** */ // The NDArray contains more or less the same information as an AronType, but there is no other way to do it // Especially, note the difference between the type's typeName (e.g. "GRAY_SCALE_IMAGE" => language dependent) and the data's type ("0") // Further, note the difference between the type's dimensions (e.g. 128x128) and the data's dimensions (128x128x3 for RGB) - class NDArray extends GenericData { Ice::IntSeq shape; string type; Ice::ByteSeq data; } - + class NDArray extends GenericData + { + Ice::IntSeq shape; + string type; + Ice::ByteSeq data; + }; /* ***** Primitive Data ***** */ - class AronInt extends GenericData { int value; }; - class AronLong extends GenericData { long value; }; - class AronDouble extends GenericData { double value; }; - class AronFloat extends GenericData { float value; }; - class AronString extends GenericData { string value; }; - class AronBool extends GenericData { bool value; }; + // They must be prefixed with 'Aron' as e.g. Int cannot be used as class name + class AronInt extends GenericData + { + int value; + }; + + class AronLong extends GenericData + { + long value; + }; + + class AronDouble extends GenericData + { + double value; + }; + + class AronFloat extends GenericData + { + float value; + }; + + class AronString extends GenericData + { + string value; + }; + + class AronBool extends GenericData + { + bool value; + }; // useful for memory ice_conversions sequence<Dict> AronDictSeq; diff --git a/source/RobotAPI/interface/components/RobotHealthInterface.ice b/source/RobotAPI/interface/components/RobotHealthInterface.ice index bbad059d5a7468428a5a351b07b95e64bc27532b..0832146d934a45cf35dd2d42591a4b4949f8d15d 100644 --- a/source/RobotAPI/interface/components/RobotHealthInterface.ice +++ b/source/RobotAPI/interface/components/RobotHealthInterface.ice @@ -22,8 +22,12 @@ #pragma once +#include <ArmarXCore/interface/core/BasicTypes.ice> +#include <ArmarXCore/interface/core/time.ice> + module armarx { + enum RobotHealthState { HealthOK, HealthWarning, HealthError @@ -31,24 +35,74 @@ module armarx struct RobotHealthHeartbeatArgs { - int maximumCycleTimeWarningMS = 100; - int maximumCycleTimeErrorMS = 200; - string message; + string identifier; + // bool requiredByDefault; + string description; + Ice::StringSeq tags; + + armarx::core::time::dto::Duration maximumCycleTimeWarning; + armarx::core::time::dto::Duration maximumCycleTimeError; }; interface RobotHealthInterface { - void heartbeat(string componentName, RobotHealthHeartbeatArgs args); - void unregister(string componentName); + void signUp(RobotHealthHeartbeatArgs args); + void unregister(string identifier); + + void addRequiredTags(string requesterIdentifier, Ice::StringSeq tags); + void removeRequiredTags(string requesterIdentifier, Ice::StringSeq tags); + void resetRequiredTags(); + + void heartbeat(string identifier, armarx::core::time::dto::DateTime referenceTime); + + string getTopicName(); }; + // Used by the RobotHealth to send an overall status update ehich e.g. the emergency stop listens to. interface AggregatedRobotHealthInterface { void aggregatedHeartbeat(RobotHealthState overallHealthState); }; + struct RobotHealthInfoEntry + { + string identifier; + RobotHealthState state; + + // string message; + armarx::core::time::dto::Duration minDelta; + armarx::core::time::dto::Duration maxDelta; + + armarx::core::time::dto::DateTime lastReferenceTimestamp; + + //< Time delta to now() when arrived at heart beat component + armarx::core::time::dto::Duration timeSinceLastArrival; + + //< Time delta to reference timestamp sent by component + armarx::core::time::dto::Duration timeSinceLastUpdateReference; + + armarx::core::time::dto::Duration timeSyncDelayAndIce; + + bool required; // + bool enabled; + + armarx::core::time::dto::Duration maximumCycleTimeWarning; + armarx::core::time::dto::Duration maximumCycleTimeError; + + Ice::StringSeq tags; + }; + + dictionary<string, RobotHealthInfoEntry> RobotHealthEntries; + + struct RobotHealthInfo + { + Ice::StringSeq activeTags; + RobotHealthEntries entries; + }; + + interface RobotHealthComponentInterface extends RobotHealthInterface { - string getSummary(); + RobotHealthInfo getSummary(); }; }; diff --git a/source/RobotAPI/interface/units/LaserScannerUnit.ice b/source/RobotAPI/interface/units/LaserScannerUnit.ice index 631974396e0de5c50dcd67e73c47da2ad78fa99f..cf3a48562253065449dcdceb30030573f1a85e87 100644 --- a/source/RobotAPI/interface/units/LaserScannerUnit.ice +++ b/source/RobotAPI/interface/units/LaserScannerUnit.ice @@ -46,18 +46,18 @@ module armarx **/ struct LaserScanStep { - float angle; - float distance; -// float intensity; + float angle; + float distance; + float intensity; }; struct LaserScannerInfo { - string device; - string frame; - float minAngle; - float maxAngle; - float stepSize; + string device; + string frame; + float minAngle; + float maxAngle; + float stepSize; }; sequence<LaserScanStep> LaserScan; @@ -82,4 +82,3 @@ module armarx }; }; - diff --git a/source/RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.cpp b/source/RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.cpp index 41b48bdff28d2cdbd2e601ab7e9d6dadcdbc0e2b..9c1d995dee640e413d178d900df769068f1746df 100644 --- a/source/RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.cpp +++ b/source/RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.cpp @@ -2,56 +2,115 @@ #include <ArmarXCore/core/Component.h> #include <ArmarXCore/core/exceptions/local/ExpressionException.h> +#include <ArmarXCore/core/time/DateTime.h> +#include <ArmarXCore/core/time/ice_conversions.h> #include <RobotAPI/interface/components/RobotHealthInterface.h> namespace armarx::plugins { - void HeartbeatComponentPlugin::configureHeartbeatChannel(const std::string& channel, - const RobotHealthHeartbeatArgs& args) + + void + HeartbeatComponentPlugin::signUp(const std::string& identifier, + const std::vector<std::string>& tags, + const std::string& description) + { + RobotHealthHeartbeatArgs argsCopy = defaultHeartbeatArgs; + argsCopy.description = description; + argsCopy.identifier = identifier; + argsCopy.tags = tags; + signUp(argsCopy); + } + + void + HeartbeatComponentPlugin::signUp(const std::string& identifier, + const armarx::core::time::Duration& warning, + const armarx::core::time::Duration& error, + const std::vector<std::string>& tags, + const std::string& description) { - channelHeartbeatConfig.emplace(channel, args); + RobotHealthHeartbeatArgs argsCopy = defaultHeartbeatArgs; + argsCopy.description = description; + argsCopy.tags = tags; + argsCopy.identifier = identifier; + toIce(argsCopy.maximumCycleTimeWarning, warning); + toIce(argsCopy.maximumCycleTimeError, error); + + ARMARX_TRACE; + signUp(argsCopy); } - void HeartbeatComponentPlugin::configureHeartbeatChannel(const std::string& channel, const std::string& message) + void + HeartbeatComponentPlugin::signUp(const armarx::core::time::Duration& warning, + const armarx::core::time::Duration& error, + const std::vector<std::string>& tags, + const std::string& description) { - auto args = heartbeatArgs; - args.message = message; - configureHeartbeatChannel(channel, args); + RobotHealthHeartbeatArgs argsCopy = defaultHeartbeatArgs; + argsCopy.description = description; + argsCopy.tags = tags; + toIce(argsCopy.maximumCycleTimeWarning, warning); + toIce(argsCopy.maximumCycleTimeError, error); + // argsCopy.requiredByDefault = required; + signUp(argsCopy); } - void HeartbeatComponentPlugin::heartbeat() + void + HeartbeatComponentPlugin::signUp(const RobotHealthHeartbeatArgs& args) { + ARMARX_TRACE; + ARMARX_CHECK_NOT_NULL(robotHealthComponentPrx); - if (robotHealthTopic) + if (args.identifier.empty()) { - robotHealthTopic->heartbeat(componentName, heartbeatArgs); - } else + RobotHealthHeartbeatArgs argsCopy = args; + argsCopy.identifier = parent().getName(); + robotHealthComponentPrx->signUp(argsCopy); + } + else { - ARMARX_WARNING << "No robot health topic available!"; + // add component name prefix to identifier + RobotHealthHeartbeatArgs argsCopy = args; + argsCopy.identifier = parent().getName() + "_" + argsCopy.identifier; + robotHealthComponentPrx->signUp(argsCopy); } } - void HeartbeatComponentPlugin::heartbeat(const std::string& channel) + void + HeartbeatComponentPlugin::heartbeat() { - const auto argsIt = channelHeartbeatConfig.find(channel); - ARMARX_CHECK(argsIt != channelHeartbeatConfig.end()) << "heartbeat() called for unknown channel '" << channel - << "'." - << "You must register the config using configureHeartbeatChannel(channel) first!"; - - const auto& args = argsIt->second; + if (robotHealthComponentPrx) + { + armarx::core::time::dto::DateTime now; + armarx::core::time::toIce(now, armarx::core::time::DateTime::Now()); + robotHealthComponentPrx->heartbeat(parent().getName(), now); + } + else + { + ARMARX_WARNING << "No robot health proxy available!"; + } + } - if (robotHealthTopic) + void + HeartbeatComponentPlugin::heartbeatOnChannel(const std::string& channelName) + { + if (robotHealthComponentPrx) { - robotHealthTopic->heartbeat(componentName + "_" + channel, args); - } else + armarx::core::time::dto::DateTime now; + armarx::core::time::toIce(now, armarx::core::time::DateTime::Now()); + robotHealthComponentPrx->heartbeat(parent().getName() + "_" + channelName, now); + } + else { - ARMARX_WARNING << "No robot health topic available!"; + ARMARX_WARNING << "No robot health proxy available!"; } } - void HeartbeatComponentPlugin::preOnInitComponent() + void + HeartbeatComponentPlugin::preOnInitComponent() { + // defaultHeartbeatArgs.requiredByDefault = true; + // if (topicName.empty()) // { // parent<Component>().getProperty(topicName, makePropertyName(topicPropertyName)); @@ -59,33 +118,42 @@ namespace armarx::plugins // parent<Component>().offeringTopic(topicName); } - void HeartbeatComponentPlugin::postOnInitComponent() + void + HeartbeatComponentPlugin::postOnInitComponent() { + // set default args + auto warn = armarx::core::time::Duration::MilliSeconds(p.maximumCycleTimeWarningMS); + auto err = armarx::core::time::Duration::MilliSeconds(p.maximumCycleTimeErrorMS); + armarx::core::time::toIce(defaultHeartbeatArgs.maximumCycleTimeWarning, warn); + armarx::core::time::toIce(defaultHeartbeatArgs.maximumCycleTimeError, err); } - void HeartbeatComponentPlugin::preOnConnectComponent() + void + HeartbeatComponentPlugin::postOnConnectComponent() { - // robotHealthTopic = parent<Component>().getTopic<RobotHealthInterfacePrx>(topicName); - componentName = parent<Component>().getName(); + ARMARX_CHECK_NOT_NULL(robotHealthComponentPrx); } - void HeartbeatComponentPlugin::postCreatePropertyDefinitions(PropertyDefinitionsPtr& properties) + void + HeartbeatComponentPlugin::postCreatePropertyDefinitions(PropertyDefinitionsPtr& properties) { - if (!properties->hasDefinition(makePropertyName(topicPropertyName))) + if (!properties->hasDefinition(makePropertyName(healthPropertyName))) { - properties->topic(robotHealthTopic, topicName, topicPropertyName, - "Name of the topic the DebugObserver listens on"); + properties->component( + robotHealthComponentPrx, "RobotHealth", healthPropertyName, "Name of the robot health component."); } if (not properties->hasDefinition(makePropertyName(maximumCycleTimeWarningMSPropertyName))) { - properties->required(heartbeatArgs.maximumCycleTimeWarningMS, maximumCycleTimeWarningMSPropertyName, + properties->optional(p.maximumCycleTimeWarningMS, + maximumCycleTimeWarningMSPropertyName, "maximum cycle time before warning is emitted"); } if (not properties->hasDefinition(makePropertyName(maximumCycleTimeErrorMSPropertyName))) { - properties->required(heartbeatArgs.maximumCycleTimeErrorMS, maximumCycleTimeErrorMSPropertyName, + properties->optional(p.maximumCycleTimeErrorMS, + maximumCycleTimeErrorMSPropertyName, "maximum cycle time before error is emitted"); } } diff --git a/source/RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.h b/source/RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.h index bbefa079c1d54e71444d9f0e90120f4db0250297..8a7f4a42ca0e8a603945535445a0f35abf3110c6 100644 --- a/source/RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.h +++ b/source/RobotAPI/libraries/RobotAPIComponentPlugins/HeartbeatComponentPlugin.h @@ -22,6 +22,8 @@ #pragma once #include <ArmarXCore/core/ComponentPlugin.h> +#include <ArmarXCore/core/ManagedIceObject.h> +#include <ArmarXCore/core/time/Duration.h> #include <RobotAPI/interface/components/RobotHealthInterface.h> @@ -34,21 +36,33 @@ namespace armarx::plugins using ComponentPlugin::ComponentPlugin; /** - * @brief Configures a heartbeat subchannel. - * - * @param channel Identifier of the heartbeat channel - * @param args Configuration of this channel's heartbeat properties + * @brief register component to heartbeat */ - void configureHeartbeatChannel(const std::string& channel, const std::string& message); + void signUp(const std::string& channelName = "", + const std::vector<std::string>& aliases = {}, + const std::string& description = ""); /** - * @brief Configures a heartbeat subchannel. - * - * @param channel Identifier of the heartbeat channel - * @param args Configuration of this channel's heartbeat properties + * @brief register component to heartbeat + */ + void signUp(const armarx::core::time::Duration& warning, + const armarx::core::time::Duration& error, + const std::vector<std::string>& aliases = {}, + const std::string& description = ""); + + /** + * @brief register component to heartbeat + */ + void signUp(const std::string& channelName, + const armarx::core::time::Duration& warning, + const armarx::core::time::Duration& error, + const std::vector<std::string>& aliases = {}, + const std::string& description = ""); + + /** + * @brief register component to heartbeat, possibly with different component name */ - void configureHeartbeatChannel(const std::string& channel, - const RobotHealthHeartbeatArgs& args); + void signUp(const RobotHealthHeartbeatArgs& args); /** * @brief Sends out a heartbeat using the default config @@ -63,35 +77,33 @@ namespace armarx::plugins * * @param channel Identifier of the heartbeat channel */ - void heartbeat(const std::string& channel); + void heartbeatOnChannel(const std::string& channelName); protected: void preOnInitComponent() override; void postOnInitComponent() override; - void preOnConnectComponent() override; + // void preOnConnectComponent() override; + void postOnConnectComponent() override; void postCreatePropertyDefinitions(PropertyDefinitionsPtr& properties) override; private: - //! heartbeat topic name (outgoing) - std::string topicName{"RobotHealthTopic"}; - - //! name of this component used as identifier for heartbeats - std::string componentName; + RobotHealthComponentInterfacePrx robotHealthComponentPrx; // - static constexpr auto topicPropertyName = "heartbeat.TopicName"; + static constexpr auto healthPropertyName = "heartbeat.ComponentName"; static constexpr auto maximumCycleTimeWarningMSPropertyName = "heartbeat.maximumCycleTimeWarningMS"; static constexpr auto maximumCycleTimeErrorMSPropertyName = "heartbeat.maximumCycleTimeErrorMS"; - RobotHealthInterfacePrx robotHealthTopic; + struct Properties + { + long maximumCycleTimeWarningMS = 100; // [ms] + long maximumCycleTimeErrorMS = 200; // [ms] + } p; //! default config used in heartbeat(), set via properties - RobotHealthHeartbeatArgs heartbeatArgs; - - //! configs used in heartbeat(channel), set by user via configureHeartbeatChannel(...) - std::unordered_map<std::string, RobotHealthHeartbeatArgs> channelHeartbeatConfig; + RobotHealthHeartbeatArgs defaultHeartbeatArgs; }; } // namespace armarx::plugins diff --git a/source/RobotAPI/libraries/armem/server/test/ArMemMemoryTest.cpp b/source/RobotAPI/libraries/armem/server/test/ArMemMemoryTest.cpp index 70a0a2839f7f575d02d876a2721c3b3a6c73b58c..eb562e3278db9cb51aaa364e726e6fe5f71655fc 100644 --- a/source/RobotAPI/libraries/armem/server/test/ArMemMemoryTest.cpp +++ b/source/RobotAPI/libraries/armem/server/test/ArMemMemoryTest.cpp @@ -24,15 +24,15 @@ #define ARMARX_BOOST_TEST -#include <RobotAPI/Test.h> +#include <iostream> -#include <RobotAPI/libraries/armem/core/wm/memory_definitions.h> -#include <RobotAPI/libraries/armem/server/wm/memory_definitions.h> +#include <SimoxUtility/meta/type_name.h> + +#include <RobotAPI/Test.h> #include <RobotAPI/libraries/armem/core/error.h> #include <RobotAPI/libraries/armem/core/operations.h> - -#include <iostream> -#include <SimoxUtility/meta/type_name.h> +#include <RobotAPI/libraries/armem/core/wm/memory_definitions.h> +#include <RobotAPI/libraries/armem/server/wm/memory_definitions.h> #include <RobotAPI/libraries/aron/core/data/variant/container/Dict.h> #include <RobotAPI/libraries/aron/core/type/variant/container/Object.h> @@ -41,11 +41,10 @@ namespace armem = armarx::armem; namespace aron = armarx::aron; namespace wm = armarx::armem::wm; - BOOST_AUTO_TEST_CASE(test_time_to_string) { // 111111: seconds, 345: milliseconds, 789: microseconds - armem::Time time { armem::Duration::MicroSeconds(111111345789) }; + armem::Time time{armem::Duration::MicroSeconds(111111345789)}; BOOST_CHECK_EQUAL(armem::toStringMilliSeconds(time), "111111345.789 ms"); BOOST_CHECK_EQUAL(armem::toStringMilliSeconds(time, 0), "111111345 ms"); @@ -53,7 +52,10 @@ BOOST_AUTO_TEST_CASE(test_time_to_string) BOOST_CHECK_EQUAL(armem::toStringMilliSeconds(time, 2), "111111345.78 ms"); BOOST_CHECK_EQUAL(armem::toStringMilliSeconds(time, 3), "111111345.789 ms"); - BOOST_CHECK_EQUAL(armem::toStringMicroSeconds(time), "111111345789 " "\u03BC" "s"); + BOOST_CHECK_EQUAL(armem::toStringMicroSeconds(time), + "111111345789 " + "\u03BC" + "s"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time), "1970-01-02 07:51:51.345789"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time, 0), "1970-01-02 07:51:51"); @@ -63,7 +65,10 @@ BOOST_AUTO_TEST_CASE(test_time_to_string) // 111111: seconds, 000: milliseconds, 789: microseconds time = armem::Time(armem::Duration::MicroSeconds(111111000789)); BOOST_CHECK_EQUAL(armem::toStringMilliSeconds(time), "111111000.789 ms"); - BOOST_CHECK_EQUAL(armem::toStringMicroSeconds(time), "111111000789 " "\u03BC" "s"); + BOOST_CHECK_EQUAL(armem::toStringMicroSeconds(time), + "111111000789 " + "\u03BC" + "s"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time), "1970-01-02 07:51:51.000789"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time, 0), "1970-01-02 07:51:51"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time, 3), "1970-01-02 07:51:51.000"); @@ -72,14 +77,16 @@ BOOST_AUTO_TEST_CASE(test_time_to_string) // 111111: seconds, 345: milliseconds, 000: microseconds time = armem::Time(armem::Duration::MicroSeconds(111111345000)); BOOST_CHECK_EQUAL(armem::toStringMilliSeconds(time), "111111345.000 ms"); - BOOST_CHECK_EQUAL(armem::toStringMicroSeconds(time), "111111345000 " "\u03BC" "s"); + BOOST_CHECK_EQUAL(armem::toStringMicroSeconds(time), + "111111345000 " + "\u03BC" + "s"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time), "1970-01-02 07:51:51.345000"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time, 0), "1970-01-02 07:51:51"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time, 3), "1970-01-02 07:51:51.345"); BOOST_CHECK_EQUAL(armem::toDateTimeMilliSeconds(time, 6), "1970-01-02 07:51:51.345000"); } - // Public interface tests @@ -87,17 +94,18 @@ namespace ArMemMemoryTest { struct APITestFixture { - wm::EntityInstance instance { 0 }; - wm::EntitySnapshot snapshot { armem::Time(armem::Duration::MicroSeconds(1000)) }; - wm::Entity entity { "entity" }; - wm::ProviderSegment provSeg { "provider" }; - wm::CoreSegment coreSeg { "core" }; - wm::Memory memory { "memory" }; + wm::EntityInstance instance{0}; + wm::EntitySnapshot snapshot{armem::Time(armem::Duration::MicroSeconds(1000))}; + wm::Entity entity{"entity"}; + wm::ProviderSegment provSeg{"provider"}; + wm::CoreSegment coreSeg{"core"}; + wm::Memory memory{"memory"}; - - void test_add_instance(wm::EntityInstance& added, const wm::EntitySnapshot& parent) + void + test_add_instance(wm::EntityInstance& added, const wm::EntitySnapshot& parent) { - BOOST_TEST_CONTEXT("Added: " << armem::print(added) << "\n Parent: " << armem::print(parent)) + BOOST_TEST_CONTEXT("Added: " << armem::print(added) + << "\n Parent: " << armem::print(parent)) { const int index = 0; BOOST_CHECK_EQUAL(added.index(), index); @@ -106,9 +114,12 @@ namespace ArMemMemoryTest BOOST_CHECK_EQUAL(&parent.getInstance(index), &added); } } - void test_add_snapshot(wm::EntitySnapshot& added, const wm::Entity& parent) + + void + test_add_snapshot(wm::EntitySnapshot& added, const wm::Entity& parent) { - BOOST_TEST_CONTEXT("Added: " << armem::print(added) << "\n Parent: " << armem::print(parent)) + BOOST_TEST_CONTEXT("Added: " << armem::print(added) + << "\n Parent: " << armem::print(parent)) { const armem::Time time = armem::Time(armem::Duration::MicroSeconds(1000)); BOOST_CHECK_EQUAL(added.time(), time); @@ -117,9 +128,12 @@ namespace ArMemMemoryTest BOOST_CHECK_EQUAL(&parent.getSnapshot(time), &added); } } - void test_add_entity(wm::Entity& added, const wm::ProviderSegment& parent) + + void + test_add_entity(wm::Entity& added, const wm::ProviderSegment& parent) { - BOOST_TEST_CONTEXT("Added: " << armem::print(added) << "\n Parent: " << armem::print(parent)) + BOOST_TEST_CONTEXT("Added: " << armem::print(added) + << "\n Parent: " << armem::print(parent)) { const std::string name = "entity"; BOOST_CHECK_EQUAL(added.name(), name); @@ -128,9 +142,12 @@ namespace ArMemMemoryTest BOOST_CHECK_EQUAL(&parent.getEntity(name), &added); } } - void test_add_provider_segment(wm::ProviderSegment& added, const wm::CoreSegment& parent) + + void + test_add_provider_segment(wm::ProviderSegment& added, const wm::CoreSegment& parent) { - BOOST_TEST_CONTEXT("Added: " << armem::print(added) << "\n Parent: " << armem::print(parent)) + BOOST_TEST_CONTEXT("Added: " << armem::print(added) + << "\n Parent: " << armem::print(parent)) { const std::string name = "provider"; BOOST_CHECK_EQUAL(added.name(), name); @@ -139,9 +156,12 @@ namespace ArMemMemoryTest BOOST_CHECK_EQUAL(&parent.getProviderSegment(name), &added); } } - void test_add_core_segment(wm::CoreSegment& added, const wm::Memory& parent) + + void + test_add_core_segment(wm::CoreSegment& added, const wm::Memory& parent) { - BOOST_TEST_CONTEXT("Added: " << armem::print(added) << "\n Parent: " << armem::print(parent)) + BOOST_TEST_CONTEXT("Added: " << armem::print(added) + << "\n Parent: " << armem::print(parent)) { const std::string name = "core"; BOOST_CHECK_EQUAL(added.name(), name); @@ -151,21 +171,21 @@ namespace ArMemMemoryTest } } }; -} - +} // namespace ArMemMemoryTest BOOST_FIXTURE_TEST_SUITE(APITest, ArMemMemoryTest::APITestFixture) - BOOST_AUTO_TEST_CASE(test_add_instance_no_args) { test_add_instance(snapshot.addInstance(), snapshot); } + BOOST_AUTO_TEST_CASE(test_add_instance_copy) { test_add_instance(snapshot.addInstance(instance), snapshot); } + BOOST_AUTO_TEST_CASE(test_add_instance_move) { test_add_instance(snapshot.addInstance(std::move(instance)), snapshot); @@ -175,10 +195,12 @@ BOOST_AUTO_TEST_CASE(test_add_snapshot_time) { test_add_snapshot(entity.addSnapshot(armem::Time(armem::Duration::MicroSeconds(1000))), entity); } + BOOST_AUTO_TEST_CASE(test_add_snapshot_copy) { test_add_snapshot(entity.addSnapshot(snapshot), entity); } + BOOST_AUTO_TEST_CASE(test_add_snapshot_move) { test_add_snapshot(entity.addSnapshot(std::move(snapshot)), entity); @@ -188,10 +210,12 @@ BOOST_AUTO_TEST_CASE(test_add_entity_name) { test_add_entity(provSeg.addEntity("entity"), provSeg); } + BOOST_AUTO_TEST_CASE(test_add_entity_copy) { test_add_entity(provSeg.addEntity(entity), provSeg); } + BOOST_AUTO_TEST_CASE(test_add_entity_move) { test_add_entity(provSeg.addEntity(std::move(entity)), provSeg); @@ -201,10 +225,12 @@ BOOST_AUTO_TEST_CASE(test_add_provider_segment_name) { test_add_provider_segment(coreSeg.addProviderSegment("provider"), coreSeg); } + BOOST_AUTO_TEST_CASE(test_add_provider_segment_copy) { test_add_provider_segment(coreSeg.addProviderSegment(provSeg), coreSeg); } + BOOST_AUTO_TEST_CASE(test_add_provider_segment_move) { test_add_provider_segment(coreSeg.addProviderSegment(std::move(provSeg)), coreSeg); @@ -214,10 +240,12 @@ BOOST_AUTO_TEST_CASE(test_add_core_segment_name) { test_add_core_segment(memory.addCoreSegment("core"), memory); } + BOOST_AUTO_TEST_CASE(test_add_core_segment_copy) { test_add_core_segment(memory.addCoreSegment(coreSeg), memory); } + BOOST_AUTO_TEST_CASE(test_add_core_segment_move) { test_add_core_segment(memory.addCoreSegment(std::move(coreSeg)), memory); @@ -226,10 +254,6 @@ BOOST_AUTO_TEST_CASE(test_add_core_segment_move) BOOST_AUTO_TEST_SUITE_END() - - - - // COPY/MOVE CTOR/OP TESTS @@ -240,38 +264,42 @@ namespace ArMemMemoryTest using MemoryItem::MemoryItem; using MemoryItem::operator=; - std::string getKeyString() const + std::string + getKeyString() const { return ""; } - std::string getLevelName() const + + std::string + getLevelName() const { return ""; } }; + struct MemoryItemCtorOpTestFixture { - const armem::MemoryID id {"A/B/C/123/1"}; - const armem::MemoryID moved {"////1"}; // int is not moved - TestMemoryItem item { id }; + const armem::MemoryID id{"A/B/C/123/1"}; + const armem::MemoryID moved{"////1"}; // int is not moved + TestMemoryItem item{id}; MemoryItemCtorOpTestFixture() { BOOST_CHECK_EQUAL(item.id(), id); } }; -} +} // namespace ArMemMemoryTest BOOST_FIXTURE_TEST_SUITE(MemoryItemTest, ArMemMemoryTest::MemoryItemCtorOpTestFixture) - BOOST_AUTO_TEST_CASE(test_copy_ctor) { const ArMemMemoryTest::TestMemoryItem out(item); BOOST_CHECK_EQUAL(item.id(), id); BOOST_CHECK_EQUAL(out.id(), id); } + BOOST_AUTO_TEST_CASE(test_copy_op) { ArMemMemoryTest::TestMemoryItem out; @@ -279,6 +307,7 @@ BOOST_AUTO_TEST_CASE(test_copy_op) BOOST_CHECK_EQUAL(item.id(), id); BOOST_CHECK_EQUAL(out.id(), id); } + BOOST_AUTO_TEST_CASE(test_move_ctor) { ArMemMemoryTest::TestMemoryItem in = item; @@ -286,6 +315,7 @@ BOOST_AUTO_TEST_CASE(test_move_ctor) BOOST_CHECK_EQUAL(in.id(), moved); BOOST_CHECK_EQUAL(out.id(), id); } + BOOST_AUTO_TEST_CASE(test_move_op) { ArMemMemoryTest::TestMemoryItem in = item; @@ -298,34 +328,38 @@ BOOST_AUTO_TEST_CASE(test_move_op) BOOST_AUTO_TEST_SUITE_END() - - namespace ArMemMemoryTest { - struct TestMemoryContainer : public armem::base::detail::MemoryContainerBase<std::vector<int>, TestMemoryContainer> + struct TestMemoryContainer : + public armem::base::detail::MemoryContainerBase<std::vector<int>, TestMemoryContainer> { using MemoryContainerBase::MemoryContainerBase; using MemoryContainerBase::operator=; - std::string getKeyString() const + std::string + getKeyString() const { return ""; } - std::string getLevelName() const + + std::string + getLevelName() const { return ""; } - void fill() + void + fill() { - _container = std::vector<int> { -1, 2, -3 }; + _container = std::vector<int>{-1, 2, -3}; } }; + struct MemoryContainerCtorOpTestFixture { - const armem::MemoryID id {"M/C/P/E/123/1"}; - const armem::MemoryID moved {"////123/1"}; // Time and int are just copied, not moved - TestMemoryContainer cont {id}; + const armem::MemoryID id{"M/C/P/E/123/1"}; + const armem::MemoryID moved{"////123/1"}; // Time and int are just copied, not moved + TestMemoryContainer cont{id}; MemoryContainerCtorOpTestFixture() { @@ -335,7 +369,7 @@ namespace ArMemMemoryTest } }; -} +} // namespace ArMemMemoryTest BOOST_FIXTURE_TEST_SUITE(MemoryContainerTest, ArMemMemoryTest::MemoryContainerCtorOpTestFixture) @@ -347,6 +381,7 @@ BOOST_AUTO_TEST_CASE(test_copy_ctor) BOOST_CHECK_EQUAL(out.id(), id); BOOST_CHECK_EQUAL(out.size(), 3); } + BOOST_AUTO_TEST_CASE(test_copy_op) { ArMemMemoryTest::TestMemoryContainer out; @@ -356,6 +391,7 @@ BOOST_AUTO_TEST_CASE(test_copy_op) BOOST_CHECK_EQUAL(out.id(), id); BOOST_CHECK_EQUAL(out.size(), 3); } + BOOST_AUTO_TEST_CASE(test_move_ctor) { ArMemMemoryTest::TestMemoryContainer in = cont; @@ -365,6 +401,7 @@ BOOST_AUTO_TEST_CASE(test_move_ctor) BOOST_CHECK_EQUAL(out.id(), id); BOOST_CHECK_EQUAL(out.size(), 3); } + BOOST_AUTO_TEST_CASE(test_move_op) { ArMemMemoryTest::TestMemoryContainer in = cont; @@ -378,8 +415,6 @@ BOOST_AUTO_TEST_CASE(test_move_op) BOOST_AUTO_TEST_SUITE_END() - - BOOST_AUTO_TEST_CASE(test_key_ctors) { wm::EntityInstance instance(10); @@ -401,29 +436,32 @@ BOOST_AUTO_TEST_CASE(test_key_ctors) BOOST_CHECK_EQUAL(memory.name(), "memory"); } - - template <class T> struct CustomChecks { - static void checkEqual(const T& lhs, const T& rhs) + static void + checkEqual(const T& lhs, const T& rhs) { - (void) lhs, (void) rhs; + (void)lhs, (void)rhs; } - static void checkMoved(const T& moved) + + static void + checkMoved(const T& moved) { - (void) moved; + (void)moved; } }; - template <class T> -void checkEqual_d_ltm(const T& lhs, const T& rhs) +void +checkEqual_d_ltm(const T& lhs, const T& rhs) { BOOST_CHECK_EQUAL(lhs.path, rhs.path); } + template <class T> -void checkMoved_d_ltm(const T& moved) +void +checkMoved_d_ltm(const T& moved) { BOOST_CHECK_EQUAL(moved.path, nullptr); } @@ -431,16 +469,20 @@ void checkMoved_d_ltm(const T& moved) template <> struct CustomChecks<wm::EntityInstance> { - static void checkEqual(const wm::EntityInstance& lhs, const wm::EntityInstance& rhs) + static void + checkEqual(const wm::EntityInstance& lhs, const wm::EntityInstance& rhs) { BOOST_CHECK_EQUAL(lhs.metadata(), rhs.metadata()); BOOST_CHECK_EQUAL(lhs.data(), rhs.data()); } - static void checkMoved(const wm::EntityInstance& moved) + + static void + checkMoved(const wm::EntityInstance& moved) { BOOST_CHECK_EQUAL(moved.data(), nullptr); } }; + /*template <> struct CustomChecks<armem::d_ltm::EntityInstance> { @@ -517,24 +559,29 @@ struct CustomChecks<armem::d_ltm::Memory> struct CopyMoveCtorsOpsTestBase { - const armem::MemoryID id {"M", "C", "P", "E", armem::Time(armem::Duration::MicroSeconds(123000)), 1}; + const armem::MemoryID id{"M", + "C", + "P", + "E", + armem::Time(armem::Duration::MicroSeconds(123000)), + 1}; //const armem::MemoryID idMoved {"", "", "", "", armem::Time(armem::Duration::MicroSeconds(123000), 1}; armem::MemoryID idMoved = id; std::string typeName; - CopyMoveCtorsOpsTestBase(const std::string& typeName) : - typeName(typeName) + CopyMoveCtorsOpsTestBase(const std::string& typeName) : typeName(typeName) { armem::MemoryID copy = std::move(idMoved); - (void) copy; + (void)copy; } + virtual ~CopyMoveCtorsOpsTestBase() { } - - void test() + void + test() { BOOST_TEST_CONTEXT("Type " << typeName) { @@ -561,7 +608,8 @@ struct CopyMoveCtorsOpsTestBase } } - virtual void reset() + virtual void + reset() { } @@ -571,34 +619,36 @@ struct CopyMoveCtorsOpsTestBase virtual void testMoveOp() = 0; }; - - template <class T> struct InstanceCopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase { T in; - InstanceCopyMoveCtorsOpsTest() : - CopyMoveCtorsOpsTestBase(simox::meta::get_type_name<T>()) + InstanceCopyMoveCtorsOpsTest() : CopyMoveCtorsOpsTestBase(simox::meta::get_type_name<T>()) { } + virtual ~InstanceCopyMoveCtorsOpsTest() override = default; - void reset() override + void + reset() override { - in = T {id}; + in = T{id}; BOOST_CHECK_EQUAL(in.id(), id); } - void testCopyCtor() override + void + testCopyCtor() override { - T out { in }; + T out{in}; BOOST_CHECK_EQUAL(out.id(), id); CustomChecks<T>::checkEqual(out, in); } - void testCopyOp() override + + void + testCopyOp() override { T out; out = in; @@ -607,10 +657,12 @@ struct InstanceCopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase CustomChecks<T>::checkEqual(out, in); } - void testMoveCtor() override + + void + testMoveCtor() override { - T copy { in }; - T out { std::move(in) }; + T copy{in}; + T out{std::move(in)}; BOOST_CHECK_EQUAL(in.id(), idMoved); BOOST_CHECK_EQUAL(out.id(), id); @@ -618,9 +670,11 @@ struct InstanceCopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase CustomChecks<T>::checkEqual(out, copy); CustomChecks<T>::checkMoved(in); } - void testMoveOp() override + + void + testMoveOp() override { - T copy { in }; + T copy{in}; T out; out = std::move(in); @@ -632,7 +686,6 @@ struct InstanceCopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase } }; - template <class T> struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase { @@ -641,18 +694,21 @@ struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase CopyMoveCtorsOpsTest() : CopyMoveCtorsOpsTestBase(simox::meta::get_type_name<T>()) { } + virtual ~CopyMoveCtorsOpsTest() override = default; - void reset() override + void + reset() override { - in = T {id}; - if constexpr(std::is_same_v<T, wm::Memory>) + in = T{id}; + if constexpr (std::is_same_v<T, wm::Memory>) { in.addCoreSegment("C"); } { armem::EntityUpdate update; - update.entityID = armem::MemoryID("M", "C", "P", "E", armem::Time(armem::Duration::MicroSeconds(123000)), 0); + update.entityID = armem::MemoryID( + "M", "C", "P", "E", armem::Time(armem::Duration::MicroSeconds(123000)), 0); update.referencedTime = update.entityID.timestamp; update.instancesData.emplace_back(); in.update(update); @@ -661,23 +717,26 @@ struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase BOOST_CHECK_EQUAL(in.id(), id); BOOST_CHECK_EQUAL(in.size(), 1); - if constexpr(std::is_base_of_v <armarx::armem::base::detail::AronTyped, T>) + if constexpr (std::is_base_of_v<armarx::armem::base::detail::AronTyped, T>) { + auto o = std::make_shared<aron::type::Object>(); + o->setObjectName("some_object"); + in.aronType() = o; - in.aronType() = std::make_shared<aron::type::Object>("some_object"); BOOST_CHECK(in.aronType()); } } - void testCopyCtor() override + void + testCopyCtor() override { - T out { in }; + T out{in}; BOOST_CHECK_EQUAL(in.id(), id); BOOST_CHECK_EQUAL(in.size(), 1); BOOST_CHECK_EQUAL(out.id(), id); BOOST_CHECK_EQUAL(out.size(), 1); - if constexpr(std::is_base_of_v <armarx::armem::base::detail::AronTyped, T>) + if constexpr (std::is_base_of_v<armarx::armem::base::detail::AronTyped, T>) { BOOST_CHECK(in.aronType()); BOOST_CHECK(out.aronType()); @@ -686,7 +745,9 @@ struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase CustomChecks<T>::checkEqual(out, in); } - void testCopyOp() override + + void + testCopyOp() override { T out; out = in; @@ -695,7 +756,7 @@ struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase BOOST_CHECK_EQUAL(out.id(), id); BOOST_CHECK_EQUAL(out.size(), 1); - if constexpr(std::is_base_of_v <armarx::armem::base::detail::AronTyped, T>) + if constexpr (std::is_base_of_v<armarx::armem::base::detail::AronTyped, T>) { BOOST_CHECK(in.aronType()); BOOST_CHECK(out.aronType()); @@ -704,16 +765,18 @@ struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase CustomChecks<T>::checkEqual(out, in); } - void testMoveCtor() override + + void + testMoveCtor() override { - T out { std::move(in) }; + T out{std::move(in)}; BOOST_CHECK_EQUAL(in.id(), idMoved); BOOST_CHECK_EQUAL(in.size(), 0); BOOST_CHECK_EQUAL(out.id(), id); BOOST_CHECK_EQUAL(out.size(), 1); - if constexpr(std::is_base_of_v <armarx::armem::base::detail::AronTyped, T>) + if constexpr (std::is_base_of_v<armarx::armem::base::detail::AronTyped, T>) { BOOST_CHECK(out.aronType()); BOOST_CHECK_EQUAL(in.aronType(), nullptr); @@ -721,7 +784,9 @@ struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase CustomChecks<T>::checkMoved(in); } - void testMoveOp() override + + void + testMoveOp() override { T out; out = std::move(in); @@ -731,7 +796,7 @@ struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase BOOST_CHECK_EQUAL(out.id(), id); BOOST_CHECK_EQUAL(out.size(), 1); - if constexpr(std::is_base_of_v <armarx::armem::base::detail::AronTyped, T>) + if constexpr (std::is_base_of_v<armarx::armem::base::detail::AronTyped, T>) { BOOST_CHECK(out.aronType()); BOOST_CHECK_EQUAL(in.aronType(), nullptr); @@ -741,8 +806,6 @@ struct CopyMoveCtorsOpsTest : public CopyMoveCtorsOpsTestBase } }; - - BOOST_AUTO_TEST_CASE(test_copy_move_ctors_ops) { { @@ -771,8 +834,6 @@ BOOST_AUTO_TEST_CASE(test_copy_move_ctors_ops) }*/ } - - BOOST_AUTO_TEST_CASE(test_segment_setup) { armem::EntityUpdate update; @@ -809,11 +870,8 @@ BOOST_AUTO_TEST_CASE(test_segment_setup) // A successful update. update.entityID = armem::MemoryID::fromString("Memory/ImageRGB/SomeRGBImageProvider/image"); - update.instancesData = - { - std::make_shared<aron::data::Dict>(), - std::make_shared<aron::data::Dict>() - }; + update.instancesData = {std::make_shared<aron::data::Dict>(), + std::make_shared<aron::data::Dict>()}; update.referencedTime = armem::Time(armem::Duration::MilliSeconds(1000)); BOOST_CHECK_NO_THROW(providerSegment.update(update)); @@ -832,24 +890,22 @@ BOOST_AUTO_TEST_CASE(test_segment_setup) // Another update (on memory). - update.instancesData = { std::make_shared<aron::data::Dict>() }; + update.instancesData = {std::make_shared<aron::data::Dict>()}; update.referencedTime = armem::Time(armem::Duration::MilliSeconds(2000)); memory.update(update); BOOST_CHECK_EQUAL(entity.size(), 2); BOOST_CHECK(entity.hasSnapshot(update.referencedTime)); - BOOST_CHECK_EQUAL(entity.getSnapshot(update.referencedTime).size(), update.instancesData.size()); + BOOST_CHECK_EQUAL(entity.getSnapshot(update.referencedTime).size(), + update.instancesData.size()); // A third update (on entity). - update.instancesData = { std::make_shared<aron::data::Dict>() }; + update.instancesData = {std::make_shared<aron::data::Dict>()}; update.referencedTime = armem::Time(armem::Duration::MilliSeconds(3000)); entity.update(update); BOOST_CHECK_EQUAL(entity.size(), 3); - } - - BOOST_AUTO_TEST_CASE(test_history_size_in_entity) { armem::server::wm::Entity entity("entity"); @@ -892,7 +948,6 @@ BOOST_AUTO_TEST_CASE(test_history_size_in_entity) BOOST_CHECK(entity.hasSnapshot(armem::Time(armem::Duration::MilliSeconds(5000)))); } - BOOST_AUTO_TEST_CASE(test_history_size_in_provider_segment) { armem::server::wm::ProviderSegment providerSegment("SomeRGBImageProvider"); @@ -900,7 +955,7 @@ BOOST_AUTO_TEST_CASE(test_history_size_in_provider_segment) armem::EntityUpdate update; update.entityID.providerSegmentName = providerSegment.name(); - std::vector<std::string> entityNames = { "A", "B" }; + std::vector<std::string> entityNames = {"A", "B"}; // Fill entities and histories with unlimited size. for (const std::string& name : entityNames) diff --git a/source/RobotAPI/libraries/armem_gui/test/ArMemGuiTest.cpp b/source/RobotAPI/libraries/armem_gui/test/ArMemGuiTest.cpp index 627d1a2ea804d2aa38135d5fc670dcee44145b73..b8f3f0fe967212288b6385c99d812bf7e34e8124 100644 --- a/source/RobotAPI/libraries/armem_gui/test/ArMemGuiTest.cpp +++ b/source/RobotAPI/libraries/armem_gui/test/ArMemGuiTest.cpp @@ -36,14 +36,14 @@ namespace dn = armarx::aron::data; namespace tn = armarx::aron::type; - namespace ArMemGuiTest { struct Fixture { }; - void test_sanitize(const std::string& in, const std::string& expected) + void + test_sanitize(const std::string& in, const std::string& expected) { const std::string out = armarx::armem::gui::instance::sanitizeTypeName(in); BOOST_TEST_CONTEXT("in = '" << in << "'") @@ -51,13 +51,11 @@ namespace ArMemGuiTest BOOST_CHECK_EQUAL(out, expected); } } -} - +} // namespace ArMemGuiTest BOOST_FIXTURE_TEST_SUITE(ArMemGuiTest, ArMemGuiTest::Fixture) - BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_int) { test_sanitize(tn::Int().getFullName(), "Int"); @@ -72,7 +70,8 @@ BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_float) BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_dict) { - tn::Dict dict(std::make_shared<tn::Float>()); + tn::Dict dict; + dict.setAcceptedType(std::make_shared<tn::Float>()); test_sanitize(dict.getFullName(), "Dict<Float>"); test_sanitize(dn::Dict().getFullName(), "Dict"); @@ -80,7 +79,8 @@ BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_dict) BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_list) { - tn::List list(std::make_shared<tn::Long>()); + tn::List list; + list.setAcceptedType(std::make_shared<tn::Long>()); test_sanitize(list.getFullName(), "List<Long>"); test_sanitize(dn::List().getFullName(), "List"); @@ -88,20 +88,24 @@ BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_list) BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_object) { - tn::Object obj("namespace::MyObjectName"); + tn::Object obj; + obj.setObjectName("namespace::MyObjectName"); test_sanitize(obj.getFullName(), "MyObjectName (namespace)"); } BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_tuple) { std::vector<tn::VariantPtr> ac = {std::make_shared<tn::Int>(), std::make_shared<tn::Float>()}; - tn::Tuple type(ac); + tn::Tuple type; + type.setAcceptedTypes(ac); test_sanitize(type.getFullName(), "Tuple<Int, Float>"); } BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_pair) { - tn::Pair type(std::make_shared<tn::Int>(), std::make_shared<tn::Float>()); + tn::Pair type; + type.setFirstAcceptedType(std::make_shared<tn::Int>()); + type.setSecondAcceptedType(std::make_shared<tn::Float>()); test_sanitize(type.getFullName(), "Pair<Int, Float>"); } @@ -115,7 +119,7 @@ BOOST_AUTO_TEST_CASE(test_sanitizeTypeName_ndarry) } { dn::NDArray data; - data.setShape({ 3, 2, 1}); + data.setShape({3, 2, 1}); test_sanitize(data.getFullName(), "NDArray<3, 2, 1, >"); } } diff --git a/source/RobotAPI/libraries/armem_laser_scans/client/common/Writer.cpp b/source/RobotAPI/libraries/armem_laser_scans/client/common/Writer.cpp index 9a7aa7e5aa8a97032bd5ab9dcbe245b693a52cc3..8b43cef166b729c2bb7a0bb3d64df74268d1975d 100644 --- a/source/RobotAPI/libraries/armem_laser_scans/client/common/Writer.cpp +++ b/source/RobotAPI/libraries/armem_laser_scans/client/common/Writer.cpp @@ -80,7 +80,7 @@ namespace armarx::armem::laser_scans::client toAron(laserScan, timestamp, frame, agentName, aronSensorData); auto dict = aronSensorData.toAron(); - dict->addElement("scan", toAron(laserScan)); + dict->addElementCopy("scan", toAron(laserScan)); update.instancesData = {dict}; update.referencedTime = timestamp; diff --git a/source/RobotAPI/libraries/armem_laser_scans/server/Visu.cpp b/source/RobotAPI/libraries/armem_laser_scans/server/Visu.cpp index 551e4792c2eba3b5e19d2ebf468f2d090a53af41..ff8a7c9ca7437271d6e5fdabdf6e848bb771add1 100644 --- a/source/RobotAPI/libraries/armem_laser_scans/server/Visu.cpp +++ b/source/RobotAPI/libraries/armem_laser_scans/server/Visu.cpp @@ -1,7 +1,5 @@ #include "Visu.h" -#include <SimoxUtility/color/Color.h> -#include <SimoxUtility/color/ColorMap.h> #include <algorithm> #include <exception> #include <string> @@ -10,6 +8,9 @@ #include <SimoxUtility/algorithm/apply.hpp> #include <SimoxUtility/algorithm/get_map_keys_values.h> +#include <SimoxUtility/color/Color.h> +#include <SimoxUtility/color/ColorMap.h> +#include <SimoxUtility/color/hsv.h> #include <SimoxUtility/math/pose.h> #include <ArmarXCore/core/logging/Logging.h> @@ -32,33 +33,34 @@ namespace armarx::armem::server::laser_scans { + Visu::Visu() { Logging::setTag("Visu"); } - void Visu::defineProperties(armarx::PropertyDefinitionsPtr defs, const std::string& prefix) { defs->optional( p.enabled, prefix + "enabled", "Enable or disable visualization of objects."); defs->optional(p.frequencyHz, prefix + "frequenzyHz", "Frequency of visualization."); - defs->optional(p.uniformColor, prefix + "uniformColor", "If enabled, points will be drawn in red."); + defs->optional( + p.uniformColor, prefix + "uniformColor", "If enabled, points will be drawn in red."); defs->optional(p.maxRobotAgeMs, prefix + "maxRobotAgeMs", "Maximum age of robot state before a new one is retrieved in milliseconds."); + defs->optional(p.colorByIntensity, "colorByIntensity", ""); } - void - Visu::init(const wm::CoreSegment* coreSegment, armem::robot_state::VirtualRobotReader* virtualRobotReader) + Visu::init(const wm::CoreSegment* coreSegment, + armem::robot_state::VirtualRobotReader* virtualRobotReader) { this->coreSegment = coreSegment; this->virtualRobotReader = virtualRobotReader; } - void Visu::connect(const viz::Client& arviz, DebugObserverInterfacePrx debugObserver) { @@ -79,7 +81,6 @@ namespace armarx::armem::server::laser_scans updateTask->start(); } - void Visu::visualizeRun() { @@ -114,9 +115,10 @@ namespace armarx::armem::server::laser_scans } void - Visu::visualizeScan(const std::vector<Eigen::Vector3f>& points, + Visu::visualizeScan(const std::vector<ScanPoint>& points, const std::string& sensorName, - const std::string& agentName, const viz::Color& color) + const std::string& agentName, + const viz::Color& color) { viz::PointCloud pointCloud("laser_scan"); @@ -124,7 +126,30 @@ namespace armarx::armem::server::laser_scans for (const auto& point : points) { - pointCloud.addPoint(point.x(), point.y(), point.z(), color); + + // ARMARX_INFO << point.intensity; + const viz::Color specificColor = [&point, &color, this]() -> viz::Color + { + if (p.colorByIntensity) + { + Eigen::Vector3f hsv = simox::color::rgb_to_hsv( + Eigen::Vector3f(static_cast<float>(color.r) / 255.f, + static_cast<float>(color.g) / 255.f, + static_cast<float>(color.b) / 255.f)); + + // ARMARX_INFO << point.intensity; + + hsv(2) = std::clamp<float>(point.intensity, 0., 1.); + + const Eigen::Vector3f rgb = simox::color::hsv_to_rgb(hsv); + + return viz::Color{rgb(0), rgb(1), rgb(2)}; + } + + return color; + }(); + + pointCloud.addPoint(point.point.x(), point.point.y(), point.point.z(), specificColor); } pointCloud.pointSizeInPixels(3); @@ -135,22 +160,28 @@ namespace armarx::armem::server::laser_scans arviz.commit(l); } - std::vector<Eigen::Vector3f> + std::vector<ScanPoint> convertScanToGlobal(const armem::laser_scans::LaserScanStamped& scan, const Eigen::Isometry3f& global_T_sensor) { - auto scanCartesian = + const auto scanCartesian = armarx::armem::laser_scans::util::toCartesian<Eigen::Vector3f>(scan.data); - for (auto& point : scanCartesian) + std::vector<ScanPoint> points; + points.reserve(scan.data.size()); + + for (std::size_t i = 0; i < scan.data.size(); i++) { - point = global_T_sensor * point; + const auto& point = scanCartesian.at(i); + const auto& raw = scan.data.at(i); + + const Eigen::Vector3f pointGlobal = global_T_sensor * point; + points.push_back(ScanPoint{.point = pointGlobal, .intensity = raw.intensity}); } - return scanCartesian; + return points; } - // void Segment::getLatestObjectPoses(const wm::CoreSegment& coreSeg, ObjectPoseMap& out) // { // coreSeg.forEachProviderSegment([&out](const wm::ProviderSegment & provSegment) @@ -263,31 +294,35 @@ namespace armarx::armem::server::laser_scans { ARMARX_VERBOSE << "Visualizing `" << provider << "`"; - const auto global_T_sensor = [&]() -> Eigen::Isometry3f{ - + const auto global_T_sensor = [&]() -> Eigen::Isometry3f + { const auto robot = getSynchronizedRobot(scan.header.agent, scan.header.timestamp); - if(not robot) + if (not robot) { - ARMARX_VERBOSE << deactivateSpam(1) << "Robot `" << scan.header.agent << "`" << "not available"; + ARMARX_VERBOSE << deactivateSpam(1) << "Robot `" << scan.header.agent << "`" + << "not available"; return Eigen::Isometry3f::Identity(); } const auto sensorNode = robot->getRobotNode(scan.header.frame); ARMARX_CHECK_NOT_NULL(sensorNode) << "No robot node `" << scan.header.frame - << "` for robot `" << scan.header.agent << "`"; + << "` for robot `" << scan.header.agent << "`"; - ARMARX_VERBOSE << "Sensor position for sensor `" << scan.header.frame << "` is " << sensorNode->getGlobalPosition(); + ARMARX_VERBOSE << "Sensor position for sensor `" << scan.header.frame << "` is " + << sensorNode->getGlobalPosition(); return Eigen::Isometry3f{sensorNode->getGlobalPose()}; }(); - const std::vector<Eigen::Vector3f> points = convertScanToGlobal(scan, global_T_sensor); - const auto color = [&]() -> simox::Color{ - if(p.uniformColor) + const std::vector<ScanPoint> points = convertScanToGlobal(scan, global_T_sensor); + + const auto color = [&]() -> simox::Color + { + if (p.uniformColor) { return simox::Color::red(); } - + return simox::color::GlasbeyLUT::at(i++); }(); diff --git a/source/RobotAPI/libraries/armem_laser_scans/server/Visu.h b/source/RobotAPI/libraries/armem_laser_scans/server/Visu.h index d6c79dd12d9aaf7b85dfad6eacaf436e7e6f59c1..5218e6a0f5495684f2d2594d9495c2e0e31ab0fc 100644 --- a/source/RobotAPI/libraries/armem_laser_scans/server/Visu.h +++ b/source/RobotAPI/libraries/armem_laser_scans/server/Visu.h @@ -33,14 +33,18 @@ #include "RobotAPI/libraries/armem/server/wm/memory_definitions.h" #include "RobotAPI/libraries/armem_robot_state/client/common/VirtualRobotReader.h" #include <RobotAPI/components/ArViz/Client/Client.h> +#include <RobotAPI/libraries/armem/server/segment/SpecializedCoreSegment.h> +#include <RobotAPI/libraries/armem_laser_scans/types.h> #include <RobotAPI/libraries/armem_objects/types.h> #include <RobotAPI/libraries/armem_robot_state/server/forward_declarations.h> -#include <RobotAPI/libraries/armem_laser_scans/types.h> -#include <RobotAPI/libraries/armem/server/segment/SpecializedCoreSegment.h> - namespace armarx::armem::server::laser_scans { + struct ScanPoint + { + Eigen::Vector3f point; + float intensity; + }; /** * @brief Models decay of object localizations by decreasing the confidence @@ -54,7 +58,8 @@ namespace armarx::armem::server::laser_scans void defineProperties(armarx::PropertyDefinitionsPtr defs, const std::string& prefix = "visu."); - void init(const wm::CoreSegment* coreSegment, armem::robot_state::VirtualRobotReader* virtualRobotReader); + void init(const wm::CoreSegment* coreSegment, + armem::robot_state::VirtualRobotReader* virtualRobotReader); void connect(const viz::Client& arviz, DebugObserverInterfacePrx debugObserver = nullptr); @@ -70,11 +75,11 @@ namespace armarx::armem::server::laser_scans { bool enabled = true; bool uniformColor = false; + bool colorByIntensity = true; float frequencyHz = 5; int maxRobotAgeMs = 100; } p; - SimpleRunningTask<>::pointer_type updateTask; armem::robot_state::VirtualRobotReader* virtualRobotReader; @@ -84,7 +89,7 @@ namespace armarx::armem::server::laser_scans VirtualRobot::RobotPtr getSynchronizedRobot(const std::string& name, const DateTime& timestamp); - void visualizeScan(const std::vector<Eigen::Vector3f>& points, + void visualizeScan(const std::vector<ScanPoint>& points, const std::string& sensorName, const std::string& agentName, const viz::Color& color); diff --git a/source/RobotAPI/libraries/armem_robot_state/common/localization/TransformHelper.cpp b/source/RobotAPI/libraries/armem_robot_state/common/localization/TransformHelper.cpp index 529cd6d28a198d14779682d27826cb4d6b0f3cd4..e808a4b2e31f7d3763b0a0a8052502eb77260f27 100644 --- a/source/RobotAPI/libraries/armem_robot_state/common/localization/TransformHelper.cpp +++ b/source/RobotAPI/libraries/armem_robot_state/common/localization/TransformHelper.cpp @@ -258,19 +258,19 @@ namespace armarx::armem::common::robot_state::localization } catch (const armem::error::MissingEntry& missingEntryError) { - ARMARX_WARNING << missingEntryError.what(); + ARMARX_VERBOSE << missingEntryError.what(); } catch (const ::armarx::exceptions::local::ExpressionException& ex) { - ARMARX_WARNING << "Local expression exception: " << ex.what(); + ARMARX_VERBOSE << "Local expression exception: " << ex.what(); } catch (const ::armarx::LocalException& ex) { - ARMARX_WARNING << "Local exception: " << ex.what(); + ARMARX_VERBOSE << "Local exception: " << ex.what(); } catch (...) { - ARMARX_WARNING << "Unexpected error: " << GetHandledExceptionString(); + ARMARX_VERBOSE << "Unexpected error: " << GetHandledExceptionString(); } return {}; diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/Generator.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/Generator.cpp index d3c61320d0bd8d1f57fd03531edf1f79df5754f2..076d5aa61a6d0c79e4e3a56453675308e09f7bde 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/Generator.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/Generator.cpp @@ -24,40 +24,41 @@ // STD/STL #include "Generator.h" -#include "Factory.h" -#include <SimoxUtility/meta/type_name.h> #include <SimoxUtility/algorithm/string.h> +#include <SimoxUtility/meta/type_name.h> +#include "Factory.h" namespace armarx::aron::codegenerator::cpp { // constantes const std::string Generator::ARON_VARIABLE_PREFIX = "aron"; - const std::string Generator::ARON_MAYBE_TYPE_ACCESSOR = Generator::ARON_VARIABLE_PREFIX + "_maybeType"; + const std::string Generator::ARON_MAYBE_TYPE_ACCESSOR = + Generator::ARON_VARIABLE_PREFIX + "_maybeType"; const std::string Generator::ARON_READER_ACCESSOR = Generator::ARON_VARIABLE_PREFIX + "_r"; const std::string Generator::ARON_WRITER_ACCESSOR = Generator::ARON_VARIABLE_PREFIX + "_w"; - const std::string Generator::ARON_TEMPLATE_INSTANTIATIONS_ACCESSOR = Generator::ARON_VARIABLE_PREFIX + "_tmpls"; - const std::string Generator::ARON_VARIANT_RETURN_ACCESSOR = Generator::ARON_VARIABLE_PREFIX + "_variant"; + const std::string Generator::ARON_TEMPLATE_INSTANTIATIONS_ACCESSOR = + Generator::ARON_VARIABLE_PREFIX + "_tmpls"; + const std::string Generator::ARON_VARIANT_RETURN_ACCESSOR = + Generator::ARON_VARIABLE_PREFIX + "_variant"; const std::string Generator::ARON_PATH_ACCESSOR = Generator::ARON_VARIABLE_PREFIX + "_p"; const std::string Generator::ARON_OTHER_ACCESSOR = Generator::ARON_VARIABLE_PREFIX + "_o"; const SerializerFactoryPtr Generator::FACTORY = SerializerFactoryPtr(new GeneratorFactory()); // static methods - std::string Generator::EscapeAccessor(const std::string& accessor) + std::string + Generator::EscapeAccessor(const std::string& accessor) { - const static std::map<std::string, std::string> ESCAPE_ACCESSORS = - { - {"->", "_ptr_"}, - {".", "_dot_"}, - {"[", "_lbrC_"}, - {"]", "_rbrC_"}, - {"(", "_lbrR_"}, - {")", "_rbrR_"}, - {"*", "_ast_"} - }; + const static std::map<std::string, std::string> ESCAPE_ACCESSORS = {{"->", "_ptr_"}, + {".", "_dot_"}, + {"[", "_lbrC_"}, + {"]", "_rbrC_"}, + {"(", "_lbrR_"}, + {")", "_rbrR_"}, + {"*", "_ast_"}}; std::string escaped_accessor = accessor; for (const auto& [key, value] : ESCAPE_ACCESSORS) @@ -67,13 +68,16 @@ namespace armarx::aron::codegenerator::cpp return escaped_accessor; } - std::string Generator::ExtractCppTypename(const type::Variant& n) + std::string + Generator::ExtractCppTypename(const type::Variant& n) { auto cpp = Generator::FromAronType(n); ARMARX_CHECK_NOT_NULL(cpp); return cpp->getInstantiatedCppTypename(); } - std::vector<std::string> Generator::ExtractCppTypenames(const std::vector<type::VariantPtr>& n) + + std::vector<std::string> + Generator::ExtractCppTypenames(const std::vector<type::VariantPtr>& n) { std::vector<std::string> ret; for (const auto& v : n) @@ -83,29 +87,33 @@ namespace armarx::aron::codegenerator::cpp return ret; } - std::unique_ptr<Generator> Generator::FromAronType(const type::Variant& n) + std::unique_ptr<Generator> + Generator::FromAronType(const type::Variant& n) { return FACTORY->create(n, n.getPath()); } - // constructors - Generator::Generator(const std::string& instantiatedCppTypename, const std::string& classCppTypename, const std::string& aronDataTypename, const std::string& aronTypeTypename) : + Generator::Generator(const std::string& instantiatedCppTypename, + const std::string& classCppTypename, + const std::string& aronDataTypename, + const std::string& aronTypeTypename) : instantiatedCppTypename(instantiatedCppTypename), classCppTypename(classCppTypename), aronDataTypename(aronDataTypename), aronTypeTypename(aronTypeTypename) { - } // public methods - std::string Generator::getInstantiatedCppTypename() const + std::string + Generator::getInstantiatedCppTypename() const { return instantiatedCppTypename; } - std::string Generator::getFullInstantiatedCppTypename() const + std::string + Generator::getFullInstantiatedCppTypename() const { switch (getType().getMaybe()) { @@ -120,11 +128,15 @@ namespace armarx::aron::codegenerator::cpp case type::Maybe::UNIQUE_PTR: return "std::unique_ptr<" + getInstantiatedCppTypename() + ">"; default: - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Received unknown maybe enum", std::to_string((int) getType().getMaybe()), getType().getPath()); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "Received unknown maybe enum", + std::to_string((int)getType().getMaybe()), + getType().getPath()); } } - std::string Generator::getFullInstantiatedCppTypenameGenerator() const + std::string + Generator::getFullInstantiatedCppTypenameGenerator() const { switch (getType().getMaybe()) { @@ -139,16 +151,21 @@ namespace armarx::aron::codegenerator::cpp case type::Maybe::UNIQUE_PTR: return "std::make_unique<" + getInstantiatedCppTypename() + ">"; default: - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Received unknown maybe enum", std::to_string((int) getType().getMaybe()), getType().getPath()); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "Received unknown maybe enum", + std::to_string((int)getType().getMaybe()), + getType().getPath()); } } - std::string Generator::getClassCppTypename() const + std::string + Generator::getClassCppTypename() const { return classCppTypename; } - std::string Generator::getFullClassCppTypename() const + std::string + Generator::getFullClassCppTypename() const { switch (getType().getMaybe()) { @@ -163,11 +180,15 @@ namespace armarx::aron::codegenerator::cpp case type::Maybe::UNIQUE_PTR: return "std::unique_ptr<" + getClassCppTypename() + ">"; default: - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Received unknown maybe enum", std::to_string((int) getType().getMaybe()), getType().getPath()); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "Received unknown maybe enum", + std::to_string((int)getType().getMaybe()), + getType().getPath()); } } - CppCtorPtr Generator::toCtor(const std::string& name) const + CppCtorPtr + Generator::toCtor(const std::string& name) const { CppBlockPtr b = this->getCtorBlock(""); auto initList = this->getCtorInitializers(""); @@ -184,24 +205,28 @@ namespace armarx::aron::codegenerator::cpp return c; } - CppCtorPtr Generator::toCopyCtor(const std::string& name) const + CppCtorPtr + Generator::toCopyCtor(const std::string& name) const { CppBlockPtr b = this->getCopyCtorBlock(""); auto initList = this->getCopyCtorInitializers(""); if (b->size() > 0 || initList.second) { - CppCtorPtr c = CppCtorPtr(new CppCtor(name + "(const " + name + "& " + ARON_OTHER_ACCESSOR + ")")); + CppCtorPtr c = + CppCtorPtr(new CppCtor(name + "(const " + name + "& " + ARON_OTHER_ACCESSOR + ")")); c->addInitListEntries(initList.first); c->setBlock(b); return c; } - CppCtorPtr c = CppCtorPtr(new CppCtor(name + "(const " + name + "& " + ARON_OTHER_ACCESSOR + ") = default;")); + CppCtorPtr c = CppCtorPtr( + new CppCtor(name + "(const " + name + "& " + ARON_OTHER_ACCESSOR + ") = default;")); return c; } - CppMethodPtr Generator::toDtor(const std::string& name) const + CppMethodPtr + Generator::toDtor(const std::string& name) const { CppBlockPtr b = this->getDtorBlock(""); if (b->size() > 0) @@ -218,13 +243,16 @@ namespace armarx::aron::codegenerator::cpp return m; } - CppMethodPtr Generator::toResetSoftMethod() const + CppMethodPtr + Generator::toResetSoftMethod() const { std::stringstream doc; - doc << "@brief resetSoft() - This method resets all member variables with respect to the current parameterization. \n"; + doc << "@brief resetSoft() - This method resets all member variables with respect to the " + "current parameterization. \n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod("virtual void resetSoft() override", doc.str())); + CppMethodPtr m = + CppMethodPtr(new CppMethod("virtual void resetSoft() override", doc.str())); CppBlockPtr b = this->getResetSoftBlock(""); m->setBlock(b); @@ -232,13 +260,16 @@ namespace armarx::aron::codegenerator::cpp return m; } - CppMethodPtr Generator::toResetHardMethod() const + CppMethodPtr + Generator::toResetHardMethod() const { std::stringstream doc; - doc << "@brief resetHard() - This method resets member variables according to the XML type description. \n"; + doc << "@brief resetHard() - This method resets member variables according to the XML type " + "description. \n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod("virtual void resetHard() override", doc.str())); + CppMethodPtr m = + CppMethodPtr(new CppMethod("virtual void resetHard() override", doc.str())); CppBlockPtr b = this->getResetHardBlock(""); m->setBlock(b); @@ -246,13 +277,22 @@ namespace armarx::aron::codegenerator::cpp return m; } - CppMethodPtr Generator::toWriteTypeMethod() const + CppMethodPtr + Generator::toWriteTypeMethod() const { std::stringstream doc; - doc << "@brief writeType() - This method returns a new type from the class structure using a type writer implementation. This function is static. \n"; + doc << "@brief writeType() - This method returns a new type from the class structure using " + "a type writer implementation. This function is static. \n"; doc << "@return - the result of the writer implementation"; - CppMethodPtr m = CppMethodPtr(new CppMethod("template<class WriterT>\nstatic typename WriterT::ReturnType writeType(WriterT& " + ARON_WRITER_ACCESSOR + ", std::vector<std::string> " + ARON_TEMPLATE_INSTANTIATIONS_ACCESSOR + " = {}, armarx::aron::type::Maybe "+ ARON_MAYBE_TYPE_ACCESSOR +" = ::armarx::aron::type::Maybe::NONE, const ::armarx::aron::Path& "+ARON_PATH_ACCESSOR+" = ::armarx::aron::Path())", doc.str())); + CppMethodPtr m = CppMethodPtr(new CppMethod( + "template<class WriterT>\nstatic typename WriterT::ReturnType writeType(WriterT& " + + ARON_WRITER_ACCESSOR + ", std::vector<std::string> " + + ARON_TEMPLATE_INSTANTIATIONS_ACCESSOR + " = {}, armarx::aron::type::Maybe " + + ARON_MAYBE_TYPE_ACCESSOR + + " = ::armarx::aron::type::Maybe::NONE, const ::armarx::aron::Path& " + + ARON_PATH_ACCESSOR + " = ::armarx::aron::Path())", + doc.str())); CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("using _Aron_T [[maybe_unused]] = typename WriterT::ReturnType;"); @@ -264,14 +304,20 @@ namespace armarx::aron::codegenerator::cpp return m; } - CppMethodPtr Generator::toWriteMethod() const + CppMethodPtr + Generator::toWriteMethod() const { std::stringstream doc; - doc << "@brief write() - This method returns a new type from the member data types using a data writer implementation. \n"; + doc << "@brief write() - This method returns a new type from the member data types using a " + "data writer implementation. \n"; doc << "@param w - The writer implementation\n"; doc << "@return - the result of the writer implementation"; - CppMethodPtr m = CppMethodPtr(new CppMethod("template<class WriterT>\ntypename WriterT::ReturnType write(WriterT& " + ARON_WRITER_ACCESSOR + ", const ::armarx::aron::Path& "+ARON_PATH_ACCESSOR+" = armarx::aron::Path()) const", doc.str())); + CppMethodPtr m = CppMethodPtr( + new CppMethod("template<class WriterT>\ntypename WriterT::ReturnType write(WriterT& " + + ARON_WRITER_ACCESSOR + ", const ::armarx::aron::Path& " + + ARON_PATH_ACCESSOR + " = armarx::aron::Path()) const", + doc.str())); CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("using _Aron_T [[maybe_unused]] = typename WriterT::ReturnType;"); @@ -279,73 +325,106 @@ namespace armarx::aron::codegenerator::cpp std::string dummy; b->addBlock(this->getWriteBlock("", Path(), dummy)); b->addLine("catch(const std::exception& " + ARON_VARIABLE_PREFIX + "_e)"); - b->addLineAsBlock("throw ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, std::string(\"An error occured during the write method of an aron generated class. The full error log was:\\n\") + " + ARON_VARIABLE_PREFIX + "_e.what());"); + b->addLineAsBlock("throw ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, " + "std::string(\"An error occured during the write method of an aron " + "generated class. The full error log was:\\n\") + " + + ARON_VARIABLE_PREFIX + "_e.what());"); m->setBlock(b); m->setEnforceBlockGeneration(true); return m; } - CppMethodPtr Generator::toReadMethod() const + CppMethodPtr + Generator::toReadMethod() const { std::stringstream doc; - doc << "@brief read() - This method sets the struct members to new values given in a data reader implementation. \n"; + doc << "@brief read() - This method sets the struct members to new values given in a data " + "reader implementation. \n"; doc << "@param r - The reader implementation\n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod("template<class ReaderT>\nvoid read(ReaderT& " + ARON_READER_ACCESSOR + ", typename ReaderT::InputType& input)", doc.str())); + CppMethodPtr m = CppMethodPtr(new CppMethod("template<class ReaderT>\nvoid read(ReaderT& " + + ARON_READER_ACCESSOR + + ", typename ReaderT::InputType& input)", + doc.str())); CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("using _Aron_T [[maybe_unused]] = typename ReaderT::InputType;"); b->addLine("using _Aron_TNonConst [[maybe_unused]] = typename ReaderT::InputTypeNonConst;"); b->addLine("this->resetSoft();"); - b->addLine("ARMARX_CHECK_AND_THROW(!" + ARON_READER_ACCESSOR + ".readNull(input), ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, \"The input to the read method must not be null.\"));"); + b->addLine("ARMARX_CHECK_AND_THROW(!" + ARON_READER_ACCESSOR + + ".readNull(input), ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, " + "\"The input to the read method must not be null.\"));"); b->addLine("try"); b->addBlock(this->getReadBlock("", "input")); b->addLine("catch(const std::exception& " + ARON_VARIABLE_PREFIX + "_e)"); - b->addLineAsBlock("throw ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, std::string(\"An error occured during the read method of an aron generated class. The full error log was:\\n\") + " + ARON_VARIABLE_PREFIX + "_e.what());"); + b->addLineAsBlock("throw ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, " + "std::string(\"An error occured during the read method of an aron " + "generated class. The full error log was:\\n\") + " + + ARON_VARIABLE_PREFIX + "_e.what());"); m->setBlock(b); m->setEnforceBlockGeneration(true); return m; } - CppMethodPtr Generator::toSpecializedDataWriterMethod(const WriterInfo& info) const + CppMethodPtr + Generator::toSpecializedDataWriterMethod(const WriterInfo& info) const { std::stringstream doc; - doc << "@brief " << info.methodName << "() - This method returns a new data from the member data types using a writer implementation. \n"; + doc << "@brief " << info.methodName + << "() - This method returns a new data from the member data types using a writer " + "implementation. \n"; doc << "@return - the result of the writer implementation"; - CppMethodPtr m = CppMethodPtr(new CppMethod(info.returnType + " " + info.methodName + "() const" + (info.override ? " override" : ""), doc.str())); + CppMethodPtr m = + CppMethodPtr(new CppMethod(info.returnType + " " + info.methodName + "() const" + + (info.override ? " override" : ""), + doc.str())); m->addLine(info.writerClassType + " writer;"); - m->addLine("return " + info.enforceConversion + "(this->write(writer))" + info.enforceMemberAccess + ";"); + m->addLine("return " + info.enforceConversion + "(this->write(writer))" + + info.enforceMemberAccess + ";"); m->setEnforceBlockGeneration(true); return m; } - CppMethodPtr Generator::toSpecializedDataReaderMethod(const ReaderInfo& info) const + CppMethodPtr + Generator::toSpecializedDataReaderMethod(const ReaderInfo& info) const { std::stringstream doc; - doc << "@brief " << info.methodName << " - This method sets the struct members to new values given in a reader implementation. \n"; + doc << "@brief " << info.methodName + << " - This method sets the struct members to new values given in a reader " + "implementation. \n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod("void " + info.methodName + "(const " + info.argumentType + "& input)" + (info.override ? " override" : ""), doc.str())); + CppMethodPtr m = + CppMethodPtr(new CppMethod("void " + info.methodName + "(const " + info.argumentType + + "& input)" + (info.override ? " override" : ""), + doc.str())); m->addLine(info.readerClassType + " reader;"); - m->addLine("this->read(reader, " + info.enforceConversion + "(input)" + info.enforceMemberAccess + ");"); + m->addLine("this->read(reader, " + info.enforceConversion + "(input)" + + info.enforceMemberAccess + ");"); m->setEnforceBlockGeneration(true); return m; } - CppMethodPtr Generator::toSpecializedStaticDataReaderMethod(const StaticReaderInfo& info) const + CppMethodPtr + Generator::toSpecializedStaticDataReaderMethod(const StaticReaderInfo& info) const { std::stringstream doc; - doc << "@brief " << info.methodName << "() - This method sets the struct members to new values given in a reader implementation. \n"; + doc << "@brief " << info.methodName + << "() - This method sets the struct members to new values given in a reader " + "implementation. \n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod("static " + info.returnType + " " + info.methodName + "(const " + info.argumentType + "& input)", doc.str())); + CppMethodPtr m = + CppMethodPtr(new CppMethod("static " + info.returnType + " " + info.methodName + + "(const " + info.argumentType + "& input)", + doc.str())); m->addLine(info.returnType + " t;"); m->addLine("t.fromAron(input);"); m->addLine("return t;"); @@ -354,28 +433,36 @@ namespace armarx::aron::codegenerator::cpp return m; } - CppMethodPtr Generator::toSpecializedTypeWriterMethod(const WriterInfo& info) const + CppMethodPtr + Generator::toSpecializedTypeWriterMethod(const WriterInfo& info) const { std::stringstream doc; - doc << "@brief " << info.methodName << "() - This method returns a new type from the member data types using a writer implementation. \n"; + doc << "@brief " << info.methodName + << "() - This method returns a new type from the member data types using a writer " + "implementation. \n"; doc << "@return - the result of the writer implementation"; - CppMethodPtr m = CppMethodPtr(new CppMethod("static " + info.returnType + " " + info.methodName + "()", doc.str())); + CppMethodPtr m = CppMethodPtr( + new CppMethod("static " + info.returnType + " " + info.methodName + "()", doc.str())); m->addLine(info.writerClassType + " writer;"); - m->addLine("return " + info.enforceConversion + "(writeType(writer))" + info.enforceMemberAccess + ";"); + m->addLine("return " + info.enforceConversion + "(writeType(writer))" + + info.enforceMemberAccess + ";"); m->setEnforceBlockGeneration(true); return m; } - CppMethodPtr Generator::toEqualsMethod() const + CppMethodPtr + Generator::toEqualsMethod() const { std::stringstream doc; - doc << "@brief operator==() - This method checks whether all values equal another instance. \n"; + doc << "@brief operator==() - This method checks whether all values equal another " + "instance. \n"; doc << "@param i - The other instance\n"; doc << "@return - true, if all members are the same, false otherwise"; - CppMethodPtr m = CppMethodPtr(new CppMethod("bool operator==(const " + this->getFullClassCppTypename() + "& i) const", doc.str())); + CppMethodPtr m = CppMethodPtr(new CppMethod( + "bool operator==(const " + this->getFullClassCppTypename() + "& i) const", doc.str())); CppBlockPtr b = this->getEqualsBlock("", "i"); b->addLine("return true;"); m->setBlock(b); @@ -385,89 +472,111 @@ namespace armarx::aron::codegenerator::cpp } // defaulted implementations of the blocks - std::vector<std::string> Generator::getRequiredIncludes() const + std::vector<std::string> + Generator::getRequiredIncludes() const { return {}; } - std::vector<CppFieldPtr> Generator::getPublicVariableDeclarations(const std::string& name) const + + std::vector<CppFieldPtr> + Generator::getPublicVariableDeclarations(const std::string& name) const { auto field = std::make_shared<CppField>(this->getFullInstantiatedCppTypename(), name); return {field}; } - std::pair<std::vector<std::pair<std::string, std::string>>, bool> Generator::getCtorInitializers(const std::string& name) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Generator::getCtorInitializers(const std::string& name) const { - return {{{name, "{}"}}, false}; + return {{}, false}; } - CppBlockPtr Generator::getCtorBlock(const std::string&) const + CppBlockPtr + Generator::getCtorBlock(const std::string&) const { return std::make_shared<CppBlock>(); } - std::pair<std::vector<std::pair<std::string, std::string>>, bool> Generator::getCopyCtorInitializers(const std::string& name) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Generator::getCopyCtorInitializers(const std::string& name) const { const auto& t = getType(); if (t.getMaybe() == type::Maybe::UNIQUE_PTR) // unique ptrs cant be copied { - return {{{name, ARON_OTHER_ACCESSOR + "." + name + " ? " + resolveMaybeGenerator("*" + ARON_OTHER_ACCESSOR + "." + name) + " : nullptr"}}, true}; + return {{{name, + ARON_OTHER_ACCESSOR + "." + name + " ? " + + resolveMaybeGenerator("*" + ARON_OTHER_ACCESSOR + "." + name) + + " : nullptr"}}, + true}; } return {{{name, ARON_OTHER_ACCESSOR + "." + name}}, false}; } - CppBlockPtr Generator::getCopyCtorBlock(const std::string&) const + CppBlockPtr + Generator::getCopyCtorBlock(const std::string&) const { return std::make_shared<CppBlock>(); } - CppBlockPtr Generator::getDtorBlock(const std::string&) const + CppBlockPtr + Generator::getDtorBlock(const std::string&) const { return std::make_shared<CppBlock>(); } - CppBlockPtr Generator::getResetHardBlock(const std::string& cppAccessor) const + CppBlockPtr + Generator::getResetHardBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine(cppAccessor + " = " + this->getFullInstantiatedCppTypename() + "();"); + block_if_data->addLine(cppAccessor + " = " + this->getFullInstantiatedCppTypename() + + "();"); return resolveMaybeResetHardBlock(block_if_data, cppAccessor); } - CppBlockPtr Generator::getResetSoftBlock(const std::string& cppAccessor) const + CppBlockPtr + Generator::getResetSoftBlock(const std::string& cppAccessor) const { auto block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine(cppAccessor + " = " + this->getFullInstantiatedCppTypename() + "();"); + block_if_data->addLine(cppAccessor + " = " + this->getFullInstantiatedCppTypename() + + "();"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } - CppBlockPtr Generator::getEqualsBlock(const std::string& accessor, const std::string& otherInstanceAccessor) const + CppBlockPtr + Generator::getEqualsBlock(const std::string& accessor, + const std::string& otherInstanceAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string resolved_accessor = this->resolveMaybeAccessor(accessor); - std::string other_instance_resolved_accessor = this->resolveMaybeAccessor(otherInstanceAccessor); + std::string other_instance_resolved_accessor = + this->resolveMaybeAccessor(otherInstanceAccessor); - block_if_data->addLine("if (not (" + resolved_accessor + " == " + other_instance_resolved_accessor + "))"); + block_if_data->addLine("if (not (" + resolved_accessor + + " == " + other_instance_resolved_accessor + "))"); block_if_data->addLineAsBlock("return false;"); return resolveMaybeEqualsBlock(block_if_data, accessor, otherInstanceAccessor); } - // Helper methods - std::string Generator::resolveMaybeAccessor(const std::string& s) const + std::string + Generator::resolveMaybeAccessor(const std::string& s) const { const auto& t = getType(); if (t.getMaybe() == type::Maybe::OPTIONAL) { return s + ".value()"; } - if (t.getMaybe() == type::Maybe::RAW_PTR || t.getMaybe() == type::Maybe::SHARED_PTR || t.getMaybe() == type::Maybe::UNIQUE_PTR) + if (t.getMaybe() == type::Maybe::RAW_PTR || t.getMaybe() == type::Maybe::SHARED_PTR || + t.getMaybe() == type::Maybe::UNIQUE_PTR) { return "*" + s; } return s; } - std::string Generator::resolveMaybeGenerator(const std::string& args) const + std::string + Generator::resolveMaybeGenerator(const std::string& args) const { const auto& t = getType(); if (t.getMaybe() == type::Maybe::OPTIONAL) @@ -487,10 +596,10 @@ namespace armarx::aron::codegenerator::cpp return "std::make_unique<" + getInstantiatedCppTypename() + ">(" + args + ")"; } return ""; - } - std::string Generator::resolveMaybeGeneratorWithSetter(const std::string& s, const std::string& args) const + std::string + Generator::resolveMaybeGeneratorWithSetter(const std::string& s, const std::string& args) const { auto gen = resolveMaybeGenerator(args); if (!gen.empty()) @@ -500,7 +609,8 @@ namespace armarx::aron::codegenerator::cpp return ""; } - std::string Generator::nextEl() const + std::string + Generator::nextEl() const { const auto& type = getType(); switch (type.getMaybe()) @@ -513,10 +623,14 @@ namespace armarx::aron::codegenerator::cpp case type::Maybe::UNIQUE_PTR: return "->"; } - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Received unknown maybe enum", std::to_string((int) type.getMaybe()), type.getPath()); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "Received unknown maybe enum", + std::to_string((int)type.getMaybe()), + type.getPath()); } - std::string Generator::toPointerAccessor(const std::string& cppAccessor) const + std::string + Generator::toPointerAccessor(const std::string& cppAccessor) const { const auto& type = getType(); switch (type.getMaybe()) @@ -528,12 +642,18 @@ namespace armarx::aron::codegenerator::cpp return cppAccessor + ".get()"; case type::Maybe::NONE: //[[fallthrough]]; - case type::Maybe::OPTIONAL: break; + case type::Maybe::OPTIONAL: + break; } - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Received invalid maybe enum (not a pointer?)", std::to_string((int) type.getMaybe()), type.getPath()); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "Received invalid maybe enum (not a pointer?)", + std::to_string((int)type.getMaybe()), + type.getPath()); } - CppBlockPtr Generator::resolveMaybeResetHardBlock(const CppBlockPtr& block_if_data, const std::string& cppAccessor) const + CppBlockPtr + Generator::resolveMaybeResetHardBlock(const CppBlockPtr& block_if_data, + const std::string& cppAccessor) const { const auto& type = getType(); if (type.getMaybe() == type::Maybe::OPTIONAL) @@ -542,7 +662,9 @@ namespace armarx::aron::codegenerator::cpp b->addLine(cppAccessor + " = std::nullopt;"); return b; } - else if (type.getMaybe() == type::Maybe::RAW_PTR || type.getMaybe() == type::Maybe::SHARED_PTR || type.getMaybe() == type::Maybe::UNIQUE_PTR) + else if (type.getMaybe() == type::Maybe::RAW_PTR || + type.getMaybe() == type::Maybe::SHARED_PTR || + type.getMaybe() == type::Maybe::UNIQUE_PTR) { CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine(cppAccessor + " = nullptr;"); @@ -551,10 +673,14 @@ namespace armarx::aron::codegenerator::cpp return block_if_data; } - CppBlockPtr Generator::resolveMaybeResetSoftBlock(const CppBlockPtr& block_if_data, const std::string& cppAccessor) const + CppBlockPtr + Generator::resolveMaybeResetSoftBlock(const CppBlockPtr& block_if_data, + const std::string& cppAccessor) const { const auto& type = getType(); - if (type.getMaybe() == type::Maybe::OPTIONAL || type.getMaybe() == type::Maybe::RAW_PTR || type.getMaybe() == type::Maybe::SHARED_PTR || type.getMaybe() == type::Maybe::UNIQUE_PTR) + if (type.getMaybe() == type::Maybe::OPTIONAL || type.getMaybe() == type::Maybe::RAW_PTR || + type.getMaybe() == type::Maybe::SHARED_PTR || + type.getMaybe() == type::Maybe::UNIQUE_PTR) { CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("if (" + cppAccessor + ") // if " + cppAccessor + " contains data"); @@ -564,10 +690,14 @@ namespace armarx::aron::codegenerator::cpp return block_if_data; } - CppBlockPtr Generator::resolveMaybeWriteBlock(const CppBlockPtr& block_if_data, const std::string& cppAccessor) const + CppBlockPtr + Generator::resolveMaybeWriteBlock(const CppBlockPtr& block_if_data, + const std::string& cppAccessor) const { const auto& type = getType(); - if (type.getMaybe() == type::Maybe::OPTIONAL || type.getMaybe() == type::Maybe::RAW_PTR || type.getMaybe() == type::Maybe::SHARED_PTR || type.getMaybe() == type::Maybe::UNIQUE_PTR) + if (type.getMaybe() == type::Maybe::OPTIONAL || type.getMaybe() == type::Maybe::RAW_PTR || + type.getMaybe() == type::Maybe::SHARED_PTR || + type.getMaybe() == type::Maybe::UNIQUE_PTR) { CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("if (" + cppAccessor + ") // if " + cppAccessor + " contains data"); @@ -577,13 +707,19 @@ namespace armarx::aron::codegenerator::cpp return block_if_data; } - CppBlockPtr Generator::resolveMaybeReadBlock(const CppBlockPtr& block_if_data, const std::string& cppAccessor, const std::string& variantAccessor) const + CppBlockPtr + Generator::resolveMaybeReadBlock(const CppBlockPtr& block_if_data, + const std::string& cppAccessor, + const std::string& variantAccessor) const { const auto& type = getType(); - if (type.getMaybe() == type::Maybe::OPTIONAL || type.getMaybe() == type::Maybe::RAW_PTR || type.getMaybe() == type::Maybe::SHARED_PTR || type.getMaybe() == type::Maybe::UNIQUE_PTR) + if (type.getMaybe() == type::Maybe::OPTIONAL || type.getMaybe() == type::Maybe::RAW_PTR || + type.getMaybe() == type::Maybe::SHARED_PTR || + type.getMaybe() == type::Maybe::UNIQUE_PTR) { CppBlockPtr b = std::make_shared<CppBlock>(); - b->addLine("if (not (" + ARON_READER_ACCESSOR + ".readNull(" + variantAccessor + "))) // if aron contains data"); + b->addLine("if (not (" + ARON_READER_ACCESSOR + ".readNull(" + variantAccessor + + "))) // if aron contains data"); { CppBlockPtr ifb = std::make_shared<CppBlock>(); ifb->addLine(resolveMaybeGeneratorWithSetter(cppAccessor)); @@ -595,18 +731,31 @@ namespace armarx::aron::codegenerator::cpp return block_if_data; } - CppBlockPtr Generator::resolveMaybeEqualsBlock(const CppBlockPtr& block_if_data, const std::string& accessor, const std::string& otherInstanceAccessor) const + CppBlockPtr + Generator::resolveMaybeEqualsBlock(const CppBlockPtr& block_if_data, + const std::string& accessor, + const std::string& otherInstanceAccessor) const { const auto& type = getType(); - if (type.getMaybe() == type::Maybe::OPTIONAL || type.getMaybe() == type::Maybe::RAW_PTR || type.getMaybe() == type::Maybe::SHARED_PTR || type.getMaybe() == type::Maybe::UNIQUE_PTR) + if (type.getMaybe() == type::Maybe::RAW_PTR || type.getMaybe() == type::Maybe::SHARED_PTR || type.getMaybe() == type::Maybe::UNIQUE_PTR) + { + CppBlockPtr b = std::make_shared<CppBlock>(); + b->addLine("if (not (static_cast<bool>(" + accessor + ") == static_cast<bool>(" + otherInstanceAccessor + "))) // check if both contain data"); + b->addLineAsBlock("return false;"); + b->addLine("if (static_cast<bool>(" + accessor + ") && static_cast<bool>(" + otherInstanceAccessor + "))"); + b->addBlock(block_if_data); + return b; + } + + if (type.getMaybe() == type::Maybe::OPTIONAL) { CppBlockPtr b = std::make_shared<CppBlock>(); - b->addLine("if (not ((bool) " + accessor + " == (bool) " + otherInstanceAccessor + ")) // check if both contain data"); + b->addLine("if (not ( " + accessor + ".has_value() == " + otherInstanceAccessor + ".has_value())) // check if both contain data"); b->addLineAsBlock("return false;"); - b->addLine("if ((bool) " + accessor + " && (bool) " + otherInstanceAccessor + ")"); + b->addLine("if ( " + accessor + ".has_value() && " + otherInstanceAccessor + ".has_value())"); b->addBlock(block_if_data); return b; } return block_if_data; } -} +} // namespace armarx::aron::codegenerator::cpp diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/enum/IntEnum.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/enum/IntEnum.cpp index 00a9ab35d7f52eb757963c97355403377459737e..dbff73cdf796524958269d256c5100ff95c304b9 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/enum/IntEnum.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/enum/IntEnum.cpp @@ -26,7 +26,6 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { // constructors @@ -35,18 +34,27 @@ namespace armarx::aron::codegenerator::cpp::generator e.getEnumName(), e.getEnumName(), simox::meta::get_type_name<data::dto::NDArray>(), - simox::meta::get_type_name<type::dto::IntEnum>(), e) + simox::meta::get_type_name<type::dto::IntEnum>(), + e) + { + } + + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + IntEnum::getCtorInitializers(const std::string& name) const { + return {{{name, type.getDefaultValueName()}}, true}; } - CppBlockPtr IntEnum::getResetSoftBlock(const std::string& accessor) const + CppBlockPtr + IntEnum::getResetSoftBlock(const std::string& accessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(accessor + nextEl() + "resetSoft();"); return this->resolveMaybeResetSoftBlock(block_if_data, accessor); } - CppBlockPtr IntEnum::getResetHardBlock(const std::string& accessor) const + CppBlockPtr + IntEnum::getResetHardBlock(const std::string& accessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); if (type.getMaybe() != type::Maybe::NONE) @@ -60,39 +68,51 @@ namespace armarx::aron::codegenerator::cpp::generator return this->resolveMaybeResetHardBlock(b, accessor); } - CppBlockPtr IntEnum::getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const + CppBlockPtr + IntEnum::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto "+variantAccessor+" = " +getInstantiatedCppTypename() + "::writeType(" + ARON_WRITER_ACCESSOR + ", " + - "{}, " + - conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + cppAccessor); + b->addLine("auto " + variantAccessor + " = " + getInstantiatedCppTypename() + + "::writeType(" + ARON_WRITER_ACCESSOR + ", " + "{}, " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + cppAccessor); return b; } - CppBlockPtr IntEnum::getWriteBlock(const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const + CppBlockPtr + IntEnum::getWriteBlock(const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - block_if_data->addLine(variantAccessor+" = " + cppAccessor + nextEl() + "write(" + ARON_WRITER_ACCESSOR + ", "+ - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + cppAccessor); + block_if_data->addLine(variantAccessor + " = " + cppAccessor + nextEl() + "write(" + + ARON_WRITER_ACCESSOR + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + cppAccessor); return resolveMaybeWriteBlock(block_if_data, cppAccessor); } - CppBlockPtr IntEnum::getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const + CppBlockPtr + IntEnum::getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); if (const auto reset = resolveMaybeGeneratorWithSetter(cppAccessor); !reset.empty()) { block_if_data->addLine(reset); } - block_if_data->addLine(cppAccessor + nextEl() + "read(" + ARON_READER_ACCESSOR + ", " + variantAccessor + ");"); + block_if_data->addLine(cppAccessor + nextEl() + "read(" + ARON_READER_ACCESSOR + ", " + + variantAccessor + ");"); return resolveMaybeReadBlock(block_if_data, cppAccessor, variantAccessor); } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/enum/IntEnum.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/enum/IntEnum.h index cd5b36bcef8300bbb57b88abdf14ca2bde9bc911..4fc6383beebab99aaf334b21a26498d3dfcb00ca 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/enum/IntEnum.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/enum/IntEnum.h @@ -23,20 +23,18 @@ #pragma once -#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/SpecializedGenerator.h> -#include <RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.h> - #include <map> #include <string> +#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/SpecializedGenerator.h> +#include <RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.h> namespace armarx::aron::codegenerator::cpp::generator { class IntEnum; typedef std::shared_ptr<IntEnum> IntEnumSerializerPtr; - class IntEnum : - public detail::SpecializedGeneratorBase<type::IntEnum, IntEnum> + class IntEnum : public detail::SpecializedGeneratorBase<type::IntEnum, IntEnum> { public: // constructors @@ -44,10 +42,18 @@ namespace armarx::aron::codegenerator::cpp::generator virtual ~IntEnum() = default; // virtual implementations + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string& name) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getWriteBlock(const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getWriteBlock(const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Image.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Image.cpp index aae1c701a7e23804273f60346a77e346bfee1daf..f7e1a704c4903bf7c6be53bfd0bd7fb9110e123f 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Image.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Image.cpp @@ -26,79 +26,103 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { - const std::map<type::image::PixelType, std::tuple<std::string, int, std::string>> PixelType2Cpp = - { - { type::image::PixelType::RGB24, {"CV_8UC3", 3, "::armarx::aron::type::image::PixelType::RGB24"}}, - { type::image::PixelType::DEPTH32, {"CV_32FC1", 4, "::armarx::aron::type::image::PixelType::DEPTH32"}}, + const std::map<type::image::PixelType, std::tuple<std::string, int, std::string>> + PixelType2Cpp = { + {type::image::PixelType::RGB24, + {"CV_8UC3", 3, "::armarx::aron::type::image::PixelType::RGB24"}}, + {type::image::PixelType::DEPTH32, + {"CV_32FC1", 4, "::armarx::aron::type::image::PixelType::DEPTH32"}}, }; - // constructors Image::Image(const type::Image& n) : detail::NDArrayGenerator<type::Image, Image>( "cv::Mat", "cv::Mat", simox::meta::get_type_name<data::dto::NDArray>(), - simox::meta::get_type_name<type::dto::Image>(), n) + simox::meta::get_type_name<type::dto::Image>(), + n) { } - std::vector<std::string> Image::getRequiredIncludes() const + std::vector<std::string> + Image::getRequiredIncludes() const { return {"<opencv2/core/core.hpp>"}; } + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Image::getCtorInitializers(const std::string&) const + { + // TODO + return {{}, false}; + } - CppBlockPtr Image::getResetHardBlock(const std::string& cppAccessor) const + CppBlockPtr + Image::getResetHardBlock(const std::string& cppAccessor) const { - CppBlockPtr block_if_data = detail::NDArrayGenerator<type::Image, Image>::getResetHardBlock(cppAccessor); - block_if_data->addLine(cppAccessor + ".create(0, 0, " + std::get<0>(PixelType2Cpp.at(type.getPixelType())) + ");"); + CppBlockPtr block_if_data = + detail::NDArrayGenerator<type::Image, Image>::getResetHardBlock(cppAccessor); + block_if_data->addLine(cppAccessor + ".create(0, 0, " + + std::get<0>(PixelType2Cpp.at(type.getPixelType())) + ");"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } - - CppBlockPtr Image::getResetSoftBlock(const std::string& cppAccessor) const + CppBlockPtr + Image::getResetSoftBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine(cppAccessor + ".create(0, 0, " + std::get<0>(PixelType2Cpp.at(type.getPixelType())) + ");"); + block_if_data->addLine(cppAccessor + ".create(0, 0, " + + std::get<0>(PixelType2Cpp.at(type.getPixelType())) + ");"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } - - CppBlockPtr Image::getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const + CppBlockPtr + Image::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeImage(" + std::get<2>(PixelType2Cpp.at(type.getPixelType())) + ", " + - conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + cppAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeImage(" + + std::get<2>(PixelType2Cpp.at(type.getPixelType())) + ", " + "\"" + + type.getDefaultValue() + "\", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + cppAccessor); return b; } - - CppBlockPtr Image::getWriteBlock(const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const + CppBlockPtr + Image::getWriteBlock(const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; const std::string shape_vec = ARON_VARIABLE_PREFIX + "_" + escaped_accessor + "_imageShape"; - block_if_data->addLine("std::vector<int> " + shape_vec + "(" + cppAccessor + nextEl() + "size.p, " + cppAccessor + nextEl() + "size.p + " + cppAccessor + nextEl() + "dims);"); - block_if_data->addLine(shape_vec+".push_back(" + cppAccessor + nextEl() + "elemSize());"); - - block_if_data->addLine(variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeNDArray(" + shape_vec + ", "+ - "std::to_string(" + cppAccessor + nextEl() + "type()), "+ - "reinterpret_cast<const unsigned char*>(" + cppAccessor + nextEl() + "data), "+ - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {" + simox::alg::join(p.getPath(), ", ") + "})); // of " + cppAccessor); + block_if_data->addLine("std::vector<int> " + shape_vec + "(" + cppAccessor + nextEl() + + "size.p, " + cppAccessor + nextEl() + "size.p + " + cppAccessor + + nextEl() + "dims);"); + block_if_data->addLine(shape_vec + ".push_back(" + cppAccessor + nextEl() + "elemSize());"); + + block_if_data->addLine(variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeNDArray(" + + shape_vec + ", " + "std::to_string(" + cppAccessor + nextEl() + + "type()), " + "reinterpret_cast<const unsigned char*>(" + + cppAccessor + nextEl() + "data), " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + cppAccessor); return resolveMaybeWriteBlock(block_if_data, cppAccessor); } - - CppBlockPtr Image::getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const + CppBlockPtr + Image::getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); @@ -109,23 +133,28 @@ namespace armarx::aron::codegenerator::cpp::generator block_if_data->addLine("std::string " + type + ";"); block_if_data->addLine("std::vector<int> " + dims + ";"); block_if_data->addLine("std::vector<unsigned char> " + data + ";"); - block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readNDArray("+variantAccessor+", "+dims+", "+type+", "+data+"); // of " + cppAccessor); - block_if_data->addLine(cppAccessor + " = " + getInstantiatedCppTypename() + "(std::vector<int>({" + dims + ".begin(), std::prev(" + dims + ".end())}), std::stoi(" + type + "));"); - block_if_data->addLine("std::memcpy(reinterpret_cast<unsigned char*>(" + cppAccessor + nextEl() + "data), "+data+".data(), "+data+".size());"); + block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readNDArray(" + variantAccessor + + ", " + dims + ", " + type + ", " + data + "); // of " + cppAccessor); + block_if_data->addLine(cppAccessor + " = " + getInstantiatedCppTypename() + + "(std::vector<int>({" + dims + ".begin(), std::prev(" + dims + + ".end())}), std::stoi(" + type + "));"); + block_if_data->addLine("std::memcpy(reinterpret_cast<unsigned char*>(" + cppAccessor + + nextEl() + "data), " + data + ".data(), " + data + ".size());"); return resolveMaybeReadBlock(block_if_data, cppAccessor, variantAccessor); } - - CppBlockPtr Image::getEqualsBlock(const std::string& accessor, const std::string& otherInstanceAccessor) const + CppBlockPtr + Image::getEqualsBlock(const std::string& accessor, + const std::string& otherInstanceAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string resolved_accessor = this->resolveMaybeAccessor(accessor); - std::string other_instance_resolved_accessor = this->resolveMaybeAccessor(otherInstanceAccessor); + std::string other_instance_resolved_accessor = + this->resolveMaybeAccessor(otherInstanceAccessor); - block_if_data->addLine("if (cv::countNonZero(" + resolved_accessor + " != " + other_instance_resolved_accessor + ") != 0)"); + block_if_data->addLine("if (cv::countNonZero(" + resolved_accessor + + " != " + other_instance_resolved_accessor + ") != 0)"); block_if_data->addLineAsBlock("return false;"); return resolveMaybeEqualsBlock(block_if_data, accessor, otherInstanceAccessor); } -} - - +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Image.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Image.h index 72f6947c9405a1a202e8d1b94b9f990fca3fefbf..532c4adc265d8593b29fe640bee81b7cf3fe73d5 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Image.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Image.h @@ -23,33 +23,37 @@ #pragma once -#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> -#include <RobotAPI/libraries/aron/core/type/variant/ndarray/Image.h> - #include <map> #include <memory> #include <string> +#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> +#include <RobotAPI/libraries/aron/core/type/variant/ndarray/Image.h> namespace armarx::aron::codegenerator::cpp::generator { - class Image : - public detail::NDArrayGenerator<type::Image, Image> + class Image : public detail::NDArrayGenerator<type::Image, Image> { public: - Image(const type::Image& n); virtual ~Image() = default; // virtual implementations std::vector<std::string> getRequiredIncludes() const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getWriteBlock(const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getWriteBlock(const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const final; CppBlockPtr getEqualsBlock(const std::string&, const std::string&) const final; - }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Matrix.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Matrix.cpp index ce9389d138de2774555bb3c1b6bbc45b151d65cc..be7974fb2ba04d07814a468eec39f982d55aa7c5 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Matrix.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Matrix.cpp @@ -58,6 +58,33 @@ namespace armarx::aron::codegenerator::cpp::generator return {"<Eigen/Core>"}; } + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Matrix::getCtorInitializers(const std::string& name) const + { + if (type.getDefaultValue() == aron::type::matrix::default_value::DEFAULT) + { + return {{}, false}; + } + if (type.getDefaultValue() == aron::type::matrix::default_value::IDENTITY) + { + return {{{name, getInstantiatedCppTypename() + "::Identity()"}}, true}; + } + if (type.getDefaultValue() == aron::type::matrix::default_value::ZEROS) + { + return {{{name, getInstantiatedCppTypename() + "::Zero()"}}, true}; + } + if (type.getDefaultValue() == aron::type::matrix::default_value::ONES) + { + return {{{name, getInstantiatedCppTypename() + "::One()"}}, true}; + } + else + { + // try to parse num. We ensure from typereader that defaultValue is valid number + return {{{name, getInstantiatedCppTypename() + "::One() * " + type.getDefaultValue()}}, + true}; + } + } + CppBlockPtr Matrix::getResetSoftBlock(const std::string& cppAccessor) const { @@ -76,12 +103,12 @@ namespace armarx::aron::codegenerator::cpp::generator std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + - ".writeMatrix((int) " + std::to_string(type.getRows()) + ", " + "(int) " + - std::to_string(type.getCols()) + ", " + - std::get<2>(ElementType2Cpp.at(type.getElementType())) + ", " + - conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + - ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + - "})); // of " + cppAccessor); + ".writeMatrix(static_cast<int>( " + std::to_string(type.getRows()) + "), " + "static_cast<int>( " + + std::to_string(type.getCols()) + "), " + + std::get<2>(ElementType2Cpp.at(type.getElementType())) + ", " + "\"" + + type.getDefaultValue() + "\", " + conversion::Maybe2CppString.at(type.getMaybe()) + + ", " + "armarx::aron::Path(" + ARON_PATH_ACCESSOR + ", {" + + simox::alg::join(p.getPath(), ", ") + "})); // of " + cppAccessor); return b; } @@ -96,8 +123,8 @@ namespace armarx::aron::codegenerator::cpp::generator variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; block_if_data->addLine( - variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeNDArray({(int) " + cppAccessor + - nextEl() + "rows(), " + "(int) " + cppAccessor + nextEl() + "cols(), " + + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeNDArray({static_cast<int>( " + cppAccessor + + nextEl() + "rows() ), " + "static_cast<int>( " + cppAccessor + nextEl() + "cols()), " + std::to_string(std::get<1>(ElementType2Cpp.at(type.getElementType()))) + "}, " + "\"" + std::get<0>(ElementType2Cpp.at(type.getElementType())) + "\", " + "reinterpret_cast<const unsigned char*>(" + cppAccessor + nextEl() + "data()), " + diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Matrix.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Matrix.h index 9f56f2b986f199af4e662e342b5f7dc7040d778b..452ac7b53e5e9d996bc8cbc7ffa41555d7275e65 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Matrix.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Matrix.h @@ -23,17 +23,15 @@ #pragma once -#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> -#include <RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.h> - #include <map> +#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> +#include <RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.h> namespace armarx::aron::codegenerator::cpp::generator { - class Matrix : - public detail::NDArrayGenerator<type::Matrix, Matrix> + class Matrix : public detail::NDArrayGenerator<type::Matrix, Matrix> { public: // constructors @@ -42,10 +40,18 @@ namespace armarx::aron::codegenerator::cpp::generator // virtual implementations std::vector<std::string> getRequiredIncludes() const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getWriteBlock(const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getWriteBlock(const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const final; CppBlockPtr getEqualsBlock(const std::string&, const std::string&) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/NDArray.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/NDArray.cpp index 4198f74d41f91afe08a82270ba9eb4858f802cd6..4b1cba9cfbd143df8e98fd3e25cd98023e56af51 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/NDArray.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/NDArray.cpp @@ -26,7 +26,6 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { // constructors @@ -35,33 +34,47 @@ namespace armarx::aron::codegenerator::cpp::generator "NDArray", "NDArray", simox::meta::get_type_name<data::dto::NDArray>(), - simox::meta::get_type_name<type::dto::NDArray>(), n) + simox::meta::get_type_name<type::dto::NDArray>(), + n) { } - CppBlockPtr NDArray::getResetSoftBlock(const std::string& cppAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + NDArray::getCtorInitializers(const std::string&) const + { + return {{}, false}; + } + + CppBlockPtr + NDArray::getResetSoftBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine(cppAccessor + " = " + this->getFullInstantiatedCppTypename() + "();"); + block_if_data->addLine(cppAccessor + " = " + this->getFullInstantiatedCppTypename() + + "();"); return resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } - CppBlockPtr NDArray::getWriteTypeBlock(const std::string&, const std::string&, const Path& p, std::string&) const + CppBlockPtr + NDArray::getWriteTypeBlock(const std::string&, + const std::string&, + const Path& p, + std::string&) const { CppBlockPtr b = std::make_shared<CppBlock>(); return b; } - CppBlockPtr NDArray::getWriteBlock(const std::string& cppAccessor, const Path& p, std::string&) const + CppBlockPtr + NDArray::getWriteBlock(const std::string& cppAccessor, const Path& p, std::string&) const { CppBlockPtr b = std::make_shared<CppBlock>(); return b; } - CppBlockPtr NDArray::getReadBlock(const std::string& cppAccessor, const std::string&) const + CppBlockPtr + NDArray::getReadBlock(const std::string& cppAccessor, const std::string&) const { CppBlockPtr b = std::make_shared<CppBlock>(); return b; } -} - +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/NDArray.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/NDArray.h index 3b1d3d2ccc5129bfdbb53444d561b896a91d87f0..20ca2f31f34f3c1105f75785feaa3b388729e73a 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/NDArray.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/NDArray.h @@ -23,16 +23,14 @@ #pragma once -#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> -#include <RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.h> - #include <string> +#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> +#include <RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.h> namespace armarx::aron::codegenerator::cpp::generator { - class NDArray : - public detail::NDArrayGenerator<type::NDArray, NDArray> + class NDArray : public detail::NDArrayGenerator<type::NDArray, NDArray> { public: @@ -41,9 +39,17 @@ namespace armarx::aron::codegenerator::cpp::generator virtual ~NDArray() = default; // virtual implementations + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getWriteBlock(const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getWriteBlock(const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/PointCloud.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/PointCloud.cpp index 1fe84d735e74cd59f63801c0096ac19cbe1e9f9f..66b3c77d68c4cdf598b4712819c618249e49cdb8 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/PointCloud.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/PointCloud.cpp @@ -26,20 +26,31 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { - const std::map<type::pointcloud::VoxelType, std::tuple<std::string, int, std::string>> VoxelType2Cpp = - { - // see http://docs.ros.org/en/groovy/api/pcl/html/point__types_8hpp_source.html - {type::pointcloud::VoxelType::POINT_XYZ, {"pcl::PointXYZ", 16, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZ"}}, - {type::pointcloud::VoxelType::POINT_XYZI, {"pcl::PointXYZI", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZI"}}, - {type::pointcloud::VoxelType::POINT_XYZL, {"pcl::PointXYZL", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZL"}}, - {type::pointcloud::VoxelType::POINT_XYZRGB, {"pcl::PointXYZRGB", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZRGB"}}, - {type::pointcloud::VoxelType::POINT_XYZRGBL, {"pcl::PointXYZRGBL", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZRGBL"}}, - {type::pointcloud::VoxelType::POINT_XYZRGBA, {"pcl::PointXYZRGBA", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZRGBA"}}, - {type::pointcloud::VoxelType::POINT_XYZHSV, {"pcl::PointXYZHSV", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZHSV"}} - }; + const std::map<type::pointcloud::VoxelType, std::tuple<std::string, int, std::string>> + VoxelType2Cpp = { + // see http://docs.ros.org/en/groovy/api/pcl/html/point__types_8hpp_source.html + {type::pointcloud::VoxelType::POINT_XYZ, + {"pcl::PointXYZ", 16, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZ"}}, + {type::pointcloud::VoxelType::POINT_XYZI, + {"pcl::PointXYZI", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZI"}}, + {type::pointcloud::VoxelType::POINT_XYZL, + {"pcl::PointXYZL", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZL"}}, + {type::pointcloud::VoxelType::POINT_XYZRGB, + {"pcl::PointXYZRGB", 32, "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZRGB"}}, + {type::pointcloud::VoxelType::POINT_XYZRGBL, + {"pcl::PointXYZRGBL", + 32, + "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZRGBL"}}, + {type::pointcloud::VoxelType::POINT_XYZRGBA, + {"pcl::PointXYZRGBA", + 32, + "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZRGBA"}}, + {type::pointcloud::VoxelType::POINT_XYZHSV, + {"pcl::PointXYZHSV", + 32, + "::armarx::aron::type::pointcloud::VoxelType::POINT_XYZHSV"}}}; // constructors PointCloud::PointCloud(const type::PointCloud& n) : @@ -52,45 +63,72 @@ namespace armarx::aron::codegenerator::cpp::generator { } - std::vector<std::string> PointCloud::getRequiredIncludes() const + std::vector<std::string> + PointCloud::getRequiredIncludes() const { return {"<pcl/point_cloud.h>", "<pcl/point_types.h>"}; } - CppBlockPtr PointCloud::getResetSoftBlock(const std::string& cppAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + PointCloud::getCtorInitializers(const std::string&) const + { + // TODO + return {{}, false}; + } + + CppBlockPtr + PointCloud::getResetSoftBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine(cppAccessor + " = " + getFullInstantiatedCppTypenameGenerator() + "(" + cppAccessor + nextEl() + "width, " + cppAccessor + nextEl() + "height);"); + block_if_data->addLine(cppAccessor + " = " + getFullInstantiatedCppTypenameGenerator() + + "(" + cppAccessor + nextEl() + "width, " + cppAccessor + nextEl() + + "height);"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } - CppBlockPtr PointCloud::getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const + CppBlockPtr + PointCloud::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writePointCloud(" + std::get<2>(VoxelType2Cpp.at(type.getVoxelType())) + ", " + - conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + cppAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writePointCloud(" + + std::get<2>(VoxelType2Cpp.at(type.getVoxelType())) + ", " + "\"" + + type.getDefaultValue() + "\", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + cppAccessor); return b; } - CppBlockPtr PointCloud::getWriteBlock(const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const + CppBlockPtr + PointCloud::getWriteBlock(const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - block_if_data->addLine(variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeNDArray({" + cppAccessor + nextEl() + "width, " + cppAccessor + nextEl() + "height, " + std::to_string(std::get<1>(VoxelType2Cpp.at(type.getVoxelType()))) + "}, "+ - "\"" + std::get<0>(VoxelType2Cpp.at(type.getVoxelType())) + "\", "+ - "reinterpret_cast<const unsigned char*>(" + cppAccessor + nextEl() + "points.data()), "+ - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {" + simox::alg::join(p.getPath(), ", ") + "})); // of " + cppAccessor); + block_if_data->addLine( + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeNDArray({" + cppAccessor + + nextEl() + "width, " + cppAccessor + nextEl() + "height, " + + std::to_string(std::get<1>(VoxelType2Cpp.at(type.getVoxelType()))) + "}, " + "\"" + + std::get<0>(VoxelType2Cpp.at(type.getVoxelType())) + "\", " + + "reinterpret_cast<const unsigned char*>(" + cppAccessor + nextEl() + + "points.data()), " + "armarx::aron::Path(" + ARON_PATH_ACCESSOR + ", {" + + simox::alg::join(p.getPath(), ", ") + "})); // of " + cppAccessor); return resolveMaybeWriteBlock(block_if_data, cppAccessor); } - CppBlockPtr PointCloud::getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const + CppBlockPtr + PointCloud::getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); @@ -101,33 +139,48 @@ namespace armarx::aron::codegenerator::cpp::generator block_if_data->addLine("std::string " + type + ";"); block_if_data->addLine("std::vector<int> " + dims + ";"); block_if_data->addLine("std::vector<unsigned char> " + data + ";"); - block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readNDArray("+variantAccessor+", "+dims+", "+type+", "+data+"); // of " + cppAccessor); - - block_if_data->addLine("ARMARX_CHECK_AND_THROW(" + dims + ".size() == 3, ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, \"Received wrong dimensions for member '"+cppAccessor+"'.\"));"); - block_if_data->addLine("ARMARX_CHECK_AND_THROW(" + type + " == \"" + std::get<0>(VoxelType2Cpp.at(this->type.getVoxelType())) + "\", ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, \"Received wrong type for member '"+cppAccessor+"'.\"));"); + block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readNDArray(" + variantAccessor + + ", " + dims + ", " + type + ", " + data + "); // of " + cppAccessor); + + block_if_data->addLine( + "ARMARX_CHECK_AND_THROW(" + dims + + ".size() == 3, ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, \"Received " + "wrong dimensions for member '" + + cppAccessor + "'.\"));"); + block_if_data->addLine("ARMARX_CHECK_AND_THROW(" + type + " == \"" + + std::get<0>(VoxelType2Cpp.at(this->type.getVoxelType())) + + "\", ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, " + "\"Received wrong type for member '" + + cppAccessor + "'.\"));"); // assign is not availablePCL for PCL 1.8 // block_if_data->addLine(cppAccessor + nextEl() + "assign(" + dims + "[0], " + dims + "[1], " + std::get<0>(VoxelType2Cpp.at(this->type.getVoxelType())) + "());"); block_if_data->addLine(cppAccessor + nextEl() + "clear();"); // resize(width, height , value) is not available either // block_if_data->addLine(cppAccessor + nextEl() + "resize(" + dims + "[0], " + dims + "[1], " + std::get<0>(VoxelType2Cpp.at(this->type.getVoxelType())) + "()));"); - block_if_data->addLine(cppAccessor + nextEl() + "resize(" + dims + "[0] * " + dims + "[1]);"); + block_if_data->addLine(cppAccessor + nextEl() + "resize(" + dims + "[0] * " + dims + + "[1]);"); block_if_data->addLine(cppAccessor + nextEl() + "width = " + dims + "[0];"); block_if_data->addLine(cppAccessor + nextEl() + "height = " + dims + "[1];"); - block_if_data->addLine("std::memcpy(reinterpret_cast<unsigned char*>(" + cppAccessor + nextEl() + "points.data()), "+data+".data(), "+data+".size());"); + block_if_data->addLine("std::memcpy(reinterpret_cast<unsigned char*>(" + cppAccessor + + nextEl() + "points.data()), " + data + ".data(), " + data + + ".size());"); return resolveMaybeReadBlock(block_if_data, cppAccessor, variantAccessor); } - CppBlockPtr PointCloud::getEqualsBlock(const std::string& accessor, const std::string& otherInstanceAccessor) const + CppBlockPtr + PointCloud::getEqualsBlock(const std::string& accessor, + const std::string& otherInstanceAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine("if (" + accessor + nextEl() + "width != " + otherInstanceAccessor + nextEl() + "width || " + accessor + nextEl() + "height != " + otherInstanceAccessor + nextEl() + "height)"); + block_if_data->addLine("if (" + accessor + nextEl() + "width != " + otherInstanceAccessor + + nextEl() + "width || " + accessor + nextEl() + + "height != " + otherInstanceAccessor + nextEl() + "height)"); block_if_data->addLineAsBlock("return false;"); //block_if_data->addLine("if (" + accessor + nextEl() + "points != " + otherInstanceAccessor + nextEl() + "points)"); //block_if_data->addLine("\t return false;"); return resolveMaybeEqualsBlock(block_if_data, accessor, otherInstanceAccessor); } -} - +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/PointCloud.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/PointCloud.h index 9edc5a318356220a01b67c07d2f7a0e1d5acd49e..8514f807df630b16e8277a327b03096cd8839df3 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/PointCloud.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/PointCloud.h @@ -23,16 +23,14 @@ #pragma once -#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> -#include <RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.h> - #include <map> +#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> +#include <RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.h> namespace armarx::aron::codegenerator::cpp::generator { - class PointCloud : - public detail::NDArrayGenerator<type::PointCloud, PointCloud> + class PointCloud : public detail::NDArrayGenerator<type::PointCloud, PointCloud> { public: // constructors @@ -41,10 +39,18 @@ namespace armarx::aron::codegenerator::cpp::generator // virtual implementations std::vector<std::string> getRequiredIncludes() const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getWriteBlock(const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getWriteBlock(const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const final; CppBlockPtr getEqualsBlock(const std::string& cppAccessor, const std::string&) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Quaternion.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Quaternion.cpp index 32dae76ef8e2678e23e5fbec75133d5b4416f4ed..5e5632e45ca43b52befe4eea73703ceee340a2ac 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Quaternion.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Quaternion.cpp @@ -26,14 +26,14 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { - const std::map<type::quaternion::ElementType, std::tuple<std::string, int, std::string>> ElementType2Cpp = - { - {type::quaternion::ElementType::FLOAT32, {"float", 4, "::armarx::aron::type::quaternion::ElementType::FLOAT32"}}, - {type::quaternion::ElementType::FLOAT64, {"double", 8, "::armarx::aron::type::quaternion::ElementType::FLOAT64"}} - }; + const std::map<type::quaternion::ElementType, std::tuple<std::string, int, std::string>> + ElementType2Cpp = { + {type::quaternion::ElementType::FLOAT32, + {"float", 4, "::armarx::aron::type::quaternion::ElementType::FLOAT32"}}, + {type::quaternion::ElementType::FLOAT64, + {"double", 8, "::armarx::aron::type::quaternion::ElementType::FLOAT64"}}}; // constructors Quaternion::Quaternion(const type::Quaternion& n) : @@ -46,45 +46,85 @@ namespace armarx::aron::codegenerator::cpp::generator { } - std::vector<std::string> Quaternion::getRequiredIncludes() const + std::vector<std::string> + Quaternion::getRequiredIncludes() const { return {"<Eigen/Core>", "<Eigen/Geometry>"}; } - CppBlockPtr Quaternion::getResetSoftBlock(const std::string& cppAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Quaternion::getCtorInitializers(const std::string& name) const + { + if (type.getDefaultValue() == aron::type::quaternion::default_value::DEFAULT) + { + return {{}, false}; + } + if (type.getDefaultValue() == aron::type::quaternion::default_value::ZEROS) + { + return {{{name, getInstantiatedCppTypename() + "(0, 0, 0, 0)"}}, true}; + } + if (type.getDefaultValue() == aron::type::quaternion::default_value::ONES) + { + return {{{name, getInstantiatedCppTypename() + "(1, 1, 1, 1)"}}, true}; + } + else + { + // try to parse num. We ensure from typereader that defaultValue is valid number + return {{{name, getInstantiatedCppTypename() + "(" + type.getDefaultValue() + ")"}}, + true}; + } + } + + CppBlockPtr + Quaternion::getResetSoftBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + nextEl() + "setIdentity();"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } - CppBlockPtr Quaternion::getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const + CppBlockPtr + Quaternion::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeQuaternion(" + std::get<2>(ElementType2Cpp.at(type.getElementType())) + ", " + - conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + cppAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeQuaternion(" + + std::get<2>(ElementType2Cpp.at(type.getElementType())) + ", " + "\"" + + type.getDefaultValue() + "\", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + cppAccessor); return b; } - CppBlockPtr Quaternion::getWriteBlock(const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const + CppBlockPtr + Quaternion::getWriteBlock(const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - block_if_data->addLine(variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeNDArray({1, 4, " + std::to_string(std::get<1>(ElementType2Cpp.at(type.getElementType()))) + "}, "+ - "\"" + std::get<0>(ElementType2Cpp.at(type.getElementType())) + "\", "+ - "reinterpret_cast<const unsigned char*>(" + cppAccessor + nextEl() + "coeffs().data()), "+ - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {" + simox::alg::join(p.getPath(), ", ") + "})); // of " + cppAccessor); + block_if_data->addLine( + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeNDArray({1, 4, " + + std::to_string(std::get<1>(ElementType2Cpp.at(type.getElementType()))) + "}, " + "\"" + + std::get<0>(ElementType2Cpp.at(type.getElementType())) + "\", " + + "reinterpret_cast<const unsigned char*>(" + cppAccessor + nextEl() + + "coeffs().data()), " + "armarx::aron::Path(" + ARON_PATH_ACCESSOR + ", {" + + simox::alg::join(p.getPath(), ", ") + "})); // of " + cppAccessor); return resolveMaybeWriteBlock(block_if_data, cppAccessor); } - CppBlockPtr Quaternion::getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const + CppBlockPtr + Quaternion::getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(cppAccessor); @@ -95,16 +135,22 @@ namespace armarx::aron::codegenerator::cpp::generator block_if_data->addLine("std::string " + type + ";"); block_if_data->addLine("std::vector<int> " + dims + ";"); block_if_data->addLine("std::vector<unsigned char> " + data + ";"); - block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readNDArray("+variantAccessor+", "+dims+", "+type+", "+data+"); // of " + cppAccessor); - block_if_data->addLine("std::memcpy(reinterpret_cast<unsigned char*>(" + cppAccessor + nextEl() + "coeffs().data()), "+data+".data(), "+data+".size());"); + block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readNDArray(" + variantAccessor + + ", " + dims + ", " + type + ", " + data + "); // of " + cppAccessor); + block_if_data->addLine("std::memcpy(reinterpret_cast<unsigned char*>(" + cppAccessor + + nextEl() + "coeffs().data()), " + data + ".data(), " + data + + ".size());"); return resolveMaybeReadBlock(block_if_data, cppAccessor, variantAccessor); } - CppBlockPtr Quaternion::getEqualsBlock(const std::string& accessor, const std::string& otherInstanceAccessor) const + CppBlockPtr + Quaternion::getEqualsBlock(const std::string& accessor, + const std::string& otherInstanceAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine("if (not (" + accessor + nextEl() + "isApprox(" + otherInstanceAccessor + ")))"); + block_if_data->addLine("if (not (" + accessor + nextEl() + "isApprox(" + + otherInstanceAccessor + ")))"); block_if_data->addLineAsBlock("return false;"); return resolveMaybeEqualsBlock(block_if_data, accessor, otherInstanceAccessor); } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Quaternion.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Quaternion.h index f744681595d1aea76b8e5b29224313e41b056baa..4fd41b7dbd382c0231337ea30ba661f9b1e9eab3 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Quaternion.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/ndarray/Quaternion.h @@ -24,16 +24,14 @@ #pragma once -#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> -#include <RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.h> - #include <map> +#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/NDArrayGenerator.h> +#include <RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.h> namespace armarx::aron::codegenerator::cpp::generator { - class Quaternion : - public detail::NDArrayGenerator<type::Quaternion, Quaternion> + class Quaternion : public detail::NDArrayGenerator<type::Quaternion, Quaternion> { public: // constructors @@ -42,10 +40,18 @@ namespace armarx::aron::codegenerator::cpp::generator // virtual implementations std::vector<std::string> getRequiredIncludes() const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getWriteBlock(const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getWriteBlock(const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const final; CppBlockPtr getEqualsBlock(const std::string&, const std::string&) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Bool.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Bool.cpp index 7dcadbb33ae84d70a180e89763ca37a634946268..0dad3b9e12a65c73d41d390db1029e50c70f8a90 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Bool.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Bool.cpp @@ -25,7 +25,6 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { /* constructors */ @@ -34,33 +33,49 @@ namespace armarx::aron::codegenerator::cpp::generator "bool", "bool", simox::meta::get_type_name<data::dto::AronBool>(), - simox::meta::get_type_name<type::dto::AronBool>(), e) + simox::meta::get_type_name<type::dto::AronBool>(), + e) { } /* virtual implementations */ - CppBlockPtr Bool::getWriteTypeBlock(const std::string& typeAccessor, const std::string& accessor, const Path& p, std::string& variantAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Bool::getCtorInitializers(const std::string& name) const + { + return {{{name, std::to_string(type.getDefaultValue())}}, true}; + } + + CppBlockPtr + Bool::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& accessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(accessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeBool(" + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + typeAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeBool(" + + std::to_string(type.getDefaultValue()) + ", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + typeAccessor); return b; } - CppBlockPtr Bool::getResetHardBlock(const std::string& cppAccessor) const + CppBlockPtr + Bool::getResetHardBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = false;"); return resolveMaybeResetHardBlock(block_if_data, cppAccessor); } - CppBlockPtr Bool::getResetSoftBlock(const std::string& cppAccessor) const + CppBlockPtr + Bool::getResetSoftBlock(const std::string& cppAccessor) const { auto block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = false;"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Bool.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Bool.h index 381adec7bc759c7a20aedd54229dd499253110d1..f218b9938bbc57d3595542c7915e021ebc386de7 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Bool.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Bool.h @@ -23,24 +23,29 @@ #pragma once -#include "../detail/PrimitiveGenerator.h" - #include <RobotAPI/libraries/aron/core/type/variant/primitive/Bool.h> +#include "../detail/PrimitiveGenerator.h" namespace armarx::aron::codegenerator::cpp::generator { - class Bool : - public detail::PrimitiveGenerator<type::Bool, Bool> + class Bool : public detail::PrimitiveGenerator<type::Bool, Bool> { public: + static const constexpr bool DEFAULT_DEFAULT = false; + /* constructors */ Bool(const type::Bool& e); virtual ~Bool() = default; /* virtual implementations */ - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Double.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Double.cpp index 735f3ad9dc4efdf0f00a34093671644aebb0eb3f..149050164efeae441132e2e2608f57321d3ef3e8 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Double.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Double.cpp @@ -25,7 +25,6 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { /* constructors */ @@ -40,28 +39,43 @@ namespace armarx::aron::codegenerator::cpp::generator } /* virtual implementations */ - CppBlockPtr Double::getWriteTypeBlock(const std::string& typeAccessor, const std::string& accessor, const Path& p, std::string& variantAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Double::getCtorInitializers(const std::string& name) const + { + return {{{name, std::to_string(type.getDefaultValue())}}, true}; + } + + CppBlockPtr + Double::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& accessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(accessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeDouble(" + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + typeAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeDouble(" + + std::to_string(type.getDefaultValue()) + ", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + typeAccessor); return b; } - CppBlockPtr Double::getResetHardBlock(const std::string& cppAccessor) const + CppBlockPtr + Double::getResetHardBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = 0.0;"); return resolveMaybeResetHardBlock(block_if_data, cppAccessor); } - CppBlockPtr Double::getResetSoftBlock(const std::string& cppAccessor) const + CppBlockPtr + Double::getResetSoftBlock(const std::string& cppAccessor) const { auto block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = 0.0;"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Double.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Double.h index b9a96a077e225aad5b0871882e86e20f85fb3685..2ff98312264d0cfbd611544c13d3cfedddb3e884 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Double.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Double.h @@ -26,11 +26,9 @@ #include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/PrimitiveGenerator.h> #include <RobotAPI/libraries/aron/core/type/variant/primitive/Double.h> - namespace armarx::aron::codegenerator::cpp::generator { - class Double : - public detail::PrimitiveGenerator<type::Double, Double> + class Double : public detail::PrimitiveGenerator<type::Double, Double> { public: /* constructors */ @@ -38,8 +36,13 @@ namespace armarx::aron::codegenerator::cpp::generator virtual ~Double() = default; /* virtual implementations */ - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Float.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Float.cpp index d3d27ea6c34713b3d81074c1ab64e37ed696d69c..76c71a6431ca9368811c11ed516d6486c636a9ee 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Float.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Float.cpp @@ -25,7 +25,6 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { /* constructors */ @@ -40,28 +39,43 @@ namespace armarx::aron::codegenerator::cpp::generator } /* virtual implementations */ - CppBlockPtr Float::getWriteTypeBlock(const std::string& typeAccessor, const std::string& accessor, const Path& p, std::string& variantAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Float::getCtorInitializers(const std::string& name) const + { + return {{{name, std::to_string(type.getDefaultValue())}}, true}; + } + + CppBlockPtr + Float::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& accessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(accessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeFloat(" + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + typeAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeFloat(" + + std::to_string(type.getDefaultValue()) + ", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + typeAccessor); return b; } - CppBlockPtr Float::getResetHardBlock(const std::string& cppAccessor) const + CppBlockPtr + Float::getResetHardBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = 0.0f;"); return resolveMaybeResetHardBlock(block_if_data, cppAccessor); } - CppBlockPtr Float::getResetSoftBlock(const std::string& cppAccessor) const + CppBlockPtr + Float::getResetSoftBlock(const std::string& cppAccessor) const { auto block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = 0.0f;"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Float.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Float.h index f1c88c502f92b7d86afc7668eda0710f0f3351b7..7cb65fc6d2712107ea2c932d189f96532d5c04f9 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Float.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Float.h @@ -26,11 +26,9 @@ #include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/PrimitiveGenerator.h> #include <RobotAPI/libraries/aron/core/type/variant/primitive/Float.h> - namespace armarx::aron::codegenerator::cpp::generator { - class Float : - public detail::PrimitiveGenerator<type::Float, Float> + class Float : public detail::PrimitiveGenerator<type::Float, Float> { public: /* constructors */ @@ -38,8 +36,13 @@ namespace armarx::aron::codegenerator::cpp::generator virtual ~Float() = default; /* virtual implementations */ - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Int.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Int.cpp index 7a976bd83fffa4ad52bec05c2a5392bbf7400798..635cab4dee34bfd7f26232e43c80a0d0b98c73c1 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Int.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Int.cpp @@ -25,43 +25,56 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { /* constructors */ Int::Int(const type::Int& e) : - detail::PrimitiveGenerator<type::Int, Int>( - "int", - "int", - simox::meta::get_type_name<data::dto::AronInt>(), - simox::meta::get_type_name<type::dto::AronInt>(), - e) + detail::PrimitiveGenerator<type::Int, Int>("int", + "int", + simox::meta::get_type_name<data::dto::AronInt>(), + simox::meta::get_type_name<type::dto::AronInt>(), + e) { } /* virtual implementations */ - CppBlockPtr Int::getWriteTypeBlock(const std::string& typeAccessor, const std::string& accessor, const Path& p, std::string& variantAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Int::getCtorInitializers(const std::string& name) const + { + return {{{name, std::to_string(type.getDefaultValue())}}, true}; + } + + CppBlockPtr + Int::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& accessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(accessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeInt(" + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + typeAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeInt(" + + std::to_string(type.getDefaultValue()) + ", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + typeAccessor); return b; } - CppBlockPtr Int::getResetHardBlock(const std::string& cppAccessor) const + CppBlockPtr + Int::getResetHardBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = 0;"); return resolveMaybeResetHardBlock(block_if_data, cppAccessor); } - CppBlockPtr Int::getResetSoftBlock(const std::string& cppAccessor) const + CppBlockPtr + Int::getResetSoftBlock(const std::string& cppAccessor) const { auto block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = 0;"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Int.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Int.h index b21abee9cef1850a1d55da0369a530b65585c210..d552f34ea914baba72f3a7c886c9ebce99d0658b 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Int.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Int.h @@ -26,11 +26,9 @@ #include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/PrimitiveGenerator.h> #include <RobotAPI/libraries/aron/core/type/variant/primitive/Int.h> - namespace armarx::aron::codegenerator::cpp::generator { - class Int : - public detail::PrimitiveGenerator<type::Int, Int> + class Int : public detail::PrimitiveGenerator<type::Int, Int> { public: /* constructors */ @@ -38,8 +36,13 @@ namespace armarx::aron::codegenerator::cpp::generator virtual ~Int() = default; /* virtual implementations */ - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Long.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Long.cpp index fe6cd5e87f6f3db26873c351987f91d86556d27b..9b61ee5f607b3cc1f4816252b40582bfdb92fae8 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Long.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Long.cpp @@ -25,7 +25,6 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { /* constructors */ @@ -40,28 +39,43 @@ namespace armarx::aron::codegenerator::cpp::generator } /* virtual implementations */ - CppBlockPtr Long::getWriteTypeBlock(const std::string& typeAccessor, const std::string& accessor, const Path& p, std::string& variantAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + Long::getCtorInitializers(const std::string& name) const + { + return {{{name, std::to_string(type.getDefaultValue())}}, true}; + } + + CppBlockPtr + Long::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& accessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(accessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeLong(" + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + typeAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeLong(" + + std::to_string(type.getDefaultValue()) + ", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + typeAccessor); return b; } - CppBlockPtr Long::getResetHardBlock(const std::string& cppAccessor) const + CppBlockPtr + Long::getResetHardBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = 0;"); return resolveMaybeResetHardBlock(block_if_data, cppAccessor); } - CppBlockPtr Long::getResetSoftBlock(const std::string& cppAccessor) const + CppBlockPtr + Long::getResetSoftBlock(const std::string& cppAccessor) const { auto block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = 0;"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Long.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Long.h index 09d923e487108a7c2c0927156af77c21fddf79ec..8dd002ecb4680f40660bc6dc39c0583c556cf730 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Long.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/Long.h @@ -26,11 +26,9 @@ #include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/PrimitiveGenerator.h> #include <RobotAPI/libraries/aron/core/type/variant/primitive/Long.h> - namespace armarx::aron::codegenerator::cpp::generator { - class Long : - public detail::PrimitiveGenerator<type::Long, Long> + class Long : public detail::PrimitiveGenerator<type::Long, Long> { public: /* constructors */ @@ -38,8 +36,13 @@ namespace armarx::aron::codegenerator::cpp::generator virtual ~Long() = default; /* virtual implementations */ - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/String.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/String.cpp index d51ee9ed159a5abb82442a5501ffebb3500aad15..e1649b982a053830e7b65e3f763298f9b7c01b61 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/String.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/String.cpp @@ -25,7 +25,6 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { /* constructors */ @@ -40,28 +39,43 @@ namespace armarx::aron::codegenerator::cpp::generator } /* virtual implementations */ - CppBlockPtr String::getWriteTypeBlock(const std::string& typeAccessor, const std::string& accessor, const Path& p, std::string& variantAccessor) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + String::getCtorInitializers(const std::string& name) const + { + return {{{name, "\"" + type.getDefaultValue() + "\""}}, true}; + } + + CppBlockPtr + String::getWriteTypeBlock(const std::string& typeAccessor, + const std::string& accessor, + const Path& p, + std::string& variantAccessor) const { CppBlockPtr b = std::make_shared<CppBlock>(); std::string escaped_accessor = EscapeAccessor(accessor); variantAccessor = ARON_VARIANT_RETURN_ACCESSOR + "_" + escaped_accessor; - b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeString(" + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + - "armarx::aron::Path("+ARON_PATH_ACCESSOR+", {"+simox::alg::join(p.getPath(), ", ")+"})); // of " + typeAccessor); + b->addLine("auto " + variantAccessor + " = " + ARON_WRITER_ACCESSOR + ".writeString(\"" + + type.getDefaultValue() + "\", " + + conversion::Maybe2CppString.at(type.getMaybe()) + ", " + "armarx::aron::Path(" + + ARON_PATH_ACCESSOR + ", {" + simox::alg::join(p.getPath(), ", ") + + "})); // of " + typeAccessor); return b; } - CppBlockPtr String::getResetHardBlock(const std::string& cppAccessor) const + CppBlockPtr + String::getResetHardBlock(const std::string& cppAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = \"\";"); return resolveMaybeResetHardBlock(block_if_data, cppAccessor); } - CppBlockPtr String::getResetSoftBlock(const std::string& cppAccessor) const + CppBlockPtr + String::getResetSoftBlock(const std::string& cppAccessor) const { auto block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine(cppAccessor + " = \"\";"); return this->resolveMaybeResetSoftBlock(block_if_data, cppAccessor); } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/String.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/String.h index fd854ccee807d549fbe1448643eb31a4f069bcc8..628f0af2552d732a5a1e39bd6eefc684030723af 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/String.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/primitive/String.h @@ -26,11 +26,9 @@ #include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/PrimitiveGenerator.h> #include <RobotAPI/libraries/aron/core/type/variant/primitive/String.h> - namespace armarx::aron::codegenerator::cpp::generator { - class String : - public detail::PrimitiveGenerator<type::String, String> + class String : public detail::PrimitiveGenerator<type::String, String> { public: /* constructors */ @@ -38,8 +36,13 @@ namespace armarx::aron::codegenerator::cpp::generator virtual ~String() = default; /* virtual implementations */ - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path& p, std::string& variantAccessor) const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path& p, + std::string& variantAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/IntEnumClass.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/IntEnumClass.cpp index 0cddfd33161dcd0bf5f398fa87f4c0a88ec0a447..ade0f0ef42f57366ab2944014ecb2245eed29587 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/IntEnumClass.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/IntEnumClass.cpp @@ -26,7 +26,6 @@ #include <SimoxUtility/meta/type_name.h> - namespace armarx::aron::codegenerator::cpp::generator { // constructors @@ -40,11 +39,16 @@ namespace armarx::aron::codegenerator::cpp::generator { if (type.getMaybe() != type::Maybe::NONE) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Somehow the maybe flag of a top level int enum declaration is set. This is not valid!", std::to_string((int) type.getMaybe()), type.getPath()); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "Somehow the maybe flag of a top level int enum " + "declaration is set. This is not valid!", + std::to_string((int)type.getMaybe()), + type.getPath()); } } - std::vector<CppFieldPtr> IntEnumClass::getPublicVariableDeclarations(const std::string& className) const + std::vector<CppFieldPtr> + IntEnumClass::getPublicVariableDeclarations(const std::string& className) const { std::vector<CppFieldPtr> fields; std::stringstream enum_to_name; @@ -53,7 +57,11 @@ namespace armarx::aron::codegenerator::cpp::generator std::stringstream value_to_enum; // add legacy typedef - fields.push_back(std::make_shared<CppField>("using", std::string(IMPL_ENUM), simox::alg::to_lower(className) + "_details::Enum", "Legacy typedef of enum")); + fields.push_back( + std::make_shared<CppField>("using", + std::string(IMPL_ENUM), + simox::alg::to_lower(className) + "_details::Enum", + "Legacy typedef of enum")); ARMARX_CHECK(type.getAcceptedValueMap().size() > 0); @@ -64,7 +72,8 @@ namespace armarx::aron::codegenerator::cpp::generator for (const auto& [key, value] : type.getAcceptedValueMap()) { std::string enumKeyWithNamespace = std::string(IMPL_ENUM) + "::" + key; - fields.push_back(std::make_shared<CppField>("static constexpr " + std::string(IMPL_ENUM), key + " = " + enumKeyWithNamespace)); + fields.push_back(std::make_shared<CppField>( + "static constexpr " + std::string(IMPL_ENUM), key + " = " + enumKeyWithNamespace)); enum_to_name << "\t\t{" << enumKeyWithNamespace << ", \"" << key << "\"}," << std::endl; name_to_enum << "\t\t{\"" << key << "\", " << enumKeyWithNamespace << "}," << std::endl; @@ -78,31 +87,56 @@ namespace armarx::aron::codegenerator::cpp::generator enum_to_value << "\t}"; value_to_enum << "\t}"; - fields.push_back(std::make_shared<CppField>("static inline const std::map<" + std::string(IMPL_ENUM) + ", std::string>", "EnumToStringMap", enum_to_name.str(), "Mapping enum values to readable strings")); - fields.push_back(std::make_shared<CppField>("static inline const std::map<std::string, " + std::string(IMPL_ENUM) + ">", "StringToEnumMap", name_to_enum.str(), "Mapping readable strings to enum values")); - fields.push_back(std::make_shared<CppField>("static inline const std::map<" + std::string(IMPL_ENUM) + ", int>", "EnumToValueMap", enum_to_value.str(), "Mapping enum values to a int value")); - fields.push_back(std::make_shared<CppField>("static inline const std::map<int, " + std::string(IMPL_ENUM) + ">", "ValueToEnumMap", value_to_enum.str(), "Mapping int values to a enum")); - - fields.push_back(std::make_shared<CppField>(std::string(IMPL_ENUM), "value", type.getAcceptedValueNames()[0], "The current value of the enum object")); + fields.push_back(std::make_shared<CppField>("static inline const std::map<" + + std::string(IMPL_ENUM) + ", std::string>", + "EnumToStringMap", + enum_to_name.str(), + "Mapping enum values to readable strings")); + fields.push_back(std::make_shared<CppField>("static inline const std::map<std::string, " + + std::string(IMPL_ENUM) + ">", + "StringToEnumMap", + name_to_enum.str(), + "Mapping readable strings to enum values")); + fields.push_back(std::make_shared<CppField>("static inline const std::map<" + + std::string(IMPL_ENUM) + ", int>", + "EnumToValueMap", + enum_to_value.str(), + "Mapping enum values to a int value")); + fields.push_back(std::make_shared<CppField>("static inline const std::map<int, " + + std::string(IMPL_ENUM) + ">", + "ValueToEnumMap", + value_to_enum.str(), + "Mapping int values to a enum")); + + fields.push_back(std::make_shared<CppField>(std::string(IMPL_ENUM), + "value", + type.getAcceptedValueNames()[0], + "The current value of the enum object")); return fields; } - CppBlockPtr IntEnumClass::getResetSoftBlock(const std::string& accessor) const + CppBlockPtr + IntEnumClass::getResetSoftBlock(const std::string& accessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine("value = {};"); return block_if_data; } - CppBlockPtr IntEnumClass::getResetHardBlock(const std::string& accessor) const + CppBlockPtr + IntEnumClass::getResetHardBlock(const std::string& accessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine("value = {};"); return block_if_data; } - CppBlockPtr IntEnumClass::getWriteTypeBlock(const std::string&, const std::string&, const Path& p, std::string&) const + CppBlockPtr + IntEnumClass::getWriteTypeBlock(const std::string&, + const std::string&, + const Path& p, + std::string&) const { static const std::string INT_ENUM_VALUE_MAP = ARON_VARIABLE_PREFIX + "_str2ValueMap"; @@ -113,40 +147,50 @@ namespace armarx::aron::codegenerator::cpp::generator { map_initializer.push_back("{\"" + key + "\", " + std::to_string(value) + "}"); } - b->addLine("std::map<std::string, int> " + INT_ENUM_VALUE_MAP + " = {" + simox::alg::to_string(map_initializer, ", ") + "};"); - b->addLine("return " + ARON_WRITER_ACCESSOR + ".writeIntEnum(\"" + type.getEnumName() + "\", " + - INT_ENUM_VALUE_MAP + ", " + - ARON_MAYBE_TYPE_ACCESSOR + ", " + - ARON_PATH_ACCESSOR + ");"); - return b; - + b->addLine("std::map<std::string, int> " + INT_ENUM_VALUE_MAP + " = {" + + simox::alg::to_string(map_initializer, ", ") + "};"); + b->addLine("return " + ARON_WRITER_ACCESSOR + ".writeIntEnum(\"" + type.getEnumName() + + "\", " + INT_ENUM_VALUE_MAP + ", " + "\"" + type.getDefaultValueName() + "\", " + + ARON_MAYBE_TYPE_ACCESSOR + ", " + ARON_PATH_ACCESSOR + ");"); return b; } - CppBlockPtr IntEnumClass::getWriteBlock(const std::string&, const Path& p, std::string&) const + CppBlockPtr + IntEnumClass::getWriteBlock(const std::string&, const Path& p, std::string&) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine("return " + ARON_WRITER_ACCESSOR + ".writePrimitive(EnumToValueMap.at(value), " + - ARON_PATH_ACCESSOR + "); // of top level enum " + getInstantiatedCppTypename()); + block_if_data->addLine("return " + ARON_WRITER_ACCESSOR + + ".writePrimitive(EnumToValueMap.at(value), " + ARON_PATH_ACCESSOR + + "); // of top level enum " + getInstantiatedCppTypename()); return block_if_data; } - CppBlockPtr IntEnumClass::getReadBlock(const std::string&, const std::string& variantAccessor) const + CppBlockPtr + IntEnumClass::getReadBlock(const std::string&, const std::string& variantAccessor) const { static const std::string INT_ENUM_TMP_VALUE = ARON_VARIABLE_PREFIX + "_tmpValue"; CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine("int " + INT_ENUM_TMP_VALUE + ";"); - block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readPrimitive("+variantAccessor+", "+INT_ENUM_TMP_VALUE+"); // of top level enum " + getInstantiatedCppTypename()); - - block_if_data->addLine("auto valueToEnumMap_iterator = ValueToEnumMap.find("+INT_ENUM_TMP_VALUE+");"); - block_if_data->addLine("ARMARX_CHECK_AND_THROW(valueToEnumMap_iterator != ValueToEnumMap.end(), ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, \"Missing enum for value '\" + std::to_string(" + INT_ENUM_TMP_VALUE + ") + \"' in aron enum '" + getFullClassCppTypename() + "'.\"))"); + block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readPrimitive(" + variantAccessor + + ", " + INT_ENUM_TMP_VALUE + "); // of top level enum " + + getInstantiatedCppTypename()); + + block_if_data->addLine("auto valueToEnumMap_iterator = ValueToEnumMap.find(" + + INT_ENUM_TMP_VALUE + ");"); + block_if_data->addLine( + "ARMARX_CHECK_AND_THROW(valueToEnumMap_iterator != ValueToEnumMap.end(), " + "::armarx::aron::error::AronException(__PRETTY_FUNCTION__, \"Missing enum for value " + "'\" + std::to_string(" + + INT_ENUM_TMP_VALUE + ") + \"' in aron enum '" + getFullClassCppTypename() + "'.\"))"); block_if_data->addLine("value = valueToEnumMap_iterator->second;"); return block_if_data; } - CppBlockPtr IntEnumClass::getEqualsBlock(const std::string& accessor, const std::string& otherInstanceAccessor) const + CppBlockPtr + IntEnumClass::getEqualsBlock(const std::string& accessor, + const std::string& otherInstanceAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); block_if_data->addLine("if (not (value == " + otherInstanceAccessor + ".value))"); @@ -154,7 +198,6 @@ namespace armarx::aron::codegenerator::cpp::generator return block_if_data; } - /*CppCtorPtr IntEnumClass::toCopyCtor(const std::string& name) const { CppCtorPtr c = std::make_shared<CppCtor>(name + "(const " + getFullInstantiatedCppTypename() + "& i)"); @@ -164,7 +207,8 @@ namespace armarx::aron::codegenerator::cpp::generator return c; }*/ - CppCtorPtr IntEnumClass::toEnumCtor(const std::string& name) const + CppCtorPtr + IntEnumClass::toEnumCtor(const std::string& name) const { CppCtorPtr c = std::make_shared<CppCtor>(name + "(const " + std::string(IMPL_ENUM) + " e)"); std::vector<std::pair<std::string, std::string>> initList = {{"value", "e"}}; @@ -173,7 +217,8 @@ namespace armarx::aron::codegenerator::cpp::generator return c; } - std::vector<CppEnumFieldPtr> IntEnumClass::toEnumFields() const + std::vector<CppEnumFieldPtr> + IntEnumClass::toEnumFields() const { std::vector<CppEnumFieldPtr> e; for (const auto& [key, value] : type.getAcceptedValueMap()) @@ -183,7 +228,8 @@ namespace armarx::aron::codegenerator::cpp::generator return e; } - CppMethodPtr IntEnumClass::toIntMethod() const + CppMethodPtr + IntEnumClass::toIntMethod() const { std::stringstream doc; doc << "@brief int() - Converts the internally stored value to int representation \n"; @@ -196,13 +242,17 @@ namespace armarx::aron::codegenerator::cpp::generator return m; } - CppMethodPtr IntEnumClass::toCopyAssignmentMethod() const + CppMethodPtr + IntEnumClass::toCopyAssignmentMethod() const { std::stringstream doc; doc << "@brief operator=() - Assignment operator for copy \n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod(getFullInstantiatedCppTypename() + "& operator=(const " + getFullInstantiatedCppTypename() + "& c)", doc.str())); + CppMethodPtr m = + CppMethodPtr(new CppMethod(getFullInstantiatedCppTypename() + "& operator=(const " + + getFullInstantiatedCppTypename() + "& c)", + doc.str())); CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("value = c.value;"); b->addLine("return *this;"); @@ -210,13 +260,16 @@ namespace armarx::aron::codegenerator::cpp::generator return m; } - CppMethodPtr IntEnumClass::toEnumAssignmentMethod() const + CppMethodPtr + IntEnumClass::toEnumAssignmentMethod() const { std::stringstream doc; doc << "@brief operator=() - Assignment operator for the internally defined enum \n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod(getFullInstantiatedCppTypename() + "& operator=(" + std::string(IMPL_ENUM) + " v)", doc.str())); + CppMethodPtr m = CppMethodPtr(new CppMethod( + getFullInstantiatedCppTypename() + "& operator=(" + std::string(IMPL_ENUM) + " v)", + doc.str())); CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("value = v;"); b->addLine("return *this;"); @@ -224,17 +277,20 @@ namespace armarx::aron::codegenerator::cpp::generator return m; } - CppMethodPtr IntEnumClass::toIntAssignmentMethod() const + CppMethodPtr + IntEnumClass::toIntAssignmentMethod() const { std::stringstream doc; doc << "@brief operator=() - Assignment operator for the internally defined enum \n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod(getFullInstantiatedCppTypename() + "& operator=(int v)", doc.str())); + CppMethodPtr m = CppMethodPtr( + new CppMethod(getFullInstantiatedCppTypename() + "& operator=(int v)", doc.str())); CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("if (auto it = ValueToEnumMap.find(v); it == ValueToEnumMap.end())"); CppBlockPtr b2 = std::make_shared<CppBlock>(); - b2->addLine("throw armarx::LocalException(\"The input int is not valid. Could net set the enum to value '\" + std::to_string(v) + \"'\");"); + b2->addLine("throw armarx::LocalException(\"The input int is not valid. Could net set the " + "enum to value '\" + std::to_string(v) + \"'\");"); b->addBlock(b2); b->addLine("else"); CppBlockPtr b3 = std::make_shared<CppBlock>(); @@ -245,7 +301,8 @@ namespace armarx::aron::codegenerator::cpp::generator return m; } - CppMethodPtr IntEnumClass::toToStringMethod() const + CppMethodPtr + IntEnumClass::toToStringMethod() const { std::stringstream doc; doc << "@brief toString() - Converts the internally stored value to string \n"; @@ -258,17 +315,21 @@ namespace armarx::aron::codegenerator::cpp::generator return m; } - CppMethodPtr IntEnumClass::toFromStringMethod() const + CppMethodPtr + IntEnumClass::toFromStringMethod() const { std::stringstream doc; - doc << "@brief fromString() - sets the internally stored value to the corrsponding enum of the input str \n"; + doc << "@brief fromString() - sets the internally stored value to the corrsponding enum of " + "the input str \n"; doc << "@return - nothing"; - CppMethodPtr m = CppMethodPtr(new CppMethod("void fromString(const std::string& str)", doc.str())); + CppMethodPtr m = + CppMethodPtr(new CppMethod("void fromString(const std::string& str)", doc.str())); CppBlockPtr b = std::make_shared<CppBlock>(); b->addLine("if (auto it = StringToEnumMap.find(str); it == StringToEnumMap.end())"); CppBlockPtr b2 = std::make_shared<CppBlock>(); - b2->addLine("throw armarx::LocalException(\"The input name is not valid. Could net set the enum to value '\" + str + \"'\");"); + b2->addLine("throw armarx::LocalException(\"The input name is not valid. Could net set the " + "enum to value '\" + str + \"'\");"); b->addBlock(b2); b->addLine("else"); CppBlockPtr b3 = std::make_shared<CppBlock>(); @@ -278,4 +339,4 @@ namespace armarx::aron::codegenerator::cpp::generator m->setBlock(b); return m; } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/IntEnumClass.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/IntEnumClass.h index fb5e22671ba678ea69072e7b97fee54dbdd395e9..555f1e48be7600da97ec828fbff4e07c77333df2 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/IntEnumClass.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/IntEnumClass.h @@ -23,17 +23,15 @@ #pragma once -#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/SpecializedGenerator.h> -#include <RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.h> - #include <map> -#include <utility> // std::pair +#include <utility> // std::pair +#include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/SpecializedGenerator.h> +#include <RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.h> namespace armarx::aron::codegenerator::cpp::generator { - class IntEnumClass : - public detail::SpecializedGeneratorBase<type::IntEnum, IntEnumClass> + class IntEnumClass : public detail::SpecializedGeneratorBase<type::IntEnum, IntEnumClass> { public: // constructors @@ -45,9 +43,15 @@ namespace armarx::aron::codegenerator::cpp::generator CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getWriteBlock(const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getReadBlock(const std::string& cppAccessor, const std::string& variantAccessor) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getWriteBlock(const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr getReadBlock(const std::string& cppAccessor, + const std::string& variantAccessor) const final; CppBlockPtr getEqualsBlock(const std::string&, const std::string&) const final; // TODO: Move some of those methods to upper class for enums (if we want to support multiple enums) @@ -66,4 +70,4 @@ namespace armarx::aron::codegenerator::cpp::generator static const std::map<std::string, std::pair<std::string, int>> ACCEPTED_TYPES; static constexpr const char* IMPL_ENUM = "ImplEnum"; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/ObjectClass.cpp b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/ObjectClass.cpp index 605c7b8655db3accb2dd1999d7c62e1cfc48730e..6bfc0100f0738f06ea16052a666893c774f19868 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/ObjectClass.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/ObjectClass.cpp @@ -24,9 +24,8 @@ // Header #include "ObjectClass.h" -#include <SimoxUtility/meta/type_name.h> #include <SimoxUtility/algorithm/vector.hpp> - +#include <SimoxUtility/meta/type_name.h> namespace armarx::aron::codegenerator::cpp::generator { @@ -36,27 +35,54 @@ namespace armarx::aron::codegenerator::cpp::generator e.getObjectNameWithTemplateInstantiations(), // should be similar to the object name e.getObjectNameWithTemplates(), simox::meta::get_type_name<data::dto::Dict>(), - simox::meta::get_type_name<type::dto::AronObject>(), e) + simox::meta::get_type_name<type::dto::AronObject>(), + e) { if (type.getMaybe() != type::Maybe::NONE) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Somehow the maybe flag of a top level object declaration is set. This is not valid!", std::to_string((int) type.getMaybe()) + " aka " + type::defaultconversion::string::Maybe2String.at(type.getMaybe()), type.getPath()); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, + "Somehow the maybe flag of a top level object declaration is set. This is not " + "valid!", + std::to_string((int)type.getMaybe()) + " aka " + + type::defaultconversion::string::Maybe2String.at(type.getMaybe()), + type.getPath()); + } + } + + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + ObjectClass::getCtorInitializers(const std::string& name) const + { + std::vector<std::pair<std::string, std::string>> ret; + bool any = false; + for (const auto& [key, child] : type.getDirectMemberTypes()) + { + auto child_s = FromAronType(*child); + auto p = child_s->getCtorInitializers(key); + for (const auto& el : p.first) + { + ret.push_back(el); + } + any = any or p.second; } + return {ret, any}; } - std::vector<std::string> ObjectClass::getRequiredIncludes() const + std::vector<std::string> + ObjectClass::getRequiredIncludes() const { std::vector<std::string> ret; for (const auto& [key, child] : type.getDirectMemberTypes()) { - (void) key; + (void)key; auto child_s = FromAronType(*child); ret = simox::alg::appended(ret, child_s->getRequiredIncludes()); } return ret; } - std::vector<CppFieldPtr> ObjectClass::getPublicVariableDeclarations(const std::string&) const + std::vector<CppFieldPtr> + ObjectClass::getPublicVariableDeclarations(const std::string&) const { std::vector<CppFieldPtr> fields; for (const auto& [key, member] : type.getDirectMemberTypes()) @@ -68,7 +94,8 @@ namespace armarx::aron::codegenerator::cpp::generator return fields; } - CppBlockPtr ObjectClass::getResetSoftBlock(const std::string& accessor) const + CppBlockPtr + ObjectClass::getResetSoftBlock(const std::string& accessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); if (type.getExtends() != nullptr) @@ -86,7 +113,8 @@ namespace armarx::aron::codegenerator::cpp::generator return block_if_data; } - CppBlockPtr ObjectClass::getResetHardBlock(const std::string& accessor) const + CppBlockPtr + ObjectClass::getResetHardBlock(const std::string& accessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); if (type.getExtends() != nullptr) @@ -104,7 +132,11 @@ namespace armarx::aron::codegenerator::cpp::generator return block_if_data; } - CppBlockPtr ObjectClass::getWriteTypeBlock(const std::string&, const std::string&, const Path& p, std::string&) const + CppBlockPtr + ObjectClass::getWriteTypeBlock(const std::string&, + const std::string&, + const Path& p, + std::string&) const { static const std::string OBJECT_MEMBERS_ACCESSOR = ARON_VARIABLE_PREFIX + "_objectMembers"; static const std::string OBJECT_EXTENDS_ACCESSOR = ARON_VARIABLE_PREFIX + "_objectExtends"; @@ -116,10 +148,11 @@ namespace armarx::aron::codegenerator::cpp::generator { const auto extends_s = FromAronType(*type.getExtends()); b->addLine("// get base class of " + this->getFullInstantiatedCppTypename()); - b->addLine("auto " + OBJECT_EXTENDS_ACCESSOR + " = " + extends_s->getFullInstantiatedCppTypename() + "::writeType(" + - ARON_WRITER_ACCESSOR + ", " + - "{" + simox::alg::join(type.getExtends()->getTemplateInstantiations(), ", ") + "}, " + - "::armarx::aron::type::Maybe::NONE);"); + b->addLine("auto " + OBJECT_EXTENDS_ACCESSOR + " = " + + extends_s->getFullInstantiatedCppTypename() + "::writeType(" + + ARON_WRITER_ACCESSOR + ", " + "{" + + simox::alg::join(type.getExtends()->getTemplateInstantiations(), ", ") + + "}, " + "::armarx::aron::type::Maybe::NONE);"); } else { @@ -132,9 +165,11 @@ namespace armarx::aron::codegenerator::cpp::generator const auto child_s = FromAronType(*child); std::string child_return_variant; Path nextPath = p.withElement(key, true); - CppBlockPtr child_b = child_s->getWriteTypeBlock(child_s->getFullInstantiatedCppTypename(), key, nextPath, child_return_variant); + CppBlockPtr child_b = child_s->getWriteTypeBlock( + child_s->getFullInstantiatedCppTypename(), key, nextPath, child_return_variant); b->appendBlock(child_b); - b->addLine(OBJECT_MEMBERS_ACCESSOR + ".emplace(\"" + key + "\", " + child_return_variant + ");"); + b->addLine(OBJECT_MEMBERS_ACCESSOR + ".emplace(\"" + key + "\", " + + child_return_variant + ");"); } std::vector<std::string> templatesQuoted; std::vector<std::string> templateIntantiationsQuoted; @@ -147,18 +182,19 @@ namespace armarx::aron::codegenerator::cpp::generator templateIntantiationsQuoted.push_back("\"" + t + "\""); } - b->addLine("return " + ARON_WRITER_ACCESSOR + ".writeObject(\"" + type.getObjectName() + "\", " + - "{" + simox::alg::join(templatesQuoted, ", ") + "}, " + - ARON_TEMPLATE_INSTANTIATIONS_ACCESSOR + ", " + - OBJECT_MEMBERS_ACCESSOR + ", " + - OBJECT_EXTENDS_ACCESSOR + ", " + - ARON_MAYBE_TYPE_ACCESSOR + ", " + - ARON_PATH_ACCESSOR + "); // of top level object " + getInstantiatedCppTypename());; + b->addLine("return " + ARON_WRITER_ACCESSOR + ".writeObject(\"" + type.getObjectName() + + "\", " + "{" + simox::alg::join(templatesQuoted, ", ") + "}, " + + ARON_TEMPLATE_INSTANTIATIONS_ACCESSOR + ", " + OBJECT_MEMBERS_ACCESSOR + ", " + + OBJECT_EXTENDS_ACCESSOR + ", " + ARON_MAYBE_TYPE_ACCESSOR + ", " + + ARON_PATH_ACCESSOR + "); // of top level object " + + getInstantiatedCppTypename()); + ; return b; } - CppBlockPtr ObjectClass::getWriteBlock(const std::string&, const Path& p, std::string&) const + CppBlockPtr + ObjectClass::getWriteBlock(const std::string&, const Path& p, std::string&) const { static const std::string OBJECT_MEMBERS_ACCESSOR = ARON_VARIABLE_PREFIX + "_objectMembers"; static const std::string OBJECT_EXTENDS_ACCESSOR = ARON_VARIABLE_PREFIX + "_objectExtends"; @@ -171,8 +207,11 @@ namespace armarx::aron::codegenerator::cpp::generator if (type.getExtends() != nullptr) { const auto extends_s = FromAronType(*type.getExtends()); - block_if_data->addLine("// write base class of " + this->getFullInstantiatedCppTypename()); - block_if_data->addLine(OBJECT_EXTENDS_ACCESSOR + " = " + extends_s->getFullInstantiatedCppTypename() + "::write(" + ARON_WRITER_ACCESSOR + ");"); + block_if_data->addLine("// write base class of " + + this->getFullInstantiatedCppTypename()); + block_if_data->addLine(OBJECT_EXTENDS_ACCESSOR + " = " + + extends_s->getFullInstantiatedCppTypename() + "::write(" + + ARON_WRITER_ACCESSOR + ");"); } block_if_data->addLine("// members of " + this->getFullInstantiatedCppTypename()); @@ -183,51 +222,67 @@ namespace armarx::aron::codegenerator::cpp::generator Path nextPath = p.withElement(key, true); CppBlockPtr child_b = child_s->getWriteBlock(key, nextPath, child_return_variant); - block_if_data->addLine("auto " + child_return_variant + " = " + ARON_WRITER_ACCESSOR + ".writeNull();"); + block_if_data->addLine("auto " + child_return_variant + " = " + ARON_WRITER_ACCESSOR + + ".writeNull();"); block_if_data->appendBlock(child_b); - block_if_data->addLine(OBJECT_MEMBERS_ACCESSOR + ".emplace(\"" + key + "\", " + child_return_variant + ");"); + block_if_data->addLine(OBJECT_MEMBERS_ACCESSOR + ".emplace(\"" + key + "\", " + + child_return_variant + ");"); } - block_if_data->addLine("return " + ARON_WRITER_ACCESSOR + ".writeDict("+OBJECT_MEMBERS_ACCESSOR+", " + - OBJECT_EXTENDS_ACCESSOR + ", "+ - ARON_PATH_ACCESSOR + "); // of top level object " + getInstantiatedCppTypename()); + block_if_data->addLine("return " + ARON_WRITER_ACCESSOR + ".writeDict(" + + OBJECT_MEMBERS_ACCESSOR + ", " + OBJECT_EXTENDS_ACCESSOR + ", " + + ARON_PATH_ACCESSOR + "); // of top level object " + + getInstantiatedCppTypename()); return block_if_data; } - CppBlockPtr ObjectClass::getReadBlock(const std::string&, const std::string& variantAccessor) const + CppBlockPtr + ObjectClass::getReadBlock(const std::string&, const std::string& variantAccessor) const { static const std::string OBJECT_MEMBERS_ACCESSOR = ARON_VARIABLE_PREFIX + "_objectMembers"; static const std::string OBJECT_EXTENDS_ACCESSOR = ARON_VARIABLE_PREFIX + "_objectExtends"; CppBlockPtr block_if_data = std::make_shared<CppBlock>(); - block_if_data->addLine("std::map<std::string, _Aron_TNonConst> " + OBJECT_MEMBERS_ACCESSOR + ";"); + block_if_data->addLine("std::map<std::string, _Aron_TNonConst> " + OBJECT_MEMBERS_ACCESSOR + + ";"); if (type.getExtends() != nullptr) { const auto extends_s = FromAronType(*type.getExtends()); - block_if_data->addLine(extends_s->getFullInstantiatedCppTypename() + "::read(" + ARON_READER_ACCESSOR + ", "+variantAccessor+");"); + block_if_data->addLine(extends_s->getFullInstantiatedCppTypename() + "::read(" + + ARON_READER_ACCESSOR + ", " + variantAccessor + ");"); } - block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readDict("+variantAccessor+", "+OBJECT_MEMBERS_ACCESSOR+"); // of top level object " + getInstantiatedCppTypename()); + block_if_data->addLine("" + ARON_READER_ACCESSOR + ".readDict(" + variantAccessor + ", " + + OBJECT_MEMBERS_ACCESSOR + "); // of top level object " + + getInstantiatedCppTypename()); for (const auto& [key, child] : type.getDirectMemberTypes()) { const auto child_s = FromAronType(*child); std::string child_accessor = OBJECT_MEMBERS_ACCESSOR + "_" + key + "_iterator"; - block_if_data->addLine("auto " + child_accessor + " = " + OBJECT_MEMBERS_ACCESSOR + ".find(\"" + key + "\");"); - block_if_data->addLine("ARMARX_CHECK_AND_THROW(" + child_accessor + " != " + OBJECT_MEMBERS_ACCESSOR + ".end(), ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, \"Missing member '" + key + "' in aron object '" + getFullClassCppTypename() + "'.\"));"); + block_if_data->addLine("auto " + child_accessor + " = " + OBJECT_MEMBERS_ACCESSOR + + ".find(\"" + key + "\");"); + block_if_data->addLine( + "ARMARX_CHECK_AND_THROW(" + child_accessor + " != " + OBJECT_MEMBERS_ACCESSOR + + ".end(), ::armarx::aron::error::AronException(__PRETTY_FUNCTION__, \"Missing " + "member '" + + key + "' in aron object '" + getFullClassCppTypename() + "'.\"));"); block_if_data->appendBlock(child_s->getReadBlock(key, child_accessor + "->second")); } return block_if_data; } - CppBlockPtr ObjectClass::getEqualsBlock(const std::string& accessor, const std::string& otherInstanceAccessor) const + CppBlockPtr + ObjectClass::getEqualsBlock(const std::string& accessor, + const std::string& otherInstanceAccessor) const { CppBlockPtr block_if_data = std::make_shared<CppBlock>(); if (type.getExtends() != nullptr) { const auto extends_s = FromAronType(*type.getExtends()); - block_if_data->addLine("if (not (" + extends_s->getFullInstantiatedCppTypename() + "::operator== (" + otherInstanceAccessor + ")))"); + block_if_data->addLine("if (not (" + extends_s->getFullInstantiatedCppTypename() + + "::operator== (" + otherInstanceAccessor + ")))"); block_if_data->addLineAsBlock("return false;"); } for (const auto& [key, child] : type.getDirectMemberTypes()) @@ -239,7 +294,8 @@ namespace armarx::aron::codegenerator::cpp::generator return block_if_data; } - std::pair<std::vector<std::pair<std::string, std::string>>, bool> ObjectClass::getCopyCtorInitializers(const std::string&) const + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + ObjectClass::getCopyCtorInitializers(const std::string&) const { std::vector<std::pair<std::string, std::string>> ret; @@ -259,4 +315,4 @@ namespace armarx::aron::codegenerator::cpp::generator } return {ret, anyComplex}; } -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/ObjectClass.h b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/ObjectClass.h index 772d138cb7cc521753ce6bd3086bb076d475b462..34d0f16c058cca25a7fd2905e0c43f926ea365b7 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/ObjectClass.h +++ b/source/RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/toplevel/ObjectClass.h @@ -26,11 +26,9 @@ #include <RobotAPI/libraries/aron/codegeneration/codegenerator/codewriter/cpp/generator/detail/SpecializedGenerator.h> #include <RobotAPI/libraries/aron/core/type/variant/container/Object.h> - namespace armarx::aron::codegenerator::cpp::generator { - class ObjectClass : - public detail::SpecializedGeneratorBase<type::Object, ObjectClass> + class ObjectClass : public detail::SpecializedGeneratorBase<type::Object, ObjectClass> { public: // constructors @@ -41,13 +39,20 @@ namespace armarx::aron::codegenerator::cpp::generator std::vector<std::string> getRequiredIncludes() const final; std::vector<CppFieldPtr> getPublicVariableDeclarations(const std::string&) const final; - std::pair<std::vector<std::pair<std::string, std::string>>, bool> getCopyCtorInitializers(const std::string&) const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCtorInitializers(const std::string&) const final; + std::pair<std::vector<std::pair<std::string, std::string>>, bool> + getCopyCtorInitializers(const std::string&) const final; CppBlockPtr getResetHardBlock(const std::string& cppAccessor) const final; CppBlockPtr getResetSoftBlock(const std::string& cppAccessor) const final; - CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, const std::string& cppAccessor, const Path&, std::string& variantAccessor) const final; - CppBlockPtr getWriteBlock(const std::string& cppAccessor, const Path&, std::string&) const final; + CppBlockPtr getWriteTypeBlock(const std::string& typeAccessor, + const std::string& cppAccessor, + const Path&, + std::string& variantAccessor) const final; + CppBlockPtr + getWriteBlock(const std::string& cppAccessor, const Path&, std::string&) const final; CppBlockPtr getReadBlock(const std::string& cppAccessor, const std::string&) const final; CppBlockPtr getEqualsBlock(const std::string&, const std::string&) const final; }; -} +} // namespace armarx::aron::codegenerator::cpp::generator diff --git a/source/RobotAPI/libraries/aron/codegeneration/test/aron/OptionalTest.xml b/source/RobotAPI/libraries/aron/codegeneration/test/aron/OptionalTest.xml index 29b58d4594a99b5845c25fcbfe003d97bb89b763..db2d4e30c4a44df1d250b7a14c1b051b00a2c3f1 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/test/aron/OptionalTest.xml +++ b/source/RobotAPI/libraries/aron/codegeneration/test/aron/OptionalTest.xml @@ -47,7 +47,7 @@ </ObjectChild> <ObjectChild key='some_eigen_matrix'> - <Matrix rows="25" cols="10" type="int64" optional="true"/> + <Matrix rows="25" cols="10" type="int64" /> </ObjectChild> <ObjectChild key='some_obj'> @@ -63,7 +63,7 @@ </ObjectChild> <ObjectChild key="an_optional_pose"> - <Pose /> + <Pose optional="true"/> </ObjectChild> </Object> diff --git a/source/RobotAPI/libraries/aron/codegeneration/test/aron/PrimitiveTest.xml b/source/RobotAPI/libraries/aron/codegeneration/test/aron/PrimitiveTest.xml index 1770306699daf5f27d4fbe9d820c47a04b6b68b6..35ad458c89f4531934a8b77d24aa7f8f5e356e8c 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/test/aron/PrimitiveTest.xml +++ b/source/RobotAPI/libraries/aron/codegeneration/test/aron/PrimitiveTest.xml @@ -4,22 +4,22 @@ <GenerateTypes> <Object name='armarx::PrimitiveTest'> <objectchild key='the_int'> - <int /> + <int default="45"/> </ObjectChild> <objectchild key='the_long'> - <long /> + <long default="44"/> </ObjectChild> <objectchild key='the_float'> - <float /> + <float default="43"/> </ObjectChild> <objectchild key='the_double'> - <double /> + <double default="42"/> </ObjectChild> <objectchild key='the_string'> - <string /> + <string default="lalala" /> </ObjectChild> <objectchild key='the_bool'> - <bool /> + <bool default="true"/> </ObjectChild> </Object> </GenerateTypes> diff --git a/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Data.cpp b/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Data.cpp index 925582621433aa3f679dccee50af2b7e2dcad6d7..5f409eb05e322029765e3d8322be49af2430be93 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Data.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Data.cpp @@ -24,12 +24,128 @@ #include "Data.h" #include <SimoxUtility/algorithm/string/string_tools.h> + #include <RobotAPI/libraries/aron/core/Exception.h> namespace armarx::aron::typereader::xml { + bool + util::CheckStrIsInt(const std::string& s) + { + try + { + simox::alg::to_<int>(s); + } + catch (simox::error::SimoxError&) + { + return false; + } + return true; + } + + void + util::EnforceStrIsInt(const std::string& s) + { + if (!CheckStrIsInt(s)) + { + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not convert a string to an integer", s); + } + } + + bool + util::CheckStrIsFloat(const std::string& s) + { + try + { + simox::alg::to_<float>(s); + } + catch (simox::error::SimoxError&) + { + return false; + } + return true; + } + + void + util::EnforceStrIsFloat(const std::string& s) + { + if (!CheckStrIsFloat(s)) + { + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not convert a string to a floating point", s); + } + } + + bool + util::CheckStrIsNumber(const std::string& s) + { + return CheckStrIsInt(s) || CheckStrIsFloat(s); + } + + void + util::EnforceStrIsNumber(const std::string& s) + { + if (!CheckStrIsNumber(s)) + { + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not convert a string to a number", s); + } + } + + bool + util::CheckStrIsNumberSeq(const std::string& s) + { + std::vector<std::string> split = simox::alg::split(s, ","); + for (const auto& e : split) + { + if (!CheckStrIsNumber(e)) + { + return false; + } + } + return true; + } + + void + util::EnforceStrIsNumberSeq(const std::string& s) + { + if (!CheckStrIsNumberSeq(s)) + { + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, + "Could not convert a string to a sequence of numbers. Note that number sequences " + "have to separated with ','", + s); + } + } + + bool + util::CheckStrIsBool(const std::string& s) + { + try + { + simox::alg::to_<bool>(s); + } + catch (simox::error::SimoxError&) + { + return false; + } + return true; + } + + void + util::EnforceStrIsBool(const std::string& s) + { + if (!CheckStrIsBool(s)) + { + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not convert a string to a bool", s); + } + } - std::optional<RapidXmlReaderNode> util::GetFirstNodeWithTag(const RapidXmlReaderNode& node, const std::string& name) + std::optional<RapidXmlReaderNode> + util::GetFirstNodeWithTag(const RapidXmlReaderNode& node, const std::string& name) { for (const auto& n : node.nodes()) { @@ -42,26 +158,35 @@ namespace armarx::aron::typereader::xml return std::nullopt; } - void util::EnforceAttribute(const RapidXmlReaderNode& node, const std::string& att) + void + util::EnforceAttribute(const RapidXmlReaderNode& node, const std::string& att) { if (!HasAttribute(node, att)) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "A <" + node.name() + ">-tag does not have the '"+att+"' attribute", simox::alg::to_string(node.get_all_attributes())); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "A <" + node.name() + ">-tag does not have the '" + + att + "' attribute", + simox::alg::to_string(node.get_all_attributes())); } } - bool util::HasAttribute(const RapidXmlReaderNode& node, const std::string& att) + bool + util::HasAttribute(const RapidXmlReaderNode& node, const std::string& att) { return node.has_attribute(att.c_str()); } - std::string util::GetAttribute(const RapidXmlReaderNode& node, const std::string& att) + std::string + util::GetAttribute(const RapidXmlReaderNode& node, const std::string& att) { EnforceAttribute(node, att); return node.attribute_value(att.c_str()); } - std::string util::GetAttributeWithDefault(const armarx::RapidXmlReaderNode& node, const std::string& att, const std::string& def) + std::string + util::GetAttributeWithDefault(const armarx::RapidXmlReaderNode& node, + const std::string& att, + const std::string& def) { if (!(HasAttribute(node, att))) { @@ -70,7 +195,8 @@ namespace armarx::aron::typereader::xml return node.attribute_value(att.c_str()); } - bool util::AttributeIsTrue(const armarx::RapidXmlReaderNode& node, const std::string& att) + bool + util::AttributeIsTrue(const armarx::RapidXmlReaderNode& node, const std::string& att) { if (HasAttribute(node, att)) { @@ -83,20 +209,24 @@ namespace armarx::aron::typereader::xml return false; } - bool util::HasTagName(const armarx::RapidXmlReaderNode& node, const std::string& name) + bool + util::HasTagName(const armarx::RapidXmlReaderNode& node, const std::string& name) { return (simox::alg::to_lower(name) == simox::alg::to_lower(node.name())); } - void util::EnforceTagName(const armarx::RapidXmlReaderNode& node, const std::string& name) + void + util::EnforceTagName(const armarx::RapidXmlReaderNode& node, const std::string& name) { if (!(HasTagName(node, name))) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The node has the wrong tag. Expected: " + name, node.name()); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "The node has the wrong tag. Expected: " + name, node.name()); } } - void util::EnforceTagNames(const RapidXmlReaderNode& node, const std::vector<std::string>& names) + void + util::EnforceTagNames(const RapidXmlReaderNode& node, const std::vector<std::string>& names) { for (const auto& name : names) { @@ -105,57 +235,86 @@ namespace armarx::aron::typereader::xml return; } } - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The node has the wrong tag. Expected one of: " + simox::alg::to_string(names, ", "), node.name()); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "The node has the wrong tag. Expected one of: " + + simox::alg::to_string(names, ", "), + node.name()); } - std::string util::GetTagName(const armarx::RapidXmlReaderNode& node) + std::string + util::GetTagName(const armarx::RapidXmlReaderNode& node) { return simox::alg::to_lower(node.name()); } - void util::EnforceChildSizeSmaller(const RapidXmlReaderNode& node, const size_t size) + void + util::EnforceChildSizeSmaller(const RapidXmlReaderNode& node, const size_t size) { const size_t s = node.nodes().size(); if (s >= size) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The node <" + node.name() + "> has the wrong number of children", std::to_string(s), std::to_string(size)); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "The node <" + node.name() + + "> has the wrong number of children", + std::to_string(s), + std::to_string(size)); } } - void util::EnforceChildSizeSmallerEqual(const RapidXmlReaderNode& node, const size_t size) + void + util::EnforceChildSizeSmallerEqual(const RapidXmlReaderNode& node, const size_t size) { const size_t s = node.nodes().size(); if (s > size) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The node <" + node.name() + "> has the wrong number of children", std::to_string(s), std::to_string(size)); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "The node <" + node.name() + + "> has the wrong number of children", + std::to_string(s), + std::to_string(size)); } } - void util::EnforceChildSize(const armarx::RapidXmlReaderNode& node, const size_t size) + void + util::EnforceChildSize(const armarx::RapidXmlReaderNode& node, const size_t size) { const size_t s = node.nodes().size(); if (s != size) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The node <" + node.name() + "> has the wrong number of children", std::to_string(s), std::to_string(size)); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "The node <" + node.name() + + "> has the wrong number of children", + std::to_string(s), + std::to_string(size)); } } - void util::EnforceChildSizeGreaterEqual(const RapidXmlReaderNode& node, const size_t size) + void + util::EnforceChildSizeGreaterEqual(const RapidXmlReaderNode& node, const size_t size) { const size_t s = node.nodes().size(); if (s < size) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The node <" + node.name() + "> has the wrong number of children", std::to_string(s), std::to_string(size)); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "The node <" + node.name() + + "> has the wrong number of children", + std::to_string(s), + std::to_string(size)); } } - void util::EnforceChildSizeGreater(const RapidXmlReaderNode& node, const size_t size) + void + util::EnforceChildSizeGreater(const RapidXmlReaderNode& node, const size_t size) { const size_t s = node.nodes().size(); if (s <= size) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The node <" + node.name() + "> has the wrong number of children", std::to_string(s), std::to_string(size)); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "The node <" + node.name() + + "> has the wrong number of children", + std::to_string(s), + std::to_string(size)); } } -} +} // namespace armarx::aron::typereader::xml diff --git a/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Data.h b/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Data.h index bc557478142396f30a2d92191b469e2f7fcf438f..03473264cfee8732ae8bb96fb60021bbdccb5cfb 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Data.h +++ b/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Data.h @@ -41,70 +41,102 @@ namespace armarx::aron::typereader::xml namespace constantes { // Definition tags - const std::string TYPE_DEFINITION_TAG = "arontypedefinition"; + const constexpr auto TYPE_DEFINITION_TAG = "arontypedefinition"; - const std::string CODE_INCLUDES_TAG = "codeincludes"; - const std::string ARON_INCLUDES_TAG = "aronincludes"; - const std::string INCLUDES_TAG = "includes"; - const std::string SYSTEM_INCLUDE_TAG = "systeminclude"; - const std::string PACKAGE_PATH_TAG = "packagepath"; - const std::string INCLUDE_TAG = "include"; - const std::string GENERATE_TYPES_TAG = "generatetypes"; + const constexpr auto CODE_INCLUDES_TAG = "codeincludes"; + const constexpr auto ARON_INCLUDES_TAG = "aronincludes"; + const constexpr auto INCLUDES_TAG = "includes"; + const constexpr auto SYSTEM_INCLUDE_TAG = "systeminclude"; + const constexpr auto PACKAGE_PATH_TAG = "packagepath"; + const constexpr auto INCLUDE_TAG = "include"; + const constexpr auto GENERATE_TYPES_TAG = "generatetypes"; // Attribute names - const std::string ARON_ATTRIBUTE_NAME = "aron"; - const std::string CODE_ATTRIBUTE_NAME = "code"; - const std::string METHOD_ATTRIBUTE_NAME = "method"; - const std::string RETURN_ATTRIBUTE_NAME = "return"; - const std::string ARGUMENT_TYPE_ATTRIBUTE_NAME = "argumenttype"; - const std::string INCLUDE_ATTRIBUTE_NAME = "include"; - const std::string READER_ATTRIBUTE_NAME = "reader"; - const std::string WRITER_ATTRIBUTE_NAME = "writer"; - const std::string EXTENDS_ATTRIBUTE_NAME = "extends"; - const std::string NAME_ATTRIBUTE_NAME = "name"; - const std::string VALUE_ATTRIBUTE_NAME = "value"; - const std::string TEMPLATE_ATTRIBUTE_NAME = "template"; - const std::string KEY_ATTRIBUTE_NAME = "key"; - const std::string TYPE_ATTRIBUTE_NAME = "type"; - const std::string WIDTH_ATTRIBUTE_NAME = "width"; - const std::string HEIGHT_ATTRIBUTE_NAME = "height"; - const std::string ROWS_ATTRIBUTE_NAME = "rows"; - const std::string COLS_ATTRIBUTE_NAME = "cols"; - const std::string DIMENSIONS_ATTRIBUTE_NAME = "dimensions"; - const std::string SHAPE_ATTRIBUTE_NAME = "shape"; - const std::string OPTIONAL_ATTRIBUTE_NAME = "optional"; - const std::string RAW_PTR_ATTRIBUTE_NAME = "raw_ptr"; - const std::string SHARED_PTR_ATTRIBUTE_NAME = "shared_ptr"; - const std::string UNIQUE_PTR_ATTRIBUTE_NAME = "unique_ptr"; - const std::string PACKAGE_ATTRIBUTE_NAME = "package"; - const std::string DOC_BRIEF_ATTRIBUTE_NAME = "doc-brief"; - const std::string DOC_AUTHOR_ATTRIBUTE_NAME = "doc-author"; - const std::string DOC_PARAM_ATTRIBUTE_NAME = "doc-param"; - const std::string PATH_ATTRIBUTE_NAME = "path"; + const constexpr auto ARON_ATTRIBUTE_NAME = "aron"; + const constexpr auto CODE_ATTRIBUTE_NAME = "code"; + const constexpr auto METHOD_ATTRIBUTE_NAME = "method"; + const constexpr auto RETURN_ATTRIBUTE_NAME = "return"; + const constexpr auto ARGUMENT_TYPE_ATTRIBUTE_NAME = "argumenttype"; + const constexpr auto INCLUDE_ATTRIBUTE_NAME = "include"; + const constexpr auto READER_ATTRIBUTE_NAME = "reader"; + const constexpr auto WRITER_ATTRIBUTE_NAME = "writer"; + const constexpr auto EXTENDS_ATTRIBUTE_NAME = "extends"; + const constexpr auto NAME_ATTRIBUTE_NAME = "name"; + const constexpr auto VALUE_ATTRIBUTE_NAME = "value"; + const constexpr auto TEMPLATE_ATTRIBUTE_NAME = "template"; + const constexpr auto KEY_ATTRIBUTE_NAME = "key"; + const constexpr auto TYPE_ATTRIBUTE_NAME = "type"; + const constexpr auto WIDTH_ATTRIBUTE_NAME = "width"; + const constexpr auto HEIGHT_ATTRIBUTE_NAME = "height"; + const constexpr auto ROWS_ATTRIBUTE_NAME = "rows"; + const constexpr auto COLS_ATTRIBUTE_NAME = "cols"; + const constexpr auto DIMENSIONS_ATTRIBUTE_NAME = "dimensions"; + const constexpr auto SHAPE_ATTRIBUTE_NAME = "shape"; + const constexpr auto OPTIONAL_ATTRIBUTE_NAME = "optional"; + const constexpr auto RAW_PTR_ATTRIBUTE_NAME = "raw_ptr"; + const constexpr auto SHARED_PTR_ATTRIBUTE_NAME = "shared_ptr"; + const constexpr auto UNIQUE_PTR_ATTRIBUTE_NAME = "unique_ptr"; + const constexpr auto PACKAGE_ATTRIBUTE_NAME = "package"; + const constexpr auto DOC_BRIEF_ATTRIBUTE_NAME = "doc-brief"; + const constexpr auto DOC_AUTHOR_ATTRIBUTE_NAME = "doc-author"; + const constexpr auto DOC_PARAM_ATTRIBUTE_NAME = "doc-param"; + const constexpr auto PATH_ATTRIBUTE_NAME = "path"; + const constexpr auto DEFAULT_ATTRIBUTE_NAME = "default"; + + // Slugs + const constexpr auto IDENTITY_SLUG = "identity"; + const constexpr auto ZEROS_SLUG = "zeros"; + const constexpr auto ONES_SLUG = "ones"; + const constexpr auto RGB_SLUG = "rgb24"; + const constexpr auto DEPTH_SLUG = "depth32"; + const constexpr auto POINT_XYZ_SLUG = "pointxyz"; + const constexpr auto POINT_XYZI_SLUG = "pointxyzi"; + const constexpr auto POINT_XYZL_SLUG = "pointxyzl"; + const constexpr auto POINT_XYZRGB_SLUG = "pointxyzrgb"; + const constexpr auto POINT_XYZRGBL_SLUG = "pointxyzrgbl"; + const constexpr auto POINT_XYZRGBA_SLUG = "pointxyzrgba"; + const constexpr auto POINT_XYZHSV_SLUG = "pointxyzhsv"; + + const constexpr auto CHAR_SLUG = "int8"; + const constexpr auto UCHAR_SLUG = "uint8"; + const constexpr auto SHORT_SLUG = "int16"; + const constexpr auto USHORT_SLUG = "uint16"; + const constexpr auto INT_SLUG = "int32"; + const constexpr auto UINT_SLUG = "uint32"; + const constexpr auto LONG_SLUG = "int64"; + const constexpr auto ULONG_SLUG = "uint64"; + const constexpr auto FLOAT_SLUG = "float32"; + const constexpr auto DOUBLE_SLUG = "float64"; // Second level tags. Only important if in specific top level tag - const std::string OBJECT_CHILD_TAG = "objectchild"; - const std::string ENUM_VALUE_TAG = "enumvalue"; + const constexpr auto OBJECT_CHILD_TAG = "objectchild"; + const constexpr auto ENUM_VALUE_TAG = "enumvalue"; // Top Level type tags - const std::string LIST_TAG = "list"; - const std::string DICT_TAG = "dict"; - const std::string OBJECT_TAG = "object"; - const std::string PAIR_TAG = "pair"; - const std::string TUPLE_TAG = "tuple"; - const std::string INT_ENUM_TAG = "intenum"; - const std::string NDARRAY_TAG = "ndarray"; - const std::string MATRIX_TAG = "matrix"; - const std::string QUATERNION_TAG = "quaternion"; - const std::string IMAGE_TAG = "image"; - const std::string POINT_CLOUD_TAG = "pointcloud"; - const std::string INT_TAG = "int32"; - const std::string LONG_TAG = "int64"; - const std::string FLOAT_TAG = "float32"; - const std::string DOUBLE_TAG = "float64"; - const std::string STRING_TAG = "string"; - const std::string BOOL_TAG = "bool"; - const std::string ANY_OBJECT_TAG = "anyobject"; + const constexpr auto LIST_TAG = "list"; + const constexpr auto DICT_TAG = "dict"; + const constexpr auto OBJECT_TAG = "object"; + const constexpr auto PAIR_TAG = "pair"; + const constexpr auto TUPLE_TAG = "tuple"; + const constexpr auto INT_ENUM_TAG = "intenum"; + const constexpr auto NDARRAY_TAG = "ndarray"; + const constexpr auto MATRIX_TAG = "matrix"; + const constexpr auto QUATERNION_TAG = "quaternion"; + const constexpr auto IMAGE_TAG = "image"; + const constexpr auto POINT_CLOUD_TAG = "pointcloud"; + const constexpr auto CHAR_TAG = "int8"; + const constexpr auto UCHAR_TAG = "uint8"; + const constexpr auto SHORT_TAG = "int16"; + const constexpr auto USHORT_TAG = "uint16"; + const constexpr auto INT_TAG = "int32"; + const constexpr auto UINT_TAG = "uint32"; + const constexpr auto LONG_TAG = "int64"; + const constexpr auto ULONG_TAG = "uint64"; + const constexpr auto FLOAT_TAG = "float32"; + const constexpr auto DOUBLE_TAG = "float64"; + const constexpr auto STRING_TAG = "string"; + const constexpr auto BOOL_TAG = "bool"; + const constexpr auto ANY_OBJECT_TAG = "anyobject"; // others const std::vector<std::string> WHATEVER_VALUES = {"?"}; @@ -118,70 +150,76 @@ namespace armarx::aron::typereader::xml // Replacements ({tagName, {replacementsTag, additionalAronDTOXMLIncludePackagePath}, deprecationwarning}) const std::map<std::string, Replacement> REPLACEMENTS = { - {"int", - {"<int32 />", {}, "The <int />-tag is deprecated. Please use <int32 /> instead."}}, + {"int", {"int32", {}, "The <int />-tag is deprecated. Please use <int32 /> instead."}}, {"long", - {"<int64 />", {}, "The <long />-tag is deprecated. Please use <int64 /> instead."}}, + {"int64", {}, "The <long />-tag is deprecated. Please use <int64 /> instead."}}, {"float", - {"<float32 />", - {}, - "The <float />-tag is deprecated. Please use <float32 /> instead."}}, + {"float32", {}, "The <float />-tag is deprecated. Please use <float32 /> instead."}}, {"double", - {"<float64 />", - {}, - "The <double />-tag is deprecated. Please use <float64 /> instead."}}, + {"float64", {}, "The <double />-tag is deprecated. Please use <float64 /> instead."}}, // should that be deprecated? - {"position", {"<matrix rows='3' cols='1' type='float32' />", {}, ""}}, - {"pose", {"<matrix rows='4' cols='4' type='float32' />", {}, ""}}, - {"orientation", {"<quaternion type='float32' />", {}, ""}}, + {"position", {"matrix rows='3' cols='1' type='float32'", {}, ""}}, + {"pose", {"matrix rows='4' cols='4' type='float32'", {}, ""}}, + {"orientation", {"quaternion type='float32'", {}, ""}}, // values similar to eigen - {"quaternionf", {"<quaternion type='float32' />", {}, ""}}, - {"quaterniond", {"<quaternion type='float64' />", {}, ""}}, - {"vector2f", {"<matrix rows='2' cols='1' type='float32' />", {}, ""}}, - {"vector2d", {"<matrix rows='2' cols='1' type='float64' />", {}, ""}}, - {"vector3f", {"<matrix rows='3' cols='1' type='float32' />", {}, ""}}, - {"vector3d", {"<matrix rows='3' cols='1' type='float64' />", {}, ""}}, - {"vector4f", {"<matrix rows='4' cols='1' type='float32' />", {}, ""}}, - {"vector4d", {"<matrix rows='4' cols='1' type='float64' />", {}, ""}}, - {"matrix2f", {"<matrix rows='2' cols='2' type='float32' />", {}, ""}}, - {"matrix2d", {"<matrix rows='2' cols='2' type='float64' />", {}, ""}}, - {"matrix3f", {"<matrix rows='3' cols='3' type='float32' />", {}, ""}}, - {"matrix3d", {"<matrix rows='3' cols='3' type='float64' />", {}, ""}}, - {"matrix4f", {"<matrix rows='4' cols='4' type='float32' />", {}, ""}}, - {"matrix4d", {"<matrix rows='4' cols='4' type='float64' />", {}, ""}}, + {"quaternionf", {"quaternion type='float32'", {}, ""}}, + {"quaterniond", {"quaternion type='float64'", {}, ""}}, + {"vector2f", {"matrix rows='2' cols='1' type='float32'", {}, ""}}, + {"vector2d", {"matrix rows='2' cols='1' type='float64'", {}, ""}}, + {"vector3f", {"matrix rows='3' cols='1' type='float32'", {}, ""}}, + {"vector3d", {"matrix rows='3' cols='1' type='float64'", {}, ""}}, + {"vector4f", {"matrix rows='4' cols='1' type='float32'", {}, ""}}, + {"vector4d", {"matrix rows='4' cols='1' type='float64'", {}, ""}}, + {"matrix2f", {"matrix rows='2' cols='2' type='float32'", {}, ""}}, + {"matrix2d", {"matrix rows='2' cols='2' type='float64'", {}, ""}}, + {"matrix3f", {"matrix rows='3' cols='3' type='float32'", {}, ""}}, + {"matrix3d", {"matrix rows='3' cols='3' type='float64'", {}, ""}}, + {"matrix4f", {"matrix rows='4' cols='4' type='float32'", {}, ""}}, + {"matrix4d", {"matrix rows='4' cols='4' type='float64'", {}, ""}}, // You can also add replacements for arondtos here! // structure: {xml-identifier, {replacement, auto-include}, deprecationwarning} {"datetime", - {"<armarx::arondto::DateTime />", + {"armarx::arondto::DateTime", {"RobotAPI", "libraries/aron/common/aron/time.xml"}, ""}}, {"time", - {"<armarx::arondto::DateTime />", + {"armarx::arondto::DateTime", {"RobotAPI", "libraries/aron/common/aron/time.xml"}, ""}}, {"duration", - {"<armarx::arondto::Duration />", + {"armarx::arondto::Duration", {"RobotAPI", "libraries/aron/common/aron/time.xml"}, ""}}, {"framedposition", - {"<armarx::arondto::FramedPosition />", + {"armarx::arondto::FramedPosition", {"RobotAPI", "libraries/aron/common/aron/framed.xml"}, ""}}, {"framedorientation", - {"<armarx::arondto::FramedOrientation />", + {"armarx::arondto::FramedOrientation", {"RobotAPI", "libraries/aron/common/aron/framed.xml"}, ""}}, {"framedpose", - {"<armarx::arondto::FramedPose />", + {"armarx::arondto::FramedPose", {"RobotAPI", "libraries/aron/common/aron/framed.xml"}, ""}}}; } // namespace constantes namespace util { + bool CheckStrIsInt(const std::string&); + void EnforceStrIsInt(const std::string&); + bool CheckStrIsFloat(const std::string&); + void EnforceStrIsFloat(const std::string&); + bool CheckStrIsNumber(const std::string&); + void EnforceStrIsNumber(const std::string&); + bool CheckStrIsNumberSeq(const std::string&); + void EnforceStrIsNumberSeq(const std::string&); + bool CheckStrIsBool(const std::string&); + void EnforceStrIsBool(const std::string&); + std::optional<RapidXmlReaderNode> GetFirstNodeWithTag(const RapidXmlReaderNode& node, const std::string& name); diff --git a/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Factory.cpp b/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Factory.cpp index 8409c87ba128e86bab38cf78f0994d34f35844fe..da43a7631f26585412947d053131b948a2652f65 100644 --- a/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Factory.cpp +++ b/source/RobotAPI/libraries/aron/codegeneration/typereader/xml/Factory.cpp @@ -31,20 +31,33 @@ // ArmarX #include <ArmarXCore/core/time/DateTime.h> + #include <RobotAPI/libraries/aron/core/type/variant/All.h> + #include "Data.h" namespace armarx::aron::typereader::xml { - void printDeprecationWarning(const std::string& warning) + void + printDeprecationWarning(const std::string& warning) { - std::cout << "\033[1;33mAron deprecation warning: " << warning << "\033[0m" << std::endl; + std::cout + << "\033[1;33m[**Aron v" + armarx::aron::VERSION + " deprecation warning**]: " + << warning + << "\nPlease note that a future version of aron might not support this anymore.\033[0m" + << std::endl; } - type::VariantPtr ReaderFactory::create(const RapidXmlReaderNode& node, const Path& path) + void + printWarning(const std::string& warning) { - static const std::map<std::string, type::Descriptor> String2Descriptor = - { + std::cout << "\033[1;33m[**Aron warning**]: " << warning << "\033[0m" << std::endl; + } + + type::VariantPtr + ReaderFactory::create(const RapidXmlReaderNode& node, const Path& path) + { + static const std::map<std::string, type::Descriptor> String2Descriptor = { {constantes::LIST_TAG, type::Descriptor::LIST}, {constantes::OBJECT_TAG, type::Descriptor::OBJECT}, {constantes::TUPLE_TAG, type::Descriptor::TUPLE}, @@ -62,13 +75,13 @@ namespace armarx::aron::typereader::xml {constantes::DOUBLE_TAG, type::Descriptor::DOUBLE}, {constantes::STRING_TAG, type::Descriptor::STRING}, {constantes::BOOL_TAG, type::Descriptor::BOOL}, - {constantes::ANY_OBJECT_TAG, type::Descriptor::ANY_OBJECT} - }; + {constantes::ANY_OBJECT_TAG, type::Descriptor::ANY_OBJECT}}; RapidXmlReaderNode nodeToUse = node; // check for replacement - if (auto it = constantes::REPLACEMENTS.find(simox::alg::to_lower(nodeToUse.name())); it != constantes::REPLACEMENTS.end()) + if (auto it = constantes::REPLACEMENTS.find(simox::alg::to_lower(nodeToUse.name())); + it != constantes::REPLACEMENTS.end()) { auto replacement = it->second; if (!replacement.deprecatedWarning.empty()) @@ -76,47 +89,75 @@ namespace armarx::aron::typereader::xml printDeprecationWarning(replacement.deprecatedWarning); } + std::string tag = replacement.replacementTag; + if (util::HasAttribute(nodeToUse, constantes::DEFAULT_ATTRIBUTE_NAME)) + { + tag += " " + std::string(constantes::DEFAULT_ATTRIBUTE_NAME) + "=\"" + + util::GetAttribute(nodeToUse, constantes::DEFAULT_ATTRIBUTE_NAME) + "\""; + } + // We make the system believe there is another string in the xml - RapidXmlReaderPtr reader = RapidXmlReader::FromXmlString(replacement.replacementTag); + RapidXmlReaderPtr reader = RapidXmlReader::FromXmlString("<" + tag + " />"); nodeToUse = reader->getRoot(); } auto it = String2Descriptor.find(simox::alg::to_lower(nodeToUse.name())); auto descriptor = (it == String2Descriptor.end() ? type::Descriptor::UNKNOWN : it->second); - switch(descriptor) - { - case type::Descriptor::LIST: return createList(nodeToUse, path); - case type::Descriptor::DICT: return createDict(nodeToUse, path); - case type::Descriptor::OBJECT: return createObject(nodeToUse, path); - case type::Descriptor::TUPLE: return createTuple(nodeToUse, path); - case type::Descriptor::PAIR: return createPair(nodeToUse, path); - case type::Descriptor::NDARRAY: return createNDArray(nodeToUse, path); - case type::Descriptor::MATRIX: return createMatrix(nodeToUse, path); - case type::Descriptor::QUATERNION: return createQuaternion(nodeToUse, path); - case type::Descriptor::IMAGE: return createImage(nodeToUse, path); - case type::Descriptor::POINTCLOUD: return createPointCloud(nodeToUse, path); - case type::Descriptor::INT_ENUM: return createIntEnum(nodeToUse, path); - case type::Descriptor::INT: return createInt(nodeToUse, path); - case type::Descriptor::LONG: return createLong(nodeToUse, path); - case type::Descriptor::FLOAT: return createFloat(nodeToUse, path); - case type::Descriptor::DOUBLE: return createDouble(nodeToUse, path); - case type::Descriptor::STRING: return createString(nodeToUse, path); - case type::Descriptor::BOOL: return createBool(nodeToUse, path); - case type::Descriptor::ANY_OBJECT: return createAnyObject(nodeToUse, path); - case type::Descriptor::UNKNOWN: return findExistingObject(nodeToUse.name(), path); + switch (descriptor) + { + case type::Descriptor::LIST: + return createList(nodeToUse, path); + case type::Descriptor::DICT: + return createDict(nodeToUse, path); + case type::Descriptor::OBJECT: + return createObject(nodeToUse, path); + case type::Descriptor::TUPLE: + return createTuple(nodeToUse, path); + case type::Descriptor::PAIR: + return createPair(nodeToUse, path); + case type::Descriptor::NDARRAY: + return createNDArray(nodeToUse, path); + case type::Descriptor::MATRIX: + return createMatrix(nodeToUse, path); + case type::Descriptor::QUATERNION: + return createQuaternion(nodeToUse, path); + case type::Descriptor::IMAGE: + return createImage(nodeToUse, path); + case type::Descriptor::POINTCLOUD: + return createPointCloud(nodeToUse, path); + case type::Descriptor::INT_ENUM: + return createIntEnum(nodeToUse, path); + case type::Descriptor::INT: + return createInt(nodeToUse, path); + case type::Descriptor::LONG: + return createLong(nodeToUse, path); + case type::Descriptor::FLOAT: + return createFloat(nodeToUse, path); + case type::Descriptor::DOUBLE: + return createDouble(nodeToUse, path); + case type::Descriptor::STRING: + return createString(nodeToUse, path); + case type::Descriptor::BOOL: + return createBool(nodeToUse, path); + case type::Descriptor::ANY_OBJECT: + return createAnyObject(nodeToUse, path); + case type::Descriptor::UNKNOWN: + return findExistingObject(nodeToUse.name(), path); } throw aron::error::AronEOFException(__PRETTY_FUNCTION__); } - type::VariantPtr ReaderFactory::findExistingObject(const std::string& name, const Path& path) const + type::VariantPtr + ReaderFactory::findExistingObject(const std::string& name, const Path& path) const { const auto public_intenum_it = allGeneratedPublicIntEnums.find(name); if (public_intenum_it != allGeneratedPublicIntEnums.end()) { // copy the navigator - auto v = type::Variant::FromAronDTO(*public_intenum_it->second.correspondingType->toAronDTO(), path); + auto v = type::Variant::FromAronDTO( + *public_intenum_it->second.correspondingType->toAronDTO(), path); return v; } @@ -124,31 +165,44 @@ namespace armarx::aron::typereader::xml if (public_obj_it != allGeneratedPublicObjects.end()) { // copy the navigator and set instantiation template args - auto v = type::Variant::FromAronDTO(*public_obj_it->second.correspondingType->toAronDTO(), path); + auto v = type::Variant::FromAronDTO( + *public_obj_it->second.correspondingType->toAronDTO(), path); return v; } - const auto public_known_it = std::find(allPreviouslyKnownPublicTypes.begin(), allPreviouslyKnownPublicTypes.end(), name); - if(public_known_it != allPreviouslyKnownPublicTypes.end()) + const auto public_known_it = std::find( + allPreviouslyKnownPublicTypes.begin(), allPreviouslyKnownPublicTypes.end(), name); + if (public_known_it != allPreviouslyKnownPublicTypes.end()) { // create an empty navigator - auto v = std::make_shared<aron::type::Object>(*public_known_it, std::vector<std::string>(), std::vector<std::string>(), std::map<std::string, type::VariantPtr>(), path); + auto v = std::make_shared<aron::type::Object>(path); + v->setObjectName(*public_known_it); + v->setTemplates({}); + v->setTemplateInstantiations({}); + v->setMemberTypes({}); return v; } // only works during generation process (not for top-level). Used for templates. - const auto private_known_it = std::find(allPreviouslyKnownPrivateTypes.begin(), allPreviouslyKnownPrivateTypes.end(), name); - if(private_known_it != allPreviouslyKnownPrivateTypes.end()) + const auto private_known_it = std::find( + allPreviouslyKnownPrivateTypes.begin(), allPreviouslyKnownPrivateTypes.end(), name); + if (private_known_it != allPreviouslyKnownPrivateTypes.end()) { // create an empty navigator - auto v = std::make_shared<aron::type::Object>(*private_known_it, std::vector<std::string>(), std::vector<std::string>(), std::map<std::string, type::VariantPtr>(), path); + auto v = std::make_shared<aron::type::Object>(path); + v->setObjectName(*private_known_it); + v->setTemplates({}); + v->setTemplateInstantiations({}); + v->setMemberTypes({}); return v; } - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Cannot find a valid object.", name); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Cannot find a valid object.", name); } - type::Maybe ReaderFactory::getMaybe(const RapidXmlReaderNode& n) const + type::Maybe + ReaderFactory::getMaybe(const RapidXmlReaderNode& n) const { if (util::AttributeIsTrue(n, constantes::OPTIONAL_ATTRIBUTE_NAME)) { @@ -169,35 +223,51 @@ namespace armarx::aron::typereader::xml return type::Maybe::NONE; } - void ReaderFactory::checkObjectMemberName(const std::string& s) const + void + ReaderFactory::checkObjectMemberName(const std::string& s) const { if (simox::alg::starts_with(s, "_") || simox::alg::ends_with(s, "_")) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "You used an invalid membername - '_' as starting or ending char is not allowed.", s); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, + "You used an invalid membername - '_' as starting or ending char is not allowed.", + s); } if (simox::alg::starts_with(s, "aron")) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "You used an invalid membername - The prefix 'aron' is used for codegeneration.", s); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, + "You used an invalid membername - The prefix 'aron' is used for codegeneration.", + s); } } - type::VariantPtr ReaderFactory::createObject(const RapidXmlReaderNode& node, const Path& path) + type::VariantPtr + ReaderFactory::createObject(const RapidXmlReaderNode& node, const Path& path) { if (path.hasElement()) + // ensured we are toplevel! { - throw error::AronException(__PRETTY_FUNCTION__, "Having an inner class is not supported anymore since Aron Version 'beta 0.2.3'. Please move the inner class definition to the <" + constantes::GENERATE_TYPES_TAG + ">-tag."); + throw error::AronException( + __PRETTY_FUNCTION__, + "Having an inner class is not supported anymore since Aron Version 'beta 0.2.3'. " + "Please move the inner class definition to the <" + + std::string(constantes::GENERATE_TYPES_TAG) + ">-tag."); } - // ensured we are toplevel! const std::string name = util::GetAttribute(node, constantes::NAME_ATTRIBUTE_NAME); - const std::string extends = util::GetAttributeWithDefault(node, constantes::EXTENDS_ATTRIBUTE_NAME, ""); - auto templates = simox::alg::split(util::GetAttributeWithDefault(node, constantes::TEMPLATE_ATTRIBUTE_NAME, ""), ","); + const std::string extends = + util::GetAttributeWithDefault(node, constantes::EXTENDS_ATTRIBUTE_NAME, ""); + auto templates = simox::alg::split( + util::GetAttributeWithDefault(node, constantes::TEMPLATE_ATTRIBUTE_NAME, ""), ","); auto newObjectInfo = typereader::GenerateObjectInfo(); newObjectInfo.typeName = name; - newObjectInfo.doc_brief = util::GetAttributeWithDefault(node, constantes::DOC_BRIEF_ATTRIBUTE_NAME, ""); - newObjectInfo.doc_author = util::GetAttributeWithDefault(node, constantes::DOC_AUTHOR_ATTRIBUTE_NAME, ""); + newObjectInfo.doc_brief = + util::GetAttributeWithDefault(node, constantes::DOC_BRIEF_ATTRIBUTE_NAME, ""); + newObjectInfo.doc_author = + util::GetAttributeWithDefault(node, constantes::DOC_AUTHOR_ATTRIBUTE_NAME, ""); // reset private known types allPreviouslyKnownPrivateTypes = templates; @@ -219,7 +289,8 @@ namespace armarx::aron::typereader::xml if (util::HasAttribute(objectChild, constantes::DOC_BRIEF_ATTRIBUTE_NAME)) { - newObjectInfo.doc_members.insert({key, util::GetAttribute(objectChild, constantes::DOC_BRIEF_ATTRIBUTE_NAME)}); + newObjectInfo.doc_members.insert( + {key, util::GetAttribute(objectChild, constantes::DOC_BRIEF_ATTRIBUTE_NAME)}); } std::vector<RapidXmlReaderNode> children = objectChild.nodes(); @@ -230,7 +301,10 @@ namespace armarx::aron::typereader::xml if (childNavigator->getDescriptor() == aron::type::Descriptor::OBJECT) { // check if template args are present - std::vector<std::string> templates = simox::alg::split(util::GetAttributeWithDefault(children[0], constantes::TEMPLATE_ATTRIBUTE_NAME, ""), ","); + std::vector<std::string> templates = + simox::alg::split(util::GetAttributeWithDefault( + children[0], constantes::TEMPLATE_ATTRIBUTE_NAME, ""), + ","); auto obj = aron::type::Object::DynamicCastAndCheck(childNavigator); for (const auto& t : templates) { @@ -243,7 +317,11 @@ namespace armarx::aron::typereader::xml } // set the new object - auto aronObjectType = std::make_shared<type::Object>(name, templates, std::vector<std::string>(), members, objPath); + auto aronObjectType = std::make_shared<type::Object>(objPath); + aronObjectType->setObjectName(name); + aronObjectType->setTemplates(templates); + aronObjectType->setTemplateInstantiations({}); + aronObjectType->setMemberTypes(members); if (extends != "") { @@ -258,7 +336,8 @@ namespace armarx::aron::typereader::xml return aronObjectType; } - type::VariantPtr ReaderFactory::createList(const RapidXmlReaderNode &node, const Path &path) + type::VariantPtr + ReaderFactory::createList(const RapidXmlReaderNode& node, const Path& path) { util::EnforceChildSize(node, 1); @@ -267,11 +346,13 @@ namespace armarx::aron::typereader::xml type::VariantPtr type = create(typeNode, path.withAcceptedType()); type->setMaybe(getMaybe(typeNode)); - auto o = std::make_shared<type::List>(type, path); + auto o = std::make_shared<type::List>(path); + o->setAcceptedType(type); return o; } - type::VariantPtr ReaderFactory::createDict(const RapidXmlReaderNode &node, const Path &path) + type::VariantPtr + ReaderFactory::createDict(const RapidXmlReaderNode& node, const Path& path) { util::EnforceChildSize(node, 1); @@ -280,11 +361,13 @@ namespace armarx::aron::typereader::xml type::VariantPtr type = create(typeNode, path.withAcceptedType()); type->setMaybe(getMaybe(typeNode)); - auto o = std::make_shared<type::Dict>(type, path); + auto o = std::make_shared<type::Dict>(path); + o->setAcceptedType(type); return o; } - type::VariantPtr ReaderFactory::createTuple(const RapidXmlReaderNode& node, const Path& path) + type::VariantPtr + ReaderFactory::createTuple(const RapidXmlReaderNode& node, const Path& path) { util::EnforceChildSizeGreater(node, 1); @@ -304,11 +387,13 @@ namespace armarx::aron::typereader::xml elementTypes.push_back(type); } - auto o = std::make_shared<type::Tuple>(elementTypes, path); + auto o = std::make_shared<type::Tuple>(path); + o->setAcceptedTypes(elementTypes); return o; } - type::VariantPtr ReaderFactory::createPair(const RapidXmlReaderNode& node, const Path& path) + type::VariantPtr + ReaderFactory::createPair(const RapidXmlReaderNode& node, const Path& path) { util::EnforceChildSize(node, 2); @@ -322,158 +407,268 @@ namespace armarx::aron::typereader::xml type::VariantPtr type2 = create(type2Node, path.withAcceptedTypeIndex(1)); type2->setMaybe(getMaybe(type2Node)); - auto o = std::make_shared<type::Pair>(type1, type2, path); + auto o = std::make_shared<type::Pair>(path); + o->setFirstAcceptedType(type1); + o->setSecondAcceptedType(type2); return o; } - type::VariantPtr ReaderFactory::createNDArray(const RapidXmlReaderNode& node, const Path& path) const + type::VariantPtr + ReaderFactory::createNDArray(const RapidXmlReaderNode& node, const Path& path) const { - static const std::map<std::string, type::ndarray::ElementType> String2NDArrayType = - { - {"int8", type::ndarray::ElementType::INT8}, - {"int16", type::ndarray::ElementType::INT16}, - {"int32", type::ndarray::ElementType::INT32}, - {"uint8", type::ndarray::ElementType::UINT8}, - {"uint16", type::ndarray::ElementType::UINT16}, - {"uint32", type::ndarray::ElementType::UINT32}, - {"float32", type::ndarray::ElementType::FLOAT32}, - {"float64", type::ndarray::ElementType::FLOAT64} - }; + static const std::map<std::string, type::ndarray::ElementType> String2NDArrayType = { + {constantes::CHAR_SLUG, type::ndarray::ElementType::INT8}, + {constantes::SHORT_SLUG, type::ndarray::ElementType::INT16}, + {constantes::INT_SLUG, type::ndarray::ElementType::INT32}, + {constantes::LONG_SLUG, type::ndarray::ElementType::UINT8}, + {constantes::USHORT_SLUG, type::ndarray::ElementType::UINT16}, + {constantes::UINT_SLUG, type::ndarray::ElementType::UINT32}, + {constantes::FLOAT_SLUG, type::ndarray::ElementType::FLOAT32}, + {constantes::DOUBLE_SLUG, type::ndarray::ElementType::FLOAT64}}; + + static const std::map<std::string, std::string> StringSlug2NDArrayDefaultValue = { + {constantes::ONES_SLUG, type::ndarray::default_value::ONES}, + {constantes::ZEROS_SLUG, type::ndarray::default_value::ZEROS}}; + + auto o = std::make_shared<type::NDArray>(path); + util::EnforceChildSize(node, 0); + util::EnforceAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); + + // TODO return nullptr; } - type::VariantPtr ReaderFactory::createMatrix(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createMatrix(const RapidXmlReaderNode& node, const Path& path) const { - static const std::map<std::string, type::matrix::ElementType> String2MatrixType = - { - {"int16", type::matrix::ElementType::INT16}, - {"int32", type::matrix::ElementType::INT32}, - {"int64", type::matrix::ElementType::INT64}, - {"float32", type::matrix::ElementType::FLOAT32}, - {"float64", type::matrix::ElementType::FLOAT64} - }; + static const std::map<std::string, type::matrix::ElementType> StringSlug2MatrixType = { + {constantes::SHORT_SLUG, type::matrix::ElementType::INT16}, + {constantes::INT_SLUG, type::matrix::ElementType::INT32}, + {constantes::LONG_SLUG, type::matrix::ElementType::INT64}, + {constantes::FLOAT_SLUG, type::matrix::ElementType::FLOAT32}, + {constantes::DOUBLE_SLUG, type::matrix::ElementType::FLOAT64}}; + + static const std::map<std::string, std::string> StringSlug2MatrixDefaultValue = { + {constantes::IDENTITY_SLUG, type::matrix::default_value::IDENTITY}, + {constantes::ONES_SLUG, type::matrix::default_value::ONES}, + {constantes::ZEROS_SLUG, type::matrix::default_value::ZEROS}}; auto o = std::make_shared<type::Matrix>(path); util::EnforceChildSize(node, 0); - util::EnforceAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); auto rows_str = util::GetAttributeWithDefault(node, constantes::ROWS_ATTRIBUTE_NAME, "4"); auto cols_str = util::GetAttributeWithDefault(node, constantes::COLS_ATTRIBUTE_NAME, "4"); - if (std::find(constantes::WHATEVER_VALUES.begin(), constantes::WHATEVER_VALUES.end(), simox::alg::to_lower(rows_str)) != constantes::WHATEVER_VALUES.end()) + // check for unknown size + if (std::find(constantes::WHATEVER_VALUES.begin(), + constantes::WHATEVER_VALUES.end(), + simox::alg::to_lower(rows_str)) != constantes::WHATEVER_VALUES.end()) { rows_str = "-1"; } - if (std::find(constantes::WHATEVER_VALUES.begin(), constantes::WHATEVER_VALUES.end(), simox::alg::to_lower(cols_str)) != constantes::WHATEVER_VALUES.end()) + if (std::find(constantes::WHATEVER_VALUES.begin(), + constantes::WHATEVER_VALUES.end(), + simox::alg::to_lower(cols_str)) != constantes::WHATEVER_VALUES.end()) { cols_str = "-1"; } const int rows = std::stoi(rows_str); const int cols = std::stoi(cols_str); - std::string type = util::GetAttributeWithDefault(node, constantes::TYPE_ATTRIBUTE_NAME, "???"); + // set rows and cols o->setRows(rows); o->setCols(cols); - try + + // get type + std::string type = util::GetAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); + + ARMARX_CHECK_AND_THROW( + StringSlug2MatrixType.count(simox::alg::to_lower(type)), + error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not resolve type", type)); + + // set elem type + o->setElementType(StringSlug2MatrixType.at(simox::alg::to_lower(type))); + + // set default + const std::string def = simox::alg::to_lower(util::GetAttributeWithDefault( + node, constantes::DEFAULT_ATTRIBUTE_NAME, type::matrix::default_value::DEFAULT)); + + if (const auto it = StringSlug2MatrixDefaultValue.find(def); + it != StringSlug2MatrixDefaultValue.end()) { - o->setElementType(String2MatrixType.at(simox::alg::to_lower(type))); + o->setDefaultValue(it->second); } - catch (std::out_of_range& e) + else if (def == type::matrix::default_value::DEFAULT) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The type tag is not valid", type); + o->setDefaultValue(def); } + else + { + util::EnforceStrIsNumber(def); + o->setDefaultValue(def); + } + return o; } - type::VariantPtr ReaderFactory::createQuaternion(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createQuaternion(const RapidXmlReaderNode& node, const Path& path) const { - static const std::map<std::string, type::quaternion::ElementType> String2QuaternionType = - { - {"float32", type::quaternion::ElementType::FLOAT32}, - {"float64", type::quaternion::ElementType::FLOAT64} - }; + static const std::map<std::string, type::quaternion::ElementType> + StringSlug2QuaternionType = { + {constantes::FLOAT_SLUG, type::quaternion::ElementType::FLOAT32}, + {constantes::DOUBLE_SLUG, type::quaternion::ElementType::FLOAT64}}; + + static const std::map<std::string, std::string> StringSlug2QuaternionDefaultValue = { + {constantes::ONES_SLUG, type::quaternion::default_value::ONES}, + {constantes::ZEROS_SLUG, type::quaternion::default_value::ZEROS}}; auto o = std::make_shared<type::Quaternion>(path); util::EnforceChildSize(node, 0); util::EnforceAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); - std::string type = util::GetAttributeWithDefault(node, constantes::TYPE_ATTRIBUTE_NAME, "???"); + // set elem type + std::string type = util::GetAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); + ARMARX_CHECK_AND_THROW( + StringSlug2QuaternionType.count(simox::alg::to_lower(type)), + error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not resolve type", type)); - try + o->setElementType(StringSlug2QuaternionType.at(simox::alg::to_lower(type))); + + // set default + const std::string def = simox::alg::to_lower(util::GetAttributeWithDefault( + node, constantes::DEFAULT_ATTRIBUTE_NAME, type::quaternion::default_value::DEFAULT)); + + if (const auto it = StringSlug2QuaternionDefaultValue.find(def); + it != StringSlug2QuaternionDefaultValue.end()) { - o->setElementType(String2QuaternionType.at(simox::alg::to_lower(type))); + o->setDefaultValue(it->second); } - catch (std::out_of_range& e) + else if (def == type::quaternion::default_value::DEFAULT) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The type tag is not valid", type); + o->setDefaultValue(def); } + else + { + util::EnforceStrIsNumberSeq(def); + o->setDefaultValue(def); + } + return o; } - - type::VariantPtr ReaderFactory::createImage(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createImage(const RapidXmlReaderNode& node, const Path& path) const { - static const std::map<std::string, type::image::PixelType> String2PixelType = - { - {"rgb24", type::image::PixelType::RGB24}, - {"depth32", type::image::PixelType::DEPTH32} - }; + static const std::map<std::string, type::image::PixelType> String2PixelType = { + {constantes::RGB_SLUG, type::image::PixelType::RGB24}, + {constantes::DEPTH_SLUG, type::image::PixelType::DEPTH32}}; + + static const std::map<std::string, std::string> StringSlug2ImageDefaultValue = { + {constantes::IDENTITY_SLUG, type::image::default_value::IDENTITY}, + {constantes::ONES_SLUG, type::image::default_value::ONES}, + {constantes::ZEROS_SLUG, type::image::default_value::ZEROS}}; auto o = std::make_shared<type::Image>(path); util::EnforceChildSize(node, 0); util::EnforceAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); - std::string type = util::GetAttributeWithDefault(node, constantes::TYPE_ATTRIBUTE_NAME, "???"); + // set elem type + std::string type = util::GetAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); + + ARMARX_CHECK_AND_THROW( + String2PixelType.count(simox::alg::to_lower(type)), + error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not resolve type", type)); + + o->setPixelType(String2PixelType.at(simox::alg::to_lower(type))); - try + // set default + const std::string def = simox::alg::to_lower(util::GetAttributeWithDefault( + node, constantes::DEFAULT_ATTRIBUTE_NAME, type::image::default_value::DEFAULT)); + + if (const auto it = StringSlug2ImageDefaultValue.find(def); + it != StringSlug2ImageDefaultValue.end()) + { + o->setDefaultValue(it->second); + } + else if (def == type::image::default_value::DEFAULT) { - o->setPixelType(String2PixelType.at(simox::alg::to_lower(type))); + o->setDefaultValue(def); } - catch (std::out_of_range& e) + else { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The type tag is not valid", type); + util::EnforceStrIsNumber(def); + o->setDefaultValue(def); } + return o; } - type::VariantPtr ReaderFactory::createPointCloud(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createPointCloud(const RapidXmlReaderNode& node, const Path& path) const { - static const std::map<std::string, type::pointcloud::VoxelType> String2VoxelType = - { - {"pointxyz", type::pointcloud::VoxelType::POINT_XYZ}, - {"pointxyzi", type::pointcloud::VoxelType::POINT_XYZI}, - {"pointxyzl", type::pointcloud::VoxelType::POINT_XYZL}, - {"pointxyzrgb", type::pointcloud::VoxelType::POINT_XYZRGB}, - {"pointxyzrgbl", type::pointcloud::VoxelType::POINT_XYZRGBL}, - {"pointxyzrgba", type::pointcloud::VoxelType::POINT_XYZRGBA}, - {"pointxyzhsv", type::pointcloud::VoxelType::POINT_XYZHSV} - }; + static const std::map<std::string, type::pointcloud::VoxelType> StringSlug2VoxelType = { + {constantes::POINT_XYZ_SLUG, type::pointcloud::VoxelType::POINT_XYZ}, + {constantes::POINT_XYZI_SLUG, type::pointcloud::VoxelType::POINT_XYZI}, + {constantes::POINT_XYZL_SLUG, type::pointcloud::VoxelType::POINT_XYZL}, + {constantes::POINT_XYZRGB_SLUG, type::pointcloud::VoxelType::POINT_XYZRGB}, + {constantes::POINT_XYZRGBL_SLUG, type::pointcloud::VoxelType::POINT_XYZRGBL}, + {constantes::POINT_XYZRGBA_SLUG, type::pointcloud::VoxelType::POINT_XYZRGBA}, + {constantes::POINT_XYZHSV_SLUG, type::pointcloud::VoxelType::POINT_XYZHSV}}; + + static const std::map<std::string, std::string> StringSlug2PointCloudDefaultValue = { + {constantes::IDENTITY_SLUG, type::pointcloud::default_value::IDENTITY}, + {constantes::ONES_SLUG, type::pointcloud::default_value::ONES}, + {constantes::ZEROS_SLUG, type::pointcloud::default_value::ZEROS}}; auto o = std::make_shared<type::PointCloud>(path); util::EnforceChildSize(node, 0); - util::EnforceAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); - std::string type = util::GetAttributeWithDefault(node, constantes::TYPE_ATTRIBUTE_NAME, "???"); - try + // set elem type + std::string type = util::GetAttribute(node, constantes::TYPE_ATTRIBUTE_NAME); + + ARMARX_CHECK_AND_THROW( + StringSlug2VoxelType.count(simox::alg::to_lower(type)), + error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not resolve type", type)); + + o->setVoxelType(StringSlug2VoxelType.at(simox::alg::to_lower(type))); + + // set default + const std::string def = simox::alg::to_lower(util::GetAttributeWithDefault( + node, constantes::DEFAULT_ATTRIBUTE_NAME, type::pointcloud::default_value::DEFAULT)); + + if (const auto it = StringSlug2PointCloudDefaultValue.find(def); + it != StringSlug2PointCloudDefaultValue.end()) { - o->setVoxelType(String2VoxelType.at(simox::alg::to_lower(type))); + o->setDefaultValue(it->second); } - catch (std::out_of_range& e) + else if (def == type::pointcloud::default_value::DEFAULT) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The type tag is not valid", type); + o->setDefaultValue(def); } + else + { + util::EnforceStrIsNumber(def); + o->setDefaultValue(def); + } + return o; } - type::VariantPtr ReaderFactory::createIntEnum(const RapidXmlReaderNode& node, const Path& path) + type::VariantPtr + ReaderFactory::createIntEnum(const RapidXmlReaderNode& node, const Path& path) { if (path.hasElement()) + // ensured we are top-level! { - throw error::AronException(__PRETTY_FUNCTION__, "Having an inner int-enum is not supported anymore since Aron Version 'beta 0.2.3'. Please move the inner int-enum definition to the <" + constantes::GENERATE_TYPES_TAG + ">-tag."); + throw error::AronException( + __PRETTY_FUNCTION__, + "Having an inner int-enum is not supported anymore since Aron Version 'beta " + "0.2.3'. Please move the inner int-enum definition to the <" + + std::string(constantes::GENERATE_TYPES_TAG) + ">-tag."); } - // ensured we are top-level! const std::string name = util::GetAttribute(node, constantes::NAME_ATTRIBUTE_NAME); @@ -482,6 +677,10 @@ namespace armarx::aron::typereader::xml allPreviouslyKnownPrivateTypes.clear(); + std::string defaultValue = util::GetAttributeWithDefault( + node, constantes::DEFAULT_ATTRIBUTE_NAME, type::aron_enum::default_value::DEFAULT); + + // get accepted values std::map<std::string, int> acceptedValues; for (const RapidXmlReaderNode& valueChild : node.nodes()) { @@ -492,18 +691,44 @@ namespace armarx::aron::typereader::xml if (util::HasAttribute(valueChild, constantes::DOC_BRIEF_ATTRIBUTE_NAME)) { - newEnumInfo.doc_values.insert({key, util::GetAttribute(valueChild, constantes::DOC_BRIEF_ATTRIBUTE_NAME)}); + newEnumInfo.doc_values.insert( + {key, util::GetAttribute(valueChild, constantes::DOC_BRIEF_ATTRIBUTE_NAME)}); } - const std::string value = util::GetAttribute(valueChild, constantes::VALUE_ATTRIBUTE_NAME); + const std::string value = + util::GetAttribute(valueChild, constantes::VALUE_ATTRIBUTE_NAME); + + // Overwrite default value if child is tagged as default + if (util::AttributeIsTrue(valueChild, constantes::DEFAULT_ATTRIBUTE_NAME)) + { + defaultValue = key; + } acceptedValues.emplace(key, std::stoi(value)); } + if (acceptedValues.size() == 0) + { + printWarning("Found enum '" + name + "' without any members..."); + } + + // check default value + if (defaultValue != type::aron_enum::default_value::DEFAULT and + not acceptedValues.count(defaultValue)) + { + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "An int enum has a non existing default value set", + defaultValue); + } + + // create the int enum aron::Path enumPath = path; // copy, just in case there are special things set enumPath.setRootIdentifier(name); // set the root identifier to the obj name - auto o = std::make_shared<type::IntEnum>(name, acceptedValues, enumPath); + auto o = std::make_shared<type::IntEnum>(enumPath); + o->setEnumName(name); + o->setAcceptedValueMap(acceptedValues); + o->setDefaultValueName(defaultValue); newEnumInfo.correspondingType = o; allGeneratedPublicIntEnums.emplace(newEnumInfo.typeName, newEnumInfo); @@ -512,38 +737,89 @@ namespace armarx::aron::typereader::xml return o; } - type::VariantPtr ReaderFactory::createInt(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createInt(const RapidXmlReaderNode& node, const Path& path) const { - return std::make_shared<type::Int>(path); + const std::string def = + util::GetAttributeWithDefault(node, constantes::DEFAULT_ATTRIBUTE_NAME, "0"); + + util::EnforceStrIsInt(def); + + auto o = std::make_shared<type::Int>(path); + o->setDefaultValue(simox::alg::to_<int>(def)); + return o; } - type::VariantPtr ReaderFactory::createLong(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createLong(const RapidXmlReaderNode& node, const Path& path) const { - return std::make_shared<type::Long>(path); + const std::string def = + util::GetAttributeWithDefault(node, constantes::DEFAULT_ATTRIBUTE_NAME, "0"); + + util::EnforceStrIsInt(def); + + auto o = std::make_shared<type::Long>(path); + o->setDefaultValue(simox::alg::to_<long>(def)); + return o; } - type::VariantPtr ReaderFactory::createFloat(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createFloat(const RapidXmlReaderNode& node, const Path& path) const { - return std::make_shared<type::Float>(path); + const std::string def = + util::GetAttributeWithDefault(node, constantes::DEFAULT_ATTRIBUTE_NAME, "0"); + + util::EnforceStrIsFloat(def); + + auto o = std::make_shared<type::Float>(path); + o->setDefaultValue(simox::alg::to_<float>(def)); + return o; } - type::VariantPtr ReaderFactory::createDouble(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createDouble(const RapidXmlReaderNode& node, const Path& path) const { - return std::make_shared<type::Double>(path); + const std::string def = + util::GetAttributeWithDefault(node, constantes::DEFAULT_ATTRIBUTE_NAME, "0"); + + util::EnforceStrIsFloat(def); + + + auto o = std::make_shared<type::Double>(path); + o->setDefaultValue(simox::alg::to_<double>(def)); + return o; } - type::VariantPtr ReaderFactory::createString(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createString(const RapidXmlReaderNode& node, const Path& path) const { - return std::make_shared<type::String>(path); + const std::string def = + util::GetAttributeWithDefault(node, constantes::DEFAULT_ATTRIBUTE_NAME, ""); + + auto o = std::make_shared<type::String>(path); + o->setDefaultValue(def); + return o; } - type::VariantPtr ReaderFactory::createBool(const RapidXmlReaderNode &node, const Path &path) const + type::VariantPtr + ReaderFactory::createBool(const RapidXmlReaderNode& node, const Path& path) const { - return std::make_shared<type::Bool>(path); + const std::string def = + util::GetAttributeWithDefault(node, constantes::DEFAULT_ATTRIBUTE_NAME, "false"); + + util::EnforceStrIsBool(def); + + auto o = std::make_shared<type::Bool>(path); + + util::EnforceStrIsBool(def); + + o->setDefaultValue(simox::alg::to_<bool>(def)); + return o; } - type::VariantPtr ReaderFactory::createAnyObject(const RapidXmlReaderNode& node, const Path& path) const + type::VariantPtr + ReaderFactory::createAnyObject(const RapidXmlReaderNode& node, const Path& path) const { return std::make_shared<type::AnyObject>(path); } -} +} // namespace armarx::aron::typereader::xml diff --git a/source/RobotAPI/libraries/aron/converter/json/NLohmannJSONConverter.cpp b/source/RobotAPI/libraries/aron/converter/json/NLohmannJSONConverter.cpp index b4682df50a19597d8c0057b1cecd2b11978fae54..c94ff951aff27a7cc3ab740728d80795ececce23 100644 --- a/source/RobotAPI/libraries/aron/converter/json/NLohmannJSONConverter.cpp +++ b/source/RobotAPI/libraries/aron/converter/json/NLohmannJSONConverter.cpp @@ -66,8 +66,7 @@ namespace armarx::aron::type::converter AronNlohmannJSONConverter::ConvertFromNlohmannJSONTypeObject(const nlohmann::json& j, const armarx::aron::Path& p) { - type::ObjectPtr foo = - std::make_shared<aron::type::Object>("foo"); // foo is just a placeholder + type::ObjectPtr foo = std::make_shared<aron::type::Object>(); type::VariantPtr aron = std::make_shared<aron::type::Object>(*foo, p); ConvertFromNlohmannJSON(aron, j); return type::Object::DynamicCastAndCheck(aron); diff --git a/source/RobotAPI/libraries/aron/core/CMakeLists.txt b/source/RobotAPI/libraries/aron/core/CMakeLists.txt index 2fb890b86fb3c9e1bd26bee37f879922c3d6bcd5..6e3ef85cf5ef086450a9896003476d788bcfa69f 100644 --- a/source/RobotAPI/libraries/aron/core/CMakeLists.txt +++ b/source/RobotAPI/libraries/aron/core/CMakeLists.txt @@ -83,6 +83,9 @@ set(LIB_FILES type/rw/reader/variant/VariantReader.cpp type/rw/reader/nlohmannJSON/NlohmannJSONReader.cpp + type/rw/json/Data.cpp + data/rw/json/Data.cpp + data/visitor/Visitor.cpp data/visitor/RecursiveVisitor.cpp data/visitor/variant/VariantVisitor.cpp diff --git a/source/RobotAPI/libraries/aron/core/Exception.h b/source/RobotAPI/libraries/aron/core/Exception.h index fc080bafd09e2d7424bf0fc18538539f680329da..49e7ad4444286b115f71f199c553359b97dcdfe4 100644 --- a/source/RobotAPI/libraries/aron/core/Exception.h +++ b/source/RobotAPI/libraries/aron/core/Exception.h @@ -26,53 +26,58 @@ // STD/STL // ArmarX +#include <ArmarXCore/core/exceptions/Exception.h> +#include <ArmarXCore/core/exceptions/local/ExpressionException.h> #include <ArmarXCore/core/logging/Logging.h> + #include <RobotAPI/interface/aron.h> -#include <ArmarXCore/core/exceptions/local/ExpressionException.h> -#include <ArmarXCore/core/exceptions/Exception.h> -#include <RobotAPI/libraries/aron/core/Path.h> #include <RobotAPI/libraries/aron/core/Descriptor.h> - +#include <RobotAPI/libraries/aron/core/Path.h> namespace armarx::aron::error { /** * @brief A base class for aron exceptions. All aron exceptions inherit from this class */ - class AronException : - public armarx::LocalException + class AronException : public armarx::LocalException { public: AronException() = delete; + AronException(const std::string& prettymethod, const std::string& reason) : LocalException(prettymethod + ": " + reason + ".") { } - AronException(const std::string& prettymethod, const std::string& reason, const Path& path) : + AronException(const std::string& prettymethod, + const std::string& reason, + const Path& path) : LocalException(prettymethod + ": " + reason + ". The path was: " + path.toString()) { } /// call operator to append a message to the exception. Used by ARMARX_CHECK_AND_THROW - AronException& operator()(const std::string& additionalMessage = "") + AronException& + operator()(const std::string& additionalMessage = "") { auto currentReason = getReason(); - setReason(currentReason + ". Additional Message: " + additionalMessage); + if (not additionalMessage.empty()) + { + setReason(currentReason + ". Additional Message: " + additionalMessage); + } return *this; } }; - /** - * @brief A base class for aron exceptions. All aron exceptions inherit from this class - */ - class AronEOFException : - public AronException + class AronEOFException : public AronException { public: AronEOFException() = delete; + AronEOFException(const std::string& prettymethod) : - AronException(prettymethod, "REACHED THE END OF A NON VOID METHOD. PERHAPS YOU FORGOT TO ADD A VALUE TO SOME SWITCH-CASE STATEMEMT?.") + AronException(prettymethod, + "REACHED THE END OF A NON VOID METHOD. PERHAPS YOU FORGOT TO ADD A VALUE " + "TO SOME SWITCH-CASE STATEMEMT?.") { } }; @@ -80,11 +85,11 @@ namespace armarx::aron::error /** * @brief The NotImplementedYetException class */ - class NotImplementedYetException : - public AronException + class NotImplementedYetException : public AronException { public: NotImplementedYetException() = delete; + NotImplementedYetException(const std::string& prettymethod) : AronException(prettymethod, "This method is not yet implemented!") { @@ -94,66 +99,86 @@ namespace armarx::aron::error /** * @brief The AronNotValidException class. Takes a dto object as input */ - class AronNotValidException : - public AronException + class AronNotValidException : public AronException { public: AronNotValidException() = delete; - AronNotValidException(const std::string& prettymethod, const std::string& reason, const data::dto::GenericDataPtr& data) : + + AronNotValidException(const std::string& prettymethod, + const std::string& reason, + const data::dto::GenericDataPtr& data) : AronException(prettymethod, reason + ". The ice_id of the data was: " + data->ice_id()) { - } - AronNotValidException(const std::string& prettymethod, const std::string& reason, const data::dto::GenericDataPtr& data, const Path& path) : - AronException(prettymethod, reason + ". The ice_id of the data was: " + data->ice_id(), path) + AronNotValidException(const std::string& prettymethod, + const std::string& reason, + const data::dto::GenericDataPtr& data, + const Path& path) : + AronException(prettymethod, + reason + ". The ice_id of the data was: " + data->ice_id(), + path) { - } - AronNotValidException(const std::string& prettymethod, const std::string& reason, const type::dto::GenericTypePtr& type) : + AronNotValidException(const std::string& prettymethod, + const std::string& reason, + const type::dto::GenericTypePtr& type) : AronException(prettymethod, reason + ". The ice_id of the type was: " + type->ice_id()) { - } - AronNotValidException(const std::string& prettymethod, const std::string& reason, const type::dto::GenericTypePtr& type, const Path& path) : - AronException(prettymethod, reason + ". The ice_id of the type was: " + type->ice_id(), path) + AronNotValidException(const std::string& prettymethod, + const std::string& reason, + const type::dto::GenericTypePtr& type, + const Path& path) : + AronException(prettymethod, + reason + ". The ice_id of the type was: " + type->ice_id(), + path) { - } }; /** * @brief The ValueNotValidException class. Only takes strings as input (convert before) */ - class ValueNotValidException : - public AronException + class ValueNotValidException : public AronException { public: ValueNotValidException() = delete; - ValueNotValidException(const std::string& prettymethod, const std::string& reason, const std::string& input) : + + ValueNotValidException(const std::string& prettymethod, + const std::string& reason, + const std::string& input) : AronException(prettymethod, reason + ". Got: " + input) { - } - ValueNotValidException(const std::string& prettymethod, const std::string& reason, const std::string& input, const Path& path) : + ValueNotValidException(const std::string& prettymethod, + const std::string& reason, + const std::string& input, + const Path& path) : AronException(prettymethod, reason + ". Got: " + input, path) { - } - ValueNotValidException(const std::string& prettymethod, const std::string& reason, const std::string& input, const std::string& expectation) : + ValueNotValidException(const std::string& prettymethod, + const std::string& reason, + const std::string& input, + const std::string& expectation) : AronException(prettymethod, reason + ". Got: " + input + ". Expected: " + expectation) { - } - ValueNotValidException(const std::string& prettymethod, const std::string& reason, const std::string& input, const std::string& expectation, const Path& path) : - AronException(prettymethod, reason + ". Got: " + input + ". Expected: " + expectation, path) + ValueNotValidException(const std::string& prettymethod, + const std::string& reason, + const std::string& input, + const std::string& expectation, + const Path& path) : + AronException(prettymethod, + reason + ". Got: " + input + ". Expected: " + expectation, + path) { - } }; -} +} // namespace armarx::aron::error diff --git a/source/RobotAPI/libraries/aron/core/Path.cpp b/source/RobotAPI/libraries/aron/core/Path.cpp index 8d15ca0c810a94fb2972c451ca87cf01758088f7..c80e00f53c989b8aadd4618757aaa3c6a588dc4a 100644 --- a/source/RobotAPI/libraries/aron/core/Path.cpp +++ b/source/RobotAPI/libraries/aron/core/Path.cpp @@ -235,4 +235,38 @@ namespace armarx::aron ret.setDelimeter(delimeter); return ret; } + + bool + Path::hasPrefix(const Path& e) const + { + const auto& p = e.getPath(); + + if (path.size() < p.size()) + { + // prefix is impossible + return false; + } + + int i = 0; + for (const auto& el : path) + { + if (el != path[i++]) + { + return false; + } + } + + return true; + } + + bool + Path::hasDirectPrefix(const Path& e) const + { + const auto& p = e.getPath(); + if (p.size() + 1 != path.size()) + { + return false; + } + return hasPrefix(e); + } } // namespace armarx::aron diff --git a/source/RobotAPI/libraries/aron/core/Path.h b/source/RobotAPI/libraries/aron/core/Path.h index a88a00d84317ee20526d06334ebac5e829020591..888327fd929309cde7575133be27649b1a57bcd9 100644 --- a/source/RobotAPI/libraries/aron/core/Path.h +++ b/source/RobotAPI/libraries/aron/core/Path.h @@ -80,6 +80,9 @@ namespace armarx::aron Path withDetachedLastElement() const; Path getWithoutPrefix(const Path&) const; + bool hasPrefix(const Path&) const; + bool hasDirectPrefix(const Path&) const; + private: void append(const std::string&); diff --git a/source/RobotAPI/libraries/aron/core/data/rw/json/Data.cpp b/source/RobotAPI/libraries/aron/core/data/rw/json/Data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df60876fbdd629f5c43d7a3fd2efb3f2a28ba1f0 --- /dev/null +++ b/source/RobotAPI/libraries/aron/core/data/rw/json/Data.cpp @@ -0,0 +1,21 @@ +/* +* This file is part of ArmarX. +* +* ArmarX is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +* +* ArmarX is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see <http://www.gnu.org/licenses/>. +* +* @author Fabian Peller (fabian dot peller at kit dot edu) +* @copyright http://www.gnu.org/licenses/gpl-2.0.txt +* GNU General Public License +*/ + +#include "Data.h" diff --git a/source/RobotAPI/libraries/aron/core/data/variant/Factory.cpp b/source/RobotAPI/libraries/aron/core/data/variant/Factory.cpp index f458e3d9973bf34dd2dc13e49b5f505db4e403e4..3b7418fe505dc5a82e54285404ab44708f4d33c5 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/Factory.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/Factory.cpp @@ -33,7 +33,8 @@ namespace armarx::aron::data { // Access method - std::unique_ptr<data::Variant> VariantFactory::create(const data::dto::GenericDataPtr& aron, const Path& path) const + std::unique_ptr<data::Variant> + VariantFactory::create(const data::dto::GenericDataPtr& aron, const Path& path) const { // if aron is null ==> e.g. optional or ptr not set if (!aron) @@ -41,20 +42,47 @@ namespace armarx::aron::data return nullptr; }; + // compare versions + auto aronVersion = aron->VERSION; + if (aronVersion != armarx::aron::VERSION) + { + ARMARX_WARNING + << "Found inconsistencies in aron versions. This may lead to ice marshalling " + "exceptions. Please make sure to update the sender and receiver packages. " + << aronVersion << " != " << armarx::aron::VERSION; + } + auto descriptor = data::Aron2Descriptor(*aron); - switch(descriptor) + switch (descriptor) { - case data::Descriptor::LIST: return std::make_unique<data::List>(data::dto::ListPtr::dynamicCast(aron), path); - case data::Descriptor::DICT: return std::make_unique<data::Dict>(data::dto::DictPtr::dynamicCast(aron), path); - case data::Descriptor::NDARRAY: return std::make_unique<data::NDArray>(data::dto::NDArrayPtr::dynamicCast(aron), path); - case data::Descriptor::INT: return std::make_unique<data::Int>(data::dto::AronIntPtr::dynamicCast(aron), path); - case data::Descriptor::LONG: return std::make_unique<data::Long>(data::dto::AronLongPtr::dynamicCast(aron), path); - case data::Descriptor::FLOAT: return std::make_unique<data::Float>(data::dto::AronFloatPtr::dynamicCast(aron), path); - case data::Descriptor::DOUBLE: return std::make_unique<data::Double>(data::dto::AronDoublePtr::dynamicCast(aron), path); - case data::Descriptor::STRING: return std::make_unique<data::String>(data::dto::AronStringPtr::dynamicCast(aron), path); - case data::Descriptor::BOOL: return std::make_unique<data::Bool>(data::dto::AronBoolPtr::dynamicCast(aron), path); - case data::Descriptor::UNKNOWN: break; + case data::Descriptor::LIST: + return std::make_unique<data::List>(data::dto::ListPtr::dynamicCast(aron), path); + case data::Descriptor::DICT: + return std::make_unique<data::Dict>(data::dto::DictPtr::dynamicCast(aron), path); + case data::Descriptor::NDARRAY: + return std::make_unique<data::NDArray>(data::dto::NDArrayPtr::dynamicCast(aron), + path); + case data::Descriptor::INT: + return std::make_unique<data::Int>(data::dto::AronIntPtr::dynamicCast(aron), path); + case data::Descriptor::LONG: + return std::make_unique<data::Long>(data::dto::AronLongPtr::dynamicCast(aron), + path); + case data::Descriptor::FLOAT: + return std::make_unique<data::Float>(data::dto::AronFloatPtr::dynamicCast(aron), + path); + case data::Descriptor::DOUBLE: + return std::make_unique<data::Double>(data::dto::AronDoublePtr::dynamicCast(aron), + path); + case data::Descriptor::STRING: + return std::make_unique<data::String>(data::dto::AronStringPtr::dynamicCast(aron), + path); + case data::Descriptor::BOOL: + return std::make_unique<data::Bool>(data::dto::AronBoolPtr::dynamicCast(aron), + path); + case data::Descriptor::UNKNOWN: + break; } - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "", std::to_string((int) descriptor), path); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "", std::to_string((int)descriptor), path); } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/Variant.h b/source/RobotAPI/libraries/aron/core/data/variant/Variant.h index 1fab338ab2df57c267c841ac9297c533632bc46a..cc01ef83979306defb363ce9bdbf0089920ad747 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/Variant.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/Variant.h @@ -30,10 +30,9 @@ // ArmarX #include <RobotAPI/interface/aron.h> -#include <RobotAPI/libraries/aron/core/Path.h> -#include <RobotAPI/libraries/aron/core/Exception.h> #include <RobotAPI/libraries/aron/core/Descriptor.h> - +#include <RobotAPI/libraries/aron/core/Exception.h> +#include <RobotAPI/libraries/aron/core/Path.h> #include <RobotAPI/libraries/aron/core/type/variant/Variant.h> namespace armarx::aron::data @@ -66,16 +65,19 @@ namespace armarx::aron::data public: // constructors Variant() = delete; + Variant(const data::Descriptor& descriptor, const Path& path) : - descriptor(descriptor), - path(path) + descriptor(descriptor), path(path) { } + virtual ~Variant() = default; // operators virtual bool operator==(const Variant& other) const = 0; - bool operator==(const VariantPtr& other) const + + bool + operator==(const VariantPtr& other) const { if (!other) { @@ -90,25 +92,29 @@ namespace armarx::aron::data static VariantPtr FromAronDTO(const data::dto::GenericDataPtr&, const Path& = Path()); /// create a list of variants from a list of dto objects - static std::vector<VariantPtr> FromAronDTO(const std::vector<data::dto::GenericDataPtr>&, const Path& = Path()); + static std::vector<VariantPtr> FromAronDTO(const std::vector<data::dto::GenericDataPtr>&, + const Path& = Path()); /// return a list of dto objects from a list of variant objects static std::vector<data::dto::GenericDataPtr> ToAronDTO(const std::vector<VariantPtr>&); /// getter for the descriptor enum - data::Descriptor getDescriptor() const + data::Descriptor + getDescriptor() const { return descriptor; } /// get the path - Path getPath() const + Path + getPath() const { return path; } /// get the path as string - std::string pathToString() const + std::string + pathToString() const { return path.toString(); } @@ -116,6 +122,7 @@ namespace armarx::aron::data // virtual definitions /// get a pointer to a copy of this variant virtual VariantPtr cloneAsVariant() const = 0; + virtual VariantPtr cloneAsVariant(const Path& newPath) const = 0; /// get the children of a data variant virtual std::vector<VariantPtr> getChildren() const = 0; @@ -154,4 +161,4 @@ namespace armarx::aron::data template <class T> concept isVariant = std::is_base_of<Variant, T>::value; -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/complex/NDArray.cpp b/source/RobotAPI/libraries/aron/core/data/variant/complex/NDArray.cpp index 483088aa7ffaf706271072d5e13d55f26b8e4ec4..dbe828b0e92797b427b6f6f10ef16b5d46eb551d 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/complex/NDArray.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/complex/NDArray.cpp @@ -35,23 +35,31 @@ namespace armarx::aron::data { // constructors NDArray::NDArray(const Path& path) : - detail::ComplexVariant<data::dto::NDArray, NDArray>::ComplexVariant(data::Descriptor::NDARRAY, path) + detail::ComplexVariant<data::dto::NDArray, NDArray>::ComplexVariant( + data::Descriptor::NDARRAY, + path) { - } NDArray::NDArray(const data::dto::NDArrayPtr& o, const Path& path) : - detail::ComplexVariant<data::dto::NDArray, NDArray>::ComplexVariant(o, data::Descriptor::NDARRAY, path) + detail::ComplexVariant<data::dto::NDArray, NDArray>::ComplexVariant( + o, + data::Descriptor::NDARRAY, + path) { } - NDArray::NDArray(const std::vector<int>& dim, const std::string& t, const std::vector<unsigned char>& data, const Path& path) : + NDArray::NDArray(const std::vector<int>& dim, + const std::string& t, + const std::vector<unsigned char>& data, + const Path& path) : NDArray(data::dto::NDArrayPtr(new data::dto::NDArray(aron::VERSION, dim, t, data)), path) { } // operators - bool NDArray::operator==(const NDArray& other) const + bool + NDArray::operator==(const NDArray& other) const { const auto otherAron = other.toNDArrayDTO(); if (aron->shape != otherAron->shape) @@ -69,7 +77,9 @@ namespace armarx::aron::data } return true; } - bool NDArray::operator==(const NDArrayPtr& other) const + + bool + NDArray::operator==(const NDArrayPtr& other) const { if (!other) { @@ -78,8 +88,16 @@ namespace armarx::aron::data return *this == *other; } + NDArrayPtr + NDArray::clone(const Path& p) const + { + NDArrayPtr ret(new NDArray(getShape(), getType(), getDataAsVector(), p)); + return ret; + } + // static methods - NDArrayPtr NDArray::FromNDArrayDTO(const data::dto::NDArrayPtr& aron) + NDArrayPtr + NDArray::FromNDArrayDTO(const data::dto::NDArrayPtr& aron) { if (!aron) { @@ -88,13 +106,15 @@ namespace armarx::aron::data return std::make_shared<NDArray>(aron); } - data::dto::NDArrayPtr NDArray::ToNDArrayDTO(const NDArrayPtr& variant) + data::dto::NDArrayPtr + NDArray::ToNDArrayDTO(const NDArrayPtr& variant) { return variant ? variant->toNDArrayDTO() : nullptr; } // public member functions - DictPtr NDArray::getAsDict() const + DictPtr + NDArray::getAsDict() const { auto dict = std::make_shared<Dict>(); auto copy_this = FromAronDTO(toAronDTO(), getPath()); @@ -102,43 +122,51 @@ namespace armarx::aron::data return dict; } - unsigned char* NDArray::getData() const + unsigned char* + NDArray::getData() const { return aron->data.data(); } - void NDArray::setData(unsigned int elements, const unsigned char* src) + void + NDArray::setData(unsigned int elements, const unsigned char* src) { aron->data = std::vector<unsigned char>(elements); std::memcpy(aron->data.data(), src, elements); } - std::vector<unsigned char> NDArray::getDataAsVector() const + std::vector<unsigned char> + NDArray::getDataAsVector() const { return aron->data; } - std::vector<int> NDArray::getShape() const + std::vector<int> + NDArray::getShape() const { return aron->shape; } - void NDArray::setShape(const std::vector<int>& d) + void + NDArray::setShape(const std::vector<int>& d) { aron->shape = d; } - void NDArray::addToShape(int i) + void + NDArray::addToShape(int i) { aron->shape.push_back(i); } - std::string NDArray::getType() const + std::string + NDArray::getType() const { return aron->type; } - void NDArray::setType(const std::string& t) + void + NDArray::setType(const std::string& t) { if (t.empty()) { @@ -149,76 +177,85 @@ namespace armarx::aron::data aron->type = t; } - data::dto::NDArrayPtr NDArray::toNDArrayDTO() const + data::dto::NDArrayPtr + NDArray::toNDArrayDTO() const { return aron; } // virtual implementations - std::string NDArray::getShortName() const + std::string + NDArray::getShortName() const { return "NDArray"; } - std::string NDArray::getFullName() const + std::string + NDArray::getFullName() const { - return "armarx::aron::data::NDArray<" + simox::alg::to_string(aron->shape, ", ") + ", " + aron->type + ">"; + return "armarx::aron::data::NDArray<" + simox::alg::to_string(aron->shape, ", ") + ", " + + aron->type + ">"; } - type::VariantPtr NDArray::recalculateType() const + type::VariantPtr + NDArray::recalculateType() const { ARMARX_TRACE; throw error::NotImplementedYetException(__PRETTY_FUNCTION__); } - bool NDArray::fullfillsType(const type::VariantPtr& type) const + bool + NDArray::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; + if (!type) + return true; type::Descriptor typeDesc = type->getDescriptor(); switch (typeDesc) { - case type::Descriptor::MATRIX: - { - auto casted = type::Matrix::DynamicCastAndCheck(type); - ARMARX_TRACE; - return (aron->shape.size() == 3 && aron->shape[0] == casted->getRows() && aron->shape[1] == casted->getCols()); - } - case type::Descriptor::QUATERNION: - { - auto casted = type::Quaternion::DynamicCastAndCheck(type); - ARMARX_TRACE; - return (aron->shape.size() == 3 && aron->shape[0] == 1 && aron->shape[1] == 4); - } - case type::Descriptor::POINTCLOUD: - { - auto casted = type::PointCloud::DynamicCastAndCheck(type); - ARMARX_TRACE; - return (aron->shape.size() == 3); - } - case type::Descriptor::IMAGE: - { - auto casted = type::Image::DynamicCastAndCheck(type); - ARMARX_TRACE; - return (aron->shape.size() == 3); - } - case type::Descriptor::NDARRAY: - { - auto casted = type::NDArray::DynamicCastAndCheck(type); - ARMARX_TRACE; - return (aron->shape.size() == (unsigned int) casted->getNumberDimensions()); - } - default: - ARMARX_TRACE; - return false; + case type::Descriptor::MATRIX: + { + auto casted = type::Matrix::DynamicCastAndCheck(type); + ARMARX_TRACE; + return (aron->shape.size() == 3 && aron->shape[0] == casted->getRows() && + aron->shape[1] == casted->getCols()); + } + case type::Descriptor::QUATERNION: + { + auto casted = type::Quaternion::DynamicCastAndCheck(type); + ARMARX_TRACE; + return (aron->shape.size() == 3 && aron->shape[0] == 1 && aron->shape[1] == 4); + } + case type::Descriptor::POINTCLOUD: + { + auto casted = type::PointCloud::DynamicCastAndCheck(type); + ARMARX_TRACE; + return (aron->shape.size() == 3); + } + case type::Descriptor::IMAGE: + { + auto casted = type::Image::DynamicCastAndCheck(type); + ARMARX_TRACE; + return (aron->shape.size() == 3); + } + case type::Descriptor::NDARRAY: + { + auto casted = type::NDArray::DynamicCastAndCheck(type); + ARMARX_TRACE; + return (aron->shape.size() == (unsigned int)casted->getNumberDimensions()); + } + default: + ARMARX_TRACE; + return false; } } - std::string NDArray::DimensionsToString(const std::vector<int>& dimensions) + std::string + NDArray::DimensionsToString(const std::vector<int>& dimensions) { std::stringstream ss; ss << "(" << simox::alg::join(simox::alg::multi_to_string(dimensions), ", ") << ")"; return ss.str(); } -} // namespace armarx::aron::datanavigator +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/complex/NDArray.h b/source/RobotAPI/libraries/aron/core/data/variant/complex/NDArray.h index 068fd1a85cebc436ca6c1330c59c6d88ba9f183c..1cfc673719f6a4808a9f7e91bfc9b25a46cffb72 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/complex/NDArray.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/complex/NDArray.h @@ -26,8 +26,8 @@ // STD/STL #include <cstddef> #include <functional> -#include <memory> #include <map> +#include <memory> #include <numeric> #include <vector> @@ -40,22 +40,25 @@ // Types #include "../../../type/variant/ndarray/All.h" - namespace armarx::aron::data { class NDArray; using NDArrayPtr = std::shared_ptr<NDArray>; - class NDArray : - public detail::ComplexVariant<data::dto::NDArray, NDArray> + class NDArray : public detail::ComplexVariant<data::dto::NDArray, NDArray> { public: // constructors NDArray(const Path& path = Path()); NDArray(const data::dto::NDArrayPtr&, const Path& path = Path()); - NDArray(const std::vector<int>&, const std::string&, const std::vector<unsigned char>&, const Path& path = Path()); + NDArray(const std::vector<int>&, + const std::string&, + const std::vector<unsigned char>&, + const Path& path = Path()); // operators + using detail::ComplexVariant<data::dto::NDArray, NDArray>::operator==; + virtual bool operator==(const NDArray&) const override; bool operator==(const NDArrayPtr&) const override; @@ -84,11 +87,8 @@ namespace armarx::aron::data data::dto::NDArrayPtr toNDArrayDTO() const; // virtual implementations - NDArrayPtr clone() const override - { - NDArrayPtr ret(new NDArray(getShape(), getType(), getDataAsVector(), getPath())); - return ret; - } + using Base::clone; + NDArrayPtr clone(const Path& p) const override; virtual std::string getShortName() const override; virtual std::string getFullName() const override; @@ -96,13 +96,14 @@ namespace armarx::aron::data virtual type::VariantPtr recalculateType() const override; virtual bool fullfillsType(const type::VariantPtr&) const override; }; -} +} // namespace armarx::aron::data namespace armarx::aron { - template<typename... _Args> - aron::data::NDArrayPtr make_ndarray(_Args&&... args) + template <typename... _Args> + aron::data::NDArrayPtr + make_ndarray(_Args&&... args) { return std::make_shared<aron::data::NDArray>(args...); } -} +} // namespace armarx::aron diff --git a/source/RobotAPI/libraries/aron/core/data/variant/container/Dict.cpp b/source/RobotAPI/libraries/aron/core/data/variant/container/Dict.cpp index 9724ae6279a2b2a2140d5964d7d101f6e9fbabc8..21235afefb794e8c78443e840a240f56c6720b14 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/container/Dict.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/container/Dict.cpp @@ -36,12 +36,15 @@ namespace armarx::aron::data // constructors Dict::Dict(const Path& path) : - detail::ContainerVariant<data::dto::Dict, Dict>::ContainerVariant(data::Descriptor::DICT, path) + detail::ContainerVariant<data::dto::Dict, Dict>::ContainerVariant(data::Descriptor::DICT, + path) { } Dict::Dict(const data::dto::DictPtr& o, const Path& path) : - detail::ContainerVariant<data::dto::Dict, Dict>::ContainerVariant(o, data::Descriptor::DICT, path) + detail::ContainerVariant<data::dto::Dict, Dict>::ContainerVariant(o, + data::Descriptor::DICT, + path) { for (const auto& [key, dataPtr] : this->aron->elements) { @@ -49,8 +52,7 @@ namespace armarx::aron::data } } - Dict::Dict(const std::map<std::string, VariantPtr>& m, const Path& path) : - Dict(path) + Dict::Dict(const std::map<std::string, VariantPtr>& m, const Path& path) : Dict(path) { for (const auto& [key, dataPtr] : m) { @@ -59,7 +61,8 @@ namespace armarx::aron::data } // operators - bool Dict::operator==(const Dict& other) const + bool + Dict::operator==(const Dict& other) const { for (const auto& [key, nav] : childrenNavigators) { @@ -69,7 +72,7 @@ namespace armarx::aron::data } if (!nav) { - return !((bool) other.getElement(key)); + return !((bool)other.getElement(key)); } if (not(*nav == *other.getElement(key))) { @@ -78,7 +81,9 @@ namespace armarx::aron::data } return true; } - bool Dict::operator==(const DictPtr& other) const + + bool + Dict::operator==(const DictPtr& other) const { if (!other) { @@ -86,19 +91,42 @@ namespace armarx::aron::data } return *this == *other; } - VariantPtr Dict::operator[](const std::string& s) const + + VariantPtr + Dict::operator[](const std::string& s) const { return getElement(s); } - Dict& Dict::operator=(const Dict& other) + + Dict& + Dict::operator=(const Dict& other) { this->aron = other.aron; this->childrenNavigators = other.childrenNavigators; return *this; } + DictPtr + Dict::clone(const Path& p) const + { + DictPtr ret(new Dict(p)); + for (const auto& [key, val] : getElements()) + { + if (val) + { + ret->addElement(key, val->cloneAsVariant()); + } + else + { + ret->addElement(key, nullptr); + } + } + return ret; + } + // static methods - DictPtr Dict::FromAronDictDTO(const data::dto::DictPtr& aron) + DictPtr + Dict::FromAronDictDTO(const data::dto::DictPtr& aron) { if (!aron) { @@ -107,18 +135,21 @@ namespace armarx::aron::data return std::make_shared<Dict>(aron); } - data::dto::DictPtr Dict::ToAronDictDTO(const DictPtr& navigator) + data::dto::DictPtr + Dict::ToAronDictDTO(const DictPtr& navigator) { return navigator ? navigator->toAronDictDTO() : nullptr; } - data::dto::DictPtr Dict::toAronDictDTO() const + data::dto::DictPtr + Dict::toAronDictDTO() const { return aron; } // public member functions - std::vector<std::string> Dict::getAllKeys() const + std::vector<std::string> + Dict::getAllKeys() const { std::vector<std::string> ret; for (const auto& [key, _] : childrenNavigators) @@ -128,44 +159,83 @@ namespace armarx::aron::data return ret; } - std::string Dict::getAllKeysAsString() const + std::string + Dict::getAllKeysAsString() const { return simox::alg::to_string(getAllKeys(), ", "); } - void Dict::addElement(const std::string& key, const VariantPtr& data) + void + Dict::addElement(const std::string& key, const VariantPtr& data) { + // Please note that the data may be null (indicating that a non existing maybetype has been added) + if (hasElement(key)) { ARMARX_TRACE; - throw error::AronException(__PRETTY_FUNCTION__, "The key '"+key+"' already exists in a aron dict."); + throw error::AronException(__PRETTY_FUNCTION__, + "The key '" + key + "' already exists in a aron dict."); } setElement(key, data); } - bool Dict::hasElement(const std::string& key) const + void + Dict::addElementCopy(const std::string& key, const VariantPtr& data) + { + // Please note that the data may be null (indicating that a non existing maybetype has been added) + + if (hasElement(key)) + { + ARMARX_TRACE; + throw error::AronException(__PRETTY_FUNCTION__, + "The key '" + key + "' already exists in a aron dict."); + } + setElementCopy(key, data); + } + + bool + Dict::hasElement(const std::string& key) const { return childrenNavigators.count(key) > 0; } - VariantPtr Dict::getElement(const std::string& key) const + VariantPtr + Dict::getElement(const std::string& key) const { auto it = childrenNavigators.find(key); if (it == childrenNavigators.end()) { ARMARX_TRACE; - throw error::AronException(__PRETTY_FUNCTION__, "Could not find key '" + key + "'. But I found the following keys: [" + simox::alg::join(this->getAllKeys(), ", ") + "]", getPath()); + throw error::AronException(__PRETTY_FUNCTION__, + "Could not find key '" + key + + "'. But I found the following keys: [" + + simox::alg::join(this->getAllKeys(), ", ") + "]", + getPath()); } return it->second; } - std::map<std::string, VariantPtr> Dict::getElements() const + std::map<std::string, VariantPtr> + Dict::getElements() const { return childrenNavigators; } - void Dict::setElement(const std::string& key, const VariantPtr& data) + void + Dict::setElement(const std::string& key, const VariantPtr& data) { + // Please note that the data may be null (indicating that a non existing maybetype has been added) + + if (data) + { + const auto& p = data->getPath(); + if (not p.hasDirectPrefix(this->getPath())) + { + ARMARX_WARNING << "An element added to a dict does not have a correct path set. This " + "may cause errors. Please use setElemetCopy() instead."; + } + } + this->childrenNavigators[key] = data; if (data) { @@ -177,44 +247,66 @@ namespace armarx::aron::data } } - void Dict::removeElement(const std::string& key) + void + Dict::setElementCopy(const std::string& key, const VariantPtr& data) + { + // Please note that the data may be null (indicating that a non existing maybetype has been added) + + VariantPtr copy = nullptr; + if (data) + { + Path newPath = getPath().withElement(key); + copy = data->cloneAsVariant(newPath); + } + setElement(key, copy); + } + + void + Dict::removeElement(const std::string& key) { childrenNavigators.erase(key); aron->elements.erase(key); } - void Dict::clear() + void + Dict::clear() { childrenNavigators.clear(); aron->elements.clear(); } - VariantPtr Dict::at(const std::string& s) const + VariantPtr + Dict::at(const std::string& s) const { return getElement(s); } // virtual implementations - std::string Dict::getShortName() const + std::string + Dict::getShortName() const { return "Dict"; } - std::string Dict::getFullName() const + std::string + Dict::getFullName() const { return "armarx::aron::data::Dict"; } // TODO - type::VariantPtr Dict::recalculateType() const + type::VariantPtr + Dict::recalculateType() const { ARMARX_TRACE; throw error::NotImplementedYetException(__PRETTY_FUNCTION__); } - bool Dict::fullfillsType(const type::VariantPtr& type) const + bool + Dict::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; + if (!type) + return true; type::Descriptor typeDesc = type->getDescriptor(); @@ -259,7 +351,7 @@ namespace armarx::aron::data auto dictTypeNav = type::Dict::DynamicCastAndCheck(type); for (const auto& [key, nav] : childrenNavigators) { - (void) key; + (void)key; auto childTypeNav = dictTypeNav->getAcceptedType(); if (!nav) { @@ -287,7 +379,8 @@ namespace armarx::aron::data } } - std::vector<VariantPtr> Dict::getChildren() const + std::vector<VariantPtr> + Dict::getChildren() const { std::vector<VariantPtr> ret(childrenNavigators.size()); for (const auto& [key, nav] : childrenNavigators) @@ -297,23 +390,27 @@ namespace armarx::aron::data return ret; } - size_t Dict::childrenSize() const + size_t + Dict::childrenSize() const { return childrenNavigators.size(); } - VariantPtr Dict::navigateAbsolute(const Path& path) const + VariantPtr + Dict::navigateAbsolute(const Path& path) const { if (!path.hasElement()) { ARMARX_TRACE; - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate without a valid path", path); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not navigate without a valid path", path); } std::string el = path.getFirstElement(); if (!hasElement(el)) { ARMARX_TRACE; - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); } if (path.size() == 1) @@ -326,9 +423,12 @@ namespace armarx::aron::data if (!childrenNavigators.at(el)) { ARMARX_TRACE; - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate into a NULL member. Seems like the member is optional and not set.", next); + throw error::AronException(__PRETTY_FUNCTION__, + "Could not navigate into a NULL member. Seems like the " + "member is optional and not set.", + next); } return childrenNavigators.at(el)->navigateAbsolute(next); } } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/container/Dict.h b/source/RobotAPI/libraries/aron/core/data/variant/container/Dict.h index 5006a0c97a5b830f7d0998024ce2113d38af59a5..f6c2d93955f53af91a04364ada5f3da724ae7033 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/container/Dict.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/container/Dict.h @@ -24,25 +24,24 @@ #pragma once // STD/STL -#include <memory> #include <map> +#include <memory> #include <utility> // Base class #include "../detail/ContainerVariant.h" // ArmarX +#include "../../../type/variant/any/AnyObject.h" #include "../../../type/variant/container/Dict.h" #include "../../../type/variant/container/Object.h" -#include "../../../type/variant/any/AnyObject.h" namespace armarx::aron::data { class Dict; typedef std::shared_ptr<Dict> DictPtr; - class Dict : - public detail::ContainerVariant<data::dto::Dict, Dict> + class Dict : public detail::ContainerVariant<data::dto::Dict, Dict> { public: // constructors @@ -51,6 +50,8 @@ namespace armarx::aron::data Dict(const std::map<std::string, VariantPtr>&, const Path& path = Path()); // operators + using detail::ContainerVariant<data::dto::Dict, Dict>::operator==; + bool operator==(const Dict&) const override; bool operator==(const DictPtr&) const override; VariantPtr operator[](const std::string&) const; @@ -65,8 +66,10 @@ namespace armarx::aron::data std::string getAllKeysAsString() const; void addElement(const std::string& key, const VariantPtr& = nullptr); + void addElementCopy(const std::string& key, const VariantPtr& = nullptr); bool hasElement(const std::string&) const; void setElement(const std::string&, const VariantPtr& = nullptr); + void setElementCopy(const std::string&, const VariantPtr& = nullptr); VariantPtr getElement(const std::string&) const; std::map<std::string, VariantPtr> getElements() const; @@ -74,16 +77,9 @@ namespace armarx::aron::data void removeElement(const std::string& key); void clear(); - // virtual implementations - DictPtr clone() const override - { - DictPtr ret(new Dict(getPath())); - for (const auto& [key, val] : getElements()) - { - ret->addElement(key, val->cloneAsVariant()); - } - return ret; - } + // virtual implementations + using Base::clone; + DictPtr clone(const Path& p) const override; std::string getShortName() const override; std::string getFullName() const override; @@ -99,13 +95,14 @@ namespace armarx::aron::data // members std::map<std::string, VariantPtr> childrenNavigators; }; -} +} // namespace armarx::aron::data namespace armarx::aron { - template<typename... _Args> - aron::data::DictPtr make_dict(_Args&&... args) + template <typename... _Args> + aron::data::DictPtr + make_dict(_Args&&... args) { return std::make_shared<aron::data::Dict>(args...); } -} +} // namespace armarx::aron diff --git a/source/RobotAPI/libraries/aron/core/data/variant/container/List.cpp b/source/RobotAPI/libraries/aron/core/data/variant/container/List.cpp index c53b51ee1b04c3e903b4ddd718b9793d75303412..83e23f76f43ca4a7ebf8b057c51142256b5ba618 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/container/List.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/container/List.cpp @@ -37,12 +37,15 @@ namespace armarx::aron::data { // constructors List::List(const Path& path) : - detail::ContainerVariant<data::dto::List, List>::ContainerVariant(data::Descriptor::LIST, path) + detail::ContainerVariant<data::dto::List, List>::ContainerVariant(data::Descriptor::LIST, + path) { } List::List(const data::dto::ListPtr& l, const Path& path) : - detail::ContainerVariant<data::dto::List, List>::ContainerVariant(l, data::Descriptor::LIST, path) + detail::ContainerVariant<data::dto::List, List>::ContainerVariant(l, + data::Descriptor::LIST, + path) { unsigned int i = 0; for (const auto& dataPtr : l->elements) @@ -51,8 +54,7 @@ namespace armarx::aron::data } } - List::List(const std::vector<VariantPtr>& n, const Path& path) : - List(path) + List::List(const std::vector<VariantPtr>& n, const Path& path) : List(path) { for (const auto& dataPtr : n) { @@ -61,7 +63,8 @@ namespace armarx::aron::data } // operators - bool List::operator==(const List& other) const + bool + List::operator==(const List& other) const { unsigned int i = 0; for (const auto& nav : childrenNavigators) @@ -85,7 +88,9 @@ namespace armarx::aron::data } return true; } - bool List::operator==(const ListPtr& other) const + + bool + List::operator==(const ListPtr& other) const { if (!other) { @@ -94,8 +99,20 @@ namespace armarx::aron::data return *this == *other; } + ListPtr + List::clone(const Path& p) const + { + ListPtr ret(new List(p)); + for (const auto& val : getElements()) + { + ret->addElement(val->cloneAsVariant()); + } + return ret; + } + // static methods - ListPtr List::FromAronListDTO(const data::dto::ListPtr& aron) + ListPtr + List::FromAronListDTO(const data::dto::ListPtr& aron) { if (!aron) { @@ -104,13 +121,15 @@ namespace armarx::aron::data return std::make_shared<List>(aron); } - data::dto::ListPtr List::ToAronListDTO(const ListPtr& navigator) + data::dto::ListPtr + List::ToAronListDTO(const ListPtr& navigator) { return navigator ? navigator->toAronListDTO() : nullptr; } // public member functions - DictPtr List::getAsDict() const + DictPtr + List::getAsDict() const { auto dict = std::make_shared<Dict>(); auto copy_this = FromAronDTO(toAronDTO(), getPath()); @@ -118,17 +137,22 @@ namespace armarx::aron::data return dict; } - void List::addElement(const VariantPtr& n) + void + List::addElement(const VariantPtr& n) { setElement(aron->elements.size(), n); } - void List::setElement(unsigned int i, const VariantPtr& n) + void + List::setElement(unsigned int i, const VariantPtr& n) { if (i > aron->elements.size()) { ARMARX_TRACE; - throw error::AronException(__PRETTY_FUNCTION__, "Cannot set a listelement at index " + std::to_string(i) + " because this list has size " + std::to_string(aron->elements.size())); + throw error::AronException(__PRETTY_FUNCTION__, + "Cannot set a listelement at index " + std::to_string(i) + + " because this list has size " + + std::to_string(aron->elements.size())); } if (i == aron->elements.size()) @@ -157,66 +181,81 @@ namespace armarx::aron::data } } - bool List::hasElement(unsigned int i) const + bool + List::hasElement(unsigned int i) const { return i < childrenNavigators.size(); } - VariantPtr List::getElement(unsigned int i) const + VariantPtr + List::getElement(unsigned int i) const { if (i >= childrenNavigators.size()) { ARMARX_TRACE; - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The index is out of bounds (size = " + std::to_string(childrenNavigators.size()) + ")", std::to_string(i), getPath()); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "The index is out of bounds (size = " + + std::to_string(childrenNavigators.size()) + ")", + std::to_string(i), + getPath()); } return childrenNavigators[i]; } - std::vector<VariantPtr> List::getElements() const + std::vector<VariantPtr> + List::getElements() const { return childrenNavigators; } - void List::removeElement(unsigned int i) + void + List::removeElement(unsigned int i) { // Use with care since this function will not work in a loop with increasing indexes - i = std::min((unsigned int) childrenNavigators.size()-1, i); + i = std::min((unsigned int)childrenNavigators.size() - 1, i); childrenNavigators.erase(childrenNavigators.begin() + i); aron->elements.erase(aron->elements.begin() + i); } - void List::clear() + void + List::clear() { childrenNavigators.clear(); aron->elements.clear(); } - data::dto::ListPtr List::toAronListDTO() const + data::dto::ListPtr + List::toAronListDTO() const { return aron; } // virtual implementations - std::string List::getShortName() const + std::string + List::getShortName() const { return "List"; } - std::string List::getFullName() const + std::string + List::getFullName() const { return "armarx::aron::data::List"; } // TODO - type::VariantPtr List::recalculateType() const + type::VariantPtr + List::recalculateType() const { ARMARX_TRACE; throw error::NotImplementedYetException(__PRETTY_FUNCTION__); } - bool List::fullfillsType(const type::VariantPtr& type) const + bool + List::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; + if (!type) + return true; type::Descriptor typeDesc = type->getDescriptor(); switch (typeDesc) @@ -310,7 +349,8 @@ namespace armarx::aron::data return false; } ARMARX_TRACE; - return childrenNavigators[0]->fullfillsType(firstChildTypeNav) && childrenNavigators[1]->fullfillsType(secondChildTypeNav); + return childrenNavigators[0]->fullfillsType(firstChildTypeNav) && + childrenNavigators[1]->fullfillsType(secondChildTypeNav); } default: ARMARX_TRACE; @@ -318,27 +358,35 @@ namespace armarx::aron::data } } - std::vector<VariantPtr> List::getChildren() const + std::vector<VariantPtr> + List::getChildren() const { return childrenNavigators; } - size_t List::childrenSize() const + size_t + List::childrenSize() const { return childrenNavigators.size(); } - VariantPtr List::navigateAbsolute(const Path& path) const + VariantPtr + List::navigateAbsolute(const Path& path) const { if (!path.hasElement()) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate without a valid path. The path was empty."); + throw error::AronException( + __PRETTY_FUNCTION__, + "Could not navigate without a valid path. The path was empty."); } unsigned int i = std::stoi(path.getFirstElement()); if (!hasElement(i)) { ARMARX_TRACE; - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not find an element of a path.", std::to_string(i), std::to_string(childrenSize())); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "Could not find an element of a path.", + std::to_string(i), + std::to_string(childrenSize())); } if (path.size() == 1) @@ -351,9 +399,12 @@ namespace armarx::aron::data if (!childrenNavigators.at(i)) { ARMARX_TRACE; - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate into a NULL member. Seems like the member is optional and not set.", next); + throw error::AronException(__PRETTY_FUNCTION__, + "Could not navigate into a NULL member. Seems like the " + "member is optional and not set.", + next); } return childrenNavigators.at(i)->navigateAbsolute(next); } } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/container/List.h b/source/RobotAPI/libraries/aron/core/data/variant/container/List.h index 142f42ee66940c6a5fa6d99a616d4845719234e2..74d33da9af8fb260a9fe098221a1188a52d01cdd 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/container/List.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/container/List.h @@ -30,18 +30,17 @@ #include "../detail/SpecializedVariant.h" // ArmarX -#include "Dict.h" #include "../../../type/variant/container/List.h" #include "../../../type/variant/container/Pair.h" #include "../../../type/variant/container/Tuple.h" +#include "Dict.h" namespace armarx::aron::data { class List; typedef std::shared_ptr<List> ListPtr; - class List : - public detail::ContainerVariant<data::dto::List, List> + class List : public detail::ContainerVariant<data::dto::List, List> { public: // constructors @@ -50,6 +49,8 @@ namespace armarx::aron::data List(const std::vector<VariantPtr>&, const Path& path = Path()); // operators + using detail::ContainerVariant<data::dto::List, List>::operator==; + bool operator==(const List&) const override; bool operator==(const ListPtr&) const override; @@ -73,15 +74,7 @@ namespace armarx::aron::data void clear(); // virtual implementations - ListPtr clone() const override - { - ListPtr ret(new List(getPath())); - for (const auto& val : getElements()) - { - ret->addElement(val->cloneAsVariant()); - } - return ret; - } + ListPtr clone(const Path& p) const override; std::string getShortName() const override; std::string getFullName() const override; @@ -96,13 +89,14 @@ namespace armarx::aron::data private: std::vector<VariantPtr> childrenNavigators; }; -} +} // namespace armarx::aron::data namespace armarx::aron { - template<typename... _Args> - aron::data::ListPtr make_list(_Args&&... args) + template <typename... _Args> + aron::data::ListPtr + make_list(_Args&&... args) { return std::make_shared<aron::data::List>(args...); } -} +} // namespace armarx::aron diff --git a/source/RobotAPI/libraries/aron/core/data/variant/detail/ComplexVariant.h b/source/RobotAPI/libraries/aron/core/data/variant/detail/ComplexVariant.h index 868b7a8df691a47458d1f8a73b319034627cbfb7..afececc9372a6b5494ac2d686594b553b4752233 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/detail/ComplexVariant.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/detail/ComplexVariant.h @@ -33,29 +33,36 @@ namespace armarx::aron::data::detail { - template<typename AronDataT, typename DerivedT> - class ComplexVariant : - public SpecializedVariantBase<AronDataT, DerivedT> + template <typename AronDataT, typename DerivedT> + class ComplexVariant : public SpecializedVariantBase<AronDataT, DerivedT> { public: - using SpecializedVariantBase<AronDataT, DerivedT>::SpecializedVariantBase; + using Base = SpecializedVariantBase<AronDataT, DerivedT>; + using Base::SpecializedVariantBase; virtual ~ComplexVariant() = default; // virtual implementations - VariantPtr navigateAbsolute(const Path &path) const override + VariantPtr + navigateAbsolute(const Path& path) const override { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate through a non container navigator. The input path was: " + path.toString(), Variant::getPath()); + throw error::AronException( + __PRETTY_FUNCTION__, + "Could not navigate through a non container navigator. The input path was: " + + path.toString(), + Variant::getPath()); } - std::vector<VariantPtr> getChildren() const override + std::vector<VariantPtr> + getChildren() const override { return {}; } - size_t childrenSize() const override + size_t + childrenSize() const override { return 0; } }; -} +} // namespace armarx::aron::data::detail diff --git a/source/RobotAPI/libraries/aron/core/data/variant/detail/ContainerVariant.h b/source/RobotAPI/libraries/aron/core/data/variant/detail/ContainerVariant.h index 69fff7c78e637d961eebad2253327be056f4b7a0..042ef1227918ce2930c1df755958633daf8c26fa 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/detail/ContainerVariant.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/detail/ContainerVariant.h @@ -33,13 +33,13 @@ namespace armarx::aron::data::detail { - template<typename AronDataT, typename DerivedT> - class ContainerVariant : - public SpecializedVariantBase<AronDataT, DerivedT> + template <typename AronDataT, typename DerivedT> + class ContainerVariant : public SpecializedVariantBase<AronDataT, DerivedT> { public: - using SpecializedVariantBase<AronDataT, DerivedT>::SpecializedVariantBase; + using Base = SpecializedVariantBase<AronDataT, DerivedT>; + using Base::SpecializedVariantBase; virtual ~ContainerVariant() = default; }; -} +} // namespace armarx::aron::data::detail diff --git a/source/RobotAPI/libraries/aron/core/data/variant/detail/PrimitiveVariant.h b/source/RobotAPI/libraries/aron/core/data/variant/detail/PrimitiveVariant.h index 3b36c6310386a27122ae7607e41a137fc6420833..69cabb5ba160f3abef84d331b971c4146d866c29 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/detail/PrimitiveVariant.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/detail/PrimitiveVariant.h @@ -36,19 +36,21 @@ namespace armarx::aron::data::detail { - template<typename AronDataT, typename ValueT, typename DerivedT> - class PrimitiveVariant : - public SpecializedVariantBase<AronDataT, DerivedT> + template <typename AronDataT, typename ValueT, typename DerivedT> + class PrimitiveVariant : public SpecializedVariantBase<AronDataT, DerivedT> { public: + using Base = SpecializedVariantBase<AronDataT, DerivedT>; using PointerType = std::shared_ptr<DerivedT>; using ValueType = ValueT; public: - using SpecializedVariantBase<AronDataT, DerivedT>::SpecializedVariantBase; + using Base::SpecializedVariantBase; - PrimitiveVariant(const ValueT& v, const data::Descriptor descriptor, const Path& path = Path()): - SpecializedVariantBase<AronDataT, DerivedT>(descriptor, path) + PrimitiveVariant(const ValueT& v, + const data::Descriptor descriptor, + const Path& path = Path()) : + Base(descriptor, path) { this->aron->value = v; } @@ -60,7 +62,8 @@ namespace armarx::aron::data::detail return this->aron->value; } - DerivedT& operator=(const ValueT& x) + DerivedT& + operator=(const ValueT& x) { this->aron->value = x; return *this; @@ -76,23 +79,33 @@ namespace armarx::aron::data::detail virtual void fromString(const std::string& setter) = 0; // virtual implementations - VariantPtr navigateAbsolute(const Path &path) const override + VariantPtr + navigateAbsolute(const Path& path) const override { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate through a non container navigator. The input path was: " + path.toString(), Variant::getPath()); + throw error::AronException( + __PRETTY_FUNCTION__, + "Could not navigate through a non container navigator. The input path was: " + + path.toString(), + Variant::getPath()); } - PointerType clone() const override + using Base::clone; + + PointerType + clone(const Path& newPath) const override { - PointerType ret(new DerivedT(getValue(), this->getPath())); + PointerType ret(new DerivedT(getValue(), newPath)); return ret; } - std::vector<VariantPtr> getChildren() const override + std::vector<VariantPtr> + getChildren() const override { return {}; } - size_t childrenSize() const override + size_t + childrenSize() const override { return 0; } @@ -100,7 +113,8 @@ namespace armarx::aron::data::detail // static methods /* public member functions */ - DictPtr getAsDict() const + DictPtr + getAsDict() const { auto dict = std::make_shared<Dict>(); auto copy_this = FromAronDTO(this->toAronDTO(), this->getPath()); @@ -108,18 +122,22 @@ namespace armarx::aron::data::detail return dict; } - void setValue(const ValueT& x) + void + setValue(const ValueT& x) { this->aron->value = x; } - ValueT getValue() const + + ValueT + getValue() const { return this->aron->value; } - ValueT& getValue() + ValueT& + getValue() { return this->aron->value; } }; -} +} // namespace armarx::aron::data::detail diff --git a/source/RobotAPI/libraries/aron/core/data/variant/detail/SpecializedVariant.h b/source/RobotAPI/libraries/aron/core/data/variant/detail/SpecializedVariant.h index d7e6e4a55cd9e96fed989b8a1a4f60e6a1c5d8b2..1ce3a07fae4061b8fa99f3777c4b4ab321803fed 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/detail/SpecializedVariant.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/detail/SpecializedVariant.h @@ -35,11 +35,11 @@ namespace armarx::aron::data::detail { - template<typename AronDataT, typename DerivedT> - class SpecializedVariantBase : - public data::Variant + template <typename AronDataT, typename DerivedT> + class SpecializedVariantBase : public data::Variant { public: + using Base = data::Variant; using PointerType = std::shared_ptr<DerivedT>; using AronDataType = AronDataT; @@ -47,15 +47,15 @@ namespace armarx::aron::data::detail SpecializedVariantBase() = delete; SpecializedVariantBase(const data::Descriptor descriptor, const Path& path = Path()) : - Variant(descriptor, path), - aron(new AronDataType()) + Variant(descriptor, path), aron(new AronDataType()) { aron->VERSION = aron::VERSION; } - SpecializedVariantBase(const typename AronDataType::PointerType& o, const data::Descriptor descriptor, const Path& path = Path()) : - Variant(descriptor, path), - aron(o) + SpecializedVariantBase(const typename AronDataType::PointerType& o, + const data::Descriptor descriptor, + const Path& path = Path()) : + Variant(descriptor, path), aron(o) { ARMARX_CHECK_NOT_NULL(aron); } @@ -68,7 +68,8 @@ namespace armarx::aron::data::detail return aron; } - bool operator==(const Variant& other) const override + bool + operator==(const Variant& other) const override { const auto& n = DerivedT::DynamicCast(other); return *this == n; @@ -78,43 +79,61 @@ namespace armarx::aron::data::detail virtual bool operator==(const PointerType& other) const = 0; // new interface methods - virtual PointerType clone() const = 0; + virtual PointerType + clone() const + { + return clone(getPath()); + } + + virtual PointerType clone(const Path& newPath) const = 0; // virtual implementations - VariantPtr cloneAsVariant() const override + VariantPtr + cloneAsVariant() const override { return clone(); } - data::dto::GenericDataPtr toAronDTO() const override + VariantPtr + cloneAsVariant(const Path& newPath) const override + { + return clone(newPath); + } + + data::dto::GenericDataPtr + toAronDTO() const override { return aron; } - VariantPtr navigateRelative(const Path& path) const override + VariantPtr + navigateRelative(const Path& path) const override { Path absoluteFromHere = path.getWithoutPrefix(getPath()); return navigateAbsolute(absoluteFromHere); } - // static methods - static PointerType DynamicCast(const VariantPtr& n) + static PointerType + DynamicCast(const VariantPtr& n) { return std::dynamic_pointer_cast<DerivedT>(n); } - static DerivedT& DynamicCast(Variant& n) + static DerivedT& + DynamicCast(Variant& n) { return dynamic_cast<DerivedT&>(n); } - static const DerivedT& DynamicCast(const Variant& n) + static const DerivedT& + DynamicCast(const Variant& n) { return dynamic_cast<const DerivedT&>(n); } - static PointerType DynamicCastAndCheck(const VariantPtr& n) + static PointerType + DynamicCastAndCheck(const VariantPtr& n) { if (!n) { @@ -122,13 +141,17 @@ namespace armarx::aron::data::detail } PointerType casted = DerivedT::DynamicCast(n); - ARMARX_CHECK_NOT_NULL(casted) << "The path was: " << n->getPath().toString() << ".\n" - << "It has the descriptor: '" << data::defaultconversion::string::Descriptor2String.at(n->getDescriptor()) << "'.\n" - << "And the typeid: " << typeid(n).name() << ". Tried to cast to " << typeid(PointerType).name(); + ARMARX_CHECK_NOT_NULL(casted) + << "The path was: " << n->getPath().toString() << ".\n" + << "It has the descriptor: '" + << data::defaultconversion::string::Descriptor2String.at(n->getDescriptor()) + << "'.\n" + << "And the typeid: " << typeid(n).name() << ". Tried to cast to " + << typeid(PointerType).name(); return casted; } protected: typename AronDataType::PointerType aron; }; -} +} // namespace armarx::aron::data::detail diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Bool.cpp b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Bool.cpp index 2f7fe6fc8e486c43c32875c1cf072e721146c402..ed29f88c343ba218155b7510c28e496882349fe2 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Bool.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Bool.cpp @@ -27,22 +27,31 @@ namespace armarx::aron::data { /* constructors */ Bool::Bool(const data::dto::AronBoolPtr& o, const Path& path) : - detail::PrimitiveVariant<data::dto::AronBool, bool, Bool>::PrimitiveVariant(o, data::Descriptor::BOOL, path) + detail::PrimitiveVariant<data::dto::AronBool, bool, Bool>::PrimitiveVariant( + o, + data::Descriptor::BOOL, + path) { } Bool::Bool(const Path& path) : - detail::PrimitiveVariant<data::dto::AronBool, bool, Bool>::PrimitiveVariant(data::Descriptor::BOOL, path) + detail::PrimitiveVariant<data::dto::AronBool, bool, Bool>::PrimitiveVariant( + data::Descriptor::BOOL, + path) { } Bool::Bool(const bool d, const Path& path) : - detail::PrimitiveVariant<data::dto::AronBool, bool, Bool>::PrimitiveVariant(d, data::Descriptor::BOOL, path) + detail::PrimitiveVariant<data::dto::AronBool, bool, Bool>::PrimitiveVariant( + d, + data::Descriptor::BOOL, + path) { } /* operators */ - bool Bool::operator==(const Bool& other) const + bool + Bool::operator==(const Bool& other) const { const auto& otherAron = other.toAronBoolDTO(); if (aron->value != otherAron->value) @@ -51,7 +60,9 @@ namespace armarx::aron::data } return true; } - bool Bool::operator==(const BoolPtr& other) const + + bool + Bool::operator==(const BoolPtr& other) const { if (!other) { @@ -60,9 +71,9 @@ namespace armarx::aron::data return *this == *other; } - /* static methods */ - BoolPtr Bool::FromAronBoolDTO(const data::dto::AronBoolPtr& aron) + BoolPtr + Bool::FromAronBoolDTO(const data::dto::AronBoolPtr& aron) { if (!aron) { @@ -71,19 +82,22 @@ namespace armarx::aron::data return std::make_shared<Bool>(aron); } - data::dto::AronBoolPtr Bool::ToAronBoolDTO(const BoolPtr& navigator) + data::dto::AronBoolPtr + Bool::ToAronBoolDTO(const BoolPtr& navigator) { return navigator ? navigator->toAronBoolDTO() : nullptr; } /* public member functions */ - data::dto::AronBoolPtr Bool::toAronBoolDTO() const + data::dto::AronBoolPtr + Bool::toAronBoolDTO() const { return aron; } /* virtual implementations */ - void Bool::fromString(const std::string& setter) + void + Bool::fromString(const std::string& setter) { if (setter == "true" || setter == "1" || setter == "yes") { @@ -96,27 +110,36 @@ namespace armarx::aron::data else { ARMARX_TRACE; - throw error::AronException(__PRETTY_FUNCTION__, "Could not set from string. Got: '" + setter + "'"); + throw error::AronException(__PRETTY_FUNCTION__, + "Could not set from string. Got: '" + setter + "'"); } } - std::string Bool::getShortName() const + std::string + Bool::getShortName() const { return "Bool"; } - std::string Bool::getFullName() const + + std::string + Bool::getFullName() const { return "armarx::aron::data::Bool"; } - bool Bool::fullfillsType(const type::VariantPtr& type) const + bool + Bool::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; + if (!type) + return true; return type->getDescriptor() == type::Descriptor::BOOL; } - type::VariantPtr Bool::recalculateType() const + type::VariantPtr + Bool::recalculateType() const { - return std::make_shared<type::Bool>(getPath()); + ARMARX_TRACE; + throw error::NotImplementedYetException(__PRETTY_FUNCTION__); + //return std::make_shared<type::Bool>(getPath()); } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Bool.h b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Bool.h index 5e07b8a8e33577b268ea8ae8366291664b3012e6..94349fb2c608936b6e395a1af2090713e8372148 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Bool.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Bool.h @@ -48,6 +48,8 @@ namespace armarx::aron::data Bool(const bool, const Path& = Path()); // operators + using detail::PrimitiveVariant<data::dto::AronBool, bool, Bool>::operator==; + bool operator==(const Bool& other) const override; bool operator==(const BoolPtr&) const override; diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Double.cpp b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Double.cpp index 87ea9eeacbabc0356f13476714860756424f457d..66b23d4e11892841f17fbb520a61b80e54a498e2 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Double.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Double.cpp @@ -31,22 +31,31 @@ namespace armarx::aron::data { /* constructors */ Double::Double(const data::dto::AronDoublePtr& o, const Path& path) : - detail::PrimitiveVariant<data::dto::AronDouble, double, Double>::PrimitiveVariant(o, data::Descriptor::DOUBLE, path) + detail::PrimitiveVariant<data::dto::AronDouble, double, Double>::PrimitiveVariant( + o, + data::Descriptor::DOUBLE, + path) { } Double::Double(const Path& path) : - detail::PrimitiveVariant<data::dto::AronDouble, double, Double>::PrimitiveVariant(data::Descriptor::DOUBLE, path) + detail::PrimitiveVariant<data::dto::AronDouble, double, Double>::PrimitiveVariant( + data::Descriptor::DOUBLE, + path) { } Double::Double(const double d, const Path& path) : - detail::PrimitiveVariant<data::dto::AronDouble, double, Double>::PrimitiveVariant(d, data::Descriptor::DOUBLE, path) + detail::PrimitiveVariant<data::dto::AronDouble, double, Double>::PrimitiveVariant( + d, + data::Descriptor::DOUBLE, + path) { } /* operators */ - bool Double::operator==(const Double& other) const + bool + Double::operator==(const Double& other) const { const auto& otherAron = other.toAronDoubleDTO(); if (this->aron->value != otherAron->value) @@ -55,7 +64,9 @@ namespace armarx::aron::data } return true; } - bool Double::operator==(const DoublePtr& other) const + + bool + Double::operator==(const DoublePtr& other) const { if (!other) { @@ -65,7 +76,8 @@ namespace armarx::aron::data } /* static methods */ - DoublePtr Double::FromAronDoubleDTO(const data::dto::AronDoublePtr& aron) + DoublePtr + Double::FromAronDoubleDTO(const data::dto::AronDoublePtr& aron) { if (!aron) { @@ -74,41 +86,51 @@ namespace armarx::aron::data return std::make_shared<Double>(aron); } - data::dto::AronDoublePtr Double::ToAronDoubleDTO(const DoublePtr& navigator) + data::dto::AronDoublePtr + Double::ToAronDoubleDTO(const DoublePtr& navigator) { return navigator ? navigator->toAronDoubleDTO() : nullptr; } - /* public member functions */ - data::dto::AronDoublePtr Double::toAronDoubleDTO() const + data::dto::AronDoublePtr + Double::toAronDoubleDTO() const { return aron; } /* virtual implementations */ - void Double::fromString(const std::string& setter) + void + Double::fromString(const std::string& setter) { setValue(std::stod(setter)); } - std::string Double::getShortName() const + std::string + Double::getShortName() const { return "Double"; } - std::string Double::getFullName() const + + std::string + Double::getFullName() const { return "armarx::aron::data::Double"; } - bool Double::fullfillsType(const type::VariantPtr& type) const + bool + Double::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; + if (!type) + return true; return type->getDescriptor() == type::Descriptor::DOUBLE; } - type::VariantPtr Double::recalculateType() const + type::VariantPtr + Double::recalculateType() const { - return std::make_shared<type::Double>(getPath()); + ARMARX_TRACE; + throw error::NotImplementedYetException(__PRETTY_FUNCTION__); + //return std::make_shared<type::Double>(getPath()); } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Double.h b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Double.h index fb7a6880a9782397239243d38939d1ac22688fd4..59447e7def921da7face8213f24372bf5d5865df 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Double.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Double.h @@ -48,6 +48,8 @@ namespace armarx::aron::data Double(const double, const Path& = Path()); /* operators */ + using detail::PrimitiveVariant<data::dto::AronDouble, double, Double>::operator==; + bool operator==(const Double&) const override; bool operator==(const DoublePtr&) const override; diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Float.cpp b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Float.cpp index 8dd7721c4adf5e5e0ec86b04325ea6971b8413ad..26d08b4b50d88fae2045b9b1bcbcb6ea3fb237de 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Float.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Float.cpp @@ -27,22 +27,31 @@ namespace armarx::aron::data { /* constructors */ Float::Float(const data::dto::AronFloatPtr& o, const Path& path) : - detail::PrimitiveVariant<data::dto::AronFloat, float, Float>::PrimitiveVariant(o, data::Descriptor::FLOAT, path) + detail::PrimitiveVariant<data::dto::AronFloat, float, Float>::PrimitiveVariant( + o, + data::Descriptor::FLOAT, + path) { } Float::Float(const Path& path) : - detail::PrimitiveVariant<data::dto::AronFloat, float, Float>::PrimitiveVariant(data::Descriptor::FLOAT, path) + detail::PrimitiveVariant<data::dto::AronFloat, float, Float>::PrimitiveVariant( + data::Descriptor::FLOAT, + path) { } Float::Float(const float d, const Path& path) : - detail::PrimitiveVariant<data::dto::AronFloat, float, Float>::PrimitiveVariant(d, data::Descriptor::FLOAT, path) + detail::PrimitiveVariant<data::dto::AronFloat, float, Float>::PrimitiveVariant( + d, + data::Descriptor::FLOAT, + path) { } /* operators */ - bool Float::operator==(const Float& other) const + bool + Float::operator==(const Float& other) const { const auto& otherAron = other.toAronFloatDTO(); if (this->aron->value != otherAron->value) @@ -51,7 +60,9 @@ namespace armarx::aron::data } return true; } - bool Float::operator==(const FloatPtr& other) const + + bool + Float::operator==(const FloatPtr& other) const { if (!other) { @@ -60,9 +71,9 @@ namespace armarx::aron::data return *this == *other; } - /* static methods */ - FloatPtr Float::FromAronFloatDTO(const data::dto::AronFloatPtr& aron) + FloatPtr + Float::FromAronFloatDTO(const data::dto::AronFloatPtr& aron) { if (!aron) { @@ -71,41 +82,51 @@ namespace armarx::aron::data return std::make_shared<Float>(aron); } - data::dto::AronFloatPtr Float::ToAronFloatDTO(const FloatPtr& navigator) + data::dto::AronFloatPtr + Float::ToAronFloatDTO(const FloatPtr& navigator) { return navigator ? navigator->toAronFloatDTO() : nullptr; } /* public member functions */ - data::dto::AronFloatPtr Float::toAronFloatDTO() const + data::dto::AronFloatPtr + Float::toAronFloatDTO() const { return aron; } - /* virtual implementations */ - void Float::fromString(const std::string& setter) + void + Float::fromString(const std::string& setter) { setValue(std::stof(setter)); } - std::string Float::getShortName() const + std::string + Float::getShortName() const { return "Float"; } - std::string Float::getFullName() const + + std::string + Float::getFullName() const { return "armarx::aron::data::Float"; } - bool Float::fullfillsType(const type::VariantPtr& type) const + bool + Float::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; + if (!type) + return true; return type->getDescriptor() == type::Descriptor::FLOAT; } - type::VariantPtr Float::recalculateType() const + type::VariantPtr + Float::recalculateType() const { - return std::make_shared<type::Float>(getPath()); + ARMARX_TRACE; + throw error::NotImplementedYetException(__PRETTY_FUNCTION__); + //return std::make_shared<type::Float>(getPath()); } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Float.h b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Float.h index 2d0cecb7e609df5496da3e616ffcd0fe6e249800..96f84a14c7978ab6675661c6d5fab261e0ad3b92 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Float.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Float.h @@ -48,6 +48,8 @@ namespace armarx::aron::data Float(const float, const Path& = Path()); /* operators */ + using detail::PrimitiveVariant<data::dto::AronFloat, float, Float>::operator==; + bool operator==(const Float&) const override; bool operator==(const FloatPtr&) const override; diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Int.cpp b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Int.cpp index cc4d9dc2ec4285f3791e4f45752d578b6a304408..870cbcd22877a82237e143bc79bf1528e64d35de 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Int.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Int.cpp @@ -30,22 +30,31 @@ namespace armarx::aron::data { /* constructors */ Int::Int(const data::dto::AronIntPtr& o, const Path& path) : - detail::PrimitiveVariant<data::dto::AronInt, int, Int>::PrimitiveVariant(o, data::Descriptor::INT, path) + detail::PrimitiveVariant<data::dto::AronInt, int, Int>::PrimitiveVariant( + o, + data::Descriptor::INT, + path) { } Int::Int(const Path& path) : - detail::PrimitiveVariant<data::dto::AronInt, int, Int>::PrimitiveVariant(data::Descriptor::INT, path) + detail::PrimitiveVariant<data::dto::AronInt, int, Int>::PrimitiveVariant( + data::Descriptor::INT, + path) { } Int::Int(const int d, const Path& path) : - detail::PrimitiveVariant<data::dto::AronInt, int, Int>::PrimitiveVariant(d, data::Descriptor::INT, path) + detail::PrimitiveVariant<data::dto::AronInt, int, Int>::PrimitiveVariant( + d, + data::Descriptor::INT, + path) { } /* operators */ - bool Int::operator==(const Int& other) const + bool + Int::operator==(const Int& other) const { const auto& otherAron = other.toAronIntDTO(); if (this->aron->value != otherAron->value) @@ -54,7 +63,9 @@ namespace armarx::aron::data } return true; } - bool Int::operator==(const IntPtr& other) const + + bool + Int::operator==(const IntPtr& other) const { if (!other) { @@ -63,9 +74,9 @@ namespace armarx::aron::data return *this == *other; } - /* static methods */ - IntPtr Int::FromAronIntDTO(const data::dto::AronIntPtr& aron) + IntPtr + Int::FromAronIntDTO(const data::dto::AronIntPtr& aron) { if (!aron) { @@ -74,41 +85,52 @@ namespace armarx::aron::data return std::make_shared<Int>(aron); } - data::dto::AronIntPtr Int::ToAronIntDTO(const IntPtr& navigator) + data::dto::AronIntPtr + Int::ToAronIntDTO(const IntPtr& navigator) { return navigator ? navigator->toAronIntDTO() : nullptr; } /* public member functions */ - data::dto::AronIntPtr Int::toAronIntDTO() const + data::dto::AronIntPtr + Int::toAronIntDTO() const { return aron; } - /* virtual implementations */ - void Int::fromString(const std::string& setter) + void + Int::fromString(const std::string& setter) { setValue(std::stoi(setter)); } - std::string Int::getShortName() const + std::string + Int::getShortName() const { return "Int"; } - std::string Int::getFullName() const + + std::string + Int::getFullName() const { return "armarx::aron::data::Int"; } - bool Int::fullfillsType(const type::VariantPtr& type) const + bool + Int::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; - return type->getDescriptor() == type::Descriptor::INT || type->getDescriptor() == type::Descriptor::INT_ENUM; + if (!type) + return true; + return type->getDescriptor() == type::Descriptor::INT || + type->getDescriptor() == type::Descriptor::INT_ENUM; } - type::VariantPtr Int::recalculateType() const + type::VariantPtr + Int::recalculateType() const { - return std::make_shared<type::Int>(getPath()); + ARMARX_TRACE; + throw error::NotImplementedYetException(__PRETTY_FUNCTION__); + //return std::make_shared<type::Int>(getPath()); } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Int.h b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Int.h index 5ee4a270f60bd2b21d8e2257c814f5dab8a0b759..738496f71bc51b4f0bdca92f57405a84a0dc2d22 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Int.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Int.h @@ -49,6 +49,8 @@ namespace armarx::aron::data Int(const int, const Path& = Path()); /* operators */ + using detail::PrimitiveVariant<data::dto::AronInt, int, Int>::operator==; + bool operator==(const Int&) const override; bool operator==(const IntPtr&) const override; diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Long.cpp b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Long.cpp index 6a271cdc821d275c8a9afec1b65f73436010ad2f..2f62027e1ca65333d48447c4490932ecc032b543 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Long.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Long.cpp @@ -31,22 +31,31 @@ namespace armarx::aron::data { /* constructors */ Long::Long(const data::dto::AronLongPtr& o, const Path& path) : - detail::PrimitiveVariant<data::dto::AronLong, long, Long>::PrimitiveVariant(o, data::Descriptor::LONG, path) + detail::PrimitiveVariant<data::dto::AronLong, long, Long>::PrimitiveVariant( + o, + data::Descriptor::LONG, + path) { } Long::Long(const Path& path) : - detail::PrimitiveVariant<data::dto::AronLong, long, Long>::PrimitiveVariant(data::Descriptor::LONG, path) + detail::PrimitiveVariant<data::dto::AronLong, long, Long>::PrimitiveVariant( + data::Descriptor::LONG, + path) { } Long::Long(const long d, const Path& path) : - detail::PrimitiveVariant<data::dto::AronLong, long, Long>::PrimitiveVariant(d, data::Descriptor::LONG, path) + detail::PrimitiveVariant<data::dto::AronLong, long, Long>::PrimitiveVariant( + d, + data::Descriptor::LONG, + path) { } /* operators */ - bool Long::operator==(const Long& other) const + bool + Long::operator==(const Long& other) const { const auto& otherAron = other.toAronLongDTO(); if (this->aron->value != otherAron->value) @@ -55,7 +64,9 @@ namespace armarx::aron::data } return true; } - bool Long::operator==(const LongPtr& other) const + + bool + Long::operator==(const LongPtr& other) const { if (!other) { @@ -64,9 +75,9 @@ namespace armarx::aron::data return *this == *other; } - /* static methods */ - LongPtr Long::FromAronLongDTO(const data::dto::AronLongPtr& aron) + LongPtr + Long::FromAronLongDTO(const data::dto::AronLongPtr& aron) { if (!aron) { @@ -75,41 +86,51 @@ namespace armarx::aron::data return std::make_shared<Long>(aron); } - data::dto::AronLongPtr Long::ToAronLongDTO(const LongPtr& navigator) + data::dto::AronLongPtr + Long::ToAronLongDTO(const LongPtr& navigator) { return navigator ? navigator->toAronLongDTO() : nullptr; } /* public member functions */ - data::dto::AronLongPtr Long::toAronLongDTO() const + data::dto::AronLongPtr + Long::toAronLongDTO() const { return aron; } - /* virtual implementations */ - void Long::fromString(const std::string& setter) + void + Long::fromString(const std::string& setter) { setValue(std::stol(setter)); } - std::string Long::getShortName() const + std::string + Long::getShortName() const { return "Long"; } - std::string Long::getFullName() const + + std::string + Long::getFullName() const { return "armarx::aron::data::Long"; } - bool Long::fullfillsType(const type::VariantPtr& type) const + bool + Long::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; + if (!type) + return true; return type->getDescriptor() == type::Descriptor::LONG; } - type::VariantPtr Long::recalculateType() const + type::VariantPtr + Long::recalculateType() const { - return std::make_shared<type::Long>(getPath()); + ARMARX_TRACE; + throw error::NotImplementedYetException(__PRETTY_FUNCTION__); + //return std::make_shared<type::Long>(getPath()); } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Long.h b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Long.h index 97e3496c6b984ededccbc19422ecad3b5c65f17b..c28b603aa93f3b23750a310e84e9bcc6a9e7d501 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/Long.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/Long.h @@ -48,6 +48,8 @@ namespace armarx::aron::data Long(const long, const Path& = Path()); /* operators */ + using detail::PrimitiveVariant<data::dto::AronLong, long, Long>::operator==; + bool operator==(const Long&) const override; bool operator==(const LongPtr&) const override; diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/String.cpp b/source/RobotAPI/libraries/aron/core/data/variant/primitive/String.cpp index 6415245f36a08faf2b02364ff4a298d33a4c9ac9..9f765ed209f40a84e6554eebb26e1671d1a04e8b 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/String.cpp +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/String.cpp @@ -27,22 +27,31 @@ namespace armarx::aron::data { /* constructors */ String::String(const data::dto::AronStringPtr& o, const Path& path) : - detail::PrimitiveVariant<data::dto::AronString, std::string, String>::PrimitiveVariant(o, data::Descriptor::STRING, path) + detail::PrimitiveVariant<data::dto::AronString, std::string, String>::PrimitiveVariant( + o, + data::Descriptor::STRING, + path) { } String::String(const Path& path) : - detail::PrimitiveVariant<data::dto::AronString, std::string, String>::PrimitiveVariant(data::Descriptor::STRING, path) + detail::PrimitiveVariant<data::dto::AronString, std::string, String>::PrimitiveVariant( + data::Descriptor::STRING, + path) { } String::String(const std::string& d, const Path& path) : - detail::PrimitiveVariant<data::dto::AronString, std::string, String>::PrimitiveVariant(d, data::Descriptor::STRING, path) + detail::PrimitiveVariant<data::dto::AronString, std::string, String>::PrimitiveVariant( + d, + data::Descriptor::STRING, + path) { } /* operators */ - bool String::operator==(const String& other) const + bool + String::operator==(const String& other) const { const auto& otherAron = other.toAronStringDTO(); if (this->aron->value != otherAron->value) @@ -51,7 +60,9 @@ namespace armarx::aron::data } return true; } - bool String::operator==(const StringPtr& other) const + + bool + String::operator==(const StringPtr& other) const { if (!other) { @@ -60,9 +71,9 @@ namespace armarx::aron::data return *this == *other; } - /* static methods */ - StringPtr String::FromAronStringDTO(const data::dto::AronStringPtr& aron) + StringPtr + String::FromAronStringDTO(const data::dto::AronStringPtr& aron) { if (!aron) { @@ -71,41 +82,51 @@ namespace armarx::aron::data return std::make_shared<String>(aron); } - data::dto::AronStringPtr String::ToAronStringDTO(const StringPtr& navigator) + data::dto::AronStringPtr + String::ToAronStringDTO(const StringPtr& navigator) { return navigator ? navigator->toAronStringDTO() : nullptr; } /* public member functions */ - data::dto::AronStringPtr String::toAronStringDTO() const + data::dto::AronStringPtr + String::toAronStringDTO() const { return aron; } - /* virtual implementations */ - void String::fromString(const std::string& setter) + void + String::fromString(const std::string& setter) { setValue(setter); } - std::string String::getShortName() const + std::string + String::getShortName() const { return "String"; } - std::string String::getFullName() const + + std::string + String::getFullName() const { return "armarx::aron::data::String"; } - bool String::fullfillsType(const type::VariantPtr& type) const + bool + String::fullfillsType(const type::VariantPtr& type) const { - if (!type) return true; + if (!type) + return true; return type->getDescriptor() == type::Descriptor::STRING; } - type::VariantPtr String::recalculateType() const + type::VariantPtr + String::recalculateType() const { - return std::make_shared<type::String>(getPath()); + ARMARX_TRACE; + throw error::NotImplementedYetException(__PRETTY_FUNCTION__); + //return std::make_shared<type::String>(getPath()); } -} +} // namespace armarx::aron::data diff --git a/source/RobotAPI/libraries/aron/core/data/variant/primitive/String.h b/source/RobotAPI/libraries/aron/core/data/variant/primitive/String.h index 21c23698c114262b3d71658288cef82e12e4747f..def1c80315934c55073314483fcda063fbd50e76 100644 --- a/source/RobotAPI/libraries/aron/core/data/variant/primitive/String.h +++ b/source/RobotAPI/libraries/aron/core/data/variant/primitive/String.h @@ -48,6 +48,7 @@ namespace armarx::aron::data String(const std::string&, const Path& = Path()); /* operators */ + using detail::PrimitiveVariant<data::dto::AronString, std::string, String>::operator==; bool operator==(const String&) const override; bool operator==(const StringPtr&) const override; diff --git a/source/RobotAPI/libraries/aron/core/type/converter/Converter.h b/source/RobotAPI/libraries/aron/core/type/converter/Converter.h index e166ab4327c0dd9f8f800a6a0eadea3bf001408a..2355fb7f8a8786da18c861012bdd5a92b36cae1a 100644 --- a/source/RobotAPI/libraries/aron/core/type/converter/Converter.h +++ b/source/RobotAPI/libraries/aron/core/type/converter/Converter.h @@ -23,9 +23,9 @@ #pragma once -#include "../visitor/Visitor.h" #include "../rw/Reader.h" #include "../rw/Writer.h" +#include "../visitor/Visitor.h" namespace armarx::aron::type { @@ -35,16 +35,20 @@ namespace armarx::aron::type struct Converter; template <class T> - concept isConverter = std::is_base_of<Converter<typename T::ReaderType, typename T::WriterType, typename T::This>, T>::value; + concept isConverter = + std::is_base_of<Converter<typename T::ReaderType, typename T::WriterType, typename T::This>, + T>::value; template <class ConverterImplementation> requires isConverter<ConverterImplementation> - typename ConverterImplementation::WriterReturnType readAndWrite(typename ConverterImplementation::ReaderInputType& o); + typename ConverterImplementation::WriterReturnType + readAndWrite(typename ConverterImplementation::ReaderInputType& o); /// Converter struct providing the needed methods. /// WriterImplementation is a writer class, TODO: add concepts template <class ReaderImplementation, class WriterImplementation, class DerivedT> requires isReader<ReaderImplementation> && isWriter<WriterImplementation> + struct Converter : virtual public Visitor<typename ReaderImplementation::InputType> { using WriterType = WriterImplementation; @@ -60,12 +64,14 @@ namespace armarx::aron::type virtual ~Converter() = default; - type::Descriptor getDescriptor(ReaderInputType& o) final + type::Descriptor + getDescriptor(ReaderInputType& o) final { return r.getDescriptor(o); } - void visitObject(ReaderInputType& o) final + void + visitObject(ReaderInputType& o) final { std::map<std::string, ReaderInputTypeNonConst> elementsOfInput; std::string name; @@ -81,10 +87,12 @@ namespace armarx::aron::type elementsReturn.insert({key, converted}); } - last_returned = w.writeObject(name, templates, templateInstantiations, elementsReturn, std::nullopt, maybe, p); + last_returned = w.writeObject( + name, templates, templateInstantiations, elementsReturn, std::nullopt, maybe, p); } - void visitDict(ReaderInputType& o) final + void + visitDict(ReaderInputType& o) final { ReaderInputTypeNonConst acceptedType; type::Maybe maybe; @@ -96,7 +104,8 @@ namespace armarx::aron::type last_returned = w.writeDict(converted, maybe, p); }; - void visitList(ReaderInputType& o) final + void + visitList(ReaderInputType& o) final { ReaderInputTypeNonConst acceptedType; type::Maybe maybe; @@ -108,7 +117,8 @@ namespace armarx::aron::type last_returned = w.writeList(converted, maybe, p); }; - void visitPair(ReaderInputType& o) final + void + visitPair(ReaderInputType& o) final { ReaderInputTypeNonConst acceptedType1; ReaderInputTypeNonConst acceptedType2; @@ -122,7 +132,8 @@ namespace armarx::aron::type last_returned = w.writePair(converted1, converted2, maybe, p); }; - void visitTuple(ReaderInputType& o) final + void + visitTuple(ReaderInputType& o) final { std::vector<ReaderInputTypeNonConst> acceptedTypes; std::vector<WriterReturnType> elementsReturn; @@ -139,117 +150,143 @@ namespace armarx::aron::type last_returned = w.writeTuple(elementsReturn, maybe, p); }; - void visitNDArray(ReaderInputType& o) final + void + visitNDArray(ReaderInputType& o) final { type::Maybe maybe; type::ndarray::ElementType type; + std::string defaultValue; int ndim; Path p; - r.readNDArray(o, ndim, type, maybe, p); - last_returned = w.writeNDArray(ndim, type, maybe, p); + r.readNDArray(o, ndim, type, defaultValue, maybe, p); + last_returned = w.writeNDArray(ndim, type, defaultValue, maybe, p); }; - void visitMatrix(ReaderInputType& o) final + void + visitMatrix(ReaderInputType& o) final { type::Maybe maybe; type::matrix::ElementType type; + std::string defaultValue; int rows; int cols; Path p; - r.readMatrix(o, rows, cols, type, maybe, p); - last_returned = w.writeMatrix(rows, cols, type, maybe, p); + r.readMatrix(o, rows, cols, type, defaultValue, maybe, p); + last_returned = w.writeMatrix(rows, cols, type, defaultValue, maybe, p); }; - void visitQuaternion(ReaderInputType& o) final + void + visitQuaternion(ReaderInputType& o) final { type::Maybe maybe; type::quaternion::ElementType type; + std::string defaultValue; Path p; - r.readQuaternion(o, type, maybe, p); - last_returned = w.writeQuaternion(type, maybe, p); + r.readQuaternion(o, type, defaultValue, maybe, p); + last_returned = w.writeQuaternion(type, defaultValue, maybe, p); }; - void visitImage(ReaderInputType& o) final + void + visitImage(ReaderInputType& o) final { type::Maybe maybe; type::image::PixelType type; + std::string defaultValue; Path p; - r.readImage(o, type, maybe, p); - last_returned = w.writeImage(type, maybe, p); + r.readImage(o, type, defaultValue, maybe, p); + last_returned = w.writeImage(type, defaultValue, maybe, p); }; - void visitPointCloud(ReaderInputType& o) final + void + visitPointCloud(ReaderInputType& o) final { type::Maybe maybe; type::pointcloud::VoxelType type; + std::string defaultValue; Path p; - r.readPointCloud(o, type, maybe, p); - last_returned = w.writePointCloud(type, maybe, p); + r.readPointCloud(o, type, defaultValue, maybe, p); + last_returned = w.writePointCloud(type, defaultValue, maybe, p); }; - void visitIntEnum(ReaderInputType& o) final + void + visitIntEnum(ReaderInputType& o) final { type::Maybe maybe; std::string name; std::map<std::string, int> values; + std::string defaultValue; Path p; - r.readIntEnum(o, name, values, maybe, p); - last_returned = w.writeIntEnum(name, values, maybe, p); + r.readIntEnum(o, name, values, defaultValue, maybe, p); + last_returned = w.writeIntEnum(name, values, defaultValue, maybe, p); }; - void visitInt(ReaderInputType& o) final + void + visitInt(ReaderInputType& o) final { type::Maybe maybe; Path p; - r.readInt(o, maybe, p); - last_returned = w.writeInt(maybe, p); + int defaultValue; + r.readInt(o, defaultValue, maybe, p); + last_returned = w.writeInt(defaultValue, maybe, p); }; - void visitLong(ReaderInputType& o) final + void + visitLong(ReaderInputType& o) final { type::Maybe maybe; Path p; - r.readLong(o, maybe, p); - last_returned = w.writeLong(maybe, p); + long defaultValue; + r.readLong(o, defaultValue, maybe, p); + last_returned = w.writeLong(defaultValue, maybe, p); }; - void visitFloat(ReaderInputType& o) final + void + visitFloat(ReaderInputType& o) final { type::Maybe maybe; Path p; - r.readFloat(o, maybe, p); - last_returned = w.writeFloat(maybe, p); + float defaultValue; + r.readFloat(o, defaultValue, maybe, p); + last_returned = w.writeFloat(defaultValue, maybe, p); }; - void visitDouble(ReaderInputType& o) final + void + visitDouble(ReaderInputType& o) final { type::Maybe maybe; Path p; - r.readDouble(o, maybe, p); - last_returned = w.writeDouble(maybe, p); + double defaultValue; + r.readDouble(o, defaultValue, maybe, p); + last_returned = w.writeDouble(defaultValue, maybe, p); }; - void visitBool(ReaderInputType& o) final + void + visitBool(ReaderInputType& o) final { type::Maybe maybe; Path p; - r.readBool(o, maybe, p); - last_returned = w.writeBool(maybe, p); + bool defaultValue; + r.readBool(o, defaultValue, maybe, p); + last_returned = w.writeBool(defaultValue, maybe, p); }; - void visitString(ReaderInputType& o) final + void + visitString(ReaderInputType& o) final { type::Maybe maybe; Path p; - r.readString(o, maybe, p); - last_returned = w.writeString(maybe, p); + std::string defaultValue; + r.readString(o, defaultValue, maybe, p); + last_returned = w.writeString(defaultValue, maybe, p); }; - void visitUnknown(ReaderInputType& o) final + void + visitUnknown(ReaderInputType& o) final { if (!r.readNull(o)) { - throw error::AronException(__PRETTY_FUNCTION__, "A visitor got type but the enum is unknown."); + throw error::AronException(__PRETTY_FUNCTION__, + "A visitor got type but the enum is unknown."); } w.writeNull(); } @@ -259,10 +296,12 @@ namespace armarx::aron::type /// returns the returntype of T template <class ConverterImplementation> requires isConverter<ConverterImplementation> - typename ConverterImplementation::WriterReturnType readAndWrite(typename ConverterImplementation::ReaderInputType& o) + + typename ConverterImplementation::WriterReturnType + readAndWrite(typename ConverterImplementation::ReaderInputType& o) { ConverterImplementation v; type::visit(v, o); return v.last_returned; } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/rw/Reader.h b/source/RobotAPI/libraries/aron/core/type/rw/Reader.h index 790a0d9fb7f9ed77f00ca40686582db063fd3fbe..5a736c0ada20388f3ccaba62489e28b7e75b9770 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/Reader.h +++ b/source/RobotAPI/libraries/aron/core/type/rw/Reader.h @@ -28,7 +28,6 @@ #include <RobotAPI/interface/aron.h> #include <RobotAPI/libraries/aron/core/Exception.h> - namespace armarx::aron::type { /** @@ -46,61 +45,117 @@ namespace armarx::aron::type virtual type::Descriptor getDescriptor(InputType& input) = 0; /// Extract information from an Object type - virtual void readObject(const InputType& input, std::string& name, std::vector<std::string>& templates, std::vector<std::string>& templateInstantiations, std::map<std::string, InputTypeNonConst>& memberTypes, type::Maybe& maybe, Path& p) = 0; + virtual void readObject(const InputType& input, + std::string& name, + std::vector<std::string>& templates, + std::vector<std::string>& templateInstantiations, + std::map<std::string, InputTypeNonConst>& memberTypes, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from a list type - virtual void readList(const InputType& input, InputTypeNonConst& acceptedType, type::Maybe& maybe, Path& p) = 0; + virtual void readList(const InputType& input, + InputTypeNonConst& acceptedType, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from a dict type - virtual void readDict(const InputType& input, InputTypeNonConst& acceptedType, type::Maybe& maybe, Path& p) = 0; + virtual void readDict(const InputType& input, + InputTypeNonConst& acceptedType, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from a tuple type - virtual void readTuple(const InputType& input, std::vector<InputTypeNonConst>& acceptedTypes, type::Maybe& maybe, Path& p) = 0; + virtual void readTuple(const InputType& input, + std::vector<InputTypeNonConst>& acceptedTypes, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from a pair type - virtual void readPair(const InputType& input, InputTypeNonConst& acceptedTypes1, InputTypeNonConst& acceptedTypes2, type::Maybe& maybe, Path& p) = 0; + virtual void readPair(const InputType& input, + InputTypeNonConst& acceptedTypes1, + InputTypeNonConst& acceptedTypes2, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from a ndarray type - virtual void readNDArray(const InputType& input, int& ndim, type::ndarray::ElementType& type, type::Maybe& maybe, Path& p) = 0; + virtual void readNDArray(const InputType& input, + int& ndim, + type::ndarray::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from a matrix type - virtual void readMatrix(const InputType& input, int& rows, int& cols, type::matrix::ElementType& type, type::Maybe& maybe, Path& p) = 0; + virtual void readMatrix(const InputType& input, + int& rows, + int& cols, + type::matrix::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from a quaternion type - virtual void readQuaternion(const InputType& input, type::quaternion::ElementType& type, type::Maybe& maybe, Path& p) = 0; + virtual void readQuaternion(const InputType& input, + type::quaternion::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from a pointcloud type - virtual void readPointCloud(const InputType& input, type::pointcloud::VoxelType& type, type::Maybe& maybe, Path& p) = 0; + virtual void readPointCloud(const InputType& input, + type::pointcloud::VoxelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from an image type - virtual void readImage(const InputType& input, type::image::PixelType& type, type::Maybe& maybe, Path& p) = 0; + virtual void readImage(const InputType& input, + type::image::PixelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from an int enum type - virtual void readIntEnum(const InputType& input, std::string& name, std::map<std::string, int>& acceptedValues, type::Maybe& maybe, Path& p) = 0; + virtual void readIntEnum(const InputType& input, + std::string& name, + std::map<std::string, int>& acceptedValues, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from an int type - virtual void readInt(const InputType& input, type::Maybe& maybe, Path& p) = 0; + virtual void + readInt(const InputType& input, int& defaultValue, type::Maybe& maybe, Path& p) = 0; /// Extract information from an long type - virtual void readLong(const InputType& input, type::Maybe& maybe, Path& p) = 0; + virtual void + readLong(const InputType& input, long& defaultValue, type::Maybe& maybe, Path& p) = 0; /// Extract information from an float type - virtual void readFloat(const InputType& input, type::Maybe& maybe, Path& p) = 0; + virtual void + readFloat(const InputType& input, float& defaultValue, type::Maybe& maybe, Path& p) = 0; /// Extract information from an double type - virtual void readDouble(const InputType& input, type::Maybe& maybe, Path& p) = 0; + virtual void + readDouble(const InputType& input, double& defaultValue, type::Maybe& maybe, Path& p) = 0; /// Extract information from an string type - virtual void readString(const InputType& input, type::Maybe& maybe, Path& p) = 0; + virtual void readString(const InputType& input, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) = 0; /// Extract information from an bool type - virtual void readBool(const InputType& input, type::Maybe& maybe, Path& p) = 0; + virtual void + readBool(const InputType& input, bool& defaultValue, type::Maybe& maybe, Path& p) = 0; /// Extract information from an time type virtual void readAnyObject(const InputType& input, type::Maybe& maybe, Path& p) = 0; /// Check if input is null - virtual bool readNull(InputType& input) // defaulted implementation + virtual bool + readNull(InputType& input) // defaulted implementation { InputType nil = {}; return input == nil; @@ -218,4 +273,4 @@ namespace armarx::aron::type template <class T> concept isReader = std::is_base_of<ReaderInterface<typename T::InputType>, T>::value; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/rw/Writer.h b/source/RobotAPI/libraries/aron/core/type/rw/Writer.h index 5cba5dd672c7a2ebcde343485e64bc781ce26a1f..8ff7b1ce295e1c3ddbb2f28a350677db6b7344d2 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/Writer.h +++ b/source/RobotAPI/libraries/aron/core/type/rw/Writer.h @@ -22,14 +22,13 @@ // STD/STL #include <memory> -#include <string> #include <optional> +#include <string> // ArmarX #include <RobotAPI/interface/aron.h> #include <RobotAPI/libraries/aron/core/Exception.h> - namespace armarx::aron::type { /** @@ -47,67 +46,106 @@ namespace armarx::aron::type virtual type::Descriptor getDescriptor(ReturnTypeConst& input) = 0; /// Construct an object from the params - virtual ReturnType writeObject(const std::string& name, const std::vector<std::string>& templates, const std::vector<std::string>& templateInstantiations, const std::map<std::string, ReturnType>& memberTypes, const std::optional<ReturnType>& extends, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeObject(const std::string& name, + const std::vector<std::string>& templates, + const std::vector<std::string>& templateInstantiations, + const std::map<std::string, ReturnType>& memberTypes, + const std::optional<ReturnType>& extends, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a list from the params - virtual ReturnType writeList(const ReturnType& acceptedType, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType + writeList(const ReturnType& acceptedType, const type::Maybe maybe, const Path& p) = 0; /// Construct a dict from the params - virtual ReturnType writeDict(const ReturnType& acceptedType, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType + writeDict(const ReturnType& acceptedType, const type::Maybe maybe, const Path& p) = 0; /// Construct a pair from the params - virtual ReturnType writePair(const ReturnType& acceptedType1, const ReturnType& acceptedType2, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writePair(const ReturnType& acceptedType1, + const ReturnType& acceptedType2, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a tuple from the params - virtual ReturnType writeTuple(const std::vector<ReturnType>& acceptedTypes, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeTuple(const std::vector<ReturnType>& acceptedTypes, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a ndarray from the params - virtual ReturnType writeNDArray(const int ndim, const type::ndarray::ElementType, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeNDArray(const int ndim, + const type::ndarray::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a matrix from the params - virtual ReturnType writeMatrix(const int rows, const int cols, const type::matrix::ElementType type, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeMatrix(const int rows, + const int cols, + const type::matrix::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a quaternion from the params - virtual ReturnType writeQuaternion(const type::quaternion::ElementType, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeQuaternion(const type::quaternion::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a image from the params - virtual ReturnType writeImage(const type::image::PixelType, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeImage(const type::image::PixelType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a pointcloud from the params - virtual ReturnType writePointCloud(const type::pointcloud::VoxelType, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writePointCloud(const type::pointcloud::VoxelType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a int enum from the params - virtual ReturnType writeIntEnum(const std::string& name, const std::map<std::string, int>& acceptedValues, const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeIntEnum(const std::string& name, + const std::map<std::string, int>& acceptedValues, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) = 0; /// Construct a int from the params - virtual ReturnType writeInt(const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeInt(int defaultValue, const type::Maybe maybe, const Path& p) = 0; /// Construct a long from the params - virtual ReturnType writeLong(const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeLong(long defaultValue, const type::Maybe maybe, const Path& p) = 0; /// Construct a float from the params - virtual ReturnType writeFloat(const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType + writeFloat(float defaultValue, const type::Maybe maybe, const Path& p) = 0; /// Construct a double from the params - virtual ReturnType writeDouble(const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType + writeDouble(double defaultValue, const type::Maybe maybe, const Path& p) = 0; /// Construct a string from the params - virtual ReturnType writeString(const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType + writeString(const std::string& defaultValue, const type::Maybe maybe, const Path& p) = 0; /// Construct a bool from the params - virtual ReturnType writeBool(const type::Maybe maybe, const Path& p) = 0; + virtual ReturnType writeBool(bool defaultValue, const type::Maybe maybe, const Path& p) = 0; /// Construct a time from the params virtual ReturnType writeAnyObject(const type::Maybe maybe, const Path& p) = 0; /// write a null - virtual ReturnType writeNull(const Path& p = Path()) // defaulted implementation + virtual ReturnType + writeNull(const Path& p = Path()) // defaulted implementation { - (void) p; + (void)p; return {}; } }; template <class T> concept isWriter = std::is_base_of<WriterInterface<typename T::ReturnType>, T>::value; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/rw/json/Data.cpp b/source/RobotAPI/libraries/aron/core/type/rw/json/Data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df60876fbdd629f5c43d7a3fd2efb3f2a28ba1f0 --- /dev/null +++ b/source/RobotAPI/libraries/aron/core/type/rw/json/Data.cpp @@ -0,0 +1,21 @@ +/* +* This file is part of ArmarX. +* +* ArmarX is free software; you can redistribute it and/or modify +* it under the terms of the GNU General Public License version 2 as +* published by the Free Software Foundation. +* +* ArmarX is distributed in the hope that it will be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see <http://www.gnu.org/licenses/>. +* +* @author Fabian Peller (fabian dot peller at kit dot edu) +* @copyright http://www.gnu.org/licenses/gpl-2.0.txt +* GNU General Public License +*/ + +#include "Data.h" diff --git a/source/RobotAPI/libraries/aron/core/type/rw/json/Data.h b/source/RobotAPI/libraries/aron/core/type/rw/json/Data.h index a3dbadf76ff6c5d74e20f9b4ad66ae25b171d9aa..834b0b462f7f6de3e1bb6d1d4a1212773995f4ab 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/json/Data.h +++ b/source/RobotAPI/libraries/aron/core/type/rw/json/Data.h @@ -34,45 +34,46 @@ namespace armarx::aron::type::rw::json { namespace constantes { - const std::string MAYBE_SLUG = "_ARON_MAYBE"; - const std::string TYPE_SLUG = "_ARON_TYPE"; - const std::string PATH_SLUG = "_ARON_PATH"; - const std::string VERSION_SLUG = "_ARON_VERSION"; + const constexpr auto MAYBE_SLUG = "_ARON_MAYBE"; + const constexpr auto TYPE_SLUG = "_ARON_TYPE"; + const constexpr auto PATH_SLUG = "_ARON_PATH"; + const constexpr auto VERSION_SLUG = "_ARON_VERSION"; - const std::string KEY_SLUG = "_ARON_KEY"; - const std::string VALUE_SLUG = "_ARON_VALUE"; - const std::string MEMBERS_SLUG = "_ARON_MEMBERS"; - const std::string ELEMENTS_SLUG = "_ARON_ELEMENTS"; + const constexpr auto KEY_SLUG = "_ARON_KEY"; + const constexpr auto VALUE_SLUG = "_ARON_VALUE"; + const constexpr auto MEMBERS_SLUG = "_ARON_MEMBERS"; + const constexpr auto ELEMENTS_SLUG = "_ARON_ELEMENTS"; - const std::string NAME_SLUG = "_ARON_NAME"; - const std::string EXTENDS_SLUG = "_ARON_EXTENDS"; - const std::string ACCEPTED_TYPE_SLUG = "_ARON_ACCEPTED_TYPE"; - const std::string DIMENSIONS_SLUG = "_ARON_DIMESIONS"; - const std::string DATA_SLUG = "_ARON_DATA"; - const std::string USED_TYPE_SLUG = "_ARON_USED_TYPE"; - const std::string TEMPLATES_SLUG = "_ARON_TEMPLATES"; - const std::string TEMPLATE_INSTANTIATIONS_SLUG = "_ARON_TEMPLATE_INSTANTIATION"; + const constexpr auto NAME_SLUG = "_ARON_NAME"; + const constexpr auto EXTENDS_SLUG = "_ARON_EXTENDS"; + const constexpr auto ACCEPTED_TYPE_SLUG = "_ARON_ACCEPTED_TYPE"; + const constexpr auto DIMENSIONS_SLUG = "_ARON_DIMESIONS"; + const constexpr auto DATA_SLUG = "_ARON_DATA"; + const constexpr auto USED_TYPE_SLUG = "_ARON_USED_TYPE"; + const constexpr auto TEMPLATES_SLUG = "_ARON_TEMPLATES"; + const constexpr auto TEMPLATE_INSTANTIATIONS_SLUG = "_ARON_TEMPLATE_INSTANTIATION"; + const constexpr auto DEFAULT_SLUG = "_ARON_DEFAULT"; - const std::string LIST_TYPENAME_SLUG = "_ARON_LIST"; - const std::string DICT_TYPENAME_SLUG = "_ARON_DICT"; - const std::string OBJECT_TYPENAME_SLUG = "_ARON_OBJECT"; - const std::string TUPLE_TYPENAME_SLUG = "_ARON_TUPLE"; - const std::string PAIR_TYPENAME_SLUG = "_ARON_PAIR"; - const std::string NDARRAY_TYPENAME_SLUG = "_ARON_NDARRAY"; - const std::string IMAGE_TYPENAME_SLUG = "_ARON_IMAGE"; - const std::string MATRIX_TYPENAME_SLUG = "_ARON_MATRIX"; - const std::string QUATERNION_TYPENAME_SLUG = "_ARON_QUATERNION"; - const std::string POINT_CLOUD_TYPENAME_SLUG = "_ARON_POINT_CLOUD"; - const std::string INT_ENUM_TYPENAME_SLUG = "_ARON_INT_ENUM"; - const std::string INT_TYPENAME_SLUG = "_ARON_INT"; - const std::string LONG_TYPENAME_SLUG = "_ARON_LONG"; - const std::string FLOAT_TYPENAME_SLUG = "_ARON_FLOAT"; - const std::string DOUBLE_TYPENAME_SLUG = "_ARON_DOUBLE"; - const std::string STRING_TYPENAME_SLUG = "_ARON_STRING"; - const std::string BOOL_TYPENAME_SLUG = "_ARON_BOOL"; - const std::string TIME_TYPENAME_SLUG = "_ARON_TIME"; - const std::string ANY_OBJECT_TYPENAME_SLUG = "_ARON_ANY_OBJECT"; - } + const constexpr auto LIST_TYPENAME_SLUG = "_ARON_LIST"; + const constexpr auto DICT_TYPENAME_SLUG = "_ARON_DICT"; + const constexpr auto OBJECT_TYPENAME_SLUG = "_ARON_OBJECT"; + const constexpr auto TUPLE_TYPENAME_SLUG = "_ARON_TUPLE"; + const constexpr auto PAIR_TYPENAME_SLUG = "_ARON_PAIR"; + const constexpr auto NDARRAY_TYPENAME_SLUG = "_ARON_NDARRAY"; + const constexpr auto IMAGE_TYPENAME_SLUG = "_ARON_IMAGE"; + const constexpr auto MATRIX_TYPENAME_SLUG = "_ARON_MATRIX"; + const constexpr auto QUATERNION_TYPENAME_SLUG = "_ARON_QUATERNION"; + const constexpr auto POINT_CLOUD_TYPENAME_SLUG = "_ARON_POINT_CLOUD"; + const constexpr auto INT_ENUM_TYPENAME_SLUG = "_ARON_INT_ENUM"; + const constexpr auto INT_TYPENAME_SLUG = "_ARON_INT"; + const constexpr auto LONG_TYPENAME_SLUG = "_ARON_LONG"; + const constexpr auto FLOAT_TYPENAME_SLUG = "_ARON_FLOAT"; + const constexpr auto DOUBLE_TYPENAME_SLUG = "_ARON_DOUBLE"; + const constexpr auto STRING_TYPENAME_SLUG = "_ARON_STRING"; + const constexpr auto BOOL_TYPENAME_SLUG = "_ARON_BOOL"; + const constexpr auto TIME_TYPENAME_SLUG = "_ARON_TIME"; + const constexpr auto ANY_OBJECT_TYPENAME_SLUG = "_ARON_ANY_OBJECT"; + } // namespace constantes namespace conversion { @@ -94,22 +95,18 @@ namespace armarx::aron::type::rw::json {type::Descriptor::DOUBLE, rw::json::constantes::DOUBLE_TYPENAME_SLUG}, {type::Descriptor::BOOL, rw::json::constantes::BOOL_TYPENAME_SLUG}, {type::Descriptor::STRING, rw::json::constantes::STRING_TYPENAME_SLUG}, - {type::Descriptor::ANY_OBJECT, rw::json::constantes::ANY_OBJECT_TYPENAME_SLUG} - }; + {type::Descriptor::ANY_OBJECT, rw::json::constantes::ANY_OBJECT_TYPENAME_SLUG}}; const auto String2Descriptor = aron::conversion::util::InvertMap(Descriptor2String); - const std::map<type::Maybe, std::string> Maybe2String = - { + const std::map<type::Maybe, std::string> Maybe2String = { {type::Maybe::NONE, "type::maybe::NONE"}, {type::Maybe::OPTIONAL, "type::maybe::OPTIONAL"}, {type::Maybe::RAW_PTR, "type::maybe::RAW_PTR"}, {type::Maybe::SHARED_PTR, "type::maybe::SHARED_PTR"}, - {type::Maybe::UNIQUE_PTR, "type::maybe::UNIQUE_PTR"} - }; + {type::Maybe::UNIQUE_PTR, "type::maybe::UNIQUE_PTR"}}; const auto String2Maybe = aron::conversion::util::InvertMap(Maybe2String); - const std::map<type::ndarray::ElementType, std::string> NDArrayType2String = - { + const std::map<type::ndarray::ElementType, std::string> NDArrayType2String = { {type::ndarray::ElementType::INT8, "type::ndarray::INT8"}, {type::ndarray::ElementType::INT16, "type::ndarray::INT16"}, {type::ndarray::ElementType::INT32, "type::ndarray::INT32"}, @@ -117,44 +114,35 @@ namespace armarx::aron::type::rw::json {type::ndarray::ElementType::UINT16, "type::ndarray::UINT16"}, {type::ndarray::ElementType::UINT32, "type::ndarray::UINT32"}, {type::ndarray::ElementType::FLOAT32, "type::ndarray::FLOAT32"}, - {type::ndarray::ElementType::FLOAT64, "type::ndarray::FLOAT64"} - }; + {type::ndarray::ElementType::FLOAT64, "type::ndarray::FLOAT64"}}; const auto String2NDArrayType = aron::conversion::util::InvertMap(NDArrayType2String); - const std::map<type::matrix::ElementType, std::string> MatrixType2String = - { + const std::map<type::matrix::ElementType, std::string> MatrixType2String = { {type::matrix::ElementType::INT16, "type::matrix::INT16"}, {type::matrix::ElementType::INT32, "type::matrix::INT32"}, {type::matrix::ElementType::INT64, "type::matrix::INT64"}, {type::matrix::ElementType::FLOAT32, "type::matrix::FLOAT32"}, - {type::matrix::ElementType::FLOAT64, "type::matrix::FLOAT64"} - }; + {type::matrix::ElementType::FLOAT64, "type::matrix::FLOAT64"}}; const auto String2MatrixType = aron::conversion::util::InvertMap(MatrixType2String); - const std::map<type::quaternion::ElementType, std::string> QuaternionType2String = - { + const std::map<type::quaternion::ElementType, std::string> QuaternionType2String = { {type::quaternion::ElementType::FLOAT32, "type::quaternion::FLOAT32"}, - {type::quaternion::ElementType::FLOAT64, "type::quaternion::FLOAT64"} - }; + {type::quaternion::ElementType::FLOAT64, "type::quaternion::FLOAT64"}}; const auto String2QuaternionType = aron::conversion::util::InvertMap(QuaternionType2String); - const std::map<type::image::PixelType, std::string> PixelType2String = - { + const std::map<type::image::PixelType, std::string> PixelType2String = { {type::image::PixelType::RGB24, "type::image::RGB24"}, - {type::image::PixelType::DEPTH32, "type::image::DEPTH32"} - }; + {type::image::PixelType::DEPTH32, "type::image::DEPTH32"}}; const auto String2PixelType = aron::conversion::util::InvertMap(PixelType2String); - const std::map<type::pointcloud::VoxelType, std::string> VoxelType2String = - { + const std::map<type::pointcloud::VoxelType, std::string> VoxelType2String = { {type::pointcloud::VoxelType::POINT_XYZ, "type::pointcloud::POINT_XYZ"}, {type::pointcloud::VoxelType::POINT_XYZI, "type::pointcloud::POINT_XYZI"}, {type::pointcloud::VoxelType::POINT_XYZL, "type::pointcloud::POINT_XYZL"}, {type::pointcloud::VoxelType::POINT_XYZRGB, "type::pointcloud::POINT_XYZRGB"}, {type::pointcloud::VoxelType::POINT_XYZRGBA, "type::pointcloud::POINT_XYZRGBA"}, {type::pointcloud::VoxelType::POINT_XYZRGBL, "type::pointcloud::POINT_XYZRGBL"}, - {type::pointcloud::VoxelType::POINT_XYZHSV, "type::pointcloud::POINT_XYZHSV"} - }; + {type::pointcloud::VoxelType::POINT_XYZHSV, "type::pointcloud::POINT_XYZHSV"}}; const auto String2VoxelType = aron::conversion::util::InvertMap(VoxelType2String); - } -} + } // namespace conversion +} // namespace armarx::aron::type::rw::json diff --git a/source/RobotAPI/libraries/aron/core/type/rw/reader/nlohmannJSON/NlohmannJSONReader.cpp b/source/RobotAPI/libraries/aron/core/type/rw/reader/nlohmannJSON/NlohmannJSONReader.cpp index 028b6681ce8ee3f57db6a33861eb0c28d4228811..2e9b1e46aac49f71f4b14ebd524c9cf49026eb54 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/reader/nlohmannJSON/NlohmannJSONReader.cpp +++ b/source/RobotAPI/libraries/aron/core/type/rw/reader/nlohmannJSON/NlohmannJSONReader.cpp @@ -27,33 +27,48 @@ // ArmarX #include <RobotAPI/libraries/aron/core/Exception.h> -#include "../../json/Data.h" #include <RobotAPI/libraries/aron/core/type/visitor/nlohmannJSON/NlohmannJSONVisitor.h> +#include "../../json/Data.h" + namespace armarx::aron::type::reader { namespace { /// Throw an exception if the type is other than expected - void getAronMetaInformationForType(const nlohmann::json& input, const std::string& expectedType, Path& p) + void + getAronMetaInformationForType(const nlohmann::json& input, + const std::string& expectedType, + Path& p) { if (input[rw::json::constantes::TYPE_SLUG] != expectedType) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Wrong type in json encountered.", input[rw::json::constantes::TYPE_SLUG], expectedType); + throw error::ValueNotValidException(__PRETTY_FUNCTION__, + "Wrong type in json encountered.", + input[rw::json::constantes::TYPE_SLUG], + expectedType); } // get Path std::vector<std::string> pathElements = input[rw::json::constantes::PATH_SLUG]; p = Path(pathElements); } - } + } // namespace - type::Descriptor NlohmannJSONReader::getDescriptor(InputType& input) + type::Descriptor + NlohmannJSONReader::getDescriptor(InputType& input) { return ConstNlohmannJSONVisitor::GetDescriptor(input); } - void NlohmannJSONReader::readObject(const nlohmann::json& input, std::string& name, std::vector<std::string>& templates, std::vector<std::string>& templateInstantiations, std::map<std::string, nlohmann::json>& memberTypes, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readObject(const nlohmann::json& input, + std::string& name, + std::vector<std::string>& templates, + std::vector<std::string>& templateInstantiations, + std::map<std::string, nlohmann::json>& memberTypes, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::OBJECT_TYPENAME_SLUG, p); @@ -64,14 +79,21 @@ namespace armarx::aron::type::reader } if (input.count(rw::json::constantes::TEMPLATE_INSTANTIATIONS_SLUG)) { - templateInstantiations = input[rw::json::constantes::TEMPLATE_INSTANTIATIONS_SLUG].get<std::vector<std::string>>(); + templateInstantiations = input[rw::json::constantes::TEMPLATE_INSTANTIATIONS_SLUG] + .get<std::vector<std::string>>(); } maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); - memberTypes = input[rw::json::constantes::MEMBERS_SLUG].get<std::map<std::string, nlohmann::json>>(); + memberTypes = + input[rw::json::constantes::MEMBERS_SLUG].get<std::map<std::string, nlohmann::json>>(); } - void NlohmannJSONReader::readList(const nlohmann::json& input, nlohmann::json& acceptedType, type::Maybe& maybe, Path& p) + + void + NlohmannJSONReader::readList(const nlohmann::json& input, + nlohmann::json& acceptedType, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::LIST_TYPENAME_SLUG, p); @@ -79,7 +101,11 @@ namespace armarx::aron::type::reader acceptedType = input[rw::json::constantes::ACCEPTED_TYPE_SLUG]; } - void NlohmannJSONReader::readDict(const nlohmann::json& input, nlohmann::json& acceptedType, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readDict(const nlohmann::json& input, + nlohmann::json& acceptedType, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::DICT_TYPENAME_SLUG, p); @@ -87,25 +113,42 @@ namespace armarx::aron::type::reader acceptedType = input[rw::json::constantes::ACCEPTED_TYPE_SLUG]; } - void NlohmannJSONReader::readTuple(const nlohmann::json& input, std::vector<nlohmann::json>& acceptedTypes, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readTuple(const nlohmann::json& input, + std::vector<nlohmann::json>& acceptedTypes, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::TUPLE_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); - acceptedTypes = input[rw::json::constantes::ACCEPTED_TYPE_SLUG].get<std::vector<nlohmann::json>>(); + acceptedTypes = + input[rw::json::constantes::ACCEPTED_TYPE_SLUG].get<std::vector<nlohmann::json>>(); } - void NlohmannJSONReader::readPair(const nlohmann::json& input, nlohmann::json& acceptedType1, nlohmann::json& acceptedType2, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readPair(const nlohmann::json& input, + nlohmann::json& acceptedType1, + nlohmann::json& acceptedType2, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::PAIR_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); - auto list = input[rw::json::constantes::ACCEPTED_TYPE_SLUG].get<std::vector<nlohmann::json>>(); + auto list = + input[rw::json::constantes::ACCEPTED_TYPE_SLUG].get<std::vector<nlohmann::json>>(); acceptedType1 = list[0]; acceptedType2 = list[1]; } - void NlohmannJSONReader::readNDArray(const nlohmann::json& input, int& ndim, type::ndarray::ElementType& type, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readNDArray(const nlohmann::json& input, + int& ndim, + type::ndarray::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::NDARRAY_TYPENAME_SLUG, p); @@ -114,9 +157,17 @@ namespace armarx::aron::type::reader std::string t = input[rw::json::constantes::USED_TYPE_SLUG]; type = armarx::aron::type::rw::json::conversion::String2NDArrayType.at(t); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readMatrix(const nlohmann::json& input, int& rows, int& cols, type::matrix::ElementType& type, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readMatrix(const nlohmann::json& input, + int& rows, + int& cols, + type::matrix::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::MATRIX_TYPENAME_SLUG, p); @@ -127,9 +178,15 @@ namespace armarx::aron::type::reader std::string t = input[rw::json::constantes::USED_TYPE_SLUG]; type = armarx::aron::type::rw::json::conversion::String2MatrixType.at(t); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readQuaternion(const nlohmann::json& input, type::quaternion::ElementType& type, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readQuaternion(const nlohmann::json& input, + type::quaternion::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::QUATERNION_TYPENAME_SLUG, p); @@ -137,9 +194,15 @@ namespace armarx::aron::type::reader std::string t = input[rw::json::constantes::USED_TYPE_SLUG]; type = armarx::aron::type::rw::json::conversion::String2QuaternionType.at(t); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readPointCloud(const nlohmann::json& input, type::pointcloud::VoxelType& type, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readPointCloud(const nlohmann::json& input, + type::pointcloud::VoxelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::POINT_CLOUD_TYPENAME_SLUG, p); @@ -147,9 +210,15 @@ namespace armarx::aron::type::reader std::string t = input[rw::json::constantes::USED_TYPE_SLUG]; type = armarx::aron::type::rw::json::conversion::String2VoxelType.at(t); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readImage(const nlohmann::json& input, type::image::PixelType& type, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readImage(const nlohmann::json& input, + type::image::PixelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::IMAGE_TYPENAME_SLUG, p); @@ -157,64 +226,105 @@ namespace armarx::aron::type::reader std::string t = input[rw::json::constantes::USED_TYPE_SLUG]; type = armarx::aron::type::rw::json::conversion::String2PixelType.at(t); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readIntEnum(const nlohmann::json& input, std::string& name, std::map<std::string, int>& acceptedValues, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readIntEnum(const nlohmann::json& input, + std::string& name, + std::map<std::string, int>& acceptedValues, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::INT_ENUM_TYPENAME_SLUG, p); name = input[rw::json::constantes::NAME_SLUG]; maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); - acceptedValues = input[rw::json::constantes::ELEMENTS_SLUG].get<std::map<std::string, int>>(); + acceptedValues = + input[rw::json::constantes::ELEMENTS_SLUG].get<std::map<std::string, int>>(); + + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readInt(const nlohmann::json& input, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readInt(const nlohmann::json& input, + int& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::INT_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readLong(const nlohmann::json& input, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readLong(const nlohmann::json& input, + long& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::LONG_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readFloat(const nlohmann::json& input, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readFloat(const nlohmann::json& input, + float& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::FLOAT_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readDouble(const nlohmann::json& input, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readDouble(const nlohmann::json& input, + double& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::DOUBLE_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readString(const nlohmann::json& input, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readString(const nlohmann::json& input, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::STRING_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readBool(const nlohmann::json& input, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readBool(const nlohmann::json& input, + bool& defaultValue, + type::Maybe& maybe, + Path& p) { getAronMetaInformationForType(input, rw::json::constantes::BOOL_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); + defaultValue = input[rw::json::constantes::DEFAULT_SLUG]; } - void NlohmannJSONReader::readAnyObject(const nlohmann::json& input, type::Maybe& maybe, Path& p) + void + NlohmannJSONReader::readAnyObject(const nlohmann::json& input, type::Maybe& maybe, Path& p) { getAronMetaInformationForType(input, rw::json::constantes::ANY_OBJECT_TYPENAME_SLUG, p); maybe = rw::json::conversion::String2Maybe.at(input[rw::json::constantes::MAYBE_SLUG]); } -} +} // namespace armarx::aron::type::reader diff --git a/source/RobotAPI/libraries/aron/core/type/rw/reader/nlohmannJSON/NlohmannJSONReader.h b/source/RobotAPI/libraries/aron/core/type/rw/reader/nlohmannJSON/NlohmannJSONReader.h index 3775977b41ff3bc07c6c7763ed87dc34123fb1aa..fea83d4c8178db7ee73be00660039c9ce0f19b23 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/reader/nlohmannJSON/NlohmannJSONReader.h +++ b/source/RobotAPI/libraries/aron/core/type/rw/reader/nlohmannJSON/NlohmannJSONReader.h @@ -32,8 +32,7 @@ namespace armarx::aron::type::reader { - class NlohmannJSONReader : - public ReaderInterface<const nlohmann::json> + class NlohmannJSONReader : public ReaderInterface<const nlohmann::json> { public: // constructors @@ -41,27 +40,92 @@ namespace armarx::aron::type::reader type::Descriptor getDescriptor(InputType& input) final; - void readObject(InputType& input, std::string& name, std::vector<std::string>& templates, std::vector<std::string>& templateInstantiations, std::map<std::string, InputTypeNonConst>& memberTypes, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readList(InputType& input, InputTypeNonConst& acceptedType, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readDict(InputType& input, InputTypeNonConst& acceptedType, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readTuple(InputType& input, std::vector<InputTypeNonConst>& acceptedTypes, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readPair(InputType& input, InputTypeNonConst& acceptedType1, InputTypeNonConst& acceptedType2, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readObject(InputType& input, + std::string& name, + std::vector<std::string>& templates, + std::vector<std::string>& templateInstantiations, + std::map<std::string, InputTypeNonConst>& memberTypes, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readList(InputType& input, + InputTypeNonConst& acceptedType, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readDict(InputType& input, + InputTypeNonConst& acceptedType, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readTuple(InputType& input, + std::vector<InputTypeNonConst>& acceptedTypes, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readPair(InputType& input, + InputTypeNonConst& acceptedType1, + InputTypeNonConst& acceptedType2, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; - void readNDArray(InputType& input, int& ndim, type::ndarray::ElementType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readMatrix(InputType& input, int& rows, int& cols, type::matrix::ElementType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readQuaternion(InputType& input, type::quaternion::ElementType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readPointCloud(InputType& input, type::pointcloud::VoxelType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readImage(InputType& input, type::image::PixelType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readNDArray(InputType& input, + int& ndim, + type::ndarray::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readMatrix(InputType& input, + int& rows, + int& cols, + type::matrix::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readQuaternion(InputType& input, + type::quaternion::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readPointCloud(InputType& input, + type::pointcloud::VoxelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readImage(InputType& input, + type::image::PixelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; - void readIntEnum(InputType& input, std::string& name, std::map<std::string, int>& acceptedValues, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readIntEnum(InputType& input, + std::string& name, + std::map<std::string, int>& acceptedValues, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; - void readInt(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readLong(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readFloat(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readDouble(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readString(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readBool(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readInt(InputType& input, + int& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readLong(InputType& input, + long& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readFloat(InputType& input, + float& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readDouble(InputType& input, + double& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readString(InputType& input, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readBool(InputType& input, + bool& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; void readAnyObject(InputType& input, type::Maybe& maybe, Path& p) override; }; -} +} // namespace armarx::aron::type::reader diff --git a/source/RobotAPI/libraries/aron/core/type/rw/reader/variant/VariantReader.cpp b/source/RobotAPI/libraries/aron/core/type/rw/reader/variant/VariantReader.cpp index 452f240a5373678a3523dbe418d670e065e62423..90dd15d49d84c6e330b1f2756bb4959e8daefb89 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/reader/variant/VariantReader.cpp +++ b/source/RobotAPI/libraries/aron/core/type/rw/reader/variant/VariantReader.cpp @@ -33,12 +33,20 @@ namespace armarx::aron::type::reader { - type::Descriptor VariantReader::getDescriptor(InputType& input) + type::Descriptor + VariantReader::getDescriptor(InputType& input) { return ConstVariantVisitor::GetDescriptor(input); } - void VariantReader::readObject(const aron::type::VariantPtr& input, std::string& name, std::vector<std::string>& templates, std::vector<std::string>& templateInstantiations, std::map<std::string, aron::type::VariantPtr>& memberTypes, type::Maybe& maybe, Path& p) + void + VariantReader::readObject(const aron::type::VariantPtr& input, + std::string& name, + std::vector<std::string>& templates, + std::vector<std::string>& templateInstantiations, + std::map<std::string, aron::type::VariantPtr>& memberTypes, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Object::DynamicCastAndCheck(input); @@ -50,7 +58,12 @@ namespace armarx::aron::type::reader memberTypes = o->getMemberTypes(); p = o->getPath(); } - void VariantReader::readList(const aron::type::VariantPtr& input, aron::type::VariantPtr& acceptedType, type::Maybe& maybe, Path& p) + + void + VariantReader::readList(const aron::type::VariantPtr& input, + aron::type::VariantPtr& acceptedType, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::List::DynamicCastAndCheck(input); @@ -60,7 +73,11 @@ namespace armarx::aron::type::reader p = o->getPath(); } - void VariantReader::readDict(const aron::type::VariantPtr& input, aron::type::VariantPtr& acceptedType, type::Maybe& maybe, Path& p) + void + VariantReader::readDict(const aron::type::VariantPtr& input, + aron::type::VariantPtr& acceptedType, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Dict::DynamicCastAndCheck(input); @@ -70,7 +87,11 @@ namespace armarx::aron::type::reader p = o->getPath(); } - void VariantReader::readTuple(const aron::type::VariantPtr& input, std::vector<aron::type::VariantPtr>& acceptedTypes, type::Maybe& maybe, Path& p) + void + VariantReader::readTuple(const aron::type::VariantPtr& input, + std::vector<aron::type::VariantPtr>& acceptedTypes, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Tuple::DynamicCastAndCheck(input); @@ -80,7 +101,12 @@ namespace armarx::aron::type::reader p = o->getPath(); } - void VariantReader::readPair(const aron::type::VariantPtr& input, aron::type::VariantPtr& acceptedType1, aron::type::VariantPtr& acceptedType2, type::Maybe& maybe, Path& p) + void + VariantReader::readPair(const aron::type::VariantPtr& input, + aron::type::VariantPtr& acceptedType1, + aron::type::VariantPtr& acceptedType2, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Pair::DynamicCastAndCheck(input); @@ -91,7 +117,13 @@ namespace armarx::aron::type::reader p = o->getPath(); } - void VariantReader::readNDArray(const aron::type::VariantPtr& input, int& ndim, type::ndarray::ElementType& type, type::Maybe& maybe, Path& p) + void + VariantReader::readNDArray(const aron::type::VariantPtr& input, + int& ndim, + type::ndarray::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::NDArray::DynamicCastAndCheck(input); @@ -99,10 +131,18 @@ namespace armarx::aron::type::reader maybe = o->getMaybe(); ndim = o->getNumberDimensions(); type = o->getElementType(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readMatrix(const aron::type::VariantPtr& input, int& rows, int& cols, type::matrix::ElementType& type, type::Maybe& maybe, Path& p) + void + VariantReader::readMatrix(const aron::type::VariantPtr& input, + int& rows, + int& cols, + type::matrix::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Matrix::DynamicCastAndCheck(input); @@ -111,40 +151,65 @@ namespace armarx::aron::type::reader rows = o->getRows(); cols = o->getCols(); type = o->getElementType(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readQuaternion(const aron::type::VariantPtr& input, type::quaternion::ElementType& type, type::Maybe& maybe, Path& p) + void + VariantReader::readQuaternion(const aron::type::VariantPtr& input, + type::quaternion::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Quaternion::DynamicCastAndCheck(input); maybe = o->getMaybe(); type = o->getElementType(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readPointCloud(const aron::type::VariantPtr& input, type::pointcloud::VoxelType& type, type::Maybe& maybe, Path& p) + void + VariantReader::readPointCloud(const aron::type::VariantPtr& input, + type::pointcloud::VoxelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::PointCloud::DynamicCastAndCheck(input); maybe = o->getMaybe(); type = o->getVoxelType(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readImage(const aron::type::VariantPtr& input, type::image::PixelType& type, type::Maybe& maybe, Path& p) + void + VariantReader::readImage(const aron::type::VariantPtr& input, + type::image::PixelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Image::DynamicCastAndCheck(input); maybe = o->getMaybe(); type = o->getPixelType(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readIntEnum(const aron::type::VariantPtr& input, std::string& name, std::map<std::string, int>& acceptedValues, type::Maybe& maybe, Path& p) + void + VariantReader::readIntEnum(const aron::type::VariantPtr& input, + std::string& name, + std::map<std::string, int>& acceptedValues, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::IntEnum::DynamicCastAndCheck(input); @@ -152,64 +217,96 @@ namespace armarx::aron::type::reader name = o->getEnumName(); acceptedValues = o->getAcceptedValueMap(); maybe = o->getMaybe(); + defaultValue = o->getDefaultValueName(); p = o->getPath(); } - void VariantReader::readInt(const aron::type::VariantPtr& input, type::Maybe& maybe, Path& p) + void + VariantReader::readInt(const aron::type::VariantPtr& input, + int& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Int::DynamicCastAndCheck(input); maybe = o->getMaybe(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readLong(const aron::type::VariantPtr& input, type::Maybe& maybe, Path& p) + void + VariantReader::readLong(const aron::type::VariantPtr& input, + long& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Long::DynamicCastAndCheck(input); maybe = o->getMaybe(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readFloat(const aron::type::VariantPtr& input, type::Maybe& maybe, Path& p) + void + VariantReader::readFloat(const aron::type::VariantPtr& input, + float& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Float::DynamicCastAndCheck(input); maybe = o->getMaybe(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readDouble(const aron::type::VariantPtr& input, type::Maybe& maybe, Path& p) + void + VariantReader::readDouble(const aron::type::VariantPtr& input, + double& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Double::DynamicCastAndCheck(input); maybe = o->getMaybe(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readString(const aron::type::VariantPtr& input, type::Maybe& maybe, Path& p) + void + VariantReader::readString(const aron::type::VariantPtr& input, + std::string& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::String::DynamicCastAndCheck(input); maybe = o->getMaybe(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readBool(const aron::type::VariantPtr& input, type::Maybe& maybe, Path& p) + void + VariantReader::readBool(const aron::type::VariantPtr& input, + bool& defaultValue, + type::Maybe& maybe, + Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::Bool::DynamicCastAndCheck(input); maybe = o->getMaybe(); + defaultValue = o->getDefaultValue(); p = o->getPath(); } - void VariantReader::readAnyObject(const aron::type::VariantPtr& input, type::Maybe& maybe, Path& p) + void + VariantReader::readAnyObject(const aron::type::VariantPtr& input, type::Maybe& maybe, Path& p) { ARMARX_CHECK_NOT_NULL(input); auto o = type::AnyObject::DynamicCastAndCheck(input); @@ -217,4 +314,4 @@ namespace armarx::aron::type::reader maybe = o->getMaybe(); p = o->getPath(); } -} +} // namespace armarx::aron::type::reader diff --git a/source/RobotAPI/libraries/aron/core/type/rw/reader/variant/VariantReader.h b/source/RobotAPI/libraries/aron/core/type/rw/reader/variant/VariantReader.h index 5b9d592c08b4e4b43d80b3f960d90e92288b01f6..5a9e8cb87d5745d1df3cc27350c13d46b3ac5725 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/reader/variant/VariantReader.h +++ b/source/RobotAPI/libraries/aron/core/type/rw/reader/variant/VariantReader.h @@ -30,11 +30,9 @@ // ArmarX #include <RobotAPI/libraries/aron/core/type/variant/Variant.h> - namespace armarx::aron::type::reader { - class VariantReader : - public ReaderInterface<const aron::type::VariantPtr> + class VariantReader : public ReaderInterface<const aron::type::VariantPtr> { public: // constructors @@ -42,27 +40,94 @@ namespace armarx::aron::type::reader type::Descriptor getDescriptor(InputType& input) final; - void readObject(InputType& input, std::string& name, std::vector<std::string>& templates, std::vector<std::string>& templateInstantiations, std::map<std::string, InputTypeNonConst>& memberTypes, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readList(InputType& input, InputTypeNonConst& acceptedType, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readDict(InputType& input, InputTypeNonConst& acceptedType, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readTuple(InputType& input, std::vector<InputTypeNonConst>& acceptedTypes, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readPair(InputType& input, InputTypeNonConst& acceptedType1, InputTypeNonConst& acceptedType2, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readObject(InputType& input, + std::string& name, + std::vector<std::string>& templates, + std::vector<std::string>& templateInstantiations, + std::map<std::string, InputTypeNonConst>& memberTypes, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readList(InputType& input, + InputTypeNonConst& acceptedType, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readDict(InputType& input, + InputTypeNonConst& acceptedType, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readTuple(InputType& input, + std::vector<InputTypeNonConst>& acceptedTypes, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readPair(InputType& input, + InputTypeNonConst& acceptedType1, + InputTypeNonConst& acceptedType2, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; - void readNDArray(InputType& input, int& ndim, type::ndarray::ElementType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readMatrix(InputType& input, int& rows, int& cols, type::matrix::ElementType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readQuaternion(InputType& input, type::quaternion::ElementType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readPointCloud(InputType& input, type::pointcloud::VoxelType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readImage(InputType& input, type::image::PixelType& type, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readNDArray(InputType& input, + int& ndim, + type::ndarray::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readMatrix(InputType& input, + int& rows, + int& cols, + type::matrix::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readQuaternion(InputType& input, + type::quaternion::ElementType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readPointCloud(InputType& input, + type::pointcloud::VoxelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readImage(InputType& input, + type::image::PixelType& type, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; - void readIntEnum(InputType& input, std::string& name, std::map<std::string, int>& acceptedValues, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readIntEnum(InputType& input, + std::string& name, + std::map<std::string, int>& acceptedValues, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; - void readInt(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readLong(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readFloat(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readDouble(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readString(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; - void readBool(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readInt(InputType& input, + int& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readLong(InputType& input, + long& defaultvalue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readFloat(InputType& input, + float& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readDouble(InputType& input, + double& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readString(InputType& input, + std::string& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; + void readBool(InputType& input, + bool& defaultValue, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; - void readAnyObject(InputType& input, type::Maybe& maybe, Path& p = *std::unique_ptr<Path>(new Path())) override; + void readAnyObject(InputType& input, + type::Maybe& maybe, + Path& p = *std::unique_ptr<Path>(new Path())) override; }; -} +} // namespace armarx::aron::type::reader diff --git a/source/RobotAPI/libraries/aron/core/type/rw/writer/nlohmannJSON/NlohmannJSONWriter.cpp b/source/RobotAPI/libraries/aron/core/type/rw/writer/nlohmannJSON/NlohmannJSONWriter.cpp index 159c604b10c0e0bb4d761cc855538240e879abbe..960d781ce3e7d438779fd304ac518562f63b9c4d 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/writer/nlohmannJSON/NlohmannJSONWriter.cpp +++ b/source/RobotAPI/libraries/aron/core/type/rw/writer/nlohmannJSON/NlohmannJSONWriter.cpp @@ -25,29 +25,41 @@ #include "NlohmannJSONWriter.h" // Constantes -#include "../../json/Data.h" #include <RobotAPI/libraries/aron/core/type/visitor/nlohmannJSON/NlohmannJSONVisitor.h> +#include "../../json/Data.h" namespace armarx::aron::type::writer { namespace { /// Set important members for json object (aron meta information) - void setupAronMetaInformationForType(nlohmann::json& json, const std::string& type, const type::Maybe& maybe, const Path& p) + void + setupAronMetaInformationForType(nlohmann::json& json, + const std::string& type, + const type::Maybe& maybe, + const Path& p) { json[rw::json::constantes::TYPE_SLUG] = type; json[rw::json::constantes::PATH_SLUG] = p.getPath(); json[rw::json::constantes::MAYBE_SLUG] = rw::json::conversion::Maybe2String.at(maybe); } - } + } // namespace - type::Descriptor NlohmannJSONWriter::getDescriptor(ReturnTypeConst& input) + type::Descriptor + NlohmannJSONWriter::getDescriptor(ReturnTypeConst& input) { return ConstNlohmannJSONVisitor::GetDescriptor(input); } - nlohmann::json NlohmannJSONWriter::writeObject(const std::string& name, const std::vector<std::string>& templates, const std::vector<std::string>& templateInstantiations, const std::map<std::string, nlohmann::json>& memberTypes, const std::optional<nlohmann::json>& extends, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeObject(const std::string& name, + const std::vector<std::string>& templates, + const std::vector<std::string>& templateInstantiations, + const std::map<std::string, nlohmann::json>& memberTypes, + const std::optional<nlohmann::json>& extends, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::OBJECT_TYPENAME_SLUG, maybe, p); @@ -73,7 +85,10 @@ namespace armarx::aron::type::writer return o; } - nlohmann::json NlohmannJSONWriter::writeList(const nlohmann::json& acceptedType, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeList(const nlohmann::json& acceptedType, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::LIST_TYPENAME_SLUG, maybe, p); @@ -81,7 +96,10 @@ namespace armarx::aron::type::writer return o; } - nlohmann::json NlohmannJSONWriter::writeDict(const nlohmann::json& acceptedType, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeDict(const nlohmann::json& acceptedType, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::DICT_TYPENAME_SLUG, maybe, p); @@ -89,7 +107,11 @@ namespace armarx::aron::type::writer return o; } - nlohmann::json NlohmannJSONWriter::writePair(const nlohmann::json& acceptedType1, const nlohmann::json& acceptedType2, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writePair(const nlohmann::json& acceptedType1, + const nlohmann::json& acceptedType2, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::PAIR_TYPENAME_SLUG, maybe, p); @@ -97,7 +119,10 @@ namespace armarx::aron::type::writer return o; } - nlohmann::json NlohmannJSONWriter::writeTuple(const std::vector<nlohmann::json>& acceptedTypes, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeTuple(const std::vector<nlohmann::json>& acceptedTypes, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::TUPLE_TYPENAME_SLUG, maybe, p); @@ -105,53 +130,90 @@ namespace armarx::aron::type::writer return o; } - nlohmann::json NlohmannJSONWriter::writeNDArray(const int ndim, const type::ndarray::ElementType type, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeNDArray(const int ndim, + const type::ndarray::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::NDARRAY_TYPENAME_SLUG, maybe, p); o[rw::json::constantes::USED_TYPE_SLUG] = rw::json::conversion::NDArrayType2String.at(type); o[rw::json::constantes::DIMENSIONS_SLUG] = ndim; + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeMatrix(const int rows, const int cols, const type::matrix::ElementType type, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeMatrix(const int rows, + const int cols, + const type::matrix::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::MATRIX_TYPENAME_SLUG, maybe, p); o[rw::json::constantes::USED_TYPE_SLUG] = rw::json::conversion::MatrixType2String.at(type); o[rw::json::constantes::DIMENSIONS_SLUG] = {rows, cols}; + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeQuaternion(const type::quaternion::ElementType type, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeQuaternion(const type::quaternion::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; - setupAronMetaInformationForType(o, rw::json::constantes::QUATERNION_TYPENAME_SLUG, maybe, p); - o[rw::json::constantes::USED_TYPE_SLUG] = rw::json::conversion::QuaternionType2String.at(type); + setupAronMetaInformationForType( + o, rw::json::constantes::QUATERNION_TYPENAME_SLUG, maybe, p); + o[rw::json::constantes::USED_TYPE_SLUG] = + rw::json::conversion::QuaternionType2String.at(type); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeImage(const type::image::PixelType type, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeImage(const type::image::PixelType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::IMAGE_TYPENAME_SLUG, maybe, p); o[rw::json::constantes::USED_TYPE_SLUG] = rw::json::conversion::PixelType2String.at(type); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writePointCloud(const type::pointcloud::VoxelType type, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writePointCloud(const type::pointcloud::VoxelType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; - setupAronMetaInformationForType(o, rw::json::constantes::POINT_CLOUD_TYPENAME_SLUG, maybe, p); + setupAronMetaInformationForType( + o, rw::json::constantes::POINT_CLOUD_TYPENAME_SLUG, maybe, p); o[rw::json::constantes::USED_TYPE_SLUG] = rw::json::conversion::VoxelType2String.at(type); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeIntEnum(const std::string& name, const std::map<std::string, int>& acceptedValues, const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeIntEnum(const std::string& name, + const std::map<std::string, int>& acceptedValues, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::INT_ENUM_TYPENAME_SLUG, maybe, p); o[rw::json::constantes::NAME_SLUG] = name; + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; o[rw::json::constantes::ELEMENTS_SLUG] = nlohmann::json(nlohmann::json::value_t::object); for (const auto& [key, value] : acceptedValues) @@ -161,52 +223,68 @@ namespace armarx::aron::type::writer return o; } - nlohmann::json NlohmannJSONWriter::writeInt(const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeInt(int defaultValue, const type::Maybe maybe, const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::INT_TYPENAME_SLUG, maybe, p); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeLong(const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeLong(long defaultValue, const type::Maybe maybe, const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::LONG_TYPENAME_SLUG, maybe, p); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeFloat(const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeFloat(float defaultValue, const type::Maybe maybe, const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::FLOAT_TYPENAME_SLUG, maybe, p); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeDouble(const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeDouble(double defaultValue, const type::Maybe maybe, const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::DOUBLE_TYPENAME_SLUG, maybe, p); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeString(const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeString(const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::STRING_TYPENAME_SLUG, maybe, p); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeBool(const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeBool(bool defaultValue, const type::Maybe maybe, const Path& p) { nlohmann::json o; setupAronMetaInformationForType(o, rw::json::constantes::BOOL_TYPENAME_SLUG, maybe, p); + o[rw::json::constantes::DEFAULT_SLUG] = defaultValue; return o; } - nlohmann::json NlohmannJSONWriter::writeAnyObject(const type::Maybe maybe, const Path& p) + nlohmann::json + NlohmannJSONWriter::writeAnyObject(const type::Maybe maybe, const Path& p) { nlohmann::json o; - setupAronMetaInformationForType(o, rw::json::constantes::ANY_OBJECT_TYPENAME_SLUG, maybe, p); + setupAronMetaInformationForType( + o, rw::json::constantes::ANY_OBJECT_TYPENAME_SLUG, maybe, p); return o; } -} +} // namespace armarx::aron::type::writer diff --git a/source/RobotAPI/libraries/aron/core/type/rw/writer/nlohmannJSON/NlohmannJSONWriter.h b/source/RobotAPI/libraries/aron/core/type/rw/writer/nlohmannJSON/NlohmannJSONWriter.h index 25e89bdf09322528c30aac0d94a41d6483497c25..6020bb54cdf1e71efb65ce933194c0aef674e115 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/writer/nlohmannJSON/NlohmannJSONWriter.h +++ b/source/RobotAPI/libraries/aron/core/type/rw/writer/nlohmannJSON/NlohmannJSONWriter.h @@ -22,8 +22,8 @@ // STD / STL #include <memory> -#include <stack> #include <sstream> +#include <stack> // Simox #include <SimoxUtility/json.h> @@ -33,35 +33,78 @@ namespace armarx::aron::type::writer { - class NlohmannJSONWriter : - public WriterInterface<nlohmann::json> + class NlohmannJSONWriter : public WriterInterface<nlohmann::json> { public: NlohmannJSONWriter() = default; type::Descriptor getDescriptor(ReturnTypeConst& input) final; - ReturnType writeObject(const std::string& name, const std::vector<std::string>& templates, const std::vector<std::string>& templateInstantiations, const std::map<std::string, ReturnType>& memberTypes, const std::optional<ReturnType>& extends, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeList(const ReturnType& acceptedType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeDict(const ReturnType& acceptedType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writePair(const ReturnType& acceptedType1, const ReturnType& acceptedType2, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeTuple(const std::vector<ReturnType>& acceptedTypes, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType writeObject(const std::string& name, + const std::vector<std::string>& templates, + const std::vector<std::string>& templateInstantiations, + const std::map<std::string, ReturnType>& memberTypes, + const std::optional<ReturnType>& extends, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeList(const ReturnType& acceptedType, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeDict(const ReturnType& acceptedType, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writePair(const ReturnType& acceptedType1, + const ReturnType& acceptedType2, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeTuple(const std::vector<ReturnType>& acceptedTypes, + const type::Maybe maybe, + const Path& p = Path()) override; - ReturnType writeNDArray(const int ndim, const type::ndarray::ElementType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeMatrix(const int rows, const int cols, const type::matrix::ElementType type, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeQuaternion(const type::quaternion::ElementType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeImage(const type::image::PixelType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writePointCloud(const type::pointcloud::VoxelType, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType writeNDArray(const int ndim, + const type::ndarray::ElementType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeMatrix(const int rows, + const int cols, + const type::matrix::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeQuaternion(const type::quaternion::ElementType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeImage(const type::image::PixelType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writePointCloud(const type::pointcloud::VoxelType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; - ReturnType writeIntEnum(const std::string& name, const std::map<std::string, int>& acceptedValues, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType writeIntEnum(const std::string& name, + const std::map<std::string, int>& acceptedValues, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; - ReturnType writeInt(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeLong(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeFloat(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeDouble(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeString(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeBool(const type::Maybe maybe, const Path& p = Path()) override; + ReturnType + writeInt(int defaultValue, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType + writeLong(long defaultValue, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType + writeFloat(float defaultValue, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType + writeDouble(double defaultValue, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType writeString(const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType + writeBool(bool defaultValue, const type::Maybe maybe, const Path& p = Path()) override; ReturnType writeAnyObject(const type::Maybe maybe, const Path& p = Path()) override; }; -} +} // namespace armarx::aron::type::writer diff --git a/source/RobotAPI/libraries/aron/core/type/rw/writer/variant/VariantWriter.cpp b/source/RobotAPI/libraries/aron/core/type/rw/writer/variant/VariantWriter.cpp index 87af0839552de8e5a66a3e48bb2a95763f6636cb..40f5987949d14c905e3b54030b609918f2cb2949 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/writer/variant/VariantWriter.cpp +++ b/source/RobotAPI/libraries/aron/core/type/rw/writer/variant/VariantWriter.cpp @@ -20,23 +20,35 @@ #include "VariantWriter.h" -#include <RobotAPI/libraries/aron/core/type/variant/All.h> - #include <memory> #include <numeric> + +#include <RobotAPI/libraries/aron/core/type/variant/All.h> #include <RobotAPI/libraries/aron/core/type/visitor/variant/VariantVisitor.h> namespace armarx::aron::type::writer { - type::Descriptor VariantWriter::getDescriptor(ReturnTypeConst& input) + type::Descriptor + VariantWriter::getDescriptor(ReturnTypeConst& input) { return ConstVariantVisitor::GetDescriptor(input); } - aron::type::VariantPtr VariantWriter::writeObject(const std::string& name, const std::vector<std::string>& templates, const std::vector<std::string>& templateInstantiations, const std::map<std::string, aron::type::VariantPtr>& memberTypes, const std::optional<aron::type::VariantPtr>& extends, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeObject(const std::string& name, + const std::vector<std::string>& templates, + const std::vector<std::string>& templateInstantiations, + const std::map<std::string, aron::type::VariantPtr>& memberTypes, + const std::optional<aron::type::VariantPtr>& extends, + const type::Maybe maybe, + const Path& p) { - auto o = std::make_shared<type::Object>(name, templates, templateInstantiations, memberTypes, p); + auto o = std::make_shared<type::Object>(p); + o->setObjectName(name); + o->setTemplates(templates); + o->setTemplateInstantiations(templateInstantiations); + o->setMemberTypes(memberTypes); o->setMaybe(maybe); if (extends.has_value()) { @@ -46,127 +58,198 @@ namespace armarx::aron::type::writer return o; } - aron::type::VariantPtr VariantWriter::writeList(const aron::type::VariantPtr& acceptedType, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeList(const aron::type::VariantPtr& acceptedType, + const type::Maybe maybe, + const Path& p) { - auto o = std::make_shared<type::List>(acceptedType, p); + auto o = std::make_shared<type::List>(p); + o->setAcceptedType(acceptedType); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeDict(const aron::type::VariantPtr& acceptedType, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeDict(const aron::type::VariantPtr& acceptedType, + const type::Maybe maybe, + const Path& p) { - auto o = std::make_shared<type::Dict>(acceptedType, p); + auto o = std::make_shared<type::Dict>(p); + o->setAcceptedType(acceptedType); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writePair(const aron::type::VariantPtr& acceptedType1, const aron::type::VariantPtr& acceptedType2, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writePair(const aron::type::VariantPtr& acceptedType1, + const aron::type::VariantPtr& acceptedType2, + const type::Maybe maybe, + const Path& p) { - auto o = std::make_shared<type::Pair>(acceptedType1, acceptedType2, p); + auto o = std::make_shared<type::Pair>(p); + o->setFirstAcceptedType(acceptedType1); + o->setSecondAcceptedType(acceptedType2); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeTuple(const std::vector<aron::type::VariantPtr>& acceptedTypes, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeTuple(const std::vector<aron::type::VariantPtr>& acceptedTypes, + const type::Maybe maybe, + const Path& p) { - auto o = std::make_shared<type::Tuple>(acceptedTypes, p); + auto o = std::make_shared<type::Tuple>(p); + o->setAcceptedTypes(acceptedTypes); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeNDArray(const int ndim, const type::ndarray::ElementType, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeNDArray(const int ndim, + const type::ndarray::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { - auto o = std::make_shared<type::NDArray>(p); - return o; + auto o = std::make_shared<type::NDArray>(p); + o->setMaybe(maybe); + o->setElementType(type); + o->setDefaultValue(defaultValue); + return o; } - aron::type::VariantPtr VariantWriter::writeMatrix(const int rows, const int cols, const type::matrix::ElementType type, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeMatrix(const int rows, + const int cols, + const type::matrix::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { auto o = std::make_shared<type::Matrix>(p); o->setMaybe(maybe); o->setRows(rows); o->setCols(cols); o->setElementType(type); + o->setDefaultValue(defaultValue); return o; } - aron::type::VariantPtr VariantWriter::writeQuaternion(const type::quaternion::ElementType type, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeQuaternion(const type::quaternion::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { auto o = std::make_shared<type::Quaternion>(p); o->setMaybe(maybe); o->setElementType(type); + o->setDefaultValue(defaultValue); return o; } - aron::type::VariantPtr VariantWriter::writeImage(const type::image::PixelType type, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeImage(const type::image::PixelType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { auto o = std::make_shared<type::Image>(p); o->setMaybe(maybe); o->setPixelType(type); + o->setDefaultValue(defaultValue); return o; } - aron::type::VariantPtr VariantWriter::writePointCloud(const type::pointcloud::VoxelType type, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writePointCloud(const type::pointcloud::VoxelType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { auto o = std::make_shared<type::PointCloud>(p); o->setMaybe(maybe); o->setVoxelType(type); + o->setDefaultValue(defaultValue); return o; } - aron::type::VariantPtr VariantWriter::writeIntEnum(const std::string& name, const std::map<std::string, int>& acceptedValues, const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeIntEnum(const std::string& name, + const std::map<std::string, int>& acceptedValues, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { - auto o = std::make_shared<type::IntEnum>(name, acceptedValues, p); + auto o = std::make_shared<type::IntEnum>(p); + o->setEnumName(name); + o->setAcceptedValueMap(acceptedValues); + o->setDefaultValueName(defaultValue); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeInt(const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeInt(int defaultValue, const type::Maybe maybe, const Path& p) { auto o = std::make_shared<type::Int>(p); + o->setDefaultValue(defaultValue); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeLong(const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeLong(long defaultValue, const type::Maybe maybe, const Path& p) { auto o = std::make_shared<type::Long>(p); + o->setDefaultValue(defaultValue); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeFloat(const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeFloat(float defaultValue, const type::Maybe maybe, const Path& p) { auto o = std::make_shared<type::Float>(p); + o->setDefaultValue(defaultValue); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeDouble(const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeDouble(double defaultValue, const type::Maybe maybe, const Path& p) { auto o = std::make_shared<type::Double>(p); + o->setDefaultValue(defaultValue); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeString(const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeString(const std::string& defaultValue, + const type::Maybe maybe, + const Path& p) { auto o = std::make_shared<type::String>(p); + o->setDefaultValue(defaultValue); o->setMaybe(maybe); return o; } - aron::type::VariantPtr VariantWriter::writeBool(const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeBool(bool defaultValue, const type::Maybe maybe, const Path& p) { auto o = std::make_shared<type::Bool>(p); o->setMaybe(maybe); + o->setDefaultValue(defaultValue); return o; } - aron::type::VariantPtr VariantWriter::writeAnyObject(const type::Maybe maybe, const Path& p) + aron::type::VariantPtr + VariantWriter::writeAnyObject(const type::Maybe maybe, const Path& p) { auto o = std::make_shared<type::AnyObject>(p); o->setMaybe(maybe); return o; } -} +} // namespace armarx::aron::type::writer diff --git a/source/RobotAPI/libraries/aron/core/type/rw/writer/variant/VariantWriter.h b/source/RobotAPI/libraries/aron/core/type/rw/writer/variant/VariantWriter.h index 92fea0d713c496a4b09915dc392252a5c8c9275a..78accf7c8390313d1410cfe6e276489235da3b25 100644 --- a/source/RobotAPI/libraries/aron/core/type/rw/writer/variant/VariantWriter.h +++ b/source/RobotAPI/libraries/aron/core/type/rw/writer/variant/VariantWriter.h @@ -20,44 +20,86 @@ #pragma once -#include <RobotAPI/libraries/aron/core/type/rw/Writer.h> -#include <RobotAPI/libraries/aron/core/type/variant/Variant.h> - #include <memory> #include <stack> +#include <RobotAPI/libraries/aron/core/type/rw/Writer.h> +#include <RobotAPI/libraries/aron/core/type/variant/Variant.h> namespace armarx::aron::type::writer { - class VariantWriter : - public type::WriterInterface<aron::type::VariantPtr> + class VariantWriter : public type::WriterInterface<aron::type::VariantPtr> { public: VariantWriter() = default; type::Descriptor getDescriptor(ReturnTypeConst& input) final; - ReturnType writeObject(const std::string& name, const std::vector<std::string>& templates, const std::vector<std::string>& templateInstantiations, const std::map<std::string, ReturnType>& memberTypes, const std::optional<ReturnType>& extends, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeList(const ReturnType& acceptedType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeDict(const ReturnType& acceptedType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writePair(const ReturnType& acceptedType1, const ReturnType& acceptedType2, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeTuple(const std::vector<ReturnType>& acceptedTypes, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType writeObject(const std::string& name, + const std::vector<std::string>& templates, + const std::vector<std::string>& templateInstantiations, + const std::map<std::string, ReturnType>& memberTypes, + const std::optional<ReturnType>& extends, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeList(const ReturnType& acceptedType, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeDict(const ReturnType& acceptedType, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writePair(const ReturnType& acceptedType1, + const ReturnType& acceptedType2, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeTuple(const std::vector<ReturnType>& acceptedTypes, + const type::Maybe maybe, + const Path& p = Path()) override; - ReturnType writeNDArray(const int ndim, const type::ndarray::ElementType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeMatrix(const int rows, const int cols, const type::matrix::ElementType type, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeQuaternion(const type::quaternion::ElementType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeImage(const type::image::PixelType, const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writePointCloud(const type::pointcloud::VoxelType, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType writeNDArray(const int ndim, + const type::ndarray::ElementType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeMatrix(const int rows, + const int cols, + const type::matrix::ElementType type, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeQuaternion(const type::quaternion::ElementType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writeImage(const type::image::PixelType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType writePointCloud(const type::pointcloud::VoxelType, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; - ReturnType writeIntEnum(const std::string& name, const std::map<std::string, int>& acceptedValues, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType writeIntEnum(const std::string& name, + const std::map<std::string, int>& acceptedValues, + const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; - ReturnType writeInt(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeLong(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeFloat(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeDouble(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeString(const type::Maybe maybe, const Path& p = Path()) override; - ReturnType writeBool(const type::Maybe maybe, const Path& p = Path()) override; + ReturnType + writeInt(int defaultValue, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType + writeLong(long defaultValue, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType + writeFloat(float defaultValue, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType + writeDouble(double defaultValue, const type::Maybe maybe, const Path& p = Path()) override; + ReturnType writeString(const std::string& defaultValue, + const type::Maybe maybe, + const Path& p = Path()) override; + ReturnType + writeBool(bool defaultValue, const type::Maybe maybe, const Path& p = Path()) override; ReturnType writeAnyObject(const type::Maybe maybe, const Path& p = Path()) override; }; -} +} // namespace armarx::aron::type::writer diff --git a/source/RobotAPI/libraries/aron/core/type/variant/Factory.cpp b/source/RobotAPI/libraries/aron/core/type/variant/Factory.cpp index 405a5e7487213fc8097acc09986a8012b81edfad..fccc4e1306af41cc3498c700f8ed448e83d42b7b 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/Factory.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/Factory.cpp @@ -32,32 +32,85 @@ namespace armarx::aron::type { // Access method - std::unique_ptr<type::Variant> VariantFactory::create(const type::dto::GenericType& aron, const Path& path) const + std::unique_ptr<type::Variant> + VariantFactory::create(const type::dto::GenericType& aron, const Path& path) const { + + auto aronVersion = aron.VERSION; + if (aronVersion != armarx::aron::VERSION) + { + ARMARX_WARNING + << "Found inconsistencies in aron versions. This may lead to ice marshalling " + "exceptions. Please make sure to update the sender and receiver packages. " + << aronVersion << " != " << armarx::aron::VERSION; + } + auto descriptor = type::Aron2Descriptor(aron); - switch(descriptor) + switch (descriptor) { - case type::Descriptor::LIST: return std::make_unique<type::List>(dynamic_cast<const type::dto::List&>(aron), path); - case type::Descriptor::DICT: return std::make_unique<type::Dict>(dynamic_cast<const type::dto::Dict&>(aron), path); - case type::Descriptor::PAIR: return std::make_unique<type::Pair>(dynamic_cast<const type::dto::Pair&>(aron), path); - case type::Descriptor::TUPLE: return std::make_unique<type::Tuple>(dynamic_cast<const type::dto::Tuple&>(aron), path); - case type::Descriptor::OBJECT: return std::make_unique<type::Object>(dynamic_cast<const type::dto::AronObject&>(aron), path); - case type::Descriptor::NDARRAY: return std::make_unique<type::NDArray>(dynamic_cast<const type::dto::NDArray&>(aron), path); - case type::Descriptor::MATRIX: return std::make_unique<type::Matrix>(dynamic_cast<const type::dto::Matrix&>(aron), path); - case type::Descriptor::IMAGE: return std::make_unique<type::Image>(dynamic_cast<const type::dto::Image&>(aron), path); - case type::Descriptor::POINTCLOUD: return std::make_unique<type::PointCloud>(dynamic_cast<const type::dto::PointCloud&>(aron), path); - case type::Descriptor::QUATERNION: return std::make_unique<type::Quaternion>(dynamic_cast<const type::dto::Quaternion&>(aron), path); - case type::Descriptor::INT_ENUM: return std::make_unique<type::IntEnum>(dynamic_cast<const type::dto::IntEnum&>(aron), path); - case type::Descriptor::INT: return std::make_unique<type::Int>(dynamic_cast<const type::dto::AronInt&>(aron), path); - case type::Descriptor::LONG: return std::make_unique<type::Long>(dynamic_cast<const type::dto::AronLong&>(aron), path); - case type::Descriptor::FLOAT: return std::make_unique<type::Float>(dynamic_cast<const type::dto::AronFloat&>(aron), path); - case type::Descriptor::DOUBLE: return std::make_unique<type::Double>(dynamic_cast<const type::dto::AronDouble&>(aron), path); - case type::Descriptor::STRING: return std::make_unique<type::String>(dynamic_cast<const type::dto::AronString&>(aron), path); - case type::Descriptor::BOOL: return std::make_unique<type::Bool>(dynamic_cast<const type::dto::AronBool&>(aron), path); - case type::Descriptor::ANY_OBJECT: return std::make_unique<type::AnyObject>(dynamic_cast<const type::dto::AnyObject&>(aron), path); - case type::Descriptor::UNKNOWN: break; + case type::Descriptor::LIST: + return std::make_unique<type::List>(dynamic_cast<const type::dto::List&>(aron), + path); + case type::Descriptor::DICT: + return std::make_unique<type::Dict>(dynamic_cast<const type::dto::Dict&>(aron), + path); + case type::Descriptor::PAIR: + return std::make_unique<type::Pair>(dynamic_cast<const type::dto::Pair&>(aron), + path); + case type::Descriptor::TUPLE: + return std::make_unique<type::Tuple>(dynamic_cast<const type::dto::Tuple&>(aron), + path); + case type::Descriptor::OBJECT: + return std::make_unique<type::Object>( + dynamic_cast<const type::dto::AronObject&>(aron), path); + case type::Descriptor::NDARRAY: + return std::make_unique<type::NDArray>( + dynamic_cast<const type::dto::NDArray&>(aron), path); + case type::Descriptor::MATRIX: + return std::make_unique<type::Matrix>(dynamic_cast<const type::dto::Matrix&>(aron), + path); + case type::Descriptor::IMAGE: + return std::make_unique<type::Image>(dynamic_cast<const type::dto::Image&>(aron), + path); + case type::Descriptor::POINTCLOUD: + return std::make_unique<type::PointCloud>( + dynamic_cast<const type::dto::PointCloud&>(aron), path); + case type::Descriptor::QUATERNION: + return std::make_unique<type::Quaternion>( + dynamic_cast<const type::dto::Quaternion&>(aron), path); + case type::Descriptor::INT_ENUM: + return std::make_unique<type::IntEnum>( + dynamic_cast<const type::dto::IntEnum&>(aron), path); + case type::Descriptor::INT: + return std::make_unique<type::Int>(dynamic_cast<const type::dto::AronInt&>(aron), + path); + case type::Descriptor::LONG: + return std::make_unique<type::Long>(dynamic_cast<const type::dto::AronLong&>(aron), + path); + case type::Descriptor::FLOAT: + return std::make_unique<type::Float>( + dynamic_cast<const type::dto::AronFloat&>(aron), path); + case type::Descriptor::DOUBLE: + return std::make_unique<type::Double>( + dynamic_cast<const type::dto::AronDouble&>(aron), path); + case type::Descriptor::STRING: + return std::make_unique<type::String>( + dynamic_cast<const type::dto::AronString&>(aron), path); + case type::Descriptor::BOOL: + return std::make_unique<type::Bool>(dynamic_cast<const type::dto::AronBool&>(aron), + path); + case type::Descriptor::ANY_OBJECT: + return std::make_unique<type::AnyObject>( + dynamic_cast<const type::dto::AnyObject&>(aron), path); + case type::Descriptor::UNKNOWN: + break; } - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Got an unknown descriptor", std::to_string((int) descriptor) + " aka " + defaultconversion::string::Descriptor2String.at(descriptor), path); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, + "Got an unknown descriptor", + std::to_string((int)descriptor) + " aka " + + defaultconversion::string::Descriptor2String.at(descriptor), + path); } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/Variant.h b/source/RobotAPI/libraries/aron/core/type/variant/Variant.h index ab996582c630a9083bafb45bc7ec19755e59bb67..6a1e2afa366ff9ae61bef7871d1ddaff9f1b070e 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/Variant.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/Variant.h @@ -24,19 +24,19 @@ #pragma once // STD/STL -#include <memory> -#include <vector> #include <map> +#include <memory> #include <string> +#include <vector> // Simox // #include <SimoxUtility/algorithm/string.h> // ArmarX -#include <RobotAPI/libraries/aron/core/Path.h> -#include <RobotAPI/libraries/aron/core/Exception.h> #include <RobotAPI/interface/aron.h> #include <RobotAPI/libraries/aron/core/Descriptor.h> +#include <RobotAPI/libraries/aron/core/Exception.h> +#include <RobotAPI/libraries/aron/core/Path.h> namespace armarx::aron::type { @@ -64,15 +64,17 @@ namespace armarx::aron::type public: // constructors Variant(const type::Descriptor& descriptor, const Path& path = Path()) : - descriptor(descriptor), - path(path) + descriptor(descriptor), path(path) { } + virtual ~Variant() = default; // operators virtual bool operator==(const Variant& other) const = 0; - bool operator==(const VariantPtr& other) const + + bool + operator==(const VariantPtr& other) const { if (!other) { @@ -87,17 +89,20 @@ namespace armarx::aron::type static VariantPtr FromAronDTO(const type::dto::GenericType&, const Path& = Path()); // public methods - type::Descriptor getDescriptor() const + type::Descriptor + getDescriptor() const { return descriptor; } - Path getPath() const + Path + getPath() const { return path; } - std::string pathToString() const + std::string + pathToString() const { return path.toString(); } @@ -139,4 +144,4 @@ namespace armarx::aron::type template <class T> concept isVariant = std::is_base_of<Variant, T>::value; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/Dict.cpp b/source/RobotAPI/libraries/aron/core/type/variant/container/Dict.cpp index edaeccf90a02ec918fdbc90733a8209616e0bc1b..18dcb97e8c0b33b16db4b076d9481bce36cd2f51 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/Dict.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/Dict.cpp @@ -24,15 +24,12 @@ // Header #include "Dict.h" - namespace armarx::aron::type { // constructors - Dict::Dict(const VariantPtr& acceptedType, const Path& path) : - detail::ContainerVariant<type::dto::Dict, Dict>(type::Descriptor::DICT, path), - acceptedType(acceptedType) + Dict::Dict(const Path& path) : + detail::ContainerVariant<type::dto::Dict, Dict>(type::Descriptor::DICT, path) { - aron->acceptedType = acceptedType->toAronDTO(); } Dict::Dict(const type::dto::Dict& o, const Path& path) : @@ -41,75 +38,87 @@ namespace armarx::aron::type { } - VariantPtr Dict::getAcceptedType() const + VariantPtr + Dict::getAcceptedType() const { ARMARX_CHECK_NOT_NULL(acceptedType); return acceptedType; } - void Dict::setAcceptedType(const VariantPtr& a) + void + Dict::setAcceptedType(const VariantPtr& a) { ARMARX_CHECK_NOT_NULL(a); aron->acceptedType = a->toAronDTO(); acceptedType = a; } - type::dto::DictPtr Dict::toDictDTO() const + type::dto::DictPtr + Dict::toDictDTO() const { return aron; } // virtual implementations - std::vector<VariantPtr> Dict::getChildren() const + std::vector<VariantPtr> + Dict::getChildren() const { return {acceptedType}; } - size_t Dict::childrenSize() const + size_t + Dict::childrenSize() const { return 1; } - std::string Dict::getShortName() const + std::string + Dict::getShortName() const { return "Dict<" + acceptedType->getShortName() + ">"; } - std::string Dict::getFullName() const + std::string + Dict::getFullName() const { return "armarx::aron::type::Dict<" + acceptedType->getFullName() + ">"; } - std::string Dict::GetFullNamePrefix() + std::string + Dict::GetFullNamePrefix() { return "armarx::aron::type::Dict"; } - std::string Dict::GetNamePrefix() + std::string + Dict::GetNamePrefix() { return "Dict"; } - VariantPtr Dict::navigateAbsolute(const Path& path) const + VariantPtr + Dict::navigateAbsolute(const Path& path) const { if (!path.hasElement()) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate without a valid path", path); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not navigate without a valid path", path); } if (path.size() != 1) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not get more than 1 value from a dict.", path); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not get more than 1 value from a dict.", path); } std::string el = path.getFirstElement(); if (el != "::accepted_type") { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); } return acceptedType; } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/Dict.h b/source/RobotAPI/libraries/aron/core/type/variant/container/Dict.h index 7ebbf72eaa7a7582d9b33157279b857c14756540..9ae860df56869350ba2c6e56127ce8d21d6a3b46 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/Dict.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/Dict.h @@ -24,8 +24,8 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base Class #include "../detail/ContainerVariant.h" @@ -37,12 +37,11 @@ namespace armarx::aron::type * A dict only has an accepted type (a variant) * for the corresponding data object @see data/variant/container/Dict.h */ - class Dict : - public detail::ContainerVariant<type::dto::Dict, Dict> + class Dict : public detail::ContainerVariant<type::dto::Dict, Dict> { public: // constructors - Dict(const VariantPtr& acceptedType, const Path& path = Path()); + Dict(const Path& path = Path()); Dict(const type::dto::Dict&, const Path& path = Path()); // public member functions @@ -66,4 +65,4 @@ namespace armarx::aron::type // members VariantPtr acceptedType; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/List.cpp b/source/RobotAPI/libraries/aron/core/type/variant/container/List.cpp index 958596b7e60f201e565d7082d2e26c7107d7ce05..a5d036f35061ca17107e2effcd91795153d9f499 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/List.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/List.cpp @@ -27,11 +27,9 @@ namespace armarx::aron::type { // constructors - List::List(const VariantPtr& acceptedType, const Path& path) : - detail::ContainerVariant<type::dto::List, List>(type::Descriptor::LIST, path), - acceptedType(acceptedType) + List::List(const Path& path) : + detail::ContainerVariant<type::dto::List, List>(type::Descriptor::LIST, path) { - aron->acceptedType = acceptedType->toAronDTO(); } List::List(const type::dto::List& o, const Path& path) : @@ -41,12 +39,14 @@ namespace armarx::aron::type } // Member functions - VariantPtr List::getAcceptedType() const + VariantPtr + List::getAcceptedType() const { return acceptedType; } - void List::setAcceptedType(const VariantPtr& a) + void + List::setAcceptedType(const VariantPtr& a) { ARMARX_CHECK_NOT_NULL(a); aron->acceptedType = a->toAronDTO(); @@ -54,61 +54,72 @@ namespace armarx::aron::type } // static methods - type::dto::ListPtr List::toListDTO() const + type::dto::ListPtr + List::toListDTO() const { return aron; } // virtual implementations - std::vector<VariantPtr> List::getChildren() const + std::vector<VariantPtr> + List::getChildren() const { return {acceptedType}; } - size_t List::childrenSize() const + size_t + List::childrenSize() const { return 1; } - std::string List::getShortName() const + std::string + List::getShortName() const { return "List<" + acceptedType->getShortName() + ">"; } - std::string List::getFullName() const + std::string + List::getFullName() const { return "armarx::aron::type::List<" + acceptedType->getFullName() + ">"; } - std::string List::GetFullNamePrefix() + std::string + List::GetFullNamePrefix() { return "armarx::aron::type::List"; } - std::string List::GetNamePrefix() + std::string + List::GetNamePrefix() { return "List"; } - VariantPtr List::navigateAbsolute(const Path& path) const + VariantPtr + List::navigateAbsolute(const Path& path) const { if (!path.hasElement()) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate without a valid path", path); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not navigate without a valid path", path); } if (path.size() != 1) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not get more than 1 value from a dict.", path); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not get more than 1 value from a dict.", path); } std::string el = path.getFirstElement(); if (el != "::accepted_type") { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); } return acceptedType; } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/List.h b/source/RobotAPI/libraries/aron/core/type/variant/container/List.h index 67db861e299cc4031f560fbaa6507b20f1f3fbc5..4334468eeff2c121d5b93bc1589eca547beb964c 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/List.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/List.h @@ -36,12 +36,11 @@ namespace armarx::aron::type * @brief The List class. It represents the list type * It only has an accepted type (a variant) */ - class List : - public detail::ContainerVariant<type::dto::List, List> + class List : public detail::ContainerVariant<type::dto::List, List> { public: // constructors - List(const VariantPtr& acceptedType, const Path& path = Path()); + List(const Path& path = Path()); List(const type::dto::List&, const Path& path = Path()); // public member functions @@ -65,4 +64,4 @@ namespace armarx::aron::type // members VariantPtr acceptedType; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/Object.cpp b/source/RobotAPI/libraries/aron/core/type/variant/container/Object.cpp index f6d7d259a33220799098537cf1320d1a965bc4f7..bdcd00aa9914823bab7214631eb6fd06c5bbc2c0 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/Object.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/Object.cpp @@ -24,26 +24,16 @@ // Header #include "Object.h" - #include <SimoxUtility/algorithm/get_map_keys_values.h> #include <SimoxUtility/algorithm/string/string_conversion.h> - namespace armarx::aron::type { // constructors - Object::Object(const std::string& name, const std::vector<std::string>& templates, const std::vector<std::string>& templateInstantiations, const std::map<std::string, VariantPtr>& m, const Path& path) : - detail::ContainerVariant<type::dto::AronObject, Object>(type::Descriptor::OBJECT, path), - memberTypes(m) + Object::Object(const Path& path) : + detail::ContainerVariant<type::dto::AronObject, Object>(type::Descriptor::OBJECT, path) { - aron->templates = templates; - aron->templateInstantiations = templateInstantiations; - setObjectName(name); - for (const auto& [key, value] : memberTypes) - { - aron->elementTypes[key] = value->toAronDTO(); - } } Object::Object(const type::dto::AronObject& o, const Path& path) : @@ -60,7 +50,8 @@ namespace armarx::aron::type } } - ObjectPtr Object::FromAronObjectDTO(const type::dto::AronObjectPtr& aron, const aron::Path& path) + ObjectPtr + Object::FromAronObjectDTO(const type::dto::AronObjectPtr& aron, const aron::Path& path) { if (!aron) { @@ -69,7 +60,8 @@ namespace armarx::aron::type return std::make_shared<Object>(*aron, path); } - type::dto::AronObjectPtr Object::ToAronObjectDTO(const ObjectPtr& aron) + type::dto::AronObjectPtr + Object::ToAronObjectDTO(const ObjectPtr& aron) { if (!aron) { @@ -78,7 +70,8 @@ namespace armarx::aron::type return aron->toAronObjectDTO(); } - bool Object::checkObjectName(const std::string& s) const + bool + Object::checkObjectName(const std::string& s) const { if (s.empty()) { @@ -89,7 +82,30 @@ namespace armarx::aron::type } // public member functions - std::map<std::string, VariantPtr> Object::getMemberTypes() const + void + Object::setMemberTypes(const std::map<std::string, VariantPtr>& memberTypes) + { + this->memberTypes = memberTypes; + for (const auto& [key, value] : memberTypes) + { + aron->elementTypes[key] = value->toAronDTO(); + } + } + + void + Object::setTemplates(const std::vector<std::string>& templates) + { + aron->templates = templates; + } + + void + Object::setTemplateInstantiations(const std::vector<std::string>& templateInstantiations) const + { + aron->templateInstantiations = templateInstantiations; + } + + std::map<std::string, VariantPtr> + Object::getMemberTypes() const { std::map<std::string, VariantPtr> ret = memberTypes; if (extends) @@ -102,16 +118,23 @@ namespace armarx::aron::type return ret; } - std::map<std::string, VariantPtr> Object::getDirectMemberTypes() const + std::map<std::string, VariantPtr> + Object::getDirectMemberTypes() const { return memberTypes; } - VariantPtr Object::getMemberType(const std::string& s) const + VariantPtr + Object::getMemberType(const std::string& s) const { - if (memberTypes.find(s) == memberTypes.end() and not (extends and extends->hasMemberType(s))) + if (memberTypes.find(s) == memberTypes.end() and not(extends and extends->hasMemberType(s))) { - throw error::ValueNotValidException("ObjectNavigator", "getMemberType", "Member not set. The list of all members is: " + simox::alg::to_string(simox::alg::get_keys(memberTypes)), s); + throw error::ValueNotValidException( + "ObjectNavigator", + "getMemberType", + "Member not set. The list of all members is: " + + simox::alg::to_string(simox::alg::get_keys(memberTypes)), + s); } if (memberTypes.find(s) == memberTypes.end()) { @@ -120,11 +143,13 @@ namespace armarx::aron::type return memberTypes.at(s); } - void Object::addMemberType(const std::string& k, const VariantPtr& v) + void + Object::addMemberType(const std::string& k, const VariantPtr& v) { if (k.empty()) { - throw error::AronException(__PRETTY_FUNCTION__, "Cannot set an element with an empty key.", getPath()); + throw error::AronException( + __PRETTY_FUNCTION__, "Cannot set an element with an empty key.", getPath()); } ARMARX_CHECK_NOT_NULL(v); @@ -133,14 +158,16 @@ namespace armarx::aron::type memberTypes[k] = v; } - void Object::setObjectName(const std::string& n) + void + Object::setObjectName(const std::string& n) { checkObjectName(n); //path.setRootIdentifier(n); this->aron->objectName = n; } - void Object::setExtends(const std::shared_ptr<Object>& p) + void + Object::setExtends(const std::shared_ptr<Object>& p) { ARMARX_CHECK_NOT_NULL(p); type::dto::AronObjectPtr ex = p->toAronObjectDTO(); @@ -149,18 +176,21 @@ namespace armarx::aron::type extends = p; } - bool Object::hasMemberType(const std::string& k) const + bool + Object::hasMemberType(const std::string& k) const { return memberTypes.count(k) > 0 or (extends && extends->hasMemberType(k)); } - std::string Object::getObjectNameWithoutNamespace() const + std::string + Object::getObjectNameWithoutNamespace() const { std::vector<std::string> split = simox::alg::split(aron->objectName, "::"); - return split[split.size() -1]; + return split[split.size() - 1]; } - std::string Object::getObjectNameWithTemplateInstantiations() const + std::string + Object::getObjectNameWithTemplateInstantiations() const { if (aron->templateInstantiations.empty()) { @@ -169,7 +199,8 @@ namespace armarx::aron::type return getObjectName() + "<" + simox::alg::join(aron->templateInstantiations, ", ") + ">"; } - std::string Object::getObjectNameWithTemplates() const + std::string + Object::getObjectNameWithTemplates() const { if (aron->templates.empty()) { @@ -178,45 +209,56 @@ namespace armarx::aron::type return getObjectName() + "<" + simox::alg::join(aron->templates, ", ") + ">"; } - void Object::addTemplate(const std::string& s) const + void + Object::addTemplate(const std::string& s) const { if (std::find(aron->templates.begin(), aron->templates.end(), s) != aron->templates.end()) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The template already exists!", s); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "The template already exists!", s); } aron->templates.push_back(s); } - void Object::addTemplateInstantiation(const std::string& s) const + void + Object::addTemplateInstantiation(const std::string& s) const { - if (std::find(aron->templateInstantiations.begin(), aron->templateInstantiations.end(), s) != aron->templateInstantiations.end()) + if (std::find(aron->templateInstantiations.begin(), + aron->templateInstantiations.end(), + s) != aron->templateInstantiations.end()) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "The template arg already exists!", s); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "The template arg already exists!", s); } aron->templateInstantiations.push_back(s); } - std::vector<std::string> Object::getTemplates() const + std::vector<std::string> + Object::getTemplates() const { return aron->templates; } - std::vector<std::string> Object::getTemplateInstantiations() const + std::vector<std::string> + Object::getTemplateInstantiations() const { return aron->templateInstantiations; } - std::string Object::getObjectName() const + std::string + Object::getObjectName() const { return this->aron->objectName; } - std::shared_ptr<Object> Object::getExtends() const + std::shared_ptr<Object> + Object::getExtends() const { return extends; } - std::vector<std::string> Object::getAllKeys() const + std::vector<std::string> + Object::getAllKeys() const { std::vector<std::string> ret; for (const auto& [k, _] : memberTypes) @@ -233,13 +275,15 @@ namespace armarx::aron::type return ret; } - type::dto::AronObjectPtr Object::toAronObjectDTO() const + type::dto::AronObjectPtr + Object::toAronObjectDTO() const { return this->aron; } // virtual implementations - std::vector<VariantPtr> Object::getChildren() const + std::vector<VariantPtr> + Object::getChildren() const { std::vector<VariantPtr> ret; for (const auto& [k, t] : memberTypes) @@ -256,42 +300,52 @@ namespace armarx::aron::type return ret; } - size_t Object::childrenSize() const + size_t + Object::childrenSize() const { return memberTypes.size(); } - std::string Object::getShortName() const + std::string + Object::getShortName() const { - return "Object<" + this->aron->objectName + (extends ? (" : " + extends->getShortName()) : "") + ">"; + return "Object<" + this->aron->objectName + + (extends ? (" : " + extends->getShortName()) : "") + ">"; } - std::string Object::getFullName() const + std::string + Object::getFullName() const { - return "armarx::aron::type::Object<" + this->aron->objectName + (extends ? (" : " + extends->getFullName()) : "") + ">"; + return "armarx::aron::type::Object<" + this->aron->objectName + + (extends ? (" : " + extends->getFullName()) : "") + ">"; } - std::string Object::GetFullNamePrefix() + std::string + Object::GetFullNamePrefix() { return "armarx::aron::type::Object"; } - std::string Object::GetNamePrefix() + std::string + Object::GetNamePrefix() { return "Object"; } - VariantPtr Object::navigateAbsolute(const Path& path) const + VariantPtr + Object::navigateAbsolute(const Path& path) const { if (!path.hasElement()) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate without a valid path", path); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not navigate without a valid path", path); } std::string el = path.getFirstElement(); if (!hasMemberType(el)) { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); } if (path.size() == 1) @@ -303,10 +357,10 @@ namespace armarx::aron::type Path next = path.withDetachedFirstElement(); if (!memberTypes.at(el)) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate into a NULL member.", next); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not navigate into a NULL member.", next); } return memberTypes.at(el)->navigateAbsolute(next); } } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/Object.h b/source/RobotAPI/libraries/aron/core/type/variant/container/Object.h index 0f452d4b8070424af81d7d371e65acec54a4fdae..9a8417ace771bb659721006ad83d100477744991 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/Object.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/Object.h @@ -24,13 +24,12 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base Class #include "../detail/ContainerVariant.h" - namespace armarx::aron::type { class Object; @@ -40,12 +39,11 @@ namespace armarx::aron::type * @brief The Object class. It represents the object type * An object may have different types for each member, here represented as a map, mapping from the member name (as string) to the type (as a variant) */ - class Object : - public detail::ContainerVariant<type::dto::AronObject, Object> + class Object : public detail::ContainerVariant<type::dto::AronObject, Object> { public: // constructors - Object(const std::string&, const std::vector<std::string>& templates = {}, const std::vector<std::string>& templateInstantiations = {}, const std::map<std::string, VariantPtr>& = {}, const Path& = Path()); + Object(const Path& = Path()); Object(const type::dto::AronObject&, const Path& = Path()); static ObjectPtr FromAronObjectDTO(const type::dto::AronObjectPtr&, @@ -65,8 +63,12 @@ namespace armarx::aron::type void setObjectName(const std::string&); void setExtends(const std::shared_ptr<Object>&); + + void setMemberTypes(const std::map<std::string, VariantPtr>&); void addMemberType(const std::string&, const VariantPtr&); + void setTemplates(const std::vector<std::string>&); void addTemplate(const std::string&) const; + void setTemplateInstantiations(const std::vector<std::string>&) const; void addTemplateInstantiation(const std::string&) const; bool hasMemberType(const std::string&) const; @@ -95,4 +97,4 @@ namespace armarx::aron::type std::shared_ptr<Object> extends; std::map<std::string, VariantPtr> memberTypes; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/Pair.cpp b/source/RobotAPI/libraries/aron/core/type/variant/container/Pair.cpp index c147bd3dd3ab17a66b9e0068e6d3e044c663e67d..8753a121ab0e744f564ef4441425676c40cf9172 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/Pair.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/Pair.cpp @@ -24,17 +24,12 @@ // Header #include "Pair.h" - namespace armarx::aron::type { // constructors - Pair::Pair(const VariantPtr& acceptedType1, const VariantPtr& acceptedType2, const Path& path) : - detail::ContainerVariant<type::dto::Pair, Pair>(type::Descriptor::PAIR, path), - acceptedType1(acceptedType1), - acceptedType2(acceptedType2) + Pair::Pair(const Path& path) : + detail::ContainerVariant<type::dto::Pair, Pair>(type::Descriptor::PAIR, path) { - aron->acceptedType1 = acceptedType1->toAronDTO(); - aron->acceptedType2 = acceptedType2->toAronDTO(); } Pair::Pair(const type::dto::Pair& o, const Path& path) : @@ -45,22 +40,26 @@ namespace armarx::aron::type } // Member functions - std::pair<VariantPtr, VariantPtr> Pair::getAcceptedTypes() const + std::pair<VariantPtr, VariantPtr> + Pair::getAcceptedTypes() const { return {acceptedType1, acceptedType2}; } - VariantPtr Pair::getFirstAcceptedType() const + VariantPtr + Pair::getFirstAcceptedType() const { return acceptedType1; } - VariantPtr Pair::getSecondAcceptedType() const + VariantPtr + Pair::getSecondAcceptedType() const { return acceptedType2; } - void Pair::addAcceptedType(const VariantPtr& n) + void + Pair::addAcceptedType(const VariantPtr& n) { ARMARX_CHECK_NOT_NULL(n); @@ -77,59 +76,71 @@ namespace armarx::aron::type throw error::AronException(__PRETTY_FUNCTION__, "Both types are already set", getPath()); } - void Pair::setFirstAcceptedType(const VariantPtr& n) + void + Pair::setFirstAcceptedType(const VariantPtr& n) { ARMARX_CHECK_NOT_NULL(n); acceptedType1 = n; } - void Pair::setSecondAcceptedType(const VariantPtr& n) + void + Pair::setSecondAcceptedType(const VariantPtr& n) { ARMARX_CHECK_NOT_NULL(n); acceptedType2 = n; } - type::dto::PairPtr Pair::toPairDTO() const + type::dto::PairPtr + Pair::toPairDTO() const { return this->aron; } // virtual implementations - std::vector<VariantPtr> Pair::getChildren() const + std::vector<VariantPtr> + Pair::getChildren() const { return {acceptedType1, acceptedType2}; } - size_t Pair::childrenSize() const + size_t + Pair::childrenSize() const { return 2; } - std::string Pair::getShortName() const + std::string + Pair::getShortName() const { return "Pair<" + acceptedType1->getShortName() + ", " + acceptedType2->getShortName() + ">"; } - std::string Pair::getFullName() const + std::string + Pair::getFullName() const { - return "armarx::aron::type::Pair<" + acceptedType1->getFullName() + ", " + acceptedType2->getFullName() + ">"; + return "armarx::aron::type::Pair<" + acceptedType1->getFullName() + ", " + + acceptedType2->getFullName() + ">"; } - std::string Pair::GetFullNamePrefix() + std::string + Pair::GetFullNamePrefix() { return "armarx::aron::type::Pair"; } - std::string Pair::GetNamePrefix() + std::string + Pair::GetNamePrefix() { return "Pair"; } - VariantPtr Pair::navigateAbsolute(const Path& path) const + VariantPtr + Pair::navigateAbsolute(const Path& path) const { if (!path.hasElement()) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate without a valid path", path); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not navigate without a valid path", path); } std::string el = path.getFirstElement(); @@ -159,8 +170,8 @@ namespace armarx::aron::type } else { - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); } } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/Pair.h b/source/RobotAPI/libraries/aron/core/type/variant/container/Pair.h index e8bb11cd6fa82d711d87b39cf50b1dcfbd6f71fd..ce88e8d2e9b7cd03127e431c9e2b81e305a04aa4 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/Pair.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/Pair.h @@ -24,8 +24,8 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base Class #include "../detail/ContainerVariant.h" @@ -36,12 +36,11 @@ namespace armarx::aron::type * @brief The Pair class. It represents the pair type * A pair has two accepted types */ - class Pair : - public detail::ContainerVariant<type::dto::Pair, Pair> + class Pair : public detail::ContainerVariant<type::dto::Pair, Pair> { public: // constructors - Pair(const VariantPtr& acceptedType1, const VariantPtr& acceptedType2, const Path& path = Path()); + Pair(const Path& path = Path()); Pair(const type::dto::Pair&, const Path& path = Path()); // public member functions @@ -69,6 +68,5 @@ namespace armarx::aron::type // members VariantPtr acceptedType1; VariantPtr acceptedType2; - }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/Tuple.cpp b/source/RobotAPI/libraries/aron/core/type/variant/container/Tuple.cpp index cdcd605f2d475d4e8e83ab1d25a25914cc32e99a..ce4e66261f9c5e8de9e36ebaaf387c62ca0ef64c 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/Tuple.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/Tuple.cpp @@ -29,14 +29,9 @@ namespace armarx::aron::type { // constructors - Tuple::Tuple(const std::vector<VariantPtr>& acceptedTypes, const Path& path) : - detail::ContainerVariant<type::dto::Tuple, Tuple>(type::Descriptor::TUPLE, path), - acceptedTypes(acceptedTypes) + Tuple::Tuple(const Path& path) : + detail::ContainerVariant<type::dto::Tuple, Tuple>(type::Descriptor::TUPLE, path) { - for (const auto& acceptedType : acceptedTypes) - { - aron->elementTypes.push_back(acceptedType->toAronDTO()); - } } Tuple::Tuple(const type::dto::Tuple& o, const Path& path) : @@ -49,7 +44,8 @@ namespace armarx::aron::type } } - type::dto::TuplePtr Tuple::toTupleDTO() const + type::dto::TuplePtr + Tuple::toTupleDTO() const { if (acceptedTypes.empty()) { @@ -59,22 +55,36 @@ namespace armarx::aron::type } // public member functions - std::vector<VariantPtr> Tuple::getAcceptedTypes() const + std::vector<VariantPtr> + Tuple::getAcceptedTypes() const { return acceptedTypes; } - bool Tuple::hasAcceptedType(unsigned int i) const + bool + Tuple::hasAcceptedType(unsigned int i) const { return i < acceptedTypes.size(); } - VariantPtr Tuple::getAcceptedType(unsigned int i) const + VariantPtr + Tuple::getAcceptedType(unsigned int i) const { return acceptedTypes[i]; } - void Tuple::addAcceptedType(const VariantPtr& v) + void + Tuple::setAcceptedTypes(const std::vector<VariantPtr>& acceptedTypes) + { + this->acceptedTypes = acceptedTypes; + for (const auto& acceptedType : acceptedTypes) + { + aron->elementTypes.push_back(acceptedType->toAronDTO()); + } + } + + void + Tuple::addAcceptedType(const VariantPtr& v) { ARMARX_CHECK_NOT_NULL(v); this->aron->elementTypes.push_back(v->toAronDTO()); @@ -82,17 +92,20 @@ namespace armarx::aron::type } // virtual implementations - std::vector<VariantPtr> Tuple::getChildren() const + std::vector<VariantPtr> + Tuple::getChildren() const { return acceptedTypes; } - size_t Tuple::childrenSize() const + size_t + Tuple::childrenSize() const { return acceptedTypes.size(); } - std::string Tuple::getShortName() const + std::string + Tuple::getShortName() const { std::vector<std::string> names; for (const auto& n : acceptedTypes) @@ -102,7 +115,8 @@ namespace armarx::aron::type return "Tuple<" + simox::alg::to_string(names, ", ") + ">"; } - std::string Tuple::getFullName() const + std::string + Tuple::getFullName() const { std::vector<std::string> names; for (const auto& n : acceptedTypes) @@ -112,21 +126,25 @@ namespace armarx::aron::type return "armarx::aron::type::Tuple<" + simox::alg::to_string(names, ", ") + ">"; } - std::string Tuple::GetFullNamePrefix() + std::string + Tuple::GetFullNamePrefix() { return "armarx::aron::type::Tuple"; } - std::string Tuple::GetNamePrefix() + std::string + Tuple::GetNamePrefix() { return "Tuple"; } - VariantPtr Tuple::navigateAbsolute(const Path& path) const + VariantPtr + Tuple::navigateAbsolute(const Path& path) const { if (!path.hasElement()) { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate without a valid path", path); + throw error::AronException( + __PRETTY_FUNCTION__, "Could not navigate without a valid path", path); } std::string el = path.getFirstElement(); @@ -145,7 +163,7 @@ namespace armarx::aron::type } } } - throw error::ValueNotValidException(__PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Could not find an element of a path.", el, path); } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/container/Tuple.h b/source/RobotAPI/libraries/aron/core/type/variant/container/Tuple.h index 070bed6264c8a2d9c19751d1b7866794e6e3bfb8..e382cc526eb18e3859c4531b4d7814a17dfd7461 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/container/Tuple.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/container/Tuple.h @@ -24,8 +24,8 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base Class #include "../detail/ContainerVariant.h" @@ -36,18 +36,19 @@ namespace armarx::aron::type * @brief The Tuple class. It represents the tuple type * A tuple has a list of accepted types */ - class Tuple : - public detail::ContainerVariant<type::dto::Tuple, Tuple> + class Tuple : public detail::ContainerVariant<type::dto::Tuple, Tuple> { public: // constructors - Tuple(const std::vector<VariantPtr>& acceptedTypes, const Path& path = Path()); + Tuple(const Path& path = Path()); Tuple(const type::dto::Tuple&, const Path& path = Path()); // public member functions std::vector<VariantPtr> getAcceptedTypes() const; bool hasAcceptedType(unsigned int i) const; VariantPtr getAcceptedType(unsigned int i) const; + + void setAcceptedTypes(const std::vector<VariantPtr>&); void addAcceptedType(const VariantPtr&); type::dto::TuplePtr toTupleDTO() const; @@ -66,4 +67,4 @@ namespace armarx::aron::type private: std::vector<VariantPtr> acceptedTypes; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/detail/EnumVariant.h b/source/RobotAPI/libraries/aron/core/type/variant/detail/EnumVariant.h index a9b390b8db6383d63fbc594f23841351861def4f..84b1bf7821f6518498ca40554a26a16fcfaaf019 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/detail/EnumVariant.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/detail/EnumVariant.h @@ -35,29 +35,154 @@ namespace armarx::aron::type::detail { - template<typename AronTypeT, typename DerivedT> - class EnumVariant : - public SpecializedVariantBase<AronTypeT, DerivedT> + template <typename AronTypeT, typename DerivedT, typename ValueT> + class EnumVariant : public SpecializedVariantBase<AronTypeT, DerivedT> { public: - using SpecializedVariantBase<AronTypeT, DerivedT>::SpecializedVariantBase; + using ValueType = ValueT; + using Base = SpecializedVariantBase<AronTypeT, DerivedT>; + + using Base::SpecializedVariantBase; virtual ~EnumVariant() = default; /* virtual implementations */ - VariantPtr navigateAbsolute(const Path &path) const override + VariantPtr + navigateAbsolute(const Path& path) const override { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate through a non container navigator. The input path was: " + path.toString(), Variant::getPath()); + throw error::AronException( + __PRETTY_FUNCTION__, + "Could not navigate through a non container navigator. The input path was: " + + path.toString(), + Variant::getPath()); } - std::vector<VariantPtr> getChildren() const override + std::vector<VariantPtr> + getChildren() const override { return {}; } - size_t childrenSize() const override + size_t + childrenSize() const override { return 0; } + + void + setAcceptedValueMap(const std::map<std::string, ValueType>& valueMap) + { + this->aron->acceptedValues = valueMap; + } + + std::map<std::string, int> + getAcceptedValueMap() const + { + return this->aron->acceptedValues; + } + + std::vector<std::string> + getAcceptedValueNames() const + { + std::vector<std::string> names; + for (const auto& [k, _] : this->aron->acceptedValues) + { + names.push_back(k); + } + return names; + } + + std::vector<ValueType> + getAcceptedValues() const + { + std::vector<ValueType> vals; + for (const auto& [_, i] : this->aron->acceptedValues) + { + vals.push_back(i); + } + return vals; + } + + std::string + getValueName(ValueType i) const + { + for (const auto& [k, v] : this->aron->acceptedValues) + { + if (v == i) + { + return k; + } + } + throw error::AronException(__PRETTY_FUNCTION__, + "Enum could not be resolved. Input was: " + + std::to_string(i), + this->getPath()); + } + + int + getValue(const std::string& s) const + { + return this->aron->acceptedValues[s]; + } + + std::string + getEnumName() const + { + return this->aron->enumName; + } + + void + setEnumName(const std::string& s) + { + this->aron->enumName = s; + } + + void + addAcceptedValue(const std::string& s, ValueType i) + { + this->aron->acceptedValues[s] = i; + } + + std::string + getDefaultValueName() const + { + return this->aron->defaultValue; + } + + ValueType + getDefaultValue() const + { + // ARMARX_CHECK(std::find(this->aron->acceptedValues.begin(), + // this->aron->acceptedValues.end(), + // this->aron->defaultValue) != this->aron->acceptedValues.end()) + // << "An aron enum type has an invalid default value set. Got: " + // << this->aron->defaultValue; + return this->aron->acceptedValues[this->aron->defaultValue]; + } + + void + setDefaultValue(const ValueType& v) + { + for (const auto& [key, value] : this->aron->acceptedValues) + { + if (value == v) + { + this->aron->defaultValue = key; + } + } + throw error::ValueNotValidException( + __PRETTY_FUNCTION__, "Got invalid input for enum value", std::to_string(v)); + } + + void + setDefaultValueName(const std::string& v) + { + // ARMARX_CHECK(std::find(this->aron->acceptedValues.begin(), + // this->aron->acceptedValues.end(), + // this->aron->defaultValue) != this->aron->acceptedValues.end()) + // << "Trying to set an invalid default value for aron enum type. Got: " + // << this->aron->defaultValue; + this->aron->defaultValue = v; + } }; -} +} // namespace armarx::aron::type::detail diff --git a/source/RobotAPI/libraries/aron/core/type/variant/detail/NDArrayVariant.h b/source/RobotAPI/libraries/aron/core/type/variant/detail/NDArrayVariant.h index 283b11a6383593e389e905c6b27e5fec4716a72a..168db8b1073aee4ea767940b27933109800bd025 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/detail/NDArrayVariant.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/detail/NDArrayVariant.h @@ -35,9 +35,8 @@ namespace armarx::aron::type::detail { - template<typename AronTypeT, typename DerivedT> - class NDArrayVariant : - public SpecializedVariantBase<AronTypeT, DerivedT> + template <typename AronTypeT, typename DerivedT> + class NDArrayVariant : public SpecializedVariantBase<AronTypeT, DerivedT> { public: using SpecializedVariantBase<AronTypeT, DerivedT>::SpecializedVariantBase; @@ -45,19 +44,38 @@ namespace armarx::aron::type::detail virtual ~NDArrayVariant() = default; /* virtual implementations */ - VariantPtr navigateAbsolute(const Path &path) const override + VariantPtr + navigateAbsolute(const Path& path) const override { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate through a non container navigator. The input path was: " + path.toString(), Variant::getPath()); + throw error::AronException( + __PRETTY_FUNCTION__, + "Could not navigate through a non container navigator. The input path was: " + + path.toString(), + Variant::getPath()); } - std::vector<VariantPtr> getChildren() const override + std::vector<VariantPtr> + getChildren() const override { return {}; } - size_t childrenSize() const override + size_t + childrenSize() const override { return 0; } + + std::string + getDefaultValue() const + { + return this->aron->defaultValue; + } + + void + setDefaultValue(const std::string& v) + { + this->aron->defaultValue = v; + } }; -} +} // namespace armarx::aron::type::detail diff --git a/source/RobotAPI/libraries/aron/core/type/variant/detail/PrimitiveVariant.h b/source/RobotAPI/libraries/aron/core/type/variant/detail/PrimitiveVariant.h index c7c6eb0b9c00e9ab1cd40800d5917929b8e9e5c3..5bfa7fe14d8c4af284e8af977bbc61463e0540f5 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/detail/PrimitiveVariant.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/detail/PrimitiveVariant.h @@ -35,29 +35,53 @@ namespace armarx::aron::type::detail { - template<typename AronTypeT, typename DerivedT> - class PrimitiveVariant : - public SpecializedVariantBase<AronTypeT, DerivedT> + template <typename AronTypeT, typename DerivedT, typename ValueT> + class PrimitiveVariant : public SpecializedVariantBase<AronTypeT, DerivedT> { public: - using SpecializedVariantBase<AronTypeT, DerivedT>::SpecializedVariantBase; + using Base = SpecializedVariantBase<AronTypeT, DerivedT>; + + using ValueType = ValueT; + + using Base::SpecializedVariantBase; virtual ~PrimitiveVariant() = default; /* virtual implementations */ - VariantPtr navigateAbsolute(const Path &path) const override + VariantPtr + navigateAbsolute(const Path& path) const override { - throw error::AronException(__PRETTY_FUNCTION__, "Could not navigate through a non container navigator. The input path was: " + path.toString(), Variant::getPath()); + throw error::AronException( + __PRETTY_FUNCTION__, + "Could not navigate through a non container navigator. The input path was: " + + path.toString(), + Variant::getPath()); } - std::vector<VariantPtr> getChildren() const override + std::vector<VariantPtr> + getChildren() const override { return {}; } - size_t childrenSize() const override + size_t + childrenSize() const override { return 0; } + + ValueType + getDefaultValue() const + { + return this->aron->defaultValue; + } + + void + setDefaultValue(const ValueType& v) + { + this->aron->defaultValue = v; + } + + protected: }; -} +} // namespace armarx::aron::type::detail diff --git a/source/RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.cpp b/source/RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.cpp index 5ccace22723cbd9eb530064614339827cfcdd3ae..f6afbfb36c87c88c4bb2ba25532dab32e591ee56 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.cpp @@ -27,89 +27,31 @@ namespace armarx::aron::type { // constructors - IntEnum::IntEnum(const std::string& name, const std::map<std::string, int>& valueMap, const Path& path) : - detail::EnumVariant<type::dto::IntEnum, IntEnum>(type::Descriptor::INT_ENUM, path) + IntEnum::IntEnum(const Path& path) : Base(type::Descriptor::INT_ENUM, path) { - aron->enumName = name; - aron->acceptedValues = valueMap; } IntEnum::IntEnum(const type::dto::IntEnum& o, const Path& path) : - detail::EnumVariant<type::dto::IntEnum, IntEnum>(o, type::Descriptor::INT_ENUM, path) + Base(o, type::Descriptor::INT_ENUM, path) { } - std::map<std::string, int> IntEnum::getAcceptedValueMap() const - { - return this->aron->acceptedValues; - } - - std::vector<std::string> IntEnum::getAcceptedValueNames() const - { - std::vector<std::string> names; - for (const auto& [k, _] : aron->acceptedValues) - { - names.push_back(k); - } - return names; - } - - std::vector<int> IntEnum::getAcceptedValues() const - { - std::vector<int> vals; - for (const auto& [_, i] : aron->acceptedValues) - { - vals.push_back(i); - } - return vals; - } - - std::string IntEnum::getValueName(int i) const - { - for (const auto& [k, v] : this->aron->acceptedValues) - { - if (v == i) - { - return k; - } - } - throw error::AronException(__PRETTY_FUNCTION__, "Enum could not be resolved. Input was: " + std::to_string(i), getPath()); - } - - int IntEnum::getValue(const std::string& s) const - { - return this->aron->acceptedValues[s]; - } - - std::string IntEnum::getEnumName() const - { - return this->aron->enumName; - } - - void IntEnum::setEnumName(const std::string& s) - { - this->aron->enumName = s; - } - - void IntEnum::addAcceptedValue(const std::string& s, int i) - { - this->aron->acceptedValues[s] = i; - } - - type::dto::IntEnumPtr IntEnum::toIntEnumDTO() const + type::dto::IntEnumPtr + IntEnum::toIntEnumDTO() const { return this->aron; } // virtual implementations - std::string IntEnum::getShortName() const + std::string + IntEnum::getShortName() const { return "IntEnum"; } - std::string IntEnum::getFullName() const + std::string + IntEnum::getFullName() const { return "armarx::aron::type::IntEnum"; } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.h b/source/RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.h index cf652d23cfb225d1ba4efde9c7d48af7c0e34966..7e38527ba6e82a19c4572fba2c8614183001a7ec 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/enum/IntEnum.h @@ -24,8 +24,8 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base class #include "../detail/EnumVariant.h" @@ -39,30 +39,19 @@ namespace armarx::aron::type * @brief The IntEnum class. It represents the int enum type * An int enum contains a map from strings to int values */ - class IntEnum : - public detail::EnumVariant<type::dto::IntEnum, IntEnum> + class IntEnum : public detail::EnumVariant<type::dto::IntEnum, IntEnum, int> { public: + using Base = detail::EnumVariant<type::dto::IntEnum, IntEnum, int>; + // constructors - IntEnum(const std::string& name, const std::map<std::string, int>& valueMap, const Path& path = Path()); + IntEnum(const Path& path = Path()); IntEnum(const type::dto::IntEnum&, const Path& path = Path()); - // public member functions - std::map<std::string, int> getAcceptedValueMap() const; - std::vector<std::string> getAcceptedValueNames() const; - std::vector<int> getAcceptedValues() const; - - std::string getValueName(int) const; - int getValue(const std::string&) const; - std::string getEnumName() const; - - void setEnumName(const std::string&); - void addAcceptedValue(const std::string&, int); - type::dto::IntEnumPtr toIntEnumDTO() const; // virtual implementations std::string getShortName() const override; std::string getFullName() const override; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Image.cpp b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Image.cpp index f5eed5e4ed7ff4d2fa0575563a8428ce58225d0e..86e66b911e1762abdf2fd2445cde2d4e787d3756 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Image.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Image.cpp @@ -23,21 +23,18 @@ #include "Image.h" -#include <RobotAPI/libraries/aron/core/Exception.h> - #include <SimoxUtility/algorithm/string.h> #include <SimoxUtility/meta/EnumNames.hpp> +#include <RobotAPI/libraries/aron/core/Exception.h> namespace armarx::aron::type { - const std::map<image::PixelType, std::string> Image::Pixeltype2String - { + const std::map<image::PixelType, std::string> Image::Pixeltype2String{ {image::PixelType::RGB24, "RGB24"}, - {image::PixelType::DEPTH32, "DEPTH32"} - }; - const std::map<std::string, image::PixelType> Image::String2Pixeltype = conversion::util::InvertMap(Pixeltype2String); - + {image::PixelType::DEPTH32, "DEPTH32"}}; + const std::map<std::string, image::PixelType> Image::String2Pixeltype = + conversion::util::InvertMap(Pixeltype2String); // constructors Image::Image(const Path& path) : @@ -45,37 +42,39 @@ namespace armarx::aron::type { } - Image::Image(const type::dto::Image& o, const Path& path) : detail::NDArrayVariant<type::dto::Image, Image>(o, type::Descriptor::IMAGE, path) { } - type::dto::ImagePtr Image::toImageDTO() const + type::dto::ImagePtr + Image::toImageDTO() const { return this->aron; } - - image::PixelType Image::getPixelType() const + image::PixelType + Image::getPixelType() const { return aron->pixelType; } - void Image::setPixelType(const image::PixelType pixelType) const + void + Image::setPixelType(const image::PixelType pixelType) const { aron->pixelType = pixelType; } // virtual implementations - std::string Image::getShortName() const + std::string + Image::getShortName() const { return "Image"; } - std::string Image::getFullName() const + std::string + Image::getFullName() const { return "armarx::aron::type::Image<" + Pixeltype2String.at(this->aron->pixelType) + ">"; } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Image.h b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Image.h index 0b9f9dd0992c79187368a7136b7fa957a42cacae..941687c4861b504a6a57ad7350910af609b61034 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Image.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Image.h @@ -36,8 +36,7 @@ namespace armarx::aron::type * @brief The Image class. It represents the image type. * The code generation manages, which code will be generated for this type object, e.g. c++ generates opencv code. */ - class Image : - public detail::NDArrayVariant<type::dto::Image, Image> + class Image : public detail::NDArrayVariant<type::dto::Image, Image> { public: // constructors @@ -57,4 +56,4 @@ namespace armarx::aron::type static const std::map<image::PixelType, std::string> Pixeltype2String; static const std::map<std::string, image::PixelType> String2Pixeltype; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.cpp b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.cpp index b7657a8719be955f833ef8658891a39ae23ca05e..e3bcbf57344c50fe915a6177c1f60df0ead2d239 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.cpp @@ -29,16 +29,15 @@ namespace armarx::aron::type { - const std::map<matrix::ElementType, std::string> Matrix::Elementtype2String - { + const std::map<matrix::ElementType, std::string> Matrix::Elementtype2String{ {matrix::ElementType::INT16, "INT16"}, {matrix::ElementType::INT32, "INT32"}, {matrix::ElementType::INT64, "INT64"}, {matrix::ElementType::FLOAT32, "FLOAT32"}, - {matrix::ElementType::FLOAT64, "FLOAT64"} - }; + {matrix::ElementType::FLOAT64, "FLOAT64"}}; - const std::map<std::string, matrix::ElementType> Matrix::String2Elementtype = conversion::util::InvertMap(Elementtype2String); + const std::map<std::string, matrix::ElementType> Matrix::String2Elementtype = + conversion::util::InvertMap(Elementtype2String); // constructors Matrix::Matrix(const Path& path) : @@ -51,56 +50,67 @@ namespace armarx::aron::type { } - int Matrix::getRows() const + int + Matrix::getRows() const { return this->aron->rows; } - int Matrix::getCols() const + int + Matrix::getCols() const { return this->aron->cols; } - void Matrix::setRows(const int w) + void + Matrix::setRows(const int w) { if (w == 0 || w < -1) { - throw error::AronException(__PRETTY_FUNCTION__, "The rows cannot be 0 or < -1", getPath()); + throw error::AronException( + __PRETTY_FUNCTION__, "The rows cannot be 0 or < -1", getPath()); } this->aron->rows = w; } - void Matrix::setCols(const int h) + void + Matrix::setCols(const int h) { if (h == 0 || h < -1) { - throw error::AronException(__PRETTY_FUNCTION__, "The cols cannot be 0 or < -1", getPath()); + throw error::AronException( + __PRETTY_FUNCTION__, "The cols cannot be 0 or < -1", getPath()); } this->aron->cols = h; } - type::matrix::ElementType Matrix::getElementType() const + type::matrix::ElementType + Matrix::getElementType() const { return this->aron->elementType; } - void Matrix::setElementType(const type::matrix::ElementType u) + void + Matrix::setElementType(const type::matrix::ElementType u) { this->aron->elementType = u; } - type::dto::MatrixPtr Matrix::toMatrixDTO() const + type::dto::MatrixPtr + Matrix::toMatrixDTO() const { return this->aron; } // virtual implementations - std::string Matrix::getShortName() const + std::string + Matrix::getShortName() const { return "Matrix"; } - std::string Matrix::getFullName() const + std::string + Matrix::getFullName() const { std::string rows = std::to_string(aron->rows); std::string cols = std::to_string(aron->cols); @@ -115,7 +125,7 @@ namespace armarx::aron::type cols = "Dynamic"; } - return "armarx::aron::type::Matrix<" + rows + ", " + cols + ", " + Elementtype2String.at(this->aron->elementType) + ">"; + return "armarx::aron::type::Matrix<" + rows + ", " + cols + ", " + + Elementtype2String.at(this->aron->elementType) + ">"; } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.h b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.h index 41dc008d34f29e0cabfc567416af6cbcc0588a5b..b28fc260ddb8110bbb54d9a8fbb10aed052abb66 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Matrix.h @@ -24,8 +24,8 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base class #include "../detail/NDArrayVariant.h" @@ -36,8 +36,7 @@ namespace armarx::aron::type * @brief The Matrix class. It represents the matrix type * A Matrix is defined through the number of rows, cols and the element type */ - class Matrix : - public detail::NDArrayVariant<type::dto::Matrix, Matrix> + class Matrix : public detail::NDArrayVariant<type::dto::Matrix, Matrix> { public: // constructors @@ -61,4 +60,4 @@ namespace armarx::aron::type static const std::map<matrix::ElementType, std::string> Elementtype2String; static const std::map<std::string, matrix::ElementType> String2Elementtype; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.cpp b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.cpp index bddbcf91cf100a0d60b49f30fc0bc075837756d5..8c188f92225331c7166d0f2fa6e5293326bc7283 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.cpp @@ -37,45 +37,52 @@ namespace armarx::aron::type { } - type::dto::NDArrayPtr NDArray::toNDArrayDTO() const + type::dto::NDArrayPtr + NDArray::toNDArrayDTO() const { return this->aron; } - int NDArray::getNumberDimensions() const + int + NDArray::getNumberDimensions() const { return this->aron->ndimensions; } - type::ndarray::ElementType NDArray::getElementType() const + type::ndarray::ElementType + NDArray::getElementType() const { return this->aron->elementType; } - void NDArray::setElementType(type::ndarray::ElementType s) + void + NDArray::setElementType(type::ndarray::ElementType s) { this->aron->elementType = s; } - void NDArray::setNumberDimensions(int v) + void + NDArray::setNumberDimensions(int v) { this->aron->ndimensions = v; } - void NDArray::addDimension() + void + NDArray::addDimension() { this->aron->ndimensions++; } // virtual implementations - std::string NDArray::getShortName() const + std::string + NDArray::getShortName() const { return "NDArray"; } - std::string NDArray::getFullName() const + std::string + NDArray::getFullName() const { return "armarx::aron::type::NDArray"; } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.h b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.h index d04d218eb5ce19a1d53b8d1851b00d3a9ba7925a..b8df436d15f816c47820bed0e6b58bbe94a68dff 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/NDArray.h @@ -24,8 +24,8 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base class #include "../detail/NDArrayVariant.h" @@ -35,8 +35,7 @@ namespace armarx::aron::type /** * @brief The NDArray class. It represents an arbitrary array type */ - class NDArray : - public detail::NDArrayVariant<type::dto::NDArray, NDArray> + class NDArray : public detail::NDArrayVariant<type::dto::NDArray, NDArray> { public: // constructors @@ -57,4 +56,4 @@ namespace armarx::aron::type std::string getShortName() const override; std::string getFullName() const override; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.cpp b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.cpp index c28a750e26f5e7acf86bf0ebdc8fb9ad4fe48cc3..5d0609803a1f684738272ebe367ff53d7065b1e8 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.cpp @@ -26,54 +26,60 @@ namespace armarx::aron::type { - const std::map<pointcloud::VoxelType, std::string> PointCloud::Voxeltype2String - { + const std::map<pointcloud::VoxelType, std::string> PointCloud::Voxeltype2String{ {pointcloud::VoxelType::POINT_XYZ, "POINT_XYZ"}, {pointcloud::VoxelType::POINT_XYZI, "POINT_XYZI"}, {pointcloud::VoxelType::POINT_XYZL, "POINT_XYZL"}, {pointcloud::VoxelType::POINT_XYZRGB, "POINT_XYZRGB"}, {pointcloud::VoxelType::POINT_XYZRGBL, "POINT_XYZRGBL"}, {pointcloud::VoxelType::POINT_XYZRGBA, "POINT_XYZRGBA"}, - {pointcloud::VoxelType::POINT_XYZHSV, "POINT_XYZHSV"} - }; + {pointcloud::VoxelType::POINT_XYZHSV, "POINT_XYZHSV"}}; - const std::map<std::string, pointcloud::VoxelType> PointCloud::String2Voxeltype = conversion::util::InvertMap(Voxeltype2String); + const std::map<std::string, pointcloud::VoxelType> PointCloud::String2Voxeltype = + conversion::util::InvertMap(Voxeltype2String); // constructors PointCloud::PointCloud(const Path& path) : - detail::NDArrayVariant<type::dto::PointCloud, PointCloud>(type::Descriptor::POINTCLOUD, path) + detail::NDArrayVariant<type::dto::PointCloud, PointCloud>(type::Descriptor::POINTCLOUD, + path) { } PointCloud::PointCloud(const type::dto::PointCloud& o, const Path& path) : - detail::NDArrayVariant<type::dto::PointCloud, PointCloud>(o, type::Descriptor::POINTCLOUD, path) + detail::NDArrayVariant<type::dto::PointCloud, PointCloud>(o, + type::Descriptor::POINTCLOUD, + path) { } - type::dto::PointCloudPtr PointCloud::toPointCloudDTO() const + type::dto::PointCloudPtr + PointCloud::toPointCloudDTO() const { return this->aron; } - type::pointcloud::VoxelType PointCloud::getVoxelType() const + type::pointcloud::VoxelType + PointCloud::getVoxelType() const { return this->aron->voxelType; } - void PointCloud::setVoxelType(type::pointcloud::VoxelType u) + void + PointCloud::setVoxelType(type::pointcloud::VoxelType u) { this->aron->voxelType = u; } // virtual implementations - std::string PointCloud::getShortName() const + std::string + PointCloud::getShortName() const { return "PointCloud"; } - std::string PointCloud::getFullName() const + std::string + PointCloud::getFullName() const { return "armarx::aron::type::PointCloud<" + Voxeltype2String.at(this->aron->voxelType) + ">"; } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.h b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.h index 37d3aacdbed11c396cdc7351f8e7077705f2e2a6..9358e4b59fee7421da8b500990d5e5646b8c8bbb 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/PointCloud.h @@ -24,8 +24,8 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base class #include "../detail/NDArrayVariant.h" @@ -36,8 +36,7 @@ namespace armarx::aron::type * @brief The PointCloud class. It represents the pointcloud type. * A pointcloud is defined through a type. The dimension is NOT part of the type description */ - class PointCloud : - public detail::NDArrayVariant<type::dto::PointCloud, PointCloud> + class PointCloud : public detail::NDArrayVariant<type::dto::PointCloud, PointCloud> { public: // constructors @@ -58,4 +57,4 @@ namespace armarx::aron::type static const std::map<pointcloud::VoxelType, std::string> Voxeltype2String; static const std::map<std::string, pointcloud::VoxelType> String2Voxeltype; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.cpp b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.cpp index 0e1ff22fc13e08f1bdcc3d15722feeb92d17fa61..ab85bdf94860e106b3dfb222d09a663da8c5482d 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.cpp @@ -28,48 +28,55 @@ namespace armarx::aron::type { - const std::map<quaternion::ElementType, std::string> Quaternion::Elementtype2String = - { + const std::map<quaternion::ElementType, std::string> Quaternion::Elementtype2String = { {quaternion::ElementType::FLOAT32, "FLOAT32"}, - {quaternion::ElementType::FLOAT64, "FLOAT64"} - }; - const std::map<std::string, quaternion::ElementType> Quaternion::String2Elementtype = conversion::util::InvertMap(Elementtype2String); + {quaternion::ElementType::FLOAT64, "FLOAT64"}}; + const std::map<std::string, quaternion::ElementType> Quaternion::String2Elementtype = + conversion::util::InvertMap(Elementtype2String); // constructors Quaternion::Quaternion(const Path& path) : - detail::NDArrayVariant<type::dto::Quaternion, Quaternion>(type::Descriptor::QUATERNION, path) + detail::NDArrayVariant<type::dto::Quaternion, Quaternion>(type::Descriptor::QUATERNION, + path) { } Quaternion::Quaternion(const type::dto::Quaternion& o, const Path& path) : - detail::NDArrayVariant<type::dto::Quaternion, Quaternion>(o, type::Descriptor::QUATERNION, path) + detail::NDArrayVariant<type::dto::Quaternion, Quaternion>(o, + type::Descriptor::QUATERNION, + path) { } - type::dto::QuaternionPtr Quaternion::toQuaternionDTO() const + type::dto::QuaternionPtr + Quaternion::toQuaternionDTO() const { return this->aron; } - type::quaternion::ElementType Quaternion::getElementType() const + type::quaternion::ElementType + Quaternion::getElementType() const { return this->aron->elementType; } - void Quaternion::setElementType(type::quaternion::ElementType t) + void + Quaternion::setElementType(type::quaternion::ElementType t) { this->aron->elementType = t; } // virtual implementations - std::string Quaternion::getShortName() const + std::string + Quaternion::getShortName() const { return "Quaternion"; } - std::string Quaternion::getFullName() const + std::string + Quaternion::getFullName() const { - return "armarx::aron::type::Quaternion<" + Elementtype2String.at(this->aron->elementType) + ">"; + return "armarx::aron::type::Quaternion<" + Elementtype2String.at(this->aron->elementType) + + ">"; } -} - +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.h b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.h index f660702be8c84613877d164763914bcf4cd57bc9..e8140a726731f3f4a9b63fc3dda380a1104d8542 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/ndarray/Quaternion.h @@ -24,8 +24,8 @@ #pragma once // STD/STL -#include <string> #include <map> +#include <string> // Base class #include "../detail/NDArrayVariant.h" @@ -36,8 +36,7 @@ namespace armarx::aron::type * @brief The Qaternion class. It represents the quaternion type * A Quaternion has dimension 1x4 and a varying type */ - class Quaternion : - public detail::NDArrayVariant<type::dto::Quaternion, Quaternion> + class Quaternion : public detail::NDArrayVariant<type::dto::Quaternion, Quaternion> { public: // constructors @@ -57,4 +56,4 @@ namespace armarx::aron::type static const std::map<quaternion::ElementType, std::string> Elementtype2String; static const std::map<std::string, quaternion::ElementType> String2Elementtype; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Bool.cpp b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Bool.cpp index fc5cdb5cb403e4de3605b82ad9f7a755c925c5d2..d9d87c0a97088e419ed6cfbc890e2e1c1d004bdd 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Bool.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Bool.cpp @@ -23,8 +23,8 @@ // STD/STL -#include <string> #include <map> +#include <string> // Header #include "Bool.h" @@ -32,29 +32,31 @@ namespace armarx::aron::type { /* constructors */ - Bool::Bool(const Path& path) : - detail::PrimitiveVariant<type::dto::AronBool, Bool>(type::Descriptor::BOOL, path) + Bool::Bool(const Path& path) : Base(type::Descriptor::BOOL, path) { } - Bool::Bool(const type::dto::AronBool&o, const Path& path) : - detail::PrimitiveVariant<type::dto::AronBool, Bool>(o, type::Descriptor::BOOL, path) + Bool::Bool(const type::dto::AronBool& o, const Path& path) : + Base(o, type::Descriptor::BOOL, path) { } - type::dto::AronBoolPtr Bool::toBoolDTO() const + type::dto::AronBoolPtr + Bool::toBoolDTO() const { return this->aron; } /* virtual implementations */ - std::string Bool::getShortName() const + std::string + Bool::getShortName() const { return "Bool"; } - std::string Bool::getFullName() const + std::string + Bool::getFullName() const { return "armarx::aron::type::Bool"; } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Bool.h b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Bool.h index eac4aeaea068387ba065a98376a64212a2fc2307..3225dde43e9b2293e947000394e619b6019f53b9 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Bool.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Bool.h @@ -34,10 +34,11 @@ namespace armarx::aron::type /** * @brief The Bool class. It represents the bool type */ - class Bool : - public detail::PrimitiveVariant<type::dto::AronBool, Bool> + class Bool : public detail::PrimitiveVariant<type::dto::AronBool, Bool, bool> { public: + using Base = detail::PrimitiveVariant<type::dto::AronBool, Bool, bool>; + /* constructors */ Bool(const Path& = Path()); Bool(const type::dto::AronBool&, const Path& = Path()); @@ -48,4 +49,4 @@ namespace armarx::aron::type virtual std::string getShortName() const override; virtual std::string getFullName() const override; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Double.cpp b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Double.cpp index e4fd415fe7c54b34d6e60314810a336856e845c0..d5baa23743e6ec8cea2259aa2f0049acc9df63c5 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Double.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Double.cpp @@ -23,8 +23,8 @@ // STD/STL -#include <string> #include <map> +#include <string> // Header #include "Double.h" @@ -32,29 +32,31 @@ namespace armarx::aron::type { /* constructors */ - Double::Double(const Path& path) : - detail::PrimitiveVariant<type::dto::AronDouble, Double>(type::Descriptor::DOUBLE, path) + Double::Double(const Path& path) : Base(type::Descriptor::DOUBLE, path) { } - Double::Double(const type::dto::AronDouble&o, const Path& path) : - detail::PrimitiveVariant<type::dto::AronDouble, Double>(o, type::Descriptor::DOUBLE, path) + Double::Double(const type::dto::AronDouble& o, const Path& path) : + Base(o, type::Descriptor::DOUBLE, path) { } - type::dto::AronDoublePtr Double::toDoubleDTO() const + type::dto::AronDoublePtr + Double::toDoubleDTO() const { return this->aron; } /* virtual implementations */ - std::string Double::getShortName() const + std::string + Double::getShortName() const { return "Double"; } - std::string Double::getFullName() const + std::string + Double::getFullName() const { return "armarx::aron::type::Double"; } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Double.h b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Double.h index 17aa98ad764ac8081cfcd2e23aad38f388749d18..f63251434e1c945c9e8d7b79b10e3a48cecdabd6 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Double.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Double.h @@ -34,10 +34,11 @@ namespace armarx::aron::type /** * @brief The Double class. It represents the double type */ - class Double : - public detail::PrimitiveVariant<type::dto::AronDouble, Double> + class Double : public detail::PrimitiveVariant<type::dto::AronDouble, Double, double> { public: + using Base = detail::PrimitiveVariant<type::dto::AronDouble, Double, double>; + /* constructors */ Double(const Path& = Path()); Double(const type::dto::AronDouble&, const Path& = Path()); @@ -48,4 +49,4 @@ namespace armarx::aron::type virtual std::string getShortName() const override; virtual std::string getFullName() const override; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Float.cpp b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Float.cpp index 45bbad7dec390c876ff1033c650e187f29a4788e..ef7eb6e7a3791ecd82a20732dc36ae5d9c4df716 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Float.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Float.cpp @@ -23,8 +23,8 @@ // STD/STL -#include <string> #include <map> +#include <string> // Header #include "Float.h" @@ -32,29 +32,31 @@ namespace armarx::aron::type { /* constructors */ - Float::Float(const Path& path) : - detail::PrimitiveVariant<type::dto::AronFloat, Float>(type::Descriptor::FLOAT, path) + Float::Float(const Path& path) : Base(type::Descriptor::FLOAT, path) { } - Float::Float(const type::dto::AronFloat&o, const Path& path) : - detail::PrimitiveVariant<type::dto::AronFloat, Float>(o, type::Descriptor::FLOAT, path) + Float::Float(const type::dto::AronFloat& o, const Path& path) : + Base(o, type::Descriptor::FLOAT, path) { } - type::dto::AronFloatPtr Float::toFloatDTO() const + type::dto::AronFloatPtr + Float::toFloatDTO() const { return this->aron; } /* virtual implementations */ - std::string Float::getShortName() const + std::string + Float::getShortName() const { return "Float"; } - std::string Float::getFullName() const + std::string + Float::getFullName() const { return "armarx::aron::type::Float"; } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Float.h b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Float.h index 2dedfb1739b6f000baddc8bb13306781a3d34a99..0185727d6a1250630de0567e33cddb271a1eaeb3 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Float.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Float.h @@ -34,10 +34,11 @@ namespace armarx::aron::type /** * @brief The Float class. It represents the float type */ - class Float : - public detail::PrimitiveVariant<type::dto::AronFloat, Float> + class Float : public detail::PrimitiveVariant<type::dto::AronFloat, Float, float> { public: + using Base = detail::PrimitiveVariant<type::dto::AronFloat, Float, float>; + /* constructors */ Float(const Path& = Path()); Float(const type::dto::AronFloat&, const Path& = Path()); @@ -48,4 +49,4 @@ namespace armarx::aron::type virtual std::string getShortName() const override; virtual std::string getFullName() const override; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Int.cpp b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Int.cpp index 6abe9850c96afcdf34785f0226cd22f11e067be8..b4ab9eb61afa58f31950b6d0d5208709ead3ca34 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Int.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Int.cpp @@ -23,8 +23,8 @@ // STD/STL -#include <string> #include <map> +#include <string> // Header #include "Int.h" @@ -32,29 +32,30 @@ namespace armarx::aron::type { /* constructors */ - Int::Int(const Path& path) : - detail::PrimitiveVariant<type::dto::AronInt, Int>(type::Descriptor::INT, path) + Int::Int(const Path& path) : Base(type::Descriptor::INT, path) { } - Int::Int(const type::dto::AronInt&o, const Path& path) : - detail::PrimitiveVariant<type::dto::AronInt, Int>(o, type::Descriptor::INT, path) + Int::Int(const type::dto::AronInt& o, const Path& path) : Base(o, type::Descriptor::INT, path) { } - type::dto::AronIntPtr Int::toIntDTO() const + type::dto::AronIntPtr + Int::toIntDTO() const { return this->aron; } /* virtual implementations */ - std::string Int::getShortName() const + std::string + Int::getShortName() const { return "Int"; } - std::string Int::getFullName() const + std::string + Int::getFullName() const { return "armarx::aron::type::Int"; } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Int.h b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Int.h index 240cd4a50df8687f8cdba2ff15c040d21ec27fbe..10f222b79eb0432cc03e906c30ff5b588c6786ad 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Int.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Int.h @@ -34,10 +34,11 @@ namespace armarx::aron::type /** * @brief The Int class. It represents the int type */ - class Int : - public detail::PrimitiveVariant<type::dto::AronInt, Int> + class Int : public detail::PrimitiveVariant<type::dto::AronInt, Int, int> { public: + using Base = detail::PrimitiveVariant<type::dto::AronInt, Int, int>; + /* constructors */ Int(const Path& = Path()); Int(const type::dto::AronInt&, const Path& = Path()); @@ -48,4 +49,4 @@ namespace armarx::aron::type virtual std::string getShortName() const override; virtual std::string getFullName() const override; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Long.cpp b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Long.cpp index f7898bcf2247ddbffea6fedba1c51699571030ba..5abee29f0049d0a5c2e52c6604628c922a6f8490 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Long.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Long.cpp @@ -23,8 +23,8 @@ // STD/STL -#include <string> #include <map> +#include <string> // Header #include "Long.h" @@ -32,29 +32,31 @@ namespace armarx::aron::type { /* constructors */ - Long::Long(const Path& path) : - detail::PrimitiveVariant<type::dto::AronLong, Long>(type::Descriptor::LONG, path) + Long::Long(const Path& path) : Base(type::Descriptor::LONG, path) { } - Long::Long(const type::dto::AronLong&o, const Path& path) : - detail::PrimitiveVariant<type::dto::AronLong, Long>(o, type::Descriptor::LONG, path) + Long::Long(const type::dto::AronLong& o, const Path& path) : + Base(o, type::Descriptor::LONG, path) { } - type::dto::AronLongPtr Long::toLongDTO() const + type::dto::AronLongPtr + Long::toLongDTO() const { return this->aron; } /* virtual implementations */ - std::string Long::getShortName() const + std::string + Long::getShortName() const { return "Long"; } - std::string Long::getFullName() const + std::string + Long::getFullName() const { return "armarx::aron::type::Long"; } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Long.h b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Long.h index 710df1a421e5ff684ac85b70839ff7cff513378e..f64ca0a3492afcbcda9a4d023f2b61b3ede8075d 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/Long.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/Long.h @@ -34,10 +34,11 @@ namespace armarx::aron::type /** * @brief The Long class. It represents the long type */ - class Long : - public detail::PrimitiveVariant<type::dto::AronLong, Long> + class Long : public detail::PrimitiveVariant<type::dto::AronLong, Long, long> { public: + using Base = detail::PrimitiveVariant<type::dto::AronLong, Long, long>; + /* constructors */ Long(const Path& = Path()); Long(const type::dto::AronLong&, const Path& = Path()); @@ -48,4 +49,4 @@ namespace armarx::aron::type virtual std::string getShortName() const override; virtual std::string getFullName() const override; }; -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/String.cpp b/source/RobotAPI/libraries/aron/core/type/variant/primitive/String.cpp index 0ede75062e53745057b0c181db65681656365d7d..8c350084c1a710300e41783c8fec91fa8e666cc8 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/String.cpp +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/String.cpp @@ -23,8 +23,8 @@ // STD/STL -#include <string> #include <map> +#include <string> // Header #include "String.h" @@ -32,30 +32,32 @@ namespace armarx::aron::type { /* constructors */ - String::String(const Path& path) : - detail::PrimitiveVariant<type::dto::AronString, String>(type::Descriptor::STRING, path) + String::String(const Path& path) : Base(type::Descriptor::STRING, path) { } - String::String(const type::dto::AronString&o, const Path& path) : - detail::PrimitiveVariant<type::dto::AronString, String>(o, type::Descriptor::STRING, path) + String::String(const type::dto::AronString& o, const Path& path) : + Base(o, type::Descriptor::STRING, path) { } /* public member functions */ - type::dto::AronStringPtr String::toStringDTO() const + type::dto::AronStringPtr + String::toStringDTO() const { return aron; } /* virtual implementations */ - std::string String::getShortName() const + std::string + String::getShortName() const { return "String"; } - std::string String::getFullName() const + std::string + String::getFullName() const { return "armarx::aron::type::String"; } -} +} // namespace armarx::aron::type diff --git a/source/RobotAPI/libraries/aron/core/type/variant/primitive/String.h b/source/RobotAPI/libraries/aron/core/type/variant/primitive/String.h index 54dedab7b228d2262097d0cbe59675c4f721eb39..a0b9433305f455e52f2c4ddee1c3392aa1b6a20e 100644 --- a/source/RobotAPI/libraries/aron/core/type/variant/primitive/String.h +++ b/source/RobotAPI/libraries/aron/core/type/variant/primitive/String.h @@ -34,10 +34,11 @@ namespace armarx::aron::type /** * @brief The String class. It represents the string type */ - class String : - public detail::PrimitiveVariant<type::dto::AronString, String> + class String : public detail::PrimitiveVariant<type::dto::AronString, String, std::string> { public: + using Base = detail::PrimitiveVariant<type::dto::AronString, String, std::string>; + /* constructors */ String(const Path& = Path()); String(const type::dto::AronString&, const Path& = Path()); @@ -48,4 +49,4 @@ namespace armarx::aron::type virtual std::string getShortName() const override; virtual std::string getFullName() const override; }; -} +} // namespace armarx::aron::type