Files
mikeandClaude Opus 5.5 5aa33cc73c App: „Effekt 1“, kleine Reset-Knöpfe an den Effekt-Reglern, flache Spezialeffekt-Knöpfe
Reset per Knopf ↺ statt Antippen des Titels; Blitz, Explosion und
Regenbogen als flache Knöpfe mit Symbol und Text in einer Zeile.
In Firmware und Doku heißt der erste Regler ebenfalls „Effekt 1“.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:18:32 +01:00

360 lines
15 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, z. B.
// {"effect": "feuer", "auto": false, "brightness": 64}
// (alle Felder in docs/api.md); wird im Flash gespeichert
// "param"/"param2": 0..255 = Regler "Effekt 1"/"Effekt 2" des laufenden Effekts
// GET /api/categories alle Kategorien: [{"id": "flash", "name": "Flash"}, ...]
// GET /api/effects alle Effekte: [{"id": "gewitter", "name": "Gewitter", "category": "natur"}, ...]
// GET /api/weather zuletzt abgerufenes Wetter am eingestellten Ort
// GET /api/pixels Bild des manuellen Modus: {"manual": true, "pixels": ["#rrggbb", ...]}
// PUT /api/pixels alle 125 Pixel: {"pixels": ["#ff0000", ...]}, Index x + 5*y + 25*z
// PATCH /api/pixels einzelne Pixel: {"fill": "#000000", "pixels": [{"x": 0, "y": 0, "z": 0, "color": "#ff0000"}]}
// Beide schalten den manuellen Modus ein (Effekt wählen beendet ihn).
// 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["playFavorites"] = playFavorites;
doc["manual"] = manualMode;
doc["brightness"] = brightness;
doc["param"] = effectParam(currentEffect(), 0);
doc["param2"] = effectParam(currentEffect(), 1);
JsonArray favs = doc["favorites"].to<JsonArray>();
for (uint8_t k = 0; k < numFavorites(); k++) favs.add(effectId(favorite(k)));
char hex[8];
snprintf(hex, sizeof(hex), "#%02x%02x%02x", lampColor.r, lampColor.g, lampColor.b);
doc["lampColor"] = hex;
doc["text"] = tickerText;
char place[48];
float lat, lon;
if (getLocation(place, sizeof(place), lat, lon)) {
doc["place"] = place;
doc["latitude"] = lat;
doc["longitude"] = lon;
} else {
doc["place"] = "";
}
sendJson(200, doc);
}
void sendWeather() {
JsonDocument doc;
char place[48];
float lat, lon;
doc["place"] = getLocation(place, sizeof(place), lat, lon) ? place : "";
WeatherInfo w = weatherNow();
if (w.valid) {
doc["temperature"] = w.temperature;
doc["code"] = w.code;
doc["isDay"] = w.isDay;
doc["age"] = (millis() - w.updated) / 1000; // Sekunden seit dem Abruf
}
sendJson(200, doc);
}
// "#rrggbb" -> Farbe
bool parseColor(const char *s, CRGB &color) {
if (strlen(s) != 7 || s[0] != '#') return false;
for (uint8_t i = 1; i < 7; i++)
if (!isxdigit(s[i])) return false;
uint32_t v = strtoul(s + 1, nullptr, 16);
color = CRGB(v);
return true;
}
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));
e["param"] = effectParamName(i, 0);
e["param2"] = effectParamName(i, 1);
}
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);
}
// 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"];
JsonVariant playFav = body["playFavorites"], favs = body["favorites"], lamp = body["lampColor"], text = body["text"];
JsonVariant place = body["place"], lat = body["latitude"], lon = body["longitude"], manual = body["manual"];
JsonVariant param = body["param"], param2 = body["param2"];
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 (!playFav.isNull() && !playFav.is<bool>()) return sendError(400, "playFavorites muss true oder false sein");
if (!manual.isNull() && !manual.is<bool>()) return sendError(400, "manual muss true oder false sein");
if (!param.isNull() && !(param.is<int>() && param.as<int>() >= 0 && param.as<int>() <= 255))
return sendError(400, "param muss eine ganze Zahl von 0 bis 255 sein");
if (!param2.isNull() && !(param2.is<int>() && param2.as<int>() >= 0 && param2.as<int>() <= 255))
return sendError(400, "param2 muss eine ganze Zahl von 0 bis 255 sein");
uint8_t favList[MAX_FAVORITES], favCount = 0;
if (!favs.isNull()) {
if (!favs.is<JsonArray>()) return sendError(400, "favorites muss eine Liste von Effekt-ids sein");
if (favs.size() > MAX_FAVORITES) return sendError(400, "höchstens 12 Favoriten");
for (JsonVariant f : favs.as<JsonArray>()) {
int i = f.is<const char *>() ? findEffect(f.as<const char *>()) : -1;
if (i < 0) return sendError(400, "favorites enthält eine unbekannte Effekt-id, siehe /api/effects");
for (uint8_t k = 0; k < favCount; k++)
if (favList[k] == i) return sendError(400, "favorites enthält einen Effekt doppelt");
favList[favCount++] = i;
}
}
CRGB lampNew;
if (!lamp.isNull() && !(lamp.is<const char *>() && parseColor(lamp.as<const char *>(), lampNew)))
return sendError(400, "lampColor muss eine Farbe wie \"#ffa03c\" sein");
if (!text.isNull() && !(text.is<const char *>() && strlen(text.as<const char *>()) <= 100))
return sendError(400, "text muss ein String mit höchstens 100 Byte sein (Umlaute zählen doppelt)");
if (!place.isNull()) {
if (!place.is<const char *>() || strlen(place.as<const char *>()) > 47)
return sendError(400, "place muss ein String mit höchstens 47 Byte sein");
if (place.as<const char *>()[0] &&
!(lat.is<float>() && lon.is<float>() && fabsf(lat.as<float>()) <= 90 && fabsf(lon.as<float>()) <= 180))
return sendError(400, "zu place gehören latitude (-90 bis 90) und longitude (-180 bis 180)");
} else if (!lat.isNull() || !lon.isNull()) {
return sendError(400, "latitude und longitude nur zusammen mit place");
}
if (index >= 0) selectEffect(index);
if (!param.isNull()) setEffectParam(currentEffect(), 0, param.as<int>()); // gilt für den (neu gewählten) Effekt
if (!param2.isNull()) setEffectParam(currentEffect(), 1, param2.as<int>());
if (!autoOn.isNull()) autoAdvance = autoOn.as<bool>();
if (!all.isNull()) autoAll = all.as<bool>();
if (!level.isNull()) setBaseBrightness(level.as<int>());
if (!playFav.isNull()) playFavorites = playFav.as<bool>();
if (!favs.isNull()) setFavorites(favList, favCount);
if (!lamp.isNull()) lampColor = lampNew;
if (!text.isNull()) tickerText = text.as<const char *>();
if (!place.isNull()) setLocation(place.as<const char *>(), lat.as<float>(), lon.as<float>());
if (!manual.isNull()) setManual(manual.as<bool>());
settingsChanged();
sendState();
}
void sendPixels() {
JsonDocument doc;
doc["manual"] = manualMode;
JsonArray pixels = doc["pixels"].to<JsonArray>();
char hex[8];
for (uint8_t z = 0; z < NUM_LAYERS; z++)
for (uint8_t y = 0; y < CUBE_SIZE; y++)
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
const CRGB &c = manualFrame[z][y][x];
snprintf(hex, sizeof(hex), "#%02x%02x%02x", c.r, c.g, c.b);
pixels.add(hex);
}
sendJson(200, doc);
}
// PUT (full): alle 125 Pixel als Liste von Farben. PATCH: erst "fill", dann
// einzelne Pixel mit x, y, z. Wie bei /api/state erst alles prüfen, dann übernehmen.
// Absichtlich nicht im Flash gespeichert: ein Skript darf viele Bilder pro Sekunde schicken.
void updatePixels(bool full) {
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 pixels = body["pixels"], fill = body["fill"];
CRGB fillColor;
if (!fill.isNull() && !(fill.is<const char *>() && parseColor(fill.as<const char *>(), fillColor)))
return sendError(400, "fill muss eine Farbe wie \"#000000\" sein");
static CRGB frame[NUM_LEDS]; // neues Bild (PUT) bzw. neue Pixelfarben (PATCH)
static uint8_t where[NUM_LEDS][3];
uint8_t count = 0;
if (full) {
if (!pixels.is<JsonArray>() || pixels.size() != NUM_LEDS)
return sendError(400, "pixels muss eine Liste mit 125 Farben sein, Index x + 5*y + 25*z");
for (JsonVariant p : pixels.as<JsonArray>()) {
if (!(p.is<const char *>() && parseColor(p.as<const char *>(), frame[count])))
return sendError(400, "pixels: jede Farbe wie \"#ff0000\"");
count++;
}
} else {
if (pixels.isNull() && fill.isNull()) return sendError(400, "pixels oder fill angeben");
if (!pixels.isNull()) {
if (!pixels.is<JsonArray>()) return sendError(400, "pixels muss eine Liste von {x, y, z, color} sein");
if (pixels.size() > NUM_LEDS) return sendError(400, "höchstens 125 Pixel pro Anfrage");
for (JsonVariant p : pixels.as<JsonArray>()) {
JsonVariant x = p["x"], y = p["y"], z = p["z"], color = p["color"];
if (!(x.is<int>() && y.is<int>() && z.is<int>() && x.as<int>() >= 0 && y.as<int>() >= 0 && z.as<int>() >= 0 &&
x.as<int>() < CUBE_SIZE && y.as<int>() < CUBE_SIZE && z.as<int>() < NUM_LAYERS))
return sendError(400, "pixels: x, y und z müssen ganze Zahlen von 0 bis 4 sein");
if (!(color.is<const char *>() && parseColor(color.as<const char *>(), frame[count])))
return sendError(400, "pixels: color muss eine Farbe wie \"#ff0000\" sein");
where[count][0] = x.as<int>();
where[count][1] = y.as<int>();
where[count][2] = z.as<int>();
count++;
}
}
}
if (full) {
memcpy(manualFrame, frame, sizeof(manualFrame)); // gleiche Reihenfolge: [z][y][x]
} else {
if (!manualMode) fill_solid(&manualFrame[0][0][0], NUM_LEDS, CRGB::Black); // neu: leeres Bild
if (!fill.isNull()) fill_solid(&manualFrame[0][0][0], NUM_LEDS, fillColor);
for (uint8_t k = 0; k < count; k++) manualFrame[where[k][2]][where[k][1]][where[k][0]] = frame[k];
}
setManual(true);
server.send(204);
}
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/weather", HTTP_GET, sendWeather);
server.on("/api/pixels", HTTP_GET, sendPixels);
server.on("/api/pixels", HTTP_PUT, [] { updatePixels(true); });
server.on("/api/pixels", HTTP_PATCH, [] { updatePixels(false); });
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();
configTzTime(TIMEZONE, "pool.ntp.org"); // Uhrzeit für die Uhr, sobald das WLAN steht
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;
}
}