Fluessigeres UI: HA-Abfragen im Hintergrund, DMA-Doppelpuffer, keine Schatten; Cover-Status auf dem Display

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-06 21:17:33 +01:00
1 parent 249bffd14e
commit a3805a1777
4 files changed
+185 -86

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ struct NowPlaying {
uint32_t seq = 0; // changes whenever title/artist/state/device/volume change
uint32_t artSeq = 0; // changes whenever the album art buffer changes
bool hasArt = false;
char artInfo[48] = ""; // why there is no album art (shown instead of the picture)
};
struct PlayerEntry {
+1
View File
@@ -31,6 +31,7 @@
#define LV_USE_THEME_DEFAULT 1
#define LV_THEME_DEFAULT_DARK 1
#define LV_THEME_DEFAULT_TRANSITION_TIME 0 // no state-change animations (cheaper redraws)
#endif
#endif
+57 -22
View File
@@ -85,6 +85,9 @@ static int nList = 0;
static uint16_t* artBuf = nullptr;
static bool hasArt = false;
static uint32_t artSeq = 0;
static char artInfo[48] = "";
static uint32_t artRequestedAt = 0;
static int artTries = 0;
// Task-only state for album art
static String curPeerId, curPlayer, curArtUrl, artLoadedUrl, artRequestedUrl;
@@ -331,6 +334,10 @@ static void publish() {
n.seq = pub.seq + (changed ? 1 : 0);
n.artSeq = artSeq;
n.hasArt = hasArt;
if (best && !curArtUrl.length())
strcpy(artInfo, !bp->artPayload ? "Geraet sendet keine Cover" : "Player liefert kein Cover");
memcpy(n.artInfo, artInfo, sizeof artInfo);
if (strcmp(n.artInfo, pub.artInfo)) n.artSeq = ++artSeq;
pub = n;
xSemaphoreGive(mtx);
}
@@ -454,6 +461,8 @@ struct ArtCtx {
mbedtls_ssl_context* ssl;
int64_t left;
int S, ox, oy;
BYTE head[4]; // first bytes, to recognise the format in error messages
int nHead;
};
static UINT artIn(JDEC* jd, BYTE* buf, UINT nd) {
@@ -467,6 +476,7 @@ static UINT artIn(JDEC* jd, BYTE* buf, UINT nd) {
int r = mbedtls_ssl_read(c->ssl, dst, want);
if (r == MBEDTLS_ERR_SSL_WANT_READ || r == MBEDTLS_ERR_SSL_WANT_WRITE) continue;
if (r <= 0) break;
for (int k = 0; k < r && c->nHead < 4; k++) c->head[c->nHead++] = dst[k];
done += r;
c->left -= r;
}
@@ -491,25 +501,29 @@ static UINT artOut(JDEC* jd, void* bitmap, JRECT* rect) {
return 1;
}
static void setArt(bool valid) {
static void setArt(bool valid, const char* info) {
xSemaphoreTake(mtx, portMAX_DELAY);
hasArt = valid;
strncpy(artInfo, info, sizeof artInfo - 1);
artSeq++;
pub.artSeq = artSeq;
pub.hasArt = hasArt;
memcpy(pub.artInfo, artInfo, sizeof artInfo);
xSemaphoreGive(mtx);
if (info[0]) Serial.printf("KDE: Cover: %s\n", info);
}
static bool downloadArt(Peer& p, int port, int64_t size) {
if (size <= 0 || size > 2000000 || !p.ip) return false;
// Returns nullptr on success, otherwise a short reason for the display.
static const char* downloadArt(Peer& p, int port, int64_t size) {
if (size <= 0 || size > 2000000 || !p.ip) return "Ungueltige Bilddaten";
if (!artBuf) artBuf = (uint16_t*)malloc(KDE_ART_SIZE * KDE_ART_SIZE * 2);
if (!artBuf) return false;
if (ESP.getFreeHeap() < 60000 || heap_caps_get_largest_free_block(MALLOC_CAP_8BIT) < 18000) {
Serial.printf("KDE: zu wenig Speicher fuer Titelbild (Heap %u)\n", ESP.getFreeHeap());
return false;
}
if (!artBuf) return "Zu wenig Speicher";
// A TLS connection needs two ~16.7 KB buffers plus some KB for the handshake.
uint32_t freeHeap = ESP.getFreeHeap(), block = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
Serial.printf("KDE: lade Cover (%u Bytes), Heap %u, groesster Block %u\n", (unsigned)size, freeHeap, block);
if (freeHeap < 46000 || block < 17500) return "Zu wenig Speicher";
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) return false;
if (fd < 0) return "Keine Verbindung";
struct timeval tv = {5, 0};
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
@@ -517,24 +531,32 @@ static bool downloadArt(Peer& p, int port, int64_t size) {
a.sin_family = AF_INET;
a.sin_port = htons(port);
a.sin_addr.s_addr = p.ip;
if (connect(fd, (sockaddr*)&a, sizeof a) < 0) { close(fd); return false; }
if (connect(fd, (sockaddr*)&a, sizeof a) < 0) { close(fd); return "Keine Verbindung"; }
mbedtls_net_context net;
mbedtls_net_init(&net);
net.fd = fd;
mbedtls_ssl_context ssl;
mbedtls_ssl_init(&ssl);
bool ok = false;
const char* err = nullptr;
void* pool = nullptr;
if (mbedtls_ssl_setup(&ssl, &conf) == 0) {
if (mbedtls_ssl_setup(&ssl, &conf) != 0) {
err = "Zu wenig Speicher";
} else {
mbedtls_ssl_set_bio(&ssl, &net, mbedtls_net_send, mbedtls_net_recv, nullptr);
uint32_t start = millis();
int r;
while ((r = mbedtls_ssl_handshake(&ssl)) == MBEDTLS_ERR_SSL_WANT_READ || r == MBEDTLS_ERR_SSL_WANT_WRITE)
if (millis() - start > 8000) break;
pool = r == 0 ? malloc(4096) : nullptr;
if (pool) {
ArtCtx c = {&ssl, size, 0, 0, 0};
if (r != 0) {
char e[80];
mbedtls_strerror(r, e, sizeof e);
Serial.printf("KDE: Cover-TLS fehlgeschlagen: %s\n", e);
err = "Verbindung abgelehnt";
} else if (!(pool = malloc(4096))) {
err = "Zu wenig Speicher";
} else {
ArtCtx c = {&ssl, size, 0, 0, 0, {0}, 0};
JDEC jd;
JRESULT jr = jd_prepare(&jd, artIn, pool, 4096, &c);
if (jr == JDR_OK) {
@@ -545,15 +567,21 @@ static bool downloadArt(Peer& p, int port, int64_t size) {
c.ox = (W - c.S) / 2;
c.oy = (H - c.S) / 2;
jr = jd_decomp(&jd, artOut, s);
ok = jr == JDR_OK;
}
if (!ok) Serial.printf("KDE: Titelbild nicht lesbar (%d), nur normales JPEG geht\n", (int)jr);
if (jr != JDR_OK) {
Serial.printf("KDE: Cover nicht lesbar (Fehler %d, Anfang %02x %02x %02x %02x)\n", (int)jr, c.head[0],
c.head[1], c.head[2], c.head[3]);
if (c.head[0] == 0x89 && c.head[1] == 'P') err = "PNG wird nicht unterstuetzt";
else if (c.head[0] == 0xFF && c.head[1] == 0xD8) err = "JPEG-Format nicht unterstuetzt";
else if (c.nHead == 0) err = "Keine Bilddaten empfangen";
else err = "Bildformat nicht unterstuetzt";
}
}
}
free(pool);
mbedtls_ssl_free(&ssl);
mbedtls_net_free(&net);
return ok;
return err;
}
static void handlePacket(Peer& p, const String& line) {
@@ -601,9 +629,9 @@ static void handlePacket(Peer& p, const String& line) {
int port = d["payloadTransferInfo"]["port"] | 0;
String url = b["albumArtUrl"] | "";
if (port && (b["transferringAlbumArt"] | false) && p.id == curPeerId && url == curArtUrl) {
bool ok = downloadArt(p, port, d["payloadSize"] | (int64_t)0);
const char* err = downloadArt(p, port, d["payloadSize"] | (int64_t)0);
artLoadedUrl = url;
setArt(ok);
setArt(!err, err ? err : "");
}
}
}
@@ -843,11 +871,18 @@ static void kdeTask(void*) {
// Album art: ask for the picture of the track shown on the display
if (curArtUrl != artLoadedUrl) {
if (hasArt) setArt(false);
if (!curArtUrl.length()) {
if (hasArt) setArt(false, "");
artLoadedUrl = "";
} else if (curArtUrl != artRequestedUrl) {
} else if (curArtUrl != artRequestedUrl || (artTries <= 3 && millis() - artRequestedAt > 15000)) {
// New track: ask for its picture, retry twice if no answer comes.
bool fresh = curArtUrl != artRequestedUrl;
artTries = fresh ? 1 : artTries + 1;
artRequestedUrl = curArtUrl;
artRequestedAt = millis();
if (artTries > 3) { setArt(false, "Keine Antwort vom Geraet"); continue; }
if (fresh) setArt(false, "Cover wird geladen ...");
Serial.printf("KDE: frage Cover an: %s\n", curArtUrl.c_str());
for (auto& p : peers) {
if (!p.used || !p.paired || p.id != curPeerId) continue;
JsonDocument b;
+126 -64
View File
@@ -46,7 +46,9 @@ 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];
static constexpr int DRAW_BUF_PX = SCREEN_W * 16;
static lv_color_t buf1[DRAW_BUF_PX];
static lv_color_t buf2[DRAW_BUF_PX];
// ---------------------------------------------------------------- State
static constexpr size_t MAX_CLIMATE = 8;
@@ -107,10 +109,9 @@ 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.dmaWait(); // the other buffer may still be on its way
tft.setAddrWindow(a->x1, a->y1, w, h);
tft.pushColors((uint16_t*)&px->full, w * h, true);
tft.endWrite();
tft.pushPixelsDMA((uint16_t*)&px->full, w * h);
lv_disp_flush_ready(drv);
}
@@ -177,21 +178,60 @@ static int haRequest(bool post, const String& path, const String& body, String*
return code;
}
// HTTP requests run in their own task so the UI never waits for the network.
// The callback runs later in the UI loop (haProcess) with the HTTP code and response body.
using HaCallback = std::function<void(int code, String& resp)>;
struct HaJob {
bool post;
String path, body, resp;
int code;
HaCallback cb;
};
static QueueHandle_t haJobs, haResults;
static int haInFlight = 0; // only touched by the UI loop
static void haTask(void*) {
for (;;) {
HaJob* j;
if (xQueueReceive(haJobs, &j, portMAX_DELAY) != pdTRUE) continue;
j->code = haRequest(j->post, j->path, j->body, &j->resp);
xQueueSend(haResults, &j, portMAX_DELAY);
}
}
static void haAsync(bool post, const String& path, const String& body, HaCallback cb) {
HaJob* j = new HaJob{post, path, body, "", 0, cb};
if (xQueueSend(haJobs, &j, 0) != pdTRUE) { delete j; return; }
haInFlight++;
}
static void haProcess() {
HaJob* j;
while (xQueueReceive(haResults, &j, 0) == pdTRUE) {
haInFlight--;
if (j->cb) j->cb(j->code, j->resp);
delete j;
}
}
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) {
static void callService(const char* domain, const char* service, JsonDocument& doc,
std::function<void()> onOk = nullptr) {
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;
String name = String(domain) + "." + service;
haAsync(true, String("/api/services/") + domain + "/" + service, body, [name, onOk](int code, String&) {
if (code != 200) {
Serial.printf("Service %s fehlgeschlagen: %d\n", name.c_str(), code);
setStatus(LV_SYMBOL_WARNING " Fehler", lv_palette_main(LV_PALETTE_RED));
} else if (onOk) {
onOk();
}
});
}
static String domainOf(const String& e) {
@@ -294,20 +334,20 @@ static void applyLight(size_t i, JsonDocument& doc) {
lv_obj_set_height(u.card, h);
}
static bool pollEntity(size_t idx) {
static void 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;
String entity = isClimate ? CLIMATES[idx].entity : LIGHTS[idx - N_CLIMATE].entity;
haAsync(false, String("/api/states/") + entity, "", [idx, isClimate, entity](int code, String& resp) {
JsonDocument doc;
if (code != 200 || deserializeJson(doc, resp)) {
Serial.printf("GET %s -> %d\n", entity.c_str(), code);
setStatus(LV_SYMBOL_WARNING " HA", lv_palette_main(LV_PALETTE_RED));
return;
}
if (isClimate) applyClimate(idx, doc);
else applyLight(idx - N_CLIMATE, doc);
setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN));
});
}
// ---------------------------------------------------------------- Events
@@ -372,8 +412,8 @@ static void onScene(lv_event_t* e) {
size_t i = (size_t)(intptr_t)lv_event_get_user_data(e);
JsonDocument doc;
doc["entity_id"] = SCENES[i].entity;
if (callService(domainOf(SCENES[i].entity).c_str(), "turn_on", doc))
setStatus(LV_SYMBOL_OK, lv_palette_main(LV_PALETTE_GREEN));
callService(domainOf(SCENES[i].entity).c_str(), "turn_on", doc,
[] { setStatus(LV_SYMBOL_OK, lv_palette_main(LV_PALETTE_GREEN)); });
}
// ---------------------------------------------------------------- UI construction
@@ -616,7 +656,7 @@ static String asciiName(const String& in) {
}
// Asks HA (template API) for all climate/light entities and builds the UI from them.
static bool discoverDevices() {
static void discoverDevices() {
#if INCLUDE_SWITCHES
const char* lightSrc = "(states.light | list + states.switch | list)";
#else
@@ -638,15 +678,16 @@ static bool discoverDevices() {
"} | tojson }}";
JsonDocument req;
req["template"] = tpl;
String body, resp;
String body;
serializeJson(req, body);
int code = haRequest(true, "/api/template", body, &resp);
haAsync(true, "/api/template", body, [](int code, String& resp) {
if (code != 200) {
Serial.printf("Geraete-Abfrage fehlgeschlagen: %d\n", code);
return false;
setStatus(LV_SYMBOL_WARNING " HA", lv_palette_main(LV_PALETTE_RED));
return;
}
JsonDocument doc;
if (deserializeJson(doc, resp)) { Serial.println("Geraete-Antwort ist kein JSON"); return false; }
if (deserializeJson(doc, resp)) { Serial.println("Geraete-Antwort ist kein JSON"); return; }
auto fill = [&](JsonArray ids, JsonArray names, Device* dst, size_t max) {
size_t n = 0;
@@ -669,7 +710,9 @@ static bool discoverDevices() {
(unsigned)N_SCENE, weatherEntity.c_str());
populateUi();
discoveredAt = millis();
return true;
discovered = true;
setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN));
});
}
// ---------------------------------------------------------------- Time zone
@@ -677,9 +720,10 @@ static bool discoverDevices() {
static void syncTimezone() {
JsonDocument req;
req["template"] = "{{ now().strftime('%z') }}";
String body, resp;
String body;
serializeJson(req, body);
if (haRequest(true, "/api/template", body, &resp) != 200) return;
haAsync(true, "/api/template", body, [](int code, String& resp) {
if (code != 200) return;
resp.trim();
if (resp.length() != 5 || (resp[0] != '+' && resp[0] != '-')) return;
int hh = resp.substring(1, 3).toInt(), mm = resp.substring(3, 5).toInt();
@@ -691,6 +735,7 @@ static void syncTimezone() {
setenv("TZ", tz, 1);
tzset();
}
});
}
// ---------------------------------------------------------------- Weather
@@ -712,16 +757,16 @@ static const char* weatherText(const char* c) {
static void pollWeather() {
if (!weatherEntity.length()) return;
String resp;
if (haRequest(false, "/api/states/" + weatherEntity, "", &resp) != 200) return;
haAsync(false, "/api/states/" + weatherEntity, "", [](int code, String& resp) {
JsonDocument doc;
if (deserializeJson(doc, resp)) return;
if (code != 200 || deserializeJson(doc, resp)) return;
float t = doc["attributes"]["temperature"] | NAN;
const char* cond = weatherText(doc["state"] | "");
char buf[40];
if (isnan(t)) snprintf(buf, sizeof buf, LV_SYMBOL_HOME " %s", cond);
else snprintf(buf, sizeof buf, LV_SYMBOL_HOME " %.0f° %s", t, cond);
lv_label_set_text(titleLabel, buf);
});
}
// ---------------------------------------------------------------- Temperature history
@@ -789,11 +834,11 @@ static void pollAlerts() {
{{ ns.a[:10] | tojson }})J";
JsonDocument req;
req["template"] = TPL;
String body, resp;
String body;
serializeJson(req, body);
if (haRequest(true, "/api/template", body, &resp) != 200) return;
haAsync(true, "/api/template", body, [](int code, String& resp) {
JsonDocument doc;
if (deserializeJson(doc, resp)) return;
if (code != 200 || deserializeJson(doc, resp)) return;
String fresh[MAX_ALERT];
size_t n = 0;
@@ -818,13 +863,14 @@ static void pollAlerts() {
setBacklight(true);
lv_disp_trig_activity(nullptr);
}
});
}
// ---------------------------------------------------------------- Music (KDE Connect)
// Full-screen overlay with four swipeable pages: clock, cover, controls, sources/settings.
static lv_obj_t *musicPanel, *musicTv, *pageDots[4];
static lv_obj_t *mClock, *mDate, *mSource, *mTitle, *mArtist, *mBar, *mPos, *mLen, *mPlayLbl; // page 1
static lv_obj_t *cArt, *cArtPh, *cTitle, *cArtist, *cAlbum, *cBar, *cPos, *cLen, *cPlayLbl; // page 2
static lv_obj_t *cArt, *cArtPh, *cArtInfo, *cTitle, *cArtist, *cAlbum, *cBar, *cPos, *cLen, *cPlayLbl; // page 2
static lv_obj_t *sVol, *sVolLbl, *sSeek, *sSeekLbl, *sPlayLbl; // page 3
static lv_obj_t *qList, *qAuto, *qSwShow, *qSwKeep; // page 4
static lv_img_dsc_t artDsc;
@@ -995,14 +1041,16 @@ static void buildMusicUi() {
lv_obj_set_style_pad_all(frame, 0, 0);
lv_obj_set_style_border_width(frame, 0, 0);
lv_obj_set_style_radius(frame, 8, 0);
lv_obj_set_style_clip_corner(frame, true, 0);
lv_obj_set_style_bg_color(frame, lv_color_hex(0x1c232b), 0);
lv_obj_clear_flag(frame, LV_OBJ_FLAG_SCROLLABLE);
cArtPh = lv_label_create(frame);
lv_obj_set_style_text_font(cArtPh, &lv_font_montserrat_48, 0);
lv_obj_set_style_text_color(cArtPh, lv_color_hex(0x3a444e), 0);
lv_label_set_text(cArtPh, LV_SYMBOL_AUDIO);
lv_obj_center(cArtPh);
lv_obj_align(cArtPh, LV_ALIGN_CENTER, 0, -14);
cArtInfo = label(frame, nullptr, grey(), KDE_ART_SIZE - 8, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(cArtInfo, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(cArtInfo, LV_ALIGN_BOTTOM_MID, 0, -6);
artDsc.header.always_zero = 0;
artDsc.header.cf = LV_IMG_CF_TRUE_COLOR;
artDsc.header.w = KDE_ART_SIZE;
@@ -1261,6 +1309,7 @@ static void updateMusic() {
}
if (np.artSeq != lastArt) {
lastArt = np.artSeq;
lv_label_set_text(cArtInfo, np.artInfo);
const uint16_t* art = kdeArt();
if (art) {
artDsc.data = (const uint8_t*)art;
@@ -1317,8 +1366,13 @@ void setup() {
ts.begin(touchSpi);
ts.setRotation(1);
// DMA: LVGL renders the next stripe while the previous one is still being sent to the display.
tft.setSwapBytes(true);
tft.initDMA();
tft.startWrite(); // keep the bus; nothing else uses the display SPI
lv_init();
lv_disp_draw_buf_init(&drawBuf, buf1, nullptr, SCREEN_W * 24);
lv_disp_draw_buf_init(&drawBuf, buf1, buf2, DRAW_BUF_PX);
static lv_disp_drv_t dispDrv;
lv_disp_drv_init(&dispDrv);
dispDrv.hor_res = SCREEN_W;
@@ -1331,10 +1385,25 @@ void setup() {
lv_indev_drv_init(&indevDrv);
indevDrv.type = LV_INDEV_TYPE_POINTER;
indevDrv.read_cb = touchRead;
indevDrv.scroll_limit = 18; // pixels of movement before a touch counts as scrolling (default 10)
indevDrv.scroll_throw = 8; // less inertia
indevDrv.scroll_limit = 12; // pixels of movement before a touch counts as scrolling (default 10)
indevDrv.scroll_throw = 12; // inertia after letting go (default 10)
lv_indev_drv_register(&indevDrv);
// No shadows: software-rendered shadows are the most expensive part of redrawing while scrolling.
static lv_style_t flat;
lv_style_init(&flat);
lv_style_set_shadow_width(&flat, 0);
static lv_theme_t flatTheme;
lv_theme_t* base = lv_disp_get_theme(nullptr);
flatTheme = *base;
lv_theme_set_parent(&flatTheme, base);
lv_theme_set_apply_cb(&flatTheme, [](lv_theme_t*, lv_obj_t* obj) { lv_obj_add_style(obj, &flat, 0); });
lv_disp_set_theme(nullptr, &flatTheme);
haJobs = xQueueCreate(16, sizeof(HaJob*));
haResults = xQueueCreate(16, sizeof(HaJob*));
xTaskCreatePinnedToCore(haTask, "ha", 10240, nullptr, 1, nullptr, 0);
buildUi();
buildMusicUi();
lv_timer_handler();
@@ -1379,21 +1448,17 @@ void loop() {
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; }
haProcess();
if (!connected) { delay(2); 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) {
if (!haInFlight && (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));
}
discoverDevices();
}
delay(5);
delay(2);
return;
}
@@ -1413,17 +1478,14 @@ void loop() {
// 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 &&
lv_disp_get_inactive_time(nullptr) > 700) { // a blocking HTTP call would make scrolling stutter
if (!haInFlight && !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));
pollEntity(pollIdx);
pollIdx = (pollIdx + 1) % (N_CLIMATE + N_LIGHT);
}
// Background jobs; the blocking HTTP calls only run while the user is not touching the screen.
if (screenOff || lv_disp_get_inactive_time(nullptr) > 700) {
// Background jobs (one request at a time)
if (!haInFlight) {
static uint32_t lastAlert = 0, lastWeather = 0;
static uint32_t lastTz = 0;
if (!lastTz || now - lastTz > 900000) { lastTz = now ? now : 1; syncTimezone(); }
@@ -1435,5 +1497,5 @@ void loop() {
lastHist = now ? now : 1;
sampleHistory();
}
delay(5);
delay(1);
}