#include "esp32FirewallAPI.hpp" esp32FirewallApi::esp32FirewallApi(const uint16_t port) { this->setup_certificate(); this->server = new HTTPSServer(this->certificate, port, 5); this->setup_routing(); log_i("Starting server..."); this->server->start(); if (this->server->isRunning()) { log_i("Server ready."); } } void esp32FirewallApi::handle_clients() { this->server->loop(); } void esp32FirewallApi::setup_certificate() { log_i("Creating the certificate..."); this->certificate = new SSLCert(); int createCertResult = createSelfSignedCert( *this->certificate, KEYSIZE_2048, "CN=myesp32.local,O=Firewall,C=DE", "20220101000000", "20320101000000"); if (createCertResult != 0) { log_e("Cerating certificate failed. Error Code = 0x%02X, check SSLCert.hpp for details", createCertResult); while (true) delay(500); } log_i("Creating the certificate was successful"); } void esp32FirewallApi::setup_routing() { ResourceNode *restart_device = new ResourceNode("/api/v1/device/restart", "GET", std::bind(&esp32FirewallApi::restart_device_handler, this, std::placeholders::_1, std::placeholders::_2)); ResourceNode *not_found = new ResourceNode("", "GET", std::bind(&esp32FirewallApi::not_found_handler, this, std::placeholders::_1, std::placeholders::_2)); this->server->registerNode(restart_device); this->server->setDefaultNode(not_found); } void esp32FirewallApi::restart_device_handler(HTTPRequest *request, HTTPResponse *response) { this->json_message_response(response, "restarting device in 2 sec", 200); sleep(2000); esp_restart(); } void esp32FirewallApi::not_found_handler(HTTPRequest *request, HTTPResponse *response) { this->json_message_response(response, "not found", 404); } void esp32FirewallApi::json_generic_response(HTTPResponse *response, String serialized, const uint16_t response_code) { response->setHeader("Content-Type", "application/json"); response->setStatusCode(response_code); response->println(serialized); } void esp32FirewallApi::json_message_response(HTTPResponse *response, String message, const uint16_t response_code) { response->setHeader("Content-Type", "application/json"); response->setStatusCode(response_code); StaticJsonDocument<96> json; String serialized; json["message"] = message; serializeJson(json, serialized); response->println(serialized); }