#!/usr/bin/env python3 """ PylonisAmp — display.py Cała komunikacja z panelem RP2040 przez USB CDC. Zawiera: DisplayManager, obsługę okładek, LED ring. """ import os import json import time import logging import threading import queue import hashlib import requests from typing import Optional from pathlib import Path from io import BytesIO import serial import numpy as np from PIL import Image log = logging.getLogger('display') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) COVERS_DIR = Path(BASE_DIR) / 'covers' COVERS_DIR.mkdir(exist_ok=True) COVER_SIZE = (240, 240) JPEG_QUALITY = 92 HTTP_TIMEOUT = 10 # ══════════════════════════════════════════════════════════════════════════════ # Konwersja obrazu → RGB565 (dla Pico) # ══════════════════════════════════════════════════════════════════════════════ def to_rgb565(path: str) -> bytes: """Konwertuj JPEG/PNG → 240×240 RGB565 big-endian (numpy, szybkie).""" img = np.array(Image.open(path).convert('RGB').resize(COVER_SIZE)) r = (img[:, :, 0].astype(np.uint16) & 0xF8) << 8 g = (img[:, :, 1].astype(np.uint16) & 0xFC) << 3 b = (img[:, :, 2].astype(np.uint16) >> 3) return ((r | g | b).byteswap()).tobytes() # ══════════════════════════════════════════════════════════════════════════════ # Cover Manager (wbudowany — nie potrzeba osobnego pliku) # ══════════════════════════════════════════════════════════════════════════════ def _cover_cache_path(artist: str, title: str, station: str) -> Path: key = f"{artist.lower()}|{title.lower()}|{station.lower()}" return COVERS_DIR / f"{hashlib.md5(key.encode()).hexdigest()[:12]}.jpg" def get_cover_path(artist: str, title: str, station: str = '') -> Optional[str]: """Pobierz okładkę, zapisz w cache, zwróć ścieżkę.""" path = _cover_cache_path(artist, title, station) if path.exists(): return str(path) url = (_try_itunes(artist, title) or _try_musicbrainz(artist, title) or _try_station_logo(station)) if not url: return None try: r = requests.get(url, timeout=HTTP_TIMEOUT, stream=True) if r.status_code != 200: return None img = Image.open(BytesIO(r.content)).convert('RGB') img = img.resize(COVER_SIZE, Image.LANCZOS) img.save(str(path), 'JPEG', quality=JPEG_QUALITY) log.info(f"Cover saved: {path.name}") return str(path) except Exception as e: log.warning(f"Cover download error: {e}") return None def get_cover_url(artist: str, title: str, station: str = '') -> Optional[str]: path = get_cover_path(artist, title, station) if not path: return None return f'/api/cover/{os.path.basename(path)}' def _try_itunes(artist: str, title: str) -> Optional[str]: if not (artist or title): return None try: r = requests.get( 'https://itunes.apple.com/search', params={'term': f'{artist} {title}', 'media': 'music', 'limit': 3}, timeout=HTTP_TIMEOUT) for item in r.json().get('results', []): art = item.get('artworkUrl100', '') if art: return art.replace('100x100', '240x240') except Exception: pass return None def _try_musicbrainz(artist: str, title: str) -> Optional[str]: if not (artist and title): return None try: r = requests.get( 'https://musicbrainz.org/ws/2/recording', params={'query': f'recording:"{title}" AND artist:"{artist}"', 'fmt': 'json', 'limit': 3}, headers={'User-Agent': 'PylonisAmp/1.0'}, timeout=HTTP_TIMEOUT) for rec in r.json().get('recordings', []): for release in rec.get('releases', []): rid = release.get('id') if rid: ca = f'https://coverartarchive.org/release/{rid}/front-250' cr = requests.head(ca, timeout=HTTP_TIMEOUT, allow_redirects=True) if cr.status_code == 200: return ca except Exception: pass return None def _try_station_logo(station: str) -> Optional[str]: if not station: return None try: r = requests.get( f'https://de1.api.radio-browser.info/json/stations/byname/{requests.utils.quote(station)}', params={'limit': 3}, headers={'User-Agent': 'PylonisAmp/1.0'}, timeout=HTTP_TIMEOUT) for s in r.json(): favicon = s.get('favicon', '') if favicon and favicon.startswith('http'): return favicon except Exception: pass return None # ══════════════════════════════════════════════════════════════════════════════ # DisplayManager — komunikacja z Pico # ══════════════════════════════════════════════════════════════════════════════ class DisplayManager: """ Zarządza połączeniem USB CDC z RP2040. Obsługuje: state, tick, okładki RGB565, LED ring, OTA bootloader. Protokół: → {"cmd":"state", "station":..., "title":..., "artist":..., "volume":..., "time":...} → {"cmd":"tick", "volume":..., "time":...} # szybka aktualizacja → {"cmd":"img_start", "size":N} + N bajtów RGB565 # okładka → {"cmd":"led", "data":[...]} # LED ring → {"cmd":"reboot_bootloader"} # OTA ← {"evt":"ready", "fw":"v0.2.3"} ← {"evt":"hb", "ok":1} ← {"evt":"touch", "x":..., "y":...} ← {"evt":"img_err", "msg":"timeout"} """ # Priorytety kolejki: niższy = wyższy priorytet _PRI_CTRL = 0 # volume, bootloader _PRI_STATE = 1 # state _PRI_TICK = 2 # tick _PRI_COVER = 5 # okładki _PRI_LED = 8 # LED def __init__(self, source_engine, port: str = '/dev/ttyACM0', baud: int = 500000): self.port = port self.baud = baud self.sm = source_engine self.serial: Optional[serial.Serial] = None self.online = False self.running = False self._lock = threading.Lock() self._pq: queue.PriorityQueue = queue.PriorityQueue() self._pq_seq = 0 # tiebreaker dla equal priority self._last_reconnect = 0.0 self._last_offline = 0.0 self._write_errors = 0 self._last_state_hash = '' self._last_cover_path: Optional[str] = None # Cover worker queue self._cover_q: queue.Queue = queue.Queue(maxsize=2) def start(self): self.running = True threading.Thread(target=self._read_loop, daemon=True, name='fp-read').start() threading.Thread(target=self._write_loop, daemon=True, name='fp-write').start() threading.Thread(target=self._cover_worker, daemon=True, name='fp-cover').start() threading.Thread(target=self._led_loop, daemon=True, name='fp-led').start() log.info(f"DisplayManager started on {self.port} @ {self.baud}") def stop(self): self.running = False if self.serial: self.serial.close() @property def connected(self) -> bool: return self.online and bool(self.serial and self.serial.is_open) # ── Public send API ─────────────────────────────────────────────────── def send_state(self): """Wyślij pełny stan (station, title, artist, volume, time).""" if not self.sm: return src = self.sm.active status = src.get_status() if src else {} artist = str(status.get('artist', '')) title = str(status.get('title', status.get('station', ''))) msg = { 'cmd': 'state', 'station': str(status.get('station', src.SOURCE_ID if src else '')), 'title': title, 'artist': artist, 'volume': self.sm.volume, 'time': status.get('time', '00:00'), } h = json.dumps(msg, sort_keys=True) if h == self._last_state_hash: return self._last_state_hash = h self._enqueue(self._PRI_STATE, msg) def send_fast_update(self): """Szybka aktualizacja volume/time — nie rysuje całego UI.""" if not self.sm: return src = self.sm.active status = src.get_status() if src else {} self._enqueue(self._PRI_TICK, { 'cmd': 'tick', 'volume': self.sm.volume, 'time': status.get('time', '00:00'), }) def send_meters(self, bands: list): """Widmo do LED/wyświetlacza — niska prioritet.""" self._enqueue(self._PRI_LED, {'cmd': 'meters', 'data': bands}) def on_meta_change(self, meta: dict): """Wywołane gdy tytuł/wykonawca się zmienił — pobierz okładkę.""" self.send_state() artist = meta.get('artist', '') title = meta.get('title', '') station = meta.get('station', '') # Dodaj do cover worker (nie blokuje) try: self._cover_q.put_nowait((artist, title, station)) except queue.Full: pass def reboot_to_bootloader(self): """Wyślij komendę OTA — Pico wchodzi w BOOTSEL.""" self._enqueue(self._PRI_CTRL, {'cmd': 'reboot_bootloader'}) # ── Read loop ───────────────────────────────────────────────────────── def _read_loop(self): while self.running: if not self.online: self._try_connect() time.sleep(0.5) continue try: line = self.serial.readline().decode('utf-8', errors='ignore').strip() if line: self._handle_incoming(line) except serial.SerialException as e: log.warning(f"Serial error: {e}") self._disconnect() except Exception as e: log.error(f"Read loop: {e}") self._disconnect() def _try_connect(self): now = time.time() if now - self._last_reconnect < 10: return self._last_reconnect = now try: self.serial = serial.Serial( self.port, self.baud, timeout=0.1, write_timeout=0) self.online = True self._write_errors = 0 log.info(f"Połączono z Pico na {self.port}") self.send_state() except Exception as e: log.debug(f"Pico niedostępny: {e}") self.serial = None self._last_offline = time.time() def _disconnect(self): self.online = False self._last_offline = time.time() if self.serial: try: self.serial.close() except Exception: pass self.serial = None def _handle_incoming(self, line: str): try: data = json.loads(line) except json.JSONDecodeError: log.debug(f"Non-JSON from Pico: {line}") return evt = data.get('evt') cmd = data.get('cmd') if evt == 'ready': fw = data.get('fw', '?') log.info(f"Pico ready, fw={fw}") self._last_state_hash = '' # wymuś wysłanie stanu self.send_state() elif evt == 'hb': # Jeśli Pico prosi o cover (cover=none) — wyślij ponownie if data.get('cover') == 'none' and self._last_cover_path: if os.path.exists(self._last_cover_path): self._enqueue_cover(self._last_cover_path) elif evt == 'touch': x, y = data.get('x', 0), data.get('y', 0) log.info(f"Touch: x={x} y={y}") elif evt == 'img_err': log.warning(f"Pico img_err: {data.get('msg')}") elif cmd == 'req': # Pico prosi o aktualny stan (np. po wznowieniu) self._last_state_hash = '' self.send_state() # ── Write loop ──────────────────────────────────────────────────────── def _write_loop(self): while self.running: try: _, _, msg = self._pq.get(timeout=0.5) except queue.Empty: continue if not self.online: continue self._send(msg) def _enqueue(self, priority: int, msg: dict): self._pq_seq += 1 self._pq.put((priority, self._pq_seq, msg)) def _send(self, msg: dict) -> bool: with self._lock: if not self.online or not self.serial or not self.serial.is_open: return False # Nie wysyłaj jeśli bufor wyjściowy jest zapchany try: if self.serial.out_waiting > 2048: return False except Exception: pass try: payload = json.dumps(msg, ensure_ascii=False).encode() + b'\n' self.serial.write(payload) return True except (serial.SerialException, serial.SerialTimeoutException) as e: log.warning(f"Write error: {e}") self._write_errors += 1 if self._write_errors > 3: self._disconnect() return False # ── Cover worker ────────────────────────────────────────────────────── def _cover_worker(self): while self.running: try: artist, title, station = self._cover_q.get(timeout=1) except queue.Empty: continue try: path = get_cover_path(artist, title, station) if path: self._last_cover_path = path self._enqueue_cover(path) except Exception as e: log.error(f"Cover worker: {e}") def _enqueue_cover(self, path: str): """Wstaw okładkę do kolejki (osobny typ wiadomości).""" self._enqueue(self._PRI_COVER, {'__cover': path}) def _send(self, msg: dict) -> bool: """Rozszerzona wersja — obsługuje __cover.""" if '__cover' in msg: self._do_send_cover(msg['__cover']) return True with self._lock: if not self.online or not self.serial or not self.serial.is_open: return False try: if self.serial.out_waiting > 2048: return False payload = json.dumps(msg, ensure_ascii=False).encode() + b'\n' self.serial.write(payload) return True except (serial.SerialException, serial.SerialTimeoutException) as e: log.warning(f"Write error: {e}") self._write_errors += 1 if self._write_errors > 3: self._disconnect() return False def _do_send_cover(self, path: str): """Wyślij okładkę jako RGB565 — blokuje write_loop na czas transferu.""" try: data = to_rgb565(path) except Exception as e: log.error(f"Cover RGB565 convert: {e}") return with self._lock: if not self.online or not self.serial: return try: # Zapowiedź header = json.dumps({'cmd': 'img_start', 'size': len(data)}, ensure_ascii=False).encode() + b'\n' self.serial.write(header) self.serial.flush() # Dane w kawałkach 4096B CHUNK = 4096 for offset in range(0, len(data), CHUNK): self.serial.write(data[offset:offset + CHUNK]) self.serial.flush() log.debug(f"Cover sent: {len(data)} bytes") except Exception as e: log.error(f"Cover send: {e}") # ── LED loop ────────────────────────────────────────────────────────── def _led_loop(self): """Oddychanie LED ring — 8 diod z fazowym offsetem.""" while self.running: if not self.online: time.sleep(0.5) continue now = time.time() * 1000 brightness = [] for idx in range(8): offset = idx * 875 cycle = (now + offset) % 7000 if cycle < 2000: b = 0 elif cycle < 4000: b = int(20 * (cycle - 2000) / 2000) elif cycle < 5000: b = 20 else: b = int(20 * (7000 - cycle) / 2000) brightness.append(max(0, min(255, b * 12))) self._enqueue(self._PRI_LED, {'cmd': 'led', 'data': brightness}) time.sleep(0.05)