Hallo zusammen,
ich habe ein Projekt mit einem Waveshare ESP32-S3 Touch LCD 7" (RGB Panel) und LVGL. Es läuft erst normal, aber spätestens nach ~10 Stunden treten Probleme auf:
Problem
- Links erscheinen komische horizontale Streifen
- Der komplette Inhalt verschiebt sich ein paar Millimeter nach oben (Header teilweise doppelt sichtbar (unten und oben)/“wrap-around”)
Ich habe Fotos vom Fehler (siehe Anhang).
Setup / Umgebung
- Board: Waveshare ESP32-S3 Touch LCD 7" (RGB)
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <time.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <set>
#include <esp_now.h>
#include <Preferences.h>
#include <esp_display_panel.hpp>
#include "lvgl.h"
#include "lvgl_v8_port.h"
#include "event_types.h" // struct Event { String uid, summary; time_t start,end; bool allDay; uint8_t src; bool segStartAtDay, segEndAtDay; uint8_t parentAllDaySpan; }
#include "types_local.h"
#include <esp_task_wdt.h> // NEU: Watchdog
#include <freertos/FreeRTOS.h> // NEU: portNUM_PROCESSORS
#define WDT_TIMEOUT_SECONDS 300 // NEU: Watchdog-Timeout in Sekunden
// --- WDT: sauber nur resetten wenn registriert ---
static bool g_wdt_inited = false;
static inline void wdt_kick() {
if (g_wdt_inited) esp_task_wdt_reset();
}
using namespace esp_panel::drivers;
using namespace esp_panel::board;
/* ---------- Optionen ---------- */
// (LEFT_SAFETY_MASK entfernt, da ungenutzt)
/* ---------- Vorwärtsdeklarationen ---------- */
static void drawCalendarView();
static void drawDataView();
static void drawLEDView();
static void rebuild_cal_list();
static void attach_cal_list_events();
static void mail_fab_create(lv_obj_t* parent);
static void mail_fab_update_visibility();
static void show_new_events_list_popup();
static inline time_t normEnd(const Event& e);
static bool parseICS(const String& icsRaw, uint8_t src, std::vector<Event>& out);
static void logWiFiStatus(const char* tag);
static bool testDNS(const char* host = "pool.ntp.org");
// neu: ensureWiFi vorwärtsdeklarieren, da in fetchWeather() verwendet
void ensureWiFi();
/* --------- Wecker / Alarm --------- */
static bool g_alarm_enabled = false; // Wecker an/aus
static uint8_t g_alarm_hour = 7; // Standard: 07:00
static uint8_t g_alarm_minute = 0; // Standard: 07:00
static int g_alarm_last_daykey = -1; // um 1x pro Tag zu feuern
// UI-Elemente für Wecker
static lv_obj_t* alarm_time_label = nullptr;
static lv_obj_t* alarm_toggle_btn = nullptr;
static lv_obj_t* alarm_toggle_label = nullptr;
/* ---------- LED-/ESP-NOW Vorwärtsdeklarationen ---------- */
static void led_init_espnow();
static void led_send_cmd(uint8_t cmd); // an LED-Empfänger
static void led_send_cmd_to_controller(uint8_t cmd); // an Timer-/OLED-ESP
static void led_send_timer_set_minutes(uint16_t mins); // Timer-Minuten sync
static void led_set_timer_minutes(uint16_t mins, bool fromRemote);
static void led_timer_slider_event_cb(lv_event_t* e);
static void led_update_ui_state();
/* ---- Neue Termine FAB / Buffer ---- */
static bool g_has_new_events = false;
static std::vector<Event> g_new_events_buf;
static lv_obj_t* mail_fab = nullptr;
// Retry-Parameter (für LED-ESP-NOW)
static volatile bool g_lastSendDone = false;
static volatile esp_now_send_status_t g_lastSendStatus = ESP_NOW_SEND_FAIL;
static const int MAX_SEND_RETRIES = 10;
static const unsigned long SEND_TIMEOUT_MS = 80; // ms pro Versuch
static void alarm_update_time_label();
static void alarm_update_toggle_button();
static volatile bool g_req_show_new_events_popup = false;
static volatile bool g_popup_scheduled = false;
static void async_show_new_events_popup(void* userdata) {
(void)userdata;
g_popup_scheduled = false;
show_new_events_list_popup(); // <- wird im LVGL-Kontext ausgeführt
}
/* ---------- ICONS (extern aus .c Dateien) ---------- */
extern const lv_img_dsc_t school_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
extern const lv_img_dsc_t favorite_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
extern const lv_img_dsc_t pool_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
extern const lv_img_dsc_t work_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
extern const lv_img_dsc_t directions_bike_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
extern const lv_img_dsc_t mark_email_unread_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
/* ---------- Font-Fallbacks ---------- */
#if defined(LV_FONT_MONTSERRAT_22) && LV_FONT_MONTSERRAT_22
#define FONT_22 (&lv_font_montserrat_22)
#else
#define FONT_22 (&lv_font_montserrat_16)
#endif
#if defined(LV_FONT_MONTSERRAT_24) && LV_FONT_MONTSERRAT_24
#define FONT_24 (&lv_font_montserrat_24)
#elif defined(LV_FONT_MONTSERRAT_22) && LV_FONT_MONTSERRAT_22
#define FONT_24 (&lv_font_montserrat_22)
#else
#define FONT_24 (&lv_font_montserrat_16)
#endif
#if defined(LV_FONT_MONTSERRAT_30) && LV_FONT_MONTSERRAT_30
#define FONT_30 (&lv_font_montserrat_30)
#elif defined(LV_FONT_MONTSERRAT_28) && LV_FONT_MONTSERRAT_28
#define FONT_30 (&lv_font_montserrat_28)
#elif defined(LV_FONT_MONTSERRAT_24) && LV_FONT_MONTSERRAT_24
#define FONT_30 (&lv_font_montserrat_24)
#else
#define FONT_30 (&lv_font_montserrat_16)
#endif
#if defined(LV_FONT_MONTSERRAT_34) && LV_FONT_MONTSERRAT_34
#define FONT_34 (&lv_font_montserrat_34)
#elif defined(LV_FONT_MONTSERRAT_32) && LV_FONT_MONTSERRAT_32
#define FONT_34 (&lv_font_montserrat_32)
#else
#define FONT_34 (FONT_30)
#endif
/* --------- WLAN & Standort --------- */
const char* WIFI_SSID = "Wlan";
const char* WIFI_PASS = "1234";
const float LAT = 0000;
const float LON = 0000;
const char* TZ_EU_BERLIN = "CET-1CEST,M3.5.0/2,M10.5.0/3";
/* --------- Views (ohne Chart) --------- */
enum View { VIEW_CAL=0, VIEW_DATA=1, VIEW_LED=2 };
static volatile bool g_need_view_redraw = false;
static View currentView = VIEW_CAL;
/* --------- Kalender --------- */
const char* ICS_URL_1 = "Beispiel.ics";
const char* ICS_URL_2 = "Beispiel.ics";
const int RECURRENCE_WINDOW_DAYS = 20;
const int DISPLAY_OFFSET_MIN = 0;
const int EARLY_HIDE_SEC = 300;
const unsigned long REFRESH_MS = 20UL * 60UL*1000;
std::vector<Event> cal_events;
std::vector<Event> cache1, cache2;
String etag1, etag2;
unsigned long cal_lastFetch=0;
DayWeather wToday,wTomorrow;
float currentTemp=NAN, currentApp=NAN, currentHum=NAN, currentWind=NAN, currentCloud=NAN;
/* 5 Tage + 8 Stunden Vorschau */
static DayWeather wDays[5];
static int wDaysCount = 0;
static float next8_temp[8];
static String next8_time[8];
static int next8_count = 0;
/* Zeitpunkte „zuletzt aktualisiert“ */
static time_t g_lastWeatherFetchTs = 0;
static time_t g_lastCalFetchTs = 0;
/* --------- LVGL UI --------- */
static Board *g_board = nullptr;
static Backlight *g_backlight = nullptr; // Backlight-Objekt vom Board
// ----- Präsenz / PIR -----
#define PIR_PIN 6 // AD-Pin am Sensor-Header des Waveshare-Boards
// So lange nach letzter Bewegung warten, bis das Display ausgeht
static const unsigned long NO_MOTION_SCREENOFF_MS = 5UL * 60UL * 1000UL;
static unsigned long g_lastMotionMs = 0;
static bool g_screenOff = false;
static lv_obj_t *root_scr = nullptr;
static lv_obj_t *header_label = nullptr;
static lv_obj_t *content = nullptr;
static lv_obj_t *footer_badge = nullptr;
/* Kalender-Viewport + Liste */
static lv_obj_t *cal_viewport = nullptr;
static lv_obj_t *cal_list = nullptr;
/* Wetter */
static lv_obj_t *data_box = nullptr;
/* LED-View */
static lv_obj_t *led_box = nullptr;
static lv_obj_t *led_toggle_btn = nullptr;
static lv_obj_t *led_toggle_label = nullptr;
static lv_obj_t *led_color_btns[4] = {nullptr, nullptr, nullptr, nullptr};
static bool led_on = false;
static uint8_t led_current_color = 0;
// LED-Timer UI
static lv_obj_t *led_timer_slider = nullptr;
static lv_obj_t *led_timer_label = nullptr;
static uint16_t led_timer_minutes = 30; // aktuelle Einstellung
static uint16_t led_timer_minutes_last = 30; // zuletzt gesendeter Wert
/* ---- linker Abstand ---- */
static const int LEFT_INSET_PX = 56;
static const int HEADER_H = 56;
/* ---------- Safety/Bounds Helpers ---------- */
// g_left_mask entfernt, da ungenutzt
/* --------- Einstellungen --------- */
static int g_events_limit = 15;
static bool g_is_scrolling = false;
// Swipes sperren, solange Slider gedrückt wird
static bool g_block_swipe = false;
/* --------- Styles --------- */
static lv_style_t st_row_even, st_row_odd, st_row_base;
static lv_style_t st_date, st_time, st_title;
static lv_style_t st_date_today;
static lv_style_t st_row_today;
static lv_style_t st_bigtemp, st_kv_key, st_kv_val, st_section;
static lv_style_t st_card, st_day_chip, st_day_text_small, st_icon, st_chip_hour;
/* === Popup Styles === */
static lv_style_t st_popup, st_popup_title, st_popup_details;
/* ====================== ESP-NOW / LED-Steuerung ====================== */
// ---------- Befehls-IDs ----------
#define CMD_ON 1
#define CMD_OFF 2
#define CMD_GREEN 3
#define CMD_BLUE 4
#define CMD_YELLOW 5
#define CMD_RED 6
#define CMD_STATE_QUERY 10 // nur Controller<->Controller
#define CMD_TIMER_SET_MINUTES 20 // Timer-Minuten synchronisieren
typedef struct {
uint8_t cmd;
} esp_cmd_t;
// 4 Empfänger (LED-Leisten)
uint8_t macA1[] = { };
uint8_t macA2[] = { };
uint8_t macA3[] = { };
uint8_t macA4[] = { };
uint8_t* peersA[] = { macA1, macA2, macA3, macA4 };
const size_t peersA_count = sizeof(peersA) / sizeof(peersA[0]);
// zusätzlicher Peer: Timer-Controller (OLED-ESP32, STA-MAC 84:1F:E8:29:82:7C)
static uint8_t macCtrlOther[] = { 0x84, 0x1F, 0xE8, 0x29, 0x82, 0x7C };
/* ===================== ACK / Bestätigungen ===================== */
static Preferences g_prefs;
static std::set<String> g_ack_keys;
static std::set<String> g_ack_required;
static std::set<String> g_ack_external_done;
static std::set<String> g_ack_is_task;
/* ===================== Popup "Neuer Termin" & FAB ===================== */
static const int POPUP_W = 540;
static const int POPUP_H = 180;
static const int GAP = 10;
static const int PAD_V = 10;
static lv_obj_t* g_popup = nullptr;
static lv_timer_t* g_popup_timer = nullptr;
static std::set<String> g_seen_event_keys;
static bool g_seen_built_once = false;
/* ============ Helpers / Styles etc. ============ */
static inline int mm_to_px(float mm){
lv_disp_t* d = lv_disp_get_default();
int dpi = lv_disp_get_dpi(d);
return (int)roundf(dpi * (mm / 25.4f));
}
static void clamp_to_screen(lv_obj_t* o, int w=800, int h=480){
lv_coord_t x = lv_obj_get_x(o);
lv_coord_t y = lv_obj_get_y(o);
if (x < 0) lv_obj_set_x(o, 0);
if (y < 0) lv_obj_set_y(o, 0);
}
static void alarm_arm_next_occurrence_from_now() {
time_t nowTs = time(nullptr);
if (nowTs < 1600000000) {
// Zeit noch nicht gültig -> lieber nicht blockieren
g_alarm_last_daykey = -1;
return;
}
struct tm tmL;
localtime_r(&nowTs, &tmL);
int todayKey = (tmL.tm_year + 1900) * 10000 +
(tmL.tm_mon + 1) * 100 +
tmL.tm_mday;
// "Schon vorbei" = strikt später als Zielzeit (07:00 genau gilt NICHT als vorbei)
bool strictlyPast =
(tmL.tm_hour > g_alarm_hour) ||
(tmL.tm_hour == g_alarm_hour && tmL.tm_min > g_alarm_minute) ||
(tmL.tm_hour == g_alarm_hour && tmL.tm_min == g_alarm_minute && tmL.tm_sec > 0);
// Wenn heute schon vorbei -> blockiere heute, damit er erst morgen feuert
g_alarm_last_daykey = strictlyPast ? todayKey : -1;
}
static void make_opaque_noclipbleed(lv_obj_t* o){
lv_obj_set_style_bg_opa(o, LV_OPA_COVER, 0);
lv_obj_set_style_bg_color(o, lv_color_white(), 0);
lv_obj_set_style_border_width(o, 0, 0);
lv_obj_set_style_shadow_width(o, 0, 0);
lv_obj_set_style_outline_width(o, 0, 0);
lv_obj_set_style_clip_corner(o, true, 0);
}
// ensure_left_mask entfernt, da die Safety-Maske deaktiviert und ungenutzt war
/* ============ Styles ============ */
static void init_styles() {
// Kalenderzeilen
lv_style_init(&st_row_base);
lv_style_set_pad_ver(&st_row_base, 8);
lv_style_set_pad_hor(&st_row_base, 8);
lv_style_set_pad_column(&st_row_base, 8);
lv_style_set_border_width(&st_row_base, 0);
lv_style_set_outline_width(&st_row_base, 0);
lv_style_set_bg_opa(&st_row_base, LV_OPA_COVER);
lv_style_set_min_height(&st_row_base, 48);
lv_style_set_shadow_width(&st_row_base, 0);
lv_style_init(&st_row_even);
lv_style_set_bg_color(&st_row_even, lv_color_white());
lv_style_set_bg_opa(&st_row_even, LV_OPA_COVER);
lv_style_init(&st_row_odd);
lv_style_set_bg_color(&st_row_odd, lv_color_hex(0xF2F2F2));
lv_style_set_bg_opa(&st_row_odd, LV_OPA_COVER);
lv_style_init(&st_date);
lv_style_set_text_color(&st_date, lv_color_black());
lv_style_set_text_font(&st_date, FONT_24);
lv_style_init(&st_date_today);
lv_style_set_text_color(&st_date_today, lv_color_black());
lv_style_set_text_font(&st_date_today, FONT_24);
lv_style_set_text_decor(&st_date_today, LV_TEXT_DECOR_UNDERLINE);
lv_style_init(&st_time);
lv_style_set_text_color(&st_time, lv_color_black());
lv_style_set_text_font(&st_time, FONT_24);
lv_style_init(&st_title);
lv_style_set_text_color(&st_title, lv_color_black());
lv_style_set_text_font(&st_title, FONT_24);
lv_style_set_text_line_space(&st_title, 2);
lv_style_init(&st_row_today);
lv_style_set_bg_opa(&st_row_today, LV_OPA_COVER);
lv_style_set_bg_color(&st_row_today, lv_color_hex(0xFFF7D6));
// Wetter
lv_style_init(&st_bigtemp);
lv_style_set_text_color(&st_bigtemp, lv_palette_main(LV_PALETTE_YELLOW));
lv_style_set_text_font(&st_bigtemp, FONT_34);
lv_style_init(&st_kv_key);
lv_style_set_text_color(&st_kv_key, lv_palette_main(LV_PALETTE_CYAN));
lv_style_set_text_font(&st_kv_key, FONT_22);
lv_style_init(&st_kv_val);
lv_style_set_text_color(&st_kv_val, lv_color_black());
lv_style_set_text_font(&st_kv_val, FONT_24);
lv_style_init(&st_section);
lv_style_set_text_color(&st_section, lv_color_hex(0x444444));
lv_style_set_text_font(&st_section, FONT_24);
// Karten / Chips
lv_style_init(&st_card);
lv_style_set_bg_opa(&st_card, LV_OPA_COVER);
lv_style_set_bg_color(&st_card, lv_color_hex(0xF7F9FC));
lv_style_set_radius(&st_card, 14);
lv_style_set_pad_all(&st_card, 12);
lv_style_set_border_width(&st_card, 0);
lv_style_set_shadow_width(&st_card, 0);
lv_style_init(&st_day_chip);
lv_style_set_bg_opa(&st_day_chip, LV_OPA_COVER);
lv_style_set_bg_color(&st_day_chip, lv_color_hex(0xFFFFFF));
lv_style_set_radius(&st_day_chip, 10);
lv_style_set_pad_top(&st_day_chip, 8);
lv_style_set_pad_bottom(&st_day_chip, 8);
lv_style_set_pad_left(&st_day_chip, 6);
lv_style_set_pad_right(&st_day_chip, 6);
lv_style_set_border_width(&st_day_chip, 1);
lv_style_set_border_color(&st_day_chip, lv_color_hex(0xE5EAF0));
lv_style_set_shadow_width(&st_day_chip, 0);
lv_style_init(&st_chip_hour);
lv_style_set_bg_opa(&st_chip_hour, LV_OPA_COVER);
lv_style_set_bg_color(&st_chip_hour, lv_color_hex(0xFDFDFE));
lv_style_set_radius(&st_chip_hour, 8);
lv_style_set_pad_top(&st_chip_hour, 6);
lv_style_set_pad_bottom(&st_chip_hour, 6);
lv_style_set_pad_left(&st_chip_hour, 6);
lv_style_set_pad_right(&st_chip_hour, 6);
lv_style_set_border_width(&st_chip_hour, 1);
lv_style_set_border_color(&st_chip_hour, lv_color_hex(0xEAECEF));
lv_style_init(&st_day_text_small);
lv_style_set_text_color(&st_day_text_small, lv_color_hex(0x4A5568));
lv_style_set_text_font(&st_day_text_small, FONT_22);
lv_style_init(&st_icon);
lv_style_set_text_color(&st_icon, lv_color_hex(0x2B6CB0));
lv_style_set_text_font(&st_icon, FONT_24);
// Popup
lv_style_init(&st_popup);
lv_style_set_bg_opa(&st_popup, LV_OPA_COVER);
lv_style_set_bg_color(&st_popup, lv_color_hex(0xFFFFFF));
lv_style_set_radius(&st_popup, 16);
lv_style_set_border_width(&st_popup, 1);
lv_style_set_border_color(&st_popup, lv_color_hex(0xD7DDE6));
lv_style_set_shadow_width(&st_popup, 10);
lv_style_set_shadow_ofs_y(&st_popup, 4);
lv_style_set_shadow_color(&st_popup, lv_color_hex(0xC8D2E4));
lv_style_set_pad_left(&st_popup, 16);
lv_style_set_pad_right(&st_popup, 16);
lv_style_set_pad_top(&st_popup, 12);
lv_style_set_pad_bottom(&st_popup, 12);
lv_style_init(&st_popup_title);
lv_style_set_text_color(&st_popup_title, lv_color_hex(0x0B1F4B));
lv_style_set_text_font(&st_popup_title, FONT_30);
lv_style_init(&st_popup_details);
lv_style_set_text_color(&st_popup_details, lv_color_hex(0x1F2937));
lv_style_set_text_font(&st_popup_details, FONT_24);
lv_style_set_text_line_space(&st_popup_details, 6);
}
/* ============= Helpers ============= */
static void logWiFiStatus(const char* tag) {
Serial.printf("[WIFI] %s: status=%d (%s)\n",
tag,
(int)WiFi.status(),
(WiFi.status() == WL_CONNECTED ? "CONNECTED" : "NOT CONNECTED"));
if (WiFi.status() == WL_CONNECTED) {
Serial.printf("[WIFI] SSID: %s\n", WiFi.SSID().c_str());
Serial.printf("[WIFI] RSSI: %d dBm\n", (int)WiFi.RSSI());
Serial.printf("[WIFI] IP: %s\n", WiFi.localIP().toString().c_str());
Serial.printf("[WIFI] GW: %s\n", WiFi.gatewayIP().toString().c_str());
Serial.printf("[WIFI] DNS: %s\n", WiFi.dnsIP().toString().c_str());
Serial.printf("[WIFI] CH: %d\n", (int)WiFi.channel());
}
}
static String fmt_hhmm(time_t ts){
if (ts<=0) return String("--:--");
struct tm tm; localtime_r(&ts,&tm);
char b[8]; strftime(b,sizeof(b),"%H:%M",&tm);
return String(b);
}
String trimCopy(const String& s){ String r=s; r.trim(); return r; }
static std::vector<String> splitCSV(const String& s){
std::vector<String> out; out.reserve(8);
int start=0; while (start < s.length()){
int c = s.indexOf(',', start); if (c<0) c = s.length();
String tok = s.substring(start, c); tok.trim(); if (tok.length()) out.push_back(tok);
start = c + 1;
} return out;
}
static int bydayTokToWday(const String& tok){
String t=tok; t.trim(); t.toUpperCase();
if (t.endsWith("SU")) return 0; if (t.endsWith("MO")) return 1; if (t.endsWith("TU")) return 2;
if (t.endsWith("WE")) return 3; if (t.endsWith("TH")) return 4; if (t.endsWith("FR")) return 5; if (t.endsWith("SA")) return 6;
return -1;
}
bool waitForTime(uint32_t timeoutMs=20000) {
uint32_t t0 = millis();
while (millis() - t0 < timeoutMs) {
wdt_kick();
if (time(nullptr) > 1600000000) return true;
delay(200);
}
return false;
}
time_t makeTimeInTZ(struct tm t, const char* tz) {
const char* oldTZ=getenv("TZ"); String old=oldTZ?String(oldTZ):String();
setenv("TZ", tz, 1); tzset(); t.tm_isdst = -1; time_t epoch=mktime(&t);
if (old.length()) setenv("TZ", old.c_str(), 1); else unsetenv("TZ"); tzset();
return epoch;
}
time_t makeTimeUTC(struct tm t) {
const char* oldTZ=getenv("TZ"); String old=oldTZ?String(oldTZ):String();
setenv("TZ", "UTC0", 1); tzset(); t.tm_isdst = -1; time_t epoch=mktime(&t);
if (old.length()) setenv("TZ", old.c_str(), 1); else unsetenv("TZ"); tzset();
return epoch;
}
String icsUnfold(const String& raw) {
String out; out.reserve(raw.length() + 16);
int n=raw.length();
for (int i=0;i<n;) {
int j=raw.indexOf('\n', i);
String line=(j>=0)? raw.substring(i,j): raw.substring(i);
if (j>=0) i=j+1; else i=n;
if (line.endsWith("\r")) line.remove(line.length()-1);
if (i<n && (raw.charAt(i)==' '||raw.charAt(i)=='\t')) out += line;
else { out += line; out += '\n'; }
}
return out;
}
bool feedFloatingAsUTC(const String& ics) {
String up=ics; up.toUpperCase();
return up.indexOf("X-WR-TIMEZONE:UTC")>=0 || up.indexOf("TZID:UTC")>=0 || up.indexOf("ETC/UTC")>=0;
}
/* ---- DST-feste Zeit-Helfer ---- */
static time_t make_local_datetime(int y,int M,int d,int H,int m,int s){
struct tm t={}; t.tm_year=y-1900; t.tm_mon=M-1; t.tm_mday=d; t.tm_hour=H; t.tm_min=m; t.tm_sec=s; t.tm_isdst=-1;
return mktime(&t);
}
static time_t dayStartLocal(time_t t){
struct tm tmL; localtime_r(&t,&tmL);
tmL.tm_hour=0; tmL.tm_min=0; tmL.tm_sec=0; tmL.tm_isdst=-1;
return mktime(&tmL);
}
static time_t add_days_local(time_t t, int days){
struct tm tmL; localtime_r(&t,&tmL);
tmL.tm_mday += days; tmL.tm_isdst=-1;
return mktime(&tmL);
}
static time_t nextDayStartLocal(time_t t){
return add_days_local(dayStartLocal(t), 1);
}
static time_t week_start_local(time_t t, int wkst){
struct tm tmL; localtime_r(&t,&tmL);
int wd = tmL.tm_wday;
int diff = ( (wd - wkst + 7) % 7 );
tmL.tm_hour=0; tmL.tm_min=0; tmL.tm_sec=0;
tmL.tm_mday -= diff; tmL.tm_isdst=-1;
return mktime(&tmL);
}
/* ---------- parseDateTimeField ---------- */
bool parseDateTimeField(const String& line, time_t& outTs, bool& isAllDay,
const char* defaultLocalTZ, bool floatingIsUTC) {
int colon=line.lastIndexOf(':'); if (colon<0) return false;
String lhs=line.substring(0,colon); String v=line.substring(colon+1); v.trim();
if (v.length()==8 && v.indexOf('T')<0) {
int y=v.substring(0,4).toInt(), M=v.substring(4,6).toInt(), d=v.substring(6,8).toInt();
struct tm t={}; t.tm_year=y-1900; t.tm_mon=M-1; t.tm_mday=d; t.tm_hour=0; t.tm_min=0; t.tm_sec=0; t.tm_isdst=-1;
outTs=makeTimeInTZ(t, defaultLocalTZ); isAllDay=true; return true;
}
int y=v.substring(0,4).toInt(), M=v.substring(4,6).toInt(), d=v.substring(6,8).toInt();
int h=(v.length()>=11)? v.substring(9,11).toInt():0;
int m=(v.length()>=13)? v.substring(11,13).toInt():0;
int s=(v.length()>=15)? v.substring(13,15).toInt():0;
struct tm t={}; t.tm_year=y-1900; t.tm_mon=M-1; t.tm_mday=d; t.tm_hour=h; t.tm_min=m; t.tm_sec=s; t.tm_isdst=-1;
bool isUTC=v.endsWith("Z");
if (isUTC) {
outTs=makeTimeUTC(t);
} else if (lhs.indexOf("TZID=")>=0) {
int p = lhs.indexOf("TZID=");
String tzid = lhs.substring(p + 5);
int sc = tzid.indexOf(';'); if (sc >= 0) tzid = tzid.substring(0, sc);
int cl = tzid.indexOf(':'); if (cl >= 0) tzid = tzid.substring(0, cl);
tzid.trim(); tzid.toUpperCase();
if (tzid.indexOf("UTC") >= 0) outTs = makeTimeUTC(t);
else outTs = makeTimeInTZ(t, TZ_EU_BERLIN);
} else {
outTs = floatingIsUTC ? makeTimeUTC(t) : makeTimeInTZ(t, defaultLocalTZ);
}
isAllDay=false; return true;
}
/* ---------- Header-Zeit ---------- */
static const char* DE_WD[7]={"So","Mo","Di","Mi","Do","Fr","Sa"};
static String headerNowString(){
time_t nowTs = time(nullptr);
struct tm tm; localtime_r(&nowTs, &tm);
char buf[32];
strftime(buf, sizeof(buf), "%d.%m.%Y %H:%M", &tm);
String s = String(DE_WD[tm.tm_wday]) + " " + String(buf);
return s;
}
/* ---------- RRule Parser ---------- */
static void parseRRule(const String& rule, RRule& out){
String s = rule; s.trim(); int p = s.indexOf(':'); if (p>=0) s = s.substring(p+1);
std::vector<String> parts; parts.reserve(8);
int start=0; while (start < s.length()){
int sc = s.indexOf(';', start); if (sc<0) sc = s.length();
String tok = s.substring(start, sc); tok.trim(); if (tok.length()) parts.push_back(tok);
start = sc + 1;
}
for (auto &kv : parts){
int eq = kv.indexOf('='); if (eq<0) continue;
String k=kv.substring(0,eq); String v=kv.substring(eq+1); k.trim(); v.trim(); k.toUpperCase();
if (k=="FREQ") { v.toUpperCase(); out.freq=v; }
else if (k=="INTERVAL") { long iv=v.toInt(); if (iv<1) iv=1; out.interval=(int)iv; }
else if (k=="COUNT") out.count = v.toInt();
else if (k=="UNTIL") { time_t ts=0; bool ad=false; String fake = String("DTSTART:")+v; (void)parseDateTimeField(fake, ts, ad, TZ_EU_BERLIN, false); out.until = ts; }
else if (k=="BYDAY") { auto toks=splitCSV(v); out.byday.clear(); for (auto &t : toks){ int wd=bydayTokToWday(t); if (wd>=0) out.byday.push_back(wd);} }
else if (k=="BYMONTHDAY") { auto toks=splitCSV(v); out.bymonthday.clear(); for (auto &t : toks){ int d=t.toInt(); if (d!=0) out.bymonthday.push_back(d);} }
else if (k=="BYMONTH") { auto toks=splitCSV(v); out.bymonth.clear(); for (auto &t : toks){ int M=t.toInt(); if (M>=1 && M<=12) out.bymonth.push_back(M);} }
else if (k=="WKST") { int wd=bydayTokToWday(v); if (wd>=0) out.wkst=wd; }
}
}
static void parseMultiDateLine(const String& line, std::vector<time_t>& outVals, bool floatingUTC){
int colon=line.lastIndexOf(':'); if (colon<0) return;
String lhs=line.substring(0,colon); String rhs=line.substring(colon+1); rhs.trim();
auto vals = splitCSV(rhs);
for (auto &v : vals){
String recon = lhs+":"+v; time_t ts=0; bool ad=false;
if (parseDateTimeField(recon, ts, ad, TZ_EU_BERLIN, floatingUTC)) outVals.push_back(ts);
}
}
static inline time_t normEnd(const Event& e){ return e.end? e.end : (e.allDay? (e.start+24*3600):(e.start+3600)); }
/* ---------- ICS Parser ---------- */
static bool parseICS(const String& icsRaw, uint8_t src, std::vector<Event>& out) {
String ics=icsUnfold(icsRaw);
bool floatingUTC=feedFloatingAsUTC(ics);
time_t nowLocal = time(nullptr);
const time_t wStart = nowLocal - 86400;
const time_t wEnd = nowLocal + (time_t)RECURRENCE_WINDOW_DAYS * 86400;
bool inEvent=false; String uid, summary, rruleLine;
std::vector<String> exdateLines, rdateLines;
std::vector<String> attendeeLines;
String categoriesVal;
time_t dtstart=0, dtend=0; bool hasDTSTART=false; bool hasDTEND=false; bool allDay=false;
out.clear(); out.reserve(64);
int i=0;
while (i>=0){
int j=ics.indexOf('\n', i);
String line=(j>=0)? ics.substring(i,j): ics.substring(i);
if (j>=0) i=j+1; else i=-1; line.trim();
if (line=="BEGIN:VEVENT"){
inEvent=true; uid=""; summary=""; rruleLine=""; exdateLines.clear(); rdateLines.clear(); attendeeLines.clear();
dtstart=0; dtend=0; hasDTSTART=false; hasDTEND=false; allDay=false; categoriesVal="";
} else if (line=="END:VEVENT"){
if (inEvent && hasDTSTART){
Event base; base.uid=uid; base.summary=summary; base.start=dtstart; base.end=dtend;
base.allDay=allDay; base.src=src; base.segStartAtDay=false; base.segEndAtDay=false; base.parentAllDaySpan=0;
time_t dur = (hasDTEND && dtend>dtstart) ? (dtend - dtstart) : (allDay ? 86400 : 3600);
std::set<time_t> ex;
for (auto &exl : exdateLines){ std::vector<time_t> vals; parseMultiDateLine(exl, vals, floatingUTC); for (auto ts: vals) ex.insert(ts); }
std::vector<time_t> rdates; for (auto &rdl : rdateLines){ parseMultiDateLine(rdl, rdates, floatingUTC); }
bool hasAtt = !attendeeLines.empty();
bool anyRSVPflag = false;
bool anyPARTSTAT = false;
for (auto &al : attendeeLines) {
String up = al; up.toUpperCase();
if (up.indexOf("RSVP=TRUE") >= 0) anyRSVPflag = true;
if (up.indexOf("PARTSTAT=") >= 0) anyPARTSTAT = true;
}
int relevantCount = 0;
int acceptedCount = 0;
for (auto &al : attendeeLines) {
String up = al; up.toUpperCase();
bool isRelevant =
(anyRSVPflag && up.indexOf("RSVP=TRUE") >= 0) ||
(!anyRSVPflag && anyPARTSTAT && up.indexOf("PARTSTAT=") >= 0);
if (!isRelevant) continue;
relevantCount++;
if (up.indexOf("PARTSTAT=ACCEPTED") >= 0) acceptedCount++;
}
bool needsAckMeeting = hasAtt && (anyRSVPflag || anyPARTSTAT);
bool allRelevantAccepted = (relevantCount > 0) && (acceptedCount == relevantCount);
String sumLow = summary; sumLow.toLowerCase();
auto contains = [&](const char* needle)->bool { return sumLow.indexOf(needle) >= 0; };
String catLow = categoriesVal; catLow.toLowerCase();
bool looksTask =
contains("erledigen")
|| contains("aufgabe")
|| contains("todo")
|| contains("[ ]")
|| catLow.indexOf("task")>=0
|| catLow.indexOf("todo")>=0
|| catLow.indexOf("aufgabe")>=0;
auto maybeAddOcc=[&](time_t st){
if (ex.count(st)) return;
time_t en = st + dur;
if (en <= wStart) return;
if (st >= wEnd) return;
Event e = base; e.start = st; e.end = en; out.push_back(e);
String k = e.uid + "#" + String((uint32_t)st);
if (looksTask) {
g_ack_required.insert(k);
g_ack_is_task.insert(k);
} else if (needsAckMeeting) {
g_ack_required.insert(k);
if (allRelevantAccepted) g_ack_external_done.insert(k);
}
};
if (rruleLine.length()==0 && rdates.empty()){
maybeAddOcc(dtstart);
} else {
for (auto ts : rdates) maybeAddOcc(ts);
RRule rr; if (rruleLine.length()) parseRRule(rruleLine, rr);
String f = rr.freq; f.toUpperCase();
auto pushIfFirstAndAllowed = [&](){ maybeAddOcc(dtstart); };
if (f=="DAILY"){
pushIfFirstAndAllowed();
time_t cur = dtstart;
while (true){
cur = add_days_local(cur, rr.interval);
if (cur>=wEnd) break;
maybeAddOcc(cur);
}
} else if (f=="WEEKLY"){
struct tm tm0; localtime_r(&dtstart,&tm0);
int dt_wd = tm0.tm_wday;
int H = tm0.tm_hour, m = tm0.tm_min, s = tm0.tm_sec;
pushIfFirstAndAllowed();
time_t week0 = week_start_local(dtstart, rr.wkst);
std::vector<int> by = rr.byday.empty()? std::vector<int>{ dt_wd } : rr.byday;
for (time_t baseW = week0; ; baseW = add_days_local(baseW, rr.interval*7)){
if (baseW >= wEnd) break;
for (int wd : by){
int offs = (wd - rr.wkst + 7) % 7;
time_t day_ts = add_days_local(baseW, offs);
struct tm t; localtime_r(&day_ts,&t);
time_t occ = make_local_datetime(t.tm_year+1900, t.tm_mon+1, t.tm_mday, H, m, s);
if (occ < dtstart) continue;
maybeAddOcc(occ);
}
}
} else if (f=="MONTHLY"){
pushIfFirstAndAllowed();
struct tm tm; localtime_r(&dtstart,&tm);
int y=tm.tm_year+1900, M=tm.tm_mon+1, d=tm.tm_mday, H=tm.tm_hour, mi=tm.tm_min, s=tm.tm_sec;
while (true){
int ny=y, nM=M+rr.interval; while (nM>12){ nM-=12; ny++; }
y=ny; M=nM;
struct tm t3={}; t3.tm_year=y-1900; t3.tm_mon=M-1; t3.tm_mday=1; t3.tm_isdst=-1;
if (mktime(&t3) >= wEnd) break;
auto daysInMonth=[&](int yy,int MM){ static const int md[12]={31,28,31,30,31,30,31,31,30,31,30,31}; int dd=md[MM-1]; bool leap=( (yy%4==0 && yy%100!=0) || (yy%400==0) ); return (MM==2 && leap)? 29: dd; };
std::vector<int> dm = rr.bymonthday.empty()? std::vector<int>{ d } : rr.bymonthday;
for (int day : dm){
int dim = daysInMonth(y,M); if (day<1 || day>dim) continue;
time_t occ = make_local_datetime(y,M,day,H,mi,s);
if (occ < dtstart) continue;
maybeAddOcc(occ);
}
}
} else if (f=="YEARLY"){
pushIfFirstAndAllowed();
struct tm tm; localtime_r(&dtstart,&tm);
int y=tm.tm_year+1900, M=tm.tm_mon+1, d=tm.tm_mday, H=tm.tm_hour, mi=tm.tm_min, s=tm.tm_sec;
while (true){
y += rr.interval;
struct tm jan1={}; jan1.tm_year=y-1900; jan1.tm_mon=0; jan1.tm_mday=1; jan1.tm_isdst=-1;
if (mktime(&jan1) >= wEnd) break;
std::vector<int> months = rr.bymonth.empty()? std::vector<int>{ M } : rr.bymonth;
auto daysInMonth=[&](int yy,int MM){ static const int md[12]={31,28,31,30,31,30,31,31,30,31,30,31}; int dd=md[MM-1]; bool leap=( (yy%4==0 && yy%100!=0) || (yy%400==0) ); return (MM==2 && leap)? 29: dd; };
for (int MM : months){
std::vector<int> dm = rr.bymonthday.empty()? std::vector<int>{ d } : rr.bymonthday;
for (int day : dm){
int dim=daysInMonth(y,MM); if (day<1 || day>dim) continue;
time_t occ = make_local_datetime(y,MM,day,H,mi,s);
if (occ < dtstart) continue;
maybeAddOcc(occ);
}
}
}
} else {
maybeAddOcc(dtstart);
}
}
}
inEvent=false;
} else if (inEvent) {
if (line.startsWith("UID:")) { uid=line.substring(4); }
else if (line.startsWith("SUMMARY:")) { summary=line.substring(8); }
else if (line.startsWith("DTSTART")) { time_t ts=0; bool ad=false; if (parseDateTimeField(line, ts, ad, TZ_EU_BERLIN, floatingUTC)){ dtstart=ts; allDay=ad; hasDTSTART=true; } }
else if (line.startsWith("DTEND")) { time_t ts=0; bool ad=false; if (parseDateTimeField(line, ts, ad, TZ_EU_BERLIN, floatingUTC)){ dtend=ts; hasDTEND=true; } }
else if (line.startsWith("RRULE")) { rruleLine=line; }
else if (line.startsWith("EXDATE")) { exdateLines.push_back(line); }
else if (line.startsWith("RDATE")) { rdateLines.push_back(line); }
else if (line.startsWith("ATTENDEE")) { attendeeLines.push_back(line); }
else if (line.startsWith("CATEGORIES:")) { categoriesVal = line.substring(11); categoriesVal.trim(); }
}
}
return true;
}
/* ---------- HTTP + Wetter ---------- */
static WiFiClientSecure g_tls_client;
static bool g_tls_init = false;
int httpGetICS_ETag(const char* url, const String& sendEtag, String& payload, String& newETag) {
payload = ""; newETag = "";
if (!g_tls_init) { g_tls_client.setInsecure(); g_tls_init = true; }
HTTPClient http; http.setTimeout(12000); http.setReuse(true);
if (!http.begin(g_tls_client, url)) return -1;
if (sendEtag.length()) http.addHeader("If-None-Match", sendEtag);
http.addHeader("Connection", "keep-alive");
int code=http.GET();
if (code==HTTP_CODE_OK) { payload=http.getString(); newETag=http.header("ETag"); }
http.end();
return code;
}
String fmt(float v,int d=1,const char* suf=""){ if(isnan(v)) return "--"; String s=String(v,d); if(suf&&suf[0]) s+=suf; return s; }
String fmtTimeShortRaw(time_t t){ struct tm tm; localtime_r(&t,&tm); char b[16]; strftime(b,sizeof(b),"%H:%M",&tm); return String(b); }
time_t disp(time_t t){ return t + DISPLAY_OFFSET_MIN*60; }
String fmtTimeShortAdj(time_t t){ return fmtTimeShortRaw(disp(t)); }
static const char* cond_from(float cloud, float pprob){
if (!isnan(pprob) && pprob >= 55) return "Regen";
if (!isnan(cloud)){
if (cloud <= 25) return "Sonne";
if (cloud <= 70) return "Wolken";
}
return "Wolken";
}
static const char* icon_text(float cloud, float pprob){ return cond_from(cloud, pprob); }
bool fetchWeather(String& err) {
ensureWiFi();
if (!g_tls_init) { g_tls_client.setInsecure(); g_tls_init = true; }
HTTPClient http;
http.setTimeout(8000);
http.setReuse(true);
String url =
String("https://api.open-meteo.com/v1/forecast?latitude=")+String(LAT,4)+
"&longitude="+String(LON,4)+
"¤t=temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,cloud_cover"+
"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum,precipitation_probability_max,precipitation_hours,sunrise,sunset,uv_index_max"+
"&hourly=temperature_2m"+
"&past_days=1&timezone=Europe%2FBerlin";
if(!http.begin(g_tls_client,url)){ err="HTTP begin"; return false; }
http.addHeader("Connection", "keep-alive");
int code=http.GET();
if(code!=HTTP_CODE_OK){ err=String("HTTP ")+code; http.end(); return false; }
String payload=http.getString();
http.end();
// WICHTIG: NICHT als großes Objekt auf dem Stack (das kann Reboots verursachen)
static StaticJsonDocument<24576> doc;
doc.clear();
auto jerr=deserializeJson(doc,payload);
if(jerr){ err=String("JSON: ")+jerr.c_str(); return false; }
currentTemp = doc["current"]["temperature_2m"] | NAN;
currentApp = doc["current"]["apparent_temperature"] | NAN;
currentHum = doc["current"]["relative_humidity_2m"] | NAN;
currentWind = doc["current"]["wind_speed_10m"] | NAN;
currentCloud= doc["current"]["cloud_cover"] | NAN;
JsonObject daily = doc["daily"];
JsonArray timeArr = daily["time"];
time_t nowTs = time(nullptr);
struct tm tmNow; localtime_r(&nowTs, &tmNow);
char buf[16];
strftime(buf, sizeof(buf), "%Y-%m-%d", &tmNow);
String todayStr = buf;
int todayIdx = -1;
for (int i = 0; i < (int)timeArr.size(); ++i)
if (String(timeArr[i].as<const char*>()) == todayStr) { todayIdx = i; break; }
if (todayIdx < 0) todayIdx = 0;
// 5-Tage-Vorschau
wDaysCount = 0;
for (int k = 0; k < 5; ++k) {
int idx = todayIdx + k;
if (idx >= (int)timeArr.size()) break;
DayWeather d;
d.date = (const char*)timeArr[idx];
d.tmax = daily["temperature_2m_max"].isNull() ? NAN : (float)daily["temperature_2m_max"][idx].as<double>();
d.tmin = daily["temperature_2m_min"].isNull() ? NAN : (float)daily["temperature_2m_min"][idx].as<double>();
d.precip_sum = daily["precipitation_sum"].isNull() ? NAN : (float)daily["precipitation_sum"][idx].as<double>();
d.precip_prob = daily["precipitation_probability_max"].isNull() ? NAN : (float)daily["precipitation_probability_max"][idx].as<double>();
d.precip_hours = daily["precipitation_hours"].isNull() ? NAN : (float)daily["precipitation_hours"][idx].as<double>();
d.uv_max = daily["uv_index_max"].isNull() ? NAN : (float)daily["uv_index_max"][idx].as<double>();
{ String ss=(const char*)daily["sunrise"][idx]; int t=ss.indexOf('T'); d.sunrise=(t>0)? ss.substring(t+1, t+6): ss; }
{ String ss=(const char*)daily["sunset"][idx]; int t=ss.indexOf('T'); d.sunset =(t>0)? ss.substring(t+1, t+6): ss; }
wDays[wDaysCount++] = d;
if (wDaysCount >= 5) break;
}
// WICHTIG: Heute/Morgen wieder sauber setzen (ohne deinen alten auskommentierten Block)
auto clearDay = [](DayWeather &dw){
dw.date = "";
dw.tmax = NAN; dw.tmin = NAN;
dw.precip_sum = NAN; dw.precip_prob = NAN; dw.precip_hours = NAN;
dw.uv_max = NAN;
dw.sunrise = ""; dw.sunset = "";
};
clearDay(wToday);
clearDay(wTomorrow);
if (wDaysCount > 0) wToday = wDays[0];
if (wDaysCount > 1) wTomorrow = wDays[1];
// nächste 8 Stunden
next8_count = 0;
JsonArray htemps = doc["hourly"]["temperature_2m"].as<JsonArray>();
JsonArray htime = doc["hourly"]["time"].as<JsonArray>();
int idxNow = -1;
if (!htemps.isNull() && !htime.isNull() && htemps.size() == htime.size() && htemps.size() > 0) {
char hb[20]; strftime(hb, sizeof(hb), "%Y-%m-%dT%H:00", &tmNow);
String nowHourStr = hb;
for (int i = 0; i < (int)htime.size(); ++i)
if (String(htime[i].as<const char*>()) == nowHourStr) { idxNow = i; break; }
if (idxNow < 0) {
for (int i = (int)htime.size() - 1; i >= 0; --i) {
String ts = String(htime[i].as<const char*>());
if (ts <= nowHourStr) { idxNow = i; break; }
}
}
if (idxNow >= 0) {
for (int j = 1; j <= 8 && (idxNow + j) < (int)htime.size(); ++j) {
next8_temp[next8_count] = (float)htemps[idxNow + j].as<double>();
String ts = (const char*)htime[idxNow + j];
String HH = ts.substring(11,13);
next8_time[next8_count] = HH + "h";
next8_count++;
}
}
}
err = "";
g_lastWeatherFetchTs = time(nullptr);
return true;
}
/* ---------- WiFi ---------- */
static bool testDNS(const char* host) {
IPAddress ip;
bool ok = WiFi.hostByName(host, ip);
Serial.printf("[WIFI] DNS test %s -> %s (%s)\n",
host,
ok ? ip.toString().c_str() : "FAIL",
ok ? "OK" : "FAIL");
return ok;
}
void ensureWiFi() {
if (WiFi.status() == WL_CONNECTED) return;
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED && (millis() - t0) < 15000) {
wdt_kick();
delay(100);
}
// NEU: Ergebnis loggen
logWiFiStatus("ensureWiFi()");
if (WiFi.status() == WL_CONNECTED) {
testDNS();
} else {
Serial.println("[WIFI] Connect FAILED (timeout)");
}
}
/* ---------- Persistenz für Aufgaben-Checks ---------- */
static String ack_key_for(const Event& e) {
String k = e.uid; k += "#"; k += String((uint32_t)e.start);
return k;
}
static void ack_load() {
if (!g_prefs.begin("ack", true)) return;
String csv = g_prefs.getString("keys", "");
g_prefs.end();
g_ack_keys.clear();
int i=0;
while (i < (int)csv.length()) {
int c = csv.indexOf(',', i); if (c < 0) c = csv.length();
String tok = csv.substring(i, c); tok.trim();
if (tok.length()) g_ack_keys.insert(tok);
i = c + 1;
}
}
static void ack_save() {
if (!g_prefs.begin("ack", false)) return;
String csv;
for (auto it=g_ack_keys.begin(); it!=g_ack_keys.end(); ++it) {
if (it!=g_ack_keys.begin()) csv += ",";
csv += *it;
}
g_prefs.putString("keys", csv);
g_prefs.end();
}
/* ---------- Alarm Persistenz ---------- */
static void alarm_load_settings() {
if (!g_prefs.begin("alarm", true)) return;
g_alarm_enabled = g_prefs.getBool("enabled", false);
g_alarm_hour = g_prefs.getUChar("hour", 7);
g_alarm_minute = g_prefs.getUChar("min", 0);
g_prefs.end();
// Falls jemand Mist reinschreibt / Daten kaputt sind:
if (g_alarm_hour > 23) g_alarm_hour = 7;
if (g_alarm_minute > 59) g_alarm_minute = 0;
}
static void alarm_save_settings() {
if (!g_prefs.begin("alarm", false)) return;
g_prefs.putBool("enabled", g_alarm_enabled);
g_prefs.putUChar("hour", g_alarm_hour);
g_prefs.putUChar("min", g_alarm_minute);
g_prefs.end();
}
/* ---------- Custom Check-Square ---------- */
static void set_check_square_state(lv_obj_t* box, bool checked) {
lv_obj_set_size(box, 30, 30);
lv_obj_set_style_bg_opa(box, LV_OPA_COVER, 0);
lv_obj_set_style_bg_color(box, lv_color_white(), 0);
lv_obj_set_style_radius(box, 6, 0);
lv_obj_set_style_border_width(box, 1, 0);
lv_obj_set_style_border_color(box, lv_color_hex(0xC8CBD0), 0);
lv_obj_set_style_pad_all(box, 0, 0);
if (checked) lv_obj_add_state(box, LV_STATE_CHECKED);
else lv_obj_clear_state(box, LV_STATE_CHECKED);
lv_obj_t* tick = nullptr;
uint32_t cnt = lv_obj_get_child_cnt(box);
for (uint32_t i=0;i<cnt;i++){
lv_obj_t* ch = lv_obj_get_child(box, i);
if (lv_obj_check_type(ch, &lv_line_class)) { tick = ch; break; }
}
if (!tick) tick = lv_line_create(box);
static lv_point_t pts[3];
pts[0] = { 6, 16 };
pts[1] = { 13, 22 };
pts[2] = { 24, 9 };
lv_line_set_points(tick, pts, 3);
lv_obj_center(tick);
lv_color_t green = lv_color_hex(0x1F7A1F);
lv_obj_set_style_line_color(tick, checked ? green : lv_color_white(), 0);
lv_obj_set_style_line_width(tick, 5, 0);
lv_obj_set_style_line_rounded(tick, true, 0);
lv_obj_set_style_opa(tick, checked ? LV_OPA_COVER : LV_OPA_TRANSP, 0);
}
static void check_square_toggle_cb(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_CLICKED) return;
lv_obj_t* box = lv_event_get_target(e);
const char* key = (const char*)lv_event_get_user_data(e);
bool wasChecked = lv_obj_has_state(box, LV_STATE_CHECKED);
bool nowChecked = !wasChecked;
if (key) {
if (nowChecked) g_ack_keys.insert(String(key));
else g_ack_keys.erase(String(key));
ack_save();
}
set_check_square_state(box, nowChecked);
}
static lv_obj_t* create_check_square(lv_obj_t* parent, bool checked, bool clickable, const String& keyS) {
lv_obj_t* box = lv_obj_create(parent);
lv_obj_remove_style_all(box);
lv_obj_set_flex_grow(box, 0);
lv_obj_set_style_pad_left(box, 10, 0);
set_check_square_state(box, checked);
if (clickable) {
char* heapKey = (char*)malloc(keyS.length()+1);
if (heapKey) memcpy(heapKey, keyS.c_str(), keyS.length()+1);
lv_obj_add_event_cb(box, check_square_toggle_cb, LV_EVENT_CLICKED, (void*)heapKey);
lv_obj_add_event_cb(box, [](lv_event_t* ev){
if (lv_event_get_code(ev) == LV_EVENT_DELETE) {
void* ud = (void*)lv_event_get_user_data(ev);
if (ud) free(ud);
}
}, LV_EVENT_DELETE, (void*)heapKey);
lv_obj_add_flag(box, LV_OBJ_FLAG_CLICKABLE);
} else {
lv_obj_clear_flag(box, LV_OBJ_FLAG_CLICKABLE);
}
return box;
}
/* ========== Popup / Neue Termine / FAB ========== */
static String fmt_date_dmy(time_t ts) {
struct tm tmL; localtime_r(&ts,&tmL);
char b[16]; strftime(b,sizeof(b),"%d.%m.%Y",&tmL);
return String(b);
}
// Kalender-Name aus src ableiten
// src = 1 => ICS_URL_1 => Lena
// src = 2 => ICS_URL_2 => Damian
static String cal_name_for_src(uint8_t src) {
switch (src) {
case 1: return "Lena"; // ICS_URL_1
case 2: return "Damian"; // ICS_URL_2
default: {
String s = "Kalender ";
s += String(src);
return s;
}
}
}
static void popup_close_cb(lv_timer_t* t){
(void)t;
if (g_popup){
lv_obj_del_async(g_popup);
g_popup = nullptr;
}
if (g_popup_timer){
lv_timer_del(g_popup_timer);
g_popup_timer = nullptr;
}
}
static void show_new_event_popup(const String& title, const String& detail){
if (g_popup){ lv_obj_del(g_popup); g_popup=nullptr; }
if (g_popup_timer){ lv_timer_del(g_popup_timer); g_popup_timer=nullptr; }
g_popup = lv_obj_create(root_scr);
lv_obj_remove_style_all(g_popup);
lv_obj_add_style(g_popup, &st_popup, 0);
lv_obj_set_size(g_popup, POPUP_W, POPUP_H);
lv_obj_align(g_popup, LV_ALIGN_TOP_MID, 0, 60);
lv_obj_set_flex_flow(g_popup, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_top(g_popup, 12 + PAD_V, 0);
lv_obj_set_style_pad_bottom(g_popup, 12 + PAD_V, 0);
lv_obj_set_style_pad_left(g_popup, 16, 0);
lv_obj_set_style_pad_right(g_popup, 16, 0);
lv_obj_set_style_pad_row(g_popup, GAP, 0);
lv_obj_t* lblTitle = lv_label_create(g_popup);
lv_obj_add_style(lblTitle, &st_popup_title, 0);
lv_label_set_text(lblTitle, title.c_str());
lv_label_set_long_mode(lblTitle, LV_LABEL_LONG_WRAP);
lv_obj_set_width(lblTitle, LV_PCT(100));
lv_obj_set_style_text_align(lblTitle, LV_TEXT_ALIGN_LEFT, 0);
lv_obj_add_flag(lblTitle, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_t* sep = lv_obj_create(g_popup);
lv_obj_remove_style_all(sep);
lv_obj_set_width(sep, LV_PCT(100));
lv_obj_set_height(sep, 1);
lv_obj_set_style_bg_opa(sep, LV_OPA_COVER, 0);
lv_obj_set_style_bg_color(sep, lv_color_hex(0xE5EAF0), 0);
lv_obj_add_flag(sep, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_t* lblDet = lv_label_create(g_popup);
lv_obj_add_style(lblDet, &st_popup_details, 0);
lv_label_set_text(lblDet, detail.c_str());
lv_label_set_long_mode(lblDet, LV_LABEL_LONG_WRAP);
lv_obj_set_width(lblDet, LV_PCT(100));
lv_obj_set_style_text_align(lblDet, LV_TEXT_ALIGN_LEFT, 0);
lv_obj_add_flag(lblDet, LV_OBJ_FLAG_ADV_HITTEST);
g_popup_timer = lv_timer_create(popup_close_cb, 8000, nullptr);
}
static void show_new_event_popup_for(const Event& e){
String title = "Neuer Termin";
struct tm tmL;
localtime_r(&e.start, &tmL);
char hb[8];
strftime(hb, sizeof(hb), "%H:%M", &tmL);
// Titelzeile: Name des Termins
String detail = (e.summary.length() ? e.summary : String("(ohne Titel)"));
detail += "\n";
// Zweite Zeile: Tag + Datum + Zeit
detail += String(DE_WD[tmL.tm_wday]) + " " + fmt_date_dmy(e.start) + " um " + String(hb);
// Dritte Zeile: von Lena / von Damian
detail += "\nvon ";
detail += cal_name_for_src(e.src);
show_new_event_popup(title, detail);
}
static void mail_fab_update_visibility() {
if (!mail_fab) return;
if (g_has_new_events) lv_obj_clear_flag(mail_fab, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(mail_fab, LV_OBJ_FLAG_HIDDEN);
}
static void close_popup_and_clear_new_list(lv_obj_t* pop) {
g_new_events_buf.clear();
g_has_new_events = false;
mail_fab_update_visibility();
if (pop) lv_obj_del_async(pop);
}
static void mail_fab_clicked_cb(lv_event_t* e); // fwd
static void mail_fab_create(lv_obj_t* parent) {
if (mail_fab) return;
mail_fab = lv_btn_create(parent);
lv_obj_remove_style_all(mail_fab);
lv_obj_set_size(mail_fab, 48, 48);
lv_obj_set_style_radius(mail_fab, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_bg_color(mail_fab, lv_palette_main(LV_PALETTE_BLUE), 0);
lv_obj_set_style_bg_opa(mail_fab, LV_OPA_COVER, 0);
lv_obj_set_style_shadow_width(mail_fab, 8, 0);
lv_obj_set_style_shadow_opa(mail_fab, LV_OPA_30, 0);
lv_obj_set_style_shadow_ofs_y(mail_fab, 2, 0);
lv_obj_align(mail_fab, LV_ALIGN_BOTTOM_LEFT, 10, -10);
lv_obj_add_event_cb(mail_fab, mail_fab_clicked_cb, LV_EVENT_CLICKED, NULL);
lv_obj_t* ico = lv_img_create(mail_fab);
lv_img_set_src(ico, &mark_email_unread_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24);
lv_obj_center(ico);
lv_obj_add_flag(mail_fab, LV_OBJ_FLAG_HIDDEN);
}
static void show_new_events_list_popup() {
if (g_new_events_buf.empty()) return;
// Popup erzeugen
lv_obj_t* pop = lv_obj_create(root_scr);
lv_obj_remove_style_all(pop);
lv_obj_add_style(pop, &st_popup, 0);
// Breite fix, Höhe = Inhalt, aber nicht höher als 380px
lv_obj_set_width(pop, 560);
lv_obj_set_height(pop, LV_SIZE_CONTENT);
lv_obj_set_style_max_height(pop, 380, 0);
lv_obj_align(pop, LV_ALIGN_TOP_LEFT, 50, 70);
lv_obj_set_flex_flow(pop, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_top(pop, 8, 0);
lv_obj_set_style_pad_bottom(pop, 8, 0);
lv_obj_set_style_pad_row(pop, 4, 0);
// Titel
lv_obj_t* t = lv_label_create(pop);
lv_obj_add_style(t, &st_popup_title, 0);
lv_label_set_text(t, "Neue Termine");
lv_obj_add_flag(t, LV_OBJ_FLAG_ADV_HITTEST);
// Trennlinie
lv_obj_t* sep = lv_obj_create(pop);
lv_obj_remove_style_all(sep);
lv_obj_set_width(sep, LV_PCT(100));
lv_obj_set_height(sep, 1);
lv_obj_set_style_bg_color(sep, lv_color_hex(0xE5EAF0), 0);
lv_obj_set_style_bg_opa(sep, LV_OPA_COVER, 0);
lv_obj_add_flag(sep, LV_OBJ_FLAG_ADV_HITTEST);
// Liste der neuen Termine
lv_obj_t* list = lv_obj_create(pop);
lv_obj_remove_style_all(list);
lv_obj_set_width(list, LV_PCT(100));
lv_obj_set_flex_flow(list, LV_FLEX_FLOW_COLUMN);
lv_obj_set_height(list, LV_SIZE_CONTENT);
lv_obj_set_style_max_height(list, 300, 0);
lv_obj_set_style_bg_opa(list, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_row(list, 1, 0);
lv_obj_set_style_pad_top(list, 0, 0);
lv_obj_set_style_pad_bottom(list, 0, 0);
lv_obj_add_flag(list, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scroll_dir(list, LV_DIR_VER);
lv_obj_set_scrollbar_mode(list, LV_SCROLLBAR_MODE_OFF);
// --- Ein Block pro Termin (3 Zeilen untereinander) ---
int maxItems = 12;
int count = 0;
for (const auto& e : g_new_events_buf) {
if (count++ >= maxItems) break;
lv_obj_t* row = lv_obj_create(list);
lv_obj_remove_style_all(row);
lv_obj_set_width(row, LV_PCT(100));
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_bg_opa(row, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_top(row, 0, 0);
lv_obj_set_style_pad_bottom(row, 0, 0);
lv_obj_set_style_pad_left(row, 2, 0);
lv_obj_set_style_pad_right(row, 2, 0);
lv_obj_set_style_pad_row(row, 0, 0);
// ----- Zeile 1: Tag + Datum + Zeit -----
struct tm tmL;
localtime_r(&e.start, &tmL);
String whenLine;
if (e.allDay) {
whenLine = String(DE_WD[tmL.tm_wday]) + " " + fmt_date_dmy(e.start) + ", ganzt.";
} else {
String s = fmtTimeShortAdj(e.start);
String en = (e.end > e.start) ? fmtTimeShortAdj(e.end) : "";
String timePart = en.length() ? (s + " - " + en) : s;
whenLine = String(DE_WD[tmL.tm_wday]) + " " + fmt_date_dmy(e.start) + " " + timePart;
}
lv_obj_t* lwhen = lv_label_create(row);
lv_obj_add_style(lwhen, &st_time, 0);
lv_label_set_text(lwhen, whenLine.c_str());
lv_obj_set_style_text_align(lwhen, LV_TEXT_ALIGN_LEFT, 0);
lv_obj_add_flag(lwhen, LV_OBJ_FLAG_ADV_HITTEST);
// ----- Zeile 2: Name des Termins -----
String titleText = e.summary.length() ? e.summary : "(ohne Titel)";
lv_obj_t* ltitle = lv_label_create(row);
lv_obj_add_style(ltitle, &st_title, 0);
lv_label_set_text(ltitle, titleText.c_str());
lv_label_set_long_mode(ltitle, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(ltitle, LV_TEXT_ALIGN_LEFT, 0);
lv_obj_add_flag(ltitle, LV_OBJ_FLAG_ADV_HITTEST);
// ----- Zeile 3: von Lena / von Damian -----
String calLine = "von ";
calLine += cal_name_for_src(e.src);
lv_obj_t* lcal = lv_label_create(row);
lv_obj_add_style(lcal, &st_day_text_small, 0);
lv_label_set_text(lcal, calLine.c_str());
lv_obj_set_style_text_align(lcal, LV_TEXT_ALIGN_LEFT, 0);
lv_obj_add_flag(lcal, LV_OBJ_FLAG_ADV_HITTEST);
}
// OK-Button
lv_obj_t* btn_row = lv_obj_create(list);
lv_obj_remove_style_all(btn_row);
lv_obj_set_width(btn_row, LV_PCT(100));
lv_obj_set_flex_flow(btn_row, LV_FLEX_FLOW_ROW);
lv_obj_set_style_bg_opa(btn_row, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_top(btn_row, 6, 0);
lv_obj_set_style_pad_bottom(btn_row, 0, 0);
lv_obj_set_flex_align(btn_row, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START);
lv_obj_t* ok = lv_btn_create(btn_row);
lv_obj_remove_style_all(ok);
lv_obj_set_style_bg_color(ok, lv_palette_main(LV_PALETTE_BLUE), 0);
lv_obj_set_style_bg_opa(ok, LV_OPA_COVER, 0);
lv_obj_set_style_radius(ok, 10, 0);
lv_obj_set_style_pad_left(ok, 16, 0);
lv_obj_set_style_pad_right(ok, 16, 0);
lv_obj_set_style_pad_top(ok, 8, 0);
lv_obj_set_style_pad_bottom(ok, 8, 0);
lv_obj_add_event_cb(ok, [](lv_event_t* e){
lv_obj_t* btn = lv_event_get_target(e);
lv_obj_t* btn_row = lv_obj_get_parent(btn);
lv_obj_t* list = lv_obj_get_parent(btn_row);
lv_obj_t* pop = lv_obj_get_parent(list);
close_popup_and_clear_new_list(pop);
}, LV_EVENT_CLICKED, NULL);
lv_obj_t* ok_lbl = lv_label_create(ok);
lv_obj_set_style_text_color(ok_lbl, lv_color_white(), 0);
lv_label_set_text(ok_lbl, "OK");
lv_obj_center(ok_lbl);
lv_obj_add_flag(ok_lbl, LV_OBJ_FLAG_ADV_HITTEST);
}
static void mail_fab_clicked_cb(lv_event_t* e) {
(void)e;
g_req_show_new_events_popup = true; // nur anfordern
}
/* ===================== LVGL UI ===================== */
static String current_view_title(){
switch(currentView){
case VIEW_CAL: return "Klender - Termine";
case VIEW_DATA: return "Wetter Stulln";
case VIEW_LED: return "LED Steuerung";
}
return "Klender";
}
static void set_header_with_now() {
static String lastText;
String base = current_view_title();
String nowS = headerNowString();
time_t lastTs = (currentView==VIEW_CAL) ? g_lastCalFetchTs : g_lastWeatherFetchTs;
String upd = "Aktualisiert: " + fmt_hhmm(lastTs);
String text = base + " | " + nowS + " | " + upd;
if (text != lastText) {
lv_label_set_text(header_label, text.c_str());
lastText = text;
}
}
static void set_footer_stale(bool on) {
if (on) lv_obj_clear_flag(footer_badge, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(footer_badge, LV_OBJ_FLAG_HIDDEN);
}
static lv_color_t color_for_src(uint8_t src) {
switch (src) {
case 1: return lv_palette_main(LV_PALETTE_BLUE);
case 2: return lv_palette_main(LV_PALETTE_GREEN);
default:return lv_palette_main(LV_PALETTE_GREY);
}
}
static void gesture_event_cb(lv_event_t *e){
if (lv_event_get_code(e) != LV_EVENT_GESTURE) return;
// Wenn Slider/Touchelement gerade Swipes blockiert -> nichts tun
if (g_block_swipe) return;
lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act());
// ---- Swipe: Kalender ist Hub, direkte LED<->Wetter Wechsel werden verhindert ----
bool changed = false;
if (dir == LV_DIR_LEFT) {
if (currentView == VIEW_CAL) {
currentView = VIEW_DATA; // Kalender -> Wetter
changed = true;
} else if (currentView == VIEW_LED) {
currentView = VIEW_CAL; // LED -> Kalender
changed = true;
} else {
// VIEW_DATA: links -> NICHTS tun
return;
}
}
else if (dir == LV_DIR_RIGHT) {
if (currentView == VIEW_CAL) {
currentView = VIEW_LED; // Kalender -> LED
changed = true;
} else if (currentView == VIEW_DATA) {
currentView = VIEW_CAL; // Wetter -> Kalender
changed = true;
} else {
// VIEW_LED: rechts -> NICHTS tun
return;
}
}
else {
return;
}
if (changed) {
// NICHT direkt zeichnen, sondern nur redraw vormerken
g_need_view_redraw = true;
}
}
/* ---------------- Kalender View ---------------- */
static bool icontains(const String& hay, const char* needle) {
const char* h = hay.c_str();
size_t hl = hay.length();
size_t nl = strlen(needle);
if (nl == 0 || nl > hl) return false;
auto tolow = [](char c)->char { return (c>='A'&&c<='Z') ? (c+32) : c; };
for (size_t i=0; i+nl<=hl; ++i) {
size_t k=0;
for (; k<nl; ++k) {
if (tolow(h[i+k]) != tolow(needle[k])) break;
}
if (k==nl) return true;
}
return false;
}
static bool summary_has_any(const String& title, std::initializer_list<const char*> words) {
for (auto w : words) if (icontains(title, w)) return true;
return false;
}
static const lv_img_dsc_t* pick_icon_for(const String& title) {
//if (summary_has_any(title, {"uni", "vorlesung", "campus"}))
//return &school_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
if (summary_has_any(title, {"lieb", "lena", "oma", "familie"}))
return &favorite_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
//if (summary_has_any(title, {"schwimmen", "pool", "baden"}))
// return &pool_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
// if (summary_has_any(title, {"arbeit", "job", "büro"}))
// return &work_24dp_1F1F1F_FILL0_wght400_GRAD0_opsz24;
return nullptr;
}
static void rebuild_cal_list() {
static uint32_t last_hash = 0;
uint32_t h = 1469598103u;
auto mix = [&](uint32_t v){ h ^= v; h *= 16777619u; };
mix((uint32_t)cal_events.size());
for (size_t i=0;i<cal_events.size(); ++i) {
mix((uint32_t)cal_events[i].start);
mix((uint32_t)cal_events[i].end);
}
if (h == last_hash) return;
last_hash = h;
lv_obj_clean(cal_list);
lv_obj_invalidate(cal_list); // <- neu
lv_obj_invalidate(cal_viewport);
time_t nowTs = time(nullptr);
struct tm tmNow; localtime_r(&nowTs, &tmNow);
const int todayKey = (tmNow.tm_year + 1900) * 10000 + (tmNow.tm_mon + 1) * 100 + (tmNow.tm_mday);
if (cal_events.empty()) {
lv_obj_clean(cal_list); // Liste wirklich leer machen
lv_obj_invalidate(cal_list); // <-- wichtig: kompletten Bereich neu zeichnen
lv_obj_t* row = lv_label_create(cal_list);
lv_obj_set_width(row, LV_PCT(100)); // sorgt für sauberen Invalidate/Redraw
lv_label_set_text(row, "Keine kommenden Termine.");
lv_obj_add_style(row, &st_title, 0);
// NICHT translate_x (kann Artefakte verursachen) -> stattdessen echtes Padding
lv_obj_set_style_pad_left(row, LEFT_INSET_PX + mm_to_px(20.0f), 0);
lv_obj_set_style_pad_top(row, 10, 0);
return;
}
int shown = 0;
const int W_DATE = 100;
const int W_TIME = 170;
const int W_BUL = 12;
const int PAD_RIGHT = 8;
int lastKey = -1;
for (size_t i=0; i<cal_events.size() && shown < g_events_limit; ++i) {
const auto &e = cal_events[i];
struct tm tmS; localtime_r(&e.start, &tmS);
int key = (tmS.tm_year + 1900) * 10000 + (tmS.tm_mon + 1) * 100 + (tmS.tm_mday);
bool showDate = (key != lastKey);
lv_obj_t* row = lv_obj_create(cal_list);
lv_obj_remove_style_all(row);
lv_obj_set_width(row, LV_PCT(100));
lv_obj_set_height(row, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START);
lv_obj_add_style(row, &st_row_base, 0);
(shown % 2) ? lv_obj_add_style(row, &st_row_odd, 0)
: lv_obj_add_style(row, &st_row_even, 0);
lv_obj_set_style_clip_corner(row, true, 0);
lv_obj_set_style_pad_left(row, LEFT_INSET_PX, 0);
lv_obj_set_style_pad_right(row, PAD_RIGHT, 0);
lv_obj_set_style_pad_bottom(row, 3, 0);
lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(row, LV_OBJ_FLAG_GESTURE_BUBBLE);
if (key == todayKey) lv_obj_add_style(row, &st_row_today, 0);
// Datum-Spalte
lv_obj_t* l_date = lv_label_create(row);
lv_obj_add_style(l_date, &st_date, 0);
lv_obj_set_style_min_width(l_date, W_DATE, 0);
lv_obj_set_style_max_width(l_date, W_DATE, 0);
lv_obj_set_style_text_align(l_date, LV_TEXT_ALIGN_RIGHT, 0);
if (showDate) {
char dbuf[24]; snprintf(dbuf, sizeof(dbuf), "%s %d:", DE_WD[tmS.tm_wday], tmS.tm_mday);
lv_label_set_text(l_date, dbuf);
if (key == todayKey) lv_obj_add_style(l_date, &st_date_today, 0);
} else {
lv_label_set_text(l_date, "");
}
lv_obj_add_flag(l_date, LV_OBJ_FLAG_ADV_HITTEST);
// Farbbullet (Quelle)
lv_obj_t* bullet = lv_obj_create(row);
lv_obj_remove_style_all(bullet);
lv_obj_set_size(bullet, W_BUL, W_BUL);
lv_obj_set_style_radius(bullet, 3, 0);
lv_obj_set_style_bg_color(bullet, color_for_src(e.src), 0);
lv_obj_set_style_bg_opa(bullet, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(bullet, 0, 0);
lv_obj_add_flag(bullet, LV_OBJ_FLAG_ADV_HITTEST);
// Zeitspalte
String timeCol;
if (e.allDay) timeCol = "ganzt.";
else {
String startStr = e.segStartAtDay ? "00:00" : fmtTimeShortAdj(e.start);
String endStr = e.segEndAtDay ? "00:00" : (e.end>e.start ? fmtTimeShortAdj(e.end) : "");
timeCol = endStr.length()? (startStr + " - " + endStr) : startStr;
}
lv_obj_t* l_time = lv_label_create(row);
lv_label_set_text(l_time, timeCol.c_str());
lv_obj_add_style(l_time, &st_time, 0);
lv_obj_set_style_min_width(l_time, W_TIME, 0);
lv_obj_set_style_max_width(l_time, W_TIME, 0);
lv_label_set_long_mode(l_time, LV_LABEL_LONG_CLIP);
lv_obj_add_flag(l_time, LV_OBJ_FLAG_ADV_HITTEST);
// Titel
String titleText = (e.summary.length()? e.summary : (e.src==1? "Arbeit" : ""));
lv_obj_t* l_title = lv_label_create(row);
lv_obj_add_style(l_title, &st_title, 0);
lv_label_set_text(l_title, titleText.c_str());
lv_label_set_long_mode(l_title, LV_LABEL_LONG_CLIP);
lv_obj_set_flex_grow(l_title, 0);
lv_obj_set_width(l_title, LV_SIZE_CONTENT);
lv_obj_set_style_pad_left(l_title, 6, 0);
lv_obj_add_flag(l_title, LV_OBJ_FLAG_ADV_HITTEST);
// Spacer
lv_obj_t* spacer = lv_obj_create(row);
lv_obj_remove_style_all(spacer);
lv_obj_set_width(spacer, 1);
lv_obj_set_height(spacer, 1);
lv_obj_set_style_bg_opa(spacer, LV_OPA_TRANSP, 0);
lv_obj_set_flex_grow(spacer, 1);
lv_obj_add_flag(spacer, LV_OBJ_FLAG_ADV_HITTEST);
// Aufgaben/Bestätigungs-Check
String keyS = ack_key_for(e);
if (g_ack_required.find(keyS) != g_ack_required.end()) {
bool isTask = (g_ack_is_task.find(keyS) != g_ack_is_task.end());
bool extDone = (g_ack_external_done.find(keyS) != g_ack_external_done.end());
if (isTask) {
bool isChecked = (g_ack_keys.find(keyS) != g_ack_keys.end());
(void)create_check_square(row, isChecked, true, keyS);
} else {
(void)create_check_square(row, extDone, false, "");
}
}
lastKey = key;
shown++;
}
}
static void drawCalendarView() {
lvgl_port_lock(-1);
set_header_with_now();
// Kalender sichtbar
lv_obj_clear_flag(cal_viewport, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(cal_list, LV_OBJ_FLAG_HIDDEN);
if (data_box) lv_obj_add_flag(data_box, LV_OBJ_FLAG_HIDDEN);
if (led_box) lv_obj_add_flag(led_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_invalidate(cal_viewport);
lv_obj_invalidate(cal_list);
rebuild_cal_list();
lvgl_port_unlock();
}
/* ----- Scroll-/Gesture-Events für Kalenderliste ----- */
static void attach_cal_list_events(){
lv_obj_add_event_cb(cal_list, [](lv_event_t *e){
lv_event_code_t code = lv_event_get_code(e);
if (code == LV_EVENT_SCROLL_BEGIN) g_is_scrolling = true;
if (code == LV_EVENT_SCROLL_END) g_is_scrolling = false;
}, LV_EVENT_ALL, NULL);
}
/* ----- Kalender Backend ----- */
static inline bool removeExpiredLocallyEarlyHide() {
bool removed=false; time_t nowLocal=time(nullptr);
for (size_t i=0;i<cal_events.size();) {
const Event& ev = cal_events[i];
time_t endEff = normEnd(ev);
bool expire = ev.allDay ? (nowLocal >= endEff)
: (nowLocal >= (endEff - EARLY_HIDE_SEC));
if (expire){ cal_events.erase(cal_events.begin()+i); removed=true; }
else ++i;
}
if (removed) std::sort(cal_events.begin(), cal_events.end(), [](const Event&a,const Event&b){return a.start<b.start;});
return removed;
}
// Prüft, ob die eingestellte Weckzeit erreicht ist und schaltet dann die LEDs ein.
// NEU: Wenn LEDs bereits an sind -> heute NICHT nochmal feuern.
static void alarm_check_and_fire() {
if (!g_alarm_enabled) return;
time_t nowTs = time(nullptr);
// Zeit noch nicht per NTP gesetzt?
if (nowTs < 1600000000) return;
struct tm tmL;
localtime_r(&nowTs, &tmL);
int dayKey = (tmL.tm_year + 1900) * 10000 +
(tmL.tm_mon + 1) * 100 +
tmL.tm_mday;
// Wenn heute schon ausgelöst/übersprungen -> nix machen
if (dayKey == g_alarm_last_daykey) return;
bool timeReached =
(tmL.tm_hour > g_alarm_hour) ||
(tmL.tm_hour == g_alarm_hour && tmL.tm_min >= g_alarm_minute);
if (!timeReached) return;
// ===== NEU: Wenn LEDs schon an sind -> NICHT feuern, aber heute als erledigt markieren =====
if (led_on) {
Serial.println("[WECKER] Zeit erreicht, aber LEDs sind schon AN -> überspringe heute.");
g_alarm_last_daykey = dayKey; // heute blocken, damit nicht jede Loop wieder versucht
return;
}
// =========================================================================================
Serial.printf("[WECKER] Alarm feuert heute um %02u:%02u\n",
(unsigned)g_alarm_hour, (unsigned)g_alarm_minute);
// LEDs einschalten
led_on = true;
led_send_cmd(CMD_ON);
led_send_cmd_to_controller(CMD_ON);
// Standard-Farbe, z.B. GRÜN
led_current_color = 1; // 1 = Grün
led_send_cmd(CMD_GREEN);
led_send_cmd_to_controller(CMD_GREEN);
led_update_ui_state();
// Merken, dass der Wecker für heute schon durch ist
g_alarm_last_daykey = dayKey;
// OPTIONAL: Wenn du "One-shot" willst (wie bisher), lass das drin.
// Wenn der Wecker TÄGLICH klingeln soll, diese 3 Zeilen löschen/auskommentieren:
g_alarm_enabled = false;
alarm_save_settings();
alarm_update_toggle_button();
}
static void cal_background_update_and_draw_if_active() {
unsigned long nowMs = millis();
if (nowMs - cal_lastFetch > REFRESH_MS || cal_events.empty()) {
// Watchdog: lange Aktion fängt an
wdt_kick();
ensureWiFi();
g_ack_required.clear();
g_ack_external_done.clear();
g_ack_is_task.clear();
bool ok1=false, ok2=false;
{
String payload, newETag;
int code = httpGetICS_ETag(ICS_URL_1, etag1, payload, newETag);
Serial.printf("[CAL] ICS1 HTTP code=%d etagSend=%s\n", code, etag1.c_str());
if (code == HTTP_CODE_OK) {
Serial.printf("[CAL] ICS1 payload bytes=%u newETag=%s\n",
(unsigned)payload.length(), newETag.c_str());
} else if (code == HTTP_CODE_NOT_MODIFIED) {
Serial.println("[CAL] ICS1 not modified -> using cache");
}
// Watchdog nach dem ersten (potentiell langen) HTTP-Request
wdt_kick();
if (code==HTTP_CODE_OK && payload.length()) {
std::vector<Event> tmp;
if (parseICS(payload,1,tmp)) {
for (auto &e: tmp)
if (e.end==0)
e.end = e.allDay ? (e.start+24*3600) : (e.start+3600);
cache1.swap(tmp);
if (newETag.length()) etag1=newETag;
ok1=true;
}
} else if (code==HTTP_CODE_NOT_MODIFIED) {
ok1=true;
}
}
{
String payload, newETag;
int code = httpGetICS_ETag(ICS_URL_2, etag2, payload, newETag);
Serial.printf("[CAL] ICS2 HTTP code=%d etagSend=%s\n", code, etag2.c_str());
if (code == HTTP_CODE_OK) {
Serial.printf("[CAL] ICS2 payload bytes=%u newETag=%s\n",
(unsigned)payload.length(), newETag.c_str());
} else if (code == HTTP_CODE_NOT_MODIFIED) {
Serial.println("[CAL] ICS2 not modified -> using cache");
}
// Watchdog nach dem zweiten HTTP-Request
wdt_kick();
if (code==HTTP_CODE_OK && payload.length()) {
std::vector<Event> tmp;
if (parseICS(payload,2,tmp)) {
for (auto &e: tmp)
if (e.end==0)
e.end = e.allDay ? (e.start+24*3600) : (e.start+3600);
cache2.swap(tmp);
if (newETag.length()) etag2=newETag;
ok2=true;
}
} else if (code==HTTP_CODE_NOT_MODIFIED) {
ok2=true;
}
}
// Watchdog vor den größeren Schleifen/Sorts
wdt_kick();
std::vector<Event> merged; merged.reserve(cache1.size()+cache2.size());
merged.insert(merged.end(), cache1.begin(), cache1.end());
merged.insert(merged.end(), cache2.begin(), cache2.end());
std::vector<Event> expanded; expanded.reserve(merged.size()*2);
for (const auto& e: merged) {
time_t s=e.start; time_t eend= normEnd(e);
if (eend<=s){
Event seg=e; seg.parentAllDaySpan = e.allDay?1:0;
expanded.push_back(seg);
continue;
}
if (e.allDay) {
time_t firstDay = dayStartLocal(s);
time_t lastDay = dayStartLocal(eend - 1);
uint8_t spanDays = (uint8_t)(((lastDay - firstDay) / 86400) + 1);
for (time_t d=firstDay; d<=lastDay; d=add_days_local(d,1)) {
Event seg=e;
seg.start=d;
seg.end=nextDayStartLocal(d);
seg.allDay=true;
seg.segStartAtDay=true;
seg.segEndAtDay=true;
seg.parentAllDaySpan = spanDays;
expanded.push_back(seg);
}
continue;
}
time_t curDayStart=dayStartLocal(s), lastDayStart=dayStartLocal(eend-1);
if (curDayStart==lastDayStart){
Event seg=e;
seg.parentAllDaySpan=0;
expanded.push_back(seg);
continue;
}
{
Event seg=e;
seg.start=s;
seg.end=nextDayStartLocal(s);
if (seg.end>eend) seg.end=eend;
seg.allDay=false;
seg.segStartAtDay=false;
seg.segEndAtDay=(seg.end==nextDayStartLocal(s));
seg.parentAllDaySpan=0;
expanded.push_back(seg);
}
time_t d=nextDayStartLocal(s);
while (d<lastDayStart){
Event seg=e;
seg.start=d;
seg.end=nextDayStartLocal(d);
seg.allDay=true;
seg.segStartAtDay=true;
seg.segEndAtDay=true;
seg.parentAllDaySpan=255;
expanded.push_back(seg);
d=add_days_local(d,1);
}
{
Event seg=e;
seg.start=lastDayStart;
seg.end=eend;
seg.allDay=false;
seg.segStartAtDay=true;
seg.segEndAtDay=(seg.end==nextDayStartLocal(lastDayStart));
seg.parentAllDaySpan=0;
expanded.push_back(seg);
}
}
time_t nowLocal=time(nullptr);
std::vector<Event> filtered; filtered.reserve(expanded.size());
for (auto &e: expanded){
time_t endEff = normEnd(e);
if (e.allDay) {
if (nowLocal < endEff) filtered.push_back(e);
} else {
if (nowLocal < (endEff - EARLY_HIDE_SEC)) filtered.push_back(e);
}
}
std::sort(filtered.begin(), filtered.end(),
[](const Event&a,const Event&b){ return a.start<b.start; });
// Noch einmal Watchdog - wir sind fast fertig
wdt_kick();
if (!g_seen_built_once) {
for (const auto& e : filtered)
g_seen_event_keys.insert(ack_key_for(e));
g_seen_built_once = true;
} else {
bool firstShown = false;
time_t nowLocal2 = time(nullptr);
for (const auto& e : filtered) {
String k = ack_key_for(e);
if (g_seen_event_keys.find(k) == g_seen_event_keys.end()) {
if (e.start > nowLocal2) {
g_new_events_buf.push_back(e);
if (!firstShown) {
lvgl_port_lock(-1);
show_new_event_popup_for(e);
lvgl_port_unlock();
firstShown = true;
}
}
}
}
for (const auto& e : filtered)
g_seen_event_keys.insert(ack_key_for(e));
if (!g_new_events_buf.empty()) {
g_has_new_events = true;
lvgl_port_lock(-1);
mail_fab_update_visibility();
lvgl_port_unlock();
}
}
cal_events.swap(filtered);
cal_lastFetch=nowMs;
if (ok1 || ok2) g_lastCalFetchTs = time(nullptr);
lvgl_port_lock(-1);
set_footer_stale(!(ok1 && ok2));
lvgl_port_unlock();
if (currentView==VIEW_CAL && !g_is_scrolling)
drawCalendarView();
} else {
if (removeExpiredLocallyEarlyHide() &&
currentView == VIEW_CAL && !g_is_scrolling) {
drawCalendarView();
}
}
}
/* ---------- Wetter UI ---------- */
static lv_obj_t* kv_row(lv_obj_t* parent, const char* k, const String& v) {
lv_obj_t* row = lv_obj_create(parent);
lv_obj_remove_style_all(row);
lv_obj_set_width(row, LV_PCT(100));
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_column(row, 6, 0);
lv_obj_set_style_pad_top(row, 0, 0);
lv_obj_set_style_pad_bottom(row, 0, 0);
lv_obj_t* lk = lv_label_create(row);
lv_obj_add_style(lk, &st_kv_key, 0);
lv_label_set_text(lk, k);
lv_obj_add_flag(lk, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_t* lvv = lv_label_create(row);
lv_obj_add_style(lvv, &st_kv_val, 0);
lv_label_set_text(lvv, v.c_str());
lv_obj_set_flex_grow(lvv, 1);
lv_obj_set_style_text_align(lvv, LV_TEXT_ALIGN_RIGHT, 0);
lv_label_set_long_mode(lvv, LV_LABEL_LONG_CLIP);
lv_obj_add_flag(lvv, LV_OBJ_FLAG_ADV_HITTEST);
return row;
}
static void section_title(lv_obj_t* parent, const char* txt) {
lv_obj_t* t = lv_label_create(parent);
lv_obj_add_style(t, &st_section, 0);
lv_label_set_text(t, txt);
lv_obj_add_flag(t, LV_OBJ_FLAG_ADV_HITTEST);
}
static void fill_day_block(lv_obj_t* parent, const DayWeather& d) {
(void)kv_row(parent, "Temp", String((int)lroundf(std::min(d.tmin,d.tmax)))+" °C / "+String((int)lroundf(std::max(d.tmin,d.tmax)))+" °C");
(void)kv_row(parent, "Regen", String(d.precip_sum,1)+" L ("+String(d.precip_prob,0)+" %)");
(void)kv_row(parent, "Regenstd", isnan(d.precip_hours)? String("--") : String(d.precip_hours,0));
(void)kv_row(parent, "UV max", isnan(d.uv_max)? String("--") : String(d.uv_max,0));
(void)kv_row(parent, "Aufgang", d.sunrise.length()? d.sunrise : String("--:--"));
(void)kv_row(parent, "Untergang",d.sunset.length()? d.sunset : String("--:--"));
}
static const char* weekday3_from_iso(const String& ymd){
int y = ymd.substring(0,4).toInt();
int M = ymd.substring(5,7).toInt();
int d = ymd.substring(8,10).toInt();
struct tm t = {};
t.tm_year = y - 1900; t.tm_mon = M - 1; t.tm_mday = d; t.tm_isdst = -1;
time_t ts = mktime(&t);
struct tm out; localtime_r(&ts, &out);
static const char* WD[7] = {"So","Mo","Di","Mi","Do","Fr","Sa"};
return WD[out.tm_wday];
}
static void drawDataView() {
lvgl_port_lock(-1);
set_header_with_now();
if (cal_viewport) lv_obj_add_flag(cal_viewport, LV_OBJ_FLAG_HIDDEN);
if (cal_list) lv_obj_add_flag(cal_list, LV_OBJ_FLAG_HIDDEN);
if (led_box) lv_obj_add_flag(led_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(data_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_clean(data_box);
lv_obj_remove_style_all(data_box);
lv_obj_set_size(data_box, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_bg_color(data_box, lv_color_white(), 0);
lv_obj_set_style_bg_opa(data_box, LV_OPA_COVER, 0);
lv_obj_set_style_clip_corner(data_box, true, 0);
lv_obj_set_flex_flow(data_box, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_left(data_box, LEFT_INSET_PX, 0);
lv_obj_set_style_pad_right(data_box, 14, 0);
lv_obj_set_style_pad_top(data_box, 10, 0);
lv_obj_set_style_pad_bottom(data_box, 10, 0);
lv_obj_set_style_pad_row(data_box, 10, 0);
// Karte oben: aktuelle Werte
lv_obj_t *card = lv_obj_create(data_box);
lv_obj_remove_style_all(card);
lv_obj_add_style(card, &st_card, 0);
lv_obj_set_width(card, LV_PCT(100));
lv_obj_set_flex_flow(card, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_row(card, 2, 0);
lv_obj_set_style_pad_column(card, 12, 0);
lv_obj_t *colL = lv_obj_create(card);
lv_obj_remove_style_all(colL);
lv_obj_set_flex_flow(colL, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_bg_opa(colL, LV_OPA_TRANSP, 0);
lv_obj_t *lblTemp = lv_label_create(colL);
String tempLine = isnan(currentTemp) ? "-- °C" : (String((int)lroundf(currentTemp)) + " °C");
lv_label_set_text(lblTemp, tempLine.c_str());
lv_obj_add_style(lblTemp, &st_bigtemp, 0);
lv_obj_add_flag(lblTemp, LV_OBJ_FLAG_ADV_HITTEST);
const char* cond = cond_from(currentCloud, wToday.precip_prob);
lv_obj_t *lblCond = lv_label_create(colL);
lv_obj_add_style(lblCond, &st_kv_val, 0);
lv_label_set_text(lblCond, cond);
lv_obj_add_flag(lblCond, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_t *lblHL = lv_label_create(colL);
lv_obj_add_style(lblHL, &st_kv_val, 0);
String hl = String("H ") + fmt(wToday.tmax,0,"°") + " N " + fmt(wToday.tmin,0,"°");
lv_label_set_text(lblHL, hl.c_str());
lv_obj_add_flag(lblHL, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_t *colR = lv_obj_create(card);
lv_obj_remove_style_all(colR);
lv_obj_set_flex_flow(colR, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_bg_opa(colR, LV_OPA_TRANSP, 0);
(void)kv_row(colR, "Gef.:", isnan(currentApp) ? String("-- °C") : String(currentApp,1) + " °C");
(void)kv_row(colR, "Wind", isnan(currentWind) ? String("-- km/h") : String((int)lroundf(currentWind))+" km/h");
(void)kv_row(colR, "Feuchte", isnan(currentHum) ? String("-- %") : String((int)lroundf(currentHum))+" %");
(void)kv_row(colR, "Wolken", isnan(currentCloud)? String("-- %") : String((int)lroundf(currentCloud))+" %");
// 5-Tage Chips
lv_obj_t *row5 = lv_obj_create(data_box);
lv_obj_remove_style_all(row5);
lv_obj_set_width(row5, LV_PCT(100));
lv_obj_set_flex_flow(row5, LV_FLEX_FLOW_ROW);
lv_obj_set_style_bg_opa(row5, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_column(row5, 8, 0);
lv_obj_set_flex_align(row5, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START);
for (int i = 0; i < wDaysCount; ++i) {
const DayWeather &d = wDays[i];
lv_obj_t *chip = lv_obj_create(row5);
lv_obj_remove_style_all(chip);
lv_obj_add_style(chip, &st_day_chip, 0);
lv_obj_set_width(chip, 140);
lv_obj_set_flex_flow(chip, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(chip, 4, 0);
lv_obj_t *wd = lv_label_create(chip);
lv_obj_add_style(wd, &st_day_text_small, 0);
lv_label_set_text(wd, weekday3_from_iso(d.date));
lv_obj_set_style_text_align(wd, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_add_flag(wd, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_t *ico = lv_label_create(chip);
lv_obj_add_style(ico, &st_icon, 0);
lv_label_set_text(ico, icon_text(currentCloud, d.precip_prob));
lv_obj_set_style_text_align(ico, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_add_flag(ico, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_t *hlbl = lv_label_create(chip);
lv_obj_add_style(hlbl, &st_day_text_small, 0);
char tline[24];
snprintf(tline, sizeof(tline), "%d° / %d°", (int)lroundf(d.tmax), (int)lroundf(d.tmin));
lv_label_set_text(hlbl, tline);
lv_obj_set_style_text_align(hlbl, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_add_flag(hlbl, LV_OBJ_FLAG_ADV_HITTEST);
if (!isnan(d.precip_prob)) {
lv_obj_t *pp = lv_label_create(chip);
lv_obj_add_style(pp, &st_day_text_small, 0);
char ptxt[8]; snprintf(ptxt, sizeof(ptxt), "%d%%", (int)lroundf(d.precip_prob));
lv_label_set_text(pp, ptxt);
lv_obj_set_style_text_align(pp, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_add_flag(pp, LV_OBJ_FLAG_ADV_HITTEST);
}
}
// nächste 8 Stunden
if (next8_count > 0) {
lv_obj_t *rowh = lv_obj_create(data_box);
lv_obj_remove_style_all(rowh);
lv_obj_set_width(rowh, LV_PCT(100));
lv_obj_set_flex_flow(rowh, LV_FLEX_FLOW_ROW);
lv_obj_set_style_bg_opa(rowh, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_column(rowh, 6, 0);
lv_obj_set_flex_align(rowh, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START);
for (int i=0;i<next8_count;i++){
lv_obj_t *hc = lv_obj_create(rowh);
lv_obj_remove_style_all(hc);
lv_obj_add_style(hc, &st_chip_hour, 0);
lv_obj_set_width(hc, 80);
lv_obj_set_flex_flow(hc, LV_FLEX_FLOW_COLUMN);
lv_obj_t *t = lv_label_create(hc);
lv_obj_add_style(t, &st_day_text_small, 0);
lv_label_set_text(t, next8_time[i].c_str());
lv_obj_set_style_text_align(t, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_add_flag(t, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_t *tv = lv_label_create(hc);
lv_obj_add_style(tv, &st_day_text_small, 0);
char v[8]; snprintf(v, sizeof(v), "%d°", (int)lroundf(next8_temp[i]));
lv_label_set_text(tv, v);
lv_obj_set_style_text_align(tv, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_add_flag(tv, LV_OBJ_FLAG_ADV_HITTEST);
}
}
// Detailblöcke Heute / Morgen
lv_obj_t *detailRow = lv_obj_create(data_box);
lv_obj_remove_style_all(detailRow);
lv_obj_set_width(detailRow, LV_PCT(100));
lv_obj_set_flex_flow(detailRow, LV_FLEX_FLOW_ROW);
lv_obj_set_style_bg_opa(detailRow, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_column(detailRow, 12, 0);
/*lv_obj_t *colToday = lv_obj_create(detailRow);
lv_obj_remove_style_all(colToday);
lv_obj_set_width(colToday, LV_PCT(50));
lv_obj_set_flex_flow(colToday, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_bg_opa(colToday, LV_OPA_TRANSP, 0);
lv_obj_t* t1 = lv_label_create(colToday);
lv_obj_add_style(t1, &st_section, 0);
//lv_label_set_text(t1, "Heute");
lv_obj_add_flag(t1, LV_OBJ_FLAG_ADV_HITTEST);
//fill_day_block(colToday, wToday);
lv_obj_t *colTom = lv_obj_create(detailRow);
lv_obj_remove_style_all(colTom);
lv_obj_set_width(colTom, LV_PCT(50));
lv_obj_set_flex_flow(colTom, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_bg_opa(colTom, LV_OPA_TRANSP, 0);
lv_obj_t* t2 = lv_label_create(colTom);
lv_obj_add_style(t2, &st_section, 0);
//lv_label_set_text(t2, "Morgen");
lv_obj_add_flag(t2, LV_OBJ_FLAG_ADV_HITTEST);
//fill_day_block(colTom, wTomorrow);
*/
lvgl_port_unlock();
}
/* ===================== LED-View / Timer ===================== */
// Timerwert lokal setzen (auch vom anderen Controller)
static void led_set_timer_minutes(uint16_t mins, bool fromRemote) {
(void)fromRemote;
led_timer_minutes = mins;
led_timer_minutes_last = mins;
if (led_timer_slider) {
lv_slider_set_value(led_timer_slider, mins, LV_ANIM_OFF);
}
if (led_timer_label) {
char buf[32];
snprintf(buf, sizeof(buf), "Timer: %u min", (unsigned)mins);
lv_label_set_text(led_timer_label, buf);
}
}
static void led_update_ui_state() {
if (!led_toggle_btn || !led_toggle_label) return;
lv_label_set_text(led_toggle_label, led_on ? "LED AN" : "LED AUS");
lv_color_t bg = led_on ? lv_palette_main(LV_PALETTE_GREEN) : lv_palette_main(LV_PALETTE_GREY);
lv_obj_set_style_bg_color(led_toggle_btn, bg, 0);
lv_obj_set_style_bg_opa(led_toggle_btn, LV_OPA_COVER, 0);
for (int i=0;i<4;i++) {
if (!led_color_btns[i]) continue;
bool active = (led_on && (led_current_color == (uint8_t)(i+1)));
lv_obj_set_style_border_width(led_color_btns[i], active ? 4 : 0, 0);
lv_obj_set_style_border_color(led_color_btns[i], lv_color_black(), 0);
}
}
/* ========== Wecker UI Helpers ========== */
static void alarm_update_time_label() {
if (!alarm_time_label) return;
char buf[16];
snprintf(buf, sizeof(buf), "%02u:%02u",
(unsigned)g_alarm_hour,
(unsigned)g_alarm_minute);
lv_label_set_text(alarm_time_label, buf);
}
static void alarm_update_toggle_button() {
if (!alarm_toggle_btn || !alarm_toggle_label) return;
lv_label_set_text(alarm_toggle_label, g_alarm_enabled ? "Wecker AN" : "Wecker AUS");
lv_color_t bg = g_alarm_enabled ? lv_palette_main(LV_PALETTE_GREEN)
: lv_palette_main(LV_PALETTE_GREY);
lv_obj_set_style_bg_color(alarm_toggle_btn, bg, 0);
lv_obj_set_style_bg_opa(alarm_toggle_btn, LV_OPA_COVER, 0);
}
static void alarm_adjust_time(int dHour, int dMin) {
int h = (int)g_alarm_hour + dHour;
int m = (int)g_alarm_minute + dMin;
while (m < 0) { m += 60; h--; }
while (m > 59) { m -= 60; h++; }
while (h < 0) h += 24;
while (h > 23) h -= 24;
g_alarm_hour = (uint8_t)h;
g_alarm_minute = (uint8_t)m;
if (g_alarm_enabled) alarm_arm_next_occurrence_from_now();
// WICHTIG: nach Zeitänderung heute wieder erlauben
g_alarm_last_daykey = -1;
alarm_update_time_label();
alarm_save_settings();
}
/* ---- Callbacks für Buttons ---- */
static void alarm_toggle_btn_cb(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_CLICKED) return;
g_alarm_enabled = !g_alarm_enabled;
if (g_alarm_enabled) {
alarm_arm_next_occurrence_from_now(); // <-- WICHTIG
}
alarm_update_toggle_button();
alarm_save_settings();
}
static void alarm_inc_hour_cb(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_CLICKED) return;
alarm_adjust_time(+1, 0);
}
static void alarm_dec_hour_cb(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_CLICKED) return;
alarm_adjust_time(-1, 0);
}
// Minuten in 10-Minuten-Schritten
static void alarm_inc_min_cb(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_CLICKED) return;
alarm_adjust_time(0, +10);
}
static void alarm_dec_min_cb(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_CLICKED) return;
alarm_adjust_time(0, -10);
}
// Slider-Event: Timer einstellen + Swipe blockieren während Drag
static void led_timer_slider_event_cb(lv_event_t* e) {
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t* slider = lv_event_get_target(e);
if (!slider) return;
if (code == LV_EVENT_PRESSED) {
g_block_swipe = true;
}
if (code == LV_EVENT_RELEASED || code == LV_EVENT_PRESS_LOST) {
g_block_swipe = false;
}
int32_t val = lv_slider_get_value(slider);
if (val < 0) val = 0;
uint16_t mins = (uint16_t)val;
led_timer_minutes = mins;
if (led_timer_label) {
char buf[32];
snprintf(buf, sizeof(buf), "Timer: %ld min", (long)val);
lv_label_set_text(led_timer_label, buf);
}
if (code == LV_EVENT_RELEASED || code == LV_EVENT_SHORT_CLICKED) {
if (mins != led_timer_minutes_last) {
led_timer_minutes_last = mins;
led_send_timer_set_minutes(mins);
}
}
}
static void led_toggle_btn_event_cb(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_CLICKED) return;
led_on = !led_on;
uint8_t cmd = led_on ? CMD_ON : CMD_OFF;
led_send_cmd(cmd);
led_send_cmd_to_controller(cmd);
led_update_ui_state();
}
static void led_color_btn_event_cb(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_CLICKED) return;
int idx = (int)(uintptr_t)lv_event_get_user_data(e);
uint8_t cmd = CMD_GREEN;
switch (idx) {
case 0: cmd = CMD_GREEN; break;
case 1: cmd = CMD_BLUE; break;
case 2: cmd = CMD_YELLOW; break;
case 3: cmd = CMD_RED; break;
}
if (!led_on) {
led_on = true;
led_send_cmd(CMD_ON);
led_send_cmd_to_controller(CMD_ON);
}
led_current_color = (uint8_t)(idx+1);
led_send_cmd(cmd);
led_send_cmd_to_controller(cmd);
led_update_ui_state();
}
static void led_build_ui() {
if (!led_box) return;
if (led_toggle_btn) return;
lv_obj_remove_style_all(led_box);
lv_obj_set_size(led_box, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_bg_color(led_box, lv_color_white(), 0);
lv_obj_set_style_bg_opa(led_box, LV_OPA_COVER, 0);
lv_obj_set_style_clip_corner(led_box, true, 0);
// Kompaktere Abstände
lv_obj_set_flex_flow(led_box, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_left(led_box, LEFT_INSET_PX, 0);
lv_obj_set_style_pad_right(led_box, 12, 0); // war 20
lv_obj_set_style_pad_top(led_box, 6, 0); // war 10
lv_obj_set_style_pad_bottom(led_box, 6, 0); // war 10
lv_obj_set_style_pad_row(led_box, 6, 0); // war 8
// Buttons etwas flacher
const int MAIN_BTN_W = 230;
const int MAIN_BTN_H = 52; // war 60
/* ===== TOP: LED (links) + Wecker (rechts) ===== */
lv_obj_t* top_row = lv_obj_create(led_box);
lv_obj_remove_style_all(top_row);
lv_obj_set_width(top_row, LV_PCT(100));
lv_obj_set_flex_flow(top_row, LV_FLEX_FLOW_ROW);
lv_obj_set_style_bg_opa(top_row, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_column(top_row, 10, 0);
lv_obj_set_style_pad_row(top_row, 0, 0);
// Spalten sollen sich den Platz teilen (statt fixe 330px)
lv_obj_t* led_col = lv_obj_create(top_row);
lv_obj_remove_style_all(led_col);
lv_obj_set_width(led_col, 0);
lv_obj_set_flex_grow(led_col, 1);
lv_obj_set_flex_flow(led_col, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_bg_opa(led_col, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_row(led_col, 4, 0);
lv_obj_t* alarm_col = lv_obj_create(top_row);
lv_obj_remove_style_all(alarm_col);
lv_obj_set_width(alarm_col, 0);
lv_obj_set_flex_grow(alarm_col, 1);
lv_obj_set_flex_flow(alarm_col, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_bg_opa(alarm_col, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_row(alarm_col, 4, 0);
// ----- LED Titel + Toggle
lv_obj_t* title_led = lv_label_create(led_col);
lv_obj_add_style(title_led, &st_section, 0);
lv_label_set_text(title_led, "LED Steuerung");
lv_obj_add_flag(title_led, LV_OBJ_FLAG_ADV_HITTEST);
led_toggle_btn = lv_btn_create(led_col);
lv_obj_remove_style_all(led_toggle_btn);
lv_obj_set_width(led_toggle_btn, MAIN_BTN_W);
lv_obj_set_height(led_toggle_btn, MAIN_BTN_H);
lv_obj_set_style_radius(led_toggle_btn, 14, 0);
lv_obj_set_style_bg_color(led_toggle_btn, lv_palette_main(LV_PALETTE_GREY), 0);
lv_obj_set_style_bg_opa(led_toggle_btn, LV_OPA_COVER, 0);
lv_obj_set_style_shadow_width(led_toggle_btn, 6, 0);
lv_obj_set_style_shadow_opa(led_toggle_btn, LV_OPA_30, 0);
lv_obj_set_style_shadow_ofs_y(led_toggle_btn, 2, 0);
lv_obj_add_event_cb(led_toggle_btn, led_toggle_btn_event_cb, LV_EVENT_CLICKED, nullptr);
led_toggle_label = lv_label_create(led_toggle_btn);
lv_obj_set_style_text_color(led_toggle_label, lv_color_white(), 0);
lv_obj_set_style_text_font(led_toggle_label, FONT_24, 0);
lv_label_set_text(led_toggle_label, "LED AUS");
lv_obj_center(led_toggle_label);
lv_obj_add_flag(led_toggle_label, LV_OBJ_FLAG_ADV_HITTEST);
// ----- Wecker Titel + Toggle
lv_obj_t* alarm_title = lv_label_create(alarm_col);
lv_obj_add_style(alarm_title, &st_section, 0);
lv_label_set_text(alarm_title, "Wecker");
lv_obj_add_flag(alarm_title, LV_OBJ_FLAG_ADV_HITTEST);
alarm_toggle_btn = lv_btn_create(alarm_col);
lv_obj_remove_style_all(alarm_toggle_btn);
lv_obj_set_width(alarm_toggle_btn, MAIN_BTN_W);
lv_obj_set_height(alarm_toggle_btn, MAIN_BTN_H);
lv_obj_set_style_radius(alarm_toggle_btn, 14, 0);
lv_obj_set_style_bg_color(alarm_toggle_btn, lv_palette_main(LV_PALETTE_GREY), 0);
lv_obj_set_style_bg_opa(alarm_toggle_btn, LV_OPA_COVER, 0);
lv_obj_set_style_shadow_width(alarm_toggle_btn, 6, 0);
lv_obj_set_style_shadow_opa(alarm_toggle_btn, LV_OPA_20, 0);
lv_obj_set_style_shadow_ofs_y(alarm_toggle_btn, 2, 0);
lv_obj_add_event_cb(alarm_toggle_btn, alarm_toggle_btn_cb, LV_EVENT_CLICKED, nullptr);
alarm_toggle_label = lv_label_create(alarm_toggle_btn);
lv_obj_set_style_text_color(alarm_toggle_label, lv_color_white(), 0);
lv_obj_set_style_text_font(alarm_toggle_label, FONT_24, 0);
lv_label_set_text(alarm_toggle_label, "Wecker AUS");
lv_obj_center(alarm_toggle_label);
lv_obj_add_flag(alarm_toggle_label, LV_OBJ_FLAG_ADV_HITTEST);
// Zeit + Buttons kompakter
lv_obj_t* alarm_time_row = lv_obj_create(alarm_col);
lv_obj_remove_style_all(alarm_time_row);
lv_obj_set_width(alarm_time_row, LV_PCT(100));
lv_obj_set_flex_flow(alarm_time_row, LV_FLEX_FLOW_ROW);
lv_obj_set_style_bg_opa(alarm_time_row, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_column(alarm_time_row, 4, 0);
lv_obj_t* alarm_label_txt = lv_label_create(alarm_time_row);
lv_obj_add_style(alarm_label_txt, &st_day_text_small, 0);
lv_label_set_text(alarm_label_txt, "Zeit:");
lv_obj_add_flag(alarm_label_txt, LV_OBJ_FLAG_ADV_HITTEST);
alarm_time_label = lv_label_create(alarm_time_row);
lv_obj_add_style(alarm_time_label, &st_day_text_small, 0);
lv_label_set_text(alarm_time_label, "07:00");
lv_obj_add_flag(alarm_time_label, LV_OBJ_FLAG_ADV_HITTEST);
auto make_small_btn = [&](const char* txt, lv_event_cb_t cb)->lv_obj_t* {
lv_obj_t* b = lv_btn_create(alarm_time_row);
lv_obj_remove_style_all(b);
lv_obj_set_size(b, 44, 34); // kleiner als vorher
lv_obj_set_style_radius(b, 10, 0);
lv_obj_set_style_bg_color(b, lv_palette_main(LV_PALETTE_BLUE), 0);
lv_obj_set_style_bg_opa(b, LV_OPA_COVER, 0);
lv_obj_set_style_shadow_width(b, 2, 0);
lv_obj_set_style_shadow_opa(b, LV_OPA_20, 0);
lv_obj_set_style_shadow_ofs_y(b, 1, 0);
lv_obj_add_event_cb(b, cb, LV_EVENT_CLICKED, nullptr);
lv_obj_t* l = lv_label_create(b);
lv_obj_set_style_text_color(l, lv_color_white(), 0);
lv_obj_set_style_text_font(l, FONT_24, 0);
lv_label_set_text(l, txt);
lv_obj_center(l);
lv_obj_add_flag(l, LV_OBJ_FLAG_ADV_HITTEST);
return b;
};
(void)make_small_btn("-H", alarm_dec_hour_cb);
(void)make_small_btn("+H", alarm_inc_hour_cb);
(void)make_small_btn("-M", alarm_dec_min_cb);
(void)make_small_btn("+M", alarm_inc_min_cb);
/* ===== Farben: 2×2 Grid via Wrap ===== */
lv_obj_t* color_wrap = lv_obj_create(led_box);
lv_obj_remove_style_all(color_wrap);
lv_obj_set_width(color_wrap, LV_PCT(100));
lv_obj_set_style_bg_opa(color_wrap, LV_OPA_TRANSP, 0);
// Wrap sorgt für 2 Zeilen statt 1×4
lv_obj_set_flex_flow(color_wrap, LV_FLEX_FLOW_ROW_WRAP);
lv_obj_set_style_pad_column(color_wrap, 10, 0);
lv_obj_set_style_pad_row(color_wrap, 8, 0);
lv_obj_set_flex_align(color_wrap,
LV_FLEX_ALIGN_SPACE_EVENLY,
LV_FLEX_ALIGN_CENTER,
LV_FLEX_ALIGN_START);
const char* names[4] = {"Gruen","Blau","Gelb","Rot"};
lv_color_t cols[4] = {
lv_palette_main(LV_PALETTE_GREEN),
lv_palette_main(LV_PALETTE_BLUE),
lv_palette_main(LV_PALETTE_YELLOW),
lv_palette_main(LV_PALETTE_RED)
};
// Buttons flacher -> passen sicher
const int COLOR_W = 160;
const int COLOR_H = 68; // war 90
for (int i = 0; i < 4; i++) {
lv_obj_t* b = lv_btn_create(color_wrap);
lv_obj_remove_style_all(b);
lv_obj_set_size(b, COLOR_W, COLOR_H);
lv_obj_set_style_radius(b, 16, 0);
lv_obj_set_style_bg_color(b, cols[i], 0);
lv_obj_set_style_bg_opa(b, LV_OPA_COVER, 0);
lv_obj_set_style_shadow_width(b, 5, 0);
lv_obj_set_style_shadow_opa(b, LV_OPA_20, 0);
lv_obj_set_style_shadow_ofs_y(b, 2, 0);
lv_obj_add_event_cb(b, led_color_btn_event_cb, LV_EVENT_CLICKED, (void*)(uintptr_t)i);
lv_obj_t* lbl = lv_label_create(b);
lv_obj_set_style_text_color(lbl, lv_color_white(), 0);
lv_obj_set_style_text_font(lbl, FONT_24, 0);
lv_label_set_text(lbl, names[i]);
lv_obj_center(lbl);
lv_obj_add_flag(lbl, LV_OBJ_FLAG_ADV_HITTEST);
led_color_btns[i] = b;
}
/* ===== Timer (bündig, nicht zu weit rechts) ===== */
lv_obj_t* timer_row = lv_obj_create(led_box);
lv_obj_remove_style_all(timer_row);
lv_obj_set_width(timer_row, LV_PCT(100));
lv_obj_set_style_bg_opa(timer_row, LV_OPA_TRANSP, 0);
lv_obj_set_flex_flow(timer_row, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(timer_row, 4, 0);
// extra: Timer container ohne zusätzliche Innenpaddings
lv_obj_set_style_pad_left(timer_row, 0, 0);
lv_obj_set_style_pad_right(timer_row, 0, 0);
led_timer_label = lv_label_create(timer_row);
lv_obj_add_style(led_timer_label, &st_day_text_small, 0);
{
char buf[32];
snprintf(buf, sizeof(buf), "Timer: %u min", (unsigned)led_timer_minutes);
lv_label_set_text(led_timer_label, buf);
}
lv_obj_add_flag(led_timer_label, LV_OBJ_FLAG_ADV_HITTEST);
led_timer_slider = lv_slider_create(timer_row);
lv_slider_set_range(led_timer_slider, 5, 180);
lv_slider_set_value(led_timer_slider, led_timer_minutes, LV_ANIM_OFF);
// Slider minimal schmaler + linksbündiger Eindruck
lv_obj_set_width(led_timer_slider, LV_PCT(96));
lv_obj_set_style_translate_x(led_timer_slider, -6, 0);
lv_obj_add_event_cb(led_timer_slider, led_timer_slider_event_cb, LV_EVENT_ALL, nullptr);
lv_obj_clear_flag(led_timer_slider, LV_OBJ_FLAG_GESTURE_BUBBLE);
led_update_ui_state();
alarm_update_time_label();
alarm_update_toggle_button();
}
static void drawLEDView() {
lvgl_port_lock(-1);
set_header_with_now();
lv_obj_add_flag(led_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scroll_dir(led_box, LV_DIR_VER);
lv_obj_set_scrollbar_mode(led_box, LV_SCROLLBAR_MODE_OFF);
if (led_box) {
lv_obj_clear_flag(led_box, LV_OBJ_FLAG_HIDDEN);
led_build_ui();
led_update_ui_state();
}
lvgl_port_unlock();
}
/* ====================== ESP-NOW-Implementierung ====================== */
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
void led_OnDataSent(const wifi_tx_info_t *info, esp_now_send_status_t status) {
(void)info;
g_lastSendStatus = status;
g_lastSendDone = true;
Serial.print("[LED-ESP-NOW] Send callback: ");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Erfolgreich" : "Fehlgeschlagen");
}
#else
void led_OnDataSent(const uint8_t *mac, esp_now_send_status_t status) {
(void)mac;
g_lastSendStatus = status;
g_lastSendDone = true;
Serial.print("[LED-ESP-NOW] Send callback: ");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Erfolgreich" : "Fehlgeschlagen");
}
#endif
bool led_addPeer(const uint8_t mac[6], uint8_t channel=1, bool encrypt=false) {
esp_now_peer_info_t p;
memset(&p, 0, sizeof(p));
memcpy(p.peer_addr, mac, 6);
p.channel = channel;
p.encrypt = encrypt;
if (esp_now_is_peer_exist(mac)) {
esp_now_del_peer(mac);
}
return esp_now_add_peer(&p) == ESP_OK;
}
static bool led_send_packet_reliable(const uint8_t mac[6], const void* data, size_t len) {
for (int attempt = 0; attempt < MAX_SEND_RETRIES; ++attempt) {
g_lastSendDone = false;
g_lastSendStatus = ESP_NOW_SEND_FAIL;
esp_err_t res = esp_now_send(mac, (const uint8_t*)data, len);
if (res != ESP_OK) {
Serial.printf("[LED-ESP-NOW] esp_now_send Fehler (res=%d), Versuch %d\n", (int)res, attempt+1);
delay(5);
continue;
}
unsigned long t0 = millis();
while (!g_lastSendDone && (millis() - t0) < SEND_TIMEOUT_MS) {
delay(1);
}
if (!g_lastSendDone) {
Serial.printf("[LED-ESP-NOW] Timeout beim Senden, Versuch %d\n", attempt+1);
continue;
}
if (g_lastSendStatus == ESP_NOW_SEND_SUCCESS) {
return true;
} else {
Serial.printf("[LED-ESP-NOW] Send-Status FAIL, Versuch %d\n", attempt+1);
}
}
Serial.println("[LED-ESP-NOW] Alle Sendeversuche fehlgeschlagen");
return false;
}
static void led_send_cmd(uint8_t cmd) {
esp_cmd_t c;
c.cmd = cmd;
for (size_t i = 0; i < peersA_count; i++) {
if (!peersA[i]) continue;
// 1. Send immer
bool ok1 = led_send_packet_reliable(peersA[i], &c, sizeof(c));
Serial.printf("[LED-ESP-NOW] Cmd %u an Peer %u: %s\n",
cmd, (unsigned)i, ok1 ? "OK" : "FEHLER");
// NUR macA3 (Peer 2) IMMER ein zweites Mal schicken
if (i == 2) { // peersA[2] == macA3
delay(15); // kleiner Abstand, damit Funk/Empfänger Luft hat
wdt_kick();
bool ok2 = led_send_packet_reliable(peersA[i], &c, sizeof(c));
Serial.printf("[LED-ESP-NOW] Cmd %u an Peer %u (DOPPELT): %s\n",
cmd, (unsigned)i, ok2 ? "OK" : "FEHLER");
}
}
}
static void led_send_cmd_to_controller(uint8_t cmd) {
esp_cmd_t c;
c.cmd = cmd;
bool ok = led_send_packet_reliable(macCtrlOther, &c, sizeof(c));
Serial.printf("[LED-ESP-NOW] Cmd %u an Controller: %s\n",
cmd, ok ? "OK" : "FEHLER");
}
static void led_send_timer_set_minutes(uint16_t mins) {
uint8_t buf[3];
buf[0] = CMD_TIMER_SET_MINUTES;
buf[1] = (uint8_t)(mins & 0xFF);
buf[2] = (uint8_t)(mins >> 8);
bool ok = led_send_packet_reliable(macCtrlOther, buf, sizeof(buf));
Serial.printf("[LED-ESP-NOW] Timer %u min an Controller: %s\n",
(unsigned)mins, ok ? "OK" : "FEHLER");
}
static void led_handle_remote_cmd(uint8_t cmd) {
switch (cmd) {
case CMD_ON:
led_on = true;
break;
case CMD_OFF:
led_on = false;
break;
case CMD_GREEN:
led_on = true;
led_current_color = 1;
break;
case CMD_BLUE:
led_on = true;
led_current_color = 2;
break;
case CMD_YELLOW:
led_on = true;
led_current_color = 3;
break;
case CMD_RED:
led_on = true;
led_current_color = 4;
break;
case CMD_STATE_QUERY:
return;
default:
return;
}
led_update_ui_state();
}
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
static void led_OnDataRecv(const esp_now_recv_info_t *info, const uint8_t *data, int len) {
(void)info;
if (len < 1) return;
uint8_t cmd = data[0];
if (cmd == CMD_TIMER_SET_MINUTES && len >= 3) {
uint16_t mins = (uint16_t)data[1] | ((uint16_t)data[2] << 8);
led_set_timer_minutes(mins, true);
return;
}
if (len >= (int)sizeof(esp_cmd_t)) {
const esp_cmd_t* p = (const esp_cmd_t*)data;
led_handle_remote_cmd(p->cmd);
}
}
#else
static void led_OnDataRecv(const uint8_t *mac, const uint8_t *data, int len) {
(void)mac;
if (len < 1) return;
uint8_t cmd = data[0];
if (cmd == CMD_TIMER_SET_MINUTES && len >= 3) {
uint16_t mins = (uint16_t)data[1] | ((uint16_t)data[2] << 8);
led_set_timer_minutes(mins, true);
return;
}
if (len >= (int)sizeof(esp_cmd_t)) {
const esp_cmd_t* p = (const esp_cmd_t*)data;
led_handle_remote_cmd(p->cmd);
}
}
#endif
static void led_request_state_from_controller() {
Serial.println("[LED-ESP-NOW] Sende Status-Abfrage an Timer-Controller");
led_send_cmd_to_controller(CMD_STATE_QUERY);
}
static void led_init_espnow() {
if (esp_now_init() != ESP_OK) {
Serial.println("[LED-ESP-NOW] Init Fehler");
return;
}
esp_now_register_send_cb(led_OnDataSent);
esp_now_register_recv_cb(led_OnDataRecv);
for (size_t i=0; i<peersA_count; i++) {
if (peersA[i] && !led_addPeer(peersA[i], 1)) {
Serial.println("[LED-ESP-NOW] Peer A Fehler");
}
}
if (!led_addPeer(macCtrlOther, 1)) {
Serial.println("[LED-ESP-NOW] Controller-Peer Fehler");
}
Serial.println("[LED-ESP-NOW] Initialisiert");
led_request_state_from_controller();
}
/* ===================== SETUP / LOOP ===================== */
void setup() {
Serial.begin(115200);
Serial.println("Kalender+Wetter+LED (LVGL, ohne Chart) start");
// ---- Task Watchdog korrekt initialisieren & loopTask registrieren ----
// ---- Task Watchdog korrekt initialisieren & loopTask registrieren ----
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
esp_task_wdt_config_t cfg = {
.timeout_ms = (uint32_t)(WDT_TIMEOUT_SECONDS * 1000),
.idle_core_mask = (1 << portNUM_PROCESSORS) - 1,
.trigger_panic = false
};
esp_err_t wres = esp_task_wdt_init(&cfg);
// Wenn schon initialisiert -> neu konfigurieren
if (wres == ESP_ERR_INVALID_STATE) {
Serial.println("[WDT] already initialized -> reconfigure");
esp_task_wdt_reconfigure(&cfg); // <-- WICHTIG
wres = ESP_OK;
}
#else
// Alte IDF Version (Arduino ESP32 Core 2.x)
esp_err_t wres = esp_task_wdt_init(WDT_TIMEOUT_SECONDS, false);
#endif
if (wres == ESP_OK) {
// loopTask registrieren (nur wenn noch nicht registriert)
esp_task_wdt_add(NULL);
g_wdt_inited = true;
Serial.println("[WDT] initialized OK");
} else {
Serial.printf("[WDT] init failed: %d\n", (int)wres);
g_wdt_inited = false;
}
pinMode(PIR_PIN, INPUT);
g_lastMotionMs = millis();
g_screenOff = false;
g_board = new Board();
g_board->init();
#if defined(LVGL_PORT_AVOID_TEARING_MODE) || defined(LVGL_PORT_AVOID_TEAR)
auto lcd = g_board->getLCD();
lcd->configFrameBufferNumber(3);
#if ESP_PANEL_DRIVERS_BUS_ENABLE_RGB && CONFIG_IDF_TARGET_ESP32S3
auto lcd_bus = lcd->getBus();
if (lcd_bus->getBasicAttributes().type == ESP_PANEL_BUS_TYPE_RGB) {
static_cast<esp_panel::drivers::BusRGB *>(lcd_bus)
->configRGB_BounceBufferSize(lcd->getFrameWidth() * 8);
}
#endif
#endif
assert(g_board->begin());
lvgl_port_init(g_board->getLCD(), g_board->getTouch());
g_backlight = g_board->getBacklight();
if (g_backlight) {
g_backlight->setBrightness(1); // Boot: erst dunkel (weniger Einschaltspitze)
}
lvgl_port_lock(-1);
root_scr = lv_scr_act();
lv_disp_t *disp = lv_disp_get_default();
lv_disp_set_bg_color(disp, lv_color_white());
lv_disp_set_bg_opa(disp, LV_OPA_COVER);
lv_obj_set_style_bg_color(root_scr, lv_color_white(), 0);
lv_obj_set_style_bg_opa(root_scr, LV_OPA_COVER, 0);
lv_obj_set_style_clip_corner(root_scr, true, 0);
lv_obj_add_event_cb(root_scr, gesture_event_cb, LV_EVENT_GESTURE, NULL);
lv_obj_clear_flag(root_scr, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scroll_dir(root_scr, LV_DIR_NONE);
lv_obj_set_scrollbar_mode(root_scr, LV_SCROLLBAR_MODE_OFF);
header_label = lv_label_create(root_scr);
lv_obj_set_width(header_label, LV_PCT(100));
lv_obj_align(header_label, LV_ALIGN_TOP_LEFT, 0, 0);
lv_obj_set_style_text_color(header_label, lv_color_white(), 0);
lv_obj_set_style_bg_color(header_label, lv_palette_main(LV_PALETTE_BLUE), 0);
lv_obj_set_style_bg_opa(header_label, LV_OPA_COVER, 0);
lv_obj_set_style_pad_left(header_label, LEFT_INSET_PX, 0);
lv_obj_set_style_pad_right(header_label, 10, 0);
lv_obj_set_style_pad_top(header_label, 8, 0);
lv_obj_set_style_pad_bottom(header_label, 8, 0);
lv_obj_set_style_text_font(header_label, FONT_24, 0);
lv_obj_set_height(header_label, HEADER_H); // feste Höhe
lv_label_set_long_mode(header_label, LV_LABEL_LONG_CLIP); // kein Umbruch, kein Höhenwechsel
lv_obj_set_style_text_align(header_label, LV_TEXT_ALIGN_LEFT, 0);
lv_obj_add_flag(header_label, LV_OBJ_FLAG_ADV_HITTEST);
content = lv_obj_create(root_scr);
lv_obj_remove_style_all(content);
lv_obj_set_size(content, LV_PCT(100), LV_PCT(100));
lv_obj_align(content, LV_ALIGN_TOP_LEFT, 0, HEADER_H);
lv_obj_set_style_bg_color(content, lv_color_white(), 0);
lv_obj_set_style_bg_opa(content, LV_OPA_COVER, 0);
lv_obj_set_style_clip_corner(content, true, 0);
lv_obj_clear_flag(content, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scroll_dir(content, LV_DIR_NONE);
lv_obj_set_scrollbar_mode(content, LV_SCROLLBAR_MODE_OFF);
lv_obj_add_flag(content, LV_OBJ_FLAG_GESTURE_BUBBLE);
lv_obj_add_flag(content, LV_OBJ_FLAG_ADV_HITTEST);
cal_viewport = lv_obj_create(content);
lv_obj_remove_style_all(cal_viewport);
lv_obj_set_size(cal_viewport, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_bg_color(cal_viewport, lv_color_white(), 0);
lv_obj_set_style_bg_opa(cal_viewport, LV_OPA_COVER, 0);
lv_obj_set_style_clip_corner(cal_viewport, true, 0);
lv_obj_set_style_pad_left(cal_viewport, 0, 0);
lv_obj_set_style_pad_right(cal_viewport, 0, 0);
lv_obj_set_style_pad_top(cal_viewport, 0, 0);
lv_obj_set_style_pad_bottom(cal_viewport, 0, 0);
lv_obj_clear_flag(cal_viewport, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scroll_dir(cal_viewport, LV_DIR_NONE);
lv_obj_set_scrollbar_mode(cal_viewport, LV_SCROLLBAR_MODE_OFF);
lv_obj_add_flag(cal_viewport, LV_OBJ_FLAG_GESTURE_BUBBLE);
lv_obj_add_flag(cal_viewport, LV_OBJ_FLAG_ADV_HITTEST);
cal_list = lv_obj_create(cal_viewport);
lv_obj_remove_style_all(cal_list);
lv_obj_set_size(cal_list, LV_PCT(100), LV_PCT(100));
lv_obj_add_flag(cal_list, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scroll_dir(cal_list, LV_DIR_VER);
lv_obj_set_scrollbar_mode(cal_list, LV_SCROLLBAR_MODE_OFF);
lv_obj_clear_flag(cal_list, LV_OBJ_FLAG_SCROLL_MOMENTUM);
lv_obj_clear_flag(cal_list, LV_OBJ_FLAG_SCROLL_ELASTIC);
lv_obj_clear_flag(cal_list, LV_OBJ_FLAG_SCROLL_CHAIN);
lv_obj_set_style_anim_time(cal_list, 0, 0);
lv_obj_set_style_bg_color(cal_list, lv_color_white(), 0);
lv_obj_set_style_bg_opa(cal_list, LV_OPA_COVER, 0);
lv_obj_set_style_clip_corner(cal_list, true, 0);
lv_obj_set_flex_flow(cal_list, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(cal_list, 0, 0);
lv_obj_set_style_pad_row(cal_list, 4, 0);
lv_obj_add_flag(cal_list, LV_OBJ_FLAG_GESTURE_BUBBLE);
data_box = lv_obj_create(content);
lv_obj_remove_style_all(data_box);
lv_obj_set_size(data_box, LV_PCT(100), LV_PCT(100));
lv_obj_add_flag(data_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_style_bg_color(data_box, lv_color_white(), 0);
lv_obj_set_style_bg_opa(data_box, LV_OPA_COVER, 0);
lv_obj_set_style_clip_corner(data_box, true, 0);
lv_obj_clear_flag(data_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scroll_dir(data_box, LV_DIR_NONE);
lv_obj_set_scrollbar_mode(data_box, LV_SCROLLBAR_MODE_OFF);
lv_obj_add_flag(data_box, LV_OBJ_FLAG_ADV_HITTEST);
led_box = lv_obj_create(content);
lv_obj_remove_style_all(led_box);
lv_obj_set_size(led_box, LV_PCT(100), LV_PCT(100));
lv_obj_add_flag(led_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_style_bg_color(led_box, lv_color_white(), 0);
lv_obj_set_style_bg_opa(led_box, LV_OPA_COVER, 0);
lv_obj_set_style_clip_corner(led_box, true, 0);
lv_obj_clear_flag(led_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scroll_dir(led_box, LV_DIR_NONE);
lv_obj_set_scrollbar_mode(led_box, LV_SCROLLBAR_MODE_OFF);
lv_obj_add_flag(led_box, LV_OBJ_FLAG_ADV_HITTEST);
footer_badge = lv_obj_create(root_scr);
lv_obj_remove_style_all(footer_badge);
lv_obj_set_size(footer_badge, 14, 14);
lv_obj_set_style_radius(footer_badge, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_bg_color(footer_badge, lv_color_black(), 0);
lv_obj_align(footer_badge, LV_ALIGN_BOTTOM_RIGHT, -6, -6);
lv_obj_add_flag(footer_badge, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(footer_badge, LV_OBJ_FLAG_ADV_HITTEST);
mail_fab_create(root_scr);
mail_fab_update_visibility();
init_styles();
make_opaque_noclipbleed(root_scr);
make_opaque_noclipbleed(content);
make_opaque_noclipbleed(cal_viewport);
make_opaque_noclipbleed(cal_list);
make_opaque_noclipbleed(data_box);
make_opaque_noclipbleed(led_box);
clamp_to_screen(root_scr);
clamp_to_screen(content);
clamp_to_screen(cal_viewport);
clamp_to_screen(cal_list);
clamp_to_screen(data_box);
clamp_to_screen(led_box);
attach_cal_list_events();
lvgl_port_unlock();
ensureWiFi();
logWiFiStatus("setup after ensureWiFi");
if (WiFi.status() == WL_CONNECTED) testDNS();
wdt_kick(); // <-- NEU
configTzTime(TZ_EU_BERLIN, "pool.ntp.org", "time.nist.gov");
wdt_kick(); // <-- NEU
waitForTime();
wdt_kick(); // <-- NEU
led_init_espnow();
ack_load();
alarm_load_settings();
if (g_alarm_enabled) alarm_arm_next_occurrence_from_now();
String err; (void)fetchWeather(err);
drawCalendarView();
// Backlight sanft hochfahren (stabiler Start)
if (g_backlight) {
delay(300);
for (int b = 0; b <= 90; b += 10) {
g_backlight->setBrightness(b);
delay(40);
}
}
}
void loop() {
wdt_kick();
if (g_req_show_new_events_popup && !g_popup_scheduled) {
g_req_show_new_events_popup = false;
g_popup_scheduled = true;
lv_async_call(async_show_new_events_popup, nullptr);
}
cal_background_update_and_draw_if_active();
static uint32_t last_full_refr = 0;
if (millis() - last_full_refr > 60UL * 1000UL) { // alle 60s
last_full_refr = millis();
lvgl_port_lock(-1);
lv_obj_invalidate(lv_scr_act()); // nur "dirty" markieren
lvgl_port_unlock();
wdt_kick();
}
static uint32_t lastW=0;
const uint32_t WINT=60UL*60UL*1000UL;
if (millis()-lastW>WINT) {
lastW=millis();
String err; (void)fetchWeather(err);
if (currentView==VIEW_DATA) {
drawDataView();
} else {
lvgl_port_lock(-1);
set_header_with_now();
lvgl_port_unlock();
}
}
static uint32_t lastHeader = 0;
if (millis() - lastHeader > 30UL*1000UL) {
lastHeader = millis();
lvgl_port_lock(-1);
set_header_with_now();
lvgl_port_unlock();
}
unsigned long now = millis();
int pirVal = digitalRead(PIR_PIN);
if (pirVal == HIGH) {
g_lastMotionMs = now;
if (g_backlight && g_screenOff) {
Serial.println("[PRESENCE] Bewegung -> Backlight EIN");
g_backlight->setBrightness(90);
g_screenOff = false;
}
} else {
if (!g_screenOff && (now - g_lastMotionMs > NO_MOTION_SCREENOFF_MS)) {
if (g_backlight) {
Serial.println("[PRESENCE] Lange keine Bewegung -> Backlight AUS");
g_backlight->setBrightness(0);
}
g_screenOff = true;
}
}
alarm_check_and_fire();
if (g_need_view_redraw) {
g_need_view_redraw = false;
if (currentView == VIEW_CAL) drawCalendarView();
else if (currentView == VIEW_DATA) drawDataView();
else drawLEDView();
}
delay(30);
}
- Arduino IDE + ESP32 Core
- LVGL: v8 (lvgl_v8_port / esp_display_panel / esp_panel_board)
- PSRAM: OPI (QSPI führt zu
PSRAM chip is not connected) - Framebuffers: aktuell 2 oder 3 (ich habe beides getestet)
Was ich bereits gemacht habe
- PSRAM zurück auf OPI gestellt (QSPI verursacht
no mem for frame buffer/alloc frame buffers failed) - Watchdog eingebaut (timeout 300s), trotzdem gab es zeitweise:
task_wdt: Task watchdog got triggered ... loopTask (CPU1)
- WLAN/DNS Logging ergänzt, Verbindung ist OK
- Anzeige/Backlight-Handling (PIR) drin (Backlight wird nach 1 min ohne Bewegung dunkel)
Frage
Hat jemand eine Idee, ob das eher ein:
- LVGL Memory Leak / Heap Fragmentation
- RGB Framebuffer/VSYNC/Tearing/Timing Problem
- oder ein Power/Backlight/PSRAM Problem ist?
Und welche Settings sind für dieses Waveshare 7" RGB Panel am stabilsten?
