From 676f5bccd9aec8674bdbd0bd1dab8f3f7131e785 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Tue, 2 Jul 2024 13:09:14 +0200 Subject: [PATCH 01/23] added option to send messages as json --- CMakeLists.txt | 28 ++++++++---- cmake/Dependencies.cmake | 21 +++++---- .../mission_module/devices/AutonomyDevice.hpp | 4 ++ .../mission_module/devices/AutonomyDevice.cpp | 44 +++++++++++++++++-- source/external_server_api.cpp | 14 +++++- 5 files changed, 89 insertions(+), 22 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 62e6c0a..3f00e26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,6 +17,7 @@ OPTION(BRINGAUTO_PACKAGE "Configure package creation" OFF) OPTION(BRINGAUTO_SYSTEM_DEP "System dependencies are used if switched to ON, packager used if OFF" OFF) OPTION(FLEET_PROTOCOL_BUILD_MODULE_GATEWAY "Build shared library for module gateway " ON) OPTION(FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER "Build shared library for external server " ON) +OPTION(SKIP_PROTOBUF "Handle commands and statuses only as JSON strings" OFF) IF (BRINGAUTO_PACKAGE) IF (NOT BRINGAUTO_INSTALL) @@ -50,7 +51,11 @@ IF (NOT BRINGAUTO_SYSTEM_DEP) INCLUDE("cmake/Dependencies.cmake") ENDIF () -FIND_PACKAGE(Protobuf 3.21.12 REQUIRED) +IF (SKIP_PROTOBUF) + FIND_PACKAGE(nlohmann_json 3.10.5 REQUIRED) +ELSE () + FIND_PACKAGE(Protobuf 3.21.12 REQUIRED) +ENDIF () FIND_PACKAGE(fleet-protocol-interface 2.0.0 REQUIRED) FIND_PACKAGE(fleet-protocol-cxx-helpers-static 1.1.1 REQUIRED) @@ -68,18 +73,23 @@ CMDEF_ADD_LIBRARY( VERSION ${MISSION_MODULE_VERSION} ) -# Protobuf mission payload -SET(Protobuf_USE_STATIC_LIBS ON) -FILE(GLOB_RECURSE protobuf_mission_cpp_files "lib/protobuf-mission-module/*") -ADD_LIBRARY(protobuf_mission_lib STATIC ${protobuf_mission_cpp_files}) -TARGET_INCLUDE_DIRECTORIES(protobuf_mission_lib PUBLIC "lib/protobuf-mission-module/") -TARGET_LINK_LIBRARIES(protobuf_mission_lib PUBLIC protobuf::libprotobuf) +IF (SKIP_PROTOBUF) + # JSON mission payload + ADD_LIBRARY(message_handler_lib ALIAS nlohmann_json::nlohmann_json) +ELSE() + # Protobuf mission payload + SET(Protobuf_USE_STATIC_LIBS ON) + FILE(GLOB_RECURSE protobuf_mission_cpp_files "lib/protobuf-mission-module/*") + ADD_LIBRARY(message_handler_lib STATIC ${protobuf_mission_cpp_files}) + TARGET_INCLUDE_DIRECTORIES(message_handler_lib PUBLIC "lib/protobuf-mission-module/") + TARGET_LINK_LIBRARIES(message_handler_lib PUBLIC protobuf::libprotobuf) +ENDIF() FILE(GLOB_RECURSE HEADERS "include/*") ADD_LIBRARY(mission_module_hpp INTERFACE ${HEADERS}) TARGET_INCLUDE_DIRECTORIES(mission_module_hpp INTERFACE "include/") -TARGET_LINK_LIBRARIES(mission_module_hpp INTERFACE protobuf_mission_lib) +TARGET_LINK_LIBRARIES(mission_module_hpp INTERFACE message_handler_lib) FILE(GLOB_RECURSE SOURCES "source/bringauto/*") @@ -89,7 +99,7 @@ TARGET_LINK_LIBRARIES(mission_module_sources PUBLIC mission_module_hpp fleet-protocol-interface::common-headers-interface fleet-protocol-cxx-helpers-static::fleet-protocol-cxx-helpers-static - protobuf_mission_lib + message_handler_lib ) IF (FLEET_PROTOCOL_BUILD_MODULE_GATEWAY) diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index cc74dad..df80e6b 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -1,13 +1,18 @@ SET(CMAKE_FIND_USE_CMAKE_SYSTEM_PATH FALSE) -BA_PACKAGE_LIBRARY(fleet-protocol-interface v2.0.0 PLATFORM_STRING_MODE any_machine NO_DEBUG ON) -BA_PACKAGE_LIBRARY(fleet-protocol-cxx-helpers-static v1.1.1) -BA_PACKAGE_LIBRARY(protobuf v4.21.12) -BA_PACKAGE_LIBRARY(zlib v1.2.11) +BA_PACKAGE_LIBRARY(fleet-protocol-interface v2.0.0 PLATFORM_STRING_MODE any_machine NO_DEBUG ON) +BA_PACKAGE_LIBRARY(fleet-protocol-cxx-helpers-static v1.1.1) +BA_PACKAGE_LIBRARY(zlib v1.2.11) + +IF (SKIP_PROTOBUF) + BA_PACKAGE_LIBRARY(nlohmann-json v3.10.5 PLATFORM_STRING_MODE any_machine NO_DEBUG ON) +ELSE () + BA_PACKAGE_LIBRARY(protobuf v4.21.12) +ENDIF () IF (FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER) - BA_PACKAGE_LIBRARY(fleet-http-client-shared v1.3.0) - BA_PACKAGE_LIBRARY(boost v1.78.0) - BA_PACKAGE_LIBRARY(cpprestsdk v2.10.20) - BA_PACKAGE_LIBRARY(ba-logger v1.2.0) + BA_PACKAGE_LIBRARY(fleet-http-client-shared v1.3.0) + BA_PACKAGE_LIBRARY(boost v1.78.0) + BA_PACKAGE_LIBRARY(cpprestsdk v2.10.20) + BA_PACKAGE_LIBRARY(ba-logger v1.2.0) ENDIF () diff --git a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp index 749e6a2..55a5efe 100644 --- a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp +++ b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp @@ -1,6 +1,8 @@ #pragma once +#ifndef SKIP_PROTOBUF #include +#endif #include #include @@ -90,8 +92,10 @@ class AutonomyDevice { */ static int command_data_valid(const struct buffer command); private: +#ifndef SKIP_PROTOBUF static MissionModule::AutonomyCommand generateCommand(std::vector stops, std::string route, MissionModule::AutonomyCommand::Action action); +#endif /** * @brief Map of last sent status timestamps for each device type diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index 84f677f..4eda7e2 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -1,10 +1,13 @@ +#ifndef SKIP_PROTOBUF #include -#include +#include +#include +#endif +#include #include #include -#include -#include + @@ -13,6 +16,7 @@ namespace bringauto::modules::mission_module::devices { std::map AutonomyDevice::last_sent_status_timestamps_ {}; int AutonomyDevice::send_status_condition(const struct buffer current_status, const struct buffer new_status, unsigned int device_type) { +#ifndef SKIP_PROTOBUF auto currentAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(current_status); auto newAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(new_status); @@ -28,10 +32,14 @@ int AutonomyDevice::send_status_condition(const struct buffer current_status, co } } return CONDITION_NOT_MET; +#else + return OK; +#endif } int AutonomyDevice::generate_command(struct buffer *generated_command, const struct buffer new_status, const struct buffer current_status, const struct buffer current_command) { +#ifndef SKIP_PROTOBUF auto currentAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(current_status); auto newAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(new_status); auto currentAutonomyCommand = protobuf::ProtobufHelper::parseAutonomyCommand(current_command); @@ -43,6 +51,13 @@ int AutonomyDevice::generate_command(struct buffer *generated_command, const str } } return protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(generated_command, currentAutonomyCommand); +#else + if (allocate(generated_command, current_command.size_in_bytes) != OK) { + return NOT_OK; + } + std::memcpy(generated_command->data, current_command.data, generated_command->size_in_bytes); + return OK; +#endif } int AutonomyDevice::aggregate_status(struct buffer *aggregated_status, const struct buffer current_status, @@ -56,6 +71,7 @@ int AutonomyDevice::aggregate_status(struct buffer *aggregated_status, const str int AutonomyDevice::aggregate_error(struct buffer *error_message, const struct buffer current_error_message, const struct buffer status) { +#ifndef SKIP_PROTOBUF auto autonomyError = protobuf::ProtobufHelper::parseAutonomyError(current_error_message); auto autonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(status); @@ -71,36 +87,57 @@ int AutonomyDevice::aggregate_error(struct buffer *error_message, const struct b } return protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(error_message, autonomyError); +#else + if (allocate(error_message, current_error_message.size_in_bytes) != OK) { + return NOT_OK; + } + std::memcpy(error_message->data, current_error_message.data, error_message->size_in_bytes); + return OK; +#endif } int AutonomyDevice::generate_first_command(struct buffer *default_command) { +#ifndef SKIP_PROTOBUF MissionModule::AutonomyCommand command = generateCommand(std::vector(), "", MissionModule::AutonomyCommand_Action_NO_ACTION); if (protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(default_command, command) != OK) { return NOT_OK; } return OK; +#else + std::string default_command_str = "{}"; + if ((allocate(default_command, default_command_str.length())) == OK) { + std::memcpy(default_command->data, default_command_str.c_str(), default_command->size_in_bytes); + return OK; + } + return NOT_OK; +#endif } int AutonomyDevice::status_data_valid(const struct buffer status) { +#ifndef SKIP_PROTOBUF try { protobuf::ProtobufHelper::parseAutonomyStatus(status); } catch (...) { return NOT_OK; } +#endif return OK; } int AutonomyDevice::command_data_valid(const struct buffer command) { +#ifndef SKIP_PROTOBUF try { protobuf::ProtobufHelper::parseAutonomyCommand(command); } catch (...) { return NOT_OK; } +#endif return OK; } +#ifndef SKIP_PROTOBUF MissionModule::AutonomyCommand AutonomyDevice::generateCommand(std::vector stops, std::string route, MissionModule::AutonomyCommand::Action action) { @@ -111,5 +148,6 @@ AutonomyDevice::generateCommand(std::vector stops, std:: command.set_action(action); return command; } +#endif } \ No newline at end of file diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index a631449..40b23bd 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -2,12 +2,14 @@ #include #include #include -#include #include #include #include #include +#ifndef SKIP_PROTOBUF +#include #include +#endif #include #include @@ -147,12 +149,16 @@ int forward_status(const buffer device_status, const device_identification devic auto con = static_cast (context); if(device.device_type == bamm::AUTONOMY_DEVICE_TYPE) { +#ifdef SKIP_PROTOBUF + std::string device_status_str = device_status.getStringView(); +#else std::string device_status_str; auto device_status_parsed = bringauto::protobuf::ProtobufHelper::parseAutonomyStatus(device_status); auto protobuf_options = google::protobuf::util::JsonPrintOptions(); protobuf_options.always_print_primitive_fields = true; google::protobuf::util::MessageToJsonString(device_status_parsed, &device_status_str, protobuf_options); - +#endif + bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); con->fleet_api_client->setDeviceIdentification( @@ -302,6 +308,9 @@ int wait_for_command(int timeout_time_in_ms, void *context) { } if(parse_commands) { +#ifdef SKIP_PROTOBUF + std::string command_str = command->getPayload()->getData()->getJson().serialize(); +#else MissionModule::AutonomyCommand proto_command {}; const auto parse_status = google::protobuf::util::JsonStringToMessage( command->getPayload()->getData()->getJson().serialize(), &proto_command @@ -311,6 +320,7 @@ int wait_for_command(int timeout_time_in_ms, void *context) { } std::string command_str; proto_command.SerializeToString(&command_str); +#endif con->command_vector.emplace_back(command_str, bringauto::fleet_protocol::cxx::DeviceID( received_device_id->getModuleId(), From d9a391970f95c8c8deafecd079b4b4e08b75662c Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Thu, 11 Jul 2024 10:17:54 +0200 Subject: [PATCH 02/23] added flag to use raw json instead of protobuf --- CMakeLists.txt | 1 + include/bringauto/json/DeviceCommand.hpp | 43 ++++++++ include/bringauto/json/DeviceError.hpp | 38 +++++++ include/bringauto/json/DeviceStatus.hpp | 33 +++++++ include/bringauto/json/EnumUtils.hpp | 21 ++++ include/bringauto/json/SerializationUtils.hpp | 17 ++++ include/bringauto/json/Structures.hpp | 78 +++++++++++++++ .../mission_module/devices/AutonomyDevice.hpp | 1 + include/bringauto/protobuf/ProtobufHelper.hpp | 4 +- source/bringauto/json/DeviceCommand.cpp | 76 ++++++++++++++ source/bringauto/json/DeviceError.cpp | 69 +++++++++++++ source/bringauto/json/DeviceStatus.cpp | 76 ++++++++++++++ source/bringauto/json/EnumUtils.cpp | 60 ++++++++++++ source/bringauto/json/SerializationUtils.cpp | 22 +++++ .../mission_module/devices/AutonomyDevice.cpp | 98 +++++++++++++------ source/bringauto/protobuf/ProtobufHelper.cpp | 3 +- source/external_server_api.cpp | 8 +- 17 files changed, 614 insertions(+), 34 deletions(-) create mode 100644 include/bringauto/json/DeviceCommand.hpp create mode 100644 include/bringauto/json/DeviceError.hpp create mode 100644 include/bringauto/json/DeviceStatus.hpp create mode 100644 include/bringauto/json/EnumUtils.hpp create mode 100644 include/bringauto/json/SerializationUtils.hpp create mode 100644 include/bringauto/json/Structures.hpp create mode 100644 source/bringauto/json/DeviceCommand.cpp create mode 100644 source/bringauto/json/DeviceError.cpp create mode 100644 source/bringauto/json/DeviceStatus.cpp create mode 100644 source/bringauto/json/EnumUtils.cpp create mode 100644 source/bringauto/json/SerializationUtils.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b2e87c6..44027b0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,6 +56,7 @@ IF (NOT BRINGAUTO_SYSTEM_DEP) ENDIF () IF (SKIP_PROTOBUF) + ADD_COMPILE_DEFINITIONS(SKIP_PROTOBUF) FIND_PACKAGE(nlohmann_json 3.10.5 REQUIRED) ELSE () FIND_PACKAGE(Protobuf 3.21.12 REQUIRED) diff --git a/include/bringauto/json/DeviceCommand.hpp b/include/bringauto/json/DeviceCommand.hpp new file mode 100644 index 0000000..2c9a588 --- /dev/null +++ b/include/bringauto/json/DeviceCommand.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include +#include + +namespace bringauto::json { + +class DeviceCommand { +public: + DeviceCommand(); + + /** + * @brief Serializes this object into given buffer using json. + */ + int serializeToBuffer(buffer *command_buffer); + + /** + * @brief Deserializes command in buffer (json string in data) and sets this object. + * @return OK - serialization successful, NOT_OK - serialization failed + */ + int deserializeFromBuffer(buffer command_buffer); + + /** + * @brief Returns the command of the device. + */ + AutonomyCommand getCommand() const { return command_; } + + /** + * @brief Sets the action of the device command. + */ + void setAction(AutonomyAction action) { command_.act = action; } + + /** + * @brief Remove the first top in the stops list. + */ + void removeFirstStop(); + +private: + AutonomyCommand command_ {}; + +}; + +} diff --git a/include/bringauto/json/DeviceError.hpp b/include/bringauto/json/DeviceError.hpp new file mode 100644 index 0000000..82208fc --- /dev/null +++ b/include/bringauto/json/DeviceError.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include +#include + +namespace bringauto::json { + +class DeviceError { +public: + DeviceError(); + + /** + * @brief Serializes this object into given buffer using json. + */ + int serializeToBuffer(buffer *error_buffer); + + /** + * @brief Deserializes error in buffer (json string in data) and sets this object. + * @return OK - serialization successful, NOT_OK - serialization failed + */ + int deserializeFromBuffer(buffer error_buffer); + + /** + * @brief Returns the error of the device. + */ + AutonomyError getError() const { return error_; } + + /** + * @brief Add a stop to the finished stops list. + */ + void addFinishedStop(const Station &station); + +private: + AutonomyError error_ {}; + +}; + +} diff --git a/include/bringauto/json/DeviceStatus.hpp b/include/bringauto/json/DeviceStatus.hpp new file mode 100644 index 0000000..3d26a88 --- /dev/null +++ b/include/bringauto/json/DeviceStatus.hpp @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +namespace bringauto::json { + +class DeviceStatus { +public: + DeviceStatus(); + + /** + * @brief Serializes this object into given buffer using json. + */ + int serializeToBuffer(buffer *status_buffer); + + /** + * @brief Deserializes status in buffer (json string in data) and sets this object. + * @return OK - serialization successful, NOT_OK - serialization failed + */ + int deserializeFromBuffer(buffer status_buffer); + + /** + * @brief Returns the status of the device. + */ + AutonomyStatus getStatus() const { return status_; } + +private: + AutonomyStatus status_ {}; + +}; + +} diff --git a/include/bringauto/json/EnumUtils.hpp b/include/bringauto/json/EnumUtils.hpp new file mode 100644 index 0000000..7b45089 --- /dev/null +++ b/include/bringauto/json/EnumUtils.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include + +namespace bringauto::json { + +class EnumUtils { +public: + EnumUtils() = delete; + + static AutonomyState stringToAutonomyState(const std::string &state); + + static std::string autonomyStateToString(const AutonomyState &state); + + static AutonomyAction stringToAutonomyAction(const std::string &action); + + static std::string autonomyActionToString(const AutonomyAction &action); + +}; + +} \ No newline at end of file diff --git a/include/bringauto/json/SerializationUtils.hpp b/include/bringauto/json/SerializationUtils.hpp new file mode 100644 index 0000000..3c7d0b2 --- /dev/null +++ b/include/bringauto/json/SerializationUtils.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include + +#include + +namespace bringauto::json { + +using json = nlohmann::ordered_json; + +class SerializationUtils { +public: + int static json_to_buffer(json json, buffer *buffer); + +}; + +} \ No newline at end of file diff --git a/include/bringauto/json/Structures.hpp b/include/bringauto/json/Structures.hpp new file mode 100644 index 0000000..c002327 --- /dev/null +++ b/include/bringauto/json/Structures.hpp @@ -0,0 +1,78 @@ +#pragma once + +#include +#include + +namespace bringauto::json { + +enum AutonomyState { + IDLE, DRIVE, IN_STOP, OBSTACLE, ERROR +}; + +enum AutonomyAction { + NO_ACTION, STOP, START +}; + +struct Position { + double alt; + double lat; + double lon; + + double altitude() { return alt; }; + double latitude() { return lat; }; + double longitude() { return lon; }; + + bool operator==(const Position &other) const { + return alt == other.alt && lat == other.lat && lon == other.lon; + }; +}; + +struct Station { + std::string nam; + Position pos; + + std::string name() { return nam; }; + Position position() { return pos; }; + + bool operator==(const Station &other) const { + return nam == other.nam && pos == other.pos; + }; +}; + +struct Telemetry { + double spe; + double fue; + Position pos; + + double speed() { return spe; }; + double fuel() { return fue; }; + Position position() { return pos; }; +}; + +struct AutonomyStatus { + Telemetry tel; + AutonomyState sta; + Station nex; + + Telemetry telemetry() { return tel; }; + AutonomyState state() { return sta; }; + Station nextstop() { return nex; }; +}; + +struct AutonomyCommand { + std::list sto; + std::string rou; + AutonomyAction act; + + std::list stops() { return sto; }; + std::string route() { return rou; }; + AutonomyAction action() { return act; }; +}; + +struct AutonomyError { + std::list fin; + + std::list finishedstops() { return fin; }; +}; + +} \ No newline at end of file diff --git a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp index 55a5efe..ef29849 100644 --- a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp +++ b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp @@ -5,6 +5,7 @@ #endif #include +#include #include namespace bringauto::modules::mission_module::devices { diff --git a/include/bringauto/protobuf/ProtobufHelper.hpp b/include/bringauto/protobuf/ProtobufHelper.hpp index 74405be..ef9a3ad 100644 --- a/include/bringauto/protobuf/ProtobufHelper.hpp +++ b/include/bringauto/protobuf/ProtobufHelper.hpp @@ -1,5 +1,6 @@ #pragma once +#ifndef SKIP_PROTOBUF #include #include @@ -16,4 +17,5 @@ class ProtobufHelper { }; -} \ No newline at end of file +} +#endif diff --git a/source/bringauto/json/DeviceCommand.cpp b/source/bringauto/json/DeviceCommand.cpp new file mode 100644 index 0000000..89501f0 --- /dev/null +++ b/source/bringauto/json/DeviceCommand.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include + +#include + +namespace bringauto::json { + +using json = nlohmann::ordered_json; + +DeviceCommand::DeviceCommand() { + +} + +int DeviceCommand::serializeToBuffer(buffer *command_buffer) { + json command_json; + command_json["route"] = command_.rou; + command_json["action"] = EnumUtils::autonomyActionToString(command_.act); + + int i = 0; + for(auto const& stop : command_.sto) { + command_json["stops"][i]["name"] = stop.nam; + command_json["stops"][i]["position"]["altitude"] = stop.pos.alt; + command_json["stops"][i]["position"]["latitude"] = stop.pos.lat; + command_json["stops"][i]["position"]["longitude"] = stop.pos.lon; + i++; + } + + if (SerializationUtils::json_to_buffer(command_json, command_buffer) == NOT_OK) { + return NOT_OK; + } + + return OK; +} + +int DeviceCommand::deserializeFromBuffer(buffer command_buffer) { + json command_json; + char *buffer_data = static_cast (command_buffer.data); + + try { + command_json = json::parse(buffer_data, buffer_data + command_buffer.size_in_bytes); + } catch (json::parse_error &) { + return NOT_OK; + } + + try { + for (int i = 0; i < command_json.at("stops").size(); i++) { + bringauto::json::Position position { + .alt = command_json.at("stops").at(i).at("position").at("altitude"), + .lat = command_json.at("stops").at(i).at("position").at("latitude"), + .lon = command_json.at("stops").at(i).at("position").at("longitude") + }; + bringauto::json::Station stop { + .nam = command_json.at("stops").at(i).at("name"), + .pos = position + }; + command_.sto.push_back(stop); + } + + command_.rou = command_json.at("route"); + command_.act = EnumUtils::stringToAutonomyAction(command_json.at("action")); + } catch (json::exception &) { + return NOT_OK; + } + + return OK; +} + +void DeviceCommand::removeFirstStop() { + if (!command_.sto.empty()) { + command_.sto.pop_front(); + } +} + +} \ No newline at end of file diff --git a/source/bringauto/json/DeviceError.cpp b/source/bringauto/json/DeviceError.cpp new file mode 100644 index 0000000..8a16437 --- /dev/null +++ b/source/bringauto/json/DeviceError.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include + +#include + +namespace bringauto::json { + +using json = nlohmann::ordered_json; + +DeviceError::DeviceError() { + +} + +int DeviceError::serializeToBuffer(buffer *error_buffer) { + json error_json; + + int i = 0; + for(auto const& stop : error_.fin) { + error_json["finishedStops"][i]["name"] = stop.nam; + error_json["finishedStops"][i]["position"]["altitude"] = stop.pos.alt; + error_json["finishedStops"][i]["position"]["latitude"] = stop.pos.lat; + error_json["finishedStops"][i]["position"]["longitude"] = stop.pos.lon; + i++; + } + + if (SerializationUtils::json_to_buffer(error_json, error_buffer) == NOT_OK) { + return NOT_OK; + } + + return OK; +} + +int DeviceError::deserializeFromBuffer(buffer error_buffer) { + json error_json; + char *buffer_data = static_cast (error_buffer.data); + + try { + error_json = json::parse(buffer_data, buffer_data + error_buffer.size_in_bytes); + } catch (json::parse_error &) { + return NOT_OK; + } + + try { + for (int i = 0; i < error_json.at("finishedStops").size(); i++) { + bringauto::json::Position position { + .alt = error_json.at("finishedStops").at(i).at("position").at("altitude"), + .lat = error_json.at("finishedStops").at(i).at("position").at("latitude"), + .lon = error_json.at("finishedStops").at(i).at("position").at("longitude") + }; + bringauto::json::Station stop { + .nam = error_json.at("finishedStops").at(i).at("name"), + .pos = position + }; + error_.fin.push_back(stop); + } + } catch (json::exception &) { + return NOT_OK; + } + + return OK; +} + +void DeviceError::addFinishedStop(const Station &station) { + error_.fin.push_back(station); +} + +} diff --git a/source/bringauto/json/DeviceStatus.cpp b/source/bringauto/json/DeviceStatus.cpp new file mode 100644 index 0000000..debf642 --- /dev/null +++ b/source/bringauto/json/DeviceStatus.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include + +#include + +namespace bringauto::json { + +using json = nlohmann::ordered_json; + +DeviceStatus::DeviceStatus() { + +} + +int DeviceStatus::serializeToBuffer(buffer *status_buffer) { + json status_json; + status_json["telemetry"]["fuel"] = status_.tel.fue; + status_json["telemetry"]["speed"] = status_.tel.spe; + status_json["telemetry"]["position"]["altitude"] = status_.tel.pos.alt; + status_json["telemetry"]["position"]["latitude"] = status_.tel.pos.lat; + status_json["telemetry"]["position"]["longitude"] = status_.tel.pos.lon; + status_json["nextStop"]["name"] = status_.nex.nam; + status_json["nextStop"]["position"]["altitude"] = status_.nex.pos.alt; + status_json["nextStop"]["position"]["latitude"] = status_.nex.pos.lat; + status_json["nextStop"]["position"]["longitude"] = status_.nex.pos.lon; + status_json["state"] = EnumUtils::autonomyStateToString(status_.sta); + + if (SerializationUtils::json_to_buffer(status_json, status_buffer) == NOT_OK) { + return NOT_OK; + } + + return OK; +} + +int DeviceStatus::deserializeFromBuffer(buffer status_buffer) { + json status_json; + char *buffer_data = static_cast (status_buffer.data); + + try { + status_json = json::parse(buffer_data, buffer_data + status_buffer.size_in_bytes); + } catch (json::parse_error &) { + return NOT_OK; + } + + try { + bringauto::json::Position position { + .alt = status_json.at("telemetry").at("position").at("altitude"), + .lat = status_json.at("telemetry").at("position").at("latitude"), + .lon = status_json.at("telemetry").at("position").at("longitude") + }; + bringauto::json::Telemetry telemetry { + .spe = status_json.at("telemetry").at("speed"), + .fue = status_json.at("telemetry").at("fuel"), + .pos = position + }; + bringauto::json::Position next_stop_position { + .alt = status_json.at("nextStop").at("position").at("altitude"), + .lat = status_json.at("nextStop").at("position").at("latitude"), + .lon = status_json.at("nextStop").at("position").at("longitude") + }; + bringauto::json::Station next_stop { + .nam = status_json.at("nextStop").at("name"), + .pos = next_stop_position + }; + status_.nex = next_stop; + status_.tel = telemetry; + status_.sta = EnumUtils::stringToAutonomyState(status_json.at("state")); + } catch (json::exception &) { + return NOT_OK; + } + + return OK; +} + +} \ No newline at end of file diff --git a/source/bringauto/json/EnumUtils.cpp b/source/bringauto/json/EnumUtils.cpp new file mode 100644 index 0000000..d5b0dd1 --- /dev/null +++ b/source/bringauto/json/EnumUtils.cpp @@ -0,0 +1,60 @@ +#include + + +namespace bringauto::json { + +AutonomyState EnumUtils::stringToAutonomyState(const std::string &state) { + if (state == "IDLE") { + return AutonomyState::IDLE; + } else if (state == "DRIVE") { + return AutonomyState::DRIVE; + } else if (state == "IN_STOP") { + return AutonomyState::IN_STOP; + } else if (state == "OBSTACLE") { + return AutonomyState::OBSTACLE; + } else if (state == "ERROR") { + return AutonomyState::ERROR; + } + return AutonomyState::ERROR; +} + +std::string EnumUtils::autonomyStateToString(const AutonomyState &state) { + switch (state) { + case AutonomyState::IDLE: + return "IDLE"; + case AutonomyState::DRIVE: + return "DRIVE"; + case AutonomyState::IN_STOP: + return "IN_STOP"; + case AutonomyState::OBSTACLE: + return "OBSTACLE"; + case AutonomyState::ERROR: + return "ERROR"; + } + return "ERROR"; +} + +AutonomyAction EnumUtils::stringToAutonomyAction(const std::string &action) { + if (action == "NO_ACTION") { + return AutonomyAction::NO_ACTION; + } else if (action == "STOP") { + return AutonomyAction::STOP; + } else if (action == "START") { + return AutonomyAction::START; + } + return AutonomyAction::NO_ACTION; +} + +std::string EnumUtils::autonomyActionToString(const AutonomyAction &action) { + switch (action) { + case AutonomyAction::NO_ACTION: + return "NO_ACTION"; + case AutonomyAction::STOP: + return "STOP"; + case AutonomyAction::START: + return "START"; + } + return "NO_ACTION"; +} + +} \ No newline at end of file diff --git a/source/bringauto/json/SerializationUtils.cpp b/source/bringauto/json/SerializationUtils.cpp new file mode 100644 index 0000000..1ceb7ca --- /dev/null +++ b/source/bringauto/json/SerializationUtils.cpp @@ -0,0 +1,22 @@ +#include +#include + +#include + +namespace bringauto::json { + +using json = nlohmann::ordered_json; + +int SerializationUtils::json_to_buffer(json json, buffer *buffer) { + std::string tmp = to_string(json); + + if (allocate(buffer, tmp.size()) == NOT_OK) { + return NOT_OK; + } + + std::memcpy(buffer->data, tmp.c_str(), tmp.size()); + + return OK; +} + +} \ No newline at end of file diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index 8fed531..6935521 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -1,4 +1,8 @@ -#ifndef SKIP_PROTOBUF +#ifdef SKIP_PROTOBUF +#include +#include +#include +#else #include #include #include @@ -8,6 +12,7 @@ #include #include +#include @@ -18,12 +23,24 @@ namespace bamm = bringauto::modules::mission_module; std::map AutonomyDevice::last_sent_status_timestamps_ {}; int AutonomyDevice::send_status_condition(const struct buffer current_status, const struct buffer new_status, unsigned int device_type) { -#ifndef SKIP_PROTOBUF +#ifdef SKIP_PROTOBUF + bringauto::json::DeviceStatus current_status_object {}; + bringauto::json::DeviceStatus new_status_object {}; + current_status_object.deserializeFromBuffer(current_status); + new_status_object.deserializeFromBuffer(new_status); + auto currentAutonomyStatus = current_status_object.getStatus(); + auto newAutonomyStatus = new_status_object.getStatus(); +#else auto currentAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(current_status); auto newAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(new_status); +#endif if (currentAutonomyStatus.state() != newAutonomyStatus.state() +#ifdef SKIP_PROTOBUF + || currentAutonomyStatus.nextstop() != newAutonomyStatus.nextstop()) { +#else || !google::protobuf::util::MessageDifferencer::Equals(currentAutonomyStatus.nextstop(), newAutonomyStatus.nextstop())) { +#endif return OK; } else if (newAutonomyStatus.telemetry().speed() >= bamm::Constants::status_speed_threshold) { auto current_time = std::chrono::duration_cast( @@ -34,14 +51,24 @@ int AutonomyDevice::send_status_condition(const struct buffer current_status, co } } return CONDITION_NOT_MET; -#else - return OK; -#endif } int AutonomyDevice::generate_command(struct buffer *generated_command, const struct buffer new_status, const struct buffer current_status, const struct buffer current_command) { -#ifndef SKIP_PROTOBUF +#ifdef SKIP_PROTOBUF + bringauto::json::DeviceStatus current_status_object {}; + bringauto::json::DeviceStatus new_status_object {}; + bringauto::json::DeviceCommand current_command_object {}; + current_status_object.deserializeFromBuffer(current_status); + new_status_object.deserializeFromBuffer(new_status); + current_command_object.deserializeFromBuffer(current_command); + + if (current_status_object.getStatus().state() == bringauto::json::AutonomyState::DRIVE && + new_status_object.getStatus().state() == bringauto::json::AutonomyState::IN_STOP) { + current_command_object.removeFirstStop(); + } + return current_command_object.serializeToBuffer(generated_command); +#else auto currentAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(current_status); auto newAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(new_status); auto currentAutonomyCommand = protobuf::ProtobufHelper::parseAutonomyCommand(current_command); @@ -54,12 +81,6 @@ int AutonomyDevice::generate_command(struct buffer *generated_command, const str } } return protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(generated_command, currentAutonomyCommand); -#else - if (allocate(generated_command, current_command.size_in_bytes) != OK) { - return NOT_OK; - } - std::memcpy(generated_command->data, current_command.data, generated_command->size_in_bytes); - return OK; #endif } @@ -74,7 +95,25 @@ int AutonomyDevice::aggregate_status(struct buffer *aggregated_status, const str int AutonomyDevice::aggregate_error(struct buffer *error_message, const struct buffer current_error_message, const struct buffer status) { -#ifndef SKIP_PROTOBUF +#ifdef SKIP_PROTOBUF + bringauto::json::DeviceStatus status_object {}; + bringauto::json::DeviceError error_object {}; + status_object.deserializeFromBuffer(status); + error_object.deserializeFromBuffer(current_error_message); + + if (status_object.getStatus().state() == bringauto::json::AutonomyState::IN_STOP) { + auto nextStop = status_object.getStatus().nextstop(); + if (!error_object.getError().finishedstops().empty()) { + if (error_object.getError().finishedstops().back() != nextStop) { + error_object.addFinishedStop(nextStop); + } + } else { + error_object.addFinishedStop(nextStop); + } + } + + return error_object.serializeToBuffer(error_message); +#else auto autonomyError = protobuf::ProtobufHelper::parseAutonomyError(current_error_message); auto autonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(status); @@ -90,54 +129,51 @@ int AutonomyDevice::aggregate_error(struct buffer *error_message, const struct b } return protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(error_message, autonomyError); -#else - if (allocate(error_message, current_error_message.size_in_bytes) != OK) { - return NOT_OK; - } - std::memcpy(error_message->data, current_error_message.data, error_message->size_in_bytes); - return OK; #endif } int AutonomyDevice::generate_first_command(struct buffer *default_command) { -#ifndef SKIP_PROTOBUF +#ifdef SKIP_PROTOBUF + bringauto::json::DeviceCommand command_object {}; + command_object.setAction(bringauto::json::AutonomyAction::NO_ACTION); + return command_object.serializeToBuffer(default_command); +#else MissionModule::AutonomyCommand command = generateCommand(std::vector(), "", MissionModule::AutonomyCommand_Action_NO_ACTION); if (protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(default_command, command) != OK) { return NOT_OK; } return OK; -#else - std::string default_command_str = "{}"; - if ((allocate(default_command, default_command_str.length())) == OK) { - std::memcpy(default_command->data, default_command_str.c_str(), default_command->size_in_bytes); - return OK; - } - return NOT_OK; #endif } int AutonomyDevice::status_data_valid(const struct buffer status) { -#ifndef SKIP_PROTOBUF +#ifdef SKIP_PROTOBUF + bringauto::json::DeviceStatus status_object {}; + return status_object.deserializeFromBuffer(status); +#else try { protobuf::ProtobufHelper::parseAutonomyStatus(status); } catch (...) { return NOT_OK; } -#endif return OK; +#endif } int AutonomyDevice::command_data_valid(const struct buffer command) { -#ifndef SKIP_PROTOBUF +#ifdef SKIP_PROTOBUF + bringauto::json::DeviceCommand command_object {}; + return command_object.deserializeFromBuffer(command); +#else try { protobuf::ProtobufHelper::parseAutonomyCommand(command); } catch (...) { return NOT_OK; } -#endif return OK; +#endif } #ifndef SKIP_PROTOBUF diff --git a/source/bringauto/protobuf/ProtobufHelper.cpp b/source/bringauto/protobuf/ProtobufHelper.cpp index 38028eb..27dbc56 100644 --- a/source/bringauto/protobuf/ProtobufHelper.cpp +++ b/source/bringauto/protobuf/ProtobufHelper.cpp @@ -1,3 +1,4 @@ +#ifndef SKIP_PROTOBUF #include #include @@ -29,4 +30,4 @@ MissionModule::AutonomyError ProtobufHelper::parseAutonomyError(struct buffer er return autonomyError; } } - +#endif diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index d0a469d..ee7a788 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -149,7 +149,8 @@ int forward_status(const buffer device_status, const device_identification devic if(device.device_type == bamm::AUTONOMY_DEVICE_TYPE) { #ifdef SKIP_PROTOBUF - std::string device_status_str = device_status.getStringView(); + bringauto::fleet_protocol::cxx::BufferAsString device_status_bas(&device_status); + auto device_status_str = std::string(device_status_bas.getStringView()); #else std::string device_status_str; auto device_status_parsed = bringauto::protobuf::ProtobufHelper::parseAutonomyStatus(device_status); @@ -190,11 +191,16 @@ int forward_error_message(const buffer error_msg, const device_identification de auto con = static_cast (context); if(device.device_type == bamm::AUTONOMY_DEVICE_TYPE) { +#ifdef SKIP_PROTOBUF + bringauto::fleet_protocol::cxx::BufferAsString error_msg_bas(&error_msg); + auto error_msg_str = std::string(error_msg_bas.getStringView()); +#else std::string error_msg_str; auto error_msg_parsed = bringauto::protobuf::ProtobufHelper::parseAutonomyError(error_msg); auto protobuf_options = google::protobuf::util::JsonPrintOptions(); protobuf_options.always_print_primitive_fields = true; google::protobuf::util::MessageToJsonString(error_msg_parsed, &error_msg_str, protobuf_options); +#endif bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); From c4d135359f0e171195258362917f0eacc4578668 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Fri, 2 Aug 2024 15:37:31 +0200 Subject: [PATCH 03/23] dump json instead of to_string --- source/bringauto/json/SerializationUtils.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/source/bringauto/json/SerializationUtils.cpp b/source/bringauto/json/SerializationUtils.cpp index 1ceb7ca..157959f 100644 --- a/source/bringauto/json/SerializationUtils.cpp +++ b/source/bringauto/json/SerializationUtils.cpp @@ -1,14 +1,12 @@ #include #include -#include - namespace bringauto::json { using json = nlohmann::ordered_json; int SerializationUtils::json_to_buffer(json json, buffer *buffer) { - std::string tmp = to_string(json); + std::string tmp = json.dump(); if (allocate(buffer, tmp.size()) == NOT_OK) { return NOT_OK; From 7d9fe2b04f726622f851e1b908e503b2100ffcf5 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Mon, 5 Aug 2024 12:00:15 +0200 Subject: [PATCH 04/23] use protobuf only for message validation --- CMakeLists.txt | 26 +-- cmake/Dependencies.cmake | 8 +- include/bringauto/ba_json/JsonHelper.hpp | 24 +++ include/bringauto/json/DeviceCommand.hpp | 43 ----- include/bringauto/json/DeviceError.hpp | 38 ----- include/bringauto/json/DeviceStatus.hpp | 33 ---- include/bringauto/json/EnumUtils.hpp | 21 --- include/bringauto/json/SerializationUtils.hpp | 17 -- include/bringauto/json/Structures.hpp | 78 --------- .../mission_module/devices/AutonomyDevice.hpp | 7 - include/bringauto/protobuf/ProtobufHelper.hpp | 8 +- source/bringauto/ba_json/JsonHelper.cpp | 60 +++++++ source/bringauto/json/DeviceCommand.cpp | 76 --------- source/bringauto/json/DeviceError.cpp | 69 -------- source/bringauto/json/DeviceStatus.cpp | 76 --------- source/bringauto/json/EnumUtils.cpp | 60 ------- source/bringauto/json/SerializationUtils.cpp | 20 --- .../mission_module/devices/AutonomyDevice.cpp | 161 +++++------------- source/bringauto/protobuf/ProtobufHelper.cpp | 43 +++-- source/external_server_api.cpp | 36 +--- 20 files changed, 179 insertions(+), 725 deletions(-) create mode 100644 include/bringauto/ba_json/JsonHelper.hpp delete mode 100644 include/bringauto/json/DeviceCommand.hpp delete mode 100644 include/bringauto/json/DeviceError.hpp delete mode 100644 include/bringauto/json/DeviceStatus.hpp delete mode 100644 include/bringauto/json/EnumUtils.hpp delete mode 100644 include/bringauto/json/SerializationUtils.hpp delete mode 100644 include/bringauto/json/Structures.hpp create mode 100644 source/bringauto/ba_json/JsonHelper.cpp delete mode 100644 source/bringauto/json/DeviceCommand.cpp delete mode 100644 source/bringauto/json/DeviceError.cpp delete mode 100644 source/bringauto/json/DeviceStatus.cpp delete mode 100644 source/bringauto/json/EnumUtils.cpp delete mode 100644 source/bringauto/json/SerializationUtils.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 44027b0..9f17312 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,7 +18,6 @@ OPTION(BRINGAUTO_SYSTEM_DEP "System dependencies are used if switched to ON, pac OPTION(BRINGAUTO_GET_PACKAGES_ONLY "Only download packages for this project" OFF) OPTION(FLEET_PROTOCOL_BUILD_MODULE_GATEWAY "Build shared library for module gateway " ON) OPTION(FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER "Build shared library for external server " ON) -OPTION(SKIP_PROTOBUF "Handle commands and statuses only as JSON strings" OFF) IF (BRINGAUTO_PACKAGE) IF (NOT BRINGAUTO_INSTALL) @@ -55,12 +54,8 @@ IF (NOT BRINGAUTO_SYSTEM_DEP) ENDIF () ENDIF () -IF (SKIP_PROTOBUF) - ADD_COMPILE_DEFINITIONS(SKIP_PROTOBUF) - FIND_PACKAGE(nlohmann_json 3.10.5 REQUIRED) -ELSE () - FIND_PACKAGE(Protobuf 3.21.12 REQUIRED) -ENDIF () +FIND_PACKAGE(nlohmann_json 3.10.5 REQUIRED) +FIND_PACKAGE(Protobuf 3.21.12 REQUIRED) FIND_PACKAGE(fleet-protocol-interface 2.0.0 REQUIRED) FIND_PACKAGE(fleet-protocol-cxx-helpers-static 1.1.1 REQUIRED) @@ -78,17 +73,12 @@ CMDEF_ADD_LIBRARY( VERSION ${MISSION_MODULE_VERSION} ) -IF (SKIP_PROTOBUF) - # JSON mission payload - ADD_LIBRARY(message_handler_lib ALIAS nlohmann_json::nlohmann_json) -ELSE() - # Protobuf mission payload - SET(Protobuf_USE_STATIC_LIBS ON) - FILE(GLOB_RECURSE protobuf_mission_cpp_files "lib/protobuf-mission-module/*") - ADD_LIBRARY(message_handler_lib STATIC ${protobuf_mission_cpp_files}) - TARGET_INCLUDE_DIRECTORIES(message_handler_lib PUBLIC "lib/protobuf-mission-module/") - TARGET_LINK_LIBRARIES(message_handler_lib PUBLIC protobuf::libprotobuf) -ENDIF() +# Protobuf, JSON mission payload +SET(Protobuf_USE_STATIC_LIBS ON) +FILE(GLOB_RECURSE protobuf_mission_cpp_files "lib/protobuf-mission-module/*") +ADD_LIBRARY(message_handler_lib STATIC ${protobuf_mission_cpp_files}) +TARGET_INCLUDE_DIRECTORIES(message_handler_lib PUBLIC "lib/protobuf-mission-module/") +TARGET_LINK_LIBRARIES(message_handler_lib PUBLIC protobuf::libprotobuf nlohmann_json::nlohmann_json) FILE(GLOB_RECURSE HEADERS "include/*") diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index df80e6b..2a8a07d 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -3,12 +3,8 @@ SET(CMAKE_FIND_USE_CMAKE_SYSTEM_PATH FALSE) BA_PACKAGE_LIBRARY(fleet-protocol-interface v2.0.0 PLATFORM_STRING_MODE any_machine NO_DEBUG ON) BA_PACKAGE_LIBRARY(fleet-protocol-cxx-helpers-static v1.1.1) BA_PACKAGE_LIBRARY(zlib v1.2.11) - -IF (SKIP_PROTOBUF) - BA_PACKAGE_LIBRARY(nlohmann-json v3.10.5 PLATFORM_STRING_MODE any_machine NO_DEBUG ON) -ELSE () - BA_PACKAGE_LIBRARY(protobuf v4.21.12) -ENDIF () +BA_PACKAGE_LIBRARY(nlohmann-json v3.10.5 PLATFORM_STRING_MODE any_machine NO_DEBUG ON) +BA_PACKAGE_LIBRARY(protobuf v4.21.12) IF (FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER) BA_PACKAGE_LIBRARY(fleet-http-client-shared v1.3.0) diff --git a/include/bringauto/ba_json/JsonHelper.hpp b/include/bringauto/ba_json/JsonHelper.hpp new file mode 100644 index 0000000..c7a5c37 --- /dev/null +++ b/include/bringauto/ba_json/JsonHelper.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include + +#include + +namespace bringauto::ba_json { + +using json = nlohmann::ordered_json; + +class JsonHelper { +public: + static int bufferToJson(json* json, const buffer& buffer); + + static int jsonToBuffer(buffer* buffer, const json& json); + + static MissionModule::AutonomyStatus_State stringToAutonomyState(const std::string &state); + + static std::string autonomyStateToString(MissionModule::AutonomyStatus_State state); + +}; +} diff --git a/include/bringauto/json/DeviceCommand.hpp b/include/bringauto/json/DeviceCommand.hpp deleted file mode 100644 index 2c9a588..0000000 --- a/include/bringauto/json/DeviceCommand.hpp +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include - -namespace bringauto::json { - -class DeviceCommand { -public: - DeviceCommand(); - - /** - * @brief Serializes this object into given buffer using json. - */ - int serializeToBuffer(buffer *command_buffer); - - /** - * @brief Deserializes command in buffer (json string in data) and sets this object. - * @return OK - serialization successful, NOT_OK - serialization failed - */ - int deserializeFromBuffer(buffer command_buffer); - - /** - * @brief Returns the command of the device. - */ - AutonomyCommand getCommand() const { return command_; } - - /** - * @brief Sets the action of the device command. - */ - void setAction(AutonomyAction action) { command_.act = action; } - - /** - * @brief Remove the first top in the stops list. - */ - void removeFirstStop(); - -private: - AutonomyCommand command_ {}; - -}; - -} diff --git a/include/bringauto/json/DeviceError.hpp b/include/bringauto/json/DeviceError.hpp deleted file mode 100644 index 82208fc..0000000 --- a/include/bringauto/json/DeviceError.hpp +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include -#include - -namespace bringauto::json { - -class DeviceError { -public: - DeviceError(); - - /** - * @brief Serializes this object into given buffer using json. - */ - int serializeToBuffer(buffer *error_buffer); - - /** - * @brief Deserializes error in buffer (json string in data) and sets this object. - * @return OK - serialization successful, NOT_OK - serialization failed - */ - int deserializeFromBuffer(buffer error_buffer); - - /** - * @brief Returns the error of the device. - */ - AutonomyError getError() const { return error_; } - - /** - * @brief Add a stop to the finished stops list. - */ - void addFinishedStop(const Station &station); - -private: - AutonomyError error_ {}; - -}; - -} diff --git a/include/bringauto/json/DeviceStatus.hpp b/include/bringauto/json/DeviceStatus.hpp deleted file mode 100644 index 3d26a88..0000000 --- a/include/bringauto/json/DeviceStatus.hpp +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include -#include - -namespace bringauto::json { - -class DeviceStatus { -public: - DeviceStatus(); - - /** - * @brief Serializes this object into given buffer using json. - */ - int serializeToBuffer(buffer *status_buffer); - - /** - * @brief Deserializes status in buffer (json string in data) and sets this object. - * @return OK - serialization successful, NOT_OK - serialization failed - */ - int deserializeFromBuffer(buffer status_buffer); - - /** - * @brief Returns the status of the device. - */ - AutonomyStatus getStatus() const { return status_; } - -private: - AutonomyStatus status_ {}; - -}; - -} diff --git a/include/bringauto/json/EnumUtils.hpp b/include/bringauto/json/EnumUtils.hpp deleted file mode 100644 index 7b45089..0000000 --- a/include/bringauto/json/EnumUtils.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -namespace bringauto::json { - -class EnumUtils { -public: - EnumUtils() = delete; - - static AutonomyState stringToAutonomyState(const std::string &state); - - static std::string autonomyStateToString(const AutonomyState &state); - - static AutonomyAction stringToAutonomyAction(const std::string &action); - - static std::string autonomyActionToString(const AutonomyAction &action); - -}; - -} \ No newline at end of file diff --git a/include/bringauto/json/SerializationUtils.hpp b/include/bringauto/json/SerializationUtils.hpp deleted file mode 100644 index 3c7d0b2..0000000 --- a/include/bringauto/json/SerializationUtils.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -#include - -namespace bringauto::json { - -using json = nlohmann::ordered_json; - -class SerializationUtils { -public: - int static json_to_buffer(json json, buffer *buffer); - -}; - -} \ No newline at end of file diff --git a/include/bringauto/json/Structures.hpp b/include/bringauto/json/Structures.hpp deleted file mode 100644 index c002327..0000000 --- a/include/bringauto/json/Structures.hpp +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once - -#include -#include - -namespace bringauto::json { - -enum AutonomyState { - IDLE, DRIVE, IN_STOP, OBSTACLE, ERROR -}; - -enum AutonomyAction { - NO_ACTION, STOP, START -}; - -struct Position { - double alt; - double lat; - double lon; - - double altitude() { return alt; }; - double latitude() { return lat; }; - double longitude() { return lon; }; - - bool operator==(const Position &other) const { - return alt == other.alt && lat == other.lat && lon == other.lon; - }; -}; - -struct Station { - std::string nam; - Position pos; - - std::string name() { return nam; }; - Position position() { return pos; }; - - bool operator==(const Station &other) const { - return nam == other.nam && pos == other.pos; - }; -}; - -struct Telemetry { - double spe; - double fue; - Position pos; - - double speed() { return spe; }; - double fuel() { return fue; }; - Position position() { return pos; }; -}; - -struct AutonomyStatus { - Telemetry tel; - AutonomyState sta; - Station nex; - - Telemetry telemetry() { return tel; }; - AutonomyState state() { return sta; }; - Station nextstop() { return nex; }; -}; - -struct AutonomyCommand { - std::list sto; - std::string rou; - AutonomyAction act; - - std::list stops() { return sto; }; - std::string route() { return rou; }; - AutonomyAction action() { return act; }; -}; - -struct AutonomyError { - std::list fin; - - std::list finishedstops() { return fin; }; -}; - -} \ No newline at end of file diff --git a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp index ef29849..e360389 100644 --- a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp +++ b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp @@ -1,8 +1,6 @@ #pragma once -#ifndef SKIP_PROTOBUF #include -#endif #include #include @@ -93,11 +91,6 @@ class AutonomyDevice { */ static int command_data_valid(const struct buffer command); private: -#ifndef SKIP_PROTOBUF - static MissionModule::AutonomyCommand generateCommand(std::vector stops, std::string route, - MissionModule::AutonomyCommand::Action action); -#endif - /** * @brief Map of last sent status timestamps for each device type */ diff --git a/include/bringauto/protobuf/ProtobufHelper.hpp b/include/bringauto/protobuf/ProtobufHelper.hpp index ef9a3ad..b65a7ce 100644 --- a/include/bringauto/protobuf/ProtobufHelper.hpp +++ b/include/bringauto/protobuf/ProtobufHelper.hpp @@ -1,6 +1,5 @@ #pragma once -#ifndef SKIP_PROTOBUF #include #include @@ -9,13 +8,12 @@ class ProtobufHelper { public: static int serializeProtobufMessageToBuffer(struct buffer* message, const google::protobuf::Message &protobufMessage); - static MissionModule::AutonomyStatus parseAutonomyStatus(struct buffer status); + static int validateAutonomyStatus(std::string status); - static MissionModule::AutonomyCommand parseAutonomyCommand(struct buffer command); + static int validateAutonomyCommand(std::string command); - static MissionModule::AutonomyError parseAutonomyError(struct buffer errorMessage); + static int validateAutonomyError(std::string errorMessage); }; } -#endif diff --git a/source/bringauto/ba_json/JsonHelper.cpp b/source/bringauto/ba_json/JsonHelper.cpp new file mode 100644 index 0000000..fe4b2e2 --- /dev/null +++ b/source/bringauto/ba_json/JsonHelper.cpp @@ -0,0 +1,60 @@ +#include + +#include + + +namespace bringauto::ba_json { + +using json = nlohmann::ordered_json; + +int JsonHelper::bufferToJson(json* json, const buffer& buffer) { + char *buffer_data = static_cast (buffer.data); + try { + *json = json::parse(buffer_data, buffer_data + buffer.size_in_bytes); + } catch (json::parse_error &) { + return NOT_OK; + } + return OK; +} + +int JsonHelper::jsonToBuffer(buffer *buffer, const json& json) { + std::string tmp = json.dump(); + if (allocate(buffer, tmp.size()) == NOT_OK) { + return NOT_OK; + } + std::memcpy(buffer->data, tmp.c_str(), tmp.size()); + return OK; +} + +MissionModule::AutonomyStatus_State JsonHelper::stringToAutonomyState(const std::string &state) { + if (state == "IDLE") { + return MissionModule::AutonomyStatus_State::AutonomyStatus_State_IDLE; + } else if (state == "DRIVE") { + return MissionModule::AutonomyStatus_State::AutonomyStatus_State_DRIVE; + } else if (state == "IN_STOP") { + return MissionModule::AutonomyStatus_State::AutonomyStatus_State_IN_STOP; + } else if (state == "OBSTACLE") { + return MissionModule::AutonomyStatus_State::AutonomyStatus_State_OBSTACLE; + } else if (state == "ERROR") { + return MissionModule::AutonomyStatus_State::AutonomyStatus_State_ERROR; + } + return MissionModule::AutonomyStatus_State::AutonomyStatus_State_ERROR; +} + +std::string JsonHelper::autonomyStateToString(MissionModule::AutonomyStatus_State state) { + switch (state) { + case MissionModule::AutonomyStatus_State::AutonomyStatus_State_IDLE: + return "IDLE"; + case MissionModule::AutonomyStatus_State::AutonomyStatus_State_DRIVE: + return "DRIVE"; + case MissionModule::AutonomyStatus_State::AutonomyStatus_State_IN_STOP: + return "IN_STOP"; + case MissionModule::AutonomyStatus_State::AutonomyStatus_State_OBSTACLE: + return "OBSTACLE"; + case MissionModule::AutonomyStatus_State::AutonomyStatus_State_ERROR: + default: + return "ERROR"; + } +} + +} diff --git a/source/bringauto/json/DeviceCommand.cpp b/source/bringauto/json/DeviceCommand.cpp deleted file mode 100644 index 89501f0..0000000 --- a/source/bringauto/json/DeviceCommand.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include -#include -#include - -#include - -namespace bringauto::json { - -using json = nlohmann::ordered_json; - -DeviceCommand::DeviceCommand() { - -} - -int DeviceCommand::serializeToBuffer(buffer *command_buffer) { - json command_json; - command_json["route"] = command_.rou; - command_json["action"] = EnumUtils::autonomyActionToString(command_.act); - - int i = 0; - for(auto const& stop : command_.sto) { - command_json["stops"][i]["name"] = stop.nam; - command_json["stops"][i]["position"]["altitude"] = stop.pos.alt; - command_json["stops"][i]["position"]["latitude"] = stop.pos.lat; - command_json["stops"][i]["position"]["longitude"] = stop.pos.lon; - i++; - } - - if (SerializationUtils::json_to_buffer(command_json, command_buffer) == NOT_OK) { - return NOT_OK; - } - - return OK; -} - -int DeviceCommand::deserializeFromBuffer(buffer command_buffer) { - json command_json; - char *buffer_data = static_cast (command_buffer.data); - - try { - command_json = json::parse(buffer_data, buffer_data + command_buffer.size_in_bytes); - } catch (json::parse_error &) { - return NOT_OK; - } - - try { - for (int i = 0; i < command_json.at("stops").size(); i++) { - bringauto::json::Position position { - .alt = command_json.at("stops").at(i).at("position").at("altitude"), - .lat = command_json.at("stops").at(i).at("position").at("latitude"), - .lon = command_json.at("stops").at(i).at("position").at("longitude") - }; - bringauto::json::Station stop { - .nam = command_json.at("stops").at(i).at("name"), - .pos = position - }; - command_.sto.push_back(stop); - } - - command_.rou = command_json.at("route"); - command_.act = EnumUtils::stringToAutonomyAction(command_json.at("action")); - } catch (json::exception &) { - return NOT_OK; - } - - return OK; -} - -void DeviceCommand::removeFirstStop() { - if (!command_.sto.empty()) { - command_.sto.pop_front(); - } -} - -} \ No newline at end of file diff --git a/source/bringauto/json/DeviceError.cpp b/source/bringauto/json/DeviceError.cpp deleted file mode 100644 index 8a16437..0000000 --- a/source/bringauto/json/DeviceError.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include -#include -#include -#include - -#include - -namespace bringauto::json { - -using json = nlohmann::ordered_json; - -DeviceError::DeviceError() { - -} - -int DeviceError::serializeToBuffer(buffer *error_buffer) { - json error_json; - - int i = 0; - for(auto const& stop : error_.fin) { - error_json["finishedStops"][i]["name"] = stop.nam; - error_json["finishedStops"][i]["position"]["altitude"] = stop.pos.alt; - error_json["finishedStops"][i]["position"]["latitude"] = stop.pos.lat; - error_json["finishedStops"][i]["position"]["longitude"] = stop.pos.lon; - i++; - } - - if (SerializationUtils::json_to_buffer(error_json, error_buffer) == NOT_OK) { - return NOT_OK; - } - - return OK; -} - -int DeviceError::deserializeFromBuffer(buffer error_buffer) { - json error_json; - char *buffer_data = static_cast (error_buffer.data); - - try { - error_json = json::parse(buffer_data, buffer_data + error_buffer.size_in_bytes); - } catch (json::parse_error &) { - return NOT_OK; - } - - try { - for (int i = 0; i < error_json.at("finishedStops").size(); i++) { - bringauto::json::Position position { - .alt = error_json.at("finishedStops").at(i).at("position").at("altitude"), - .lat = error_json.at("finishedStops").at(i).at("position").at("latitude"), - .lon = error_json.at("finishedStops").at(i).at("position").at("longitude") - }; - bringauto::json::Station stop { - .nam = error_json.at("finishedStops").at(i).at("name"), - .pos = position - }; - error_.fin.push_back(stop); - } - } catch (json::exception &) { - return NOT_OK; - } - - return OK; -} - -void DeviceError::addFinishedStop(const Station &station) { - error_.fin.push_back(station); -} - -} diff --git a/source/bringauto/json/DeviceStatus.cpp b/source/bringauto/json/DeviceStatus.cpp deleted file mode 100644 index debf642..0000000 --- a/source/bringauto/json/DeviceStatus.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include -#include -#include - -#include - -namespace bringauto::json { - -using json = nlohmann::ordered_json; - -DeviceStatus::DeviceStatus() { - -} - -int DeviceStatus::serializeToBuffer(buffer *status_buffer) { - json status_json; - status_json["telemetry"]["fuel"] = status_.tel.fue; - status_json["telemetry"]["speed"] = status_.tel.spe; - status_json["telemetry"]["position"]["altitude"] = status_.tel.pos.alt; - status_json["telemetry"]["position"]["latitude"] = status_.tel.pos.lat; - status_json["telemetry"]["position"]["longitude"] = status_.tel.pos.lon; - status_json["nextStop"]["name"] = status_.nex.nam; - status_json["nextStop"]["position"]["altitude"] = status_.nex.pos.alt; - status_json["nextStop"]["position"]["latitude"] = status_.nex.pos.lat; - status_json["nextStop"]["position"]["longitude"] = status_.nex.pos.lon; - status_json["state"] = EnumUtils::autonomyStateToString(status_.sta); - - if (SerializationUtils::json_to_buffer(status_json, status_buffer) == NOT_OK) { - return NOT_OK; - } - - return OK; -} - -int DeviceStatus::deserializeFromBuffer(buffer status_buffer) { - json status_json; - char *buffer_data = static_cast (status_buffer.data); - - try { - status_json = json::parse(buffer_data, buffer_data + status_buffer.size_in_bytes); - } catch (json::parse_error &) { - return NOT_OK; - } - - try { - bringauto::json::Position position { - .alt = status_json.at("telemetry").at("position").at("altitude"), - .lat = status_json.at("telemetry").at("position").at("latitude"), - .lon = status_json.at("telemetry").at("position").at("longitude") - }; - bringauto::json::Telemetry telemetry { - .spe = status_json.at("telemetry").at("speed"), - .fue = status_json.at("telemetry").at("fuel"), - .pos = position - }; - bringauto::json::Position next_stop_position { - .alt = status_json.at("nextStop").at("position").at("altitude"), - .lat = status_json.at("nextStop").at("position").at("latitude"), - .lon = status_json.at("nextStop").at("position").at("longitude") - }; - bringauto::json::Station next_stop { - .nam = status_json.at("nextStop").at("name"), - .pos = next_stop_position - }; - status_.nex = next_stop; - status_.tel = telemetry; - status_.sta = EnumUtils::stringToAutonomyState(status_json.at("state")); - } catch (json::exception &) { - return NOT_OK; - } - - return OK; -} - -} \ No newline at end of file diff --git a/source/bringauto/json/EnumUtils.cpp b/source/bringauto/json/EnumUtils.cpp deleted file mode 100644 index d5b0dd1..0000000 --- a/source/bringauto/json/EnumUtils.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include - - -namespace bringauto::json { - -AutonomyState EnumUtils::stringToAutonomyState(const std::string &state) { - if (state == "IDLE") { - return AutonomyState::IDLE; - } else if (state == "DRIVE") { - return AutonomyState::DRIVE; - } else if (state == "IN_STOP") { - return AutonomyState::IN_STOP; - } else if (state == "OBSTACLE") { - return AutonomyState::OBSTACLE; - } else if (state == "ERROR") { - return AutonomyState::ERROR; - } - return AutonomyState::ERROR; -} - -std::string EnumUtils::autonomyStateToString(const AutonomyState &state) { - switch (state) { - case AutonomyState::IDLE: - return "IDLE"; - case AutonomyState::DRIVE: - return "DRIVE"; - case AutonomyState::IN_STOP: - return "IN_STOP"; - case AutonomyState::OBSTACLE: - return "OBSTACLE"; - case AutonomyState::ERROR: - return "ERROR"; - } - return "ERROR"; -} - -AutonomyAction EnumUtils::stringToAutonomyAction(const std::string &action) { - if (action == "NO_ACTION") { - return AutonomyAction::NO_ACTION; - } else if (action == "STOP") { - return AutonomyAction::STOP; - } else if (action == "START") { - return AutonomyAction::START; - } - return AutonomyAction::NO_ACTION; -} - -std::string EnumUtils::autonomyActionToString(const AutonomyAction &action) { - switch (action) { - case AutonomyAction::NO_ACTION: - return "NO_ACTION"; - case AutonomyAction::STOP: - return "STOP"; - case AutonomyAction::START: - return "START"; - } - return "NO_ACTION"; -} - -} \ No newline at end of file diff --git a/source/bringauto/json/SerializationUtils.cpp b/source/bringauto/json/SerializationUtils.cpp deleted file mode 100644 index 157959f..0000000 --- a/source/bringauto/json/SerializationUtils.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include -#include - -namespace bringauto::json { - -using json = nlohmann::ordered_json; - -int SerializationUtils::json_to_buffer(json json, buffer *buffer) { - std::string tmp = json.dump(); - - if (allocate(buffer, tmp.size()) == NOT_OK) { - return NOT_OK; - } - - std::memcpy(buffer->data, tmp.c_str(), tmp.size()); - - return OK; -} - -} \ No newline at end of file diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index 6935521..f91ce56 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -1,12 +1,5 @@ -#ifdef SKIP_PROTOBUF -#include -#include -#include -#else -#include #include -#include -#endif +#include #include #include @@ -19,30 +12,22 @@ namespace bringauto::modules::mission_module::devices { namespace bamm = bringauto::modules::mission_module; +using json = nlohmann::ordered_json; std::map AutonomyDevice::last_sent_status_timestamps_ {}; int AutonomyDevice::send_status_condition(const struct buffer current_status, const struct buffer new_status, unsigned int device_type) { -#ifdef SKIP_PROTOBUF - bringauto::json::DeviceStatus current_status_object {}; - bringauto::json::DeviceStatus new_status_object {}; - current_status_object.deserializeFromBuffer(current_status); - new_status_object.deserializeFromBuffer(new_status); - auto currentAutonomyStatus = current_status_object.getStatus(); - auto newAutonomyStatus = new_status_object.getStatus(); -#else - auto currentAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(current_status); - auto newAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(new_status); -#endif - - if (currentAutonomyStatus.state() != newAutonomyStatus.state() -#ifdef SKIP_PROTOBUF - || currentAutonomyStatus.nextstop() != newAutonomyStatus.nextstop()) { -#else - || !google::protobuf::util::MessageDifferencer::Equals(currentAutonomyStatus.nextstop(), newAutonomyStatus.nextstop())) { -#endif + json current_status_json {}; + json new_status_json {}; + if (ba_json::JsonHelper::bufferToJson(¤t_status_json, current_status) != OK || + ba_json::JsonHelper::bufferToJson(&new_status_json, new_status) != OK) { + return NOT_OK; + } + + if (current_status_json["state"] != new_status_json["state"] || + current_status_json["nextStop"] != new_status_json["nextStop"]) { return OK; - } else if (newAutonomyStatus.telemetry().speed() >= bamm::Constants::status_speed_threshold) { + } else if (new_status_json["telemetry"]["speed"] >= bamm::Constants::status_speed_threshold) { auto current_time = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()); if (last_sent_status_timestamps_[device_type] + bamm::Constants::status_sending_period < current_time) { @@ -55,33 +40,22 @@ int AutonomyDevice::send_status_condition(const struct buffer current_status, co int AutonomyDevice::generate_command(struct buffer *generated_command, const struct buffer new_status, const struct buffer current_status, const struct buffer current_command) { -#ifdef SKIP_PROTOBUF - bringauto::json::DeviceStatus current_status_object {}; - bringauto::json::DeviceStatus new_status_object {}; - bringauto::json::DeviceCommand current_command_object {}; - current_status_object.deserializeFromBuffer(current_status); - new_status_object.deserializeFromBuffer(new_status); - current_command_object.deserializeFromBuffer(current_command); - - if (current_status_object.getStatus().state() == bringauto::json::AutonomyState::DRIVE && - new_status_object.getStatus().state() == bringauto::json::AutonomyState::IN_STOP) { - current_command_object.removeFirstStop(); + json current_status_json {}; + json new_status_json {}; + json current_command_json {}; + if (ba_json::JsonHelper::bufferToJson(¤t_status_json, current_status) != OK || + ba_json::JsonHelper::bufferToJson(&new_status_json, new_status) != OK || + ba_json::JsonHelper::bufferToJson(¤t_command_json, current_command) != OK) { + return NOT_OK; } - return current_command_object.serializeToBuffer(generated_command); -#else - auto currentAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(current_status); - auto newAutonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(new_status); - auto currentAutonomyCommand = protobuf::ProtobufHelper::parseAutonomyCommand(current_command); - - if (currentAutonomyStatus.state() == MissionModule::AutonomyStatus_State_DRIVE && - newAutonomyStatus.state() == MissionModule::AutonomyStatus_State_IN_STOP) { - auto* stations = currentAutonomyCommand.mutable_stops(); - if (stations->size() > 0) { - stations->erase(stations->begin()); + + if (ba_json::JsonHelper::stringToAutonomyState(current_status_json["state"]) == MissionModule::AutonomyStatus_State_DRIVE && + ba_json::JsonHelper::stringToAutonomyState(new_status_json["state"]) == MissionModule::AutonomyStatus_State_IN_STOP) { + if (current_command_json["stops"].size() > 0) { + current_command_json["stops"].erase(current_command_json["stops"].begin()); } } - return protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(generated_command, currentAutonomyCommand); -#endif + return ba_json::JsonHelper::jsonToBuffer(generated_command, current_command_json); } int AutonomyDevice::aggregate_status(struct buffer *aggregated_status, const struct buffer current_status, @@ -95,98 +69,55 @@ int AutonomyDevice::aggregate_status(struct buffer *aggregated_status, const str int AutonomyDevice::aggregate_error(struct buffer *error_message, const struct buffer current_error_message, const struct buffer status) { -#ifdef SKIP_PROTOBUF - bringauto::json::DeviceStatus status_object {}; - bringauto::json::DeviceError error_object {}; - status_object.deserializeFromBuffer(status); - error_object.deserializeFromBuffer(current_error_message); - - if (status_object.getStatus().state() == bringauto::json::AutonomyState::IN_STOP) { - auto nextStop = status_object.getStatus().nextstop(); - if (!error_object.getError().finishedstops().empty()) { - if (error_object.getError().finishedstops().back() != nextStop) { - error_object.addFinishedStop(nextStop); - } - } else { - error_object.addFinishedStop(nextStop); - } + json status_json {}; + json error_json {}; + if (ba_json::JsonHelper::bufferToJson(&status_json, status) != OK || + ba_json::JsonHelper::bufferToJson(&error_json, current_error_message) != OK) { + return NOT_OK; } - return error_object.serializeToBuffer(error_message); -#else - auto autonomyError = protobuf::ProtobufHelper::parseAutonomyError(current_error_message); - auto autonomyStatus = protobuf::ProtobufHelper::parseAutonomyStatus(status); - - if (autonomyStatus.state() == MissionModule::AutonomyStatus_State_IN_STOP) { - const auto & finishedStops = autonomyError.finishedstops(); - if (!finishedStops.empty()) { - if (!google::protobuf::util::MessageDifferencer::Equals(finishedStops[finishedStops.size() -1], autonomyStatus.nextstop())) { - autonomyError.add_finishedstops()->CopyFrom(autonomyStatus.nextstop()); + if (status_json["state"] == ba_json::JsonHelper::autonomyStateToString(MissionModule::AutonomyStatus_State_IN_STOP)) { + if (error_json["finishedStops"].size() > 0) { + if (error_json["finishedStops"][error_json["finishedStops"].size() - 1] != status_json["nextStop"]) { + error_json["finishedStops"].push_back(status_json["nextStop"]); } } else { - autonomyError.add_finishedstops()->CopyFrom(autonomyStatus.nextstop()); + error_json["finishedStops"].push_back(status_json["nextStop"]); } } - return protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(error_message, autonomyError); -#endif + return ba_json::JsonHelper::jsonToBuffer(error_message, error_json); } int AutonomyDevice::generate_first_command(struct buffer *default_command) { -#ifdef SKIP_PROTOBUF - bringauto::json::DeviceCommand command_object {}; - command_object.setAction(bringauto::json::AutonomyAction::NO_ACTION); - return command_object.serializeToBuffer(default_command); -#else - MissionModule::AutonomyCommand command = generateCommand(std::vector(), "", MissionModule::AutonomyCommand_Action_NO_ACTION); + MissionModule::AutonomyCommand command {}; + command.set_action(MissionModule::AutonomyCommand_Action_NO_ACTION); if (protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(default_command, command) != OK) { return NOT_OK; } return OK; -#endif } int AutonomyDevice::status_data_valid(const struct buffer status) { -#ifdef SKIP_PROTOBUF - bringauto::json::DeviceStatus status_object {}; - return status_object.deserializeFromBuffer(status); -#else - try { - protobuf::ProtobufHelper::parseAutonomyStatus(status); + json status_json; + if (ba_json::JsonHelper::bufferToJson(&status_json, status) != OK) { + return NOT_OK; } - catch (...) { + if (protobuf::ProtobufHelper::validateAutonomyStatus(status_json.dump()) != OK) { return NOT_OK; } return OK; -#endif } int AutonomyDevice::command_data_valid(const struct buffer command) { -#ifdef SKIP_PROTOBUF - bringauto::json::DeviceCommand command_object {}; - return command_object.deserializeFromBuffer(command); -#else - try { - protobuf::ProtobufHelper::parseAutonomyCommand(command); + json command_json; + if (ba_json::JsonHelper::bufferToJson(&command_json, command) != OK) { + return NOT_OK; } - catch (...) { + if (protobuf::ProtobufHelper::validateAutonomyCommand(command_json.dump()) != OK) { return NOT_OK; } return OK; -#endif -} - -#ifndef SKIP_PROTOBUF -MissionModule::AutonomyCommand -AutonomyDevice::generateCommand(std::vector stops, std::string route, - MissionModule::AutonomyCommand::Action action) { - MissionModule::AutonomyCommand command; - auto stopsField = command.mutable_stops(); - stopsField->Add(stops.begin(), stops.end()); - command.set_route(route); - command.set_action(action); - return command; } -#endif } \ No newline at end of file diff --git a/source/bringauto/protobuf/ProtobufHelper.cpp b/source/bringauto/protobuf/ProtobufHelper.cpp index 27dbc56..4fa1899 100644 --- a/source/bringauto/protobuf/ProtobufHelper.cpp +++ b/source/bringauto/protobuf/ProtobufHelper.cpp @@ -1,8 +1,9 @@ -#ifndef SKIP_PROTOBUF #include #include +#include + namespace bringauto::protobuf { int ProtobufHelper::serializeProtobufMessageToBuffer(struct buffer* message, const google::protobuf::Message &protobufMessage) { if ((allocate(message, protobufMessage.ByteSizeLong())) == OK) { @@ -12,22 +13,36 @@ int ProtobufHelper::serializeProtobufMessageToBuffer(struct buffer* message, con return NOT_OK; } -MissionModule::AutonomyStatus ProtobufHelper::parseAutonomyStatus(struct buffer status) { - MissionModule::AutonomyStatus autonomyStatus; - autonomyStatus.ParseFromArray(status.data, status.size_in_bytes); - return autonomyStatus; +int ProtobufHelper::validateAutonomyStatus(std::string status) { + MissionModule::AutonomyStatus autonomyStatus {}; + const auto parse_status = google::protobuf::util::JsonStringToMessage( + status, &autonomyStatus + ); + if(!parse_status.ok()) { + return NOT_OK; + } + return OK; } -MissionModule::AutonomyCommand ProtobufHelper::parseAutonomyCommand(struct buffer command) { - MissionModule::AutonomyCommand autonomyCommand; - autonomyCommand.ParseFromArray(command.data, command.size_in_bytes); - return autonomyCommand; +int ProtobufHelper::validateAutonomyCommand(std::string command) { + MissionModule::AutonomyCommand autonomyCommand {}; + const auto parse_status = google::protobuf::util::JsonStringToMessage( + command, &autonomyCommand + ); + if(!parse_status.ok()) { + return NOT_OK; + } + return OK; } -MissionModule::AutonomyError ProtobufHelper::parseAutonomyError(struct buffer errorMessage) { - MissionModule::AutonomyError autonomyError; - autonomyError.ParseFromArray(errorMessage.data, errorMessage.size_in_bytes); - return autonomyError; +int ProtobufHelper::validateAutonomyError(std::string errorMessage) { + MissionModule::AutonomyError autonomyError {}; + const auto parse_status = google::protobuf::util::JsonStringToMessage( + errorMessage, &autonomyError + ); + if(!parse_status.ok()) { + return NOT_OK; + } + return OK; } } -#endif diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index ee7a788..54cfac2 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -6,10 +6,7 @@ #include #include #include -#ifndef SKIP_PROTOBUF #include -#include -#endif #include #include @@ -148,16 +145,11 @@ int forward_status(const buffer device_status, const device_identification devic auto con = static_cast (context); if(device.device_type == bamm::AUTONOMY_DEVICE_TYPE) { -#ifdef SKIP_PROTOBUF bringauto::fleet_protocol::cxx::BufferAsString device_status_bas(&device_status); auto device_status_str = std::string(device_status_bas.getStringView()); -#else - std::string device_status_str; - auto device_status_parsed = bringauto::protobuf::ProtobufHelper::parseAutonomyStatus(device_status); - auto protobuf_options = google::protobuf::util::JsonPrintOptions(); - protobuf_options.always_print_primitive_fields = true; - google::protobuf::util::MessageToJsonString(device_status_parsed, &device_status_str, protobuf_options); -#endif + if (bringauto::protobuf::ProtobufHelper::validateAutonomyStatus(device_status_str) != OK) { + return NOT_OK; + } bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); @@ -191,16 +183,11 @@ int forward_error_message(const buffer error_msg, const device_identification de auto con = static_cast (context); if(device.device_type == bamm::AUTONOMY_DEVICE_TYPE) { -#ifdef SKIP_PROTOBUF bringauto::fleet_protocol::cxx::BufferAsString error_msg_bas(&error_msg); auto error_msg_str = std::string(error_msg_bas.getStringView()); -#else - std::string error_msg_str; - auto error_msg_parsed = bringauto::protobuf::ProtobufHelper::parseAutonomyError(error_msg); - auto protobuf_options = google::protobuf::util::JsonPrintOptions(); - protobuf_options.always_print_primitive_fields = true; - google::protobuf::util::MessageToJsonString(error_msg_parsed, &error_msg_str, protobuf_options); -#endif + if (bringauto::protobuf::ProtobufHelper::validateAutonomyError(error_msg_str) != OK) { + return NOT_OK; + } bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); @@ -313,19 +300,10 @@ int wait_for_command(int timeout_time_in_ms, void *context) { } if(parse_commands) { -#ifdef SKIP_PROTOBUF std::string command_str = command->getPayload()->getData()->getJson().serialize(); -#else - MissionModule::AutonomyCommand proto_command {}; - const auto parse_status = google::protobuf::util::JsonStringToMessage( - command->getPayload()->getData()->getJson().serialize(), &proto_command - ); - if(!parse_status.ok()) { + if (bringauto::protobuf::ProtobufHelper::validateAutonomyCommand(command_str) != OK) { return NOT_OK; } - std::string command_str; - proto_command.SerializeToString(&command_str); -#endif con->command_vector.emplace_back(command_str, bringauto::fleet_protocol::cxx::DeviceID( received_device_id->getModuleId(), From 3c47f5f8c28c22f6f1f19d5e6b1a9fb5e29ad5bf Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Mon, 5 Aug 2024 13:12:32 +0200 Subject: [PATCH 05/23] print received command --- source/external_server_api.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index 54cfac2..6a737f7 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -301,6 +301,7 @@ int wait_for_command(int timeout_time_in_ms, void *context) { if(parse_commands) { std::string command_str = command->getPayload()->getData()->getJson().serialize(); + std::cerr << "Received command: " << command_str << std::endl; if (bringauto::protobuf::ProtobufHelper::validateAutonomyCommand(command_str) != OK) { return NOT_OK; } From 616f0d3825276dedba14cac132c7f474f9be2b13 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Mon, 5 Aug 2024 13:55:00 +0200 Subject: [PATCH 06/23] generate first command manually --- include/bringauto/ba_json/JsonHelper.hpp | 2 ++ source/bringauto/ba_json/JsonHelper.cpp | 12 ++++++++++++ .../mission_module/devices/AutonomyDevice.cpp | 8 +++++--- source/external_server_api.cpp | 1 - 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/include/bringauto/ba_json/JsonHelper.hpp b/include/bringauto/ba_json/JsonHelper.hpp index c7a5c37..d8c80bd 100644 --- a/include/bringauto/ba_json/JsonHelper.hpp +++ b/include/bringauto/ba_json/JsonHelper.hpp @@ -20,5 +20,7 @@ class JsonHelper { static std::string autonomyStateToString(MissionModule::AutonomyStatus_State state); + static std::string autonomyActionToString(MissionModule::AutonomyCommand_Action action); + }; } diff --git a/source/bringauto/ba_json/JsonHelper.cpp b/source/bringauto/ba_json/JsonHelper.cpp index fe4b2e2..0d50950 100644 --- a/source/bringauto/ba_json/JsonHelper.cpp +++ b/source/bringauto/ba_json/JsonHelper.cpp @@ -57,4 +57,16 @@ std::string JsonHelper::autonomyStateToString(MissionModule::AutonomyStatus_Stat } } +std::string JsonHelper::autonomyActionToString(MissionModule::AutonomyCommand_Action action) { + switch (action) { + case MissionModule::AutonomyCommand_Action::AutonomyCommand_Action_STOP: + return "STOP"; + case MissionModule::AutonomyCommand_Action::AutonomyCommand_Action_START: + return "DRIVE"; + case MissionModule::AutonomyCommand_Action::AutonomyCommand_Action_NO_ACTION: + default: + return "NO_ACTION"; + } +} + } diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index f91ce56..3432bce 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -90,9 +90,11 @@ int AutonomyDevice::aggregate_error(struct buffer *error_message, const struct b } int AutonomyDevice::generate_first_command(struct buffer *default_command) { - MissionModule::AutonomyCommand command {}; - command.set_action(MissionModule::AutonomyCommand_Action_NO_ACTION); - if (protobuf::ProtobufHelper::serializeProtobufMessageToBuffer(default_command, command) != OK) { + json command {}; + command["action"] = ba_json::JsonHelper::autonomyActionToString(MissionModule::AutonomyCommand_Action_NO_ACTION); + command["route"] = ""; + command["stops"] = json::array(); + if (ba_json::JsonHelper::jsonToBuffer(default_command, command) != OK) { return NOT_OK; } return OK; diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index 6a737f7..54cfac2 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -301,7 +301,6 @@ int wait_for_command(int timeout_time_in_ms, void *context) { if(parse_commands) { std::string command_str = command->getPayload()->getData()->getJson().serialize(); - std::cerr << "Received command: " << command_str << std::endl; if (bringauto::protobuf::ProtobufHelper::validateAutonomyCommand(command_str) != OK) { return NOT_OK; } From dc4e25b73d902cc7a8aa6e99651e846f313ba5f3 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Mon, 5 Aug 2024 15:13:33 +0200 Subject: [PATCH 07/23] use to_string on json --- source/bringauto/ba_json/JsonHelper.cpp | 2 +- .../modules/mission_module/devices/AutonomyDevice.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/source/bringauto/ba_json/JsonHelper.cpp b/source/bringauto/ba_json/JsonHelper.cpp index 0d50950..6a7b6db 100644 --- a/source/bringauto/ba_json/JsonHelper.cpp +++ b/source/bringauto/ba_json/JsonHelper.cpp @@ -18,7 +18,7 @@ int JsonHelper::bufferToJson(json* json, const buffer& buffer) { } int JsonHelper::jsonToBuffer(buffer *buffer, const json& json) { - std::string tmp = json.dump(); + std::string tmp = nlohmann::to_string(json); if (allocate(buffer, tmp.size()) == NOT_OK) { return NOT_OK; } diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index 3432bce..9547b23 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -105,7 +105,7 @@ int AutonomyDevice::status_data_valid(const struct buffer status) { if (ba_json::JsonHelper::bufferToJson(&status_json, status) != OK) { return NOT_OK; } - if (protobuf::ProtobufHelper::validateAutonomyStatus(status_json.dump()) != OK) { + if (protobuf::ProtobufHelper::validateAutonomyStatus(nlohmann::to_string(status_json)) != OK) { return NOT_OK; } return OK; @@ -116,7 +116,7 @@ int AutonomyDevice::command_data_valid(const struct buffer command) { if (ba_json::JsonHelper::bufferToJson(&command_json, command) != OK) { return NOT_OK; } - if (protobuf::ProtobufHelper::validateAutonomyCommand(command_json.dump()) != OK) { + if (protobuf::ProtobufHelper::validateAutonomyCommand(nlohmann::to_string(command_json)) != OK) { return NOT_OK; } return OK; From 36fc047c1f66bdf1f73961473465be531ae9bece Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 7 Aug 2024 14:26:10 +0200 Subject: [PATCH 08/23] code improvements --- .../modules/mission_module/Constants.hpp | 2 +- .../modules/mission_module/Context.hpp | 5 +- .../modules/mission_module/MissionModule.hpp | 4 +- .../mission_module/devices/AutonomyDevice.hpp | 1 - include/bringauto/protobuf/ProtobufHelper.hpp | 6 +- source/bringauto/ba_json/JsonHelper.cpp | 8 +- .../mission_module/devices/AutonomyDevice.cpp | 11 +- source/bringauto/protobuf/ProtobufHelper.cpp | 10 +- source/external_server_api.cpp | 116 +++++++++--------- 9 files changed, 80 insertions(+), 83 deletions(-) diff --git a/include/bringauto/modules/mission_module/Constants.hpp b/include/bringauto/modules/mission_module/Constants.hpp index 24f2e10..715ee02 100644 --- a/include/bringauto/modules/mission_module/Constants.hpp +++ b/include/bringauto/modules/mission_module/Constants.hpp @@ -18,7 +18,7 @@ class Constants { /** * @brief Minimum time between two status messages being sent when speed is above the threshold */ - static constexpr std::chrono::milliseconds status_sending_period = std::chrono::milliseconds(2900); + static constexpr auto status_sending_period = std::chrono::milliseconds(2900); }; } \ No newline at end of file diff --git a/include/bringauto/modules/mission_module/Context.hpp b/include/bringauto/modules/mission_module/Context.hpp index 394974b..525429b 100644 --- a/include/bringauto/modules/mission_module/Context.hpp +++ b/include/bringauto/modules/mission_module/Context.hpp @@ -5,14 +5,13 @@ #include #include -#include namespace bringauto::modules::mission_module { struct Context { - std::shared_ptr fleet_api_client; + std::shared_ptr fleet_api_client; std::vector devices; - std::vector> command_vector; + std::vector> command_vector; std::mutex mutex; std::condition_variable con_variable; long last_command_timestamp; diff --git a/include/bringauto/modules/mission_module/MissionModule.hpp b/include/bringauto/modules/mission_module/MissionModule.hpp index 48fc49f..3077272 100644 --- a/include/bringauto/modules/mission_module/MissionModule.hpp +++ b/include/bringauto/modules/mission_module/MissionModule.hpp @@ -2,7 +2,7 @@ namespace bringauto::modules::mission_module { - static const int MISSION_MODULE_NUMBER = 1; + static constexpr int MISSION_MODULE_NUMBER = 1; - static const int AUTONOMY_DEVICE_TYPE = 1; + static constexpr int AUTONOMY_DEVICE_TYPE = 1; } \ No newline at end of file diff --git a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp index e360389..79dd0f4 100644 --- a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp +++ b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp @@ -1,6 +1,5 @@ #pragma once -#include #include #include diff --git a/include/bringauto/protobuf/ProtobufHelper.hpp b/include/bringauto/protobuf/ProtobufHelper.hpp index b65a7ce..4fca370 100644 --- a/include/bringauto/protobuf/ProtobufHelper.hpp +++ b/include/bringauto/protobuf/ProtobufHelper.hpp @@ -8,11 +8,11 @@ class ProtobufHelper { public: static int serializeProtobufMessageToBuffer(struct buffer* message, const google::protobuf::Message &protobufMessage); - static int validateAutonomyStatus(std::string status); + static int validateAutonomyStatus(const std::string &status); - static int validateAutonomyCommand(std::string command); + static int validateAutonomyCommand(const std::string &command); - static int validateAutonomyError(std::string errorMessage); + static int validateAutonomyError(const std::string &errorMessage); }; diff --git a/source/bringauto/ba_json/JsonHelper.cpp b/source/bringauto/ba_json/JsonHelper.cpp index 6a7b6db..5cd1746 100644 --- a/source/bringauto/ba_json/JsonHelper.cpp +++ b/source/bringauto/ba_json/JsonHelper.cpp @@ -8,7 +8,7 @@ namespace bringauto::ba_json { using json = nlohmann::ordered_json; int JsonHelper::bufferToJson(json* json, const buffer& buffer) { - char *buffer_data = static_cast (buffer.data); + const auto buffer_data = static_cast (buffer.data); try { *json = json::parse(buffer_data, buffer_data + buffer.size_in_bytes); } catch (json::parse_error &) { @@ -18,7 +18,7 @@ int JsonHelper::bufferToJson(json* json, const buffer& buffer) { } int JsonHelper::jsonToBuffer(buffer *buffer, const json& json) { - std::string tmp = nlohmann::to_string(json); + const std::string tmp = nlohmann::to_string(json); if (allocate(buffer, tmp.size()) == NOT_OK) { return NOT_OK; } @@ -41,7 +41,7 @@ MissionModule::AutonomyStatus_State JsonHelper::stringToAutonomyState(const std: return MissionModule::AutonomyStatus_State::AutonomyStatus_State_ERROR; } -std::string JsonHelper::autonomyStateToString(MissionModule::AutonomyStatus_State state) { +std::string JsonHelper::autonomyStateToString(const MissionModule::AutonomyStatus_State state) { switch (state) { case MissionModule::AutonomyStatus_State::AutonomyStatus_State_IDLE: return "IDLE"; @@ -57,7 +57,7 @@ std::string JsonHelper::autonomyStateToString(MissionModule::AutonomyStatus_Stat } } -std::string JsonHelper::autonomyActionToString(MissionModule::AutonomyCommand_Action action) { +std::string JsonHelper::autonomyActionToString(const MissionModule::AutonomyCommand_Action action) { switch (action) { case MissionModule::AutonomyCommand_Action::AutonomyCommand_Action_STOP: return "STOP"; diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index 9547b23..80abd1f 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -11,7 +11,6 @@ namespace bringauto::modules::mission_module::devices { -namespace bamm = bringauto::modules::mission_module; using json = nlohmann::ordered_json; std::map AutonomyDevice::last_sent_status_timestamps_ {}; @@ -27,10 +26,12 @@ int AutonomyDevice::send_status_condition(const struct buffer current_status, co if (current_status_json["state"] != new_status_json["state"] || current_status_json["nextStop"] != new_status_json["nextStop"]) { return OK; - } else if (new_status_json["telemetry"]["speed"] >= bamm::Constants::status_speed_threshold) { + } + + if (new_status_json["telemetry"]["speed"] >= Constants::status_speed_threshold) { auto current_time = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()); - if (last_sent_status_timestamps_[device_type] + bamm::Constants::status_sending_period < current_time) { + if (last_sent_status_timestamps_[device_type] + Constants::status_sending_period < current_time) { last_sent_status_timestamps_[device_type] = current_time; return OK; } @@ -51,7 +52,7 @@ int AutonomyDevice::generate_command(struct buffer *generated_command, const str if (ba_json::JsonHelper::stringToAutonomyState(current_status_json["state"]) == MissionModule::AutonomyStatus_State_DRIVE && ba_json::JsonHelper::stringToAutonomyState(new_status_json["state"]) == MissionModule::AutonomyStatus_State_IN_STOP) { - if (current_command_json["stops"].size() > 0) { + if (!current_command_json["stops"].empty()) { current_command_json["stops"].erase(current_command_json["stops"].begin()); } } @@ -77,7 +78,7 @@ int AutonomyDevice::aggregate_error(struct buffer *error_message, const struct b } if (status_json["state"] == ba_json::JsonHelper::autonomyStateToString(MissionModule::AutonomyStatus_State_IN_STOP)) { - if (error_json["finishedStops"].size() > 0) { + if (!error_json["finishedStops"].empty()) { if (error_json["finishedStops"][error_json["finishedStops"].size() - 1] != status_json["nextStop"]) { error_json["finishedStops"].push_back(status_json["nextStop"]); } diff --git a/source/bringauto/protobuf/ProtobufHelper.cpp b/source/bringauto/protobuf/ProtobufHelper.cpp index 4fa1899..52ac535 100644 --- a/source/bringauto/protobuf/ProtobufHelper.cpp +++ b/source/bringauto/protobuf/ProtobufHelper.cpp @@ -6,14 +6,14 @@ namespace bringauto::protobuf { int ProtobufHelper::serializeProtobufMessageToBuffer(struct buffer* message, const google::protobuf::Message &protobufMessage) { - if ((allocate(message, protobufMessage.ByteSizeLong())) == OK) { - protobufMessage.SerializeToArray(message->data, (int)message->size_in_bytes); + if (allocate(message, protobufMessage.ByteSizeLong()) == OK) { + protobufMessage.SerializeToArray(message->data, static_cast(message->size_in_bytes)); return OK; } return NOT_OK; } -int ProtobufHelper::validateAutonomyStatus(std::string status) { +int ProtobufHelper::validateAutonomyStatus(const std::string &status) { MissionModule::AutonomyStatus autonomyStatus {}; const auto parse_status = google::protobuf::util::JsonStringToMessage( status, &autonomyStatus @@ -24,7 +24,7 @@ int ProtobufHelper::validateAutonomyStatus(std::string status) { return OK; } -int ProtobufHelper::validateAutonomyCommand(std::string command) { +int ProtobufHelper::validateAutonomyCommand(const std::string &command) { MissionModule::AutonomyCommand autonomyCommand {}; const auto parse_status = google::protobuf::util::JsonStringToMessage( command, &autonomyCommand @@ -35,7 +35,7 @@ int ProtobufHelper::validateAutonomyCommand(std::string command) { return OK; } -int ProtobufHelper::validateAutonomyError(std::string errorMessage) { +int ProtobufHelper::validateAutonomyError(const std::string &errorMessage) { MissionModule::AutonomyError autonomyError {}; const auto parse_status = google::protobuf::util::JsonStringToMessage( errorMessage, &autonomyError diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index 54cfac2..5f1a1f1 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -10,8 +10,6 @@ #include #include -#include -#include #include @@ -19,7 +17,7 @@ namespace bamm = bringauto::modules::mission_module; void *init(const config config_data) { auto *context = new bamm::Context {}; - bringauto::fleet_protocol::cxx::KeyValueConfig config(config_data); + const bringauto::fleet_protocol::cxx::KeyValueConfig config(config_data); std::string api_url; std::string api_key; std::string company_name; @@ -29,75 +27,75 @@ void *init(const config config_data) { int delay_after_threshold_reached_ms; int retry_requests_delay_ms; - for (auto i = config.cbegin(); i != config.cend(); i++) { - if (i->first == "api_url") { - if (!std::regex_match(i->second, std::regex(R"(^(http|https)://([\w-]+\.)?+[\w-]+(:[0-9]+)?(/[\w-]*)?+$)"))) { + for (const auto & i : config) { + if (i.first == "api_url") { + if (!std::regex_match(i.second, std::regex(R"(^(http|https)://([\w-]+\.)?+[\w-]+(:[0-9]+)?(/[\w-]*)?+$)"))) { delete context; return nullptr; } - api_url = i->second; + api_url = i.second; } - else if (i->first == "api_key") { - if (i->second.empty()) { + else if (i.first == "api_key") { + if (i.second.empty()) { delete context; return nullptr; } - api_key = i->second; + api_key = i.second; } - else if (i->first == "company_name") { - if (!std::regex_match(i->second, std::regex("^[a-z0-9_]*$")) || i->second.empty()) { + else if (i.first == "company_name") { + if (!std::regex_match(i.second, std::regex("^[a-z0-9_]*$")) || i.second.empty()) { delete context; return nullptr; } - company_name = i->second; + company_name = i.second; } - else if (i->first == "car_name") { - if (!std::regex_match(i->second, std::regex("^[a-z0-9_]*$")) || i->second.empty()) { + else if (i.first == "car_name") { + if (!std::regex_match(i.second, std::regex("^[a-z0-9_]*$")) || i.second.empty()) { delete context; return nullptr; } - car_name = i->second; + car_name = i.second; } - else if (i->first == "max_requests_threshold_count") { + else if (i.first == "max_requests_threshold_count") { try { - max_requests_threshold_count = std::stoi(i->second); - if (max_requests_threshold_count < 0 || i->second.empty()) { + max_requests_threshold_count = std::stoi(i.second); + if (max_requests_threshold_count < 0 || i.second.empty()) { throw std::exception(); } - } catch (std::exception& e) { + } catch (...) { delete context; return nullptr; } } - else if (i->first == "max_requests_threshold_period_ms") { + else if (i.first == "max_requests_threshold_period_ms") { try { - max_requests_threshold_period_ms = std::stoi(i->second); - if (max_requests_threshold_period_ms < 0 || i->second.empty()) { + max_requests_threshold_period_ms = std::stoi(i.second); + if (max_requests_threshold_period_ms < 0 || i.second.empty()) { throw std::exception(); } - } catch (std::exception& e) { + } catch (...) { delete context; return nullptr; } } - else if (i->first == "delay_after_threshold_reached_ms") { + else if (i.first == "delay_after_threshold_reached_ms") { try { - delay_after_threshold_reached_ms = std::stoi(i->second); - if (delay_after_threshold_reached_ms < 0 || i->second.empty()) { + delay_after_threshold_reached_ms = std::stoi(i.second); + if (delay_after_threshold_reached_ms < 0 || i.second.empty()) { throw std::exception(); } - } catch (std::exception& e) { + } catch (...) { delete context; return nullptr; } } - else if (i->first == "retry_requests_delay_ms") { + else if (i.first == "retry_requests_delay_ms") { try { - retry_requests_delay_ms = std::stoi(i->second); - if (retry_requests_delay_ms < 0 || i->second.empty()) { + retry_requests_delay_ms = std::stoi(i.second); + if (retry_requests_delay_ms < 0 || i.second.empty()) { throw std::exception(); } - } catch (std::exception& e) { + } catch (...) { delete context; return nullptr; } @@ -130,7 +128,7 @@ int destroy(void **context) { if(*context == nullptr){ return NOT_OK; } - auto con = reinterpret_cast (context); + const auto con = reinterpret_cast (context); delete *con; *con = nullptr; @@ -142,17 +140,17 @@ int forward_status(const buffer device_status, const device_identification devic return CONTEXT_INCORRECT; } - auto con = static_cast (context); + const auto con = static_cast (context); if(device.device_type == bamm::AUTONOMY_DEVICE_TYPE) { - bringauto::fleet_protocol::cxx::BufferAsString device_status_bas(&device_status); - auto device_status_str = std::string(device_status_bas.getStringView()); + const bringauto::fleet_protocol::cxx::BufferAsString device_status_bas(&device_status); + const auto device_status_str = std::string(device_status_bas.getStringView()); if (bringauto::protobuf::ProtobufHelper::validateAutonomyStatus(device_status_str) != OK) { return NOT_OK; } - bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); - bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); + const bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); + const bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); con->fleet_api_client->setDeviceIdentification( bringauto::fleet_protocol::cxx::DeviceID( device.module, @@ -165,7 +163,7 @@ int forward_status(const buffer device_status, const device_identification devic try { con->fleet_api_client->sendStatus(device_status_str); - } catch (std::exception& e) { + } catch (...) { return NOT_OK; } @@ -180,17 +178,17 @@ int forward_error_message(const buffer error_msg, const device_identification de return CONTEXT_INCORRECT; } - auto con = static_cast (context); + const auto con = static_cast (context); if(device.device_type == bamm::AUTONOMY_DEVICE_TYPE) { - bringauto::fleet_protocol::cxx::BufferAsString error_msg_bas(&error_msg); - auto error_msg_str = std::string(error_msg_bas.getStringView()); + const bringauto::fleet_protocol::cxx::BufferAsString error_msg_bas(&error_msg); + const auto error_msg_str = std::string(error_msg_bas.getStringView()); if (bringauto::protobuf::ProtobufHelper::validateAutonomyError(error_msg_str) != OK) { return NOT_OK; } - bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); - bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); + const bringauto::fleet_protocol::cxx::BufferAsString device_role(&device.device_role); + const bringauto::fleet_protocol::cxx::BufferAsString device_name(&device.device_name); con->fleet_api_client->setDeviceIdentification( bringauto::fleet_protocol::cxx::DeviceID( device.module, @@ -205,7 +203,7 @@ int forward_error_message(const buffer error_msg, const device_identification de con->fleet_api_client->sendStatus( error_msg_str, bringauto::fleet_protocol::http_client::FleetApiClient::StatusType::STATUS_ERROR ); - } catch (std::exception& e) { + } catch (...) { return NOT_OK; } @@ -220,7 +218,7 @@ int device_disconnected(const int disconnect_type, const device_identification d return CONTEXT_INCORRECT; } - auto con = static_cast (context); + const auto con = static_cast (context); const std::string_view device_device_role(static_cast (device.device_role.data), device.device_role.size_in_bytes); const std::string_view device_device_name(static_cast (device.device_name.data), device.device_name.size_in_bytes); @@ -248,13 +246,13 @@ int device_connected(const device_identification device, void *context) { return CONTEXT_INCORRECT; } - auto con = static_cast (context); + const auto con = static_cast (context); - device_identification new_device; - - new_device.module = device.module; - new_device.device_type = device.device_type; - new_device.priority = device.priority; + device_identification new_device { + .module = device.module, + .device_type = device.device_type, + .priority = device.priority + }; if(allocate(&new_device.device_role, device.device_role.size_in_bytes) != OK) { return NOT_OK; @@ -275,10 +273,10 @@ int wait_for_command(int timeout_time_in_ms, void *context) { return CONTEXT_INCORRECT; } - auto con = static_cast (context); + const auto con = static_cast (context); std::unique_lock lock(con->mutex); std::vector> commands; - bool parse_commands = con->last_command_timestamp != 0; + const bool parse_commands = con->last_command_timestamp != 0; try { commands = con->fleet_api_client->getCommands(con->last_command_timestamp + 1, true); @@ -287,12 +285,12 @@ int wait_for_command(int timeout_time_in_ms, void *context) { } bool received_no_commands = true; - for(auto command : commands) { + for(const auto &command : commands) { if(command->getTimestamp() > con->last_command_timestamp) { con->last_command_timestamp = command->getTimestamp(); } - auto received_device_id = command->getDeviceId(); + const auto received_device_id = command->getDeviceId(); if(received_device_id->getModuleId() == bamm::MISSION_MODULE_NUMBER) { received_no_commands = false; } else { @@ -330,12 +328,12 @@ int pop_command(buffer* command, device_identification* device, void *context) { return CONTEXT_INCORRECT; } - auto con = static_cast (context); - auto command_object = std::get<0>(con->command_vector.back()); + const auto con = static_cast (context); + const auto command_object = std::get<0>(con->command_vector.back()); bringauto::fleet_protocol::cxx::StringAsBuffer::createBufferAndCopyData(command, command_object); - auto& device_id = std::get<1>(con->command_vector.back()); + const auto& device_id = std::get<1>(con->command_vector.back()); device->module = device_id.getDeviceId().module; device->device_type = device_id.getDeviceId().device_type; From 28b3eb02c07d07ef20076612278f308c761bdb1c Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 7 Aug 2024 14:37:08 +0200 Subject: [PATCH 09/23] config is not iterable --- source/external_server_api.cpp | 50 +++++++++++++++++----------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index 5f1a1f1..21592b5 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -27,39 +27,39 @@ void *init(const config config_data) { int delay_after_threshold_reached_ms; int retry_requests_delay_ms; - for (const auto & i : config) { - if (i.first == "api_url") { - if (!std::regex_match(i.second, std::regex(R"(^(http|https)://([\w-]+\.)?+[\w-]+(:[0-9]+)?(/[\w-]*)?+$)"))) { + for (auto i = config.cbegin(); i != config.cend(); ++i) { + if (i->first == "api_url") { + if (!std::regex_match(i->second, std::regex(R"(^(http|https)://([\w-]+\.)?+[\w-]+(:[0-9]+)?(/[\w-]*)?+$)"))) { delete context; return nullptr; } - api_url = i.second; + api_url = i->second; } - else if (i.first == "api_key") { - if (i.second.empty()) { + else if (i->first == "api_key") { + if (i->second.empty()) { delete context; return nullptr; } - api_key = i.second; + api_key = i->second; } - else if (i.first == "company_name") { - if (!std::regex_match(i.second, std::regex("^[a-z0-9_]*$")) || i.second.empty()) { + else if (i->first == "company_name") { + if (!std::regex_match(i->second, std::regex("^[a-z0-9_]*$")) || i->second.empty()) { delete context; return nullptr; } - company_name = i.second; + company_name = i->second; } - else if (i.first == "car_name") { - if (!std::regex_match(i.second, std::regex("^[a-z0-9_]*$")) || i.second.empty()) { + else if (i->first == "car_name") { + if (!std::regex_match(i->second, std::regex("^[a-z0-9_]*$")) || i->second.empty()) { delete context; return nullptr; } - car_name = i.second; + car_name = i->second; } - else if (i.first == "max_requests_threshold_count") { + else if (i->first == "max_requests_threshold_count") { try { - max_requests_threshold_count = std::stoi(i.second); - if (max_requests_threshold_count < 0 || i.second.empty()) { + max_requests_threshold_count = std::stoi(i->second); + if (max_requests_threshold_count < 0 || i->second.empty()) { throw std::exception(); } } catch (...) { @@ -67,10 +67,10 @@ void *init(const config config_data) { return nullptr; } } - else if (i.first == "max_requests_threshold_period_ms") { + else if (i->first == "max_requests_threshold_period_ms") { try { - max_requests_threshold_period_ms = std::stoi(i.second); - if (max_requests_threshold_period_ms < 0 || i.second.empty()) { + max_requests_threshold_period_ms = std::stoi(i->second); + if (max_requests_threshold_period_ms < 0 || i->second.empty()) { throw std::exception(); } } catch (...) { @@ -78,10 +78,10 @@ void *init(const config config_data) { return nullptr; } } - else if (i.first == "delay_after_threshold_reached_ms") { + else if (i->first == "delay_after_threshold_reached_ms") { try { - delay_after_threshold_reached_ms = std::stoi(i.second); - if (delay_after_threshold_reached_ms < 0 || i.second.empty()) { + delay_after_threshold_reached_ms = std::stoi(i->second); + if (delay_after_threshold_reached_ms < 0 || i->second.empty()) { throw std::exception(); } } catch (...) { @@ -89,10 +89,10 @@ void *init(const config config_data) { return nullptr; } } - else if (i.first == "retry_requests_delay_ms") { + else if (i->first == "retry_requests_delay_ms") { try { - retry_requests_delay_ms = std::stoi(i.second); - if (retry_requests_delay_ms < 0 || i.second.empty()) { + retry_requests_delay_ms = std::stoi(i->second); + if (retry_requests_delay_ms < 0 || i->second.empty()) { throw std::exception(); } } catch (...) { From d452390f48187c0c38f38f18d563c3dfab0795de Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Thu, 8 Aug 2024 10:07:40 +0200 Subject: [PATCH 10/23] add debug prints to command validation --- .../modules/mission_module/devices/AutonomyDevice.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index 80abd1f..35c946b 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -102,7 +102,7 @@ int AutonomyDevice::generate_first_command(struct buffer *default_command) { } int AutonomyDevice::status_data_valid(const struct buffer status) { - json status_json; + json status_json {}; if (ba_json::JsonHelper::bufferToJson(&status_json, status) != OK) { return NOT_OK; } @@ -113,11 +113,14 @@ int AutonomyDevice::status_data_valid(const struct buffer status) { } int AutonomyDevice::command_data_valid(const struct buffer command) { - json command_json; + json command_json {}; if (ba_json::JsonHelper::bufferToJson(&command_json, command) != OK) { + std::cerr << "Failed to parse command json" << std::endl; return NOT_OK; } + std::cerr << command_json.dump() << std::endl; if (protobuf::ProtobufHelper::validateAutonomyCommand(nlohmann::to_string(command_json)) != OK) { + std::cerr << "Failed to validate command" << std::endl; return NOT_OK; } return OK; From ef57529a5e83f9f4b80b5f02859627c9d9a46eaf Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Thu, 8 Aug 2024 10:59:43 +0200 Subject: [PATCH 11/23] use .at when addressing json keys --- include/bringauto/ba_json/JsonHelper.hpp | 2 +- source/bringauto/ba_json/JsonHelper.cpp | 4 +- .../mission_module/devices/AutonomyDevice.cpp | 45 +++++++++---------- 3 files changed, 24 insertions(+), 27 deletions(-) diff --git a/include/bringauto/ba_json/JsonHelper.hpp b/include/bringauto/ba_json/JsonHelper.hpp index d8c80bd..38b335a 100644 --- a/include/bringauto/ba_json/JsonHelper.hpp +++ b/include/bringauto/ba_json/JsonHelper.hpp @@ -12,7 +12,7 @@ using json = nlohmann::ordered_json; class JsonHelper { public: - static int bufferToJson(json* json, const buffer& buffer); + static int bufferToJson(json& json, const buffer& buffer); static int jsonToBuffer(buffer* buffer, const json& json); diff --git a/source/bringauto/ba_json/JsonHelper.cpp b/source/bringauto/ba_json/JsonHelper.cpp index 5cd1746..999c7e3 100644 --- a/source/bringauto/ba_json/JsonHelper.cpp +++ b/source/bringauto/ba_json/JsonHelper.cpp @@ -7,10 +7,10 @@ namespace bringauto::ba_json { using json = nlohmann::ordered_json; -int JsonHelper::bufferToJson(json* json, const buffer& buffer) { +int JsonHelper::bufferToJson(json& json, const buffer& buffer) { const auto buffer_data = static_cast (buffer.data); try { - *json = json::parse(buffer_data, buffer_data + buffer.size_in_bytes); + json = json::parse(buffer_data, buffer_data + buffer.size_in_bytes); } catch (json::parse_error &) { return NOT_OK; } diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index 35c946b..e864ff8 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -18,17 +18,17 @@ std::map AutonomyDevice::last_sent_stat int AutonomyDevice::send_status_condition(const struct buffer current_status, const struct buffer new_status, unsigned int device_type) { json current_status_json {}; json new_status_json {}; - if (ba_json::JsonHelper::bufferToJson(¤t_status_json, current_status) != OK || - ba_json::JsonHelper::bufferToJson(&new_status_json, new_status) != OK) { + if (ba_json::JsonHelper::bufferToJson(current_status_json, current_status) != OK || + ba_json::JsonHelper::bufferToJson(new_status_json, new_status) != OK) { return NOT_OK; } - if (current_status_json["state"] != new_status_json["state"] || - current_status_json["nextStop"] != new_status_json["nextStop"]) { + if (current_status_json.at("state") != new_status_json.at("state") || + current_status_json.at("nextStop") != new_status_json.at("nextStop")) { return OK; } - if (new_status_json["telemetry"]["speed"] >= Constants::status_speed_threshold) { + if (new_status_json.at("telemetry").at("speed") >= Constants::status_speed_threshold) { auto current_time = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()); if (last_sent_status_timestamps_[device_type] + Constants::status_sending_period < current_time) { @@ -44,16 +44,16 @@ int AutonomyDevice::generate_command(struct buffer *generated_command, const str json current_status_json {}; json new_status_json {}; json current_command_json {}; - if (ba_json::JsonHelper::bufferToJson(¤t_status_json, current_status) != OK || - ba_json::JsonHelper::bufferToJson(&new_status_json, new_status) != OK || - ba_json::JsonHelper::bufferToJson(¤t_command_json, current_command) != OK) { + if (ba_json::JsonHelper::bufferToJson(current_status_json, current_status) != OK || + ba_json::JsonHelper::bufferToJson(new_status_json, new_status) != OK || + ba_json::JsonHelper::bufferToJson(current_command_json, current_command) != OK) { return NOT_OK; } - if (ba_json::JsonHelper::stringToAutonomyState(current_status_json["state"]) == MissionModule::AutonomyStatus_State_DRIVE && - ba_json::JsonHelper::stringToAutonomyState(new_status_json["state"]) == MissionModule::AutonomyStatus_State_IN_STOP) { - if (!current_command_json["stops"].empty()) { - current_command_json["stops"].erase(current_command_json["stops"].begin()); + if (ba_json::JsonHelper::stringToAutonomyState(current_status_json.at("state")) == MissionModule::AutonomyStatus_State_DRIVE && + ba_json::JsonHelper::stringToAutonomyState(new_status_json.at("state")) == MissionModule::AutonomyStatus_State_IN_STOP) { + if (!current_command_json.at("stops").empty()) { + current_command_json.at("stops").erase(current_command_json.at("stops").begin()); } } return ba_json::JsonHelper::jsonToBuffer(generated_command, current_command_json); @@ -72,18 +72,18 @@ int AutonomyDevice::aggregate_error(struct buffer *error_message, const struct b const struct buffer status) { json status_json {}; json error_json {}; - if (ba_json::JsonHelper::bufferToJson(&status_json, status) != OK || - ba_json::JsonHelper::bufferToJson(&error_json, current_error_message) != OK) { + if (ba_json::JsonHelper::bufferToJson(status_json, status) != OK || + ba_json::JsonHelper::bufferToJson(error_json, current_error_message) != OK) { return NOT_OK; } - if (status_json["state"] == ba_json::JsonHelper::autonomyStateToString(MissionModule::AutonomyStatus_State_IN_STOP)) { - if (!error_json["finishedStops"].empty()) { - if (error_json["finishedStops"][error_json["finishedStops"].size() - 1] != status_json["nextStop"]) { - error_json["finishedStops"].push_back(status_json["nextStop"]); + if (status_json.at("state") == ba_json::JsonHelper::autonomyStateToString(MissionModule::AutonomyStatus_State_IN_STOP)) { + if (!error_json.at("finishedStops").empty()) { + if (error_json.at("finishedStops")[error_json.at("finishedStops").size() - 1] != status_json.at("nextStop")) { + error_json.at("finishedStops").push_back(status_json.at("nextStop")); } } else { - error_json["finishedStops"].push_back(status_json["nextStop"]); + error_json.at("finishedStops").push_back(status_json.at("nextStop")); } } @@ -103,7 +103,7 @@ int AutonomyDevice::generate_first_command(struct buffer *default_command) { int AutonomyDevice::status_data_valid(const struct buffer status) { json status_json {}; - if (ba_json::JsonHelper::bufferToJson(&status_json, status) != OK) { + if (ba_json::JsonHelper::bufferToJson(status_json, status) != OK) { return NOT_OK; } if (protobuf::ProtobufHelper::validateAutonomyStatus(nlohmann::to_string(status_json)) != OK) { @@ -114,13 +114,10 @@ int AutonomyDevice::status_data_valid(const struct buffer status) { int AutonomyDevice::command_data_valid(const struct buffer command) { json command_json {}; - if (ba_json::JsonHelper::bufferToJson(&command_json, command) != OK) { - std::cerr << "Failed to parse command json" << std::endl; + if (ba_json::JsonHelper::bufferToJson(command_json, command) != OK) { return NOT_OK; } - std::cerr << command_json.dump() << std::endl; if (protobuf::ProtobufHelper::validateAutonomyCommand(nlohmann::to_string(command_json)) != OK) { - std::cerr << "Failed to validate command" << std::endl; return NOT_OK; } return OK; From 095b7e7368cd068dfa2253eb6e8a86ede0f036e0 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Mon, 12 Aug 2024 10:51:47 +0200 Subject: [PATCH 12/23] debug logging --- CMakeLists.txt | 4 +++- cmake/Dependencies.cmake | 3 ++- source/bringauto/protobuf/ProtobufHelper.cpp | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f17312..d2fedc2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,13 +58,14 @@ FIND_PACKAGE(nlohmann_json 3.10.5 REQUIRED) FIND_PACKAGE(Protobuf 3.21.12 REQUIRED) FIND_PACKAGE(fleet-protocol-interface 2.0.0 REQUIRED) FIND_PACKAGE(fleet-protocol-cxx-helpers-static 1.1.1 REQUIRED) +FIND_PACKAGE(libbringauto_logger 2.0.0 REQUIRED) IF (FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER) FIND_PACKAGE(fleet-http-client-shared 1.3.0 REQUIRED) ### fleet-http-client dependencies FIND_PACKAGE(Boost REQUIRED) FIND_PACKAGE(cpprestsdk REQUIRED) - FIND_PACKAGE(libbringauto_logger 1.2.0 REQUIRED) + #FIND_PACKAGE(libbringauto_logger 1.2.0 REQUIRED) ENDIF () CMDEF_ADD_LIBRARY( @@ -95,6 +96,7 @@ TARGET_LINK_LIBRARIES(mission_module_sources PUBLIC fleet-protocol-interface::common-headers-interface fleet-protocol-cxx-helpers-static::fleet-protocol-cxx-helpers-static message_handler_lib + bringauto_logger::bringauto_logger ) IF (FLEET_PROTOCOL_BUILD_MODULE_GATEWAY) diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index 2a8a07d..c041e1b 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -5,10 +5,11 @@ BA_PACKAGE_LIBRARY(fleet-protocol-cxx-helpers-static v1.1.1) BA_PACKAGE_LIBRARY(zlib v1.2.11) BA_PACKAGE_LIBRARY(nlohmann-json v3.10.5 PLATFORM_STRING_MODE any_machine NO_DEBUG ON) BA_PACKAGE_LIBRARY(protobuf v4.21.12) +BA_PACKAGE_LIBRARY(ba-logger v2.0.0) IF (FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER) BA_PACKAGE_LIBRARY(fleet-http-client-shared v1.3.0) BA_PACKAGE_LIBRARY(boost v1.78.0) BA_PACKAGE_LIBRARY(cpprestsdk v2.10.20) - BA_PACKAGE_LIBRARY(ba-logger v1.2.0) + #BA_PACKAGE_LIBRARY(ba-logger v1.2.0) ENDIF () diff --git a/source/bringauto/protobuf/ProtobufHelper.cpp b/source/bringauto/protobuf/ProtobufHelper.cpp index 52ac535..4fee927 100644 --- a/source/bringauto/protobuf/ProtobufHelper.cpp +++ b/source/bringauto/protobuf/ProtobufHelper.cpp @@ -3,8 +3,17 @@ #include #include +#include +#include namespace bringauto::protobuf { + +using namespace bringauto::logging; +static constexpr LoggerId context = {.id = "id"}; +using Logger1 = Logger; +//Logger1::addSink(); +//Logger1::init(LoggerSettings {"MissionModule", LoggerVerbosity::Debug}); + int ProtobufHelper::serializeProtobufMessageToBuffer(struct buffer* message, const google::protobuf::Message &protobufMessage) { if (allocate(message, protobufMessage.ByteSizeLong()) == OK) { protobufMessage.SerializeToArray(message->data, static_cast(message->size_in_bytes)); @@ -14,10 +23,14 @@ int ProtobufHelper::serializeProtobufMessageToBuffer(struct buffer* message, con } int ProtobufHelper::validateAutonomyStatus(const std::string &status) { + Logger1::addSink(); + Logger1::init(LoggerSettings {"MissionModule", LoggerVerbosity::Debug}); + Logger1::logDebug("status: {}", status); MissionModule::AutonomyStatus autonomyStatus {}; const auto parse_status = google::protobuf::util::JsonStringToMessage( status, &autonomyStatus ); + Logger1::destroy(); if(!parse_status.ok()) { return NOT_OK; } @@ -25,10 +38,14 @@ int ProtobufHelper::validateAutonomyStatus(const std::string &status) { } int ProtobufHelper::validateAutonomyCommand(const std::string &command) { + Logger1::addSink(); + Logger1::init(LoggerSettings {"MissionModule", LoggerVerbosity::Debug}); + Logger1::logDebug("command: {}", command); MissionModule::AutonomyCommand autonomyCommand {}; const auto parse_status = google::protobuf::util::JsonStringToMessage( command, &autonomyCommand ); + Logger1::destroy(); if(!parse_status.ok()) { return NOT_OK; } From 39f03d086519112a170213704442cb9148e6ce06 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 14 Aug 2024 14:14:03 +0200 Subject: [PATCH 13/23] validate a command when validating a command --- source/module_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/module_manager.cpp b/source/module_manager.cpp index 7e335b4..becaa28 100644 --- a/source/module_manager.cpp +++ b/source/module_manager.cpp @@ -70,7 +70,7 @@ aggregate_status(struct buffer *aggregated_status, const struct buffer current_s [[nodiscard]] int command_data_valid(const struct buffer command, unsigned int device_type) { switch (device_type) { case bamm::AUTONOMY_DEVICE_TYPE: - return bamm::devices::AutonomyDevice::status_data_valid(command); + return bamm::devices::AutonomyDevice::command_data_valid(command); default: return NOT_OK; } From f998d24fdcfbc9490264b9d921268d5f5710e078 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 14 Aug 2024 14:28:58 +0200 Subject: [PATCH 14/23] remove debug logging --- source/bringauto/protobuf/ProtobufHelper.cpp | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/source/bringauto/protobuf/ProtobufHelper.cpp b/source/bringauto/protobuf/ProtobufHelper.cpp index 4fee927..52ac535 100644 --- a/source/bringauto/protobuf/ProtobufHelper.cpp +++ b/source/bringauto/protobuf/ProtobufHelper.cpp @@ -3,17 +3,8 @@ #include #include -#include -#include namespace bringauto::protobuf { - -using namespace bringauto::logging; -static constexpr LoggerId context = {.id = "id"}; -using Logger1 = Logger; -//Logger1::addSink(); -//Logger1::init(LoggerSettings {"MissionModule", LoggerVerbosity::Debug}); - int ProtobufHelper::serializeProtobufMessageToBuffer(struct buffer* message, const google::protobuf::Message &protobufMessage) { if (allocate(message, protobufMessage.ByteSizeLong()) == OK) { protobufMessage.SerializeToArray(message->data, static_cast(message->size_in_bytes)); @@ -23,14 +14,10 @@ int ProtobufHelper::serializeProtobufMessageToBuffer(struct buffer* message, con } int ProtobufHelper::validateAutonomyStatus(const std::string &status) { - Logger1::addSink(); - Logger1::init(LoggerSettings {"MissionModule", LoggerVerbosity::Debug}); - Logger1::logDebug("status: {}", status); MissionModule::AutonomyStatus autonomyStatus {}; const auto parse_status = google::protobuf::util::JsonStringToMessage( status, &autonomyStatus ); - Logger1::destroy(); if(!parse_status.ok()) { return NOT_OK; } @@ -38,14 +25,10 @@ int ProtobufHelper::validateAutonomyStatus(const std::string &status) { } int ProtobufHelper::validateAutonomyCommand(const std::string &command) { - Logger1::addSink(); - Logger1::init(LoggerSettings {"MissionModule", LoggerVerbosity::Debug}); - Logger1::logDebug("command: {}", command); MissionModule::AutonomyCommand autonomyCommand {}; const auto parse_status = google::protobuf::util::JsonStringToMessage( command, &autonomyCommand ); - Logger1::destroy(); if(!parse_status.ok()) { return NOT_OK; } From 9127756beb6f5ff3eb67623ecb351397c5e909f6 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 14 Aug 2024 14:30:33 +0200 Subject: [PATCH 15/23] update version tag --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d2fedc2..ef319aa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,7 +10,7 @@ INCLUDE(CheckPIESupported) CHECK_PIE_SUPPORTED() SET(CMAKE_POSITION_INDEPENDENT_CODE ON) -SET(MISSION_MODULE_VERSION 1.2.8) +SET(MISSION_MODULE_VERSION 2.0.0) OPTION(BRINGAUTO_INSTALL "Configure install" OFF) OPTION(BRINGAUTO_PACKAGE "Configure package creation" OFF) From 7707c2fcd8bdda60de078badccf6d9186596090b Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 14 Aug 2024 14:37:25 +0200 Subject: [PATCH 16/23] formatting fixes --- CMakeLists.txt | 3 +-- cmake/Dependencies.cmake | 3 +-- include/bringauto/modules/mission_module/Constants.hpp | 2 +- include/bringauto/modules/mission_module/MissionModule.hpp | 2 +- .../modules/mission_module/devices/AutonomyDevice.hpp | 2 +- .../modules/mission_module/devices/AutonomyDevice.cpp | 2 +- source/device_management.cpp | 1 - source/external_server_api.cpp | 4 ++-- 8 files changed, 8 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ef319aa..b3e1828 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,14 +58,13 @@ FIND_PACKAGE(nlohmann_json 3.10.5 REQUIRED) FIND_PACKAGE(Protobuf 3.21.12 REQUIRED) FIND_PACKAGE(fleet-protocol-interface 2.0.0 REQUIRED) FIND_PACKAGE(fleet-protocol-cxx-helpers-static 1.1.1 REQUIRED) -FIND_PACKAGE(libbringauto_logger 2.0.0 REQUIRED) IF (FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER) FIND_PACKAGE(fleet-http-client-shared 1.3.0 REQUIRED) ### fleet-http-client dependencies FIND_PACKAGE(Boost REQUIRED) FIND_PACKAGE(cpprestsdk REQUIRED) - #FIND_PACKAGE(libbringauto_logger 1.2.0 REQUIRED) + FIND_PACKAGE(libbringauto_logger 1.2.0 REQUIRED) ENDIF () CMDEF_ADD_LIBRARY( diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index c041e1b..2a8a07d 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -5,11 +5,10 @@ BA_PACKAGE_LIBRARY(fleet-protocol-cxx-helpers-static v1.1.1) BA_PACKAGE_LIBRARY(zlib v1.2.11) BA_PACKAGE_LIBRARY(nlohmann-json v3.10.5 PLATFORM_STRING_MODE any_machine NO_DEBUG ON) BA_PACKAGE_LIBRARY(protobuf v4.21.12) -BA_PACKAGE_LIBRARY(ba-logger v2.0.0) IF (FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER) BA_PACKAGE_LIBRARY(fleet-http-client-shared v1.3.0) BA_PACKAGE_LIBRARY(boost v1.78.0) BA_PACKAGE_LIBRARY(cpprestsdk v2.10.20) - #BA_PACKAGE_LIBRARY(ba-logger v1.2.0) + BA_PACKAGE_LIBRARY(ba-logger v1.2.0) ENDIF () diff --git a/include/bringauto/modules/mission_module/Constants.hpp b/include/bringauto/modules/mission_module/Constants.hpp index 715ee02..235fbbe 100644 --- a/include/bringauto/modules/mission_module/Constants.hpp +++ b/include/bringauto/modules/mission_module/Constants.hpp @@ -21,4 +21,4 @@ class Constants { static constexpr auto status_sending_period = std::chrono::milliseconds(2900); }; -} \ No newline at end of file +} diff --git a/include/bringauto/modules/mission_module/MissionModule.hpp b/include/bringauto/modules/mission_module/MissionModule.hpp index 3077272..cfe5a6f 100644 --- a/include/bringauto/modules/mission_module/MissionModule.hpp +++ b/include/bringauto/modules/mission_module/MissionModule.hpp @@ -5,4 +5,4 @@ namespace bringauto::modules::mission_module { static constexpr int MISSION_MODULE_NUMBER = 1; static constexpr int AUTONOMY_DEVICE_TYPE = 1; -} \ No newline at end of file +} diff --git a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp index 79dd0f4..730962b 100644 --- a/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp +++ b/include/bringauto/modules/mission_module/devices/AutonomyDevice.hpp @@ -96,4 +96,4 @@ class AutonomyDevice { static std::map last_sent_status_timestamps_; }; -} \ No newline at end of file +} diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index e864ff8..823382d 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -123,4 +123,4 @@ int AutonomyDevice::command_data_valid(const struct buffer command) { return OK; } -} \ No newline at end of file +} diff --git a/source/device_management.cpp b/source/device_management.cpp index 718b98a..c591db2 100644 --- a/source/device_management.cpp +++ b/source/device_management.cpp @@ -12,4 +12,3 @@ int is_device_type_supported(unsigned int device_type) { return NOT_OK; } } - diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index 21592b5..827245d 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -2,11 +2,11 @@ #include #include #include +#include #include #include #include #include -#include #include #include @@ -356,4 +356,4 @@ int pop_command(buffer* command, device_identification* device, void *context) { int command_ack(const buffer command, const device_identification device, void *context) { return OK; -} \ No newline at end of file +} From 05cc21e010beaa0b7ac0607f4f358f37ad7f7027 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 14 Aug 2024 15:10:28 +0200 Subject: [PATCH 17/23] fix cmakelists --- CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b3e1828..ac766de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -95,7 +95,6 @@ TARGET_LINK_LIBRARIES(mission_module_sources PUBLIC fleet-protocol-interface::common-headers-interface fleet-protocol-cxx-helpers-static::fleet-protocol-cxx-helpers-static message_handler_lib - bringauto_logger::bringauto_logger ) IF (FLEET_PROTOCOL_BUILD_MODULE_GATEWAY) From 7bf43942688db871e6521eab1b7a48329c7fab76 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Thu, 15 Aug 2024 11:13:40 +0200 Subject: [PATCH 18/23] sonar cloud fixes --- include/bringauto/ba_json/JsonHelper.hpp | 2 +- source/bringauto/ba_json/JsonHelper.cpp | 4 +-- .../mission_module/devices/AutonomyDevice.cpp | 11 +++--- source/external_server_api.cpp | 36 +++++++++---------- 4 files changed, 26 insertions(+), 27 deletions(-) diff --git a/include/bringauto/ba_json/JsonHelper.hpp b/include/bringauto/ba_json/JsonHelper.hpp index 38b335a..408ea67 100644 --- a/include/bringauto/ba_json/JsonHelper.hpp +++ b/include/bringauto/ba_json/JsonHelper.hpp @@ -16,7 +16,7 @@ class JsonHelper { static int jsonToBuffer(buffer* buffer, const json& json); - static MissionModule::AutonomyStatus_State stringToAutonomyState(const std::string &state); + static MissionModule::AutonomyStatus_State stringToAutonomyState(const std::string_view &state); static std::string autonomyStateToString(MissionModule::AutonomyStatus_State state); diff --git a/source/bringauto/ba_json/JsonHelper.cpp b/source/bringauto/ba_json/JsonHelper.cpp index 999c7e3..aa6d8ad 100644 --- a/source/bringauto/ba_json/JsonHelper.cpp +++ b/source/bringauto/ba_json/JsonHelper.cpp @@ -26,7 +26,7 @@ int JsonHelper::jsonToBuffer(buffer *buffer, const json& json) { return OK; } -MissionModule::AutonomyStatus_State JsonHelper::stringToAutonomyState(const std::string &state) { +MissionModule::AutonomyStatus_State JsonHelper::stringToAutonomyState(const std::string_view &state) { if (state == "IDLE") { return MissionModule::AutonomyStatus_State::AutonomyStatus_State_IDLE; } else if (state == "DRIVE") { @@ -51,7 +51,6 @@ std::string JsonHelper::autonomyStateToString(const MissionModule::AutonomyStatu return "IN_STOP"; case MissionModule::AutonomyStatus_State::AutonomyStatus_State_OBSTACLE: return "OBSTACLE"; - case MissionModule::AutonomyStatus_State::AutonomyStatus_State_ERROR: default: return "ERROR"; } @@ -63,7 +62,6 @@ std::string JsonHelper::autonomyActionToString(const MissionModule::AutonomyComm return "STOP"; case MissionModule::AutonomyCommand_Action::AutonomyCommand_Action_START: return "DRIVE"; - case MissionModule::AutonomyCommand_Action::AutonomyCommand_Action_NO_ACTION: default: return "NO_ACTION"; } diff --git a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp index 823382d..58d6535 100644 --- a/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp +++ b/source/bringauto/modules/mission_module/devices/AutonomyDevice.cpp @@ -50,11 +50,12 @@ int AutonomyDevice::generate_command(struct buffer *generated_command, const str return NOT_OK; } - if (ba_json::JsonHelper::stringToAutonomyState(current_status_json.at("state")) == MissionModule::AutonomyStatus_State_DRIVE && - ba_json::JsonHelper::stringToAutonomyState(new_status_json.at("state")) == MissionModule::AutonomyStatus_State_IN_STOP) { - if (!current_command_json.at("stops").empty()) { - current_command_json.at("stops").erase(current_command_json.at("stops").begin()); - } + if (ba_json::JsonHelper::stringToAutonomyState(std::string(current_status_json.at("state"))) == + MissionModule::AutonomyStatus_State_DRIVE && + ba_json::JsonHelper::stringToAutonomyState(std::string(new_status_json.at("state"))) == + MissionModule::AutonomyStatus_State_IN_STOP && + !current_command_json.at("stops").empty()) { + current_command_json.at("stops").erase(current_command_json.at("stops").begin()); } return ba_json::JsonHelper::jsonToBuffer(generated_command, current_command_json); } diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index 827245d..9f233c4 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -18,14 +18,14 @@ namespace bamm = bringauto::modules::mission_module; void *init(const config config_data) { auto *context = new bamm::Context {}; const bringauto::fleet_protocol::cxx::KeyValueConfig config(config_data); - std::string api_url; - std::string api_key; - std::string company_name; - std::string car_name; - int max_requests_threshold_count; - int max_requests_threshold_period_ms; - int delay_after_threshold_reached_ms; - int retry_requests_delay_ms; + std::string api_url {}; + std::string api_key {}; + std::string company_name {}; + std::string car_name {}; + int max_requests_threshold_count {}; + int max_requests_threshold_period_ms {}; + int delay_after_threshold_reached_ms {}; + int retry_requests_delay_ms {}; for (auto i = config.cbegin(); i != config.cend(); ++i) { if (i->first == "api_url") { @@ -62,7 +62,7 @@ void *init(const config config_data) { if (max_requests_threshold_count < 0 || i->second.empty()) { throw std::exception(); } - } catch (...) { + } catch (std::exception&) { delete context; return nullptr; } @@ -73,7 +73,7 @@ void *init(const config config_data) { if (max_requests_threshold_period_ms < 0 || i->second.empty()) { throw std::exception(); } - } catch (...) { + } catch (std::exception&) { delete context; return nullptr; } @@ -84,7 +84,7 @@ void *init(const config config_data) { if (delay_after_threshold_reached_ms < 0 || i->second.empty()) { throw std::exception(); } - } catch (...) { + } catch (std::exception&) { delete context; return nullptr; } @@ -95,7 +95,7 @@ void *init(const config config_data) { if (retry_requests_delay_ms < 0 || i->second.empty()) { throw std::exception(); } - } catch (...) { + } catch (std::exception&) { delete context; return nullptr; } @@ -163,7 +163,7 @@ int forward_status(const buffer device_status, const device_identification devic try { con->fleet_api_client->sendStatus(device_status_str); - } catch (...) { + } catch (std::exception&) { return NOT_OK; } @@ -203,7 +203,7 @@ int forward_error_message(const buffer error_msg, const device_identification de con->fleet_api_client->sendStatus( error_msg_str, bringauto::fleet_protocol::http_client::FleetApiClient::StatusType::STATUS_ERROR ); - } catch (...) { + } catch (std::exception&) { return NOT_OK; } @@ -223,12 +223,12 @@ int device_disconnected(const int disconnect_type, const device_identification d const std::string_view device_device_role(static_cast (device.device_role.data), device.device_role.size_in_bytes); const std::string_view device_device_name(static_cast (device.device_name.data), device.device_name.size_in_bytes); - for(auto it = con->devices.begin(); it != con->devices.end(); it++) { + for(auto it = con->devices.begin(); it != con->devices.end(); ++it) { const std::string_view it_device_role(static_cast (it->device_role.data), it->device_role.size_in_bytes); const std::string_view it_device_name(static_cast (it->device_name.data), it->device_name.size_in_bytes); - bool device_is_present = it->device_type == device.device_type && it_device_role == device_device_role && it_device_name == device_device_name - && it->module == device.module && it->priority == device.priority; + const bool device_is_present = it->device_type == device.device_type && it_device_role == device_device_role && + it_device_name == device_device_name && it->module == device.module && it->priority == device.priority; if(device_is_present) { deallocate(&it->device_role); @@ -280,7 +280,7 @@ int wait_for_command(int timeout_time_in_ms, void *context) { try { commands = con->fleet_api_client->getCommands(con->last_command_timestamp + 1, true); - } catch (std::exception& e) { + } catch (std::exception&) { return TIMEOUT_OCCURRED; } From 18b96e99d1994306086f6f29c9d5f6338150142b Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Thu, 15 Aug 2024 12:23:36 +0200 Subject: [PATCH 19/23] catch specific exceptions --- source/external_server_api.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index 9f233c4..c8231ac 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -60,9 +60,9 @@ void *init(const config config_data) { try { max_requests_threshold_count = std::stoi(i->second); if (max_requests_threshold_count < 0 || i->second.empty()) { - throw std::exception(); + throw std::invalid_argument("max_requests_threshold_count must be a positive integer"); } - } catch (std::exception&) { + } catch (std::invalid_argument&) { delete context; return nullptr; } @@ -71,9 +71,9 @@ void *init(const config config_data) { try { max_requests_threshold_period_ms = std::stoi(i->second); if (max_requests_threshold_period_ms < 0 || i->second.empty()) { - throw std::exception(); + throw std::invalid_argument("max_requests_threshold_period_ms must be a positive integer"); } - } catch (std::exception&) { + } catch (std::invalid_argument&) { delete context; return nullptr; } @@ -82,9 +82,9 @@ void *init(const config config_data) { try { delay_after_threshold_reached_ms = std::stoi(i->second); if (delay_after_threshold_reached_ms < 0 || i->second.empty()) { - throw std::exception(); + throw std::invalid_argument("delay_after_threshold_reached_ms must be a positive integer"); } - } catch (std::exception&) { + } catch (std::invalid_argument&) { delete context; return nullptr; } @@ -93,9 +93,9 @@ void *init(const config config_data) { try { retry_requests_delay_ms = std::stoi(i->second); if (retry_requests_delay_ms < 0 || i->second.empty()) { - throw std::exception(); + throw std::invalid_argument("retry_requests_delay_ms must be a positive integer"); } - } catch (std::exception&) { + } catch (std::invalid_argument&) { delete context; return nullptr; } @@ -163,7 +163,7 @@ int forward_status(const buffer device_status, const device_identification devic try { con->fleet_api_client->sendStatus(device_status_str); - } catch (std::exception&) { + } catch (org::openapitools::client::api::ApiException&) { return NOT_OK; } @@ -203,7 +203,7 @@ int forward_error_message(const buffer error_msg, const device_identification de con->fleet_api_client->sendStatus( error_msg_str, bringauto::fleet_protocol::http_client::FleetApiClient::StatusType::STATUS_ERROR ); - } catch (std::exception&) { + } catch (org::openapitools::client::api::ApiException&) { return NOT_OK; } @@ -280,7 +280,7 @@ int wait_for_command(int timeout_time_in_ms, void *context) { try { commands = con->fleet_api_client->getCommands(con->last_command_timestamp + 1, true); - } catch (std::exception&) { + } catch (org::openapitools::client::api::ApiException&) { return TIMEOUT_OCCURRED; } From db41bef0ec92c844dfe9bf65a9e6ae0df389040e Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Thu, 15 Aug 2024 12:31:25 +0200 Subject: [PATCH 20/23] revert to general exceptions --- source/external_server_api.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index c8231ac..9f233c4 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -60,9 +60,9 @@ void *init(const config config_data) { try { max_requests_threshold_count = std::stoi(i->second); if (max_requests_threshold_count < 0 || i->second.empty()) { - throw std::invalid_argument("max_requests_threshold_count must be a positive integer"); + throw std::exception(); } - } catch (std::invalid_argument&) { + } catch (std::exception&) { delete context; return nullptr; } @@ -71,9 +71,9 @@ void *init(const config config_data) { try { max_requests_threshold_period_ms = std::stoi(i->second); if (max_requests_threshold_period_ms < 0 || i->second.empty()) { - throw std::invalid_argument("max_requests_threshold_period_ms must be a positive integer"); + throw std::exception(); } - } catch (std::invalid_argument&) { + } catch (std::exception&) { delete context; return nullptr; } @@ -82,9 +82,9 @@ void *init(const config config_data) { try { delay_after_threshold_reached_ms = std::stoi(i->second); if (delay_after_threshold_reached_ms < 0 || i->second.empty()) { - throw std::invalid_argument("delay_after_threshold_reached_ms must be a positive integer"); + throw std::exception(); } - } catch (std::invalid_argument&) { + } catch (std::exception&) { delete context; return nullptr; } @@ -93,9 +93,9 @@ void *init(const config config_data) { try { retry_requests_delay_ms = std::stoi(i->second); if (retry_requests_delay_ms < 0 || i->second.empty()) { - throw std::invalid_argument("retry_requests_delay_ms must be a positive integer"); + throw std::exception(); } - } catch (std::invalid_argument&) { + } catch (std::exception&) { delete context; return nullptr; } @@ -163,7 +163,7 @@ int forward_status(const buffer device_status, const device_identification devic try { con->fleet_api_client->sendStatus(device_status_str); - } catch (org::openapitools::client::api::ApiException&) { + } catch (std::exception&) { return NOT_OK; } @@ -203,7 +203,7 @@ int forward_error_message(const buffer error_msg, const device_identification de con->fleet_api_client->sendStatus( error_msg_str, bringauto::fleet_protocol::http_client::FleetApiClient::StatusType::STATUS_ERROR ); - } catch (org::openapitools::client::api::ApiException&) { + } catch (std::exception&) { return NOT_OK; } @@ -280,7 +280,7 @@ int wait_for_command(int timeout_time_in_ms, void *context) { try { commands = con->fleet_api_client->getCommands(con->last_command_timestamp + 1, true); - } catch (org::openapitools::client::api::ApiException&) { + } catch (std::exception&) { return TIMEOUT_OCCURRED; } From c47cfd67aa8a135ee8fe54dc112e0b3274d5fe40 Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 16 Oct 2024 14:15:06 +0200 Subject: [PATCH 21/23] use from_chars to convert strings --- source/external_server_api.cpp | 32 ++++++++------------------------ 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index ba2ffba..fcb84b4 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -57,45 +57,29 @@ void *init(const config config_data) { car_name = i->second; } else if (i->first == "max_requests_threshold_count") { - try { - max_requests_threshold_count = std::stoi(i->second); - if (max_requests_threshold_count < 0 || i->second.empty()) { - throw std::exception(); - } - } catch (std::exception&) { + auto result = std::from_chars(i->second.data(), i->second.data() + i->second.size(), max_requests_threshold_count); + if (result.ec == std::errc() || max_requests_threshold_count < 0 || i->second.empty()) { delete context; return nullptr; } } else if (i->first == "max_requests_threshold_period_ms") { - try { - max_requests_threshold_period_ms = std::stoi(i->second); - if (max_requests_threshold_period_ms < 0 || i->second.empty()) { - throw std::exception(); - } - } catch (std::exception&) { + auto result = std::from_chars(i->second.data(), i->second.data() + i->second.size(), max_requests_threshold_period_ms); + if (result.ec == std::errc() || max_requests_threshold_period_ms < 0 || i->second.empty()) { delete context; return nullptr; } } else if (i->first == "delay_after_threshold_reached_ms") { - try { - delay_after_threshold_reached_ms = std::stoi(i->second); - if (delay_after_threshold_reached_ms < 0 || i->second.empty()) { - throw std::exception(); - } - } catch (std::exception&) { + auto result = std::from_chars(i->second.data(), i->second.data() + i->second.size(), delay_after_threshold_reached_ms); + if (result.ec == std::errc() || delay_after_threshold_reached_ms < 0 || i->second.empty()) { delete context; return nullptr; } } else if (i->first == "retry_requests_delay_ms") { - try { - retry_requests_delay_ms = std::stoi(i->second); - if (retry_requests_delay_ms < 0 || i->second.empty()) { - throw std::exception(); - } - } catch (std::exception&) { + auto result = std::from_chars(i->second.data(), i->second.data() + i->second.size(), retry_requests_delay_ms); + if (result.ec == std::errc() || retry_requests_delay_ms < 0 || i->second.empty()) { delete context; return nullptr; } From b01f4eb67875148f50d5b7a8eabccf29c203992d Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 23 Oct 2024 11:10:07 +0200 Subject: [PATCH 22/23] update fleet protocol http client version --- CMakeLists.txt | 2 +- cmake/Dependencies.cmake | 2 +- source/external_server_api.cpp | 23 +++++++++-------------- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index aa1ba14..9f194e6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,7 +60,7 @@ FIND_PACKAGE(fleet-protocol-interface 2.0.0 REQUIRED) FIND_PACKAGE(fleet-protocol-cxx-helpers-static 1.1.1 REQUIRED) IF (FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER) - FIND_PACKAGE(fleet-http-client-shared 1.5.0 REQUIRED) + FIND_PACKAGE(fleet-http-client-shared 2.0.0 REQUIRED) ### fleet-http-client dependencies FIND_PACKAGE(Boost REQUIRED) FIND_PACKAGE(cpprestsdk REQUIRED) diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index 9b42c62..b3a2802 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -7,7 +7,7 @@ BA_PACKAGE_LIBRARY(nlohmann-json v3.10.5 PLATFORM_STRING_MOD BA_PACKAGE_LIBRARY(protobuf v4.21.12) IF (FLEET_PROTOCOL_BUILD_EXTERNAL_SERVER) - BA_PACKAGE_LIBRARY(fleet-http-client-shared v1.5.0) + BA_PACKAGE_LIBRARY(fleet-http-client-shared v2.0.0) BA_PACKAGE_LIBRARY(boost v1.86.0) BA_PACKAGE_LIBRARY(cpprestsdk v2.10.20) ENDIF () diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index fcb84b4..9d6875e 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -145,9 +145,8 @@ int forward_status(const buffer device_status, const device_identification devic ) ); - try { - con->fleet_api_client->sendStatus(device_status_str); - } catch (std::exception&) { + auto rc = con->fleet_api_client->sendStatus(device_status_str); + if(rc != bringauto::fleet_protocol::http_client::FleetApiClient::ReturnCode::OK) { return NOT_OK; } @@ -183,11 +182,10 @@ int forward_error_message(const buffer error_msg, const device_identification de ) ); - try { - con->fleet_api_client->sendStatus( - error_msg_str, bringauto::fleet_protocol::http_client::FleetApiClient::StatusType::STATUS_ERROR - ); - } catch (std::exception&) { + auto rc = con->fleet_api_client->sendStatus( + error_msg_str, bringauto::fleet_protocol::http_client::FleetApiClient::StatusType::STATUS_ERROR + ); + if(rc != bringauto::fleet_protocol::http_client::FleetApiClient::ReturnCode::OK) { return NOT_OK; } @@ -259,18 +257,15 @@ int wait_for_command(int timeout_time_in_ms, void *context) { const auto con = static_cast (context); std::unique_lock lock(con->mutex); - std::pair>, - bringauto::fleet_protocol::http_client::FleetApiClient::ReturnCode> commands; bool parse_commands = con->last_command_timestamp != 0; - try { - commands = con->fleet_api_client->getCommands(con->last_command_timestamp + 1, true); - } catch (std::exception&) { + auto [commands, rc] = con->fleet_api_client->getCommands(con->last_command_timestamp + 1, true); + if(rc != bringauto::fleet_protocol::http_client::FleetApiClient::ReturnCode::OK) { return TIMEOUT_OCCURRED; } bool received_no_commands = true; - for(const auto& command : commands.first) { + for(const auto& command : commands) { if(command->getTimestamp() > con->last_command_timestamp) { con->last_command_timestamp = command->getTimestamp(); } From 12700152fddc3902cdf1060269d7ce478f8e6aeb Mon Sep 17 00:00:00 2001 From: MarioIvancik Date: Wed, 23 Oct 2024 11:32:47 +0200 Subject: [PATCH 23/23] fix config value checking --- source/external_server_api.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/external_server_api.cpp b/source/external_server_api.cpp index 9d6875e..a94163a 100644 --- a/source/external_server_api.cpp +++ b/source/external_server_api.cpp @@ -58,28 +58,28 @@ void *init(const config config_data) { } else if (i->first == "max_requests_threshold_count") { auto result = std::from_chars(i->second.data(), i->second.data() + i->second.size(), max_requests_threshold_count); - if (result.ec == std::errc() || max_requests_threshold_count < 0 || i->second.empty()) { + if (result.ec != std::errc() || max_requests_threshold_count < 0 || i->second.empty()) { delete context; return nullptr; } } else if (i->first == "max_requests_threshold_period_ms") { auto result = std::from_chars(i->second.data(), i->second.data() + i->second.size(), max_requests_threshold_period_ms); - if (result.ec == std::errc() || max_requests_threshold_period_ms < 0 || i->second.empty()) { + if (result.ec != std::errc() || max_requests_threshold_period_ms < 0 || i->second.empty()) { delete context; return nullptr; } } else if (i->first == "delay_after_threshold_reached_ms") { auto result = std::from_chars(i->second.data(), i->second.data() + i->second.size(), delay_after_threshold_reached_ms); - if (result.ec == std::errc() || delay_after_threshold_reached_ms < 0 || i->second.empty()) { + if (result.ec != std::errc() || delay_after_threshold_reached_ms < 0 || i->second.empty()) { delete context; return nullptr; } } else if (i->first == "retry_requests_delay_ms") { auto result = std::from_chars(i->second.data(), i->second.data() + i->second.size(), retry_requests_delay_ms); - if (result.ec == std::errc() || retry_requests_delay_ms < 0 || i->second.empty()) { + if (result.ec != std::errc() || retry_requests_delay_ms < 0 || i->second.empty()) { delete context; return nullptr; }