Compare commits

...
5 Commits
6 changed files with 590 additions and 130 deletions

No files matched your search

+1 -1
View File
@@ -32,7 +32,7 @@ Hinweis: Die eingebaute Schrift hat keine Umlaute. Schreib die Namen also als "K
3. Auf dem Display **Koppeln** tippen. Die Kopplung wird gespeichert und überlebt Neustarts. 3. Auf dem Display **Koppeln** tippen. Die Kopplung wird gespeichert und überlebt Neustarts.
4. Android: Unter den Plugin-Einstellungen von „HomeBoard“ **Mediensteuerung empfangen** („Receive media control“) aktivieren und KDE Connect den Zugriff auf Benachrichtigungen erlauben, sonst sieht die App nicht, was spielt. 4. Android: Unter den Plugin-Einstellungen von „HomeBoard“ **Mediensteuerung empfangen** („Receive media control“) aktivieren und KDE Connect den Zugriff auf Benachrichtigungen erlauben, sonst sieht die App nicht, was spielt.
Titelbilder kommen nur, wenn der Player eins liefert, und nur als normales JPEG (kein Progressive-JPEG, kein PNG). Titelbilder kommen nur, wenn der Player eins liefert. Mit **micro-SD-Karte** im Slot (FAT32 oder FAT16, **kein exFAT**: Karten ab 64 GB vorher als FAT32 formatieren) des Boards werden Cover erst auf die Karte geladen und dann angezeigt: Das braucht deutlich weniger Arbeitsspeicher, unterstützt auch PNG, und bereits geladene Cover (Ordner `/covers`) kommen sofort ohne erneute Übertragung. Ohne Karte gehen nur normale JPEGs (kein Progressive-JPEG). Steht statt des Covers ein Text auf der Cover-Seite, ist das der Grund, warum es nicht geklappt hat.
Beim ersten Start erzeugt das Board einmalig ein Zertifikat (ein paar Sekunden). Ausschalten mit `KDE_CONNECT 0` in `config.h`. Beim ersten Start erzeugt das Board einmalig ein Zertifikat (ein paar Sekunden). Ausschalten mit `KDE_CONNECT 0` in `config.h`.
+5
View File
@@ -22,6 +22,7 @@ struct NowPlaying {
uint32_t seq = 0; // changes whenever title/artist/state/device/volume change uint32_t seq = 0; // changes whenever title/artist/state/device/volume change
uint32_t artSeq = 0; // changes whenever the album art buffer changes uint32_t artSeq = 0; // changes whenever the album art buffer changes
bool hasArt = false; bool hasArt = false;
char artInfo[48] = ""; // why there is no album art (shown instead of the picture)
}; };
struct PlayerEntry { struct PlayerEntry {
@@ -48,5 +49,9 @@ void kdeSeek(int32_t posMs);
int kdeListPlayers(PlayerEntry* out, int max); int kdeListPlayers(PlayerEntry* out, int max);
// Show this player instead of picking automatically (nullptr = automatic again). // Show this player instead of picking automatically (nullptr = automatic again).
void kdeSelectPlayer(const char* key); void kdeSelectPlayer(const char* key);
// The UI tells whether the cover is needed (music view open); otherwise its memory is released.
void kdeSetArtWanted(bool wanted);
// Status text for the display: connections, SD card, free memory, last error.
void kdeStatus(char* out, size_t n);
// Number of paired devices currently connected. // Number of paired devices currently connected.
int kdeConnectedCount(); int kdeConnectedCount();
+1
View File
@@ -31,6 +31,7 @@
#define LV_USE_THEME_DEFAULT 1 #define LV_USE_THEME_DEFAULT 1
#define LV_THEME_DEFAULT_DARK 1 #define LV_THEME_DEFAULT_DARK 1
#define LV_THEME_DEFAULT_TRANSITION_TIME 0 // no state-change animations (cheaper redraws)
#endif #endif
#endif #endif
+3 -1
View File
@@ -10,12 +10,14 @@ monitor_filters = esp32_exception_decoder
lib_deps = lib_deps =
bodmer/[email protected] bodmer/[email protected]
https://github.com/PaulStoffregen/XPT2046_Touchscreen.git#v1.4
lvgl/[email protected] lvgl/[email protected]
bblanchon/[email protected] bblanchon/[email protected]
bitbank2/[email protected]
build_flags = build_flags =
; LVGL: lv_conf.h aus include/ verwenden ; LVGL: lv_conf.h aus include/ verwenden
; PNGdec: lines up to 1024 px wide (cover art)
-D PNG_MAX_BUFFERED_PIXELS=8194
-D LV_CONF_INCLUDE_SIMPLE -D LV_CONF_INCLUDE_SIMPLE
-I include -I include
; TFT_eSPI: Setup direkt hier statt User_Setup.h ; TFT_eSPI: Setup direkt hier statt User_Setup.h
+346 -46
View File
@@ -22,12 +22,16 @@
#include <mbedtls/sha256.h> #include <mbedtls/sha256.h>
#include <mbedtls/error.h> #include <mbedtls/error.h>
#include <esp_heap_caps.h> #include <esp_heap_caps.h>
#include <SPI.h>
#include <SD.h>
#include <PNGdec.h>
#include <new>
extern "C" { extern "C" {
#include <esp32/rom/tjpgd.h> #include <esp32/rom/tjpgd.h>
} }
static constexpr int KDE_PORT = 1716; static constexpr int KDE_PORT = 1716;
static constexpr int MAX_PEERS = 3; static constexpr int MAX_PEERS = 2;
static constexpr int MAX_PLAYERS = 4; static constexpr int MAX_PLAYERS = 4;
static constexpr int MAX_TRUSTED = 8; static constexpr int MAX_TRUSTED = 8;
static constexpr size_t MAX_RX = 16384; static constexpr size_t MAX_RX = 16384;
@@ -85,6 +89,9 @@ static int nList = 0;
static uint16_t* artBuf = nullptr; static uint16_t* artBuf = nullptr;
static bool hasArt = false; static bool hasArt = false;
static uint32_t artSeq = 0; static uint32_t artSeq = 0;
static char artInfo[48] = "";
static uint32_t artRequestedAt = 0;
static int artTries = 0;
// Task-only state for album art // Task-only state for album art
static String curPeerId, curPlayer, curArtUrl, artLoadedUrl, artRequestedUrl; static String curPeerId, curPlayer, curArtUrl, artLoadedUrl, artRequestedUrl;
@@ -331,6 +338,10 @@ static void publish() {
n.seq = pub.seq + (changed ? 1 : 0); n.seq = pub.seq + (changed ? 1 : 0);
n.artSeq = artSeq; n.artSeq = artSeq;
n.hasArt = hasArt; 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; pub = n;
xSemaphoreGive(mtx); xSemaphoreGive(mtx);
} }
@@ -454,10 +465,17 @@ struct ArtCtx {
mbedtls_ssl_context* ssl; mbedtls_ssl_context* ssl;
int64_t left; int64_t left;
int S, ox, oy; int S, ox, oy;
BYTE head[4]; // first bytes, to recognise the format in error messages
int nHead;
File* file; // set: read from the SD card instead of TLS
}; };
static UINT artIn(JDEC* jd, BYTE* buf, UINT nd) { static UINT artIn(JDEC* jd, BYTE* buf, UINT nd) {
ArtCtx* c = (ArtCtx*)jd->device; ArtCtx* c = (ArtCtx*)jd->device;
if (c->file) {
if (!buf) { c->file->seek(c->file->position() + nd); return nd; }
return c->file->read(buf, nd);
}
static BYTE skip[64]; static BYTE skip[64];
UINT done = 0; UINT done = 0;
while (done < nd && c->left > 0) { while (done < nd && c->left > 0) {
@@ -467,6 +485,7 @@ static UINT artIn(JDEC* jd, BYTE* buf, UINT nd) {
int r = mbedtls_ssl_read(c->ssl, dst, want); 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 == MBEDTLS_ERR_SSL_WANT_READ || r == MBEDTLS_ERR_SSL_WANT_WRITE) continue;
if (r <= 0) break; if (r <= 0) break;
for (int k = 0; k < r && c->nHead < 4; k++) c->head[c->nHead++] = dst[k];
done += r; done += r;
c->left -= r; c->left -= r;
} }
@@ -491,50 +510,108 @@ static UINT artOut(JDEC* jd, void* bitmap, JRECT* rect) {
return 1; return 1;
} }
static void setArt(bool valid) { static void setArt(bool valid, const char* info) {
xSemaphoreTake(mtx, portMAX_DELAY); xSemaphoreTake(mtx, portMAX_DELAY);
hasArt = valid; hasArt = valid;
strncpy(artInfo, info, sizeof artInfo - 1);
artSeq++; artSeq++;
pub.artSeq = artSeq; pub.artSeq = artSeq;
pub.hasArt = hasArt; pub.hasArt = hasArt;
memcpy(pub.artInfo, artInfo, sizeof artInfo);
xSemaphoreGive(mtx);
if (info[0]) Serial.printf("KDE: Cover: %s\n", info);
}
// ---- SD card: covers are downloaded to /covers first and decoded from there afterwards, so the
// TLS connection (~40 KB) and the decoder + picture buffer never need memory at the same time.
// Downloaded covers stay on the card, the same album later needs no transfer at all.
static SPIClass sdSpi(VSPI);
static bool sdOk = false;
static volatile bool artWanted = false;
static char lastError[48] = "";
static void setLastError(const char* e) {
xSemaphoreTake(mtx, portMAX_DELAY);
strncpy(lastError, e, sizeof lastError - 1);
xSemaphoreGive(mtx); xSemaphoreGive(mtx);
} }
static bool downloadArt(Peer& p, int port, int64_t size) { static void initSd() {
if (size <= 0 || size > 2000000 || !p.ip) return false; sdSpi.begin(18, 19, 23, 5); // CYD micro-SD slot
if (!artBuf) artBuf = (uint16_t*)malloc(KDE_ART_SIZE * KDE_ART_SIZE * 2); // The card is only mounted while a cover is read or written: mounted it would permanently
if (!artBuf) return false; // take ~10 KB that the KDE connections need.
if (ESP.getFreeHeap() < 60000 || heap_caps_get_largest_free_block(MALLOC_CAP_8BIT) < 18000) { sdOk = SD.begin(5, sdSpi, 20000000, "/sd", 2);
Serial.printf("KDE: zu wenig Speicher fuer Titelbild (Heap %u)\n", ESP.getFreeHeap()); if (sdOk) {
return false; if (!SD.exists("/covers")) SD.mkdir("/covers");
SD.end();
} }
int fd = socket(AF_INET, SOCK_STREAM, 0); Serial.printf("KDE: SD-Karte %s\n", sdOk ? "gefunden, Cover werden dort gespeichert"
if (fd < 0) return false; : "nicht gefunden (FAT32 noetig, exFAT geht nicht)");
struct timeval tv = {5, 0}; }
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
sockaddr_in a = {};
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; }
mbedtls_net_context net; static bool sdMount() {
mbedtls_net_init(&net); return sdOk && SD.begin(5, sdSpi, 20000000, "/sd", 2);
net.fd = fd; }
mbedtls_ssl_context ssl;
mbedtls_ssl_init(&ssl); static void sdUnmount() {
bool ok = false; SD.end();
void* pool = nullptr; }
if (mbedtls_ssl_setup(&ssl, &conf) == 0) {
mbedtls_ssl_set_bio(&ssl, &net, mbedtls_net_send, mbedtls_net_recv, nullptr); static String artPath(const String& url) {
uint32_t start = millis(); unsigned char h[32];
int r; mbedtls_sha256_ret((const unsigned char*)url.c_str(), url.length(), h, 0);
while ((r = mbedtls_ssl_handshake(&ssl)) == MBEDTLS_ERR_SSL_WANT_READ || r == MBEDTLS_ERR_SSL_WANT_WRITE) char hex[17];
if (millis() - start > 8000) break; for (int i = 0; i < 8; i++) sprintf(hex + i * 2, "%02x", h[i]);
pool = r == 0 ? malloc(4096) : nullptr; return String("/covers/") + hex + ".img";
if (pool) { }
ArtCtx c = {&ssl, size, 0, 0, 0};
static bool allocArtBuf() {
if (!artBuf) artBuf = (uint16_t*)malloc(KDE_ART_SIZE * KDE_ART_SIZE * 2);
return artBuf != nullptr;
}
// PNG: one line at a time, scaled into artBuf like the JPEG path
struct PngCtx {
PNG* png;
uint16_t* line;
int S, ox, oy;
};
static void* pngOpen(const char* path, int32_t* size) {
File* f = new File(SD.open(path, FILE_READ));
if (!*f) { delete f; return nullptr; }
*size = f->size();
return f;
}
static void pngClose(void* h) { File* f = (File*)h; f->close(); delete f; }
static int32_t pngRead(PNGFILE* pf, uint8_t* buf, int32_t len) { return ((File*)pf->fHandle)->read(buf, len); }
static int32_t pngSeek(PNGFILE* pf, int32_t pos) { return ((File*)pf->fHandle)->seek(pos) ? pos : -1; }
static int pngDraw(PNGDRAW* d) {
PngCtx* c = (PngCtx*)d->pUser;
const int N = KDE_ART_SIZE;
int y = d->y;
if (y < c->oy || y >= c->oy + c->S) return 1;
c->png->getLineAsRGB565(d, c->line, PNG_RGB565_LITTLE_ENDIAN, 0xff000000);
int dy0 = ((y - c->oy) * N + c->S - 1) / c->S, dy1 = ((y + 1 - c->oy) * N + c->S - 1) / c->S;
for (int dy = dy0; dy < dy1 && dy < N; dy++)
for (int dx = 0; dx < N; dx++) artBuf[dy * N + dx] = c->line[c->ox + dx * c->S / N];
return 1;
}
static const char* decodeFile(const String& path) {
File f = SD.open(path, FILE_READ);
if (!f) return "Cover-Datei fehlt";
uint8_t head[4] = {0};
f.read(head, 4);
f.seek(0);
if (!allocArtBuf()) { f.close(); return "Zu wenig Speicher"; }
const char* err = nullptr;
if (head[0] == 0xFF && head[1] == 0xD8) {
void* pool = malloc(4096);
if (!pool) { f.close(); return "Zu wenig Speicher"; }
ArtCtx c = {nullptr, 0, 0, 0, 0, {0}, 0, &f};
JDEC jd; JDEC jd;
JRESULT jr = jd_prepare(&jd, artIn, pool, 4096, &c); JRESULT jr = jd_prepare(&jd, artIn, pool, 4096, &c);
if (jr == JDR_OK) { if (jr == JDR_OK) {
@@ -545,15 +622,173 @@ static bool downloadArt(Peer& p, int port, int64_t size) {
c.ox = (W - c.S) / 2; c.ox = (W - c.S) / 2;
c.oy = (H - c.S) / 2; c.oy = (H - c.S) / 2;
jr = jd_decomp(&jd, artOut, s); 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: JPEG-Fehler %d\n", (int)jr);
err = "JPEG-Format nicht unterstuetzt";
}
free(pool);
f.close();
} else if (head[0] == 0x89 && head[1] == 'P') {
f.close();
void* mem = malloc(sizeof(PNG));
if (!mem) return "Zu wenig Speicher fuer PNG";
PNG* png = new (mem) PNG();
if (png->open(path.c_str(), pngOpen, pngClose, pngRead, pngSeek, pngDraw) != PNG_SUCCESS) {
err = "PNG nicht lesbar";
} else {
int W = png->getWidth(), H = png->getHeight();
PngCtx c = {png, (uint16_t*)malloc(W * 2), 0, 0, 0};
c.S = min(W, H);
c.ox = (W - c.S) / 2;
c.oy = (H - c.S) / 2;
if (!c.line) err = "Zu wenig Speicher fuer PNG";
else if (png->decode(&c, 0) != PNG_SUCCESS) err = "PNG zu gross oder ungueltig";
free(c.line);
png->close();
}
png->~PNG();
free(mem);
} else {
f.close();
err = "Bildformat nicht unterstuetzt";
}
return err;
}
// Opens the payload connection the peer offered and returns it ready for reading (nullptr = error).
static const char* openPayload(Peer& p, int port, mbedtls_net_context& net, mbedtls_ssl_context& ssl) {
uint32_t freeHeap = ESP.getFreeHeap(), block = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
Serial.printf("KDE: Cover-Verbindung, Heap %u, groesster Block %u\n", freeHeap, block);
if (freeHeap < 52000 || block < 17500) return "Zu wenig Speicher";
int fd = socket(AF_INET, SOCK_STREAM, 0);
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);
sockaddr_in a = {};
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 "Keine Verbindung"; }
net.fd = fd;
if (mbedtls_ssl_setup(&ssl, &conf) != 0) return "Zu wenig Speicher";
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;
if (r != 0) {
char e[80];
mbedtls_strerror(r, e, sizeof e);
Serial.printf("KDE: Cover-TLS fehlgeschlagen: %s\n", e);
return "Verbindung abgelehnt";
}
return nullptr;
}
static const char* downloadToSd(Peer& p, int port, int64_t size, const String& path) {
if (size <= 0 || size > 4000000 || !p.ip) return "Ungueltige Bilddaten";
mbedtls_net_context net;
mbedtls_net_init(&net);
mbedtls_ssl_context ssl;
mbedtls_ssl_init(&ssl);
const char* err = openPayload(p, port, net, ssl);
if (!err) {
String tmp = path + ".tmp";
File f = SD.open(tmp, FILE_WRITE);
if (!f) {
err = "SD-Karte nicht beschreibbar";
} else {
static uint8_t buf[1024];
int64_t left = size;
while (left > 0) {
int r = mbedtls_ssl_read(&ssl, buf, (size_t)min<int64_t>(left, sizeof buf));
if (r == MBEDTLS_ERR_SSL_WANT_READ || r == MBEDTLS_ERR_SSL_WANT_WRITE) continue;
if (r <= 0) break;
f.write(buf, r);
left -= r;
}
f.close();
if (left > 0) { SD.remove(tmp); err = "Download abgebrochen"; }
else { SD.remove(path); SD.rename(tmp, path); }
}
}
// Free the TLS buffers before decoding.
mbedtls_ssl_free(&ssl);
mbedtls_net_free(&net);
return err;
}
// 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 "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 < 62000 || block < 17500) return "Zu wenig Speicher";
int fd = socket(AF_INET, SOCK_STREAM, 0);
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);
sockaddr_in a = {};
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 "Keine Verbindung"; }
mbedtls_net_context net;
mbedtls_net_init(&net);
net.fd = fd;
mbedtls_ssl_context ssl;
mbedtls_ssl_init(&ssl);
const char* err = nullptr;
void* pool = nullptr;
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;
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, nullptr};
JDEC jd;
JRESULT jr = jd_prepare(&jd, artIn, pool, 4096, &c);
if (jr == JDR_OK) {
int s = 0;
while (s < 3 && (int)(min(jd.width, jd.height) >> (s + 1)) >= KDE_ART_SIZE) s++;
int W = jd.width >> s, H = jd.height >> s;
c.S = min(W, H);
c.ox = (W - c.S) / 2;
c.oy = (H - c.S) / 2;
jr = jd_decomp(&jd, artOut, s);
}
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); free(pool);
mbedtls_ssl_free(&ssl); mbedtls_ssl_free(&ssl);
mbedtls_net_free(&net); mbedtls_net_free(&net);
return ok; return err;
} }
static void handlePacket(Peer& p, const String& line) { static void handlePacket(Peer& p, const String& line) {
@@ -601,9 +836,18 @@ static void handlePacket(Peer& p, const String& line) {
int port = d["payloadTransferInfo"]["port"] | 0; int port = d["payloadTransferInfo"]["port"] | 0;
String url = b["albumArtUrl"] | ""; String url = b["albumArtUrl"] | "";
if (port && (b["transferringAlbumArt"] | false) && p.id == curPeerId && url == curArtUrl) { if (port && (b["transferringAlbumArt"] | false) && p.id == curPeerId && url == curArtUrl) {
bool ok = downloadArt(p, port, d["payloadSize"] | (int64_t)0); int64_t size = d["payloadSize"] | (int64_t)0;
const char* err;
if (sdMount()) {
String path = artPath(url);
err = downloadToSd(p, port, size, path);
if (!err) err = decodeFile(path);
sdUnmount();
} else {
err = downloadArt(p, port, size);
}
artLoadedUrl = url; artLoadedUrl = url;
setArt(ok); setArt(!err, err ? err : "");
} }
} }
} }
@@ -648,8 +892,11 @@ static void acceptPeer(int fd) {
Peer* slot = nullptr; Peer* slot = nullptr;
for (auto& p : peers) if (p.used && p.id == id) closePeer(p); // reconnect replaces the old link for (auto& p : peers) if (p.used && p.id == id) closePeer(p); // reconnect replaces the old link
for (auto& p : peers) if (!p.used) { slot = &p; break; } for (auto& p : peers) if (!p.used) { slot = &p; break; }
if (!slot || ESP.getFreeHeap() < 45000) { // A connection needs ~40 KB; keep ~12 KB for WLAN and the HA requests.
Serial.printf("KDE: kein Platz fuer weitere Verbindung (Heap %u)\n", ESP.getFreeHeap()); if (!slot || ESP.getFreeHeap() < 52000 || heap_caps_get_largest_free_block(MALLOC_CAP_8BIT) < 17500) {
Serial.printf("KDE: %s abgewiesen (Heap %u, Block %u)\n", ascii(d["body"]["deviceName"] | "?").c_str(),
ESP.getFreeHeap(), heap_caps_get_largest_free_block(MALLOC_CAP_8BIT));
setLastError(!slot ? "Max. 2 Geraete gleichzeitig" : "Zu wenig Speicher fuer Verbindung");
close(fd); close(fd);
return; return;
} }
@@ -676,6 +923,8 @@ static void acceptPeer(int fd) {
char err[80]; char err[80];
mbedtls_strerror(r, err, sizeof err); mbedtls_strerror(r, err, sizeof err);
Serial.printf("KDE: TLS mit %s fehlgeschlagen: %s\n", p.name.c_str(), err); Serial.printf("KDE: TLS mit %s fehlgeschlagen: %s\n", p.name.c_str(), err);
setLastError(r == MBEDTLS_ERR_SSL_ALLOC_FAILED ? "Zu wenig Speicher fuer Verbindung"
: "Verschluesselung fehlgeschlagen");
closePeer(p); closePeer(p);
return; return;
} }
@@ -769,6 +1018,7 @@ static void pollUdp() {
static void kdeTask(void*) { static void kdeTask(void*) {
while (WiFi.status() != WL_CONNECTED) vTaskDelay(pdMS_TO_TICKS(500)); while (WiFi.status() != WL_CONNECTED) vTaskDelay(pdMS_TO_TICKS(500));
if (!initIdentity()) { Serial.println("KDE: Initialisierung fehlgeschlagen"); vTaskDelete(nullptr); } if (!initIdentity()) { Serial.println("KDE: Initialisierung fehlgeschlagen"); vTaskDelete(nullptr); }
initSd();
if (!openSockets()) { Serial.println("KDE: Ports nicht verfuegbar"); vTaskDelete(nullptr); } if (!openSockets()) { Serial.println("KDE: Ports nicht verfuegbar"); vTaskDelete(nullptr); }
uint32_t lastBroadcast = 0; uint32_t lastBroadcast = 0;
@@ -841,13 +1091,43 @@ static void kdeTask(void*) {
} }
if (selChanged) { selChanged = false; publish(); } if (selChanged) { selChanged = false; publish(); }
// Album art: ask for the picture of the track shown on the display // While the music view is closed the picture buffer (29 KB) is given back; with an SD card
if (curArtUrl != artLoadedUrl) { // the cover comes back from the card in a moment when the view opens again.
if (hasArt) setArt(false); if (!artWanted) {
if (artBuf && sdOk) {
setArt(false, "");
vTaskDelay(pdMS_TO_TICKS(100)); // let the UI drop its reference first
free(artBuf);
artBuf = nullptr;
artLoadedUrl = artRequestedUrl = "";
}
} else if (curArtUrl != artLoadedUrl) {
if (!curArtUrl.length()) { if (!curArtUrl.length()) {
if (hasArt) setArt(false, "");
artLoadedUrl = ""; 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;
if (fresh && sdMount()) {
String path = artPath(curArtUrl);
const char* err = "-";
if (SD.exists(path)) { // already on the card
err = decodeFile(path);
if (err) SD.remove(path); // broken file: fetch it again
}
sdUnmount();
if (!err) {
artRequestedUrl = artLoadedUrl = curArtUrl;
setArt(true, "");
continue;
}
}
artTries = fresh ? 1 : artTries + 1;
artRequestedUrl = curArtUrl; 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) { for (auto& p : peers) {
if (!p.used || !p.paired || p.id != curPeerId) continue; if (!p.used || !p.paired || p.id != curPeerId) continue;
JsonDocument b; JsonDocument b;
@@ -932,6 +1212,26 @@ void kdeSelectPlayer(const char* key) {
selChanged = true; selChanged = true;
} }
void kdeSetArtWanted(bool wanted) { artWanted = wanted; }
void kdeStatus(char* out, size_t n) {
if (!mtx) { snprintf(out, n, "KDE Connect: startet ..."); return; }
int conn = 0, all = 0;
String names;
for (auto& p : peers) { // read-only snapshot, good enough for a status line
if (!p.used) continue;
all++;
if (p.paired) { conn++; names += (names.length() ? ", " : "") + p.name; }
}
xSemaphoreTake(mtx, portMAX_DELAY);
snprintf(out, n, "KDE Connect: %d gekoppelt verbunden%s%s\nSD-Karte: %s - Speicher frei: %u KB%s%s", conn,
names.length() ? " (" : "", names.length() ? (names + ")").c_str() : "",
sdOk ? "ja" : "nein", (unsigned)(ESP.getFreeHeap() / 1024), lastError[0] ? "\nLetzter Fehler: " : "",
lastError);
xSemaphoreGive(mtx);
(void)all;
}
int kdeConnectedCount() { int kdeConnectedCount() {
if (!mtx) return 0; if (!mtx) return 0;
xSemaphoreTake(mtx, portMAX_DELAY); xSemaphoreTake(mtx, portMAX_DELAY);
+234 -82
View File
@@ -6,7 +6,6 @@
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <SPI.h> #include <SPI.h>
#include <TFT_eSPI.h> #include <TFT_eSPI.h>
#include <XPT2046_Touchscreen.h>
#include <lvgl.h> #include <lvgl.h>
#include <time.h> #include <time.h>
#include <Preferences.h> #include <Preferences.h>
@@ -42,11 +41,11 @@ static constexpr int XPT2046_CLK = 25;
static constexpr int XPT2046_CS = 33; static constexpr int XPT2046_CS = 33;
static TFT_eSPI tft; 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_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 // ---------------------------------------------------------------- State
static constexpr size_t MAX_CLIMATE = 8; static constexpr size_t MAX_CLIMATE = 8;
@@ -107,10 +106,9 @@ static bool swallowTouch = false;
// ---------------------------------------------------------------- Display / touch drivers // ---------------------------------------------------------------- Display / touch drivers
static void dispFlush(lv_disp_drv_t* drv, const lv_area_t* a, lv_color_t* px) { 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; 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.setAddrWindow(a->x1, a->y1, w, h);
tft.pushColors((uint16_t*)&px->full, w * h, true); tft.pushPixelsDMA((uint16_t*)&px->full, w * h);
tft.endWrite();
lv_disp_flush_ready(drv); lv_disp_flush_ready(drv);
} }
@@ -119,8 +117,55 @@ static void setBacklight(bool on) {
screenOff = !on; screenOff = !on;
} }
// XPT2046 via software SPI: the hardware SPI bus (VSPI) belongs to the SD card slot.
// Same command sequence as the XPT2046_Touchscreen library, so the calibration stays valid.
static uint16_t tpXfer16(uint16_t out, int bits = 16) {
uint16_t in = 0;
for (int i = bits - 1; i >= 0; i--) {
digitalWrite(XPT2046_MOSI, (out >> i) & 1);
delayMicroseconds(1);
digitalWrite(XPT2046_CLK, HIGH);
in = (in << 1) | digitalRead(XPT2046_MISO);
delayMicroseconds(1);
digitalWrite(XPT2046_CLK, LOW);
}
return in;
}
static int16_t bestTwoAvg(int16_t a, int16_t b, int16_t c) {
int16_t ab = abs(a - b), ac = abs(a - c), bc = abs(c - b);
if (ab <= ac && ab <= bc) return (a + b) >> 1;
if (ac <= ab && ac <= bc) return (a + c) >> 1;
return (b + c) >> 1;
}
static bool tpRead(int& rx, int& ry) {
if (digitalRead(XPT2046_IRQ) == HIGH) return false; // IRQ is low while touched
int16_t d[6] = {0};
digitalWrite(XPT2046_CS, LOW);
tpXfer16(0xB1, 8); // Z1 command (8 clocks, like the library)
int z = (tpXfer16(0xC1) >> 3) + 4095;
z -= tpXfer16(0x91) >> 3;
bool ok = z >= 400;
if (ok) {
tpXfer16(0x91); // first X is noisy
d[0] = tpXfer16(0xD1) >> 3;
d[1] = tpXfer16(0x91) >> 3;
d[2] = tpXfer16(0xD1) >> 3;
d[3] = tpXfer16(0x91) >> 3;
}
d[4] = tpXfer16(0xD0) >> 3; // power down
d[5] = tpXfer16(0) >> 3;
digitalWrite(XPT2046_CS, HIGH);
if (!ok) return false;
rx = bestTwoAvg(d[0], d[2], d[4]);
ry = bestTwoAvg(d[1], d[3], d[5]);
return true;
}
static void touchRead(lv_indev_drv_t*, lv_indev_data_t* data) { static void touchRead(lv_indev_drv_t*, lv_indev_data_t* data) {
bool pressed = ts.tirqTouched() && ts.touched(); int rx = 0, ry = 0;
bool pressed = tpRead(rx, ry);
if (!pressed) { if (!pressed) {
swallowTouch = false; swallowTouch = false;
data->state = LV_INDEV_STATE_REL; data->state = LV_INDEV_STATE_REL;
@@ -136,13 +181,9 @@ static void touchRead(lv_indev_drv_t*, lv_indev_data_t* data) {
data->state = LV_INDEV_STATE_REL; data->state = LV_INDEV_STATE_REL;
return; return;
} }
// Average a few samples: raw XPT2046 readings jitter, which makes taps look like drags. // A second sample against jitter (raw XPT2046 readings jitter, which makes taps look like drags).
int sx = 0, sy = 0, n = 0; int rx2, ry2;
for (int k = 0; k < 4; k++) { if (tpRead(rx2, ry2)) { rx = (rx + rx2) / 2; ry = (ry + ry2) / 2; }
TS_Point q = ts.getPoint();
sx += q.x; sy += q.y; n++;
}
int rx = sx / n, ry = sy / n;
if (TOUCH_SWAP_XY) std::swap(rx, ry); if (TOUCH_SWAP_XY) std::swap(rx, ry);
int x = map(rx, TOUCH_X_MIN, TOUCH_X_MAX, 0, SCREEN_W - 1); 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); int y = map(ry, TOUCH_Y_MIN, TOUCH_Y_MAX, 0, SCREEN_H - 1);
@@ -177,21 +218,69 @@ static int haRequest(bool post, const String& path, const String& body, String*
return code; 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) { static void setStatus(const char* txt, lv_color_t col) {
lv_label_set_text(statusLabel, txt); lv_label_set_text(statusLabel, txt);
lv_obj_set_style_text_color(statusLabel, col, 0); lv_obj_set_style_text_color(statusLabel, col, 0);
} }
static bool callService(const char* domain, const char* service, JsonDocument& doc) { // Shows the HTTP error code and the free memory, e.g. "HA -1 38K" (-1 = no connection, 401 = token).
static void haError(int code) {
char buf[32];
snprintf(buf, sizeof buf, LV_SYMBOL_WARNING " HA %d %uK", code, (unsigned)(ESP.getFreeHeap() / 1024));
setStatus(buf, lv_palette_main(LV_PALETTE_RED));
Serial.printf("HA-Fehler %d, Heap %u, groesster Block %u\n", code, ESP.getFreeHeap(),
heap_caps_get_largest_free_block(MALLOC_CAP_8BIT));
}
static void callService(const char* domain, const char* service, JsonDocument& doc,
std::function<void()> onOk = nullptr) {
String body; String body;
serializeJson(doc, body); serializeJson(doc, body);
int code = haRequest(true, String("/api/services/") + domain + "/" + service, body, nullptr); String name = String(domain) + "." + service;
haAsync(true, String("/api/services/") + domain + "/" + service, body, [name, onOk](int code, String&) {
if (code != 200) { if (code != 200) {
Serial.printf("Service %s.%s fehlgeschlagen: %d\n", domain, service, code); Serial.printf("Service %s fehlgeschlagen: %d\n", name.c_str(), code);
setStatus(LV_SYMBOL_WARNING " Fehler", lv_palette_main(LV_PALETTE_RED)); setStatus(LV_SYMBOL_WARNING " Fehler", lv_palette_main(LV_PALETTE_RED));
return false; } else if (onOk) {
onOk();
} }
return true; });
} }
static String domainOf(const String& e) { static String domainOf(const String& e) {
@@ -294,20 +383,20 @@ static void applyLight(size_t i, JsonDocument& doc) {
lv_obj_set_height(u.card, h); lv_obj_set_height(u.card, h);
} }
static bool pollEntity(size_t idx) { static void pollEntity(size_t idx) {
bool isClimate = idx < N_CLIMATE; bool isClimate = idx < N_CLIMATE;
const String& entity = isClimate ? CLIMATES[idx].entity : LIGHTS[idx - N_CLIMATE].entity; String entity = isClimate ? CLIMATES[idx].entity : LIGHTS[idx - N_CLIMATE].entity;
String resp; haAsync(false, String("/api/states/") + entity, "", [idx, isClimate, entity](int code, 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; JsonDocument doc;
if (deserializeJson(doc, resp)) return false; if (code != 200 || deserializeJson(doc, resp)) {
Serial.printf("GET %s -> %d\n", entity.c_str(), code);
haError(code);
return;
}
if (isClimate) applyClimate(idx, doc); if (isClimate) applyClimate(idx, doc);
else applyLight(idx - N_CLIMATE, doc); else applyLight(idx - N_CLIMATE, doc);
return true; setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN));
});
} }
// ---------------------------------------------------------------- Events // ---------------------------------------------------------------- Events
@@ -372,8 +461,8 @@ static void onScene(lv_event_t* e) {
size_t i = (size_t)(intptr_t)lv_event_get_user_data(e); size_t i = (size_t)(intptr_t)lv_event_get_user_data(e);
JsonDocument doc; JsonDocument doc;
doc["entity_id"] = SCENES[i].entity; doc["entity_id"] = SCENES[i].entity;
if (callService(domainOf(SCENES[i].entity).c_str(), "turn_on", doc)) callService(domainOf(SCENES[i].entity).c_str(), "turn_on", doc,
setStatus(LV_SYMBOL_OK, lv_palette_main(LV_PALETTE_GREEN)); [] { setStatus(LV_SYMBOL_OK, lv_palette_main(LV_PALETTE_GREEN)); });
} }
// ---------------------------------------------------------------- UI construction // ---------------------------------------------------------------- UI construction
@@ -405,6 +494,8 @@ static lv_obj_t* makeRoundBtn(lv_obj_t* parent, const char* sym, intptr_t ud) {
return b; return b;
} }
static void addKdeInfo();
static void buildUi() { static void buildUi() {
lv_obj_t* scr = lv_scr_act(); lv_obj_t* scr = lv_scr_act();
lv_obj_set_style_bg_color(scr, lv_color_hex(0x101418), 0); lv_obj_set_style_bg_color(scr, lv_color_hex(0x101418), 0);
@@ -471,6 +562,7 @@ static void buildUi() {
lv_label_set_text(hintHist, "Lade Geraete aus HA ..."); lv_label_set_text(hintHist, "Lade Geraete aus HA ...");
lv_obj_t* h = lv_label_create(tabAlert); lv_obj_t* h = lv_label_create(tabAlert);
lv_label_set_text(h, "Pruefe Hinweise ..."); lv_label_set_text(h, "Pruefe Hinweise ...");
addKdeInfo();
} }
static void populateUi() { static void populateUi() {
@@ -616,7 +708,7 @@ static String asciiName(const String& in) {
} }
// Asks HA (template API) for all climate/light entities and builds the UI from them. // Asks HA (template API) for all climate/light entities and builds the UI from them.
static bool discoverDevices() { static void discoverDevices() {
#if INCLUDE_SWITCHES #if INCLUDE_SWITCHES
const char* lightSrc = "(states.light | list + states.switch | list)"; const char* lightSrc = "(states.light | list + states.switch | list)";
#else #else
@@ -638,15 +730,16 @@ static bool discoverDevices() {
"} | tojson }}"; "} | tojson }}";
JsonDocument req; JsonDocument req;
req["template"] = tpl; req["template"] = tpl;
String body, resp; String body;
serializeJson(req, body); serializeJson(req, body);
int code = haRequest(true, "/api/template", body, &resp); haAsync(true, "/api/template", body, [](int code, String& resp) {
if (code != 200) { if (code != 200) {
Serial.printf("Geraete-Abfrage fehlgeschlagen: %d\n", code); Serial.printf("Geraete-Abfrage fehlgeschlagen: %d\n", code);
return false; haError(code);
return;
} }
JsonDocument doc; 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) { auto fill = [&](JsonArray ids, JsonArray names, Device* dst, size_t max) {
size_t n = 0; size_t n = 0;
@@ -669,7 +762,9 @@ static bool discoverDevices() {
(unsigned)N_SCENE, weatherEntity.c_str()); (unsigned)N_SCENE, weatherEntity.c_str());
populateUi(); populateUi();
discoveredAt = millis(); discoveredAt = millis();
return true; discovered = true;
setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN));
});
} }
// ---------------------------------------------------------------- Time zone // ---------------------------------------------------------------- Time zone
@@ -677,9 +772,10 @@ static bool discoverDevices() {
static void syncTimezone() { static void syncTimezone() {
JsonDocument req; JsonDocument req;
req["template"] = "{{ now().strftime('%z') }}"; req["template"] = "{{ now().strftime('%z') }}";
String body, resp; String body;
serializeJson(req, 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(); resp.trim();
if (resp.length() != 5 || (resp[0] != '+' && resp[0] != '-')) return; if (resp.length() != 5 || (resp[0] != '+' && resp[0] != '-')) return;
int hh = resp.substring(1, 3).toInt(), mm = resp.substring(3, 5).toInt(); int hh = resp.substring(1, 3).toInt(), mm = resp.substring(3, 5).toInt();
@@ -691,6 +787,7 @@ static void syncTimezone() {
setenv("TZ", tz, 1); setenv("TZ", tz, 1);
tzset(); tzset();
} }
});
} }
// ---------------------------------------------------------------- Weather // ---------------------------------------------------------------- Weather
@@ -712,16 +809,16 @@ static const char* weatherText(const char* c) {
static void pollWeather() { static void pollWeather() {
if (!weatherEntity.length()) return; if (!weatherEntity.length()) return;
String resp; haAsync(false, "/api/states/" + weatherEntity, "", [](int code, String& resp) {
if (haRequest(false, "/api/states/" + weatherEntity, "", &resp) != 200) return;
JsonDocument doc; JsonDocument doc;
if (deserializeJson(doc, resp)) return; if (code != 200 || deserializeJson(doc, resp)) return;
float t = doc["attributes"]["temperature"] | NAN; float t = doc["attributes"]["temperature"] | NAN;
const char* cond = weatherText(doc["state"] | ""); const char* cond = weatherText(doc["state"] | "");
char buf[40]; char buf[40];
if (isnan(t)) snprintf(buf, sizeof buf, LV_SYMBOL_HOME " %s", cond); if (isnan(t)) snprintf(buf, sizeof buf, LV_SYMBOL_HOME " %s", cond);
else snprintf(buf, sizeof buf, LV_SYMBOL_HOME " %.0f° %s", t, cond); else snprintf(buf, sizeof buf, LV_SYMBOL_HOME " %.0f° %s", t, cond);
lv_label_set_text(titleLabel, buf); lv_label_set_text(titleLabel, buf);
});
} }
// ---------------------------------------------------------------- Temperature history // ---------------------------------------------------------------- Temperature history
@@ -753,8 +850,34 @@ static void sampleHistory() {
} }
// ---------------------------------------------------------------- Alerts // ---------------------------------------------------------------- Alerts
static void showAlertList();
static lv_obj_t* kdeInfo = nullptr;
static void updateKdeInfo() {
if (!kdeInfo) return;
char buf[200];
kdeStatus(buf, sizeof buf);
lv_label_set_text(kdeInfo, buf);
}
static void addKdeInfo() {
#if KDE_CONNECT
kdeInfo = lv_label_create(tabAlert);
lv_obj_set_width(kdeInfo, lv_pct(100));
lv_label_set_long_mode(kdeInfo, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_color(kdeInfo, lv_palette_lighten(LV_PALETTE_GREY, 1), 0);
updateKdeInfo();
#endif
}
static void showAlerts() { static void showAlerts() {
lv_obj_clean(tabAlert); lv_obj_clean(tabAlert);
kdeInfo = nullptr;
showAlertList();
addKdeInfo();
}
static void showAlertList() {
if (!nAlerts) { if (!nAlerts) {
lv_obj_t* l = lv_label_create(tabAlert); lv_obj_t* l = lv_label_create(tabAlert);
lv_obj_set_style_text_color(l, lv_palette_main(LV_PALETTE_GREEN), 0); lv_obj_set_style_text_color(l, lv_palette_main(LV_PALETTE_GREEN), 0);
@@ -789,11 +912,11 @@ static void pollAlerts() {
{{ ns.a[:10] | tojson }})J"; {{ ns.a[:10] | tojson }})J";
JsonDocument req; JsonDocument req;
req["template"] = TPL; req["template"] = TPL;
String body, resp; String body;
serializeJson(req, body); serializeJson(req, body);
if (haRequest(true, "/api/template", body, &resp) != 200) return; haAsync(true, "/api/template", body, [](int code, String& resp) {
JsonDocument doc; JsonDocument doc;
if (deserializeJson(doc, resp)) return; if (code != 200 || deserializeJson(doc, resp)) return;
String fresh[MAX_ALERT]; String fresh[MAX_ALERT];
size_t n = 0; size_t n = 0;
@@ -818,13 +941,14 @@ static void pollAlerts() {
setBacklight(true); setBacklight(true);
lv_disp_trig_activity(nullptr); lv_disp_trig_activity(nullptr);
} }
});
} }
// ---------------------------------------------------------------- Music (KDE Connect) // ---------------------------------------------------------------- Music (KDE Connect)
// Full-screen overlay with four swipeable pages: clock, cover, controls, sources/settings. // Full-screen overlay with four swipeable pages: clock, cover, controls, sources/settings.
static lv_obj_t *musicPanel, *musicTv, *pageDots[4]; 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 *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 *sVol, *sVolLbl, *sSeek, *sSeekLbl, *sPlayLbl; // page 3
static lv_obj_t *qList, *qAuto, *qSwShow, *qSwKeep; // page 4 static lv_obj_t *qList, *qAuto, *qSwShow, *qSwKeep; // page 4
static lv_img_dsc_t artDsc; static lv_img_dsc_t artDsc;
@@ -842,8 +966,12 @@ static void wakeScreen() {
lv_disp_trig_activity(nullptr); lv_disp_trig_activity(nullptr);
} }
static uint32_t musicShownAt = 0;
static void showMusic(bool show) { static void showMusic(bool show) {
if (show && !musicVisible) musicShownAt = millis();
musicVisible = show; musicVisible = show;
kdeSetArtWanted(show);
if (show) lv_obj_clear_flag(musicPanel, LV_OBJ_FLAG_HIDDEN); if (show) lv_obj_clear_flag(musicPanel, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(musicPanel, LV_OBJ_FLAG_HIDDEN); else lv_obj_add_flag(musicPanel, LV_OBJ_FLAG_HIDDEN);
} }
@@ -995,14 +1123,16 @@ static void buildMusicUi() {
lv_obj_set_style_pad_all(frame, 0, 0); lv_obj_set_style_pad_all(frame, 0, 0);
lv_obj_set_style_border_width(frame, 0, 0); lv_obj_set_style_border_width(frame, 0, 0);
lv_obj_set_style_radius(frame, 8, 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_set_style_bg_color(frame, lv_color_hex(0x1c232b), 0);
lv_obj_clear_flag(frame, LV_OBJ_FLAG_SCROLLABLE); lv_obj_clear_flag(frame, LV_OBJ_FLAG_SCROLLABLE);
cArtPh = lv_label_create(frame); cArtPh = lv_label_create(frame);
lv_obj_set_style_text_font(cArtPh, &lv_font_montserrat_48, 0); 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_obj_set_style_text_color(cArtPh, lv_color_hex(0x3a444e), 0);
lv_label_set_text(cArtPh, LV_SYMBOL_AUDIO); 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.always_zero = 0;
artDsc.header.cf = LV_IMG_CF_TRUE_COLOR; artDsc.header.cf = LV_IMG_CF_TRUE_COLOR;
artDsc.header.w = KDE_ART_SIZE; artDsc.header.w = KDE_ART_SIZE;
@@ -1213,11 +1343,15 @@ static void updateMusic() {
static uint32_t lastSeq = 0, lastArt = 0; static uint32_t lastSeq = 0, lastArt = 0;
static String lastTitle; static String lastTitle;
static bool lastPlaying = false; static bool lastPlaying = false;
static uint32_t stoppedAt = 0; static uint32_t lastActive = 0; // last time something was playing
kdeGetNowPlaying(np); kdeGetNowPlaying(np);
bool active = np.valid && np.playing;
// Short gaps (a device reconnecting, track change) do not count as "stopped".
bool resumed = active && (lastActive == 0 || millis() - lastActive > 10000);
if (active) lastActive = millis();
if (np.seq != lastSeq) { if (np.seq != lastSeq) {
lastSeq = np.seq; lastSeq = np.seq;
bool newTrack = np.valid && np.playing && (!lastPlaying || lastTitle != np.title); bool newTrack = active && (resumed || (lastTitle.length() && lastTitle != np.title) || !lastTitle.length());
if (np.valid) { if (np.valid) {
const char* pin = np.pinned ? " " LV_SYMBOL_EYE_OPEN : ""; const char* pin = np.pinned ? " " LV_SYMBOL_EYE_OPEN : "";
if (np.player[0] && strcmp(np.player, np.device)) if (np.player[0] && strcmp(np.player, np.device))
@@ -1252,15 +1386,13 @@ static void updateMusic() {
showMusic(true); showMusic(true);
wakeScreen(); wakeScreen();
} }
if (lastPlaying && !np.playing) { if (lastPlaying && !active && musicVisible) lv_disp_trig_activity(nullptr); // screen timeout starts now
stoppedAt = millis(); lastPlaying = active;
if (musicVisible) lv_disp_trig_activity(nullptr); // screen timeout starts counting now if (np.valid) lastTitle = np.title;
}
lastPlaying = np.valid && np.playing;
lastTitle = np.title;
} }
if (np.artSeq != lastArt) { if (np.artSeq != lastArt) {
lastArt = np.artSeq; lastArt = np.artSeq;
lv_label_set_text(cArtInfo, np.artInfo);
const uint16_t* art = kdeArt(); const uint16_t* art = kdeArt();
if (art) { if (art) {
artDsc.data = (const uint8_t*)art; artDsc.data = (const uint8_t*)art;
@@ -1274,7 +1406,9 @@ static void updateMusic() {
lv_obj_clear_flag(cArtPh, LV_OBJ_FLAG_HIDDEN); lv_obj_clear_flag(cArtPh, LV_OBJ_FLAG_HIDDEN);
} }
} }
if (musicVisible && (!np.valid || (!np.playing && millis() - stoppedAt > MUSIC_HIDE_S * 1000UL))) // Close only after nothing has played for MUSIC_HIDE_S (counted from opening if opened while paused).
uint32_t since = max(lastActive, musicShownAt);
if (musicVisible && !active && millis() - since > MUSIC_HIDE_S * 1000UL)
showMusic(false); showMusic(false);
// Clock, date and progress // Clock, date and progress
@@ -1313,12 +1447,21 @@ void setup() {
pinMode(TFT_BL, OUTPUT); pinMode(TFT_BL, OUTPUT);
setBacklight(true); setBacklight(true);
touchSpi.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS); pinMode(XPT2046_CLK, OUTPUT);
ts.begin(touchSpi); pinMode(XPT2046_MOSI, OUTPUT);
ts.setRotation(1); pinMode(XPT2046_CS, OUTPUT);
pinMode(XPT2046_MISO, INPUT);
pinMode(XPT2046_IRQ, INPUT);
digitalWrite(XPT2046_CS, HIGH);
digitalWrite(XPT2046_CLK, LOW);
// 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_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; static lv_disp_drv_t dispDrv;
lv_disp_drv_init(&dispDrv); lv_disp_drv_init(&dispDrv);
dispDrv.hor_res = SCREEN_W; dispDrv.hor_res = SCREEN_W;
@@ -1331,10 +1474,25 @@ void setup() {
lv_indev_drv_init(&indevDrv); lv_indev_drv_init(&indevDrv);
indevDrv.type = LV_INDEV_TYPE_POINTER; indevDrv.type = LV_INDEV_TYPE_POINTER;
indevDrv.read_cb = touchRead; indevDrv.read_cb = touchRead;
indevDrv.scroll_limit = 18; // pixels of movement before a touch counts as scrolling (default 10) indevDrv.scroll_limit = 12; // pixels of movement before a touch counts as scrolling (default 10)
indevDrv.scroll_throw = 8; // less inertia indevDrv.scroll_throw = 12; // inertia after letting go (default 10)
lv_indev_drv_register(&indevDrv); 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", 8192, nullptr, 1, nullptr, 0);
buildUi(); buildUi();
buildMusicUi(); buildMusicUi();
lv_timer_handler(); lv_timer_handler();
@@ -1359,11 +1517,12 @@ void loop() {
updateMusic(); updateMusic();
} }
// WiFi signal strength // WiFi signal strength, KDE status
static uint32_t lastRssi = 0; static uint32_t lastRssi = 0;
if (now - lastRssi > 2000) { if (now - lastRssi > 2000) {
lastRssi = now; lastRssi = now;
updateRssi(); updateRssi();
updateKdeInfo();
} }
// Backlight timeout // Backlight timeout
@@ -1379,21 +1538,17 @@ void loop() {
if (connected) setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN)); if (connected) setStatus(LV_SYMBOL_WIFI, lv_palette_main(LV_PALETTE_GREEN));
else setStatus(LV_SYMBOL_WIFI " offline", lv_palette_main(LV_PALETTE_RED)); 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) // Discover devices from HA (retry every 10 s until it works)
static uint32_t lastDiscover = 0; static uint32_t lastDiscover = 0;
if (!discovered) { if (!discovered) {
if (lastDiscover == 0 || now - lastDiscover > 10000) { if (!haInFlight && (lastDiscover == 0 || now - lastDiscover > 10000)) {
lastDiscover = now ? now : 1; lastDiscover = now ? now : 1;
if (discoverDevices()) { 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(2);
delay(5);
return; return;
} }
@@ -1413,17 +1568,14 @@ void loop() {
// Round-robin polling (paused while the screen is off; starts with a full pass) // Round-robin polling (paused while the screen is off; starts with a full pass)
static uint32_t lastPoll = 0; static uint32_t lastPoll = 0;
static size_t pollIdx = 0; static size_t pollIdx = 0;
if (!screenOff && (N_CLIMATE + N_LIGHT) > 0 && now - lastPoll > POLL_STEP_MS && if (!haInFlight && !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
lastPoll = now; lastPoll = now;
bool ok = pollEntity(pollIdx); 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); pollIdx = (pollIdx + 1) % (N_CLIMATE + N_LIGHT);
} }
// Background jobs; the blocking HTTP calls only run while the user is not touching the screen. // Background jobs (one request at a time)
if (screenOff || lv_disp_get_inactive_time(nullptr) > 700) { if (!haInFlight) {
static uint32_t lastAlert = 0, lastWeather = 0; static uint32_t lastAlert = 0, lastWeather = 0;
static uint32_t lastTz = 0; static uint32_t lastTz = 0;
if (!lastTz || now - lastTz > 900000) { lastTz = now ? now : 1; syncTimezone(); } if (!lastTz || now - lastTz > 900000) { lastTz = now ? now : 1; syncTimezone(); }
@@ -1435,5 +1587,5 @@ void loop() {
lastHist = now ? now : 1; lastHist = now ? now : 1;
sampleHistory(); sampleHistory();
} }
delay(5); delay(1);
} }