Shelly-Skript meldet nach eigenem Schalten sofort erneut, damit die Statusseite nicht bis zu 10 Minuten hinterherhängt. Schlüssel aus dem Skript in die ignorierte Datei shelly/heizung.key ausgelagert. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
681 lines
22 KiB
C++
681 lines
22 KiB
C++
// Heizungspumpe – lokale Steuerung mit Web-App, Benutzerverwaltung und Zeitplan.
|
||
// Erreichbar im Heimnetz bzw. per WireGuard-VPN unter http://heizung-pumpe.fritz.box
|
||
//
|
||
// API (JSON, Anmeldung per Cookie "session"):
|
||
// POST /api/login {"user","pass"}
|
||
// POST /api/logout
|
||
// GET /api/state Zustand, Zeitplan, angemeldeter Benutzer
|
||
// POST /api/cmd {"action":"on"|"off"|"auto","minutes":120} minutes optional
|
||
// POST /api/schedule {"windows":[{"days":31,"on":"06:00","off":"22:00"}]}
|
||
// POST /api/password {"old","new"} eigenes Passwort ändern
|
||
// GET /api/users (nur Admin)
|
||
// POST /api/users {"user","pass","admin"} anlegen/ändern (nur Admin)
|
||
// POST /api/users/delete {"user"} (nur Admin)
|
||
// days: Bitmaske, Bit 0 = Montag ... Bit 6 = Sonntag. on > off = über Mitternacht.
|
||
|
||
#include <Arduino.h>
|
||
#include <WiFi.h>
|
||
#include <WebServer.h>
|
||
#include <ArduinoOTA.h>
|
||
#include <ArduinoJson.h>
|
||
#include <Preferences.h>
|
||
#include <esp_system.h>
|
||
#include <mbedtls/md.h>
|
||
#include <mbedtls/pkcs5.h>
|
||
#include <time.h>
|
||
#include <vector>
|
||
|
||
#include "config.h"
|
||
#include "secrets.h"
|
||
|
||
// Eingebettete Web-App (board_build.embed_txtfiles in platformio.ini)
|
||
extern const char WEB_INDEX[] asm("_binary_web_index_html_start");
|
||
extern const char WEB_APP_JS[] asm("_binary_web_app_js_start");
|
||
extern const char WEB_STYLE[] asm("_binary_web_style_css_start");
|
||
extern const char WEB_ICON[] asm("_binary_web_icon_svg_start");
|
||
extern const char WEB_MANIFEST[] asm("_binary_web_manifest_webmanifest_start");
|
||
|
||
struct Window {
|
||
uint8_t days; // Bit 0 = Montag
|
||
uint16_t on; // Minuten seit Mitternacht
|
||
uint16_t off;
|
||
};
|
||
|
||
struct User {
|
||
String name;
|
||
String salt;
|
||
String hash;
|
||
bool admin;
|
||
};
|
||
|
||
enum class Mode : uint8_t { Auto = 0, On = 1, Off = 2 };
|
||
|
||
static Window windows[MAX_WINDOWS];
|
||
static uint8_t windowCount = 0;
|
||
|
||
static Mode mode = Mode::Auto;
|
||
static time_t manualUntil = 0; // 0 = unbegrenzt
|
||
static bool relayOn = false;
|
||
static const char* reason = "start";
|
||
|
||
static String lastBy;
|
||
static String lastAction;
|
||
static time_t lastAt = 0;
|
||
|
||
static std::vector<User> users;
|
||
static uint8_t tokenSecret[32];
|
||
|
||
static WebServer server(80);
|
||
static Preferences prefs;
|
||
|
||
static bool timeValid() { return time(nullptr) > 1700000000; }
|
||
|
||
static const char* modeName(Mode m) {
|
||
switch (m) {
|
||
case Mode::On: return "on";
|
||
case Mode::Off: return "off";
|
||
default: return "auto";
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Zeitplan
|
||
// ---------------------------------------------------------------------------
|
||
|
||
static int parseHhmm(const char* s) {
|
||
int h, m;
|
||
if (!s || sscanf(s, "%d:%d", &h, &m) != 2) return -1;
|
||
if (h < 0 || h > 24 || m < 0 || m > 59 || (h == 24 && m != 0)) return -1;
|
||
return h * 60 + m;
|
||
}
|
||
|
||
static void formatHhmm(uint16_t minutes, char* out) {
|
||
snprintf(out, 6, "%02u:%02u", minutes / 60, minutes % 60);
|
||
}
|
||
|
||
// Liest {"windows":[...]} ein. Bei Fehler bleibt der alte Zeitplan erhalten.
|
||
static bool loadWindows(JsonVariantConst src, String& error) {
|
||
JsonArrayConst arr = src["windows"].as<JsonArrayConst>();
|
||
if (arr.isNull()) { error = "windows fehlt"; return false; }
|
||
if (arr.size() > MAX_WINDOWS) { error = "zu viele Zeitfenster"; return false; }
|
||
|
||
Window tmp[MAX_WINDOWS];
|
||
uint8_t n = 0;
|
||
for (JsonObjectConst w : arr) {
|
||
int days = w["days"] | -1;
|
||
int on = parseHhmm(w["on"]);
|
||
int off = parseHhmm(w["off"]);
|
||
if (days < 0 || days > 127 || on < 0 || off < 0) { error = "ungültiges Zeitfenster"; return false; }
|
||
tmp[n++] = {(uint8_t)days, (uint16_t)(on % 1440), (uint16_t)(off % 1440)};
|
||
}
|
||
memcpy(windows, tmp, sizeof(Window) * n);
|
||
windowCount = n;
|
||
return true;
|
||
}
|
||
|
||
static void scheduleToJson(JsonArray arr) {
|
||
char buf[6];
|
||
for (uint8_t i = 0; i < windowCount; i++) {
|
||
JsonObject o = arr.add<JsonObject>();
|
||
o["days"] = windows[i].days;
|
||
formatHhmm(windows[i].on, buf);
|
||
o["on"] = buf;
|
||
formatHhmm(windows[i].off, buf);
|
||
o["off"] = buf;
|
||
}
|
||
}
|
||
|
||
static bool scheduleActive(const tm& t) {
|
||
int today = (t.tm_wday + 6) % 7; // 0 = Montag
|
||
int yesterday = (today + 6) % 7;
|
||
int now = t.tm_hour * 60 + t.tm_min;
|
||
for (uint8_t i = 0; i < windowCount; i++) {
|
||
const Window& w = windows[i];
|
||
if (w.on == w.off) continue;
|
||
bool dayToday = w.days & (1 << today);
|
||
if (w.on < w.off) {
|
||
if (dayToday && now >= w.on && now < w.off) return true;
|
||
} else { // über Mitternacht
|
||
if (dayToday && now >= w.on) return true;
|
||
if ((w.days & (1 << yesterday)) && now < w.off) return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Benutzer und Anmeldung
|
||
// ---------------------------------------------------------------------------
|
||
|
||
static String toHex(const uint8_t* b, size_t n) {
|
||
static const char* hex = "0123456789abcdef";
|
||
String s;
|
||
s.reserve(n * 2);
|
||
for (size_t i = 0; i < n; i++) {
|
||
s += hex[b[i] >> 4];
|
||
s += hex[b[i] & 15];
|
||
}
|
||
return s;
|
||
}
|
||
|
||
static String randomHex(size_t bytes) {
|
||
uint8_t buf[32];
|
||
esp_fill_random(buf, bytes);
|
||
return toHex(buf, bytes);
|
||
}
|
||
|
||
static String hashPassword(const String& pass, const String& salt) {
|
||
uint8_t out[32];
|
||
mbedtls_md_context_t ctx;
|
||
mbedtls_md_init(&ctx);
|
||
mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
|
||
mbedtls_pkcs5_pbkdf2_hmac(&ctx, (const uint8_t*)pass.c_str(), pass.length(),
|
||
(const uint8_t*)salt.c_str(), salt.length(), PBKDF2_ITERATIONS, 32, out);
|
||
mbedtls_md_free(&ctx);
|
||
return toHex(out, 32);
|
||
}
|
||
|
||
static String hmacHex(const String& msg) {
|
||
uint8_t out[32];
|
||
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), tokenSecret, sizeof(tokenSecret),
|
||
(const uint8_t*)msg.c_str(), msg.length(), out);
|
||
return toHex(out, 32);
|
||
}
|
||
|
||
// Vergleich ohne frühen Abbruch (gegen Zeitmessungs-Angriffe)
|
||
static bool safeEquals(const String& a, const String& b) {
|
||
if (a.length() != b.length()) return false;
|
||
uint8_t diff = 0;
|
||
for (size_t i = 0; i < a.length(); i++) diff |= a[i] ^ b[i];
|
||
return diff == 0;
|
||
}
|
||
|
||
static bool validName(const String& n) {
|
||
if (n.length() < 1 || n.length() > 24) return false;
|
||
for (char c : n)
|
||
if (!isalnum((unsigned char)c) && c != '.' && c != '-' && c != '_') return false;
|
||
return true;
|
||
}
|
||
|
||
static User* findUser(const String& name) {
|
||
for (auto& u : users)
|
||
if (u.name.equalsIgnoreCase(name)) return &u;
|
||
return nullptr;
|
||
}
|
||
|
||
static int adminCount() {
|
||
int n = 0;
|
||
for (auto& u : users) n += u.admin;
|
||
return n;
|
||
}
|
||
|
||
static void saveUsers() {
|
||
JsonDocument doc;
|
||
JsonArray arr = doc.to<JsonArray>();
|
||
for (auto& u : users) {
|
||
JsonObject o = arr.add<JsonObject>();
|
||
o["n"] = u.name;
|
||
o["s"] = u.salt;
|
||
o["h"] = u.hash;
|
||
o["a"] = u.admin;
|
||
}
|
||
String s;
|
||
serializeJson(doc, s);
|
||
prefs.putString("users", s);
|
||
}
|
||
|
||
static void setUser(const String& name, const String& pass, bool admin) {
|
||
User* u = findUser(name);
|
||
if (!u) {
|
||
users.push_back({name, "", "", admin});
|
||
u = &users.back();
|
||
}
|
||
u->admin = admin;
|
||
if (pass.length()) {
|
||
u->salt = randomHex(16);
|
||
u->hash = hashPassword(pass, u->salt); // neuer Hash macht alte Sitzungen ungültig
|
||
}
|
||
saveUsers();
|
||
}
|
||
|
||
static void loadUsers() {
|
||
if (prefs.getBytes("secret", tokenSecret, sizeof(tokenSecret)) != sizeof(tokenSecret)) {
|
||
esp_fill_random(tokenSecret, sizeof(tokenSecret));
|
||
prefs.putBytes("secret", tokenSecret, sizeof(tokenSecret));
|
||
}
|
||
JsonDocument doc;
|
||
if (!deserializeJson(doc, prefs.getString("users", "[]"))) {
|
||
for (JsonObject o : doc.as<JsonArray>())
|
||
users.push_back({o["n"].as<String>(), o["s"].as<String>(), o["h"].as<String>(), o["a"] | false});
|
||
}
|
||
if (users.empty()) {
|
||
Serial.println("Lege ersten Administrator an");
|
||
setUser(ADMIN_USER, ADMIN_PASSWORD, true);
|
||
}
|
||
Serial.printf("%u Benutzer\n", users.size());
|
||
}
|
||
|
||
// Sitzungs-Token: name|ablauf|signatur. Die Signatur bezieht den Passwort-Hash ein,
|
||
// damit eine Passwortänderung oder Löschung alle Sitzungen beendet.
|
||
static String makeToken(const User& u) {
|
||
long long exp = (long long)time(nullptr) + SESSION_DAYS * 86400LL;
|
||
String base = u.name + "|" + String(exp);
|
||
return base + "|" + hmacHex(base + "|" + u.hash);
|
||
}
|
||
|
||
static User* currentUser() {
|
||
String c = server.header("Cookie");
|
||
int i = c.indexOf("session=");
|
||
if (i < 0) return nullptr;
|
||
int end = c.indexOf(';', i);
|
||
String tok = c.substring(i + 8, end < 0 ? c.length() : end);
|
||
int p1 = tok.indexOf('|');
|
||
int p2 = tok.indexOf('|', p1 + 1);
|
||
if (p1 < 0 || p2 < 0) return nullptr;
|
||
User* u = findUser(tok.substring(0, p1));
|
||
if (!u) return nullptr;
|
||
String base = tok.substring(0, p2);
|
||
if (!safeEquals(hmacHex(base + "|" + u->hash), tok.substring(p2 + 1))) return nullptr;
|
||
if (timeValid() && atoll(tok.substring(p1 + 1, p2).c_str()) < (long long)time(nullptr)) return nullptr;
|
||
return u;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Speichern (NVS)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
static void saveMode() {
|
||
prefs.putUChar("mode", (uint8_t)mode);
|
||
prefs.putLong64("until", (int64_t)manualUntil);
|
||
}
|
||
|
||
static void saveSchedule() {
|
||
JsonDocument doc;
|
||
scheduleToJson(doc["windows"].to<JsonArray>());
|
||
String s;
|
||
serializeJson(doc, s);
|
||
prefs.putString("schedule", s);
|
||
}
|
||
|
||
static void loadSettings() {
|
||
prefs.begin("pumpe", false);
|
||
uint8_t m = prefs.getUChar("mode", 0);
|
||
mode = m <= 2 ? (Mode)m : Mode::Auto;
|
||
manualUntil = (time_t)prefs.getLong64("until", 0);
|
||
|
||
String s = prefs.getString("schedule", "");
|
||
if (s.length()) {
|
||
JsonDocument doc;
|
||
String err;
|
||
if (!deserializeJson(doc, s)) loadWindows(doc.as<JsonVariantConst>(), err);
|
||
}
|
||
Serial.printf("Einstellungen: Modus %s, %u Zeitfenster\n", modeName(mode), windowCount);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Relais-Logik
|
||
// ---------------------------------------------------------------------------
|
||
|
||
static void writeRelay(bool on) {
|
||
relayOn = on;
|
||
digitalWrite(RELAY_PIN, (on != RELAY_ACTIVE_LOW) ? HIGH : LOW);
|
||
}
|
||
|
||
static void noteChange(const String& by, const String& action) {
|
||
lastBy = by;
|
||
lastAction = action;
|
||
lastAt = time(nullptr);
|
||
Serial.printf("Änderung: %s durch %s\n", action.c_str(), by.c_str());
|
||
}
|
||
|
||
// Bestimmt den Sollzustand und schaltet das Relais. Wird jede Sekunde aufgerufen.
|
||
static void evaluate() {
|
||
time_t now = time(nullptr);
|
||
|
||
if (mode != Mode::Auto && manualUntil && timeValid() && now >= manualUntil) {
|
||
mode = Mode::Auto;
|
||
manualUntil = 0;
|
||
saveMode();
|
||
noteChange("System", "auto (Zeit abgelaufen)");
|
||
}
|
||
|
||
bool want;
|
||
const char* why;
|
||
if (mode == Mode::On) {
|
||
want = true;
|
||
why = "manual";
|
||
} else if (mode == Mode::Off) {
|
||
want = false;
|
||
why = "manual";
|
||
} else if (!timeValid()) {
|
||
want = FAILSAFE_RELAY_ON;
|
||
why = "failsafe";
|
||
} else {
|
||
tm t;
|
||
localtime_r(&now, &t);
|
||
want = scheduleActive(t);
|
||
why = "schedule";
|
||
}
|
||
|
||
if (want != relayOn || strcmp(why, reason) != 0) {
|
||
writeRelay(want);
|
||
reason = why;
|
||
Serial.printf("Relais %s (%s)\n", want ? "AN" : "AUS", why);
|
||
}
|
||
}
|
||
|
||
static void setManual(Mode m, long minutes, const String& by) {
|
||
mode = m;
|
||
manualUntil = (m != Mode::Auto && minutes > 0 && timeValid()) ? time(nullptr) + minutes * 60 : 0;
|
||
saveMode();
|
||
String action = modeName(m);
|
||
if (manualUntil) action += " für " + String(minutes) + " min";
|
||
noteChange(by, action);
|
||
evaluate();
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Webserver
|
||
// ---------------------------------------------------------------------------
|
||
|
||
static void sendJson(int code, const JsonDocument& doc) {
|
||
String out;
|
||
serializeJson(doc, out);
|
||
server.sendHeader("Cache-Control", "no-store");
|
||
server.send(code, "application/json", out);
|
||
}
|
||
|
||
static void sendError(int code, const char* msg) {
|
||
JsonDocument doc;
|
||
doc["error"] = msg;
|
||
sendJson(code, doc);
|
||
}
|
||
|
||
static bool readBody(JsonDocument& doc) {
|
||
if (deserializeJson(doc, server.arg("plain"))) {
|
||
sendError(400, "Ungültige Anfrage");
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
// Prüft die Anmeldung. Sendet bei Fehler selbst die Antwort.
|
||
static User* requireUser(bool admin = false) {
|
||
User* u = currentUser();
|
||
if (!u) {
|
||
sendError(401, "Bitte anmelden");
|
||
return nullptr;
|
||
}
|
||
if (admin && !u->admin) {
|
||
sendError(403, "Nur für Administratoren");
|
||
return nullptr;
|
||
}
|
||
return u;
|
||
}
|
||
|
||
static void sendState(const User& me) {
|
||
JsonDocument doc;
|
||
doc["relay"] = relayOn;
|
||
doc["mode"] = modeName(mode);
|
||
doc["until"] = (long long)manualUntil;
|
||
doc["reason"] = reason;
|
||
doc["timeOk"] = timeValid();
|
||
doc["now"] = (long long)time(nullptr);
|
||
doc["uptime"] = millis() / 1000;
|
||
doc["rssi"] = WiFi.RSSI();
|
||
doc["fw"] = FIRMWARE_VERSION;
|
||
if (lastAt) {
|
||
JsonObject last = doc["last"].to<JsonObject>();
|
||
last["by"] = lastBy;
|
||
last["action"] = lastAction;
|
||
last["at"] = (long long)lastAt;
|
||
}
|
||
scheduleToJson(doc["windows"].to<JsonArray>());
|
||
doc["me"]["user"] = me.name;
|
||
doc["me"]["admin"] = me.admin;
|
||
sendJson(200, doc);
|
||
}
|
||
|
||
static void serveStatic(const char* type, const char* body) {
|
||
server.sendHeader("Cache-Control", "no-cache");
|
||
server.send_P(200, type, body);
|
||
}
|
||
|
||
static unsigned long loginLockUntil = 0;
|
||
static uint8_t loginFails = 0;
|
||
|
||
static void handleLogin() {
|
||
if ((long)(millis() - loginLockUntil) < 0) {
|
||
sendError(429, "Zu viele Fehlversuche. Bitte eine Minute warten.");
|
||
return;
|
||
}
|
||
JsonDocument body;
|
||
if (!readBody(body)) return;
|
||
User* u = findUser(body["user"] | "");
|
||
String pass = body["pass"] | "";
|
||
if (!u || !safeEquals(hashPassword(pass, u->salt), u->hash)) {
|
||
if (++loginFails >= LOGIN_MAX_FAILS) {
|
||
loginFails = 0;
|
||
loginLockUntil = millis() + LOGIN_LOCK_S * 1000UL;
|
||
}
|
||
sendError(401, "Benutzername oder Passwort falsch.");
|
||
return;
|
||
}
|
||
loginFails = 0;
|
||
server.sendHeader("Set-Cookie", "session=" + makeToken(*u) + "; Path=/; Max-Age=" +
|
||
String(SESSION_DAYS * 86400L) + "; HttpOnly; SameSite=Strict");
|
||
sendState(*u);
|
||
}
|
||
|
||
static void handleUsersList() {
|
||
if (!requireUser(true)) return;
|
||
JsonDocument doc;
|
||
JsonArray arr = doc["users"].to<JsonArray>();
|
||
for (auto& u : users) {
|
||
JsonObject o = arr.add<JsonObject>();
|
||
o["user"] = u.name;
|
||
o["admin"] = u.admin;
|
||
}
|
||
doc["max"] = MAX_USERS;
|
||
sendJson(200, doc);
|
||
}
|
||
|
||
static void handleUsersSet() {
|
||
User* me = requireUser(true);
|
||
if (!me) return;
|
||
JsonDocument body;
|
||
if (!readBody(body)) return;
|
||
String name = body["user"] | "";
|
||
String pass = body["pass"] | "";
|
||
bool admin = body["admin"] | false;
|
||
User* existing = findUser(name);
|
||
|
||
if (!validName(name)) return sendError(400, "Name: 1–24 Zeichen, nur Buchstaben, Ziffern, . - _");
|
||
if (!existing && users.size() >= MAX_USERS) return sendError(400, "Maximale Anzahl Benutzer erreicht");
|
||
if (!existing && pass.length() < 8) return sendError(400, "Passwort: mindestens 8 Zeichen");
|
||
if (existing && pass.length() && pass.length() < 8) return sendError(400, "Passwort: mindestens 8 Zeichen");
|
||
if (existing && existing->admin && !admin && adminCount() <= 1)
|
||
return sendError(400, "Der letzte Administrator kann nicht herabgestuft werden");
|
||
|
||
String myName = me->name; // me kann durch push_back ungültig werden
|
||
setUser(existing ? existing->name : name, pass, admin);
|
||
noteChange(myName, String(existing ? "Benutzer geändert: " : "Benutzer angelegt: ") + name);
|
||
handleUsersList();
|
||
}
|
||
|
||
static void handleUsersDelete() {
|
||
User* me = requireUser(true);
|
||
if (!me) return;
|
||
JsonDocument body;
|
||
if (!readBody(body)) return;
|
||
String name = body["user"] | "";
|
||
if (name.equalsIgnoreCase(me->name)) return sendError(400, "Eigenen Zugang nicht löschbar");
|
||
String myName = me->name;
|
||
for (size_t i = 0; i < users.size(); i++) {
|
||
if (users[i].name.equalsIgnoreCase(name)) {
|
||
users.erase(users.begin() + i);
|
||
saveUsers();
|
||
noteChange(myName, "Benutzer gelöscht: " + name);
|
||
return handleUsersList();
|
||
}
|
||
}
|
||
sendError(404, "Benutzer nicht gefunden");
|
||
}
|
||
|
||
static void setupServer() {
|
||
static const char* headers[] = {"Cookie"};
|
||
server.collectHeaders(headers, 1);
|
||
|
||
server.on("/", HTTP_GET, [] { serveStatic("text/html; charset=utf-8", WEB_INDEX); });
|
||
server.on("/app.js", HTTP_GET, [] { serveStatic("text/javascript; charset=utf-8", WEB_APP_JS); });
|
||
server.on("/style.css", HTTP_GET, [] { serveStatic("text/css; charset=utf-8", WEB_STYLE); });
|
||
server.on("/icon.svg", HTTP_GET, [] { serveStatic("image/svg+xml", WEB_ICON); });
|
||
server.on("/manifest.webmanifest", HTTP_GET, [] { serveStatic("application/manifest+json", WEB_MANIFEST); });
|
||
|
||
server.on("/api/login", HTTP_POST, handleLogin);
|
||
server.on("/api/logout", HTTP_POST, [] {
|
||
server.sendHeader("Set-Cookie", "session=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict");
|
||
server.send(204);
|
||
});
|
||
server.on("/api/state", HTTP_GET, [] {
|
||
if (User* u = requireUser()) sendState(*u);
|
||
});
|
||
server.on("/api/cmd", HTTP_POST, [] {
|
||
User* u = requireUser();
|
||
if (!u) return;
|
||
JsonDocument body;
|
||
if (!readBody(body)) return;
|
||
const char* action = body["action"] | "";
|
||
long minutes = body["minutes"] | 0L;
|
||
if (minutes < 0 || minutes > 7 * 1440) return sendError(400, "Ungültige Dauer");
|
||
if (!strcmp(action, "on")) setManual(Mode::On, minutes, u->name);
|
||
else if (!strcmp(action, "off")) setManual(Mode::Off, minutes, u->name);
|
||
else if (!strcmp(action, "auto")) setManual(Mode::Auto, 0, u->name);
|
||
else return sendError(400, "Unbekannte Aktion");
|
||
sendState(*u);
|
||
});
|
||
server.on("/api/schedule", HTTP_POST, [] {
|
||
User* u = requireUser();
|
||
if (!u) return;
|
||
JsonDocument body;
|
||
if (!readBody(body)) return;
|
||
String err;
|
||
if (!loadWindows(body.as<JsonVariantConst>(), err)) return sendError(400, err.c_str());
|
||
saveSchedule();
|
||
noteChange(u->name, "Zeitplan geändert");
|
||
evaluate();
|
||
sendState(*u);
|
||
});
|
||
server.on("/api/password", HTTP_POST, [] {
|
||
User* u = requireUser();
|
||
if (!u) return;
|
||
JsonDocument body;
|
||
if (!readBody(body)) return;
|
||
String oldPass = body["old"] | "";
|
||
String newPass = body["new"] | "";
|
||
if (!safeEquals(hashPassword(oldPass, u->salt), u->hash)) return sendError(400, "Altes Passwort falsch");
|
||
if (newPass.length() < 8) return sendError(400, "Neues Passwort: mindestens 8 Zeichen");
|
||
setUser(u->name, newPass, u->admin);
|
||
// neues Cookie, da das alte mit dem alten Passwort-Hash signiert war
|
||
server.sendHeader("Set-Cookie", "session=" + makeToken(*u) + "; Path=/; Max-Age=" +
|
||
String(SESSION_DAYS * 86400L) + "; HttpOnly; SameSite=Strict");
|
||
sendState(*u);
|
||
});
|
||
server.on("/api/users", HTTP_GET, handleUsersList);
|
||
server.on("/api/users", HTTP_POST, handleUsersSet);
|
||
server.on("/api/users/delete", HTTP_POST, handleUsersDelete);
|
||
|
||
server.onNotFound([] { sendError(404, "Nicht gefunden"); });
|
||
server.begin();
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// WLAN, OTA, Taster, LED
|
||
// ---------------------------------------------------------------------------
|
||
|
||
static void handleNetwork() {
|
||
static bool started = false;
|
||
if (WiFi.status() != WL_CONNECTED) return;
|
||
if (!started) {
|
||
ArduinoOTA.setHostname(HOSTNAME);
|
||
ArduinoOTA.setPassword(OTA_PASSWORD);
|
||
ArduinoOTA.onStart([] { Serial.println("OTA-Update startet"); });
|
||
ArduinoOTA.begin();
|
||
setupServer();
|
||
started = true;
|
||
Serial.printf("WLAN verbunden: http://%s (http://%s.fritz.box)\n",
|
||
WiFi.localIP().toString().c_str(), HOSTNAME);
|
||
}
|
||
ArduinoOTA.handle();
|
||
server.handleClient();
|
||
}
|
||
|
||
static void handleButton() {
|
||
static bool wasDown = false;
|
||
static unsigned long downAt = 0;
|
||
static bool longDone = false;
|
||
bool down = digitalRead(BUTTON_PIN) == LOW;
|
||
|
||
if (down && !wasDown) {
|
||
downAt = millis();
|
||
longDone = false;
|
||
} else if (down && !longDone && millis() - downAt >= BUTTON_LONG_MS) {
|
||
longDone = true;
|
||
setManual(Mode::Auto, 0, "Taster");
|
||
} else if (!down && wasDown && !longDone && millis() - downAt > 50) {
|
||
setManual(relayOn ? Mode::Off : Mode::On, 0, "Taster");
|
||
}
|
||
wasDown = down;
|
||
}
|
||
|
||
// LED: an = alles in Ordnung, langsam blinkend = keine Uhrzeit, schnell = kein WLAN
|
||
static void handleLed() {
|
||
bool on;
|
||
if (WiFi.status() != WL_CONNECTED) on = (millis() / 200) % 2;
|
||
else if (!timeValid()) on = (millis() / 1000) % 2;
|
||
else on = true;
|
||
digitalWrite(LED_PIN, on);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
|
||
void setup() {
|
||
// Relais so früh wie möglich in definierten Zustand
|
||
pinMode(RELAY_PIN, OUTPUT);
|
||
for (int pin : UNUSED_RELAY_PINS) {
|
||
pinMode(pin, OUTPUT);
|
||
digitalWrite(pin, RELAY_ACTIVE_LOW ? HIGH : LOW);
|
||
}
|
||
pinMode(LED_PIN, OUTPUT);
|
||
pinMode(BUTTON_PIN, INPUT_PULLUP);
|
||
|
||
Serial.begin(115200);
|
||
Serial.printf("\nHeizungspumpe %s\n", FIRMWARE_VERSION);
|
||
|
||
loadSettings();
|
||
loadUsers();
|
||
evaluate();
|
||
|
||
WiFi.mode(WIFI_STA);
|
||
WiFi.setHostname(HOSTNAME);
|
||
WiFi.setAutoReconnect(true);
|
||
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
|
||
|
||
// fritz.box als erster Zeitserver: funktioniert auch, wenn nur das Heimnetz läuft
|
||
configTzTime(TZ_INFO, "fritz.box", "de.pool.ntp.org", "pool.ntp.org");
|
||
}
|
||
|
||
void loop() {
|
||
static unsigned long lastEval = 0;
|
||
|
||
handleNetwork();
|
||
handleButton();
|
||
handleLed();
|
||
|
||
if (millis() - lastEval >= 1000) {
|
||
lastEval = millis();
|
||
evaluate();
|
||
}
|
||
delay(2);
|
||
}
|