diff --git a/README.md b/README.md index d8ec907..8bfb792 100644 --- a/README.md +++ b/README.md @@ -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. 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** (FAT32) im Slot 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`. diff --git a/platformio.ini b/platformio.ini index 618c158..644da8f 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,12 +10,14 @@ monitor_filters = esp32_exception_decoder lib_deps = bodmer/TFT_eSPI@2.5.43 - https://github.com/PaulStoffregen/XPT2046_Touchscreen.git#v1.4 lvgl/lvgl@8.3.11 bblanchon/ArduinoJson@7.2.1 + bitbank2/PNGdec@1.1.6 build_flags = ; 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 -I include ; TFT_eSPI: Setup direkt hier statt User_Setup.h diff --git a/src/kdeconnect.cpp b/src/kdeconnect.cpp index 4153e41..d311584 100644 --- a/src/kdeconnect.cpp +++ b/src/kdeconnect.cpp @@ -22,6 +22,10 @@ #include #include #include +#include +#include +#include +#include extern "C" { #include } @@ -463,10 +467,15 @@ struct ArtCtx { 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) { 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]; UINT done = 0; while (done < nd && c->left > 0) { @@ -513,6 +522,182 @@ static void setArt(bool valid, const char* info) { 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 void initSd() { + sdSpi.begin(18, 19, 23, 5); // CYD micro-SD slot + sdOk = SD.begin(5, sdSpi, 20000000); + if (sdOk && !SD.exists("/covers")) SD.mkdir("/covers"); + Serial.printf("KDE: SD-Karte %s\n", sdOk ? "gefunden, Cover werden dort gespeichert" : "nicht gefunden"); +} + +static String artPath(const String& url) { + unsigned char h[32]; + mbedtls_sha256_ret((const unsigned char*)url.c_str(), url.length(), h, 0); + char hex[17]; + for (int i = 0; i < 8; i++) sprintf(hex + i * 2, "%02x", h[i]); + return String("/covers/") + hex + ".img"; +} + +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; + 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: 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 < 56000 || 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(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"; @@ -556,7 +741,7 @@ static const char* downloadArt(Peer& p, int port, int64_t size) { } else if (!(pool = malloc(4096))) { err = "Zu wenig Speicher"; } else { - ArtCtx c = {&ssl, size, 0, 0, 0, {0}, 0}; + 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) { @@ -629,7 +814,15 @@ 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) { - const char* err = downloadArt(p, port, d["payloadSize"] | (int64_t)0); + int64_t size = d["payloadSize"] | (int64_t)0; + const char* err; + if (sdOk) { + String path = artPath(url); + err = downloadToSd(p, port, size, path); + if (!err) err = decodeFile(path); + } else { + err = downloadArt(p, port, size); + } artLoadedUrl = url; setArt(!err, err ? err : ""); } @@ -797,6 +990,7 @@ static void pollUdp() { static void kdeTask(void*) { while (WiFi.status() != WL_CONNECTED) vTaskDelay(pdMS_TO_TICKS(500)); if (!initIdentity()) { Serial.println("KDE: Initialisierung fehlgeschlagen"); vTaskDelete(nullptr); } + initSd(); if (!openSockets()) { Serial.println("KDE: Ports nicht verfuegbar"); vTaskDelete(nullptr); } uint32_t lastBroadcast = 0; @@ -877,6 +1071,13 @@ static void kdeTask(void*) { } 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 && sdOk && SD.exists(artPath(curArtUrl))) { // already on the card + const char* err = decodeFile(artPath(curArtUrl)); + artRequestedUrl = artLoadedUrl = curArtUrl; + setArt(!err, err ? err : ""); + if (!err) continue; + SD.remove(artPath(curArtUrl)); // broken file: fetch it again next time + } artTries = fresh ? 1 : artTries + 1; artRequestedUrl = curArtUrl; artRequestedAt = millis(); diff --git a/src/main.cpp b/src/main.cpp index 62abc00..16ea672 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include #include @@ -42,8 +41,6 @@ static constexpr int XPT2046_CLK = 25; static constexpr int XPT2046_CS = 33; static TFT_eSPI tft; -static SPIClass touchSpi(VSPI); -static XPT2046_Touchscreen ts(XPT2046_CS, XPT2046_IRQ); static lv_disp_draw_buf_t drawBuf; static constexpr int DRAW_BUF_PX = SCREEN_W * 16; @@ -120,8 +117,55 @@ static void setBacklight(bool 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) { - bool pressed = ts.tirqTouched() && ts.touched(); + int rx = 0, ry = 0; + bool pressed = tpRead(rx, ry); if (!pressed) { swallowTouch = false; data->state = LV_INDEV_STATE_REL; @@ -137,13 +181,9 @@ static void touchRead(lv_indev_drv_t*, lv_indev_data_t* data) { data->state = LV_INDEV_STATE_REL; return; } - // Average a few samples: raw XPT2046 readings jitter, which makes taps look like drags. - int sx = 0, sy = 0, n = 0; - for (int k = 0; k < 4; k++) { - TS_Point q = ts.getPoint(); - sx += q.x; sy += q.y; n++; - } - int rx = sx / n, ry = sy / n; + // A second sample against jitter (raw XPT2046 readings jitter, which makes taps look like drags). + int rx2, ry2; + if (tpRead(rx2, ry2)) { rx = (rx + rx2) / 2; ry = (ry + ry2) / 2; } if (TOUCH_SWAP_XY) std::swap(rx, ry); int x = map(rx, TOUCH_X_MIN, TOUCH_X_MAX, 0, SCREEN_W - 1); int y = map(ry, TOUCH_Y_MIN, TOUCH_Y_MAX, 0, SCREEN_H - 1); @@ -897,7 +937,10 @@ static void wakeScreen() { lv_disp_trig_activity(nullptr); } +static uint32_t musicShownAt = 0; + static void showMusic(bool show) { + if (show && !musicVisible) musicShownAt = millis(); musicVisible = show; if (show) lv_obj_clear_flag(musicPanel, LV_OBJ_FLAG_HIDDEN); else lv_obj_add_flag(musicPanel, LV_OBJ_FLAG_HIDDEN); @@ -1270,11 +1313,15 @@ static void updateMusic() { static uint32_t lastSeq = 0, lastArt = 0; static String lastTitle; static bool lastPlaying = false; - static uint32_t stoppedAt = 0; + static uint32_t lastActive = 0; // last time something was playing 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) { 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) { const char* pin = np.pinned ? " " LV_SYMBOL_EYE_OPEN : ""; if (np.player[0] && strcmp(np.player, np.device)) @@ -1309,12 +1356,9 @@ static void updateMusic() { 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 (lastPlaying && !active && musicVisible) lv_disp_trig_activity(nullptr); // screen timeout starts now + lastPlaying = active; + if (np.valid) lastTitle = np.title; } if (np.artSeq != lastArt) { lastArt = np.artSeq; @@ -1332,7 +1376,9 @@ static void updateMusic() { 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); // Clock, date and progress @@ -1371,9 +1417,13 @@ void setup() { pinMode(TFT_BL, OUTPUT); setBacklight(true); - touchSpi.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS); - ts.begin(touchSpi); - ts.setRotation(1); + pinMode(XPT2046_CLK, OUTPUT); + pinMode(XPT2046_MOSI, OUTPUT); + 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);