Skip to content

Commit

Permalink
Simplify code and remove unneeded code
Browse files Browse the repository at this point in the history
  • Loading branch information
Chi-EEE committed Mar 14, 2024
1 parent 46f75e5 commit fc7d0b4
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 121 deletions.
4 changes: 2 additions & 2 deletions app/rpi/behaviour_tree/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ int main(int argc, const char* argv[])
std::shared_ptr<BehaviourTree> behaviour_tree = behaviour_tree_result.value();

std::shared_ptr<BehaviourTreeHandler> behaviour_tree_handler = std::make_shared<BehaviourTreeHandler>(BehaviourTreeHandler());
behaviour_tree_handler->setBehaviourTree(behaviour_tree);
behaviour_tree_handler->_setBehaviourTree(behaviour_tree);

std::unique_ptr<PluginManager> plugin_manager = std::make_unique<PluginManager>();
plugin_manager->addPlugin(behaviour_tree_handler);
Expand All @@ -130,7 +130,7 @@ int main(int argc, const char* argv[])

car_system->initialize();

behaviour_tree_handler->start();
behaviour_tree_handler->startBehaviourTree();

std::cout << "Press any key to exit the loop." << std::endl;
while (!kbhit()) {
Expand Down
76 changes: 56 additions & 20 deletions app/rpi/common/include/behaviour_tree/BehaviourTreeHandler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

#include <nod/nod.hpp>

#include "utils/Utility.hpp"

#include "car/plugin/Plugin.h"

#include "behaviour_tree/BehaviourTreeParser.hpp"
Expand All @@ -25,41 +27,74 @@ namespace behaviour_tree
this->car_system = car_system;
// The BehaviourTreeParser does not come with a CustomNodeParser since each program can have a different set of Action nodes
BehaviourTreeParser::instance().setCustomNodeParser(std::make_shared<node::custom::CarCustomNodeParser>(CarCustomNodeParser()));
this->car_system->getMessagingSystem()->getCustomCommandSignal().connect([&](std::string custom_command_type, std::string custom)
this->car_system->getMessagingSystem()->getCommandSignal().connect(std::bind(&BehaviourTreeHandler::handleCommand, this, std::placeholders::_1, std::placeholders::_2));
}

void handleCommand(const std::string message, const rapidjson::Value &message_json)
{
if (message_json["command"].GetString() != "behaviour_tree")
{
return;
}
if (!message_json.HasMember("action") || !message_json["action"].IsString())
{
spdlog::error(R"(The property "action" does not exist in the given json.)");
return;
}
switch (utils::hash(message_json["action"].GetString()))
{
case utils::hash("set"):
{
if (custom_command_type != "behaviour_tree") {
return;
}
auto maybe_behaviour_tree = BehaviourTreeParser::instance().parseXML(custom);
if (!maybe_behaviour_tree.has_value()) {
spdlog::error("Behaviour tree parsing failed | {} | {}", maybe_behaviour_tree.error(), custom);
return;
}
auto& behaviour_tree = maybe_behaviour_tree.value();
spdlog::info("Behaviour tree parsed successfully | {}", behaviour_tree->toString());
this->setBehaviourTree(behaviour_tree); });
this->setBehaviourTree(message_json);
break;
}
case utils::hash("start"):
{
this->startBehaviourTree();
break;
}
};
}

void update() final override
void setBehaviourTree(const rapidjson::Value &message_json)
{
if (this->context == nullptr)
if (!message_json.HasMember("data") || !message_json["data"].IsString())
{
spdlog::error(R"(The property "data" does not exist in the given json.)");
return;
}
this->context->update(this->tick_count);
++this->tick_count;
auto maybe_behaviour_tree = BehaviourTreeParser::instance().parseXML(message_json["data"].GetString());
if (!maybe_behaviour_tree.has_value())
{
spdlog::error(R"(Unable to parse the given behaviour tree | {})", maybe_behaviour_tree.error());
return;
}
auto &behaviour_tree = maybe_behaviour_tree.value();

spdlog::info("Behaviour tree parsed successfully | {}", behaviour_tree->toString());
this->_setBehaviourTree(behaviour_tree);
}

