// Info-Display für den LilyGO T-Display (ESP32, ST7789 135x240) // // Uhrzeit per NTP, Wetter, Regen, Luft und Pollen von Open-Meteo, Standort per IP (ip-api.com), // Blutzucker (LibreLinkUp) über eigene Endpunkte, RZ-Status vom PP&B-Monitoring, // Abfahrten und Störungen von v6.bvg.transport.rest, Strommix von energy-charts.info, // Nachrichten von tagesschau.de, Termine aus iCal-Links, Erreichbarkeit eigener Server. // Taste GPIO35: nächste Seite (Reihenfolge in PAGE_ORDER) // Taste GPIO0: kurz = Option der Seite (siehe pageOption(), sonst Helligkeit), lang = Helligkeit // Einstellungen im Browser unter http://tdisplay.local/, Firmware-Updates über WLAN mit make ota. #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "config.h" #include "secrets.h" #include "icons.h" #include "webpage.h" #include "timeutil.h" #include "ical.h" #include "astro.h" // ---------------------------------------------------------------- Hardware static constexpr int PIN_BTN_PAGE = 35; static constexpr int PIN_BTN_OPTION = 0; static constexpr int PIN_BAT_ADC = 34; static constexpr int PIN_BAT_ADC_EN = 14; class LGFX : public lgfx::LGFX_Device { lgfx::Panel_ST7789 _panel; lgfx::Bus_SPI _bus; lgfx::Light_PWM _light; public: LGFX() { { auto cfg = _bus.config(); cfg.spi_host = SPI2_HOST; cfg.spi_mode = 0; cfg.spi_3wire = true; cfg.freq_write = 40000000; cfg.freq_read = 14000000; cfg.pin_sclk = 18; cfg.pin_mosi = 19; cfg.pin_miso = -1; cfg.pin_dc = 16; _bus.config(cfg); _panel.setBus(&_bus); } { auto cfg = _panel.config(); cfg.pin_cs = 5; cfg.pin_rst = 23; cfg.panel_width = 135; cfg.panel_height = 240; cfg.offset_x = 52; cfg.offset_y = 40; cfg.invert = true; cfg.readable = false; _panel.config(cfg); } { auto cfg = _light.config(); cfg.pin_bl = 4; cfg.freq = 44100; cfg.pwm_channel = 7; _light.config(cfg); _panel.setLight(&_light); } setPanel(&_panel); } }; static LGFX lcd; static LGFX_Sprite canvas(&lcd); // Das Bild wird in zwei Hälften gezeichnet (siehe present()); der Puffer reicht für eine Hälfte. static constexpr int SCREEN_W = 240, SCREEN_H = 135, BAND_H = 68; static uint8_t* gBandBuf = nullptr; static int gBandTop = 0, gBandH = BAND_H; static uint32_t gFrameMs = 0; // millis() zu Beginn des Bildes, damit beide Hälften dasselbe zeigen static const lgfx::IFont* const FONT_TEXT = &fonts::efontJA_16; // enthält Umlaute und ° // ---------------------------------------------------------------- Daten struct DayForecast { int code = -1; float tMax = NAN; float tMin = NAN; int rainProb = -1; uint32_t sunrise = 0; // Unix-Zeit uint32_t sunset = 0; float daylight = 0; // Sekunden }; // Regen in 15-Minuten-Schritten. Etwas mehr als 2 Stunden, weil die Daten bis zu 15 Minuten alt sind. static constexpr int NOWCAST = 10; static constexpr int HOURS = 48; // Länge des Meteogramms struct HourForecast { uint32_t t = 0; // Unix-Zeit, Beginn der Stunde float temp = NAN; float dew = NAN; float precip = 0; // mm in der vorangegangenen Stunde float snow = 0; // cm in der vorangegangenen Stunde float wind = 0; // km/h float gust = 0; // km/h float pressure = NAN; // hPa uint16_t windDir = 0; // Grad, woher der Wind kommt int16_t code = -1; uint8_t prob = 0; // Niederschlagswahrscheinlichkeit % uint8_t cloud = 0; // Bewölkung % bool isDay = true; }; struct WeatherData { bool valid = false; float temp = NAN; float feels = NAN; float wind = NAN; int humidity = -1; int code = -1; bool isDay = true; DayForecast days[3]; HourForecast hours[HOURS]; int hourCount = 0; uint32_t nowcastStart = 0; // Zeitstempel des ersten Werts; jeder Wert gilt für die 15 Minuten davor float nowcast[NOWCAST]; // Niederschlag je Abschnitt in mm bool nowcastSnow[NOWCAST]; int nowcastCount = 0; uint32_t updatedMs = 0; }; struct LocationData { bool valid = false; float lat = 0; float lon = 0; char name[48] = ""; }; struct __attribute__((packed)) GlucosePoint { // 6 statt 8 Byte uint32_t t; // Unix-Zeit uint16_t v; // mg/dL }; // Der Verlauf wird mit höchstens einem Wert alle 2 Minuten gespeichert; das reicht für beide Diagramme // und halbiert den Speicher, der für TLS-Verbindungen knapp ist. static constexpr uint32_t GLUCOSE_STEP_S = 120; static constexpr size_t GLUCOSE_MAX_POINTS = 24 * 3600 / GLUCOSE_STEP_S + 30; struct GlucoseNow { bool valid = false; uint32_t t = 0; int value = 0; int trend = 0; // 1 = fällt schnell, 2 = fällt, 3 = stabil, 4 = steigt, 5 = steigt schnell }; static constexpr int MON_MAX_CHECKS = 6; static constexpr int MON_MAX_HOSTS = 8; struct MonitorCheck { char name[12]; bool ok; char detail[64]; // was nicht stimmt, bei ok leer }; struct VmHost { char name[8]; char state[8]; // VMware-Ampel: green, yellow, red, gray float cpu = NAN; // Last in % float mem = NAN; // belegter Speicher in % }; struct MonitorData { bool valid = false; MonitorCheck checks[MON_MAX_CHECKS]; int checkCount = 0; VmHost hosts[MON_MAX_HOSTS]; // nach Namen sortiert int hostCount = 0; int concerns = 0; uint32_t updatedMs = 0; }; static constexpr int MAX_DEPARTURES = 12; enum class Product : uint8_t { Suburban, Subway, Tram, Bus, Ferry, Regional, Other }; struct Departure { uint32_t when; // erwartete Abfahrt (Unix-Zeit), bei Ausfall die geplante int16_t delay; // Sekunden, DELAY_UNKNOWN ohne Echtzeitdaten Product product; bool cancelled; char line[8]; char direction[40]; }; static constexpr int16_t DELAY_UNKNOWN = INT16_MIN; struct DepartureData { bool valid = false; char stop[48] = ""; Departure deps[MAX_DEPARTURES]; int count = 0; uint32_t updatedMs = 0; }; enum Pollen { ALDER, BIRCH, GRASS, MUGWORT, RAGWEED, POLLEN_COUNT }; struct AirData { bool valid = false; int aqi = -1; // Europäischer Luftqualitätsindex float pm25 = NAN, pm10 = NAN; float uv = NAN, uvMax = NAN; // jetzt und heute höchstens float pollen[POLLEN_COUNT][2]; // Höchstwert heute und morgen, Pollen/m³ uint32_t updatedMs = 0; }; static constexpr int POWER_MAX = 192; // zwei Tage in Viertelstunden struct PowerData { bool valid = false; uint32_t start = 0; // Unix-Zeit des ersten Werts uint16_t step = 900; int count = 0; uint8_t share[POWER_MAX]; // Anteil erneuerbarer Energie in %, 255 = unbekannt int8_t signal[POWER_MAX]; // -1 Netzengpass, 0 rot, 1 gelb, 2 grün uint32_t updatedMs = 0; }; static constexpr int NEWS_MAX = 9; struct NewsItem { uint32_t time; char title[144]; }; struct NewsData { bool valid = false; NewsItem items[NEWS_MAX]; int count = 0; uint32_t updatedMs = 0; }; static constexpr int CAL_MAX = 16; struct CalendarData { bool valid = false; CalEvent events[CAL_MAX]; int count = 0; int failed = 0; // Kalender, die sich nicht laden ließen uint32_t updatedMs = 0; }; static constexpr int SERVER_MAX = 6; struct ServerStatus { char name[40]; int code; // HTTP-Status, negativ bei Verbindungsfehler int ms; // Antwortzeit int certDays; // Tage bis zum Ablauf des Zertifikats, INT_MIN ohne TLS }; struct ServerData { bool valid = false; ServerStatus servers[SERVER_MAX]; int count = 0; uint32_t updatedMs = 0; }; static constexpr int WARN_MAX = 6; struct BvgWarning { uint32_t id; char lines[40]; // betroffene Linien an der Haltestelle char summary[48]; char text[300]; }; struct WarningData { bool valid = false; BvgWarning warnings[WARN_MAX]; int count = 0; uint32_t updatedMs = 0; }; // Im Browser änderbar, im Flash gespeichert (Voreinstellungen aus config.h) struct Settings { float lat = LOCATION_LAT; float lon = LOCATION_LON; char place[48] = LOCATION_NAME; char stopId[16] = BVG_STOP_ID; char stopName[48] = ""; int walkMin = BVG_WALK_MIN; int bzLow = BZ_LOW; int bzHigh = BZ_HIGH; int bzVeryHigh = BZ_VERY_HIGH; int pageTimeout = PAGE_TIMEOUT_S; bool flip = SCREEN_ROTATION == 3; uint32_t pagesOff = 0; // Bit n = Seite n ist ausgeblendet char calUrls[512] = ""; // iCal-Links, einer pro Zeile char wasteUrl[256] = ""; // Müllabfuhr als iCal-Link char servers[384] = "https://x.micw.org/"; // zu prüfende Adressen, eine pro Zeile }; // Feste Nummern, unter denen die Auswahl gespeichert wird: neue Seiten nur hinten anfügen enum Page { PAGE_CLOCK, PAGE_GLUCOSE, PAGE_GLUCOSE_DAY, PAGE_FORECAST, PAGE_METEOGRAM, PAGE_MONITOR, PAGE_DEPARTURES, PAGE_INFO, PAGE_RAIN, PAGE_AIR, PAGE_SUN, PAGE_WARNINGS, PAGE_CALENDAR, PAGE_SERVERS, PAGE_POWER, PAGE_NEWS, PAGE_COUNT }; static const char* const PAGE_NAMES[PAGE_COUNT] = { "Uhr", "Blutzucker", "BZ 24 h", "Vorhersage", "Meteogramm", "RZ-Status", "Abfahrten", "Info", "Regen 2 h", "Luft & Pollen", "Sonne & Mond", "BVG-Störungen", "Termine", "Server", "Strommix", "Nachrichten"}; // Reihenfolge beim Blättern static const Page PAGE_ORDER[PAGE_COUNT] = { PAGE_CLOCK, PAGE_GLUCOSE, PAGE_GLUCOSE_DAY, PAGE_FORECAST, PAGE_METEOGRAM, PAGE_RAIN, PAGE_AIR, PAGE_SUN, PAGE_CALENDAR, PAGE_DEPARTURES, PAGE_WARNINGS, PAGE_MONITOR, PAGE_SERVERS, PAGE_POWER, PAGE_NEWS, PAGE_INFO}; // Die Uhr ist die Startseite und immer dabei static bool pageEnabled(const Settings& s, int page) { return page == PAGE_CLOCK || !(s.pagesOff >> page & 1); } // Wird vom Netzwerk-Task geschrieben und von loop() gelesen. static WeatherData gWeather; static LocationData gLocation; static GlucoseNow gGlucose; static std::vector gGlucoseHistory; // aufsteigend nach Zeit, höchstens 24 h // Hier hinein lädt der Netzwerk-Task den Verlauf, dann werden beide getauscht. Beide werden beim Start // reserviert: Während einer TLS-Verbindung ist der Heap zu zerstückelt für einen Block dieser Größe. static std::vector gHistoryBuffer; static MonitorData gMonitor; static DepartureData gDepartures; static AirData gAir; static PowerData gPower; static NewsData gNews; static CalendarData gCalendar; static ServerData gServers; static WarningData gWarnings; static SemaphoreHandle_t gLock; // Schreibt nur loop() (Webseite); der Netzwerk-Task liest über getSettings(). static Settings gSettings; static volatile uint32_t gSettingsGen = 0; // zählt hoch, wenn Standort oder Haltestelle wechseln static volatile uint32_t gSourcesGen = 0; // zählt hoch, wenn Kalender- oder Serverliste wechseln static volatile bool gOtaActive = false; // Netzwerk-Task pausiert während eines Updates struct Lock { Lock() { xSemaphoreTake(gLock, portMAX_DELAY); } ~Lock() { xSemaphoreGive(gLock); } }; static WeatherData getWeather() { Lock l; return gWeather; } static LocationData getLocation() { Lock l; return gLocation; } static MonitorData getMonitor() { Lock l; return gMonitor; } static DepartureData getDepartures() { Lock l; return gDepartures; } static AirData getAir() { Lock l; return gAir; } static Settings getSettings() { Lock l; return gSettings; } // ---------------------------------------------------------------- Netzwerk static WiFiMulti wifiMulti; // Speicher für normale Daten; ESP.getFreeHeap() zählt auch IRAM mit, das nur wortweise nutzbar ist static unsigned heapFree() { return heap_caps_get_free_size(MALLOC_CAP_8BIT); } static unsigned heapBlock() { return heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); } // GET-Anfrage; bei HTTP 200 wird handle mit der offenen Verbindung aufgerufen. static bool httpGet(const char* url, const std::function& handle) { WiFiClientSecure tls; WiFiClient plain; HTTPClient http; http.setTimeout(10000); http.useHTTP10(true); // ohne Chunked-Kodierung, damit sich die Antwort direkt aus getStream() lesen lässt http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); bool begun; if (strncmp(url, "https://", 8) == 0) { tls.useBuiltinCACertBundle(); // Zertifikat gegen die üblichen Root-CAs prüfen begun = http.begin(tls, url); } else { begun = http.begin(plain, url); } if (!begun) return false; int status = http.GET(); bool ok = status == HTTP_CODE_OK && handle(http); if (status != HTTP_CODE_OK) { Serial.printf("GET %.70s -> %d, Heap frei %u, größter Block %u\n", url, status, heapFree(), heapBlock()); } http.end(); return ok; } // Wartet beim Lesen auf Daten. NetworkClient::readBytes gibt auf, sobald read() -1 liefert, und das // heißt bei TLS nur "gerade nichts im Puffer". Stream::readBytes wartet dagegen bis zum Timeout. class WaitingStream : public Stream { public: explicit WaitingStream(Stream& in) : _in(in) { setTimeout(10000); } int read() override { int c = _in.read(); if (c < 0) delay(1); // Stream::timedRead fragt sonst ohne Pause erneut return c; } int available() override { return _in.available(); } int peek() override { return _in.peek(); } size_t write(uint8_t) override { return 0; } private: Stream& _in; }; // Liest JSON direkt aus der Verbindung, ohne die ganze Antwort als String zu puffern. // Mit Filter bleibt nur übrig, was darin auf true steht. static bool httpGetJson(const char* url, JsonDocument& doc, const JsonDocument* filter = nullptr) { return httpGet(url, [&](HTTPClient& http) { WaitingStream in(http.getStream()); DeserializationError err = filter ? deserializeJson(doc, in, DeserializationOption::Filter(*filter)) : deserializeJson(doc, in); if (err) { Serial.printf("JSON-Fehler (%.60s): %s, Heap frei %u, größter Block %u\n", url, err.c_str(), heapFree(), heapBlock()); } return !err; }); } // Nimmt den Antworttext entgegen und meldet jede vollständige Zeile, ohne alles zu puffern. // Zu lange Zeilen werden gekürzt. Mit unfold werden Folgezeilen, die mit Leerzeichen oder Tab // beginnen, angehängt (iCalendar faltet lange Zeilen so). class LineSink : public Stream { public: explicit LineSink(std::function onLine, bool unfold = false) : _onLine(std::move(onLine)), _unfold(unfold) {} size_t write(uint8_t c) override { if (c == '\r') return 1; if (_lineEnded) { _lineEnded = false; if (_unfold && (c == ' ' || c == '\t')) return 1; // Fortsetzung der vorigen Zeile finish(); } if (c == '\n') { if (_unfold) _lineEnded = true; // erst mit dem nächsten Zeichen steht fest, ob es weitergeht else finish(); } else if (_len < sizeof(_buf) - 1) { _buf[_len++] = c; } return 1; } void finish() { _lineEnded = false; if (_len == 0) return; _buf[_len] = 0; _len = 0; _onLine(_buf); } int available() override { return 0; } int read() override { return -1; } int peek() override { return -1; } private: std::function _onLine; bool _unfold; bool _lineEnded = false; char _buf[320]; size_t _len = 0; }; static bool fetchLocation(const Settings& s) { LocationData loc; if (s.lat != 0 || s.lon != 0) { loc.lat = s.lat; loc.lon = s.lon; strlcpy(loc.name, s.place, sizeof(loc.name)); } else { JsonDocument doc; if (!httpGetJson("http://ip-api.com/json/?fields=status,city,lat,lon&lang=de", doc)) return false; if (doc["status"] != "success") return false; loc.lat = doc["lat"]; loc.lon = doc["lon"]; strlcpy(loc.name, doc["city"] | "", sizeof(loc.name)); } loc.valid = true; { Lock l; gLocation = loc; } Serial.printf("Standort: %s (%.4f, %.4f)\n", loc.name, loc.lat, loc.lon); return true; } static bool fetchWeather() { LocationData loc = getLocation(); char url[1024]; snprintf(url, sizeof(url), "https://api.open-meteo.com/v1/forecast?latitude=%.4f&longitude=%.4f" "¤t=temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,wind_speed_10m,is_day" "&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max," "sunrise,sunset,daylight_duration" "&hourly=temperature_2m,dew_point_2m,precipitation,precipitation_probability,snowfall,cloud_cover," "wind_speed_10m,wind_direction_10m,wind_gusts_10m,pressure_msl,weather_code,is_day" "&minutely_15=precipitation,snowfall&forecast_minutely_15=%d" "&forecast_hours=%d&timeformat=unixtime&timezone=auto&forecast_days=3", loc.lat, loc.lon, NOWCAST, HOURS); JsonDocument doc; if (!httpGetJson(url, doc)) return false; JsonObject cur = doc["current"]; JsonObject daily = doc["daily"]; if (cur.isNull() || daily.isNull()) return false; // Groß, daher nur während des Abrufs auf dem Heap statt auf dem Stack des Netzwerk-Tasks std::unique_ptr holder(new WeatherData()); WeatherData& w = *holder; w.temp = cur["temperature_2m"] | NAN; w.feels = cur["apparent_temperature"] | NAN; w.wind = cur["wind_speed_10m"] | NAN; w.humidity = cur["relative_humidity_2m"] | -1; w.code = cur["weather_code"] | -1; w.isDay = (cur["is_day"] | 1) != 0; for (int i = 0; i < 3; i++) { w.days[i].code = daily["weather_code"][i] | -1; w.days[i].tMax = daily["temperature_2m_max"][i] | NAN; w.days[i].tMin = daily["temperature_2m_min"][i] | NAN; w.days[i].rainProb = daily["precipitation_probability_max"][i] | -1; w.days[i].sunrise = daily["sunrise"][i] | 0UL; w.days[i].sunset = daily["sunset"][i] | 0UL; w.days[i].daylight = daily["daylight_duration"][i] | 0.0f; } JsonObject quarter = doc["minutely_15"]; w.nowcastCount = min((int)quarter["time"].size(), NOWCAST); w.nowcastStart = quarter["time"][0] | 0UL; for (int i = 0; i < w.nowcastCount; i++) { w.nowcast[i] = quarter["precipitation"][i] | 0.0f; w.nowcastSnow[i] = (quarter["snowfall"][i] | 0.0f) > 0; } JsonObject hourly = doc["hourly"]; w.hourCount = min((int)hourly["time"].size(), HOURS); for (int i = 0; i < w.hourCount; i++) { HourForecast& h = w.hours[i]; h.t = hourly["time"][i] | 0UL; h.temp = hourly["temperature_2m"][i] | NAN; h.dew = hourly["dew_point_2m"][i] | NAN; h.precip = hourly["precipitation"][i] | 0.0f; h.snow = hourly["snowfall"][i] | 0.0f; h.wind = hourly["wind_speed_10m"][i] | 0.0f; h.gust = hourly["wind_gusts_10m"][i] | 0.0f; h.pressure = hourly["pressure_msl"][i] | NAN; h.windDir = hourly["wind_direction_10m"][i] | 0; h.code = hourly["weather_code"][i] | -1; h.prob = hourly["precipitation_probability"][i] | 0; h.cloud = hourly["cloud_cover"][i] | 0; h.isDay = (hourly["is_day"][i] | 1) != 0; } w.valid = true; w.updatedMs = millis(); { Lock l; gWeather = w; } Serial.printf("Wetter: %.1f °C, Code %d\n", w.temp, w.code); return true; } // " [trend]" static bool parseGlucoseLine(const char* line, GlucoseNow& out) { char* end; unsigned long t = strtoul(line, &end, 10); long v = strtol(end, &end, 10); long trend = strtol(end, nullptr, 10); if (t < 1600000000UL || v < 20 || v > 600) return false; out.valid = true; out.t = t; out.value = v; out.trend = trend; return true; } static void trimGlucoseHistory(std::vector& pts) { if (pts.empty()) return; uint32_t oldest = pts.back().t - 24 * 3600; auto keep = std::find_if(pts.begin(), pts.end(), [&](const GlucosePoint& p) { return p.t >= oldest; }); pts.erase(pts.begin(), keep); } static bool fetchGlucoseCurrent() { GlucoseNow g; bool ok = httpGet(BZ_URL_CURRENT, [&](HTTPClient& http) { return parseGlucoseLine(http.getString().c_str(), g); }); if (!ok) return false; Lock l; gGlucose = g; if (gGlucoseHistory.empty() || g.t >= gGlucoseHistory.back().t + GLUCOSE_STEP_S - 10) { if (gGlucoseHistory.size() >= GLUCOSE_MAX_POINTS) gGlucoseHistory.erase(gGlucoseHistory.begin()); gGlucoseHistory.push_back({g.t, (uint16_t)g.value}); trimGlucoseHistory(gGlucoseHistory); } return true; } static bool fetchGlucoseHistory() { std::vector& pts = gHistoryBuffer; // Kapazität steht seit dem Start fest pts.clear(); time_t now = time(nullptr); uint32_t cutoff = timeValid(now) ? now - 24 * 3600 : 0; LineSink sink([&](const char* line) { // Die Quelle liefert 48 h, neueste zuerst – nur behalten, was ins 24-h-Fenster und den Puffer passt GlucoseNow g; if (!parseGlucoseLine(line, g) || g.t < cutoff || pts.size() >= pts.capacity()) return; if (!pts.empty() && pts.back().t < g.t + GLUCOSE_STEP_S - 10) return; // höchstens ein Wert je 2 Minuten pts.push_back({g.t, (uint16_t)g.value}); }); bool ok = httpGet(BZ_URL_HISTORY, [&](HTTPClient& http) { return http.writeToStream(&sink) > 0; }); sink.finish(); if (!ok || pts.empty()) return false; std::sort(pts.begin(), pts.end(), [](const GlucosePoint& a, const GlucosePoint& b) { return a.t < b.t; }); trimGlucoseHistory(pts); size_t count = pts.size(); { Lock l; // Ein inzwischen neuerer Einzelwert bleibt erhalten if (gGlucose.valid && gGlucose.t > pts.back().t) { if (pts.size() == pts.capacity()) pts.erase(pts.begin()); pts.push_back({gGlucose.t, (uint16_t)gGlucose.value}); } gGlucoseHistory.swap(pts); } Serial.printf("BZ-Verlauf: %u Werte\n", (unsigned)count); return true; } // Anzeigename eines Bereichs: bekannte Schreibweisen, sonst erster Buchstabe groß static void checkName(const char* key, char* out, size_t len) { static const char* const KNOWN[][2] = {{"vmware", "VMware"}, {"netapp", "NetApp"}}; for (const auto& k : KNOWN) { if (strcmp(key, k[0]) == 0) { strlcpy(out, k[1], len); return; } } strlcpy(out, key, len); out[0] = toupper(out[0]); } static void appendItem(char* out, size_t len, const char* item) { if (*out) strlcat(out, ", ", len); strlcat(out, item, len); } // Betroffene Einträge eines gestörten Bereichs (Fehler, fehlende Hosts, Systeme ohne "ok"), sonst die Meldung static void checkDetail(JsonObjectConst c, char* out, size_t len) { out[0] = 0; for (const char* key : {"error", "missing"}) { for (JsonVariantConst v : c[key].as()) appendItem(out, len, v | "?"); } for (JsonPairConst kv : c["systems"].as()) { if (kv.value() != "ok") appendItem(out, len, kv.key().c_str()); } for (JsonPairConst kv : c["hosts"]["status"].as()) { if (kv.value() != "green") appendItem(out, len, kv.key().c_str()); } if (!*out) strlcpy(out, c["message"] | "", len); } // Zahl, die als Zahl oder als Text kommen kann static float jsonNumber(JsonVariantConst v) { return v.is() ? strtof(v.as(), nullptr) : (v | NAN); } static bool fetchMonitor() { JsonDocument doc; if (!httpGetJson(MONITOR_URL, doc) || !doc.is()) return false; // Jedes Objekt mit "status" ist ein Bereich (1 = in Ordnung) std::unique_ptr holder(new MonitorData()); // nicht auf den Stack, wie bei fetchWeather MonitorData& m = *holder; for (JsonPair kv : doc.as()) { JsonObject c = kv.value().as(); if (c.isNull() || !c["status"].is() || m.checkCount >= MON_MAX_CHECKS) continue; MonitorCheck& mc = m.checks[m.checkCount++]; checkName(kv.key().c_str(), mc.name, sizeof(mc.name)); mc.ok = c["status"] == 1; mc.detail[0] = 0; if (!mc.ok) checkDetail(c, mc.detail, sizeof(mc.detail)); } m.concerns = doc["concerns"] | 0; JsonObject vm = doc["vmware"]["hosts"]; for (JsonPair kv : vm["status"].as()) { if (m.hostCount >= MON_MAX_HOSTS) break; VmHost& h = m.hosts[m.hostCount++]; const char* name = kv.key().c_str(); strlcpy(h.name, name, sizeof(h.name)); strlcpy(h.state, kv.value() | "", sizeof(h.state)); h.cpu = jsonNumber(vm["load"][name]); h.mem = jsonNumber(vm["mem"][name]); } std::sort(m.hosts, m.hosts + m.hostCount, [](const VmHost& a, const VmHost& b) { return strcmp(a.name, b.name) < 0; }); int problems = 0; for (int i = 0; i < m.checkCount; i++) problems += !m.checks[i].ok; m.valid = m.checkCount > 0; m.updatedMs = millis(); if (m.valid) { Lock l; gMonitor = m; } Serial.printf("RZ: %d Bereiche, %d gestört, %d Hosts\n", m.checkCount, problems, m.hostCount); return m.valid; } // "2026-10-20T14:23:00+02:00" → Unix-Zeit, 0 bei Fehler static uint32_t parseIsoTime(const char* s) { int y, mo, d, h, mi, sec, oh = 0, om = 0; char sign = 'Z'; if (!s || sscanf(s, "%d-%d-%dT%d:%d:%d%c%d:%d", &y, &mo, &d, &h, &mi, &sec, &sign, &oh, &om) < 6) return 0; long off = (oh * 3600L + om * 60L) * (sign == '-' ? -1 : sign == '+' ? 1 : 0); return daysFromCivil(y, mo, d) * 86400 + h * 3600L + mi * 60L + sec - off; } // Haltestellennamen ohne " (Berlin)", Ringbahn ohne Pfeil (fehlt in der Schrift) static void cleanStopName(const char* in, char* out, size_t len) { strlcpy(out, in ? in : "", len); for (const char* junk : {" (Berlin)", " ⟳", " ⟲"}) { if (char* p = strstr(out, junk)) memmove(p, p + strlen(junk), strlen(p + strlen(junk)) + 1); } } static Product parseProduct(const char* p) { static const struct { const char* name; Product product; } MAP[] = { {"suburban", Product::Suburban}, {"subway", Product::Subway}, {"tram", Product::Tram}, {"bus", Product::Bus}, {"ferry", Product::Ferry}, {"regional", Product::Regional}, {"express", Product::Regional}, }; for (const auto& m : MAP) { if (p && strcmp(p, m.name) == 0) return m.product; } return Product::Other; } // Ohne eingestellte Haltestelle die nächste am Standort; bleibt bis zur nächsten Änderung gemerkt static char gStopId[16], gStopName[48]; // Je Linie an der Haltestelle eine Fahrt; deren Details enthalten die Störungsmeldungen der Linie static constexpr int LINE_TRIPS_MAX = 10; static struct { char line[8]; char trip[48]; } gLineTrips[LINE_TRIPS_MAX]; static int gLineTripCount = 0; static void rememberLineTrip(const char* line, const char* trip) { if (!*line || !*trip || gLineTripCount >= LINE_TRIPS_MAX) return; for (int i = 0; i < gLineTripCount; i++) { if (strcmp(gLineTrips[i].line, line) == 0) return; } strlcpy(gLineTrips[gLineTripCount].line, line, sizeof(gLineTrips[0].line)); strlcpy(gLineTrips[gLineTripCount].trip, trip, sizeof(gLineTrips[0].trip)); gLineTripCount++; } static bool resolveStop(const Settings& s) { if (gStopId[0]) return true; if (s.stopId[0]) { strlcpy(gStopId, s.stopId, sizeof(gStopId)); cleanStopName(s.stopName, gStopName, sizeof(gStopName)); return true; } LocationData loc = getLocation(); if (!loc.valid) return false; char url[160]; snprintf(url, sizeof(url), "https://v6.bvg.transport.rest/locations/nearby?latitude=%.5f&longitude=%.5f&results=1&linesOfStops=false&pretty=false", loc.lat, loc.lon); JsonDocument doc; if (!httpGetJson(url, doc) || !doc[0]["id"].is()) return false; strlcpy(gStopId, doc[0]["id"], sizeof(gStopId)); cleanStopName(doc[0]["name"], gStopName, sizeof(gStopName)); Serial.printf("Haltestelle: %s (%s)\n", gStopName, gStopId); return true; } static bool fetchDepartures(const Settings& s) { if (!resolveStop(s)) return false; char url[192]; snprintf(url, sizeof(url), "https://v6.bvg.transport.rest/stops/%s/departures?duration=60&results=%d&remarks=false&linesOfStops=false&pretty=false", gStopId, MAX_DEPARTURES + 6); // Reserve für die wegen Fußweg ausgeblendeten // Die Antwort ist groß (~2 KB je Abfahrt), behalten wird nur, was die Seite braucht JsonDocument filter; JsonObject f = filter["departures"][0].to(); for (const char* key : {"tripId", "when", "plannedWhen", "delay", "direction", "cancelled"}) f[key] = true; f["line"]["name"] = true; f["line"]["product"] = true; JsonDocument doc; if (!httpGetJson(url, doc, &filter)) return false; std::unique_ptr holder(new DepartureData()); // nicht auf den Stack, wie bei fetchWeather DepartureData& d = *holder; strlcpy(d.stop, gStopName, sizeof(d.stop)); int walk = s.walkMin; time_t now = time(nullptr); gLineTripCount = 0; for (JsonObject j : doc["departures"].as()) { rememberLineTrip(j["line"]["name"] | "", j["tripId"] | ""); if (d.count >= MAX_DEPARTURES) continue; Departure& dep = d.deps[d.count]; const char* when = j["when"]; // fehlt bei Ausfällen if (!when) when = j["plannedWhen"]; dep.cancelled = j["cancelled"] | false; dep.when = parseIsoTime(when); if (dep.when == 0 || (timeValid(now) && (int32_t)(dep.when - now) < walk * 60)) continue; dep.delay = j["delay"].is() ? (int16_t)constrain(j["delay"].as(), -32000, 32000) : DELAY_UNKNOWN; dep.product = parseProduct(j["line"]["product"]); strlcpy(dep.line, j["line"]["name"] | "?", sizeof(dep.line)); cleanStopName(j["direction"], dep.direction, sizeof(dep.direction)); d.count++; } d.valid = true; d.updatedMs = millis(); { Lock l; gDepartures = d; } Serial.printf("Abfahrten %s: %d\n", d.stop, d.count); return true; } // ---------------------------------------------------------------- Weitere Quellen // Schreibt Unicode-Zeichen als UTF-8 und hört auf, bevor ein Zeichen nicht mehr ganz hineinpasst. // Typografische Anführungszeichen und Striche werden zu einfachen, weil sie in der Schrift fehlen. struct Utf8Writer { char* out; size_t len, n = 0; bool full = false; Utf8Writer(char* o, size_t l) : out(o), len(l) { out[0] = 0; } void put(uint32_t cp) { switch (cp) { case 0x00A0: cp = ' '; break; case 0x2018: case 0x2019: case 0x201A: cp = '\''; break; case 0x201C: case 0x201D: case 0x201E: cp = '"'; break; case 0x2013: case 0x2014: cp = '-'; break; case 0x2026: put('.'); put('.'); put('.'); return; } char b[4]; size_t k; if (cp < 0x80) b[0] = cp, k = 1; else if (cp < 0x800) b[0] = 0xC0 | cp >> 6, b[1] = 0x80 | (cp & 0x3F), k = 2; else if (cp < 0x10000) b[0] = 0xE0 | cp >> 12, b[1] = 0x80 | (cp >> 6 & 0x3F), b[2] = 0x80 | (cp & 0x3F), k = 3; else b[0] = 0xF0 | cp >> 18, b[1] = 0x80 | (cp >> 12 & 0x3F), b[2] = 0x80 | (cp >> 6 & 0x3F), b[3] = 0x80 | (cp & 0x3F), k = 4; if (full || n + k >= len) { full = true; return; } memcpy(out + n, b, k); n += k; out[n] = 0; } }; static uint32_t nextCodepoint(const char*& s) { uint8_t c = *s++; if (c < 0xC0) return c; int extra = c >= 0xF0 ? 3 : c >= 0xE0 ? 2 : 1; uint32_t cp = c & (0x3F >> extra); while (extra-- && (*s & 0xC0) == 0x80) cp = cp << 6 | (*s++ & 0x3F); return cp; } // Text für die Anzeige: gekürzt auf ganze Zeichen; mit xml auch &, „ usw. aufgelöst static void cleanText(const char* in, size_t inLen, char* out, size_t len, bool xml) { Utf8Writer w(out, len); const char* end = in + inLen; while (in < end && *in && !w.full) { if (xml && *in == '&') { const char* semi = (const char*)memchr(in, ';', min(end - in, 10)); if (semi) { static const struct { const char* name; char c; } NAMED[] = { {"amp", '&'}, {"lt", '<'}, {"gt", '>'}, {"quot", '"'}, {"apos", '\''}}; uint32_t cp = 0; if (in[1] == '#') cp = in[2] == 'x' ? strtoul(in + 3, nullptr, 16) : strtoul(in + 2, nullptr, 10); for (const auto& e : NAMED) { if ((size_t)(semi - in - 1) == strlen(e.name) && !strncmp(in + 1, e.name, semi - in - 1)) cp = e.c; } if (cp) { w.put(cp); in = semi + 1; continue; } } } w.put(nextCodepoint(in)); } } static void cleanText(const char* in, char* out, size_t len) { cleanText(in, strlen(in), out, len, false); } // Leerzeichen am Rand weg, webcal:// wird zu https:// static void normalizeUrl(const char* in, char* out, size_t len) { while (*in == ' ' || *in == '\t') in++; if (!strncmp(in, "webcal://", 9)) { strlcpy(out, "https://", len); strlcat(out, in + 9, len); } else { strlcpy(out, in, len); } size_t n = strlen(out); while (n && (out[n - 1] == ' ' || out[n - 1] == '\r' || out[n - 1] == '\t')) out[--n] = 0; } // Ruft fn für jede nicht leere Zeile von list auf static void forEachLine(const char* list, const std::function& fn) { while (*list) { const char* nl = strchr(list, '\n'); size_t len = nl ? nl - list : strlen(list); char url[256]; strlcpy(url, list, min(len + 1, sizeof(url))); char clean[256]; normalizeUrl(url, clean, sizeof(clean)); if (*clean) fn(clean); list += len + (nl ? 1 : 0); } } static bool fetchAir() { LocationData loc = getLocation(); char url[512]; snprintf(url, sizeof(url), "https://air-quality-api.open-meteo.com/v1/air-quality?latitude=%.4f&longitude=%.4f" "¤t=european_aqi,pm10,pm2_5,uv_index" "&hourly=uv_index,alder_pollen,birch_pollen,grass_pollen,mugwort_pollen,ragweed_pollen" "&forecast_days=2&timeformat=unixtime&timezone=auto", loc.lat, loc.lon); JsonDocument doc; if (!httpGetJson(url, doc)) return false; JsonObject cur = doc["current"], hourly = doc["hourly"]; if (cur.isNull() || hourly.isNull()) return false; AirData a; a.aqi = cur["european_aqi"] | -1; a.pm25 = cur["pm2_5"] | NAN; a.pm10 = cur["pm10"] | NAN; a.uv = cur["uv_index"] | NAN; // Stundenwerte ab heute 0 Uhr: die ersten 24 sind heute, die nächsten 24 morgen static const char* const KEYS[POLLEN_COUNT] = {"alder_pollen", "birch_pollen", "grass_pollen", "mugwort_pollen", "ragweed_pollen"}; int n = hourly["time"].size(); a.uvMax = 0; for (int i = 0; i < min(n, 24); i++) a.uvMax = fmaxf(a.uvMax, hourly["uv_index"][i] | 0.0f); for (int p = 0; p < POLLEN_COUNT; p++) { for (int day = 0; day < 2; day++) { float most = 0; for (int i = day * 24; i < min(n, day * 24 + 24); i++) most = fmaxf(most, hourly[KEYS[p]][i] | 0.0f); a.pollen[p][day] = most; } } a.valid = true; a.updatedMs = millis(); { Lock l; gAir = a; } Serial.printf("Luft: AQI %d, UV %.1f\n", a.aqi, a.uv); return true; } static bool fetchPower() { JsonDocument doc; if (!httpGetJson("https://api.energy-charts.info/signal?country=de", doc)) return false; JsonArray t = doc["unix_seconds"], share = doc["share"], signal = doc["signal"]; if (t.size() < 2) return false; std::unique_ptr holder(new PowerData()); // nicht auf den Stack, wie bei fetchWeather PowerData& p = *holder; p.start = t[0]; p.step = (uint32_t)t[1] - (uint32_t)t[0]; for (JsonVariant s : share) { if (p.count >= POWER_MAX) break; p.share[p.count++] = s.isNull() ? 255 : (uint8_t)constrain(lroundf(s.as()), 0L, 100L); } int i = 0; for (JsonVariant s : signal) { if (i < p.count) p.signal[i++] = s | 0; } p.valid = true; p.updatedMs = millis(); { Lock l; gPower = p; } Serial.printf("Strom: %d Werte\n", p.count); return true; } // "Tue, 20 Oct 2026 14:23:23 +0200" → Unix-Zeit static uint32_t parseRfc822(const char* s) { int d, y, h, mi, sec, off = 0; char mon[4], sign = '+'; if (sscanf(s, "%*[^,], %d %3s %d %d:%d:%d %c%4d", &d, mon, &y, &h, &mi, &sec, &sign, &off) < 6) return 0; const char* months = "JanFebMarAprMayJunJulAugSepOctNovDec"; const char* m = strstr(months, mon); if (!m) return 0; long offSec = (off / 100 * 3600L + off % 100 * 60L) * (sign == '-' ? -1 : 1); return daysFromCivil(y, (m - months) / 3 + 1, d) * 86400 + h * 3600L + mi * 60L + sec - offSec; } // Der RSS-Feed ist zeilenweise aufgebaut: , darin … und … static bool fetchNews() { std::unique_ptr holder(new NewsData()); // nicht auf den Stack, wie bei fetchWeather NewsData& d = *holder; NewsItem cur = {}; bool inItem = false; LineSink sink([&](const char* line) { while (*line == ' ' || *line == '\t') line++; if (!strncmp(line, "", 6)) { inItem = true; cur = {}; } else if (!strncmp(line, "", 7)) { inItem = false; if (cur.title[0] && d.count < NEWS_MAX) d.items[d.count++] = cur; } else if (inItem && !strncmp(line, "", 7)) { const char* text = line + 7; const char* end = strstr(text, ""); if (!strncmp(text, ""); if (cdataEnd && (!end || cdataEnd < end)) end = cdataEnd; cleanText(text, end ? end - text : strlen(text), cur.title, sizeof(cur.title), true); } else if (inItem && !strncmp(line, "", 9)) { cur.time = parseRfc822(line + 9); } }); bool ok = httpGet(NEWS_URL, [&](HTTPClient& http) { return http.writeToStream(&sink) > 0; }); sink.finish(); if (!ok || d.count == 0) return false; d.valid = true; d.updatedMs = millis(); { Lock l; gNews = d; } Serial.printf("Nachrichten: %d\n", d.count); return true; } static bool fetchCalendar(const Settings& s) { time_t now = time(nullptr); if (!timeValid(now)) return false; // Ab heute 0 Uhr, damit ganztägige Termine von heute dabei sind tm today = localTm(now); today.tm_hour = today.tm_min = today.tm_sec = 0; time_t from = mktime(&today); std::unique_ptr cal(new ICalCollector(from, from + (CALENDAR_DAYS + 1) * 86400L)); int loaded = 0, failed = 0; auto load = [&](const char* url, bool waste) { cal->setWaste(waste); LineSink sink([&](const char* line) { cal->line(line); }, true); bool ok = httpGet(url, [&](HTTPClient& http) { return http.writeToStream(&sink) > 0; }); sink.finish(); ok ? loaded++ : failed++; }; forEachLine(s.calUrls, [&](const char* url) { load(url, false); }); forEachLine(s.wasteUrl, [&](const char* url) { load(url, true); }); std::unique_ptr holder(new CalendarData()); // nicht auf den Stack, wie bei fetchWeather CalendarData& d = *holder; d.count = cal->finish(d.events, CAL_MAX); d.failed = failed; d.valid = loaded > 0; d.updatedMs = millis(); { Lock l; gCalendar = d; } Serial.printf("Termine: %d aus %d Kalendern, %d Fehler\n", d.count, loaded, failed); return failed == 0; } static void checkServer(const char* url, ServerStatus& st) { const char* name = strstr(url, "://"); strlcpy(st.name, name ? name + 3 : url, sizeof(st.name)); size_t n = strlen(st.name); if (n && st.name[n - 1] == '/') st.name[n - 1] = 0; st.certDays = INT_MIN; st.ms = 0; // Weiterleitungen nicht folgen: eine Antwort 3xx zählt als erreichbar WiFiClientSecure tls; WiFiClient plain; HTTPClient http; http.setConnectTimeout(5000); http.setTimeout(8000); http.useHTTP10(true); bool https = strncmp(url, "https://", 8) == 0; if (https) tls.useBuiltinCACertBundle(); if (!(https ? http.begin(tls, url) : http.begin(plain, url))) { st.code = -1; return; } uint32_t t0 = millis(); st.code = http.GET(); st.ms = millis() - t0; time_t now = time(nullptr); if (https && st.code > 0 && timeValid(now)) { if (const mbedtls_x509_crt* crt = tls.getPeerCertificate()) { const mbedtls_x509_time& v = crt->valid_to; long long expires = daysFromCivil(v.year, v.mon, v.day) * 86400LL + v.hour * 3600 + v.min * 60 + v.sec; st.certDays = (int)((expires - now) / 86400); } } http.end(); } static bool checkServers(const Settings& s) { ServerData d; forEachLine(s.servers, [&](const char* line) { if (d.count >= SERVER_MAX) return; char url[256]; if (strstr(line, "://")) strlcpy(url, line, sizeof(url)); else snprintf(url, sizeof(url), "https://%s/", line); checkServer(url, d.servers[d.count++]); }); d.valid = true; d.updatedMs = millis(); { Lock l; gServers = d; } int bad = 0; for (int i = 0; i < d.count; i++) bad += d.servers[i].code <= 0 || d.servers[i].code >= 400; Serial.printf("Server: %d geprüft, %d gestört\n", d.count, bad); return true; } static void urlEncode(const char* in, char* out, size_t len) { size_t n = 0; for (; *in && n + 4 < len; in++) { uint8_t c = *in; if (isalnum(c) || strchr("-_.~", c)) out[n++] = c; else n += snprintf(out + n, len - n, "%%%02X", c); } out[n] = 0; } // Störungsmeldungen stehen in den Fahrtdetails; je Linie an der Haltestelle wird eine Fahrt abgefragt static bool fetchWarnings() { if (gLineTripCount == 0) return false; JsonDocument filter; JsonObject f = filter["trip"]["remarks"][0].to(); for (const char* key : {"type", "id", "summary", "text"}) f[key] = true; std::unique_ptr holder(new WarningData()); // nicht auf den Stack, wie bei fetchWeather WarningData& d = *holder; int answered = 0; for (int i = 0; i < gLineTripCount; i++) { char trip[96], url[256]; urlEncode(gLineTrips[i].trip, trip, sizeof(trip)); snprintf(url, sizeof(url), "https://v6.bvg.transport.rest/trips/%s?remarks=true&stopovers=false&polyline=false&language=de&pretty=false", trip); JsonDocument doc; if (!httpGetJson(url, doc, &filter)) continue; answered++; for (JsonObject r : doc["trip"]["remarks"].as()) { if (r["type"] != "warning") continue; uint32_t id = r["id"].is() ? strtoul(r["id"], nullptr, 10) : (r["id"] | 0u); BvgWarning* w = nullptr; for (int k = 0; k < d.count; k++) { if (d.warnings[k].id == id) w = &d.warnings[k]; } if (!w) { if (d.count >= WARN_MAX) continue; w = &d.warnings[d.count++]; w->id = id; w->lines[0] = 0; cleanText(r["summary"] | "", w->summary, sizeof(w->summary)); cleanText(r["text"] | "", w->text, sizeof(w->text)); } appendItem(w->lines, sizeof(w->lines), gLineTrips[i].line); } } if (answered == 0) return false; d.valid = true; d.updatedMs = millis(); { Lock l; gWarnings = d; } Serial.printf("Störungen: %d aus %d Linien\n", d.count, answered); return true; } // Startet die Zeitsynchronisation mit vorab aufgelösten NTP-Servern. // Hintergrund (ESP32-Core 3.3): Der erste hostByName() nach dem Verbinden leert den DNS-Cache ohne // TCP/IP-Lock. Wartet SNTP in dem Moment auf eine eigene DNS-Antwort, bricht lwIP mit // "assert failed: udp_new_ip_type" ab. Mit IP-Adressen braucht SNTP kein DNS. static bool startTimeSync() { static char server1[48], server2[48]; // SNTP speichert nur die Zeiger IPAddress ip1, ip2; if (!WiFi.hostByName(NTP_SERVER_1, ip1)) return false; if (!WiFi.hostByName(NTP_SERVER_2, ip2)) ip2 = ip1; strlcpy(server1, ip1.toString().c_str(), sizeof(server1)); strlcpy(server2, ip2.toString().c_str(), sizeof(server2)); configTzTime(TZ_INFO, server1, server2); Serial.printf("NTP: %s, %s\n", server1, server2); return true; } static bool due(uint32_t deadline) { return (int32_t)(millis() - deadline) >= 0; } static void netTask(void*) { uint32_t nextLocation = 0, nextWeather = 0, nextGlucose = 0, nextGlucoseHistory = 0, nextMonitor = 0; uint32_t nextDepartures = 0, nextAir = 0, nextPower = 0, nextNews = 0, nextCalendar = 0, nextServers = 0; uint32_t nextWarnings = 0, seenGen = 0, seenSources = 0; bool timeSyncStarted = false; for (;;) { if (gOtaActive) { vTaskDelay(pdMS_TO_TICKS(500)); continue; } if (gSettingsGen != seenGen) { // Standort oder Haltestelle geändert: neu ermitteln seenGen = gSettingsGen; { Lock l; gLocation.valid = false; gDepartures.valid = false; gWarnings.valid = false; gAir.valid = false; } gStopId[0] = 0; gLineTripCount = 0; nextLocation = nextWeather = nextDepartures = nextWarnings = nextAir = millis(); } if (gSourcesGen != seenSources) { // Kalender oder Serverliste geändert seenSources = gSourcesGen; { Lock l; gCalendar = CalendarData(); gServers = ServerData(); } nextCalendar = nextServers = millis(); } static Settings s; // 1,4 KB, daher nicht auf dem Stack s = getSettings(); static uint32_t nextHeapLog = 0; if (due(nextHeapLog)) { Serial.printf("Heap frei %u, größter Block %u, Tiefstand %u, Stack netTask frei %u\n", heapFree(), heapBlock(), (unsigned)heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT), (unsigned)uxTaskGetStackHighWaterMark(nullptr)); nextHeapLog = millis() + 10 * 60000UL; } // Sucht die bekannten Netze und verbindet mit dem stärksten (blockiert einige Sekunden) if (WiFi.status() != WL_CONNECTED && wifiMulti.run() == WL_CONNECTED) { Serial.printf("WLAN: %s, IP %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str()); } if (WiFi.status() == WL_CONNECTED) { if (!timeSyncStarted) timeSyncStarted = startTimeSync(); if (due(nextGlucoseHistory)) { bool ok = fetchGlucoseHistory(); nextGlucoseHistory = millis() + (ok ? BZ_HISTORY_REFRESH_MIN * 60000UL : 60000UL); } if (due(nextGlucose)) { fetchGlucoseCurrent(); nextGlucose = millis() + BZ_REFRESH_S * 1000UL; } if (pageEnabled(s, PAGE_MONITOR) && due(nextMonitor)) { fetchMonitor(); nextMonitor = millis() + MONITOR_REFRESH_S * 1000UL; } if (!getLocation().valid && due(nextLocation)) { fetchLocation(s); nextLocation = millis() + 30000UL; } if (getLocation().valid && due(nextWeather)) { bool ok = fetchWeather(); nextWeather = millis() + (ok ? WEATHER_REFRESH_MIN * 60000UL : 60000UL); } // Die Störungsseite braucht die Linien aus den Abfahrten if ((pageEnabled(s, PAGE_DEPARTURES) || pageEnabled(s, PAGE_WARNINGS)) && due(nextDepartures)) { bool ok = fetchDepartures(s); nextDepartures = millis() + (ok ? BVG_REFRESH_S * 1000UL : 30000UL); } if (pageEnabled(s, PAGE_WARNINGS) && gLineTripCount > 0 && due(nextWarnings)) { bool ok = fetchWarnings(); nextWarnings = millis() + (ok ? 10 * 60000UL : 60000UL); } if (pageEnabled(s, PAGE_AIR) && getLocation().valid && due(nextAir)) { bool ok = fetchAir(); nextAir = millis() + (ok ? 30 * 60000UL : 60000UL); } if (pageEnabled(s, PAGE_POWER) && due(nextPower)) { bool ok = fetchPower(); nextPower = millis() + (ok ? 15 * 60000UL : 60000UL); } if (pageEnabled(s, PAGE_NEWS) && due(nextNews)) { bool ok = fetchNews(); nextNews = millis() + (ok ? 15 * 60000UL : 60000UL); } // Termine auch ohne Terminseite, die Uhr zeigt den nächsten Termin und die Müllabfuhr if ((s.calUrls[0] || s.wasteUrl[0]) && timeValid(time(nullptr)) && due(nextCalendar)) { bool ok = fetchCalendar(s); nextCalendar = millis() + (ok ? CALENDAR_REFRESH_MIN * 60000UL : 2 * 60000UL); } if (pageEnabled(s, PAGE_SERVERS) && s.servers[0] && due(nextServers)) { checkServers(s); nextServers = millis() + SERVER_REFRESH_MIN * 60000UL; } } vTaskDelay(pdMS_TO_TICKS(1000)); } } // ---------------------------------------------------------------- Bedienung struct Button { enum Event { NONE, SHORT, LONG }; static constexpr uint32_t LONG_MS = 600; int pin; bool raw = true; // zuletzt gelesener Pegel und seit wann er anliegt uint32_t rawSince = 0; bool last = true; // entprellter Zustand, true = losgelassen uint32_t changed = 0; bool longSent = false; explicit Button(int p) : pin(p) {} void begin() { raw = last = digitalRead(pin); } // Ein neuer Pegel zählt erst, wenn er 25 ms stabil anliegt. Das filtert Prellen und die kurzen Pulse, // die die Auto-Reset-Schaltung beim Öffnen der seriellen Schnittstelle auf GPIO0 erzeugen kann. bool update() { bool level = digitalRead(pin); if (level != raw) { raw = level; rawSince = millis(); } if (raw == last || millis() - rawSince < 25) return false; last = raw; changed = millis(); return true; } // true genau einmal pro Druck bool pressed() { return update() && !last; } // SHORT beim Loslassen, LONG sobald der Knopf LONG_MS gehalten wird (dann kein SHORT mehr) Event event() { if (update()) { if (!last) { longSent = false; return NONE; } return longSent ? NONE : SHORT; } if (!last && !longSent && millis() - changed >= LONG_MS) { longSent = true; return LONG; } return NONE; } }; static Button btnPage(PIN_BTN_PAGE); static Button btnOption(PIN_BTN_OPTION); static int gPage = PAGE_CLOCK; static uint32_t gLastInput = 0; static int gBrightIdx = 0; static const uint8_t BRIGHTNESS[] = {255, 140, 60, 20}; static esp_reset_reason_t gResetReason = ESP_RST_UNKNOWN; // für die Info-Seite // Zeitbereiche, die der Optionsknopf durchschaltet (Index bleibt bis zum Neustart) static const int GLUCOSE_RANGES_H[] = {3, 6, 12}; static const int METEO_RANGES_H[] = {48, 24, 12}; static int gGlucoseRange = 0, gMeteoRange = 0; // Blätterstand der aktuellen Seite; beginnt bei jedem Seitenwechsel von vorn static int gScroll = 0; static uint32_t gScrollMs = 0; // millis() beim letzten Blättern static constexpr uint32_t NEWS_PAGE_MS = 10000, WARNING_PAGE_MS = 8000; // automatisch weiter nach // Aktuelle Position; mit autoMs > 0 blättert die Seite zusätzlich alle autoMs von selbst weiter static int scrollPos(uint32_t autoMs) { int32_t since = (int32_t)(gFrameMs - gScrollMs); return gScroll + (autoMs && since > 0 ? since / autoMs : 0); } // ---------------------------------------------------------------- Zeichnen static const char* const WEEKDAYS[] = {"Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"}; static const char* const WEEKDAYS_SHORT[] = {"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"}; static const char* const MONTHS[] = {"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}; static bool timeValid(time_t t) { return t > 1700000000; } // Clip-Bereich, geschnitten mit der gerade gezeichneten Hälfte. Nie canvas.clearClipRect() verwenden: // das gäbe Zeilen frei, die außerhalb des Puffers liegen. static void clipRect(int x, int y, int w, int h) { int top = max(y, gBandTop), bottom = min(y + h, gBandTop + gBandH); canvas.setClipRect(x, top, w, bottom - top); } static void clearClip() { canvas.setClipRect(0, gBandTop, SCREEN_W, gBandH); } // LovyanGFX' drawWideLine setzt den Clip-Bereich auf die Linie, begrenzt nur auf die Sprite-Größe, und löscht // ihn danach ganz. Beim Zeichnen in Hälften schriebe es so außerhalb des Puffers. Daher wird der Sprite für // die Linie auf genau die aktuelle Hälfte gesetzt und der Clip-Bereich danach wiederhergestellt. void wideLine(float x0, float y0, float x1, float y1, float r, uint32_t color) { int32_t cx, cy, cw, ch; canvas.getClipRect(&cx, &cy, &cw, &ch); canvas.setBuffer(gBandBuf, SCREEN_W, gBandH); canvas.drawWideLine(x0, y0 - gBandTop, x1, y1 - gBandTop, r, color); canvas.setBuffer(gBandBuf - gBandTop * SCREEN_W * 2, SCREEN_W, SCREEN_H); canvas.setClipRect(cx, cy, cw, ch); } static void text(const char* s, int x, int y, uint32_t color, textdatum_t datum = textdatum_t::top_left, const lgfx::IFont* font = FONT_TEXT) { canvas.setFont(font); canvas.setTextDatum(datum); canvas.setTextColor(color); canvas.drawString(s, x, y); } // Temperatur als ganze Zahl in einer DejaVu-Schrift (nur ASCII), das ° wird als Ring gezeichnet. static int tempWidth(float value, const lgfx::IFont* font) { char buf[8]; if (isnan(value)) strcpy(buf, "--"); else snprintf(buf, sizeof(buf), "%ld", lroundf(value)); canvas.setFont(font); int capH = canvas.fontHeight() * 7 / 10; return canvas.textWidth(buf) + (isnan(value) ? 0 : (capH >= 25 ? 12 : 8)); } static int drawTemp(int x, int baseline, float value, const lgfx::IFont* font, uint32_t color) { char buf[8]; if (isnan(value)) strcpy(buf, "--"); else snprintf(buf, sizeof(buf), "%ld", lroundf(value)); text(buf, x, baseline, color, textdatum_t::baseline_left, font); int end = x + canvas.textWidth(buf); if (isnan(value)) return end; int capH = canvas.fontHeight() * 7 / 10; int r = capH >= 25 ? 4 : 3; int cx = end + r + 2; int cy = baseline - capH + r; canvas.fillSmoothCircle(cx, cy, r, color); canvas.fillSmoothCircle(cx, cy, r - (capH >= 25 ? 2 : 1), col::bg); return cx + r; } static void drawWifi(int x, int y) { int bars = 0; if (WiFi.status() == WL_CONNECTED) { int rssi = WiFi.RSSI(); bars = rssi > -55 ? 4 : rssi > -65 ? 3 : rssi > -75 ? 2 : 1; } for (int i = 0; i < 4; i++) { int h = 3 + i * 3; canvas.fillRect(x + i * 4, y + 12 - h, 3, h, i < bars ? col::text : col::faint); } if (bars == 0) canvas.fillSmoothCircle(x + 14, y + 2, 2, col::bad); } static void drawPageDots() { int n = 0; for (Page p : PAGE_ORDER) n += pageEnabled(gSettings, p); int step = min(8, 104 / max(1, n)); int y = 67 - (n - 1) * step / 2; for (Page p : PAGE_ORDER) { if (!pageEnabled(gSettings, p)) continue; canvas.fillSmoothCircle(236, y, 2, p == gPage ? col::dim : col::faint); y += step; } } static void drawCentered(const char* line1, const char* line2) { text(line1, 120, 56, col::text, textdatum_t::middle_center); if (line2) text(line2, 120, 78, col::dim, textdatum_t::middle_center); } static void drawStatusPage(time_t now) { if (WiFi.status() != WL_CONNECTED) drawCentered("Verbinde mit WLAN", "suche bekannte Netze"); else drawCentered("Hole Uhrzeit", WiFi.SSID().c_str()); for (int i = 0; i < 3; i++) { canvas.fillSmoothCircle(108 + i * 12, 104, 3, i == now % 3 ? col::text : col::faint); } } static void drawClockPage(const tm& t, time_t now, const WeatherData& w) { char buf[48]; drawWifi(222, 4); int right = drawClockStatus(now); // Wochentag ausgeschrieben, wenn er neben die Statusanzeige passt snprintf(buf, sizeof(buf), "%s, %d. %s", WEEKDAYS[t.tm_wday], t.tm_mday, MONTHS[t.tm_mon]); canvas.setFont(FONT_TEXT); if (8 + canvas.textWidth(buf) > right - 8) { snprintf(buf, sizeof(buf), "%s, %d. %s", WEEKDAYS_SHORT[t.tm_wday], t.tm_mday, MONTHS[t.tm_mon]); } text(buf, 8, 4, col::dim); // Uhrzeit groß, Sekunden klein daneben char hm[8], ss[4]; snprintf(hm, sizeof(hm), "%02d:%02d", t.tm_hour, t.tm_min); snprintf(ss, sizeof(ss), "%02d", t.tm_sec); canvas.setFont(&fonts::DejaVu56); int wHm = canvas.textWidth(hm); canvas.setFont(&fonts::DejaVu24); int x = (240 - (wHm + 4 + canvas.textWidth(ss))) / 2; text(hm, x, 68, col::text, textdatum_t::baseline_left, &fonts::DejaVu56); text(ss, x + wHm + 4, 68, col::dim, textdatum_t::baseline_left, &fonts::DejaVu24); canvas.drawFastHLine(8, 78, 224, col::faint); if (!w.valid) { text(WiFi.status() == WL_CONNECTED ? "Lade Wetter..." : "Kein WLAN", 120, 106, col::dim, textdatum_t::middle_center); return; } drawWeatherIcon(canvas, 24, 106, w.code, w.isDay, 0.95f); int end = drawTemp(48, 124, w.temp, &fonts::DejaVu40, col::text); int cx = max(end + 10, 124); text(weatherText(w.code), cx, 82, col::text); const DayForecast& today = w.days[0]; canvas.fillTriangle(cx, 111, cx + 8, 111, cx + 4, 104, col::warm); snprintf(buf, sizeof(buf), "%ld°", lroundf(today.tMax)); text(buf, cx + 11, 100, col::text); int x2 = cx + 11 + canvas.textWidth(buf) + 10; canvas.fillTriangle(x2, 104, x2 + 8, 104, x2 + 4, 111, col::cold); snprintf(buf, sizeof(buf), "%ld°", lroundf(today.tMin)); text(buf, x2 + 11, 100, col::text); // Unterste Zeile: Termin in der nächsten Stunde, sonst Regen in den nächsten 2 Stunden, sonst der Tageswert clipRect(cx, 118, 228 - cx, 17); if (nextEventText(now, buf, sizeof(buf))) { text(buf, cx, 118, col::sun); } else if (nowcastSummary(w, now, buf, sizeof(buf))) { text(buf, cx, 118, col::rain); } else { if (today.rainProb >= 0) snprintf(buf, sizeof(buf), "Regen %d%%", today.rainProb); else snprintf(buf, sizeof(buf), "gefühlt %ld°", lroundf(w.feels)); text(buf, cx, 118, col::dim); } clearClip(); } static void drawDrop(int x, int y, uint32_t color) { canvas.fillTriangle(x, y - 5, x - 3, y, x + 3, y, color); canvas.fillSmoothCircle(x, y + 1, 3, color); } static void drawForecastPage(const tm& now, const WeatherData& w) { if (!w.valid) { drawCentered("Noch keine Vorhersage", WiFi.status() == WL_CONNECTED ? "wird geladen..." : "kein WLAN"); return; } for (int i = 0; i < 3; i++) { const DayForecast& d = w.days[i]; int cx = 40 + i * 80; if (i > 0) canvas.drawFastVLine(i * 80, 8, 119, col::faint); char label[16]; if (i == 0) { strcpy(label, "Heute"); } else { tm day = now; day.tm_mday += i; day.tm_isdst = -1; mktime(&day); snprintf(label, sizeof(label), "%s %d.", WEEKDAYS_SHORT[day.tm_wday], day.tm_mday); } text(label, cx, 4, i == 0 ? col::text : col::dim, textdatum_t::top_center); drawWeatherIcon(canvas, cx, 46, d.code, true, 1.0f); drawTemp(cx - tempWidth(d.tMax, &fonts::DejaVu24) / 2, 94, d.tMax, &fonts::DejaVu24, col::text); drawTemp(cx - tempWidth(d.tMin, &fonts::DejaVu18) / 2, 113, d.tMin, &fonts::DejaVu18, col::dim); if (d.rainProb >= 0) { char buf[8]; snprintf(buf, sizeof(buf), "%d%%", d.rainProb); canvas.setFont(FONT_TEXT); int wText = canvas.textWidth(buf); int x = cx - (wText + 10) / 2; drawDrop(x + 3, 124, col::rain); text(buf, x + 10, 117, col::rain); } } } // ---------------------------------------------------------------- Meteogramm static uint32_t blend(uint32_t a, uint32_t b, float f) { f = constrain(f, 0.0f, 1.0f); uint32_t out = 0; for (int shift = 0; shift <= 16; shift += 8) { float ca = (a >> shift) & 0xFF, cb = (b >> shift) & 0xFF; out |= (uint32_t)lroundf(ca + (cb - ca) * f) << shift; } return out; } static uint32_t tempColor(float t) { static const float temps[] = {-10, 0, 10, 20, 30}; static const uint32_t colors[] = {0x9C7CFFu, 0x64B5F6u, 0x4DD0A1u, 0xFFC83Du, 0xFF5252u}; if (t <= temps[0]) return colors[0]; for (int i = 1; i < 5; i++) { if (t <= temps[i]) return blend(colors[i - 1], colors[i], (t - temps[i - 1]) / (temps[i] - temps[i - 1])); } return colors[4]; } static uint32_t gustColor(float gust) { if (gust < 30) return col::cloud; if (gust < 50) return col::sun; if (gust < 75) return col::warm; return col::bad; } static tm localTm(uint32_t t) { time_t tt = t; tm lt; localtime_r(&tt, <); return lt; } // Kleine Temperatur in DejaVu9 mit °-Ring, links oben an (x, y) static void drawSmallTemp(int x, int y, float value, uint32_t color) { char buf[8]; snprintf(buf, sizeof(buf), "%ld", lroundf(value)); text(buf, x, y, color, textdatum_t::top_left, &fonts::DejaVu9); canvas.drawCircle(x + canvas.textWidth(buf) + 2, y + 1, 1, color); } static void drawMeteogramPage(time_t now, const WeatherData& w) { // Ab der laufenden Stunde, so viele Stunden wie mit dem Optionsknopf gewählt const int range = METEO_RANGES_H[gMeteoRange]; int first = 0; while (first + 1 < w.hourCount && (time_t)w.hours[first + 1].t <= now) first++; const int n = min(range, w.hourCount - first); if (!w.valid || n < 2) { drawCentered("Kein Meteogramm", WiFi.status() == WL_CONNECTED ? "wird geladen..." : "kein WLAN"); return; } const HourForecast* hs = w.hours + first; // Aufteilung: Tage | Himmel | Diagramm | Uhrzeiten | Wind const int X0 = 20, PX = 192 / range; // Abstände in Stunden für Uhrzeiten und Windzahlen bzw. Windpfeile, je nach Zoom const int labelEvery = range > 24 ? 6 : range > 12 ? 3 : 2; const int windEvery = range > 24 ? 3 : range > 12 ? 2 : 1; constexpr int SKY_Y = 11, SKY_H = 8; constexpr int CH_Y = 20, CH_H = 76; constexpr int HOUR_Y = 98, WIND_Y = 113, WIND_TEXT_Y = 121; auto X = [&](int i) { return X0 + i * PX; }; const int xEnd = X(n - 1) + PX; // Skalen float tLo = INFINITY, tHi = -INFINITY, pLo = INFINITY, pHi = -INFINITY, rainMax = 0; int iMin = 0, iMax = 0; for (int i = 0; i < n; i++) { tLo = fminf(tLo, fminf(hs[i].temp, hs[i].dew)); tHi = fmaxf(tHi, hs[i].temp); pLo = fminf(pLo, hs[i].pressure); pHi = fmaxf(pHi, hs[i].pressure); rainMax = fmaxf(rainMax, hs[i].precip); if (hs[i].temp < hs[iMin].temp) iMin = i; if (hs[i].temp > hs[iMax].temp) iMax = i; } const int lo = (int)floorf((tLo - 1) / 5) * 5; const int hi = (int)ceilf((tHi + 1) / 5) * 5; if (pHi - pLo < 8) { // flachen Druckverlauf nicht künstlich aufblasen float mid = (pLo + pHi) / 2; pLo = mid - 4; pHi = mid + 4; } const float rainScale = rainMax <= 2 ? 2 : rainMax <= 5 ? 5 : rainMax <= 10 ? 10 : ceilf(rainMax); auto YT = [&](float t) { return CH_Y + CH_H - 1 - (t - lo) * (CH_H - 1) / (hi - lo); }; auto YP = [&](float p) { return CH_Y + CH_H - 1 - (p - pLo) * (CH_H - 1) / (pHi - pLo); }; // Himmel (Tag/Nacht + Bewölkung), Tagstunden im Diagramm aufhellen, Gewitter markieren for (int i = 0; i < n; i++) { const HourForecast& h = hs[i]; uint32_t sky = blend(h.isDay ? col::skyDay : col::skyNight, h.isDay ? col::overcastDay : col::overcastNight, h.cloud / 100.0f); canvas.fillRect(X(i), SKY_Y, PX, SKY_H, sky); if (h.isDay) canvas.fillRect(X(i), CH_Y, PX, CH_H, col::dayShade); if (h.code >= 95) { canvas.fillTriangle(X(i) + 3, SKY_Y, X(i), SKY_Y + 5, X(i) + 2, SKY_Y + 5, col::sun); canvas.fillTriangle(X(i) + 1, SKY_Y + 3, X(i) + 4, SKY_Y + 3, X(i) + 1, SKY_Y + 8, col::sun); } } // Temperaturraster const int step = hi - lo > 25 ? 10 : 5; for (int t = lo; t <= hi; t += step) { int y = YT(t); char buf[6]; canvas.drawFastHLine(X0, y, xEnd - X0, t == 0 ? col::freezing : col::faint); snprintf(buf, sizeof(buf), "%d", t); text(buf, X0 - 3, y, col::dim, textdatum_t::middle_right, &fonts::DejaVu9); } // Tage: Trennlinien um Mitternacht, Namen über dem jeweiligen Abschnitt const tm today = localTm(now); int segStart = 0; for (int i = 1; i <= n; i++) { if (i < n && localTm(hs[i].t).tm_hour != 0) continue; int sx = X(segStart), ex = i < n ? X(i) : xEnd; tm d = localTm(hs[segStart].t); char label[12]; if (d.tm_yday == today.tm_yday && d.tm_year == today.tm_year) strcpy(label, "Heute"); else snprintf(label, sizeof(label), "%s %d.", WEEKDAYS_SHORT[d.tm_wday], d.tm_mday); canvas.setFont(&fonts::DejaVu9); if (canvas.textWidth(label) + 4 <= ex - sx) text(label, (sx + ex) / 2, 1, col::dim, textdatum_t::top_center, &fonts::DejaVu9); if (i < n) canvas.drawFastVLine(X(i), 0, CH_Y + CH_H, col::separator); segStart = i; } // Niederschlag: Höhe = Menge, Deckkraft = Wahrscheinlichkeit, weiß bei Schnee for (int i = 1; i < n; i++) { const HourForecast& h = hs[i]; if (h.precip < 0.05f) continue; int bh = max(1, (int)lroundf(fminf(h.precip, rainScale) / rainScale * CH_H * 0.7f)); bool snow = h.snow * 10 / 7 >= h.precip / 2; // Schnee in cm, ca. 7:1 zu Wasser in mm uint32_t c = blend(col::bg, snow ? col::snow : col::rain, 0.35f + 0.65f * h.prob / 100.0f); canvas.fillRect(X(i) - PX + 1, CH_Y + CH_H - bh, PX - 1, bh, c); } const bool rainLabel = rainMax >= 0.05f; const int yRain = CH_Y + (int)(CH_H * 0.3f); if (rainLabel) { char buf[8]; snprintf(buf, sizeof(buf), "%gmm", rainScale); text(buf, xEnd + 2, yRain, col::rain, textdatum_t::middle_left, &fonts::DejaVu9); } // Luftdruck (dünn), Taupunkt (gestrichelt), Temperatur (dick, farbig) for (int i = 1; i < n; i++) { const HourForecast &a = hs[i - 1], &b = hs[i]; if (!isnan(a.pressure) && !isnan(b.pressure)) { canvas.drawLine(X(i - 1), YP(a.pressure), X(i), YP(b.pressure), col::pressure); } if (i % 2 && !isnan(a.dew) && !isnan(b.dew)) { canvas.drawLine(X(i - 1), YT(a.dew), X(i), YT(b.dew), col::dew); } } for (int i = 1; i < n; i++) { const HourForecast &a = hs[i - 1], &b = hs[i]; if (isnan(a.temp) || isnan(b.temp)) continue; wideLine(X(i - 1), YT(a.temp), X(i), YT(b.temp), 1.2f, tempColor((a.temp + b.temp) / 2)); } if (!isnan(hs[n - 1].pressure) && !isnan(hs[0].pressure)) { // Endwert am Linienende, darunter die Änderung über den ganzen Zeitraum int y = constrain((int)YP(hs[n - 1].pressure), CH_Y + 4, CH_Y + CH_H - 14); if (rainLabel && y >= yRain - 19 && y <= yRain + 10) y = yRain + 11 <= CH_Y + CH_H - 14 ? yRain + 11 : yRain - 20; char buf[8]; snprintf(buf, sizeof(buf), "%ld", lroundf(hs[n - 1].pressure)); text(buf, xEnd + 2, y, col::pressure, textdatum_t::middle_left, &fonts::DejaVu9); snprintf(buf, sizeof(buf), "%+ld", lroundf(hs[n - 1].pressure - hs[0].pressure)); text(buf, xEnd + 2, y + 10, col::pressure, textdatum_t::middle_left, &fonts::DejaVu9); } // Höchst- und Tiefstwert an der Kurve auto markTemp = [&](int i, bool above) { int x = constrain(X(i) - 6, X0, xEnd - 16); int y = above ? (int)YT(hs[i].temp) - 12 : (int)YT(hs[i].temp) + 4; drawSmallTemp(x, constrain(y, CH_Y + 1, CH_Y + CH_H - 10), hs[i].temp, col::text); }; markTemp(iMax, true); markTemp(iMin, false); // Jetzt-Markierung int xNow = X0 + (int)((int64_t)(now - hs[0].t) * PX / 3600); if (xNow >= X0 && xNow < xEnd) canvas.drawFastVLine(xNow, SKY_Y - 2, SKY_H + 4, col::text); // Uhrzeiten und Wind for (int i = 0; i < n; i++) { const HourForecast& h = hs[i]; int hour = localTm(h.t).tm_hour; char buf[6]; if (hour % labelEvery == 0) { snprintf(buf, sizeof(buf), "%d", hour); text(buf, X(i), HOUR_Y, col::dim, textdatum_t::top_center, &fonts::DejaVu9); } if (hour % windEvery) continue; canvas.drawFastVLine(X(i), CH_Y + CH_H, 2, col::dim); float b = (h.windDir + 180) * DEG_TO_RAD; // Pfeil zeigt, wohin der Wind weht float dx = sinf(b), dy = -cosf(b); int cx = X(i), cy = WIND_Y; uint32_t c = gustColor(h.gust); wideLine(cx - dx * 5, cy - dy * 5, cx + dx * 2, cy + dy * 2, 0.8f, c); canvas.fillTriangle(cx + dx * 5, cy + dy * 5, cx + dx - dy * 3, cy + dy + dx * 3, cx + dx + dy * 3, cy + dy - dx * 3, c); if (hour % labelEvery == 0) { snprintf(buf, sizeof(buf), "%ld", lroundf(h.wind)); text(buf, cx, WIND_TEXT_Y, col::dim, textdatum_t::top_center, &fonts::DejaVu9); } } } // ---------------------------------------------------------------- Blutzucker-Seiten static uint32_t glucoseColor(int v) { if (v < gSettings.bzLow) return col::bad; if (v <= gSettings.bzHigh) return col::ok; if (v <= gSettings.bzVeryHigh) return col::sun; return col::warm; } // Pfeil mit halber Länge r um (cx, cy) static void drawTrendArrow(int cx, int cy, int trend, uint32_t color, float r = 16) { if (trend < 1 || trend > 5) return; float a = (3 - trend) * 45 * DEG_TO_RAD; // 0 = waagerecht, positiv = nach unten float dx = cosf(a), dy = sinf(a); float k = r / 16; float tipX = cx + dx * r, tipY = cy + dy * r; float baseX = tipX - dx * 13 * k, baseY = tipY - dy * 13 * k; float head = 9 * k; wideLine(cx - dx * r, cy - dy * r, baseX, baseY, fmaxf(2.5f * k, 1.0f), color); canvas.fillTriangle(tipX, tipY, baseX - dy * head, baseY + dx * head, baseX + dy * head, baseY - dx * head, color); } // Wert, der zeitlich am nächsten an t liegt (höchstens maxDiff Sekunden entfernt), sonst -1 static int glucoseNear(const std::vector& pts, uint32_t t, uint32_t maxDiff) { int best = -1; uint32_t bestDiff = maxDiff + 1; for (const auto& p : pts) { uint32_t d = p.t > t ? p.t - t : t - p.t; if (d < bestDiff) { bestDiff = d; best = p.v; } } return best; } // Verlauf im Zeitfenster [t0, t1] im Rechteck (x, y, w, h) mit hinterlegtem Zielbereich. // Senkrechte Linien alle gridH Stunden; bei labelH > 0 Achsenbeschriftung alle labelH Stunden. // fitData skaliert auf die Werte statt auf den ganzen Zielbereich (für kleine Verläufe). static void drawGlucoseChart(const std::vector& pts, uint32_t t0, uint32_t t1, int x, int y, int w, int h, int gridH, int labelH, bool fitData) { int dLo = INT_MAX, dHi = INT_MIN; for (const auto& p : pts) { if (p.t < t0 || p.t > t1) continue; dLo = min(dLo, (int)p.v); dHi = max(dHi, (int)p.v); } int lo, hi; if (dLo > dHi) { // keine Werte im Fenster lo = gSettings.bzLow - 10; hi = gSettings.bzHigh + 10; } else if (fitData) { lo = dLo - 15; hi = dHi + 15; if (hi - lo < 60) { int mid = (lo + hi) / 2; lo = mid - 30; hi = mid + 30; } } else { lo = min(dLo, gSettings.bzLow) - 10; hi = max(dHi, gSettings.bzHigh) + 10; } lo = max(0, lo); auto X = [&](uint32_t t) { return x + (int)((int64_t)(t - t0) * (w - 1) / (t1 - t0)); }; auto Y = [&](int v) { return y + h - 1 - (v - lo) * (h - 1) / (hi - lo); }; int bandTop = constrain(Y(gSettings.bzHigh), y, y + h - 1); int bandBot = constrain(Y(gSettings.bzLow), y, y + h - 1); if (bandBot > bandTop) canvas.fillRect(x, bandTop, w, bandBot - bandTop + 1, col::band); if (labelH) { char buf[8]; for (int v : {gSettings.bzLow, gSettings.bzHigh}) { snprintf(buf, sizeof(buf), "%d", v); text(buf, x - 3, Y(v), col::dim, textdatum_t::middle_right, &fonts::DejaVu9); } } // Raster zu vollen Stunden (Ortszeit) for (uint32_t t = t0 - t0 % 3600 + 3600; t <= t1; t += 3600) { time_t tt = t; tm lt; localtime_r(&tt, <); if (lt.tm_hour % gridH) continue; canvas.drawFastVLine(X(t), y, h, col::faint); if (labelH && lt.tm_hour % labelH == 0) { char buf[4]; snprintf(buf, sizeof(buf), "%d", lt.tm_hour); text(buf, X(t), y + h + 3, col::dim, textdatum_t::top_center, &fonts::DejaVu9); } } // Kurve, bei Datenlücken über 10 Minuten unterbrochen const GlucosePoint* prev = nullptr; for (const auto& p : pts) { if (p.t < t0 || p.t > t1) continue; if (prev && p.t - prev->t <= 600) { wideLine(X(prev->t), Y(prev->v), X(p.t), Y(p.v), 1.0f, glucoseColor((prev->v + p.v) / 2)); } else { canvas.drawPixel(X(p.t), Y(p.v), glucoseColor(p.v)); } prev = &p; } } static void drawGlucosePage(time_t now) { Lock l; // zeichnet direkt aus den gemeinsamen Daten const GlucoseNow& g = gGlucose; if (!g.valid) { drawCentered("Keine Blutzuckerdaten", WiFi.status() == WL_CONNECTED ? "werden geladen..." : "kein WLAN"); return; } char buf[32]; uint32_t age = now > (time_t)g.t ? (uint32_t)(now - g.t) : 0; if (age < 60) strcpy(buf, "gerade eben"); else snprintf(buf, sizeof(buf), "vor %lu min", (unsigned long)(age / 60)); text(buf, 8, 4, age > 10 * 60 ? col::warm : col::dim); int before = glucoseNear(gGlucoseHistory, g.t - 15 * 60, 5 * 60); if (before > 0) { int delta = g.value - before; if (delta == 0) strcpy(buf, "±0 in 15 min"); else snprintf(buf, sizeof(buf), "%+d in 15 min", delta); text(buf, 228, 4, col::dim, textdatum_t::top_right); } bool stale = age > 20 * 60; uint32_t color = stale ? col::dim : glucoseColor(g.value); snprintf(buf, sizeof(buf), "%d", g.value); text(buf, 8, 84, color, textdatum_t::baseline_left, &fonts::DejaVu72); int ax = 8 + canvas.textWidth(buf) + 30; if (!stale) drawTrendArrow(ax, 50, g.trend, color); text("mg/dL", ax, 72, col::dim, textdatum_t::top_center); int range = GLUCOSE_RANGES_H[gGlucoseRange]; snprintf(buf, sizeof(buf), "%d h", range); text(buf, 228, 92, col::dim, textdatum_t::bottom_right, &fonts::DejaVu9); drawGlucoseChart(gGlucoseHistory, now - range * 3600, now, 8, 94, 220, 38, range > 6 ? 2 : 1, 0, true); } static void drawGlucoseDayPage(time_t now) { Lock l; const auto& pts = gGlucoseHistory; uint32_t t0 = now - 24 * 3600; long sum = 0; int n = 0, inRange = 0, lo = 999, hi = 0; for (const auto& p : pts) { if (p.t < t0) continue; sum += p.v; n++; if (p.v >= gSettings.bzLow && p.v <= gSettings.bzHigh) inRange++; lo = min(lo, (int)p.v); hi = max(hi, (int)p.v); } if (n == 0) { drawCentered("Kein BZ-Verlauf", WiFi.status() == WL_CONNECTED ? "wird geladen..." : "kein WLAN"); return; } drawGlucoseChart(pts, t0, now, 26, 6, 200, 86, 3, 6, false); // Kennzahlen der letzten 24 h char buf[16]; int x = 8; auto stat = [&](const char* label, const char* value) { text(label, x, 114, col::dim); x += canvas.textWidth(label) + 4; text(value, x, 114, col::text); x += canvas.textWidth(value) + 14; }; snprintf(buf, sizeof(buf), "%ld", lround((double)sum / n)); stat("Ø", buf); snprintf(buf, sizeof(buf), "%d%%", inRange * 100 / n); stat("im Ziel", buf); canvas.fillTriangle(x, 118, x + 8, 118, x + 4, 125, col::dim); snprintf(buf, sizeof(buf), "%d", lo); text(buf, x + 11, 114, col::text); x += 11 + canvas.textWidth(buf) + 8; canvas.fillTriangle(x, 125, x + 8, 125, x + 4, 118, col::dim); snprintf(buf, sizeof(buf), "%d", hi); text(buf, x + 11, 114, col::text); } // ---------------------------------------------------------------- RZ-Status static uint32_t usageColor(float pct) { if (pct >= 90) return col::bad; if (pct >= 70) return col::sun; return col::rain; } static uint32_t vmStateColor(const char* state) { if (strcmp(state, "green") == 0) return col::ok; if (strcmp(state, "yellow") == 0) return col::sun; if (strcmp(state, "red") == 0) return col::bad; return col::dim; } static void drawUsageBar(int x, int y, int w, int h, float pct) { canvas.fillRect(x, y, w, h, col::faint); if (isnan(pct)) return; canvas.fillRect(x, y, constrain((int)lroundf(pct * w / 100), 1, w), h, usageColor(pct)); } static int monitorProblems(const MonitorData& m) { int n = 0; for (int i = 0; i < m.checkCount; i++) n += !m.checks[i].ok; return n; } static uint32_t monitorColor(const MonitorData& m) { return m.concerns ? col::bad : monitorProblems(m) ? col::sun : col::ok; } static void drawMonitorPage() { MonitorData m = getMonitor(); if (!m.valid) { drawCentered("Kein RZ-Status", WiFi.status() == WL_CONNECTED ? "wird geladen..." : "kein WLAN"); return; } int problems = monitorProblems(m); // Kopf: Gesamtzustand und Alter der Daten char buf[32]; text("RZ", 8, 4, col::dim); int x = 8 + canvas.textWidth("RZ") + 8; if (problems) snprintf(buf, sizeof(buf), "%d Störung%s", problems, problems == 1 ? "" : "en"); else if (m.concerns) snprintf(buf, sizeof(buf), "%d Concern%s", m.concerns, m.concerns == 1 ? "" : "s"); else strcpy(buf, "alles ok"); text(buf, x, 4, monitorColor(m)); uint32_t age = (millis() - m.updatedMs) / 1000; if (age < 60) strcpy(buf, "gerade eben"); else snprintf(buf, sizeof(buf), "vor %lu min", (unsigned long)(age / 60)); text(buf, 228, 4, age > 5 * 60 ? col::warm : col::dim, textdatum_t::top_right); // Links die Bereiche mit Ampel const int pitch = min(17, 88 / max(1, m.checkCount)); for (int i = 0; i < m.checkCount; i++) { const MonitorCheck& c = m.checks[i]; int y = 28 + i * pitch; canvas.fillSmoothCircle(12, y + 8, 4, c.ok ? col::ok : col::sun); text(c.name, 22, y, c.ok ? col::text : col::sun); } // Rechts die VMware-Hosts: Ampel, CPU-Last, belegter Speicher constexpr int HX = 108, CPU_X = 142, MEM_X = 188, BAR_W = 40; if (m.hostCount) { text("CPU", CPU_X, 28, col::dim, textdatum_t::top_left, &fonts::DejaVu9); text("RAM", MEM_X, 28, col::dim, textdatum_t::top_left, &fonts::DejaVu9); } const int hostPitch = min(13, 74 / max(1, m.hostCount)); for (int i = 0; i < m.hostCount; i++) { const VmHost& h = m.hosts[i]; int y = 40 + i * hostPitch; canvas.fillSmoothCircle(HX, y + 4, 2, vmStateColor(h.state)); text(h.name, HX + 5, y, col::text, textdatum_t::top_left, &fonts::DejaVu9); drawUsageBar(CPU_X, y + 1, BAR_W, 7, h.cpu); drawUsageBar(MEM_X, y + 1, BAR_W, 7, h.mem); } // Unten, was genau nicht stimmt clipRect(0, 0, 228, 135); x = 8; for (int i = 0; i < m.checkCount; i++) { const MonitorCheck& c = m.checks[i]; if (c.ok) continue; text(c.name, x, 119, col::sun, textdatum_t::top_left, &fonts::efontJA_12); x += canvas.textWidth(c.name) + 4; text(c.detail, x, 119, col::text, textdatum_t::top_left, &fonts::efontJA_12); x += canvas.textWidth(c.detail) + 10; } if (m.concerns) { snprintf(buf, sizeof(buf), "Concerns %d", m.concerns); text(buf, x, 119, col::bad, textdatum_t::top_left, &fonts::efontJA_12); } clearClip(); } // Rechts oben neben dem WLAN-Symbol: Blutzucker mit Trend und RZ-Ampel. Liefert den linken Rand. static int drawClockStatus(time_t now) { int x = 216; if (pageEnabled(gSettings, PAGE_MONITOR)) { MonitorData m = getMonitor(); if (m.valid) { canvas.fillSmoothCircle(x - 3, 12, 3, monitorColor(m)); x -= 12; } } GlucoseNow g; { Lock l; g = gGlucose; } if (uint32_t bin = wasteSoon(now)) { // Müllabfuhr heute oder morgen drawBin(x - 9, 7, bin); x -= 15; } if (!g.valid) return x; bool stale = now - (time_t)g.t > 20 * 60; uint32_t color = stale ? col::dim : glucoseColor(g.value); if (!stale && g.trend >= 1 && g.trend <= 5) { drawTrendArrow(x - 6, 12, g.trend, color, 6); x -= 15; } char buf[8]; snprintf(buf, sizeof(buf), "%d", g.value); text(buf, x, 4, color, textdatum_t::top_right); return x - canvas.textWidth(buf); } // Bricht Text an Leerzeichen um; die letzte Zeile endet mit "...", wenn nicht alles passt. // Liefert die Zahl der Zeilen. static int drawWrapped(const char* s, int x, int y, int w, int maxLines, int lineH, uint32_t color, const lgfx::IFont* font) { canvas.setFont(font); char line[200]; int lines = 0; while (*s && lines < maxLines) { while (*s == ' ') s++; // So viele Wörter wie in die Breite passen const char* fit = nullptr; for (const char* end = s;;) { while (*end && *end != ' ') end++; size_t n = min((size_t)(end - s), sizeof(line) - 1); memcpy(line, s, n); line[n] = 0; if (fit && canvas.textWidth(line) > w) break; fit = end; // das erste Wort immer, notfalls wird es abgeschnitten if (!*end || canvas.textWidth(line) > w) break; end++; } size_t n = min((size_t)(fit - s), sizeof(line) - 1); memcpy(line, s, n); line[n] = 0; s = fit; while (*s == ' ') s++; if (*s && lines == maxLines - 1) { // letzte Zeile, es fehlt noch Text while (n > 0) { char test[204]; snprintf(test, sizeof(test), "%s...", line); if (canvas.textWidth(test) <= w) break; do n--; while (n > 0 && ((uint8_t)line[n] & 0xC0) == 0x80); // ganzes UTF-8-Zeichen entfernen line[n] = 0; } strlcat(line, "...", sizeof(line)); } clipRect(x, y, w, lineH); text(line, x, y, color, textdatum_t::top_left, font); clearClip(); y += lineH; lines++; } return lines; } static void hhmm(uint32_t t, char* out, size_t len) { tm lt = localTm(t); snprintf(out, len, "%02d:%02d", lt.tm_hour, lt.tm_min); } // ---------------------------------------------------------------- Regen static constexpr float RAIN_MIN = 0.05f; // mm je Viertelstunde, darunter gilt es als trocken // Abschnitt i umfasst die 15 Minuten vor seinem Zeitstempel static uint32_t slotStart(const WeatherData& w, int i) { return w.nowcastStart + (i - 1) * 900; } static int currentSlot(const WeatherData& w, time_t now) { return constrain((int)((now - (time_t)w.nowcastStart) / 900) + 1, 0, max(0, w.nowcastCount - 1)); } // Kurzfassung der nächsten zwei Stunden; true, wenn es dabei regnet oder schneit static bool nowcastSummary(const WeatherData& w, time_t now, char* buf, size_t len) { buf[0] = 0; if (!w.valid || w.nowcastCount == 0) return false; int first = currentSlot(w, now); int last = min(w.nowcastCount, first + 8); bool wetNow = w.nowcast[first] >= RAIN_MIN; int change = -1; for (int i = first + 1; i < last && change < 0; i++) { if ((w.nowcast[i] >= RAIN_MIN) != wetNow) change = i; } char hm[6]; if (wetNow) { const char* what = w.nowcastSnow[first] ? "Schnee" : "Regen"; if (change < 0) { snprintf(buf, len, "%s hält an", what); } else { hhmm(slotStart(w, change), hm, sizeof(hm)); snprintf(buf, len, "%s bis %s", what, hm); } return true; } if (change < 0) { hhmm(slotStart(w, last), hm, sizeof(hm)); snprintf(buf, len, "Trocken bis %s", hm); return false; } hhmm(slotStart(w, change), hm, sizeof(hm)); snprintf(buf, len, "%s ab %s", w.nowcastSnow[change] ? "Schnee" : "Regen", hm); return true; } static void drawRainPage(time_t now, const WeatherData& w) { if (!w.valid || w.nowcastCount == 0) { drawCentered("Keine Regenvorhersage", WiFi.status() == WL_CONNECTED ? "wird geladen..." : "kein WLAN"); return; } char buf[48]; bool wet = nowcastSummary(w, now, buf, sizeof(buf)); text(buf, 8, 4, wet ? col::rain : col::ok); int first = currentSlot(w, now); int n = min(8, w.nowcastCount - first); float total = 0, peak = 0; for (int i = first; i < first + n; i++) { total += w.nowcast[i]; peak = fmaxf(peak, w.nowcast[i] * 4); } if (total >= RAIN_MIN) { snprintf(buf, sizeof(buf), "%.1f mm", total); text(buf, 228, 4, col::dim, textdatum_t::top_right); } // Balken je Viertelstunde, Höhe nach Wurzel der Intensität, damit auch Nieselregen sichtbar bleibt constexpr int X0 = 16, SLOT = 26, Y0 = 30, H = 70; // X0 lässt Platz für die halbe erste Uhrzeit canvas.drawFastHLine(X0, Y0 + H, SLOT * 8, col::faint); for (int k = 0; k < n; k++) { int i = first + k; float mmh = w.nowcast[i] * 4; int x = X0 + k * SLOT; if (mmh >= RAIN_MIN * 4) { int h = max(2, (int)(sqrtf(fminf(mmh, 20) / 20) * H)); canvas.fillRect(x + 2, Y0 + H - h, SLOT - 4, h, w.nowcastSnow[i] ? col::snow : col::rain); snprintf(buf, sizeof(buf), "%.1f", mmh); text(buf, x + SLOT / 2, Y0 + H - h - 11, col::dim, textdatum_t::top_center, &fonts::DejaVu9); } if (k % 2 == 0) { hhmm(slotStart(w, i), buf, sizeof(buf)); canvas.drawFastVLine(x, Y0 + H, 3, col::dim); text(buf, x, Y0 + H + 5, col::dim, textdatum_t::top_center, &fonts::DejaVu9); } } int xNow = X0 + (int)((now - (time_t)slotStart(w, first)) * SLOT / 900); canvas.drawFastVLine(constrain(xNow, X0, X0 + SLOT * 8), Y0 - 2, H + 2, col::text); if (peak >= RAIN_MIN * 4) { snprintf(buf, sizeof(buf), "bis %.1f mm/h, %s", peak, peak < 2.5f ? "leicht" : peak < 10 ? "mäßig" : "stark"); } else { strcpy(buf, "Werte in mm/h je Viertelstunde"); } text(buf, 8, 120, col::dim, textdatum_t::top_left, &fonts::efontJA_12); } // ---------------------------------------------------------------- Luft und Pollen static uint32_t aqiColor(int aqi) { static const uint32_t COLORS[] = {col::ok, 0x9BE05Fu, col::sun, col::warm, col::bad, 0xB04CFFu}; return COLORS[constrain(aqi / 20, 0, 5)]; } static const char* aqiText(int aqi) { static const char* const TEXT[] = {"sehr gut", "gut", "mäßig", "schlecht", "sehr schlecht", "extrem schlecht"}; return TEXT[constrain(aqi / 20, 0, 5)]; } static int uvLevel(float uv) { return uv < 3 ? 0 : uv < 6 ? 1 : uv < 8 ? 2 : uv < 11 ? 3 : 4; } // Stufe 0 bis 3 (keine, gering, mittel, hoch); Grenzen in Pollen/m³, grob nach den üblichen Pollenflug-Skalen static int pollenLevel(int type, float v) { static const float LIMITS[POLLEN_COUNT][3] = {{1, 10, 50}, {1, 10, 50}, {1, 10, 30}, {1, 5, 15}, {1, 5, 10}}; int level = 0; for (int i = 0; i < 3; i++) level += v >= LIMITS[type][i]; return level; } static void drawLevelBar(int x, int y, int level) { static const uint32_t COLORS[] = {col::ok, col::sun, col::bad}; for (int i = 0; i < 3; i++) canvas.fillRect(x + i * 15, y, 13, 6, i < level ? COLORS[level - 1] : col::faint); } static void drawAirPage() { AirData a = getAir(); if (!a.valid) { drawCentered("Keine Luftdaten", WiFi.status() == WL_CONNECTED ? "werden geladen..." : "kein WLAN"); return; } char buf[40]; static const uint32_t UV_COLORS[] = {col::ok, col::sun, col::warm, col::bad, 0xB04CFFu}; static const char* const UV_TEXT[] = {"niedrig", "mäßig", "hoch", "sehr hoch", "extrem"}; text("Luft", 8, 4, col::dim); if (a.aqi >= 0) text(aqiText(a.aqi), 56, 4, aqiColor(a.aqi)); snprintf(buf, sizeof(buf), "PM2,5 %.0f PM10 %.0f", a.pm25, a.pm10); text(buf, 228, 6, col::dim, textdatum_t::top_right, &fonts::efontJA_12); text("UV", 8, 24, col::dim); snprintf(buf, sizeof(buf), "%.0f %s", a.uv, UV_TEXT[uvLevel(a.uv)]); text(buf, 56, 24, UV_COLORS[uvLevel(a.uv)]); snprintf(buf, sizeof(buf), "heute bis %.0f", a.uvMax); text(buf, 228, 26, col::dim, textdatum_t::top_right, &fonts::efontJA_12); canvas.drawFastHLine(8, 45, 220, col::faint); static const char* const NAMES[POLLEN_COUNT] = {"Erle", "Birke", "Gräser", "Beifuß", "Ambrosia"}; bool any = false; for (int p = 0; p < POLLEN_COUNT; p++) any |= pollenLevel(p, a.pollen[p][0]) || pollenLevel(p, a.pollen[p][1]); text("Pollen", 8, 50, col::dim); if (!any) { text("keine, auch morgen", 64, 50, col::ok); return; } text("heute", 132, 52, col::dim, textdatum_t::top_center, &fonts::efontJA_12); text("morgen", 196, 52, col::dim, textdatum_t::top_center, &fonts::efontJA_12); for (int p = 0; p < POLLEN_COUNT; p++) { int y = 68 + p * 13; text(NAMES[p], 20, y, col::text, textdatum_t::top_left, &fonts::efontJA_12); drawLevelBar(110, y + 3, pollenLevel(p, a.pollen[p][0])); drawLevelBar(174, y + 3, pollenLevel(p, a.pollen[p][1])); } } // ---------------------------------------------------------------- Sonne und Mond // Mond mit beleuchtetem Anteil; zunehmend ist rechts hell (Nordhalbkugel) static void drawMoon(int cx, int cy, int r, double fraction) { canvas.fillCircle(cx, cy, r, 0x2A3140u); double c = cos(2 * M_PI * fraction); for (int dy = -r; dy <= r; dy++) { double half = sqrt((double)r * r - dy * dy); long a = lround(fraction < 0.5 ? half * c : -half); long b = lround(fraction < 0.5 ? half : -half * c); if (b > a) canvas.drawFastHLine(cx + a, cy + dy, b - a, col::moon); } } static void dateLabel(time_t t, char* buf, size_t len) { tm lt = localTm(t); snprintf(buf, len, "%s %d.%d.", WEEKDAYS_SHORT[lt.tm_wday], lt.tm_mday, lt.tm_mon + 1); } static void drawSunPage(time_t now, const WeatherData& w) { char buf[48], hm[8]; const DayForecast& d0 = w.days[0]; if (w.valid && d0.sunrise && d0.sunset > d0.sunrise) { // Bogen von Auf- bis Untergang, die Sonne steht an der aktuellen Stelle constexpr int CX = 120, CY = 62, R = 44; canvas.drawFastHLine(8, CY, 220, col::faint); for (int a = 0; a <= 180; a += 6) { canvas.drawPixel(CX + lround(R * cos(a * DEG_TO_RAD)), CY - lround(R * sin(a * DEG_TO_RAD)), col::dim); } double f = (double)(now - (time_t)d0.sunrise) / (d0.sunset - d0.sunrise); if (f >= 0 && f <= 1) { double a = M_PI * (1 - f); canvas.fillSmoothCircle(CX + lround(R * cos(a)), CY - lround(R * sin(a)), 6, col::sun); } text("Aufgang", 8, CY - 36, col::dim, textdatum_t::top_left, &fonts::efontJA_12); hhmm(d0.sunrise, hm, sizeof(hm)); text(hm, 8, CY - 21, col::text); text("Untergang", 228, CY - 36, col::dim, textdatum_t::top_right, &fonts::efontJA_12); hhmm(d0.sunset, hm, sizeof(hm)); text(hm, 228, CY - 21, col::text, textdatum_t::top_right); int mins = lroundf(d0.daylight / 60); long diff = w.days[1].daylight ? lroundf((w.days[1].daylight - d0.daylight) / 60) : 0; if (diff) snprintf(buf, sizeof(buf), "Tag %d:%02d h, morgen %ld min %s", mins / 60, mins % 60, labs(diff), diff < 0 ? "kürzer" : "länger"); else snprintf(buf, sizeof(buf), "Tag %d:%02d h", mins / 60, mins % 60); text(buf, 120, CY + 5, col::dim, textdatum_t::top_center, &fonts::efontJA_12); } else { text("Sonnenzeiten fehlen noch", 120, 30, col::dim, textdatum_t::top_center); } // Mond: Phase, Beleuchtung und der nächste Voll- oder Neumond MoonInfo m = moonInfo(now); drawMoon(32, 108, 20, m.fraction); text(moonPhaseName(m.fraction), 64, 88, col::text); bool fullFirst = m.nextFull < m.nextNew; char date[16]; dateLabel(fullFirst ? m.nextFull : m.nextNew, date, sizeof(date)); snprintf(buf, sizeof(buf), "%.0f %% hell, %s %s", m.illum * 100, fullFirst ? "Vollmond" : "Neumond", date); text(buf, 64, 108, col::dim, textdatum_t::top_left, &fonts::efontJA_12); } // ---------------------------------------------------------------- Termine static bool containsNoCase(const char* s, const char* part) { for (; *s; s++) { if (strncasecmp(s, part, strlen(part)) == 0) return true; } return false; } // Farbe der Tonne nach dem Namen des Abfuhrtermins static uint32_t wasteColor(const char* s) { if (containsNoCase(s, "bio")) return 0x8D6E63u; if (containsNoCase(s, "papier") || containsNoCase(s, "pappe")) return 0x4FA3FFu; if (containsNoCase(s, "wert") || containsNoCase(s, "gelb") || containsNoCase(s, "verpack")) return col::sun; if (containsNoCase(s, "glas")) return col::ok; if (containsNoCase(s, "baum")) return 0x2E7D32u; return 0x9E9E9Eu; // Hausmüll und alles andere } static void drawBin(int x, int y, uint32_t color) { canvas.fillRect(x + 3, y, 3, 2, color); // Griff canvas.fillRect(x, y + 2, 9, 2, color); // Deckel canvas.fillRect(x + 1, y + 5, 7, 7, color); // Tonne } static long localDay(time_t t) { tm lt = localTm(t); return daysFromCivil(lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday); } // Farbe der Tonne, wenn heute oder morgen abgeholt wird, sonst 0 static uint32_t wasteSoon(time_t now) { Lock l; long today = localDay(now); for (int i = 0; i < gCalendar.count; i++) { const CalEvent& e = gCalendar.events[i]; long d = localDay(e.start); if (e.waste && d >= today && d <= today + 1) return wasteColor(e.summary); } return 0; } // Termin mit Uhrzeit in der nächsten Stunde als "15:30 Zahnarzt" static bool nextEventText(time_t now, char* buf, size_t len) { Lock l; for (int i = 0; i < gCalendar.count; i++) { const CalEvent& e = gCalendar.events[i]; if (e.allDay || e.waste || e.start < now) continue; if (e.start - now > 3600) return false; // sortiert, später kommt nichts Näheres char hm[8]; hhmm(e.start, hm, sizeof(hm)); snprintf(buf, len, "%s %s", hm, e.summary); return true; } return false; } static void drawCalendarPage(time_t now) { if (!gSettings.calUrls[0] && !gSettings.wasteUrl[0]) { drawCentered("Kein Kalender eingetragen", "im Browser: " HOSTNAME ".local"); return; } Lock l; const CalendarData& c = gCalendar; if (!c.valid) { drawCentered("Keine Termine", c.failed ? "Kalender nicht erreichbar" : "werden geladen..."); return; } long today = localDay(now), lastDay = LONG_MIN; auto over = [&](const CalEvent& e) { return e.end <= now && !(e.allDay && localDay(e.start) == today); }; int total = 0; for (int i = 0; i < c.count; i++) total += !over(c.events[i]); int skip = scrollPos(0) % max(1, (total + 6) / 7) * 7; // sieben pro Bild, Optionsknopf blättert int rows = 0; char buf[16]; for (int i = 0; i < c.count && rows < 7; i++) { const CalEvent& e = c.events[i]; if (over(e) || skip-- > 0) continue; int y = 4 + rows++ * 18; long day = max(localDay(e.start), today); // laufende mehrtägige Termine stehen bei heute if (day != lastDay) { if (day == today) strcpy(buf, "Heute"); else if (day == today + 1) strcpy(buf, "Morgen"); else { // ohne Monat: innerhalb von 14 Tagen eindeutig, und so passt es vor die Uhrzeit tm lt = localTm(e.start); snprintf(buf, sizeof(buf), "%s %d.", WEEKDAYS_SHORT[lt.tm_wday], lt.tm_mday); } text(buf, 8, y, day == today ? col::text : col::dim); lastDay = day; } int x = 64; if (e.waste) { drawBin(x, y + 2, wasteColor(e.summary)); x += 15; } else if (!e.allDay) { bool running = e.start <= now; hhmm(e.start, buf, sizeof(buf)); text(running ? "jetzt" : buf, x, y, running ? col::sun : col::text); x += 48; } clipRect(x, y, 228 - x, 18); text(e.summary, x, y, col::text); clearClip(); } if (rows == 0) drawCentered("Keine Termine", "in den nächsten 14 Tagen"); if (c.failed) canvas.fillSmoothCircle(231, 6, 2, col::bad); // ein Kalender ließ sich nicht laden } // ---------------------------------------------------------------- Server static uint32_t serverColor(const ServerStatus& st) { if (st.code <= 0 || st.code >= 500 || (st.certDays != INT_MIN && st.certDays < 3)) return col::bad; if (st.code >= 400 || (st.certDays != INT_MIN && st.certDays < 14)) return col::sun; return col::ok; } static void drawServersPage() { if (!gSettings.servers[0]) { drawCentered("Keine Server eingetragen", "im Browser: " HOSTNAME ".local"); return; } Lock l; const ServerData& d = gServers; if (!d.valid) { drawCentered("Server werden geprüft", WiFi.status() == WL_CONNECTED ? "einen Moment..." : "kein WLAN"); return; } char buf[32]; int problems = 0; for (int i = 0; i < d.count; i++) problems += serverColor(d.servers[i]) != col::ok; text("Server", 8, 4, col::dim); if (problems) snprintf(buf, sizeof(buf), "%d Problem%s", problems, problems == 1 ? "" : "e"); else strcpy(buf, "alle ok"); text(buf, 64, 4, problems ? col::sun : col::ok); uint32_t age = (millis() - d.updatedMs) / 60000; snprintf(buf, sizeof(buf), "vor %lu min", (unsigned long)age); text(buf, 228, 6, col::dim, textdatum_t::top_right, &fonts::efontJA_12); for (int i = 0; i < d.count; i++) { const ServerStatus& st = d.servers[i]; int y = 26 + i * 18; uint32_t c = serverColor(st); canvas.fillSmoothCircle(12, y + 8, 4, c); // Rechts: Zertifikat in Tagen, davor die Antwortzeit oder der Fehler int right = 228; if (st.code > 0 && st.certDays != INT_MIN) { snprintf(buf, sizeof(buf), "%d T", st.certDays); text(buf, right, y, st.certDays < 14 ? c : col::dim, textdatum_t::top_right); right -= canvas.textWidth(buf) + 10; } if (st.code <= 0) strcpy(buf, "nicht erreichbar"); else if (st.code >= 400) snprintf(buf, sizeof(buf), "Fehler %d", st.code); else snprintf(buf, sizeof(buf), "%d ms", st.ms); text(buf, right, y, st.code <= 0 || st.code >= 400 ? c : col::text, textdatum_t::top_right); right -= canvas.textWidth(buf) + 8; clipRect(22, y, right - 22, 18); text(st.name, 22, y, col::text); clearClip(); } } // ---------------------------------------------------------------- BVG-Störungen static void drawWarningsPage() { Lock l; const WarningData& d = gWarnings; if (!d.valid) { drawCentered("Keine Störungsmeldungen", WiFi.status() == WL_CONNECTED ? "werden geladen..." : "kein WLAN"); return; } if (d.count == 0) { drawCentered("Keine Störungen", "auf den Linien hier"); return; } // Mehrere Meldungen wechseln von selbst oder mit dem Optionsknopf int i = scrollPos(WARNING_PAGE_MS) % d.count; const BvgWarning& w = d.warnings[i]; char buf[12]; snprintf(buf, sizeof(buf), "%d/%d", i + 1, d.count); text(buf, 228, 4, col::dim, textdatum_t::top_right); clipRect(8, 4, 228 - 8 - canvas.textWidth(buf) - 8, 18); text(w.lines, 8, 4, col::sun); clearClip(); drawWrapped(w.summary, 8, 23, 220, 1, 18, col::text, FONT_TEXT); drawWrapped(w.text, 8, 43, 220, 7, 13, col::cloud, &fonts::efontJA_12); } // ---------------------------------------------------------------- Strommix static uint32_t signalColor(int s) { return s >= 2 ? col::ok : s == 1 ? col::sun : col::bad; } static void drawPowerPage(time_t now) { Lock l; const PowerData& p = gPower; if (!p.valid || p.count == 0) { drawCentered("Kein Strommix", WiFi.status() == WL_CONNECTED ? "wird geladen..." : "kein WLAN"); return; } int cur = constrain((int)((now - (time_t)p.start) / p.step), 0, p.count - 1); while (cur > 0 && p.share[cur] == 255) cur--; // jüngster bekannter Wert // Kopf: Anteil jetzt und Ampel char buf[48]; static const char* const SIGNAL_TEXT[] = {"Netzengpass", "ungünstig", "mittel", "günstig"}; text("Ökostrom", 8, 4, col::dim); snprintf(buf, sizeof(buf), "%d %%", p.share[cur]); text(buf, 84, 4, signalColor(p.signal[cur])); text(SIGNAL_TEXT[constrain(p.signal[cur] + 1, 0, 3)], 228, 4, signalColor(p.signal[cur]), textdatum_t::top_right); // Wann heute (oder in den vorhergesagten Stunden) am meisten kommt int best = cur; for (int i = cur; i < p.count; i++) { if (p.share[i] != 255 && p.share[i] > p.share[best]) best = i; } if (best != cur) { char hm[8]; hhmm(p.start + best * p.step, hm, sizeof(hm)); snprintf(buf, sizeof(buf), "am meisten um %s (%d %%)", hm, p.share[best]); } else { strcpy(buf, "jetzt ist der beste Zeitpunkt"); } text(buf, 8, 24, col::dim, textdatum_t::top_left, &fonts::efontJA_12); // Verlauf: Balken je Viertelstunde in der Ampelfarbe, Vergangenes abgedunkelt constexpr int Y0 = 42, H = 62, W = 216; int bw = max(1, W / p.count); int x0 = 8 + (W - bw * p.count) / 2; for (int i = 0; i < p.count; i++) { if (p.share[i] == 255) continue; int h = max(1, p.share[i] * H / 100); uint32_t c = signalColor(p.signal[i]); canvas.fillRect(x0 + i * bw, Y0 + H - h, bw, h, i < cur ? blend(col::bg, c, 0.45f) : c); } canvas.drawFastHLine(x0, Y0 + H, bw * p.count, col::faint); canvas.drawFastVLine(x0 + cur * bw + bw / 2, Y0 - 4, H + 6, col::text); for (int i = 0; i < p.count; i++) { tm lt = localTm(p.start + i * p.step); if (lt.tm_min != 0 || lt.tm_hour % 6) continue; snprintf(buf, sizeof(buf), "%d", lt.tm_hour); text(buf, x0 + i * bw, Y0 + H + 4, col::dim, textdatum_t::top_center, &fonts::DejaVu9); } text("Anteil Erneuerbarer am Verbrauch", 8, 121, col::dim, textdatum_t::top_left, &fonts::efontJA_12); } // ---------------------------------------------------------------- Nachrichten static void drawNewsPage() { Lock l; const NewsData& d = gNews; if (!d.valid) { drawCentered("Keine Nachrichten", WiFi.status() == WL_CONNECTED ? "werden geladen..." : "kein WLAN"); return; } // Je drei Meldungen, die nächsten nach NEWS_PAGE_MS oder mit dem Optionsknopf constexpr int PER = 3; int screens = (d.count + PER - 1) / PER; int first = scrollPos(NEWS_PAGE_MS) % screens * PER; int y = 4; for (int i = first; i < min(d.count, first + PER); i++) { y += drawWrapped(d.items[i].title, 8, y, 220, 2, 17, col::text, FONT_TEXT) * 17 + 8; } } // ---------------------------------------------------------------- Abfahrten static uint32_t productColor(Product p) { switch (p) { case Product::Suburban: return col::sbahn; case Product::Subway: return col::ubahn; case Product::Tram: return col::tram; case Product::Bus: return col::bus; case Product::Ferry: return col::ferry; case Product::Regional: return col::regional; default: return col::cloudDk; } } static void drawDeparturesPage(time_t now) { DepartureData d = getDepartures(); if (!d.valid) { drawCentered("Keine Abfahrten", WiFi.status() == WL_CONNECTED ? "werden geladen..." : "kein WLAN"); return; } // Kopf: Haltestelle, rechts die Uhrzeit oder das Alter veralteter Daten char buf[48]; uint32_t age = (millis() - d.updatedMs) / 1000; if (age > 3 * 60) { snprintf(buf, sizeof(buf), "vor %lu min", (unsigned long)(age / 60)); } else { tm lt = localTm(now); snprintf(buf, sizeof(buf), "%02d:%02d", lt.tm_hour, lt.tm_min); } text(buf, 228, 4, age > 3 * 60 ? col::warm : col::dim, textdatum_t::top_right); int stopW = 228 - canvas.textWidth(buf) - 8 - 8; char stop[sizeof(d.stop)]; strlcpy(stop, d.stop, sizeof(stop)); char* paren = strstr(stop, " ("); // Zusatz in Klammern weglassen, wenn der Name sonst nicht passt if (paren && canvas.textWidth(stop) > stopW) *paren = 0; clipRect(0, 0, 8 + stopW, 24); text(stop, 8, 4, col::dim); clearClip(); // Linie, Richtung, Minuten: grün pünktlich, orange verspätet, weiß ohne Echtzeitdaten. // Sechs pro Bild, der Optionsknopf blättert weiter. auto reachable = [&](const Departure& dep) { return (int32_t)(dep.when - now) >= gSettings.walkMin * 60 - 30; }; int total = 0; for (int i = 0; i < d.count; i++) total += reachable(d.deps[i]); int skip = scrollPos(0) % max(1, (total + 5) / 6) * 6; int rows = 0; for (int i = 0; i < d.count && rows < 6; i++) { const Departure& dep = d.deps[i]; int32_t secs = (int32_t)(dep.when - now); if (!reachable(dep) || skip-- > 0) continue; int y = 24 + rows++ * 18; canvas.fillRoundRect(8, y + 1, 32, 15, 3, dep.cancelled ? col::faint : productColor(dep.product)); clipRect(8, y, 32, 18); text(dep.line, 24, y + 9, col::text, textdatum_t::middle_center, &fonts::efontJA_12); clearClip(); if (dep.cancelled) { strcpy(buf, "fällt aus"); } else if (secs < 60) { strcpy(buf, "jetzt"); } else if (secs < 3600) { snprintf(buf, sizeof(buf), "%ld min", (long)(secs / 60)); } else { tm lt = localTm(dep.when); snprintf(buf, sizeof(buf), "%02d:%02d", lt.tm_hour, lt.tm_min); } uint32_t mc = dep.cancelled ? col::bad : dep.delay == DELAY_UNKNOWN ? col::text : dep.delay >= 120 ? col::warm : col::ok; text(buf, 228, y, mc, textdatum_t::top_right); int minX = 228 - canvas.textWidth(buf); clipRect(46, y, minX - 6 - 46, 18); text(dep.direction, 46, y, dep.cancelled ? col::dim : col::text); clearClip(); } if (rows == 0) drawCentered("Keine Abfahrten", "in der nächsten Stunde"); } static void drawInfoPage(const WeatherData& w) { LocationData loc = getLocation(); bool online = WiFi.status() == WL_CONNECTED; char buf[48]; const char* labels[] = {"WLAN", "IP", "Ort", "Wetter", "Strom", "Laufzeit", "Neustart", "Speicher"}; String values[8]; values[0] = online ? WiFi.SSID() + ", " + String(WiFi.RSSI()) + " dBm" : String("nicht verbunden"); values[1] = online ? WiFi.localIP().toString() : String("-"); values[2] = loc.valid ? String(loc.name) : String("unbekannt"); if (w.valid) values[3] = "vor " + String((millis() - w.updatedMs) / 60000) + " min"; else values[3] = "noch nicht geladen"; float volts = analogReadMilliVolts(PIN_BAT_ADC) * 2 / 1000.0f; snprintf(buf, sizeof(buf), "%.2f V (%s)", volts, volts > 4.4f ? "USB" : "Akku"); values[4] = buf; uint32_t mins = millis() / 60000; snprintf(buf, sizeof(buf), "%lu h %lu min", (unsigned long)(mins / 60), (unsigned long)(mins % 60)); values[5] = buf; // Einschalten heißt auch: Reset über die Taste oder die USB-Leitungen switch (gResetReason) { case ESP_RST_POWERON: values[6] = "Einschalten"; break; case ESP_RST_SW: values[6] = "Software/Update"; break; case ESP_RST_PANIC: values[6] = "Absturz"; break; case ESP_RST_INT_WDT: case ESP_RST_TASK_WDT: case ESP_RST_WDT: values[6] = "Watchdog"; break; case ESP_RST_BROWNOUT: values[6] = "Unterspannung"; break; default: values[6] = "Grund " + String((int)gResetReason); break; } snprintf(buf, sizeof(buf), "%u KB, Block %u", heapFree() / 1024, heapBlock() / 1024); values[7] = buf; clipRect(0, 0, 228, 135); for (int i = 0; i < 8; i++) { int y = 3 + i * 16; text(labels[i], 8, y, col::dim); text(values[i].c_str(), 84, y, col::text); } clearClip(); } // Zeichnet ein ganzes Bild in zwei Hälften und schickt jede gleich ans Display (mit copyTo auch dorthin, // gefolgt von einer Zeile "CRC ": der Netzwerk-Task kann mitten in die Bilddaten loggen). // Ein Sprite für das ganze Bild bräuchte 65 KB am Stück. Die fehlen, solange eine TLS-Verbindung offen // ist (die belegt rund 50 KB). Für die untere Hälfte zeigt der Sprite 68 Zeilen vor den Puffer, und der // Clip-Bereich lässt nur Zeilen zu, die im Puffer liegen. static void present(const std::function& draw, Stream* copyTo = nullptr) { gFrameMs = millis(); uint32_t crc = 0; for (gBandTop = 0; gBandTop < SCREEN_H; gBandTop += BAND_H) { gBandH = min(BAND_H, SCREEN_H - gBandTop); canvas.setBuffer(gBandBuf - gBandTop * SCREEN_W * 2, SCREEN_W, SCREEN_H); clearClip(); draw(); lcd.pushImage(0, gBandTop, SCREEN_W, gBandH, (const lgfx::swap565_t*)gBandBuf); if (copyTo) { copyTo->write(gBandBuf, SCREEN_W * gBandH * 2); crc = esp_rom_crc32_le(crc, gBandBuf, SCREEN_W * gBandH * 2); } } if (copyTo) copyTo->printf("\nCRC %08lx\n", (unsigned long)crc); } static void drawFrame(time_t now) { canvas.fillScreen(col::bg); if (!timeValid(now)) { drawStatusPage(now); } else { tm t; localtime_r(&now, &t); WeatherData w = getWeather(); switch (gPage) { case PAGE_CLOCK: drawClockPage(t, now, w); break; case PAGE_GLUCOSE: drawGlucosePage(now); break; case PAGE_GLUCOSE_DAY: drawGlucoseDayPage(now); break; case PAGE_FORECAST: drawForecastPage(t, w); break; case PAGE_METEOGRAM: drawMeteogramPage(now, w); break; case PAGE_MONITOR: drawMonitorPage(); break; case PAGE_DEPARTURES: drawDeparturesPage(now); break; case PAGE_INFO: drawInfoPage(w); break; case PAGE_RAIN: drawRainPage(now, w); break; case PAGE_AIR: drawAirPage(); break; case PAGE_SUN: drawSunPage(now, w); break; case PAGE_WARNINGS: drawWarningsPage(); break; case PAGE_CALENDAR: drawCalendarPage(now); break; case PAGE_SERVERS: drawServersPage(); break; case PAGE_POWER: drawPowerPage(now); break; case PAGE_NEWS: drawNewsPage(); break; } if (gPage != PAGE_METEOGRAM) drawPageDots(); // rechter Rand ist dort mit Achsenwerten belegt } } static void render(time_t now) { present([&] { drawFrame(now); }); } // ---------------------------------------------------------------- Einstellungen, Webseite, Updates static Preferences prefs; static WebServer web(80); static bool gServicesStarted = false; static void loadString(const char* key, char* out, size_t len) { if (prefs.isKey(key)) prefs.getString(key, out, len); } // Läuft vor dem Start des Netzwerk-Tasks, daher ohne Lock static void loadSettings() { Settings& s = gSettings; if (!prefs.begin("tdisplay", true)) return; // noch nie gespeichert s.lat = prefs.getFloat("lat", s.lat); s.lon = prefs.getFloat("lon", s.lon); s.walkMin = prefs.getInt("walk", s.walkMin); s.bzLow = prefs.getInt("bzLow", s.bzLow); s.bzHigh = prefs.getInt("bzHigh", s.bzHigh); s.bzVeryHigh = prefs.getInt("bzVeryHigh", s.bzVeryHigh); s.pageTimeout = prefs.getInt("timeout", s.pageTimeout); s.flip = prefs.getBool("flip", s.flip); s.pagesOff = prefs.getUInt("pagesOff", s.pagesOff); loadString("place", s.place, sizeof(s.place)); loadString("stopId", s.stopId, sizeof(s.stopId)); loadString("stopName", s.stopName, sizeof(s.stopName)); loadString("calUrls", s.calUrls, sizeof(s.calUrls)); loadString("wasteUrl", s.wasteUrl, sizeof(s.wasteUrl)); loadString("servers", s.servers, sizeof(s.servers)); prefs.end(); } static void saveSettings(const Settings& s) { prefs.begin("tdisplay", false); prefs.putFloat("lat", s.lat); prefs.putFloat("lon", s.lon); prefs.putInt("walk", s.walkMin); prefs.putInt("bzLow", s.bzLow); prefs.putInt("bzHigh", s.bzHigh); prefs.putInt("bzVeryHigh", s.bzVeryHigh); prefs.putInt("timeout", s.pageTimeout); prefs.putBool("flip", s.flip); prefs.putUInt("pagesOff", s.pagesOff); prefs.remove("pages"); // alte Speicherung (Bit = Seite an), neue Seiten wären damit aus prefs.putString("place", s.place); prefs.putString("stopId", s.stopId); prefs.putString("stopName", s.stopName); prefs.putString("calUrls", s.calUrls); prefs.putString("wasteUrl", s.wasteUrl); prefs.putString("servers", s.servers); prefs.end(); } // Nur die Hosts der Links: private iCal-Links enthalten ein Zugangs-Token static void addHosts(JsonArray out, const char* list) { forEachLine(list, [&](const char* url) { const char* host = strstr(url, "://"); host = host ? host + 3 : url; char buf[64]; strlcpy(buf, host, min(strcspn(host, "/?") + 1, sizeof(buf))); out.add(buf); }); } static void handleGetSettings() { const Settings& s = gSettings; JsonDocument doc; doc["lat"] = s.lat; doc["lon"] = s.lon; doc["place"] = s.place; doc["stopId"] = s.stopId; doc["stopName"] = s.stopName; doc["walk"] = s.walkMin; doc["bzLow"] = s.bzLow; doc["bzHigh"] = s.bzHigh; doc["bzVeryHigh"] = s.bzVeryHigh; doc["timeout"] = s.pageTimeout; doc["flip"] = s.flip; doc["servers"] = s.servers; addHosts(doc["calHosts"].to(), s.calUrls); addHosts(doc["wasteHosts"].to(), s.wasteUrl); JsonArray pages = doc["pages"].to(); for (Page id : PAGE_ORDER) { JsonObject p = pages.add(); p["id"] = (int)id; p["name"] = PAGE_NAMES[id]; p["on"] = pageEnabled(s, id); } // Was bei automatischer Wahl gerade verwendet wird LocationData loc = getLocation(); if (loc.valid) doc["autoPlace"] = loc.name; DepartureData dep = getDepartures(); if (dep.valid) doc["autoStop"] = dep.stop; String out; serializeJson(doc, out); web.send(200, "application/json", out); } static void copyField(JsonDocument& doc, const char* key, char* out, size_t len) { if (doc[key].is()) strlcpy(out, doc[key].as(), len); } static void handlePostSettings() { JsonDocument doc; if (deserializeJson(doc, web.arg("plain"))) { web.send(400, "text/plain", "Ungültige Daten"); return; } Settings s = gSettings; s.lat = constrain(doc["lat"] | s.lat, -90.0f, 90.0f); s.lon = constrain(doc["lon"] | s.lon, -180.0f, 180.0f); s.walkMin = constrain(doc["walk"] | s.walkMin, 0, 30); s.bzLow = constrain(doc["bzLow"] | s.bzLow, 40, 150); s.bzHigh = constrain(doc["bzHigh"] | s.bzHigh, s.bzLow + 10, 400); s.bzVeryHigh = constrain(doc["bzVeryHigh"] | s.bzVeryHigh, s.bzHigh, 500); s.pageTimeout = constrain(doc["timeout"] | s.pageTimeout, 0, 3600); s.flip = doc["flip"] | s.flip; copyField(doc, "place", s.place, sizeof(s.place)); copyField(doc, "stopId", s.stopId, sizeof(s.stopId)); copyField(doc, "stopName", s.stopName, sizeof(s.stopName)); copyField(doc, "servers", s.servers, sizeof(s.servers)); copyField(doc, "calUrls", s.calUrls, sizeof(s.calUrls)); // fehlt, wenn unverändert copyField(doc, "wasteUrl", s.wasteUrl, sizeof(s.wasteUrl)); if (doc["pages"].is()) { for (JsonObject p : doc["pages"].as()) { int id = p["id"] | -1; if (id <= PAGE_CLOCK || id >= PAGE_COUNT) continue; if (p["on"] | true) s.pagesOff &= ~(1u << id); else s.pagesOff |= 1u << id; } } const Settings& old = gSettings; bool moved = s.lat != old.lat || s.lon != old.lon || strcmp(s.place, old.place) != 0 || strcmp(s.stopId, old.stopId) != 0; bool sources = strcmp(s.calUrls, old.calUrls) != 0 || strcmp(s.wasteUrl, old.wasteUrl) != 0 || strcmp(s.servers, old.servers) != 0; bool flipped = s.flip != old.flip; { Lock l; gSettings = s; } saveSettings(s); if (moved) gSettingsGen = gSettingsGen + 1; if (sources) gSourcesGen = gSourcesGen + 1; if (flipped) lcd.setRotation(s.flip ? 3 : 1); if (!pageEnabled(s, gPage)) gPage = PAGE_CLOCK; Serial.println("Einstellungen gespeichert"); web.send(200, "application/json", "{\"ok\":true}"); } static void drawOtaScreen(int percent) { static int shown = -1; if (percent == shown) return; shown = percent; present([&] { canvas.fillScreen(col::bg); text("Firmware-Update", 120, 44, col::text, textdatum_t::middle_center); canvas.drawRoundRect(30, 62, 180, 14, 4, col::dim); canvas.fillRoundRect(32, 64, 176 * percent / 100, 10, 3, col::ok); char buf[8]; snprintf(buf, sizeof(buf), "%d %%", percent); text(buf, 120, 92, col::dim, textdatum_t::middle_center); }); } // Webseite und OTA brauchen das WLAN, daher erst nach der ersten Verbindung static void startServices() { ArduinoOTA.setHostname(HOSTNAME); ArduinoOTA.setPassword(OTA_PASSWORD); ArduinoOTA.onStart([] { gOtaActive = true; drawOtaScreen(0); }); ArduinoOTA.onProgress([](unsigned int done, unsigned int total) { drawOtaScreen(done * 100 / total); }); ArduinoOTA.onError([](ota_error_t err) { Serial.printf("OTA-Fehler %d\n", err); gOtaActive = false; }); ArduinoOTA.begin(); // startet auch mDNS (.local) MDNS.addService("http", "tcp", 80); web.on("/", HTTP_GET, [] { web.send_P(200, "text/html; charset=utf-8", WEB_PAGE); }); web.on("/api/settings", HTTP_GET, handleGetSettings); web.on("/api/settings", HTTP_POST, handlePostSettings); web.onNotFound([] { web.send(404, "text/plain", "Nicht gefunden"); }); web.begin(); Serial.printf("Web: http://%s.local/ (%s)\n", HOSTNAME, WiFi.localIP().toString().c_str()); } // ---------------------------------------------------------------- Setup / Loop void setup() { Serial.begin(115200); gResetReason = esp_reset_reason(); Serial.printf("\nStart, Grund %d (1 Einschalten, 3 Software, 4 Absturz, 5-7 Watchdog, 9 Unterspannung)\n", (int)gResetReason); pinMode(PIN_BTN_PAGE, INPUT); // GPIO35 hat keinen internen Pull-up, das Board hat einen externen pinMode(PIN_BTN_OPTION, INPUT_PULLUP); pinMode(PIN_BAT_ADC_EN, OUTPUT); digitalWrite(PIN_BAT_ADC_EN, HIGH); btnPage.begin(); btnOption.begin(); loadSettings(); lcd.init(); lcd.setRotation(gSettings.flip ? 3 : 1); lcd.setBrightness(BRIGHTNESS[0]); canvas.setColorDepth(16); gBandBuf = (uint8_t*)heap_caps_malloc(SCREEN_W * BAND_H * 2, MALLOC_CAP_8BIT | MALLOC_CAP_DMA); if (!gBandBuf) Serial.println("Zu wenig Speicher für den Bildpuffer"); gGlucoseHistory.reserve(GLUCOSE_MAX_POINTS); gHistoryBuffer.reserve(GLUCOSE_MAX_POINTS); canvas.setTextWrap(false); gLock = xSemaphoreCreateMutex(); WiFi.setHostname(HOSTNAME); WiFi.mode(WIFI_STA); for (const auto& net : WIFI_NETWORKS) wifiMulti.addAP(net.ssid, net.password); xTaskCreatePinnedToCore(netTask, "net", 16384, nullptr, 1, nullptr, 0); } static void showPage(int page) { gPage = page; gScroll = 0; gScrollMs = millis(); } static void nextPage() { int i = 0; while (PAGE_ORDER[i] != gPage) i++; do { i = (i + 1) % PAGE_COUNT; } while (!pageEnabled(gSettings, PAGE_ORDER[i])); showPage(PAGE_ORDER[i]); gLastInput = millis(); } static void nextBrightness() { gBrightIdx = (gBrightIdx + 1) % (int)(sizeof(BRIGHTNESS) / sizeof(BRIGHTNESS[0])); lcd.setBrightness(BRIGHTNESS[gBrightIdx]); } // Optionsknopf kurz gedrückt: Zeitbereich umschalten oder weiterblättern. false, wenn die Seite // nichts dafür hat; dann stellt der Knopf die Helligkeit um. static bool pageOption() { switch (gPage) { case PAGE_GLUCOSE: gGlucoseRange = (gGlucoseRange + 1) % 3; return true; case PAGE_METEOGRAM: gMeteoRange = (gMeteoRange + 1) % 3; return true; case PAGE_NEWS: gScroll = scrollPos(NEWS_PAGE_MS) + 1; break; case PAGE_WARNINGS: gScroll = scrollPos(WARNING_PAGE_MS) + 1; break; case PAGE_DEPARTURES: case PAGE_CALENDAR: gScroll++; break; default: return false; } gScrollMs = millis(); // Blättern startet die automatische Weiterschaltung neu return true; } void loop() { bool dirty = false; bool screenshot = false; if (!gServicesStarted && WiFi.status() == WL_CONNECTED) { startServices(); gServicesStarted = true; } if (gServicesStarted) { ArduinoOTA.handle(); web.handleClient(); } if (btnPage.pressed()) { nextPage(); dirty = true; } // Serielle Befehle: 'p' = nächste Seite, 'o' = Optionsknopf kurz, 's' = Screenshot (siehe tools/screenshot.py) while (Serial.available()) { switch (Serial.read()) { case 'p': nextPage(); dirty = true; break; case 'o': dirty = pageOption() || dirty; break; case 's': screenshot = dirty = true; break; } } switch (btnOption.event()) { case Button::SHORT: if (pageOption()) dirty = true; else nextBrightness(); gLastInput = millis(); break; case Button::LONG: nextBrightness(); gLastInput = millis(); break; default: break; } if (gPage != PAGE_CLOCK && gSettings.pageTimeout > 0 && millis() - gLastInput > gSettings.pageTimeout * 1000UL) { showPage(PAGE_CLOCK); dirty = true; } static time_t lastDrawn = -1; time_t now = time(nullptr); if (screenshot) { Serial.printf("\nSCREENSHOT %d %d\n", SCREEN_W, SCREEN_H); present([&] { drawFrame(now); }, &Serial); Serial.flush(); lastDrawn = now; } else if (dirty || now != lastDrawn) { lastDrawn = now; render(now); } delay(10); }