| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- #include <iostream>
- #include <httplib.h>
- #include <noolite.h>
- namespace App {
- constexpr auto DefaultPort = 8888;
- constexpr auto DefaultHost = "0.0.0.0";
- constexpr auto ContentType = "application/json";
- static httplib::Server *srv = nullptr;
- }
- void signalHandler(int signum) {
- std::cout << "\n\nInterrupt signal (" << signum << ") received.\n";
- if (App::srv) {
- App::srv->stop();
- delete App::srv;
- }
- exit(signum);
- }
- int main(int argc, char *argv[])
- {
- std::signal(SIGINT, signalHandler);
- App::srv = new httplib::Server();
- 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(std::stoi(channel), noolitelib::Switch)) {
- res.set_content(formatResult(true, command + " " + channel), App::ContentType);
- } else {
- 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;
- if (argc > 1) {
- host = argv[1];
- }
- if (argc > 2) {
- port = atoi(argv[2]);
- }
- std::cout << "Listen on " << host << ":" << port << std::endl;
- App::srv->listen(host, port);
- return 0;
- }
|