esp8266-led-marquee-sign-co.../src/webserver.h
Fabian Müller 1d23e6cfef Add HTTP API endpoint for raw messages
RESTful version of simple socket listener.
2024-04-12 11:59:20 +02:00

94 lines
2.4 KiB
C

#pragma once
#include "util.h"
static ESP8266WebServer webServer(80);
// use an anonymous namespace for the module's "private" methods
// this prevents the methods from ending up in the global namespace
namespace {
void handleNotFound() {
webServer.send(404, "text/plain", "urm... nope");
}
void handleIndex() {
String htmlText = R"(
<!DOCTYPE html>
<html>
<head>
<title>LED Marquee Sign Controller</title>
</head>
<body>
<h1>LED Marquee Sign Controller</h1>
<form action="/" method="post">
<fieldset>
<div>
<label for="text">Text to send:</label>
<input type="text" name="text">
</div>
<div>
<button>Send</button>
</div>
</fieldset>
</form>
</body>
</html>
)";
webServer.send(200, "text/html", htmlText);
}
void handleFormSend() {
String text = webServer.arg("text");
if (text.isEmpty()) {
webServer.send(404, "text/plain", "empty text");
return;
}
sendTextToSign(text);
// redirect back to root page
webServer.sendHeader("Location", "/");
webServer.send(303);
}
// RESTful API endpoint -- returns a proper status code rather than a redirect
void handleApiSend() {
String text = webServer.arg("text");
if (text.isEmpty()) {
webServer.send(404, "text/plain", "empty text");
return;
}
sendTextToSign(text);
webServer.send(200, "text/plain", "ok");
}
// RESTful API endpoint -- returns a proper status code rather than a redirect
void handleRawApiSend() {
String toSend = webServer.arg("plain");
if (toSend.isEmpty()) {
webServer.send(404, "text/plain", "empty body");
return;
}
Serial.println("Raw message sent to device: " + toSend);
Serial.println("Hex dump: " + hexDump(toSend));
Serial1.print(toSend);
webServer.send(200, "text/plain", "ok");
}
}
void configureWebServer() {
webServer.onNotFound(handleNotFound);
webServer.on("/", HTTPMethod::HTTP_GET, handleIndex);
webServer.on("/", HTTPMethod::HTTP_POST, handleFormSend);
webServer.on("/send", HTTPMethod::HTTP_POST, handleApiSend);
webServer.on("/raw", HTTPMethod::HTTP_POST, handleRawApiSend);
}