void start()
void startBehaviourTree()
{
assert(this->behaviour_tree != nullptr);
assert(this->car_system != nullptr);

this->tick_count = 0;
std::shared_ptr<Context> context = std::make_shared<CarContext>(CarContext(this->behaviour_tree, this->car_system));
this->context = context;
}

void update() final override
{
if (this->context == nullptr)
{
return;
}
this->context->update(this->tick_count);
++this->tick_count;
}

void stop() final override
{
this->context = nullptr;
Expand All @@ -70,13 +105,14 @@ namespace behaviour_tree
return "BehaviourTreeHandler";
}

void setBehaviourTree(std::shared_ptr<BehaviourTree> behaviour_tree) {
void _setBehaviourTree(std::shared_ptr<BehaviourTree> behaviour_tree)
{
this->behaviour_tree = behaviour_tree;
}

private:
std::shared_ptr<BehaviourTree> behaviour_tree;

std::shared_ptr<Context> context;

int tick_count = 0;
Expand Down
24 changes: 4 additions & 20 deletions app/rpi/common/include/car/system/messaging/MessagingSystem.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,6 @@

namespace car::system::messaging
{
// https://stackoverflow.com/a/46711735
static constexpr uint32_t hash(const std::string_view s) noexcept
{
uint32_t hash = 5381;

for (const char* c = s.data(); c < s.data() + s.size(); ++c)
hash = ((hash << 5) + hash) + (unsigned char)*c;

return hash;
}

class MessagingSystem
{
public:
Expand All @@ -44,26 +33,21 @@ namespace car::system::messaging
// Necessary for the reloading the configuration
void setConfiguration(std::shared_ptr<configuration::Configuration> configuration);

nod::signal<void(const std::string, const std::string)>& getCustomCommandSignal() { return this->custom_command_signal; }
nod::signal<void(const std::string)>& getHandleMessageSignal() { return this->handle_message_signal; }
nod::signal<void(const std::string, const rapidjson::Value&)>& getCommandSignal() { return this->command_signal; }
nod::signal<void(const std::string)>& getMessageSignal() { return this->message_signal; }
nod::signal<void()>& getConnectSignal() { return this->on_connect_signal; }
nod::signal<void(const std::string)>& getDisconnectSignal() { return this->on_disconnect_signal; }

void onMessageCallback(const ix::WebSocketMessagePtr& msg) const;
std::string getUUID() const { return this->uuid; }
void handleMessage(const std::string& message) const;
void handleCommand(const rapidjson::Value& message_json) const;
void sendMessage(const std::string& message);

nod::signal<void(const ix::WebSocketMessage msg)> on_websocket_message_signal;

nod::signal<void()> on_connect_signal;
nod::signal<void(std::string)> on_disconnect_signal;

nod::signal<void(const int)> speed_command_signal;
nod::signal<void(const float)> angle_command_signal;
nod::signal<void(const std::string)> handle_message_signal;
nod::signal<void(const std::string, const std::string)> custom_command_signal;
nod::signal<void(const std::string)> message_signal;
nod::signal<void(const std::string, const rapidjson::Value&)> command_signal;

private:
tl::expected<std::string, std::string> getFirstMessage();
Expand Down
87 changes: 12 additions & 75 deletions app/rpi/common/src/car/system/messaging/MessagingSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ namespace car::system::messaging
{
ix::initNetSystem();
this->setConfiguration(configuration);
this->handle_message_signal.connect([this](const std::string message)
this->message_signal.connect([this](const std::string message)
{ this->handleMessage(message); });
}

Expand Down Expand Up @@ -81,8 +81,6 @@ namespace car::system::messaging

void MessagingSystem::onMessageCallback(const ix::WebSocketMessagePtr& msg) const
{
const ix::WebSocketMessage message = *msg;
this->on_websocket_message_signal(message);
switch (msg->type)
{
case ix::WebSocketMessageType::Open:
Expand All @@ -99,7 +97,7 @@ namespace car::system::messaging
}
case ix::WebSocketMessageType::Message:
{
this->handle_message_signal(msg->str);
this->message_signal(msg->str);
break;
}
default:
Expand All @@ -111,34 +109,33 @@ namespace car::system::messaging
{
rapidjson::Document message_json;
message_json.Parse(message.c_str());

if (message_json.HasParseError() || !message_json.IsObject())
{
spdlog::error("An error has occurred while handling the message: {}", message);
return;
}

if (!message_json.HasMember("type") || !message_json["type"].IsString())
{
spdlog::error("Type does not exist in json", message);
return;
}
const std::string type = message_json["type"].GetString();
if (type == "car")
{
return;
}

const std::string type = message_json["type"].GetString();
try
{
switch (hash(type))
{
case hash("command"):
this->handleCommand(message_json);
break;
case hash("status"):
spdlog::info("Received status message");
break;
if (!message_json.HasMember("command") || !message_json["command"].IsString())
{
return;
}
this->command_signal(message, message_json);
return;
default:
break;
return;
}
}
catch (std::exception e)
Expand All @@ -147,66 +144,6 @@ namespace car::system::messaging
}
}

void MessagingSystem::handleCommand(const rapidjson::Value& message_json) const
{
if (!message_json.HasMember("command") || !message_json["command"].IsString())
{
spdlog::error("Command not found or not a string in the JSON.");
return;
}

const std::string command = message_json["command"].GetString();

switch (hash(command))
{
case hash("turn"):
{
if (message_json.HasMember("angle") && message_json["angle"].IsFloat())
{
float angle = message_json["angle"].GetFloat();
this->angle_command_signal(angle);
spdlog::info("Turning by {} angle", angle);
}
else
{
spdlog::error("Invalid or missing 'angle' in the JSON for 'turn' command.");
}
break;
}
case hash("move"):
{
if (message_json.HasMember("speed") && message_json["speed"].IsInt())
{
int speed = message_json["speed"].GetInt();
speed_command_signal(speed);
spdlog::info("Moving with {} speed", speed);
}
else
{
spdlog::error("Invalid or missing 'speed' in the JSON for 'move' command.");
}
break;
}
case hash("custom"):
{
if (message_json.HasMember("custom_type") && message_json.HasMember("custom") &&
message_json["custom_type"].IsString() && message_json["custom"].IsString())
{
const std::string custom_type = message_json["custom_type"].GetString();
const std::string custom = message_json["custom"].GetString();
this->custom_command_signal(custom_type, custom);
}
else
{
spdlog::error("Invalid or missing 'custom_type' or 'custom' in the JSON for 'custom' command.");
}
break;
}
default:
spdlog::error("Unknown command: {}", command);
}
}

void MessagingSystem::sendMessage(const std::string& message)
{
if (this->websocket != nullptr)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ namespace car::display::console::component::debug
class DebugMessagingTextbox
{
public:
DebugMessagingTextbox(nod::signal<void(const std::string)> &handle_message_signal) : handle_message_signal(handle_message_signal)
DebugMessagingTextbox(nod::signal<void(const std::string)> &message_signal) : message_signal(message_signal)
{
this->messaging_title = MenuEntry("Simulate the MessagingSystem:") | bold;

InputOption messaging_textbox_option = InputOption();
messaging_textbox_option.on_enter = [&]()
{
this->handle_message_signal(this->message);
this->message_signal(this->message);
this->message = "";
};
this->messaging_textbox = Input(&this->message, "[Enter text here and press enter to send the message!]", messaging_textbox_option) | dim;
Expand Down Expand Up @@ -52,7 +52,7 @@ namespace car::display::console::component::debug

Component messaging_container;

nod::signal<void(const std::string)> &handle_message_signal;
nod::signal<void(const std::string)> &message_signal;
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ namespace car::display::console::screen
{
public:
SettingsScreen(std::shared_ptr<CarSystem> car_system, std::shared_ptr<JsonConfiguration> json_configuration) : car_system(car_system),
debug_messaging_text_box(DebugMessagingTextbox(car_system->getMessagingSystem()->getHandleMessageSignal())),
debug_messaging_text_box(DebugMessagingTextbox(car_system->getMessagingSystem()->getMessageSignal())),
settings_edit_config(car_system, json_configuration)
{
}
Expand Down

0 comments on commit fc7d0b4

Please sign in to comment.