Files
cube/web.cpp
T
mikeandClaude Opus 5.5 f8360c31f6 Schalter „Alle Kategorien“: automatischer Wechsel durch alle Effekte
Neues Feld allCategories in /api/state (nach dem Einschalten false),
in der App ein zweiter Schalter unter „Automatisch wechseln“.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:28:42 +01:00

194 lines
6.8 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/categories alle Kategorien: [{"id": "flash", "name": "Flash"}, ...]
// GET /api/effects alle Effekte: [{"id": "gewitter", "name": "Gewitter", "category": "flash"}, ...]
// 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["allCategories"] = autoAll;
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["category"] = categoryId(effectCategory(i));
}
sendJson(200, doc);
}
void sendCategories() {
JsonDocument doc;
for (uint8_t c = 0; c < numCategories(); c++) {
JsonObject k = doc.add<JsonObject>();
k["id"] = categoryId(c);
k["name"] = categoryName(c);
}
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"], all = body["allCategories"], 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 (!all.isNull() && !all.is<bool>()) return sendError(400, "allCategories 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 (!all.isNull()) autoAll = all.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/categories", HTTP_GET, sendCategories);
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;
}
}