Go to the documentation of this file.
22 #ifndef ENGINE_JSON_NRP_CLIENT_H
23 #define ENGINE_JSON_NRP_CLIENT_H
32 #include <nlohmann/json.hpp>
38 #include <restclient-cpp/restclient.h>
44 template<
class ENGINE, const
char* SCHEMA>
55 :
EngineClient<ENGINE, SCHEMA>(config, std::move(launcher)),
70 :
EngineClient<ENGINE, SCHEMA>(config, std::move(launcher)),
71 _serverAddress(serverAddress)
75 this->
engineConfig()[
"ServerAddress"] = this->_serverAddress;
85 this->startRegistrationServer();
92 if(enginePID > 0 && !this->
engineConfig().at(
"RegistrationServerAddress").empty())
96 if(serverAddr.empty())
100 this->_serverAddress = serverAddr;
114 for(
auto curDataPack : dataPacks)
116 assert(curDataPack->engineName() == this->engineName());
118 if(curDataPack->isEmpty())
119 throw NRPException::logCreate(
"Attempt to send empty datapack " + curDataPack->name() +
" to Engine " + this->engineName());
124 "\" cannot handle datapack type '" +
125 curDataPack->type() +
"'");
129 const auto & name = curDataPack->name();
131 request[name][
"engine_name"] = curDataPack->engineName();
132 request[name][
"type"] = curDataPack->type();
133 request[name][
"data"] = data;
139 "Engine server \"" + this->engineName() +
"\" failed during datapack handling");
148 std::vector<std::string> startParams = this->
engineConfig().at(
"EngineProcStartParams");
150 std::string name = this->
engineConfig().at(
"EngineName");
154 std::string address = this->
engineConfig().at(
"ServerAddress");
158 std::string reg_address = this->
engineConfig().at(
"RegistrationServerAddress");
169 for(
const auto &
id : requestedDataPackIds)
171 if(this->
engineName().compare(
id.EngineName) == 0)
173 request[
id.Name] = {{
"engine_name",
id.EngineName}, {
"type",
id.Type}};
181 "Engine server \"" + this->engineName() +
"\" failed during datapack retrieval"));
183 return this->getDataPackInterfacesFromJSON(resp);
196 NRPLogger::debug(
"EngineJSONNRPClient::sendInitCommand [ data: {} ]", data.dump());
201 "Engine server \"" + this->engineName() +
"\" failed during initialization");
213 NRPLogger::debug(
"EngineJSONNRPClient::sendResetCommand [ data: {} ]", data.dump());
218 "Engine server \"" + this->engineName() +
"\" failed during reset");
230 NRPLogger::debug(
"EngineJSONNRPClient::sendShutdownCommand [ data: {} ]", data.dump());
235 "Engine server \"" + this->engineName() +
"\" failed during shutdown");
250 assert(pRegistrationServer !=
nullptr);
251 assert(pRegistrationServer->isRunning());
254 auto engineAddr = pRegistrationServer->requestEngine(this->
engineName());
256 while(engineAddr.empty() && numTries > 0)
260 engineAddr = pRegistrationServer->retrieveEngineAddress(this->
engineName());
265 if(pRegistrationServer->getNumWaitingEngines() == 0)
275 const unsigned NUM_RETRIES_REG_SERVER = 2;
280 std::string _serverAddress;
290 static nlohmann::json sendRequest(
const std::string &serverName,
const std::string &contentType,
const std::string &request,
const std::string_view &exceptionMessage)
295 auto resp = RestClient::post(serverName, contentType, request);
298 throw std::domain_error(
"Request failed with code " + std::to_string(resp.code) +
299 " and message:" +
"\n" + resp.body +
300 "Client context message: " + exceptionMessage.data());
303 return nlohmann::json::parse(resp.body);
305 catch(std::exception &e)
324 "Engine Server failed during loop execution"));
332 catch(std::exception &e)
337 if(engineTime < SimulationTime::zero())
354 for(
auto curDataPackIterator = datapacks.begin(); curDataPackIterator != datapacks.end(); ++curDataPackIterator)
359 (*curDataPackIterator)[
"engine_name"],
360 (*curDataPackIterator)[
"type"]);
363 interfaces.push_back(this->getSingleDataPackInterfaceFromJSON(curDataPackIterator, datapackID));
365 catch(std::exception &e)
393 if(datapackData->size() == 2)
403 newDataPack->setEngineName(this->
engineName());
409 throw NRPException::logCreate(
"DataPack type \"" + datapackID.
Type +
"\" cannot be handled by the \"" + this->engineName() +
"\" engine");
416 void startRegistrationServer()
418 const std::string regServerAddressConfig = this->
engineConfig().at(
"RegistrationServerAddress");
421 if(regServerAddressActual != regServerAddressConfig)
423 NRPLogger::warn(
"Registration server failed to bind to the specified address '{}'. Using '{}' instead.", regServerAddressConfig, regServerAddressActual);
428 this->
engineConfig()[
"RegistrationServerAddress"] = regServerAddressActual;
434 #endif //ENGINE_JSON_NRP_CLIENT_H
std::vector< std::shared_ptr< const DataPackInterface > > datapacks_vector_t
Definition: datapack_interface.h:220
virtual pid_t launchEngine()
Launch the engine.
Definition: engine_client_interface.cpp:31
static void warn(const FormatString &fmt, const Args &...args)
NRP logging function with message formatting for warning level.
Definition: nrp_logger.h:149
std::set< std::shared_ptr< const DataPackInterface >, DataPackPointerComparator > datapacks_set_t
Definition: datapack_interface.h:219
std::unique_ptr< ProcessLauncherInterface > unique_ptr
Definition: ptr_templates.h:34
std::string waitForRegistration(unsigned int numTries, unsigned int waitTime) const
Wait for the engine registration server to receive a call from the engine.
Definition: engine_json_nrp_client.h:244
static constexpr std::string_view EngineServerContentType
Content Type passed between server and client.
Definition: engine_json_config.h:92
std::string Type
DataPack Type.
Definition: datapack_interface.h:54
static constexpr std::string_view EngineTimeName
JSON name under which the runLoopStep engine time is sent.
Definition: engine_json_config.h:87
DataPackInterface::const_shared_ptr DataPackInterfaceConstSharedPtr
Definition: datapack_interface.h:180
DataPack< nlohmann::json > JsonDataPack
Definition: json_datapack.h:29
const std::string engineName() const override final
Get Engine Name.
Definition: engine_client_interface.h:266
static std::string tryInstantiate(const std::string &initialAddress, const unsigned numRetries)
Attempts to instantiate and start the registration server.
Definition: engine_json_registration_server.cpp:81
NRP - Gazebo Communicator on the NRP side. Converts DataPackInterface classes from/to JSON objects.
Definition: engine_json_nrp_client.h:45
nlohmann::json sendResetCommand(const nlohmann::json &data)
Send a reset command.
Definition: engine_json_nrp_client.h:209
nlohmann::json sendInitCommand(const nlohmann::json &data)
Send an initialization command.
Definition: engine_json_nrp_client.h:192
Base class for all Engines.
Definition: engine_client_interface.h:191
static constexpr std::string_view EngineServerResetRoute
REST Server Route for engine reset.
Definition: engine_json_config.h:72
static constexpr std::string_view EngineServerInitializeRoute
REST Server Route for engine initialization.
Definition: engine_json_config.h:67
static std::string getType()
Returns type of the datapack class.
Definition: datapack.h:61
static void clearInstance()
Delete Instance.
Definition: engine_json_registration_server.cpp:74
static EngineJSONRegistrationServer * getInstance()
Get Instance of EngineJSONRegistrationServer.
Definition: engine_json_registration_server.cpp:61
const nlohmann::json & engineConfig() const override final
Get Engine Configuration.
Definition: engine_client_interface.h:278
std::string Name
DataPack Name. Used by simulator to identify source/sink of datapack.
Definition: datapack_interface.h:44
DataPackInterface::shared_ptr DataPackInterfaceSharedPtr
Definition: datapack_interface.h:179
std::set< DataPackIdentifier > datapack_identifiers_set_t
Definition: datapack_interface.h:221
static constexpr std::string_view EngineServerSetDataPacksRoute
REST Server Route to which to send datapack changes.
Definition: engine_json_config.h:57
static constexpr std::string_view EngineRegistrationServerAddrArg
Parameter name that is used to pass along the server address.
Definition: engine_json_config.h:42
static constexpr std::string_view EngineTimeStepName
JSON name under which the runLoopStep timeStep is saved.
Definition: engine_json_config.h:82
virtual ~EngineJSONNRPClient() override=default
static EXCEPTION logCreate(LOG_EXCEPTION_T &exception, const std::string &msg, NRPLogger::spdlog_out_fcn_t spdlogCall=NRPLogger::critical)
Definition: nrp_exceptions.h:73
EngineJSONNRPClient(const std::string &serverAddress, nlohmann::json &config, ProcessLauncherInterface::unique_ptr &&launcher)
Constructor.
Definition: engine_json_nrp_client.h:69
static constexpr std::string_view EngineServerAddrArg
Parameter name that is used to pass along the server address.
Definition: engine_json_config.h:37
static constexpr std::string_view EngineServerRunLoopStepRoute
REST Server Route to execute a single loop.
Definition: engine_json_config.h:62
nlohmann::json sendShutdownCommand(const nlohmann::json &data)
Send a shutdown command.
Definition: engine_json_nrp_client.h:226
Identifies a single datapack.
Definition: datapack_interface.h:38
static constexpr std::string_view EngineServerShutdownRoute
REST Server Route for engine shutdown.
Definition: engine_json_config.h:77
Base datapack class.
Definition: datapack.h:36
Interface to datapacks.
Definition: datapack_interface.h:89
static constexpr std::string_view EngineServerGetDataPacksRoute
REST Server Route from which to get datapack information.
Definition: engine_json_config.h:52
static constexpr std::string_view EngineNameArg
Parameter name that is used to pass along the engine name.
Definition: engine_json_config.h:47
EngineJSONNRPClient(nlohmann::json &config, ProcessLauncherInterface::unique_ptr &&launcher)
Constructor.
Definition: engine_json_nrp_client.h:54
virtual datapacks_vector_t getDataPacksFromEngine(const datapack_identifiers_set_t &requestedDataPackIds) override
Gets requested datapacks from engine.
Definition: engine_json_nrp_client.h:164
static void debug(const FormatString &fmt, const Args &...args)
NRP logging function with message formatting for debug level.
Definition: nrp_logger.h:127
std::chrono::nanoseconds SimulationTime
Definition: time_utils.h:31
std::string EngineName
Corresponding engine.
Definition: datapack_interface.h:49
virtual pid_t launchEngine() override
Launch the engine.
Definition: engine_json_nrp_client.h:81
virtual const std::vector< std::string > engineProcStartParams() const override
Get all Engine Process Startup parameters.
Definition: engine_json_nrp_client.h:144
static RestClientSetup * ensureInstance()
Ensure that RestClientSetup has been initialized.
Definition: restclient_setup.cpp:39
#define NRP_LOGGER_TRACE(...)
trace log macro. It is voided by defining \PRODUCTION_RELEASE
Definition: nrp_logger.h:39
nlohmann::json json
Definition: engine_json_server.cpp:31
virtual void sendDataPacksToEngine(const datapacks_set_t &dataPacks) override
Sends datapacks to engine.
Definition: engine_json_nrp_client.h:106