// 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 #include #include #include #include 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(); 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(); 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(); 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()) 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()) return sendError(400, "effect muss eine Effekt-id sein, siehe /api/effects"); index = findEffect(effect.as()); if (index < 0) return sendError(400, "unbekannter Effekt, siehe /api/effects"); } if (!autoOn.isNull() && !autoOn.is()) return sendError(400, "auto muss true oder false sein"); if (!all.isNull() && !all.is()) return sendError(400, "allCategories muss true oder false sein"); if (!level.isNull() && !(level.is() && level.as() >= 0 && level.as() <= 255)) return sendError(400, "brightness muss eine ganze Zahl von 0 bis 255 sein"); if (!playFav.isNull() && !playFav.is()) return sendError(400, "playFavorites muss true oder false sein"); if (!manual.isNull() && !manual.is()) return sendError(400, "manual muss true oder false sein"); if (!param.isNull() && !(param.is() && param.as() >= 0 && param.as() <= 255)) return sendError(400, "param muss eine ganze Zahl von 0 bis 255 sein"); if (!param2.isNull() && !(param2.is() && param2.as() >= 0 && param2.as() <= 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()) 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()) { int i = f.is() ? findEffect(f.as()) : -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() && parseColor(lamp.as(), lampNew))) return sendError(400, "lampColor muss eine Farbe wie \"#ffa03c\" sein"); if (!text.isNull() && !(text.is() && strlen(text.as()) <= 100)) return sendError(400, "text muss ein String mit höchstens 100 Byte sein (Umlaute zählen doppelt)"); if (!place.isNull()) { if (!place.is() || strlen(place.as()) > 47) return sendError(400, "place muss ein String mit höchstens 47 Byte sein"); if (place.as()[0] && !(lat.is() && lon.is() && fabsf(lat.as()) <= 90 && fabsf(lon.as()) <= 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()); // gilt für den (neu gewählten) Effekt if (!param2.isNull()) setEffectParam(currentEffect(), 1, param2.as()); if (!autoOn.isNull()) autoAdvance = autoOn.as(); if (!all.isNull()) autoAll = all.as(); if (!level.isNull()) setBaseBrightness(level.as()); if (!playFav.isNull()) playFavorites = playFav.as(); if (!favs.isNull()) setFavorites(favList, favCount); if (!lamp.isNull()) lampColor = lampNew; if (!text.isNull()) tickerText = text.as(); if (!place.isNull()) setLocation(place.as(), lat.as(), lon.as()); if (!manual.isNull()) setManual(manual.as()); settingsChanged(); sendState(); } void sendPixels() { JsonDocument doc; doc["manual"] = manualMode; JsonArray pixels = doc["pixels"].to(); 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()) return sendError(400, "JSON-Objekt erwartet"); JsonVariant pixels = body["pixels"], fill = body["fill"]; CRGB fillColor; if (!fill.isNull() && !(fill.is() && parseColor(fill.as(), 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() || 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()) { if (!(p.is() && parseColor(p.as(), 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()) 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()) { JsonVariant x = p["x"], y = p["y"], z = p["z"], color = p["color"]; if (!(x.is() && y.is() && z.is() && x.as() >= 0 && y.as() >= 0 && z.as() >= 0 && x.as() < CUBE_SIZE && y.as() < CUBE_SIZE && z.as() < NUM_LAYERS)) return sendError(400, "pixels: x, y und z müssen ganze Zahlen von 0 bis 4 sein"); if (!(color.is() && parseColor(color.as(), frame[count]))) return sendError(400, "pixels: color muss eine Farbe wie \"#ff0000\" sein"); where[count][0] = x.as(); where[count][1] = y.as(); where[count][2] = z.as(); 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; } }