From 3851702254f156324db809389dbba2df3ff0f739 Mon Sep 17 00:00:00 2001 From: "Denis V. Dedkov" Date: Wed, 29 May 2024 15:21:30 +0200 Subject: [PATCH] Routing was implemented --- main.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/main.cpp b/main.cpp index 7ae4fa9..dac1137 100644 --- a/main.cpp +++ b/main.cpp @@ -6,6 +6,7 @@ namespace App { constexpr auto DefaultPort = 8888; constexpr auto DefaultHost = "0.0.0.0"; +constexpr auto ContentType = "application/json"; static httplib::Server *srv = nullptr; @@ -28,15 +29,57 @@ int main(int argc, char *argv[]) App::srv = new httplib::Server(); - App::srv->Get("/", [](const httplib::Request &, httplib::Response &res) { + const std::map< std::string, noolitelib::Command > commands = { + { "off", noolitelib::Off }, + { "decraseBrightnes", noolitelib::DecraseBrightnes }, + { "on", noolitelib::DecraseBrightnes }, + { "incraseBrightnes", noolitelib::IncreaseBrightnes }, + { "switch", noolitelib::Switch }, + { "invertBrightnes", noolitelib::InvertBrightnes }, + { "set", noolitelib::Set }, + { "callScenario", noolitelib::CallScenario }, + { "saveScenario", noolitelib::SaveScenario }, + { "unbind", noolitelib::Unbind }, + { "stopColorSelection", noolitelib::StopColorSelection }, + { "bind", noolitelib::Bind }, + { "colorSelection", noolitelib::ColorSelection }, + { "colorSwitch", noolitelib::ColorSwitch }, + { "modeSwitch", noolitelib::ModeSwitch }, + { "effectSpeed", noolitelib::EffectSpeed } + }; + + App::srv->Get("/noolite/:command/:channel", [&commands](const httplib::Request &req, httplib::Response &res) { + + auto formatResult = [](bool successful, const std::string &text) -> std::string { + std::stringstream res; + res << "{\"" << (successful ? "result" : "error") + << "\":\"" << (successful ? "ok" : text) << "\""; + if (successful) { + res << (",\"command\":\"" + text + "\""); + } + res << "}"; + + return res.str(); + }; + + auto command = req.path_params.at("command"); + if (!commands.count(command)) { + res.set_content(formatResult(false, "Command not found"), App::ContentType); + return; + } + + auto channel = req.path_params.at("channel"); + noolitelib::Noolite adapter; if (adapter.sendCommand(0, noolitelib::Switch)) { - res.set_content("{\"Result\":\"Successful\"}", "application/json"); + res.set_content(formatResult(true, command + " " + channel), App::ContentType); } else { - res.set_content("{\"Result\":\"Failed\"}", "application/json"); + res.set_content(formatResult(false, "Device error"), App::ContentType); } }); + App::srv->set_mount_point("/var/www/static", "/static"); + auto host = App::DefaultHost; auto port = App::DefaultPort; @@ -47,6 +90,8 @@ int main(int argc, char *argv[]) port = atoi(argv[2]); } + std::cout << "Listen on " << host << ":" << port << std::endl; + App::srv->listen(host, port); return 0;