Files
CYD-HomeBoard/src/main.cpp
T

614 lines
21 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// CYD HomeBoard – Home Assistant dashboard for the ESP32-2432S028R
#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <SPI.h>
#include <TFT_eSPI.h>
#include <XPT2046_Touchscreen.h>
#include <lvgl.h>
#include <time.h>
struct Device { String entity; String name; };
#if __has_include("config.h")
#include "config.h"
#else
#error "include/config.h fehlt – kopiere include/config.example.h nach include/config.h"
#endif
// ---------------------------------------------------------------- Hardware
static constexpr int SCREEN_W = 320;
static constexpr int SCREEN_H = 240;
static constexpr int XPT2046_IRQ = 36;
static constexpr int XPT2046_MOSI = 32;
static constexpr int XPT2046_MISO = 39;
static constexpr int XPT2046_CLK = 25;
static constexpr int XPT2046_CS = 33;
static TFT_eSPI tft;
static SPIClass touchSpi(VSPI);
static XPT2046_Touchscreen ts(XPT2046_CS, XPT2046_IRQ);
static lv_disp_draw_buf_t drawBuf;
static lv_color_t buf1[SCREEN_W * 24];
// ---------------------------------------------------------------- State
static constexpr size_t MAX_CLIMATE = 8;
static constexpr size_t MAX_LIGHT = 12;
static Device CLIMATES[MAX_CLIMATE];
static Device LIGHTS[MAX_LIGHT];
static size_t N_CLIMATE = 0;
static size_t N_LIGHT = 0;
static bool discovered = false;
static lv_obj_t* tabHeat;
static lv_obj_t* tabLight;
static lv_obj_t* hintHeat;
static lv_obj_t* hintLight;
struct ClimateUi {
lv_obj_t* target = nullptr;
lv_obj_t* info = nullptr;
float targetVal = NAN, minT = 5, maxT = 30, step = 0.5;
uint32_t pendingSince = 0; // != 0: local change not sent yet
};
struct LightUi {
lv_obj_t* sw = nullptr;
lv_obj_t* slider = nullptr;
lv_obj_t* card = nullptr;
uint32_t ignoreUntil = 0; // ignore poll results right after a command
};
static ClimateUi climUi[MAX_CLIMATE];
static LightUi lightUi[MAX_LIGHT];
static lv_obj_t* clockLabel;
static lv_obj_t* statusLabel;
static lv_obj_t* rssiBars[4];
static lv_obj_t* rssiLabel;
static bool screenOff = false;
static bool swallowTouch = false;
// ---------------------------------------------------------------- Display / touch drivers
static void dispFlush(lv_disp_drv_t* drv, const lv_area_t* a, lv_color_t* px) {
uint32_t w = a->x2 - a->x1 + 1, h = a->y2 - a->y1 + 1;
tft.startWrite();
tft.setAddrWindow(a->x1, a->y1, w, h);
tft.pushColors((uint16_t*)&px->full, w * h, true);
tft.endWrite();
lv_disp_flush_ready(drv);
}
static void setBacklight(bool on) {
digitalWrite(TFT_BL, on ? HIGH : LOW);
screenOff = !on;
}
static void touchRead(lv_indev_drv_t*, lv_indev_data_t* data) {
bool pressed = ts.tirqTouched() && ts.touched();
if (!pressed) {
swallowTouch = false;
data->state = LV_INDEV_STATE_REL;
return;
}
// The first touch on a dark screen only wakes it up.
if (screenOff) {
setBacklight(true);
swallowTouch = true;
}
if (swallowTouch) {
lv_disp_trig_activity(nullptr);
data->state = LV_INDEV_STATE_REL;
return;
}
TS_Point p = ts.getPoint();
int rx = p.x, ry = p.y;
if (TOUCH_SWAP_XY) std::swap(rx, ry);
int x = map(rx, TOUCH_X_MIN, TOUCH_X_MAX, 0, SCREEN_W - 1);
int y = map(ry, TOUCH_Y_MIN, TOUCH_Y_MAX, 0, SCREEN_H - 1);
if (TOUCH_INVERT_X) x = SCREEN_W - 1 - x;
if (TOUCH_INVERT_Y) y = SCREEN_H - 1 - y;
data->point.x = constrain(x, 0, SCREEN_W - 1);
data->point.y = constrain(y, 0, SCREEN_H - 1);
data->state = LV_INDEV_STATE_PR;
}
// ---------------------------------------------------------------- Home Assistant API
static int haRequest(bool post, const String& path, const String& body, String* resp) {
if (WiFi.status() != WL_CONNECTED) return -1;
String url = String(HA_URL) + path;
HTTPClient http;
WiFiClient plain;
WiFiClientSecure secure;
bool ok;
if (url.startsWith("https")) {
secure.setInsecure();
ok = http.begin(secure, url);
} else {
ok = http.begin(plain, url);
}
if (!ok) return -1;
http.setTimeout(4000);
http.addHeader("Authorization", String("Bearer ") + HA_TOKEN);
http.addHeader("Content-Type", "application/json");
int code = post ? http.POST(body) : http.GET();
if (code == 200 && resp) *resp = http.getString();
http.end();
return code;
}
static void setStatus(const char* txt, lv_color_t col) {
lv_label_set_text(statusLabel, txt);
lv_obj_set_style_text_color(statusLabel, col, 0);
}
static bool callService(const char* domain, const char* service, JsonDocument& doc) {
String body;
serializeJson(doc, body);
int code = haRequest(true, String("/api/services/") + domain + "/" + service, body, nullptr);
if (code != 200) {
Serial.printf("Service %s.%s fehlgeschlagen: %d\n", domain, service, code);
setStatus(LV_SYMBOL_WARNING " Fehler", lv_palette_main(LV_PALETTE_RED));
return false;
}
return true;
}
static String domainOf(const String& e) {
return e.substring(0, e.indexOf('.'));
}
// ---------------------------------------------------------------- UI updates
static void updateRssi() {
bool conn = WiFi.status() == WL_CONNECTED;
int rssi = conn ? WiFi.RSSI() : -100;
int level = !conn ? 0 : rssi > -55 ? 4 : rssi > -65 ? 3 : rssi > -75 ? 2 : rssi > -85 ? 1 : 0;
lv_color_t col = level >= 3 ? lv_palette_main(LV_PALETTE_GREEN)
: level == 2 ? lv_palette_main(LV_PALETTE_AMBER)
: lv_palette_main(LV_PALETTE_RED);
for (int i = 0; i < 4; i++)
lv_obj_set_style_bg_color(rssiBars[i], i < level ? col : lv_color_hex(0x3a444e), 0);
char buf[12];
if (conn) snprintf(buf, sizeof buf, "%d", rssi); else buf[0] = 0;
lv_label_set_text(rssiLabel, buf);
}
static void showTarget(size_t i) {
char buf[16];
if (isnan(climUi[i].targetVal)) snprintf(buf, sizeof buf, "--");
else snprintf(buf, sizeof buf, "%.1f°", climUi[i].targetVal);
lv_label_set_text(climUi[i].target, buf);
lv_obj_set_style_text_color(climUi[i].target,
climUi[i].pendingSince ? lv_palette_main(LV_PALETTE_AMBER) : lv_color_white(), 0);
}
static const char* modeText(const char* s) {
if (!strcmp(s, "heat")) return "Heizen";
if (!strcmp(s, "off")) return "Aus";
if (!strcmp(s, "auto")) return "Auto";
if (!strcmp(s, "cool")) return "Kuehlen";
if (!strcmp(s, "heat_cool")) return "Auto";
if (!strcmp(s, "unavailable")) return "offline";
return s;
}
static void applyClimate(size_t i, JsonDocument& doc) {
ClimateUi& u = climUi[i];
const char* st = doc["state"] | "unavailable";
JsonObject a = doc["attributes"];
u.minT = a["min_temp"] | 5.0f;
u.maxT = a["max_temp"] | 30.0f;
u.step = a["target_temp_step"] | 0.5f;
float cur = a["current_temperature"] | NAN;
const char* action = a["hvac_action"] | "";
char buf[48];
if (isnan(cur)) snprintf(buf, sizeof buf, "%s", modeText(st));
else snprintf(buf, sizeof buf, "Ist %.1f°C %s", cur,
!strcmp(action, "heating") ? LV_SYMBOL_CHARGE : modeText(st));
lv_label_set_text(u.info, buf);
if (!u.pendingSince) {
u.targetVal = a["temperature"] | NAN;
showTarget(i);
}
}
static void applyLight(size_t i, JsonDocument& doc) {
LightUi& u = lightUi[i];
if (millis() < u.ignoreUntil) return;
const char* st = doc["state"] | "unavailable";
bool on = !strcmp(st, "on");
if (on) lv_obj_add_state(u.sw, LV_STATE_CHECKED);
else lv_obj_clear_state(u.sw, LV_STATE_CHECKED);
if (!strcmp(st, "unavailable")) lv_obj_add_state(u.sw, LV_STATE_DISABLED);
else lv_obj_clear_state(u.sw, LV_STATE_DISABLED);
if (!u.slider) return;
// Only show the slider if the lamp is dimmable.
JsonArray modes = doc["attributes"]["supported_color_modes"];
bool dimmable = !modes.isNull() && modes.size() > 0 && strcmp(modes[0] | "onoff", "onoff") != 0;
if (dimmable) {
lv_obj_clear_flag(u.slider, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_height(u.card, 84);
int b = doc["attributes"]["brightness"] | 0;
if (!lv_slider_is_dragged(u.slider)) lv_slider_set_value(u.slider, on ? max(1, b * 100 / 255) : 0, LV_ANIM_OFF);
} else {
lv_obj_add_flag(u.slider, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_height(u.card, 52);
}
}
static bool pollEntity(size_t idx) {
bool isClimate = idx < N_CLIMATE;
const String& entity = isClimate ? CLIMATES[idx].entity : LIGHTS[idx - N_CLIMATE].entity;
String resp;
int code = haRequest(false, String("/api/states/") + entity, "", &resp);
if (code != 200) {
Serial.printf("GET %s -> %d\n", entity.c_str(), code);
return false;
}
JsonDocument doc;
if (deserializeJson(doc, resp)) return false;
if (isClimate) applyClimate(idx, doc);
else applyLight(idx - N_CLIMATE, doc);
return true;
}
// ---------------------------------------------------------------- Events
static void onTempBtn(lv_event_t* e) {
intptr_t v = (intptr_t)lv_event_get_user_data(e);
size_t i = v >> 1;
bool plus = v & 1;
ClimateUi& u = climUi[i];
if (isnan(u.targetVal)) return;
u.targetVal = constrain(u.targetVal + (plus ? u.step : -u.step), u.minT, u.maxT);
u.pendingSince = millis();
showTarget(i);
}
static void onLightSwitch(lv_event_t* e) {
size_t i = (size_t)(intptr_t)lv_event_get_user_data(e);
bool on = lv_obj_has_state(lightUi[i].sw, LV_STATE_CHECKED);
JsonDocument doc;
doc["entity_id"] = LIGHTS[i].entity;
lightUi[i].ignoreUntil = millis() + 3000;
callService(domainOf(LIGHTS[i].entity).c_str(), on ? "turn_on" : "turn_off", doc);
}
static void onLightSlider(lv_event_t* e) {
size_t i = (size_t)(intptr_t)lv_event_get_user_data(e);
int pct = lv_slider_get_value(lightUi[i].slider);
JsonDocument doc;
doc["entity_id"] = LIGHTS[i].entity;
lightUi[i].ignoreUntil = millis() + 3000;
if (pct == 0) {
lv_obj_clear_state(lightUi[i].sw, LV_STATE_CHECKED);
callService("light", "turn_off", doc);
} else {
doc["brightness_pct"] = pct;
lv_obj_add_state(lightUi[i].sw, LV_STATE_CHECKED);
callService("light", "turn_on", doc);
}
}
// ---------------------------------------------------------------- UI construction
static lv_obj_t* makeCard(lv_obj_t* parent, int h) {
lv_obj_t* c = lv_obj_create(parent);
lv_obj_set_size(c, lv_pct(100), h);
lv_obj_set_style_pad_all(c, 8, 0);
lv_obj_set_style_radius(c, 10, 0);
lv_obj_clear_flag(c, LV_OBJ_FLAG_SCROLLABLE);
return c;
}
static lv_obj_t* makeTab(lv_obj_t* tv, const char* title) {
lv_obj_t* t = lv_tabview_add_tab(tv, title);
lv_obj_set_flex_flow(t, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(t, 6, 0);
lv_obj_set_style_pad_row(t, 6, 0);
return t;
}
static lv_obj_t* makeRoundBtn(lv_obj_t* parent, const char* sym, intptr_t ud) {
lv_obj_t* b = lv_btn_create(parent);
lv_obj_set_size(b, 42, 42);
lv_obj_set_style_radius(b, LV_RADIUS_CIRCLE, 0);
lv_obj_t* l = lv_label_create(b);
lv_label_set_text(l, sym);
lv_obj_center(l);
lv_obj_add_event_cb(b, onTempBtn, LV_EVENT_CLICKED, (void*)ud);
return b;
}
static void buildUi() {
lv_obj_t* scr = lv_scr_act();
lv_obj_set_style_bg_color(scr, lv_color_hex(0x101418), 0);
// Header
lv_obj_t* hdr = lv_obj_create(scr);
lv_obj_set_size(hdr, SCREEN_W, 26);
lv_obj_set_pos(hdr, 0, 0);
lv_obj_set_style_radius(hdr, 0, 0);
lv_obj_set_style_border_width(hdr, 0, 0);
lv_obj_set_style_pad_hor(hdr, 8, 0);
lv_obj_set_style_pad_ver(hdr, 0, 0);
lv_obj_set_style_bg_color(hdr, lv_color_hex(0x1c232b), 0);
lv_obj_clear_flag(hdr, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* title = lv_label_create(hdr);
lv_label_set_text(title, LV_SYMBOL_HOME " HomeBoard");
lv_obj_align(title, LV_ALIGN_LEFT_MID, 0, 0);
clockLabel = lv_label_create(hdr);
lv_label_set_text(clockLabel, "--:--");
lv_obj_align(clockLabel, LV_ALIGN_CENTER, 0, 0);
// WiFi signal strength: 4 bars + dBm value
for (int i = 0; i < 4; i++) {
rssiBars[i] = lv_obj_create(hdr);
lv_obj_set_size(rssiBars[i], 3, 5 + i * 3);
lv_obj_set_style_radius(rssiBars[i], 0, 0);
lv_obj_set_style_border_width(rssiBars[i], 0, 0);
lv_obj_set_style_pad_all(rssiBars[i], 0, 0);
lv_obj_clear_flag(rssiBars[i], LV_OBJ_FLAG_SCROLLABLE);
lv_obj_align(rssiBars[i], LV_ALIGN_CENTER, 52 + i * 5, 6 - (5 + i * 3) / 2 + 0);
}
rssiLabel = lv_label_create(hdr);
lv_obj_set_style_text_color(rssiLabel, lv_palette_lighten(LV_PALETTE_GREY, 1), 0);
lv_label_set_text(rssiLabel, "");
lv_obj_align(rssiLabel, LV_ALIGN_CENTER, 98, 0);
updateRssi();
statusLabel = lv_label_create(hdr);
lv_obj_align(statusLabel, LV_ALIGN_RIGHT_MID, 0, 0);
setStatus(LV_SYMBOL_WIFI " ...", lv_palette_main(LV_PALETTE_GREY));
// Tabs
lv_obj_t* tv = lv_tabview_create(scr, LV_DIR_BOTTOM, 34);
lv_obj_set_size(tv, SCREEN_W, SCREEN_H - 26);
lv_obj_set_pos(tv, 0, 26);
tabHeat = makeTab(tv, LV_SYMBOL_CHARGE " Heizung");
tabLight = makeTab(tv, LV_SYMBOL_EYE_OPEN " Licht");
hintHeat = lv_label_create(tabHeat);
lv_label_set_text(hintHeat, "Lade Geraete aus HA ...");
hintLight = lv_label_create(tabLight);
lv_label_set_text(hintLight, "Lade Geraete aus HA ...");
}
static void populateUi() {
if (hintHeat) { lv_obj_del(hintHeat); hintHeat = nullptr; }
if (hintLight) { lv_obj_del(hintLight); hintLight = nullptr; }
for (size_t i = 0; i < N_CLIMATE; i++) {
lv_obj_t* c = makeCard(tabHeat, 64);
lv_obj_t* name = lv_label_create(c);
lv_obj_set_style_text_font(name, &lv_font_montserrat_20, 0);
lv_label_set_long_mode(name, LV_LABEL_LONG_DOT);
lv_obj_set_width(name, 125);
lv_label_set_text(name, CLIMATES[i].name.c_str());
lv_obj_align(name, LV_ALIGN_TOP_LEFT, 0, -2);
climUi[i].info = lv_label_create(c);
lv_obj_set_style_text_color(climUi[i].info, lv_palette_lighten(LV_PALETTE_GREY, 1), 0);
lv_label_set_text(climUi[i].info, "...");
lv_obj_align(climUi[i].info, LV_ALIGN_BOTTOM_LEFT, 0, 2);
lv_obj_t* plus = makeRoundBtn(c, LV_SYMBOL_PLUS, (intptr_t)(i << 1 | 1));
lv_obj_align(plus, LV_ALIGN_RIGHT_MID, 0, 0);
climUi[i].target = lv_label_create(c);
lv_obj_set_style_text_font(climUi[i].target, &lv_font_montserrat_28, 0);
lv_obj_set_style_text_align(climUi[i].target, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_width(climUi[i].target, 76);
lv_obj_align_to(climUi[i].target, plus, LV_ALIGN_OUT_LEFT_MID, -2, 0);
lv_obj_t* minus = makeRoundBtn(c, LV_SYMBOL_MINUS, (intptr_t)(i << 1));
lv_obj_align_to(minus, climUi[i].target, LV_ALIGN_OUT_LEFT_MID, -2, 0);
showTarget(i);
}
for (size_t i = 0; i < N_LIGHT; i++) {
lv_obj_t* c = makeCard(tabLight, 52);
lightUi[i].card = c;
lv_obj_t* name = lv_label_create(c);
lv_obj_set_style_text_font(name, &lv_font_montserrat_20, 0);
lv_label_set_long_mode(name, LV_LABEL_LONG_DOT);
lv_obj_set_width(name, 200);
lv_label_set_text(name, LIGHTS[i].name.c_str());
lv_obj_align(name, LV_ALIGN_TOP_LEFT, 0, 4);
lightUi[i].sw = lv_switch_create(c);
lv_obj_set_size(lightUi[i].sw, 56, 30);
lv_obj_align(lightUi[i].sw, LV_ALIGN_TOP_RIGHT, 0, 0);
lv_obj_add_event_cb(lightUi[i].sw, onLightSwitch, LV_EVENT_VALUE_CHANGED, (void*)(intptr_t)i);
if (domainOf(LIGHTS[i].entity) == "light") {
lightUi[i].slider = lv_slider_create(c);
lv_slider_set_range(lightUi[i].slider, 0, 100);
lv_obj_set_width(lightUi[i].slider, lv_pct(92));
lv_obj_align(lightUi[i].slider, LV_ALIGN_BOTTOM_MID, 0, -6);
lv_obj_add_flag(lightUi[i].slider, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_event_cb(lightUi[i].slider, onLightSlider, LV_EVENT_RELEASED, (void*)(intptr_t)i);
}
}
if (!N_CLIMATE) { hintHeat = lv_label_create(tabHeat); lv_label_set_text(hintHeat, "Keine Heizungen in HA gefunden"); }
if (!N_LIGHT) { hintLight = lv_label_create(tabLight); lv_label_set_text(hintLight, "Keine Lichter in HA gefunden"); }
}
// Converts UTF-8 umlauts to ASCII (the built-in font has none) and drops other non-ASCII bytes.
static String asciiName(const String& in) {
String out;
for (size_t i = 0; i < in.length(); i++) {
uint8_t c = in[i];
if (c < 0x80) { out += (char)c; continue; }
if (c == 0xC3 && i + 1 < in.length()) {
uint8_t d = in[++i];
switch (d) {
case 0xA4: out += "ae"; break; case 0xB6: out += "oe"; break; case 0xBC: out += "ue"; break;
case 0x84: out += "Ae"; break; case 0x96: out += "Oe"; break; case 0x9C: out += "Ue"; break;
case 0x9F: out += "ss"; break;
}
}
}
out.trim();
return out;
}
// Asks HA (template API) for all climate/light entities and builds the UI from them.
static bool discoverDevices() {
#if INCLUDE_SWITCHES
const char* lightSrc = "(states.light | list + states.switch | list)";
#else
const char* lightSrc = "(states.light | list)";
#endif
String tpl = String("{{ {"
"'c': states.climate | sort(attribute='name') | map(attribute='entity_id') | list,"
"'cn': states.climate | sort(attribute='name') | map(attribute='name') | list,"
"'l': ") + lightSrc + " | sort(attribute='name') | map(attribute='entity_id') | list,"
"'ln': " + lightSrc + " | sort(attribute='name') | map(attribute='name') | list"
"} | tojson }}";
JsonDocument req;
req["template"] = tpl;
String body, resp;
serializeJson(req, body);
int code = haRequest(true, "/api/template", body, &resp);
if (code != 200) {
Serial.printf("Geraete-Abfrage fehlgeschlagen: %d\n", code);
return false;
}
JsonDocument doc;
if (deserializeJson(doc, resp)) { Serial.println("Geraete-Antwort ist kein JSON"); return false; }
auto fill = [&](JsonArray ids, JsonArray names, Device* dst, size_t max) {
size_t n = 0;
for (size_t i = 0; i < ids.size() && n < max; i++) {
String id = ids[i] | "";
String nm = asciiName(String(names[i] | ""));
dst[n].entity = id;
dst[n].name = nm.length() ? nm : id;
n++;
}
return n;
};
N_CLIMATE = fill(doc["c"], doc["cn"], CLIMATES, MAX_CLIMATE);
N_LIGHT = fill(doc["l"], doc["ln"], LIGHTS, MAX_LIGHT);
Serial.printf("HA: %u Heizungen, %u Lichter gefunden\n", (unsigned)N_CLIMATE, (unsigned)N_LIGHT);
populateUi();
return true;
}
// ---------------------------------------------------------------- Setup / loop
void setup() {
Serial.begin(115200);
tft.init();
tft.setRotation(1);
tft.invertDisplay(TFT_INVERT);
pinMode(TFT_BL, OUTPUT);
setBacklight(true);
touchSpi.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS);
ts.begin(touchSpi);
ts.setRotation(1);
lv_init();
lv_disp_draw_buf_init(&drawBuf, buf1, nullptr, SCREEN_W * 24);
static lv_disp_drv_t dispDrv;
lv_disp_drv_init(&dispDrv);
dispDrv.hor_res = SCREEN_W;
dispDrv.ver_res = SCREEN_H;
dispDrv.flush_cb = dispFlush;
dispDrv.draw_buf = &drawBuf;
lv_disp_drv_register(&dispDrv);
static lv_indev_drv_t indevDrv;
lv_indev_drv_init(&indevDrv);
indevDrv.type = LV_INDEV_TYPE_POINTER;
indevDrv.read_cb = touchRead;
lv_indev_drv_register(&indevDrv);
buildUi();
lv_timer_handler();
WiFi.mode(WIFI_STA);
WiFi.setAutoReconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASS);
configTzTime(TIMEZONE, "pool.ntp.org", "time.google.com");
}
void loop() {
lv_timer_handler();
uint32_t now = millis();
// Clock
static uint32_t lastClock = 0;
if (now - lastClock > 1000) {
lastClock = now;
struct tm t;
if (getLocalTime(&t, 0)) {
char buf[8];
strftime(buf, sizeof buf, "%H:%M", &t);
lv_label_set_text(clockLabel, buf);
}
}
// WiFi signal strength
static uint32_t lastRssi = 0;
if (now - lastRssi > 2000) {
lastRssi = now;
updateRssi();
}
// Backlight timeout
if (SCREEN_TIMEOUT_S > 0 && !screenOff && lv_disp_get_inactive_time(nullptr) > SCREEN_TIMEOUT_S * 1000UL)
setBacklight(false);
// WiFi status
static bool wasConnected = false;
bool connected = WiFi.status() == WL_CONNECTED;
if (connected != wasConnected) {
wasConnected = connected;
if (connected) setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN));
else setStatus(LV_SYMBOL_WIFI " offline", lv_palette_main(LV_PALETTE_RED));
}
if (!connected) { delay(5); return; }
// Discover devices from HA (retry every 10 s until it works)
static uint32_t lastDiscover = 0;
if (!discovered) {
if (lastDiscover == 0 || now - lastDiscover > 10000) {
lastDiscover = now ? now : 1;
if (discoverDevices()) {
discovered = true;
setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN));
} else {
setStatus(LV_SYMBOL_WARNING " HA", lv_palette_main(LV_PALETTE_RED));
}
}
delay(5);
return;
}
// Send pending target temperatures
for (size_t i = 0; i < N_CLIMATE; i++) {
ClimateUi& u = climUi[i];
if (u.pendingSince && now - u.pendingSince > SET_DELAY_MS) {
JsonDocument doc;
doc["entity_id"] = CLIMATES[i].entity;
doc["temperature"] = u.targetVal;
callService("climate", "set_temperature", doc);
u.pendingSince = 0;
showTarget(i);
}
}
// Round-robin polling (paused while the screen is off; starts with a full pass)
static uint32_t lastPoll = 0;
static size_t pollIdx = 0;
if (!screenOff && (N_CLIMATE + N_LIGHT) > 0 && now - lastPoll > POLL_STEP_MS) {
lastPoll = now;
bool ok = pollEntity(pollIdx);
if (ok) setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN));
else setStatus(LV_SYMBOL_WARNING " HA", lv_palette_main(LV_PALETTE_RED));
pollIdx = (pollIdx + 1) % (N_CLIMATE + N_LIGHT);
}
delay(5);
}