ESP32-S3-Firmware mit 18 Effekten, Mikrofon (Klatschen, Beat, Spektrum) und REST-API, Testprogramme, SwiftUI-Fernbedienung und OpenSCAD-Sockel. Die WLAN-Zugangsdaten (secrets.h) sind nicht enthalten. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
179 lines
6.2 KiB
C++
179 lines
6.2 KiB
C++
// WLAN und REST-API (JSON), erreichbar unter http://cube.local oder per IP.
|
|
// Suchen und Verbinden laufen ohne Blockieren, die Animation läuft weiter.
|
|
//
|
|
// GET /api/state aktueller Zustand
|
|
// PUT/PATCH /api/state ändern, alle Felder optional:
|
|
// {"effect": "feuer", "auto": false, "brightness": 64}
|
|
// GET /api/effects alle Effekte: [{"id": "gewitter", "name": "Gewitter", "music": false}, ...]
|
|
// POST /api/specials/{id} Spezialeffekt auslösen: blitz, explosion, regenbogen
|
|
// POST /api/lightning Blitz auslösen (wie /api/specials/blitz)
|
|
//
|
|
// Anfragen mit Body brauchen "Content-Type: application/json".
|
|
// Fehler antworten mit 4xx und {"error": "..."}.
|
|
|
|
#include "cube.h"
|
|
#include "secrets.h"
|
|
#include <WiFi.h>
|
|
#include <WebServer.h>
|
|
#include <ESPmDNS.h>
|
|
#include <ArduinoJson.h>
|
|
#include <uri/UriBraces.h>
|
|
|
|
WebServer server(80);
|
|
|
|
enum WifiState { WIFI_IDLE, WIFI_SCANNING, WIFI_CONNECTING, WIFI_ONLINE };
|
|
WifiState wifiState = WIFI_IDLE;
|
|
uint32_t wifiSince = 0;
|
|
|
|
void sendJson(int code, const JsonDocument &doc) {
|
|
String out;
|
|
serializeJson(doc, out);
|
|
server.send(code, "application/json", out);
|
|
}
|
|
|
|
void sendError(int code, const char *message) {
|
|
JsonDocument doc;
|
|
doc["error"] = message;
|
|
sendJson(code, doc);
|
|
}
|
|
|
|
void sendState() {
|
|
JsonDocument doc;
|
|
doc["effect"] = effectId(currentEffect());
|
|
doc["auto"] = autoAdvance;
|
|
doc["brightness"] = brightness;
|
|
sendJson(200, doc);
|
|
}
|
|
|
|
void sendEffects() {
|
|
JsonDocument doc;
|
|
for (uint8_t i = 0; i < numEffects(); i++) {
|
|
JsonObject e = doc.add<JsonObject>();
|
|
e["id"] = effectId(i);
|
|
e["name"] = effectName(i);
|
|
e["music"] = effectIsMusic(i);
|
|
}
|
|
sendJson(200, doc);
|
|
}
|
|
|
|
int findEffect(const char *id) {
|
|
for (uint8_t i = 0; i < numEffects(); i++)
|
|
if (strcmp(id, effectId(i)) == 0) return i;
|
|
return -1;
|
|
}
|
|
|
|
// Erst alles prüfen, dann übernehmen: eine fehlerhafte Anfrage ändert nichts.
|
|
void updateState() {
|
|
// Ohne "Content-Type: application/json" zerlegt der Webserver den Body als Formular
|
|
if (!server.hasArg("plain")) return sendError(415, "Body als JSON mit Content-Type: application/json senden");
|
|
JsonDocument body;
|
|
if (deserializeJson(body, server.arg("plain")) || !body.is<JsonObject>())
|
|
return sendError(400, "JSON-Objekt erwartet");
|
|
|
|
JsonVariant effect = body["effect"], autoOn = body["auto"], level = body["brightness"];
|
|
int index = -1;
|
|
if (!effect.isNull()) {
|
|
if (!effect.is<const char *>()) return sendError(400, "effect muss eine Effekt-id sein, siehe /api/effects");
|
|
index = findEffect(effect.as<const char *>());
|
|
if (index < 0) return sendError(400, "unbekannter Effekt, siehe /api/effects");
|
|
}
|
|
if (!autoOn.isNull() && !autoOn.is<bool>()) return sendError(400, "auto muss true oder false sein");
|
|
if (!level.isNull() && !(level.is<int>() && level.as<int>() >= 0 && level.as<int>() <= 255))
|
|
return sendError(400, "brightness muss eine ganze Zahl von 0 bis 255 sein");
|
|
|
|
if (index >= 0) selectEffect(index);
|
|
if (!autoOn.isNull()) autoAdvance = autoOn.as<bool>();
|
|
if (!level.isNull()) setBaseBrightness(level.as<int>());
|
|
sendState();
|
|
}
|
|
|
|
void webBegin() {
|
|
WiFi.setHostname("cube");
|
|
WiFi.mode(WIFI_STA);
|
|
#if CONFIG_IDF_TARGET_ESP32C3
|
|
WiFi.setTxPower(WIFI_POWER_8_5dBm); // viele C3-SuperMini verbinden sich sonst schlecht (Antenne)
|
|
#endif
|
|
|
|
server.on("/api/state", HTTP_GET, sendState);
|
|
server.on("/api/state", HTTP_PUT, updateState);
|
|
server.on("/api/state", HTTP_PATCH, updateState);
|
|
server.on("/api/effects", HTTP_GET, sendEffects);
|
|
server.on("/api/lightning", HTTP_POST, [] {
|
|
triggerLightning(millis());
|
|
server.send(204);
|
|
});
|
|
server.on(UriBraces("/api/specials/{}"), HTTP_POST, [] {
|
|
String id = server.pathArg(0);
|
|
if (id == "blitz") triggerLightning(millis());
|
|
else if (id == "explosion") triggerExplosion(millis());
|
|
else if (id == "regenbogen") triggerRainbowWave(millis());
|
|
else return sendError(404, "unbekannter Spezialeffekt: blitz, explosion oder regenbogen");
|
|
server.send(204);
|
|
});
|
|
server.onNotFound([] { sendError(404, "unbekannter Pfad oder Methode"); });
|
|
server.begin();
|
|
WiFi.onEvent([](WiFiEvent_t e, WiFiEventInfo_t info) {
|
|
if (e == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) Serial.printf("WLAN: getrennt (Grund %u)\n", info.wifi_sta_disconnected.reason);
|
|
});
|
|
}
|
|
|
|
void webUpdate(uint32_t now) {
|
|
switch (wifiState) {
|
|
case WIFI_IDLE: // (erneut) nach Netzen suchen, im Hintergrund
|
|
if (now - wifiSince >= 5000 || wifiSince == 0) {
|
|
WiFi.scanNetworks(true);
|
|
wifiState = WIFI_SCANNING;
|
|
}
|
|
break;
|
|
|
|
case WIFI_SCANNING: {
|
|
int16_t n = WiFi.scanComplete();
|
|
if (n == WIFI_SCAN_RUNNING) break;
|
|
int8_t best = -1;
|
|
int32_t bestRssi = -1000;
|
|
for (int16_t i = 0; i < n; i++)
|
|
for (uint8_t k = 0; k < sizeof(WLANS) / sizeof(WLANS[0]); k++)
|
|
if (WiFi.SSID(i) == WLANS[k].ssid && WiFi.RSSI(i) > bestRssi) {
|
|
best = k;
|
|
bestRssi = WiFi.RSSI(i);
|
|
}
|
|
WiFi.scanDelete();
|
|
wifiSince = now;
|
|
if (best < 0) {
|
|
wifiState = WIFI_IDLE;
|
|
break;
|
|
}
|
|
Serial.printf("WLAN: verbinde mit %s (%ld dBm)\n", WLANS[best].ssid, (long)bestRssi);
|
|
WiFi.begin(WLANS[best].ssid, WLANS[best].pass);
|
|
wifiState = WIFI_CONNECTING;
|
|
break;
|
|
}
|
|
|
|
case WIFI_CONNECTING:
|
|
if (WiFi.status() == WL_CONNECTED) {
|
|
static bool mdns = false;
|
|
if (!mdns && MDNS.begin("cube")) {
|
|
MDNS.addService("http", "tcp", 80);
|
|
mdns = true;
|
|
}
|
|
Serial.printf("WLAN: verbunden, REST-API unter http://%s/api/state oder http://cube.local/api/state\n", WiFi.localIP().toString().c_str());
|
|
wifiState = WIFI_ONLINE;
|
|
} else if (now - wifiSince > 15000) {
|
|
Serial.println("WLAN: Verbindung fehlgeschlagen, suche erneut");
|
|
WiFi.disconnect();
|
|
wifiSince = now;
|
|
wifiState = WIFI_IDLE;
|
|
}
|
|
break;
|
|
|
|
case WIFI_ONLINE:
|
|
if (WiFi.status() != WL_CONNECTED) {
|
|
Serial.println("WLAN: Verbindung verloren");
|
|
wifiSince = now;
|
|
wifiState = WIFI_CONNECTING; // automatische Wiederverbindung abwarten, sonst neu suchen
|
|
}
|
|
server.handleClient();
|
|
break;
|
|
}
|
|
}
|