diff --git a/README.md b/README.md index afd28c4..dc4f5c7 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Touch-Dashboard für das ESP32-2432S028R ("Cheap Yellow Display"), das Heizkörp - **Verlauf-Tab:** Temperaturkurve aller Heizungen der letzten 24 h (alle 10 min ein Punkt). Die Daten sammelt das Board selbst und sie gehen beim Neustart verloren. - **Wetter:** Außentemperatur und Zustand der ersten `weather.*`-Entität oben links, alle 10 min aktualisiert. - **Hinweise (Glocken-Tab):** Offene Fenster/Türen (mit Warnung, wenn dabei geheizt wird), offline Heizungen/Lampen, Batterien unter 20 % und HA-Benachrichtigungen. Bei Hinweisen erscheint eine rote Glocke mit Anzahl in der Kopfzeile, und ein neuer Hinweis weckt das Display. +- **Musik über KDE Connect:** Das Board meldet sich im Netz als KDE-Connect-Gerät „HomeBoard“. Mehrere Handys/PCs können gekoppelt werden (bis zu 3 gleichzeitig verbunden). Startet auf einem davon Musik, geht das Display an und zeigt groß Uhrzeit und Datum, Titel, Interpret, Quelle (Player + Gerät) und Fortschritt, dazu Zurück/Pause/Weiter. Solange Musik läuft, bleibt das Display an; 60 s nach Pause/Stopp schließt sich die Ansicht. Tippen auf die Uhr in der Kopfzeile öffnet sie wieder. - Uhrzeit über NTP, WLAN-Signalstärke (Balken + dBm), WLAN- und HA-Status, Display geht nach 60 s ohne Bedienung aus (Tippen weckt es wieder). ## Einrichtung @@ -18,6 +19,15 @@ Touch-Dashboard für das ESP32-2432S028R ("Cheap Yellow Display"), das Heizkörp Hinweis: Die eingebaute Schrift hat keine Umlaute. Schreib die Namen also als "Kueche" statt "Küche". +## KDE Connect koppeln + +1. Board und Gerät müssen im selben WLAN sein (UDP/TCP-Port 1716). +2. In der KDE-Connect-App (Android) bzw. in den Systemeinstellungen (KDE/Windows) erscheint „HomeBoard“ → **Kopplung anfordern**. +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. + +Beim ersten Start erzeugt das Board einmalig ein Zertifikat (ein paar Sekunden). Ausschalten mit `KDE_CONNECT 0` in `config.h`. + ## Wenn etwas nicht passt | Problem | Lösung in `config.h` | diff --git a/include/config.example.h b/include/config.example.h index f77c284..5d3b42b 100644 --- a/include/config.example.h +++ b/include/config.example.h @@ -25,6 +25,12 @@ #define SCREEN_TIMEOUT_S 60 // backlight off after X s without touch (0 = never) #define TIMEZONE "CET-1CEST,M3.5.0,M10.5.0/3" +// ---- KDE Connect (Musik-Anzeige) ---- +#define KDE_CONNECT 1 // 0 = aus +#define KDE_DEVICE_NAME "HomeBoard" // so erscheint das Display in KDE Connect (keine Sonderzeichen) +#define MUSIC_KEEP_SCREEN_ON 1 // Display bleibt an, solange Musik laeuft +#define MUSIC_HIDE_S 60 // Musik-Ansicht X s nach Pause/Stopp schliessen + // ---- Display / Touch (only change these if something is off) ---- #define TFT_INVERT 0 // 1 if the colours look inverted #define TOUCH_X_MIN 200 diff --git a/include/kdeconnect.h b/include/kdeconnect.h new file mode 100644 index 0000000..d2a276d --- /dev/null +++ b/include/kdeconnect.h @@ -0,0 +1,27 @@ +// Minimal KDE Connect client: pairing + MPRIS (what is playing where). +// Runs in its own FreeRTOS task; the functions below are safe to call from the UI loop. +#pragma once +#include +#include + +struct NowPlaying { + bool valid = false; // something is known (playing or paused) + bool playing = false; + char device[33] = ""; + char player[33] = ""; + char title[97] = ""; + char artist[65] = ""; + int32_t posMs = 0, lenMs = 0; // position at atMs (millis()) + uint32_t atMs = 0; + uint32_t seq = 0; // changes whenever title/artist/state/device change +}; + +void kdeStart(const char* deviceName); +void kdeGetNowPlaying(NowPlaying& out); +// Returns a non-zero id while a pairing request waits for an answer and copies the device name. +uint32_t kdePairRequest(char* name, size_t n); +void kdeAnswerPair(bool accept); +// "PlayPause", "Next", "Previous" for the player shown in kdeGetNowPlaying. +void kdeMediaAction(const char* action); +// Number of paired devices currently connected. +int kdeConnectedCount(); diff --git a/include/lv_conf.h b/include/lv_conf.h index f9f3f8c..5709f8b 100644 --- a/include/lv_conf.h +++ b/include/lv_conf.h @@ -26,6 +26,7 @@ #define LV_FONT_MONTSERRAT_14 1 #define LV_FONT_MONTSERRAT_20 1 #define LV_FONT_MONTSERRAT_28 1 +#define LV_FONT_MONTSERRAT_48 1 #define LV_FONT_DEFAULT &lv_font_montserrat_14 #define LV_USE_THEME_DEFAULT 1 diff --git a/src/kdeconnect.cpp b/src/kdeconnect.cpp new file mode 100644 index 0000000..be0a24d --- /dev/null +++ b/src/kdeconnect.cpp @@ -0,0 +1,699 @@ +// Minimal KDE Connect implementation (protocol 7/8) for the ESP32. +// +// Discovery: we broadcast our identity via UDP 1716 and answer identity broadcasts of other devices +// with a unicast identity. The other device then opens a TCP connection to our port 1716, sends its +// identity in plain text and starts TLS as *server*; we are always the TLS client. +// Supported packets: kdeconnect.identity, kdeconnect.pair, kdeconnect.mpris(.request). +#include "kdeconnect.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static constexpr int KDE_PORT = 1716; +static constexpr int MAX_PEERS = 3; +static constexpr int MAX_PLAYERS = 4; +static constexpr int MAX_TRUSTED = 8; +static constexpr size_t MAX_RX = 16384; + +struct Player { + String name, title, artist; + bool playing = false; + int32_t pos = 0, len = 0; + uint32_t at = 0, startedAt = 0; +}; + +struct Peer { + bool used = false; + mbedtls_net_context net; + mbedtls_ssl_context ssl; + String id, name, fp, rx; + int proto = 7; + bool paired = false; + bool sentUnpair = false; + Player pl[MAX_PLAYERS]; + int nPl = 0; +}; + +static Peer peers[MAX_PEERS]; +static String deviceId, deviceName; +static String trustId[MAX_TRUSTED], trustFp[MAX_TRUSTED]; +static int nTrust = 0; + +static mbedtls_entropy_context entropy; +static mbedtls_ctr_drbg_context drbg; +static mbedtls_ssl_config conf; +static mbedtls_x509_crt ownCrt; +static mbedtls_pk_context ownKey; +static int udpFd = -1, tcpFd = -1; + +// Shared with the UI task +static SemaphoreHandle_t mtx; +static NowPlaying pub; +static String pubPeerId, pubPlayer; +static uint32_t pairId = 0, pairCounter = 0; +static String pairPeerId; +static char pairName[33]; +static int pairAnswer = 0; // 0 none, 1 accept, 2 reject +static char pendingAction[16] = ""; +static int connectedPaired = 0; + +// ---------------------------------------------------------------- Helpers +static int64_t packetId() { + time_t t = time(nullptr); + return t > 1600000000 ? (int64_t)t * 1000 + millis() % 1000 : (int64_t)millis(); +} + +static void copyStr(char* dst, size_t n, const String& s) { + strncpy(dst, s.c_str(), n - 1); + dst[n - 1] = 0; +} + +// The display font has no umlauts: convert them and drop other non-ASCII characters. +static String ascii(const char* in) { + String out; + for (const uint8_t* p = (const uint8_t*)in; *p; p++) { + if (*p < 0x80) { out += (char)*p; continue; } + if (*p == 0xC3 && p[1]) { + switch (*++p) { + 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; + case 0xA9: case 0xA8: out += "e"; break; case 0xA1: case 0xA0: out += "a"; break; + } + } else if (*p == 0xE2 && p[1] == 0x80 && (p[2] == 0x93 || p[2] == 0x94)) { + out += '-'; p += 2; // en/em dash + } else if (*p == 0xE2 && p[1] == 0x80 && (p[2] == 0x98 || p[2] == 0x99)) { + out += '\''; p += 2; + } + } + out.trim(); + return out; +} + +static String identityJson(bool newline) { + JsonDocument d; + d["id"] = packetId(); + d["type"] = "kdeconnect.identity"; + JsonObject b = d["body"].to(); + b["deviceId"] = deviceId; + b["deviceName"] = deviceName; + b["deviceType"] = "desktop"; + b["protocolVersion"] = 8; + b["tcpPort"] = KDE_PORT; + b["incomingCapabilities"].to().add("kdeconnect.mpris"); + b["outgoingCapabilities"].to().add("kdeconnect.mpris.request"); + String s; + serializeJson(d, s); + if (newline) s += '\n'; + return s; +} + +// ---------------------------------------------------------------- Identity / certificate +static void loadTrust(Preferences& p) { + String t = p.getString("trust", ""); + nTrust = 0; + int start = 0; + while (start < (int)t.length() && nTrust < MAX_TRUSTED) { + int end = t.indexOf(';', start); + if (end < 0) end = t.length(); + String e = t.substring(start, end); + int c = e.indexOf(','); + if (c > 0) { trustId[nTrust] = e.substring(0, c); trustFp[nTrust] = e.substring(c + 1); nTrust++; } + start = end + 1; + } +} + +static void saveTrust() { + String t; + for (int i = 0; i < nTrust; i++) t += trustId[i] + "," + trustFp[i] + ";"; + Preferences p; + p.begin("kdec", false); + p.putString("trust", t); + p.end(); +} + +static bool isTrusted(const String& id, const String& fp) { + for (int i = 0; i < nTrust; i++) if (trustId[i] == id && trustFp[i] == fp) return true; + return false; +} + +static void setTrust(const String& id, const String& fp, bool trusted) { + for (int i = 0; i < nTrust; i++) { + if (trustId[i] != id) continue; + for (int j = i; j < nTrust - 1; j++) { trustId[j] = trustId[j + 1]; trustFp[j] = trustFp[j + 1]; } + nTrust--; + break; + } + if (trusted) { + if (nTrust == MAX_TRUSTED) { // forget the oldest + for (int j = 0; j < nTrust - 1; j++) { trustId[j] = trustId[j + 1]; trustFp[j] = trustFp[j + 1]; } + nTrust--; + } + trustId[nTrust] = id; trustFp[nTrust] = fp; nTrust++; + } + saveTrust(); +} + +static bool generateCert(String& keyPem, String& crtPem) { + static unsigned char buf[2048]; + mbedtls_pk_free(&ownKey); + mbedtls_pk_init(&ownKey); + if (mbedtls_pk_setup(&ownKey, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY))) return false; + if (mbedtls_ecp_gen_key(MBEDTLS_ECP_DP_SECP256R1, mbedtls_pk_ec(ownKey), mbedtls_ctr_drbg_random, &drbg)) + return false; + + mbedtls_x509write_cert c; + mbedtls_x509write_crt_init(&c); + mbedtls_x509write_crt_set_version(&c, MBEDTLS_X509_CRT_VERSION_3); + mbedtls_x509write_crt_set_md_alg(&c, MBEDTLS_MD_SHA256); + mbedtls_x509write_crt_set_subject_key(&c, &ownKey); + mbedtls_x509write_crt_set_issuer_key(&c, &ownKey); + String subject = "CN=" + deviceId + ",O=KDE,OU=Kde connect"; + mbedtls_x509write_crt_set_subject_name(&c, subject.c_str()); + mbedtls_x509write_crt_set_issuer_name(&c, subject.c_str()); + mbedtls_mpi serial; + mbedtls_mpi_init(&serial); + mbedtls_mpi_lset(&serial, 10); + mbedtls_x509write_crt_set_serial(&c, &serial); + mbedtls_x509write_crt_set_validity(&c, "20200101000000", "20491231235959"); + int r = mbedtls_x509write_crt_pem(&c, buf, sizeof buf, mbedtls_ctr_drbg_random, &drbg); + mbedtls_mpi_free(&serial); + mbedtls_x509write_crt_free(&c); + if (r) return false; + crtPem = (const char*)buf; + if (mbedtls_pk_write_key_pem(&ownKey, buf, sizeof buf)) return false; + keyPem = (const char*)buf; + return true; +} + +static bool initIdentity() { + mbedtls_entropy_init(&entropy); + mbedtls_ctr_drbg_init(&drbg); + if (mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy, (const unsigned char*)"kdec", 4)) return false; + mbedtls_x509_crt_init(&ownCrt); + mbedtls_pk_init(&ownKey); + + Preferences p; + p.begin("kdec", false); + deviceId = p.getString("id", ""); + String keyPem = p.getString("key", ""), crtPem = p.getString("crt", ""); + if (deviceId.length() != 32) { + char hex[33]; + for (int i = 0; i < 32; i++) hex[i] = "0123456789abcdef"[esp_random() & 15]; + hex[32] = 0; + deviceId = hex; + p.putString("id", deviceId); + keyPem = crtPem = ""; + } + bool ok = keyPem.length() && crtPem.length() && + mbedtls_pk_parse_key(&ownKey, (const unsigned char*)keyPem.c_str(), keyPem.length() + 1, nullptr, 0) == 0; + if (!ok) { + Serial.println("KDE: erzeuge Zertifikat ..."); + if (!generateCert(keyPem, crtPem)) { p.end(); return false; } + p.putString("key", keyPem); + p.putString("crt", crtPem); + } + loadTrust(p); + p.end(); + if (mbedtls_x509_crt_parse(&ownCrt, (const unsigned char*)crtPem.c_str(), crtPem.length() + 1)) return false; + + mbedtls_ssl_config_init(&conf); + if (mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT)) + return false; + // KDE Connect uses self-signed certificates; trust is established by pairing + pinning the fingerprint. + mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_NONE); + mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &drbg); + mbedtls_ssl_conf_min_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); // TLS 1.2 + if (mbedtls_ssl_conf_own_cert(&conf, &ownCrt, &ownKey)) return false; + Serial.printf("KDE: Geraete-ID %s, %d gekoppelt\n", deviceId.c_str(), nTrust); + return true; +} + +// ---------------------------------------------------------------- Shared state +static void publish() { + Peer* bp = nullptr; + Player* best = nullptr; + for (auto& p : peers) { + if (!p.used || !p.paired) continue; + for (int k = 0; k < p.nPl; k++) { + Player& pl = p.pl[k]; + if (!pl.title.length()) continue; + bool better = !best || (pl.playing && !best->playing) || + (pl.playing == best->playing && (pl.playing ? pl.startedAt > best->startedAt : pl.at > best->at)); + if (better) { best = &pl; bp = &p; } + } + } + int conn = 0; + for (auto& p : peers) if (p.used && p.paired) conn++; + + xSemaphoreTake(mtx, portMAX_DELAY); + connectedPaired = conn; + NowPlaying n; + if (best) { + n.valid = true; + n.playing = best->playing; + copyStr(n.device, sizeof n.device, bp->name); + copyStr(n.player, sizeof n.player, best->name); + copyStr(n.title, sizeof n.title, best->title); + copyStr(n.artist, sizeof n.artist, best->artist); + n.posMs = best->pos; + n.lenMs = best->len; + n.atMs = best->at; + pubPeerId = bp->id; + pubPlayer = best->name; + } + bool changed = n.valid != pub.valid || n.playing != pub.playing || strcmp(n.title, pub.title) || + strcmp(n.artist, pub.artist) || strcmp(n.device, pub.device) || strcmp(n.player, pub.player); + n.seq = pub.seq + (changed ? 1 : 0); + pub = n; + xSemaphoreGive(mtx); +} + +// ---------------------------------------------------------------- Connections +static bool sendRaw(Peer& p, const String& s) { + const unsigned char* d = (const unsigned char*)s.c_str(); + size_t left = s.length(); + uint32_t start = millis(); + while (left) { + int r = mbedtls_ssl_write(&p.ssl, d, left); + if (r > 0) { d += r; left -= r; continue; } + if ((r == MBEDTLS_ERR_SSL_WANT_WRITE || r == MBEDTLS_ERR_SSL_WANT_READ) && millis() - start < 3000) { + vTaskDelay(pdMS_TO_TICKS(5)); + continue; + } + return false; + } + return true; +} + +static void sendPacket(Peer& p, const char* type, JsonDocument& body) { + JsonDocument d; + d["id"] = packetId(); + d["type"] = type; + d["body"] = body; + String s; + serializeJson(d, s); + s += '\n'; + sendRaw(p, s); +} + +static void sendPair(Peer& p, bool pair) { + JsonDocument b; + b["pair"] = pair; + b["timestamp"] = (int64_t)time(nullptr); + sendPacket(p, "kdeconnect.pair", b); +} + +static void requestPlayers(Peer& p) { + JsonDocument b; + b["requestPlayerList"] = true; + sendPacket(p, "kdeconnect.mpris.request", b); +} + +static void closePeer(Peer& p) { + if (!p.used) return; + Serial.printf("KDE: %s getrennt\n", p.name.c_str()); + mbedtls_ssl_free(&p.ssl); + mbedtls_net_free(&p.net); + bool wasPending = false; + xSemaphoreTake(mtx, portMAX_DELAY); + if (pairId && pairPeerId == p.id) { pairId = 0; wasPending = true; } + xSemaphoreGive(mtx); + (void)wasPending; + p = Peer(); + publish(); +} + +static Player* findPlayer(Peer& p, const String& name, bool create) { + for (int k = 0; k < p.nPl; k++) if (p.pl[k].name == name) return &p.pl[k]; + if (!create || p.nPl >= MAX_PLAYERS) return nullptr; + p.pl[p.nPl] = Player(); + p.pl[p.nPl].name = name; + return &p.pl[p.nPl++]; +} + +static void handleMpris(Peer& p, JsonObject b) { + if (b["playerList"].is()) { + JsonArray list = b["playerList"]; + Player keep[MAX_PLAYERS]; + int n = 0; + for (JsonVariant v : list) { + if (n >= MAX_PLAYERS) break; + String name = v | ""; + if (!name.length()) continue; + Player* old = findPlayer(p, name, false); + bool known = old != nullptr; + keep[n] = known ? *old : Player(); + keep[n].name = name; + n++; + if (!known) { + JsonDocument r; + r["player"] = name; + r["requestNowPlaying"] = true; + sendPacket(p, "kdeconnect.mpris.request", r); + } + } + for (int k = 0; k < n; k++) p.pl[k] = keep[k]; + p.nPl = n; + } + if (b["player"].is()) { + Player* pl = findPlayer(p, String((const char*)b["player"]), true); + if (!pl) return; + bool wasPlaying = pl->playing; + String oldTitle = pl->title; + if (b["title"].is()) pl->title = ascii(b["title"]); + if (b["artist"].is()) pl->artist = ascii(b["artist"]); + if (!b["title"].is() && b["nowPlaying"].is()) { // older peers + pl->title = ascii(b["nowPlaying"]); + pl->artist = ""; + } + if (b["isPlaying"].is()) pl->playing = b["isPlaying"]; + if (b["length"].is()) pl->len = (int32_t)(b["length"].as()); + if (b["pos"].is()) pl->pos = (int32_t)(b["pos"].as()); + else if (pl->playing && wasPlaying) pl->pos += millis() - pl->at; + pl->at = millis(); + if (pl->playing && (!wasPlaying || pl->title != oldTitle)) pl->startedAt = millis(); + } + publish(); +} + +static void handlePacket(Peer& p, const String& line) { + JsonDocument d; + if (deserializeJson(d, line)) return; + const char* type = d["type"] | ""; + JsonObject b = d["body"]; + if (!strcmp(type, "kdeconnect.identity")) { // protocol 8 repeats it inside TLS + if (b["deviceName"].is()) p.name = ascii(b["deviceName"]); + return; + } + if (!strcmp(type, "kdeconnect.pair")) { + bool pair = b["pair"] | false; + if (pair) { + if (p.paired) { sendPair(p, true); return; } + Serial.printf("KDE: Kopplungsanfrage von %s\n", p.name.c_str()); + xSemaphoreTake(mtx, portMAX_DELAY); + pairId = ++pairCounter; + pairPeerId = p.id; + copyStr(pairName, sizeof pairName, p.name); + pairAnswer = 0; + xSemaphoreGive(mtx); + } else { + xSemaphoreTake(mtx, portMAX_DELAY); + if (pairId && pairPeerId == p.id) pairId = 0; + xSemaphoreGive(mtx); + if (p.paired) { + Serial.printf("KDE: %s hat die Kopplung aufgehoben\n", p.name.c_str()); + p.paired = false; + p.nPl = 0; + setTrust(p.id, p.fp, false); + publish(); + } + } + return; + } + if (!p.paired) { + // The other side still thinks we are paired (e.g. after a reset here): tell it we are not. + if (!p.sentUnpair) { sendPair(p, false); p.sentUnpair = true; } + return; + } + if (!strcmp(type, "kdeconnect.mpris")) handleMpris(p, b); +} + +static bool readLine(int fd, String& out, uint32_t timeoutMs) { + uint32_t start = millis(); + char c; + while (millis() - start < timeoutMs) { + int r = recv(fd, &c, 1, 0); + if (r == 1) { + if (c == '\n') return true; + out += c; + if (out.length() > 8192) return false; + } else if (r == 0) { + return false; + } else if (errno != EAGAIN && errno != EWOULDBLOCK) { + return false; + } + } + return false; +} + +static void acceptPeer(int fd) { + int flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); + struct timeval tv = {5, 0}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); + int one = 1, idle = 30, intvl = 10, cnt = 3; + setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof one); + setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof idle); + setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof intvl); + setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof cnt); + + String line; + if (!readLine(fd, line, 5000)) { close(fd); return; } + JsonDocument d; + if (deserializeJson(d, line) || strcmp(d["type"] | "", "kdeconnect.identity")) { close(fd); return; } + String id = d["body"]["deviceId"] | ""; + if (!id.length() || id == deviceId) { close(fd); return; } + + 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) { slot = &p; break; } + if (!slot || ESP.getFreeHeap() < 45000) { + Serial.printf("KDE: kein Platz fuer weitere Verbindung (Heap %u)\n", ESP.getFreeHeap()); + close(fd); + return; + } + Peer& p = *slot; + p = Peer(); + p.id = id; + p.name = ascii(d["body"]["deviceName"] | "Geraet"); + p.proto = d["body"]["protocolVersion"] | 7; + mbedtls_net_init(&p.net); + p.net.fd = fd; + mbedtls_ssl_init(&p.ssl); + p.used = true; + if (mbedtls_ssl_setup(&p.ssl, &conf)) { closePeer(p); return; } + mbedtls_ssl_set_hostname(&p.ssl, nullptr); + mbedtls_ssl_set_bio(&p.ssl, &p.net, mbedtls_net_send, mbedtls_net_recv, nullptr); + + uint32_t start = millis(); + int r; + while ((r = mbedtls_ssl_handshake(&p.ssl)) != 0) { + if ((r != MBEDTLS_ERR_SSL_WANT_READ && r != MBEDTLS_ERR_SSL_WANT_WRITE) || millis() - start > 10000) { + char err[80]; + mbedtls_strerror(r, err, sizeof err); + Serial.printf("KDE: TLS mit %s fehlgeschlagen: %s\n", p.name.c_str(), err); + closePeer(p); + return; + } + } + const mbedtls_x509_crt* pc = mbedtls_ssl_get_peer_cert(&p.ssl); + if (!pc) { closePeer(p); return; } + unsigned char hash[32]; + mbedtls_sha256_ret(pc->raw.p, pc->raw.len, hash, 0); + char hex[65]; + for (int i = 0; i < 32; i++) sprintf(hex + i * 2, "%02x", hash[i]); + p.fp = hex; + mbedtls_net_set_nonblock(&p.net); + + if (p.proto >= 8) sendRaw(p, identityJson(true)); + p.paired = isTrusted(p.id, p.fp); + Serial.printf("KDE: verbunden mit %s (v%d, %s)\n", p.name.c_str(), p.proto, p.paired ? "gekoppelt" : "nicht gekoppelt"); + if (p.paired) requestPlayers(p); + publish(); +} + +static void pollPeer(Peer& p) { + unsigned char buf[512]; + for (int guard = 0; guard < 32; guard++) { + int r = mbedtls_ssl_read(&p.ssl, buf, sizeof buf); + if (r == MBEDTLS_ERR_SSL_WANT_READ || r == MBEDTLS_ERR_SSL_WANT_WRITE) return; + if (r <= 0) { closePeer(p); return; } + p.rx.concat((const char*)buf, r); + int nl; + while ((nl = p.rx.indexOf('\n')) >= 0) { + String line = p.rx.substring(0, nl); + p.rx.remove(0, nl + 1); + if (line.length()) handlePacket(p, line); + if (!p.used) return; + } + if (p.rx.length() > MAX_RX) { closePeer(p); return; } + } +} + +// ---------------------------------------------------------------- Sockets +static bool openSockets() { + udpFd = socket(AF_INET, SOCK_DGRAM, 0); + tcpFd = socket(AF_INET, SOCK_STREAM, 0); + if (udpFd < 0 || tcpFd < 0) return false; + int one = 1; + setsockopt(udpFd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); + setsockopt(udpFd, SOL_SOCKET, SO_BROADCAST, &one, sizeof one); + setsockopt(tcpFd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); + sockaddr_in a = {}; + a.sin_family = AF_INET; + a.sin_port = htons(KDE_PORT); + a.sin_addr.s_addr = htonl(INADDR_ANY); + if (bind(udpFd, (sockaddr*)&a, sizeof a) < 0) return false; + if (bind(tcpFd, (sockaddr*)&a, sizeof a) < 0) return false; + if (listen(tcpFd, 2) < 0) return false; + fcntl(udpFd, F_SETFL, fcntl(udpFd, F_GETFL, 0) | O_NONBLOCK); + fcntl(tcpFd, F_SETFL, fcntl(tcpFd, F_GETFL, 0) | O_NONBLOCK); + return true; +} + +static void sendIdentityUdp(uint32_t ip) { + String s = identityJson(true); + sockaddr_in to = {}; + to.sin_family = AF_INET; + to.sin_port = htons(KDE_PORT); + to.sin_addr.s_addr = ip; + sendto(udpFd, s.c_str(), s.length(), 0, (sockaddr*)&to, sizeof to); +} + +static void pollUdp() { + static char buf[2048]; + sockaddr_in from; + socklen_t fl = sizeof from; + int r = recvfrom(udpFd, buf, sizeof buf - 1, 0, (sockaddr*)&from, &fl); + if (r <= 0) return; + buf[r] = 0; + JsonDocument d; + if (deserializeJson(d, buf) || strcmp(d["type"] | "", "kdeconnect.identity")) return; + String id = d["body"]["deviceId"] | ""; + if (!id.length() || id == deviceId) return; + for (auto& p : peers) if (p.used && p.id == id) return; // already connected + // Answer with our identity: the other device then connects to us via TCP. + static uint32_t lastReply = 0; + static uint32_t lastIp = 0; + if (from.sin_addr.s_addr == lastIp && millis() - lastReply < 15000) return; + lastIp = from.sin_addr.s_addr; + lastReply = millis(); + sendIdentityUdp(from.sin_addr.s_addr); +} + +// ---------------------------------------------------------------- Task +static void kdeTask(void*) { + while (WiFi.status() != WL_CONNECTED) vTaskDelay(pdMS_TO_TICKS(500)); + if (!initIdentity()) { Serial.println("KDE: Initialisierung fehlgeschlagen"); vTaskDelete(nullptr); } + if (!openSockets()) { Serial.println("KDE: Ports nicht verfuegbar"); vTaskDelete(nullptr); } + + uint32_t lastBroadcast = 0; + bool wasConnected = false; + for (;;) { + bool connected = WiFi.status() == WL_CONNECTED; + if (connected && !wasConnected) lastBroadcast = 0; + wasConnected = connected; + + if (connected) { + // Broadcast now and then while some known device is missing (or none is paired yet). + int paired = 0; + for (auto& p : peers) if (p.used && p.paired) paired++; + uint32_t every = (nTrust == 0 || paired < nTrust) ? 60000 : 300000; + if (!lastBroadcast || millis() - lastBroadcast > every) { + lastBroadcast = millis() | 1; + sendIdentityUdp(htonl(INADDR_BROADCAST)); + } + pollUdp(); + int fd = accept(tcpFd, nullptr, nullptr); + if (fd >= 0) acceptPeer(fd); + } + for (auto& p : peers) if (p.used) pollPeer(p); + + // Answers from the UI + int answer = 0; + String answerId, actPeer, actPlayer; + char act[16] = ""; + xSemaphoreTake(mtx, portMAX_DELAY); + if (pairAnswer) { answer = pairAnswer; answerId = pairPeerId; pairAnswer = 0; pairId = 0; } + if (pendingAction[0]) { strcpy(act, pendingAction); pendingAction[0] = 0; actPeer = pubPeerId; actPlayer = pubPlayer; } + xSemaphoreGive(mtx); + if (answer) { + for (auto& p : peers) { + if (!p.used || p.id != answerId) continue; + if (answer == 1) { + p.paired = true; + p.sentUnpair = false; + setTrust(p.id, p.fp, true); + sendPair(p, true); + requestPlayers(p); + Serial.printf("KDE: mit %s gekoppelt\n", p.name.c_str()); + } else { + sendPair(p, false); + } + publish(); + } + } + if (act[0]) { + for (auto& p : peers) { + if (!p.used || !p.paired || p.id != actPeer) continue; + JsonDocument b; + b["player"] = actPlayer; + b["action"] = act; + sendPacket(p, "kdeconnect.mpris.request", b); + } + } + vTaskDelay(pdMS_TO_TICKS(20)); + } +} + +// ---------------------------------------------------------------- Public API +void kdeStart(const char* name) { + deviceName = name; + mtx = xSemaphoreCreateMutex(); + xTaskCreatePinnedToCore(kdeTask, "kdeconnect", 16384, nullptr, 1, nullptr, 0); +} + +void kdeGetNowPlaying(NowPlaying& out) { + if (!mtx) { out = NowPlaying(); return; } + xSemaphoreTake(mtx, portMAX_DELAY); + out = pub; + xSemaphoreGive(mtx); +} + +uint32_t kdePairRequest(char* name, size_t n) { + if (!mtx) return 0; + xSemaphoreTake(mtx, portMAX_DELAY); + uint32_t id = pairAnswer ? 0 : pairId; + if (id && name && n) { strncpy(name, pairName, n - 1); name[n - 1] = 0; } + xSemaphoreGive(mtx); + return id; +} + +void kdeAnswerPair(bool accept) { + if (!mtx) return; + xSemaphoreTake(mtx, portMAX_DELAY); + if (pairId) pairAnswer = accept ? 1 : 2; + xSemaphoreGive(mtx); +} + +void kdeMediaAction(const char* action) { + if (!mtx) return; + xSemaphoreTake(mtx, portMAX_DELAY); + strncpy(pendingAction, action, sizeof pendingAction - 1); + pendingAction[sizeof pendingAction - 1] = 0; + xSemaphoreGive(mtx); +} + +int kdeConnectedCount() { + if (!mtx) return 0; + xSemaphoreTake(mtx, portMAX_DELAY); + int n = connectedPaired; + xSemaphoreGive(mtx); + return n; +} diff --git a/src/main.cpp b/src/main.cpp index 91d7601..d38451d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -17,6 +17,19 @@ struct Device { String entity; String name; }; #else #error "include/config.h fehlt – kopiere include/config.example.h nach include/config.h" #endif +#ifndef KDE_CONNECT +#define KDE_CONNECT 1 +#endif +#ifndef KDE_DEVICE_NAME +#define KDE_DEVICE_NAME "HomeBoard" +#endif +#ifndef MUSIC_KEEP_SCREEN_ON +#define MUSIC_KEEP_SCREEN_ON 1 +#endif +#ifndef MUSIC_HIDE_S +#define MUSIC_HIDE_S 60 +#endif +#include "kdeconnect.h" // ---------------------------------------------------------------- Hardware static constexpr int SCREEN_W = 320; @@ -785,6 +798,217 @@ static void pollAlerts() { } } +// ---------------------------------------------------------------- Music (KDE Connect) +static lv_obj_t *musicPanel, *mClock, *mDate, *mSource, *mTitle, *mArtist, *mBar, *mPos, *mLen, *mPlayLbl; +static lv_obj_t* pairBox = nullptr; +static uint32_t pairShown = 0; +static NowPlaying np; +static bool musicVisible = false; + +static void wakeScreen() { + if (screenOff) setBacklight(true); + lv_disp_trig_activity(nullptr); +} + +static void showMusic(bool show) { + musicVisible = show; + if (show) lv_obj_clear_flag(musicPanel, LV_OBJ_FLAG_HIDDEN); + else lv_obj_add_flag(musicPanel, LV_OBJ_FLAG_HIDDEN); +} + +static void onMusicBtn(lv_event_t* e) { + const char* act = (const char*)lv_event_get_user_data(e); + if (act) kdeMediaAction(act); + else showMusic(false); +} + +static void onClockClick(lv_event_t*) { + if (np.valid) showMusic(true); +} + +static lv_obj_t* musicBtn(lv_obj_t* parent, const char* sym, const char* act, int x, int w) { + lv_obj_t* b = lv_btn_create(parent); + lv_obj_set_size(b, w, 40); + lv_obj_align(b, LV_ALIGN_BOTTOM_MID, x, -4); + lv_obj_set_style_radius(b, 20, 0); + lv_obj_t* l = lv_label_create(b); + lv_obj_set_style_text_font(l, &lv_font_montserrat_20, 0); + lv_label_set_text(l, sym); + lv_obj_center(l); + lv_obj_add_event_cb(b, onMusicBtn, LV_EVENT_CLICKED, (void*)act); + return l; +} + +static void buildMusicUi() { + musicPanel = lv_obj_create(lv_layer_top()); + lv_obj_set_size(musicPanel, SCREEN_W, SCREEN_H); + lv_obj_set_pos(musicPanel, 0, 0); + lv_obj_set_style_radius(musicPanel, 0, 0); + lv_obj_set_style_border_width(musicPanel, 0, 0); + lv_obj_set_style_pad_all(musicPanel, 0, 0); + lv_obj_set_style_bg_color(musicPanel, lv_color_hex(0x0b0e12), 0); + lv_obj_clear_flag(musicPanel, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_add_flag(musicPanel, LV_OBJ_FLAG_HIDDEN); + + mClock = lv_label_create(musicPanel); + lv_obj_set_style_text_font(mClock, &lv_font_montserrat_48, 0); + lv_label_set_text(mClock, "--:--"); + lv_obj_align(mClock, LV_ALIGN_TOP_MID, 0, 4); + mDate = lv_label_create(musicPanel); + lv_obj_set_style_text_color(mDate, lv_palette_lighten(LV_PALETTE_GREY, 1), 0); + lv_label_set_text(mDate, ""); + lv_obj_align(mDate, LV_ALIGN_TOP_MID, 0, 58); + + lv_obj_t* close = lv_btn_create(musicPanel); + lv_obj_set_size(close, 34, 34); + lv_obj_align(close, LV_ALIGN_TOP_RIGHT, -4, 4); + lv_obj_set_style_bg_color(close, lv_color_hex(0x2a323b), 0); + lv_obj_t* cl = lv_label_create(close); + lv_label_set_text(cl, LV_SYMBOL_CLOSE); + lv_obj_center(cl); + lv_obj_add_event_cb(close, onMusicBtn, LV_EVENT_CLICKED, nullptr); + + mSource = lv_label_create(musicPanel); + lv_obj_set_style_text_color(mSource, lv_palette_main(LV_PALETTE_LIGHT_BLUE), 0); + lv_label_set_long_mode(mSource, LV_LABEL_LONG_DOT); + lv_obj_set_width(mSource, 300); + lv_obj_set_style_text_align(mSource, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_align(mSource, LV_ALIGN_TOP_MID, 0, 84); + + mTitle = lv_label_create(musicPanel); + lv_obj_set_style_text_font(mTitle, &lv_font_montserrat_20, 0); + lv_label_set_long_mode(mTitle, LV_LABEL_LONG_SCROLL_CIRCULAR); + lv_obj_set_width(mTitle, 300); + lv_obj_set_style_text_align(mTitle, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_align(mTitle, LV_ALIGN_TOP_MID, 0, 104); + + mArtist = lv_label_create(musicPanel); + lv_obj_set_style_text_color(mArtist, lv_palette_lighten(LV_PALETTE_GREY, 1), 0); + lv_label_set_long_mode(mArtist, LV_LABEL_LONG_DOT); + lv_obj_set_width(mArtist, 300); + lv_obj_set_style_text_align(mArtist, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_align(mArtist, LV_ALIGN_TOP_MID, 0, 132); + + mBar = lv_bar_create(musicPanel); + lv_obj_set_size(mBar, 200, 6); + lv_obj_align(mBar, LV_ALIGN_TOP_MID, 0, 164); + lv_bar_set_range(mBar, 0, 1000); + mPos = lv_label_create(musicPanel); + lv_obj_set_style_text_color(mPos, lv_palette_lighten(LV_PALETTE_GREY, 1), 0); + lv_obj_align(mPos, LV_ALIGN_TOP_LEFT, 10, 158); + mLen = lv_label_create(musicPanel); + lv_obj_set_style_text_color(mLen, lv_palette_lighten(LV_PALETTE_GREY, 1), 0); + lv_obj_align(mLen, LV_ALIGN_TOP_RIGHT, -10, 158); + + musicBtn(musicPanel, LV_SYMBOL_PREV, "Previous", -80, 64); + mPlayLbl = musicBtn(musicPanel, LV_SYMBOL_PAUSE, "PlayPause", 0, 80); + musicBtn(musicPanel, LV_SYMBOL_NEXT, "Next", 80, 64); + + lv_obj_add_flag(clockLabel, LV_OBJ_FLAG_CLICKABLE); + lv_obj_set_ext_click_area(clockLabel, 12); + lv_obj_add_event_cb(clockLabel, onClockClick, LV_EVENT_CLICKED, nullptr); +} + +static void fmtTime(char* buf, size_t n, int32_t ms) { + if (ms < 0) ms = 0; + int s = ms / 1000; + snprintf(buf, n, "%d:%02d", s / 60, s % 60); +} + +static void onPairBox(lv_event_t* e) { + lv_obj_t* box = lv_event_get_current_target(e); + kdeAnswerPair(lv_msgbox_get_active_btn(box) == 0); + lv_msgbox_close(box); + pairBox = nullptr; +} + +static void updateMusic() { + static const char* DAYS[] = {"Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"}; + static const char* MONTHS[] = {"Januar", "Februar", "Maerz", "April", "Mai", "Juni", "Juli", + "August", "September", "Oktober", "November", "Dezember"}; + // Pairing requests + char name[40]; + uint32_t req = kdePairRequest(name, sizeof name); + if (req && req != pairShown) { + if (pairBox) lv_msgbox_close(pairBox); + static const char* btns[] = {"Koppeln", "Ablehnen", ""}; + char txt[96]; + snprintf(txt, sizeof txt, "%s moechte sich mit dem HomeBoard koppeln.", name); + pairBox = lv_msgbox_create(nullptr, "KDE Connect", txt, btns, false); + lv_obj_set_width(pairBox, 280); + lv_obj_center(pairBox); + lv_obj_add_event_cb(pairBox, onPairBox, LV_EVENT_VALUE_CHANGED, nullptr); + pairShown = req; + wakeScreen(); + } else if (!req && pairBox) { + lv_msgbox_close(pairBox); + pairBox = nullptr; + } + if (!req) pairShown = 0; + + // Now playing + static uint32_t lastSeq = 0; + static String lastTitle; + static bool lastPlaying = false; + static uint32_t stoppedAt = 0; + kdeGetNowPlaying(np); + if (np.seq != lastSeq) { + lastSeq = np.seq; + bool newTrack = np.valid && np.playing && (!lastPlaying || lastTitle != np.title); + if (np.valid) { + if (np.player[0] && strcmp(np.player, np.device)) + lv_label_set_text_fmt(mSource, LV_SYMBOL_AUDIO " %s - %s", np.player, np.device); + else + lv_label_set_text_fmt(mSource, LV_SYMBOL_AUDIO " %s", np.device); + lv_label_set_text(mTitle, np.title); + lv_label_set_text(mArtist, np.artist); + lv_label_set_text(mPlayLbl, np.playing ? LV_SYMBOL_PAUSE : LV_SYMBOL_PLAY); + } + if (newTrack) { + showMusic(true); + wakeScreen(); + } + if (lastPlaying && !np.playing) { + stoppedAt = millis(); + if (musicVisible) lv_disp_trig_activity(nullptr); // screen timeout starts counting now + } + lastPlaying = np.valid && np.playing; + lastTitle = np.title; + } + if (musicVisible && (!np.valid || (!np.playing && millis() - stoppedAt > MUSIC_HIDE_S * 1000UL))) + showMusic(false); + + // Clock, date and progress + struct tm t; + if (getLocalTime(&t, 0)) { + char buf[40]; + strftime(buf, sizeof buf, "%H:%M", &t); + if (np.valid && np.playing) lv_label_set_text_fmt(clockLabel, LV_SYMBOL_AUDIO " %s", buf); + else lv_label_set_text(clockLabel, buf); + if (musicVisible) { + lv_label_set_text(mClock, buf); + lv_label_set_text_fmt(mDate, "%s, %d. %s", DAYS[t.tm_wday], t.tm_mday, MONTHS[t.tm_mon]); + } + } + if (musicVisible) { + int32_t pos = np.posMs + (np.playing ? (int32_t)(millis() - np.atMs) : 0); + if (np.lenMs > 0) { + pos = min(pos, np.lenMs); + char a[12], b[12]; + fmtTime(a, sizeof a, pos); + fmtTime(b, sizeof b, np.lenMs); + lv_label_set_text(mPos, a); + lv_label_set_text(mLen, b); + lv_bar_set_value(mBar, (int64_t)pos * 1000 / np.lenMs, LV_ANIM_OFF); + lv_obj_clear_flag(mBar, LV_OBJ_FLAG_HIDDEN); + } else { + lv_label_set_text(mPos, ""); + lv_label_set_text(mLen, ""); + lv_obj_add_flag(mBar, LV_OBJ_FLAG_HIDDEN); + } + } +} + // ---------------------------------------------------------------- Setup / loop void setup() { Serial.begin(115200); @@ -818,28 +1042,27 @@ void setup() { lv_indev_drv_register(&indevDrv); buildUi(); + buildMusicUi(); lv_timer_handler(); WiFi.mode(WIFI_STA); WiFi.setAutoReconnect(true); WiFi.begin(WIFI_SSID, WIFI_PASS); configTzTime(TIMEZONE, "pool.ntp.org", "time.google.com"); +#if KDE_CONNECT + kdeStart(KDE_DEVICE_NAME); +#endif } void loop() { lv_timer_handler(); uint32_t now = millis(); - // Clock + // Clock, music view, pairing dialog static uint32_t lastClock = 0; - if (now - lastClock > 1000) { + if (now - lastClock > 250) { 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); - } + updateMusic(); } // WiFi signal strength @@ -850,7 +1073,8 @@ void loop() { } // Backlight timeout - if (SCREEN_TIMEOUT_S > 0 && !screenOff && lv_disp_get_inactive_time(nullptr) > SCREEN_TIMEOUT_S * 1000UL) + bool keepOn = MUSIC_KEEP_SCREEN_ON && musicVisible && np.playing; + if (SCREEN_TIMEOUT_S > 0 && !screenOff && !keepOn && lv_disp_get_inactive_time(nullptr) > SCREEN_TIMEOUT_S * 1000UL) setBacklight(false); // WiFi status