- Neue Kategorie Extras: Lampe in wählbarer Farbe, Laufschrift mit eigener 5-LED-Schrift (A-Z, ÄÖÜß, Ziffern, Satzzeichen, °, ♥), Uhr per NTP, Wetter von Open-Meteo (eigener Task auf Kern 0, alle 15 min) - Favoriten: bis zu 12, aus den Favoriten gestartet wechselt der Würfel nur durch sie (playFavorites) - Effekt, Autowechsel, Helligkeit, Favoriten, Lampenfarbe, Text und Ort werden 2 s nach einer Änderung im NVS gespeichert und beim Start geladen - API: neue Felder in /api/state, GET /api/weather - App: Favoriten-Zeile, langes Drücken = Favorit, Einstellungen für Lampe, Laufschrift und Wetter-Ort (Suche über Open-Meteo) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
268 lines
10 KiB
C++
268 lines
10 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
|
|
// 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
|
|
// 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["brightness"] = brightness;
|
|
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));
|
|
}
|
|
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"];
|
|
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");
|
|
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 (!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>());
|
|
settingsChanged();
|
|
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/weather", HTTP_GET, sendWeather);
|
|
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;
|
|
}
|
|
}
|