Zapis obecnego stanu plików z backupu
This commit is contained in:
1 parent
e177c41fd7
commit
4736a87009
18 files changed
+5353
No files matched your search
@@ -0,0 +1,548 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
REST API routes — wszystkie endpointy HTTP.
|
||||
Importowane przez app.py.
|
||||
FIXED: meters format dla Pico (data zamiast bands, uv vs spectrum)
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
import psutil
|
||||
import subprocess
|
||||
import time
|
||||
from flask import Blueprint, jsonify, request, current_app, send_file
|
||||
|
||||
def _bt():
|
||||
return getattr(current_app, 'bt_manager', None)
|
||||
def _net():
|
||||
return getattr(current_app, 'net_manager', None)
|
||||
def _eq():
|
||||
return getattr(current_app, 'eq_manager', None)
|
||||
|
||||
bp = Blueprint('api', __name__, url_prefix='/api')
|
||||
|
||||
STATIONS_FILE = os.path.join(os.path.dirname(__file__), '..', 'radio', 'stations.json')
|
||||
|
||||
# Ograniczenie częstotliwości wysyłania LED (np. co 100ms)
|
||||
_last_led_send = 0
|
||||
|
||||
# ── Helper ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _mgr():
|
||||
return current_app.source
|
||||
|
||||
def _uart():
|
||||
return current_app.display
|
||||
|
||||
|
||||
def _load_stations() -> dict:
|
||||
try:
|
||||
with open(STATIONS_FILE) as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {'version': '3.0', 'stations': []}
|
||||
|
||||
def _save_stations(data: dict):
|
||||
with open(STATIONS_FILE, 'w') as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
|
||||
|
||||
# ── Status ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@bp.route('/version', methods=['GET'])
|
||||
def api_version():
|
||||
"""Zwróć wersję z pliku VERSION."""
|
||||
import os
|
||||
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
try:
|
||||
ver = open(os.path.join(base, 'VERSION')).read().strip()
|
||||
except Exception:
|
||||
ver = '0.0.0'
|
||||
return jsonify({'version': ver})
|
||||
|
||||
@bp.route('/status')
|
||||
def api_status():
|
||||
"""Pełny status systemu."""
|
||||
sm = _mgr()
|
||||
net = _net()
|
||||
uart = _uart()
|
||||
|
||||
net_status = net.get_status()
|
||||
|
||||
cpu_temp = None
|
||||
try:
|
||||
with open('/sys/class/thermal/thermal_zone0/temp') as f:
|
||||
cpu_temp = round(int(f.read().strip()) / 1000, 1)
|
||||
except Exception:
|
||||
try:
|
||||
temps = psutil.sensors_temperatures()
|
||||
for key in ('cpu_thermal', 'cpu-thermal', 'coretemp'):
|
||||
if key in temps and temps[key]:
|
||||
cpu_temp = round(temps[key][0].current, 1)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
cpu_load = psutil.cpu_percent(interval=0.0)
|
||||
except Exception:
|
||||
cpu_load = None
|
||||
|
||||
try:
|
||||
with open('/proc/uptime') as f:
|
||||
secs = int(float(f.read().split()[0]))
|
||||
days = secs // 86400
|
||||
hours = (secs % 86400) // 3600
|
||||
mins = (secs % 3600) // 60
|
||||
uptime = f"{days}d {hours}h {mins}m" if days else f"{hours}h {mins}m"
|
||||
except Exception:
|
||||
uptime = ''
|
||||
|
||||
return jsonify({
|
||||
**sm.get_all_status(),
|
||||
'volume': sm.volume,
|
||||
'loudness': sm.get_config('loudness', True),
|
||||
'autogain': sm.get_config('autogain', True),
|
||||
'meter_mode': sm.get_config('meter_mode', 'vu'),
|
||||
'direct': sm.get_config('direct', False),
|
||||
'source_gains': sm._cfg.get('source_gains', {}),
|
||||
'mono': sm.get_config('mono', False),
|
||||
'network': net_status,
|
||||
'uart': current_app.display.connected if current_app.display else False,
|
||||
'cd_ready': False,
|
||||
'cd_disc': None,
|
||||
'cpu_temp': cpu_temp,
|
||||
'cpu_load': cpu_load,
|
||||
'cpu_hot': bool(cpu_temp is not None and cpu_temp >= 70.0),
|
||||
'uptime': uptime,
|
||||
})
|
||||
|
||||
|
||||
# ── Source ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/source', methods=['GET'])
|
||||
def api_source_get():
|
||||
return jsonify(_mgr().get_all_status())
|
||||
|
||||
@bp.route('/source', methods=['POST'])
|
||||
def api_source_set():
|
||||
data = request.get_json(force=True) or {}
|
||||
source_id = data.get('source')
|
||||
if not source_id:
|
||||
return jsonify({'error': 'source required'}), 400
|
||||
ok = _mgr().switch(source_id)
|
||||
if not ok:
|
||||
return jsonify({'error': f'Cannot activate source: {source_id}'}), 400
|
||||
_mgr().set_config('last_source', source_id)
|
||||
status = _mgr().active.get_status() if _mgr().active else {}
|
||||
if _uart(): _uart().send_state()
|
||||
return jsonify(_mgr().get_all_status())
|
||||
|
||||
|
||||
# ── Volume ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/volume', methods=['GET'])
|
||||
def api_volume_get():
|
||||
return jsonify({'volume': _mgr().volume})
|
||||
|
||||
@bp.route('/volume', methods=['POST'])
|
||||
def api_volume_set():
|
||||
data = request.get_json(force=True) or {}
|
||||
vol = int(data.get('volume', 75))
|
||||
_mgr().set_volume(vol)
|
||||
if _uart():
|
||||
if current_app.display: current_app.display.send_fast_update()
|
||||
return jsonify({'volume': vol})
|
||||
|
||||
|
||||
# ── Level (VU meter) ───────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/level', methods=['GET'])
|
||||
def api_level():
|
||||
if source and hasattr(source, 'get_level'):
|
||||
return jsonify(source.get_level())
|
||||
return jsonify({'rms_l': -60, 'rms_r': -60, 'peak_l': -60, 'peak_r': -60})
|
||||
|
||||
@bp.route('/spectrum', methods=['GET'])
|
||||
def api_spectrum():
|
||||
source = _mgr().active
|
||||
if source and hasattr(source, 'get_spectrum'):
|
||||
return jsonify({'bands': source.get_spectrum()})
|
||||
return jsonify({'bands': [-60.0] * 32})
|
||||
|
||||
@bp.route('/meters', methods=['GET'])
|
||||
def api_meters():
|
||||
"""Level + Spectrum w jednym requeście."""
|
||||
global _last_led_send
|
||||
source = _mgr().active
|
||||
level = {'rms_l': -60.0, 'rms_r': -60.0, 'peak_l': -60.0, 'peak_r': -60.0}
|
||||
bands = [-60.0] * 32
|
||||
|
||||
mgr = _mgr()
|
||||
if mgr:
|
||||
level = mgr.get_level()
|
||||
bands = mgr.get_spectrum()
|
||||
now = time.time()
|
||||
if _uart() and _uart().connected and (now - _last_led_send > 0.1):
|
||||
_last_led_send = now
|
||||
_uart().send_meters(bands)
|
||||
|
||||
return jsonify({**level, 'bands': bands})
|
||||
|
||||
|
||||
# ── Stream Info ────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/stream', methods=['GET'])
|
||||
def api_stream_info():
|
||||
"""Zwraca parametry strumienia (bitrate, sample rate itp.) dla aktywnego źródła."""
|
||||
source = _mgr().active
|
||||
if source and hasattr(source, 'get_status'):
|
||||
status = source.get_status()
|
||||
return jsonify(status.get('stream', {}))
|
||||
return jsonify({})
|
||||
|
||||
|
||||
# ── Cover art ───────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/cover/<filename>', methods=['GET'])
|
||||
def api_cover_file(filename):
|
||||
"""Serwuje plik okładki z cache."""
|
||||
from pathlib import Path
|
||||
covers_dir = Path(__file__).parent / 'covers'
|
||||
path = covers_dir / filename
|
||||
if not path.exists() or path.suffix.lower() not in ('.jpg', '.jpeg', '.png'):
|
||||
return '', 404
|
||||
return send_file(str(path), mimetype='image/jpeg')
|
||||
|
||||
@bp.route('/cover', methods=['GET'])
|
||||
def api_cover_fetch():
|
||||
"""Pobierz okładkę dla podanego artysty/tytułu/stacji."""
|
||||
artist = request.args.get('artist', '')
|
||||
title = request.args.get('title', '')
|
||||
station = request.args.get('station', '')
|
||||
try:
|
||||
from display import get_cover_url
|
||||
url = get_cover_url(artist, title, station)
|
||||
return jsonify({'url': url})
|
||||
except Exception as e:
|
||||
return jsonify({'url': None, 'error': str(e)})
|
||||
|
||||
|
||||
# ── Settings ───────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/setting', methods=['POST'])
|
||||
def api_setting():
|
||||
data = request.get_json(force=True) or {}
|
||||
key = data.get('key')
|
||||
value = data.get('value')
|
||||
if key in ('loudness', 'mono', 'autogain', 'meter_mode'):
|
||||
_mgr().set_config(key, value if key == 'meter_mode' else bool(value))
|
||||
return jsonify({'key': key, 'value': value})
|
||||
return jsonify({'error': 'Unknown setting'}), 400
|
||||
|
||||
@bp.route('/setting/direct', methods=['POST'])
|
||||
def api_direct():
|
||||
data = request.json or {}
|
||||
enabled = bool(data.get('enabled', False))
|
||||
sm = _mgr()
|
||||
sm.set_config('direct', enabled)
|
||||
src = sm.get('radio')
|
||||
if src and hasattr(src, 'set_direct'):
|
||||
src.set_direct(enabled)
|
||||
return jsonify({'direct': enabled})
|
||||
|
||||
|
||||
# ── EQ ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/eq/<source_id>', methods=['GET'])
|
||||
def api_eq_get(source_id):
|
||||
return jsonify({
|
||||
'source': source_id,
|
||||
'gains': _eq().get(source_id),
|
||||
'bands': _eq().get_band_names(),
|
||||
})
|
||||
|
||||
@bp.route('/eq/<source_id>', methods=['POST'])
|
||||
def api_eq_set(source_id):
|
||||
data = request.get_json(force=True) or {}
|
||||
gains = data.get('gains')
|
||||
if not gains or len(gains) != 10:
|
||||
return jsonify({'error': 'gains must be array of 10'}), 400
|
||||
_mgr().set_eq(source_id, gains)
|
||||
if _eq(): _eq().set(source_id, gains)
|
||||
return jsonify({'source': source_id, 'gains': gains})
|
||||
|
||||
@bp.route('/eq/<source_id>/preset/<preset>', methods=['POST'])
|
||||
def api_eq_preset(source_id, preset):
|
||||
try:
|
||||
gains = _eq().apply_preset(source_id, preset)
|
||||
_mgr().set_eq(source_id, gains)
|
||||
return jsonify({'source': source_id, 'preset': preset, 'gains': gains})
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
@bp.route('/eq/presets', methods=['GET'])
|
||||
def api_eq_presets():
|
||||
eq = _eq()
|
||||
return jsonify({'presets': eq.get_presets(), 'names': eq.get_preset_names()})
|
||||
|
||||
@bp.route('/eq/user/<preset_id>/save', methods=['POST'])
|
||||
def api_eq_user_save(preset_id):
|
||||
data = request.json or {}
|
||||
source_id = data.get('source', _mgr().active.SOURCE_ID if _mgr().active else 'radio')
|
||||
eq = _eq()
|
||||
gains = eq.get(source_id)
|
||||
try:
|
||||
saved = eq.save_user_preset(preset_id, gains)
|
||||
return jsonify({'preset': preset_id, 'gains': saved})
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
@bp.route('/eq/user/<preset_id>/name', methods=['POST'])
|
||||
def api_eq_user_rename(preset_id):
|
||||
data = request.json or {}
|
||||
name = data.get('name', '').strip()
|
||||
if not name:
|
||||
return jsonify({'error': 'name required'}), 400
|
||||
try:
|
||||
new_name = _eq().set_preset_name(preset_id, name)
|
||||
return jsonify({'preset': preset_id, 'name': new_name})
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
|
||||
# ── Radio / Stations ────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/radio/stations', methods=['GET'])
|
||||
def api_stations():
|
||||
return jsonify(_load_stations())
|
||||
|
||||
@bp.route('/radio/stations', methods=['POST'])
|
||||
def api_add_station():
|
||||
data = request.get_json(force=True) or {}
|
||||
name = (data.get('name') or '').strip()
|
||||
url = (data.get('url') or '').strip()
|
||||
genre = (data.get('genre') or '').strip()
|
||||
if not name or not url:
|
||||
return jsonify({'error': 'name and url required'}), 400
|
||||
sd = _load_stations()
|
||||
station = {
|
||||
'id': str(uuid.uuid4())[:8],
|
||||
'name': name,
|
||||
'url': url,
|
||||
'genre': genre,
|
||||
'bitrate': int(data.get('bitrate', 128)),
|
||||
'codec': data.get('codec', 'MP3'),
|
||||
'favorite': False,
|
||||
'enabled': True,
|
||||
}
|
||||
sd['stations'].append(station)
|
||||
_save_stations(sd)
|
||||
return jsonify({'status': 'created', 'station': station}), 201
|
||||
|
||||
@bp.route('/radio/stations/<station_id>', methods=['DELETE'])
|
||||
def api_delete_station(station_id):
|
||||
sd = _load_stations()
|
||||
sd['stations'] = [s for s in sd['stations'] if s['id'] != station_id]
|
||||
_save_stations(sd)
|
||||
return jsonify({'status': 'deleted'})
|
||||
|
||||
@bp.route('/radio/stations/<station_id>/favorite', methods=['POST'])
|
||||
def api_favorite(station_id):
|
||||
add = bool(request.get_json(force=True).get('add', True))
|
||||
sd = _load_stations()
|
||||
for s in sd['stations']:
|
||||
if s['id'] == station_id:
|
||||
s['favorite'] = add
|
||||
_save_stations(sd)
|
||||
return jsonify({'status': 'ok', 'favorite': add})
|
||||
|
||||
@bp.route('/radio/play', methods=['POST'])
|
||||
def api_radio_play():
|
||||
data = request.get_json(force=True) or {}
|
||||
station_id = data.get('id')
|
||||
url = data.get('url')
|
||||
station_name = ''
|
||||
|
||||
if station_id:
|
||||
stations = _load_stations().get('stations', [])
|
||||
station = next((s for s in stations if s['id'] == station_id), None)
|
||||
if not station:
|
||||
return jsonify({'error': 'Station not found'}), 404
|
||||
url = station['url']
|
||||
station_name = station['name']
|
||||
|
||||
if not url:
|
||||
return jsonify({'error': 'No URL or station ID'}), 400
|
||||
|
||||
if not _mgr().switch('radio'):
|
||||
return jsonify({'error': 'Cannot activate radio'}), 500
|
||||
|
||||
radio = _mgr().get('radio')
|
||||
radio.play(url, station_name)
|
||||
|
||||
if station_id:
|
||||
_mgr().set_config('last_station_id', station_id)
|
||||
if _uart(): _uart().send_state()
|
||||
return jsonify({'status': 'playing', 'url': url, 'station': station_name})
|
||||
|
||||
@bp.route('/radio/stop', methods=['POST'])
|
||||
def api_radio_stop():
|
||||
radio = _mgr().get('radio')
|
||||
if radio:
|
||||
radio.stop()
|
||||
if _uart(): _uart().send_state()
|
||||
return jsonify({'status': 'stopped'})
|
||||
|
||||
|
||||
# ── Network ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/network/status', methods=['GET'])
|
||||
def api_net_status():
|
||||
return jsonify(_net().get_status())
|
||||
|
||||
@bp.route('/network/scan', methods=['GET'])
|
||||
def api_net_scan():
|
||||
return jsonify({'networks': _net().scan()})
|
||||
|
||||
@bp.route('/network/connect', methods=['POST'])
|
||||
def api_net_connect():
|
||||
data = request.get_json(force=True) or {}
|
||||
ssid = data.get('ssid', '')
|
||||
password = data.get('password', '')
|
||||
if not ssid:
|
||||
return jsonify({'error': 'ssid required'}), 400
|
||||
result = _net().connect(ssid, password)
|
||||
return jsonify(result)
|
||||
|
||||
@bp.route('/network/disconnect', methods=['POST'])
|
||||
def api_net_disconnect():
|
||||
return jsonify(_net().disconnect())
|
||||
|
||||
@bp.route('/network/wifi', methods=['GET'])
|
||||
def api_wifi_state():
|
||||
return jsonify({'wifi': _net().get_wifi_enabled()})
|
||||
|
||||
@bp.route('/network/wifi', methods=['POST'])
|
||||
def api_wifi_toggle():
|
||||
data = request.json or {}
|
||||
enabled = bool(data.get('enabled', True))
|
||||
ok = _net().set_wifi_enabled(enabled)
|
||||
return jsonify({'wifi': enabled, 'ok': ok})
|
||||
|
||||
|
||||
# ── Source Gain ─────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/source/<source_id>/gain', methods=['GET'])
|
||||
def api_get_gain(source_id):
|
||||
return jsonify({'source': source_id, 'gain': _mgr().get_source_gain(source_id)})
|
||||
|
||||
@bp.route('/source/<source_id>/gain', methods=['POST'])
|
||||
def api_set_gain(source_id):
|
||||
data = request.json or {}
|
||||
gain = float(data.get('gain', 0))
|
||||
new_gain = _mgr().set_source_gain(source_id, gain)
|
||||
return jsonify({'source': source_id, 'gain': new_gain})
|
||||
|
||||
@bp.route('/source/gains', methods=['GET'])
|
||||
def api_get_all_gains():
|
||||
sm = _mgr()
|
||||
sources = ['radio', 'bluetooth', 'phono', 'line1', 'line2', 'spdif']
|
||||
return jsonify({s: sm.get_source_gain(s) for s in sources})
|
||||
|
||||
|
||||
# ── Bluetooth ───────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/bluetooth/devices', methods=['GET'])
|
||||
def api_bt_devices():
|
||||
return jsonify({
|
||||
'paired': _bt().get_paired(),
|
||||
'scanning': _bt().scanning,
|
||||
'mode': _bt().mode,
|
||||
'connected': _bt().connected_device,
|
||||
})
|
||||
|
||||
@bp.route('/bluetooth/scan', methods=['POST'])
|
||||
def api_bt_scan():
|
||||
_bt().scan_async(duration=10, callback=None)
|
||||
return jsonify({'status': 'scanning', 'message': 'Scan started (10s)'})
|
||||
|
||||
@bp.route('/bluetooth/pair', methods=['POST'])
|
||||
def api_bt_pair():
|
||||
mac = (request.get_json(force=True) or {}).get('mac', '')
|
||||
if not mac:
|
||||
return jsonify({'error': 'mac required'}), 400
|
||||
ok = _bt().pair(mac)
|
||||
return jsonify({'status': 'paired' if ok else 'error', 'mac': mac})
|
||||
|
||||
@bp.route('/bluetooth/connect', methods=['POST'])
|
||||
def api_bt_connect():
|
||||
mac = (request.get_json(force=True) or {}).get('mac', '')
|
||||
if not mac:
|
||||
return jsonify({'error': 'mac required'}), 400
|
||||
ok = _bt().connect(mac)
|
||||
return jsonify({'status': 'connected' if ok else 'error', 'mac': mac})
|
||||
|
||||
@bp.route('/bluetooth/disconnect', methods=['POST'])
|
||||
def api_bt_disconnect():
|
||||
mac = (request.get_json(force=True) or {}).get('mac', '')
|
||||
_bt().disconnect(mac)
|
||||
return jsonify({'status': 'disconnected'})
|
||||
|
||||
@bp.route('/bluetooth/unpair', methods=['POST'])
|
||||
def api_bt_unpair():
|
||||
data = request.get_json(force=True) or {}
|
||||
mac = data.get('mac', '')
|
||||
if not mac:
|
||||
return jsonify({'error': 'mac required'}), 400
|
||||
_bt().disconnect_device(mac)
|
||||
_bt().remove_device(mac)
|
||||
return jsonify({'status': 'unpaired', 'mac': mac})
|
||||
|
||||
@bp.route('/bluetooth/mode', methods=['POST'])
|
||||
def api_bt_mode():
|
||||
mode = (request.get_json(force=True) or {}).get('mode', 'sink')
|
||||
_bt().set_mode(mode)
|
||||
return jsonify({'mode': mode})
|
||||
|
||||
|
||||
# ── System ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@bp.route('/system/reboot', methods=['POST'])
|
||||
def api_reboot():
|
||||
import threading, time
|
||||
def _do():
|
||||
time.sleep(1)
|
||||
subprocess.run(['sudo', 'reboot'])
|
||||
threading.Thread(target=_do, daemon=True).start()
|
||||
return jsonify({'status': 'rebooting'})
|
||||
|
||||
@bp.route('/system/shutdown', methods=['POST'])
|
||||
def api_shutdown():
|
||||
import threading, time
|
||||
def _do():
|
||||
time.sleep(1)
|
||||
subprocess.run(['sudo', 'poweroff'])
|
||||
threading.Thread(target=_do, daemon=True).start()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@bp.route('/system/info', methods=['GET'])
|
||||
def api_sysinfo():
|
||||
try:
|
||||
cpu = psutil.cpu_percent(interval=0.5)
|
||||
mem = psutil.virtual_memory().percent
|
||||
disk = psutil.disk_usage('/').percent
|
||||
temps = psutil.sensors_temperatures()
|
||||
temp = round(temps['cpu_thermal'][0].current, 1) if 'cpu_thermal' in temps else None
|
||||
except Exception:
|
||||
cpu = mem = disk = temp = None
|
||||
try:
|
||||
with open('/proc/uptime') as f:
|
||||
secs = int(float(f.read().split()[0]))
|
||||
uptime = f"{secs//86400}d {(secs%86400)//3600}h {(secs%3600)%60}m"
|
||||
except Exception:
|
||||
uptime = ''
|
||||
return jsonify({'cpu_pct': cpu, 'mem_pct': mem, 'disk_pct': disk, 'temp': temp, 'uptime': uptime})
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
PylonisAmp — app.py
|
||||
Flask + SocketIO aplikacja. Tylko inicjalizacja, routing i WebSocket.
|
||||
Logika audio → source.py, komunikacja z Pico → display.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import json
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
from flask import Flask, render_template, request
|
||||
from flask_socketio import SocketIO, emit
|
||||
|
||||
# ── Ścieżki ────────────────────────────────────────────────────────────────
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# Wersja z pliku VERSION
|
||||
def _read_version() -> str:
|
||||
try:
|
||||
return open(os.path.join(BASE_DIR, 'VERSION')).read().strip()
|
||||
except Exception:
|
||||
return '0.0.0'
|
||||
|
||||
VERSION = _read_version()
|
||||
sys.path.insert(0, BASE_DIR)
|
||||
|
||||
LOG_DIR = os.path.join(BASE_DIR, 'logs')
|
||||
CONFIG_PATH = os.path.join(BASE_DIR, 'config.json')
|
||||
os.makedirs(LOG_DIR, exist_ok=True)
|
||||
|
||||
# ── Logging ────────────────────────────────────────────────────────────────
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(logging.INFO)
|
||||
fmt = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
|
||||
|
||||
fh = RotatingFileHandler(os.path.join(LOG_DIR, 'streamer.log'),
|
||||
maxBytes=10*1024*1024, backupCount=5)
|
||||
fh.setFormatter(fmt)
|
||||
root_logger.addHandler(fh)
|
||||
|
||||
sh = logging.StreamHandler()
|
||||
sh.setFormatter(fmt)
|
||||
root_logger.addHandler(sh)
|
||||
|
||||
logging.getLogger('werkzeug').setLevel(logging.WARNING)
|
||||
log = logging.getLogger('app')
|
||||
|
||||
# ── Config ──────────────────────────────────────────────────────────────────
|
||||
def _load_cfg() -> dict:
|
||||
try:
|
||||
with open(CONFIG_PATH) as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
cfg = _load_cfg()
|
||||
ALSA_DEVICE = os.environ.get('ALSA_DEVICE', cfg.get('alsa_device', 'hw:1,0'))
|
||||
WEB_PORT = int(os.environ.get('WEB_PORT', 8000))
|
||||
|
||||
# ── Flask ───────────────────────────────────────────────────────────────────
|
||||
app = Flask(__name__,
|
||||
template_folder=os.path.join(BASE_DIR, 'web', 'templates'),
|
||||
static_folder=os.path.join(BASE_DIR, 'web', 'static'))
|
||||
|
||||
socketio = SocketIO(app, cors_allowed_origins='*', async_mode='threading')
|
||||
|
||||
# Singletony — inicjalizowane w init_app()
|
||||
app.source = None # SourceEngine (source.py)
|
||||
app.display = None # DisplayManager (display.py)
|
||||
|
||||
# ── Importy opóźnione (żeby nie circular) ──────────────────────────────────
|
||||
def init_app():
|
||||
from source import SourceEngine
|
||||
from display import DisplayManager
|
||||
from api import bp as api_bp
|
||||
|
||||
app.register_blueprint(api_bp)
|
||||
|
||||
# Callbacki → SocketIO push
|
||||
def on_state(source_id, state):
|
||||
try:
|
||||
sm = app.source
|
||||
socketio.emit('state', {
|
||||
'source': source_id,
|
||||
'state': state,
|
||||
'status': sm.get_status(),
|
||||
'volume': sm.volume,
|
||||
})
|
||||
except Exception as e:
|
||||
log.debug(f"on_state error: {e}")
|
||||
|
||||
def on_meta(source_id, meta):
|
||||
try:
|
||||
socketio.emit('meta', {'source': source_id, **meta})
|
||||
if app.display:
|
||||
app.display.on_meta_change(meta)
|
||||
except Exception as e:
|
||||
log.debug(f"on_meta error: {e}")
|
||||
|
||||
# Pomocnicze managery
|
||||
from modules.eq_manager import EQManager
|
||||
from modules.network_manager import NetworkManager
|
||||
from modules.bt_manager import BTManager
|
||||
|
||||
eq_mgr = EQManager()
|
||||
net_mgr = NetworkManager()
|
||||
app.eq_manager = eq_mgr
|
||||
app.net_manager = net_mgr
|
||||
|
||||
# SourceEngine
|
||||
src = SourceEngine(
|
||||
alsa_device=ALSA_DEVICE,
|
||||
on_state=on_state,
|
||||
on_meta=on_meta,
|
||||
)
|
||||
app.source = src
|
||||
|
||||
# DisplayManager (Pico przez USB CDC)
|
||||
disp = DisplayManager(source_engine=src)
|
||||
disp.start()
|
||||
app.display = disp
|
||||
|
||||
# BT manager
|
||||
bt_src = src.get('bluetooth')
|
||||
app.bt_manager = BTManager(bt_src)
|
||||
|
||||
# Przywróć ostatnie źródło i stację
|
||||
src.restore()
|
||||
|
||||
# Status push co 3s
|
||||
def _push():
|
||||
while True:
|
||||
time.sleep(3)
|
||||
try:
|
||||
socketio.emit('status', _full_status())
|
||||
except Exception:
|
||||
pass
|
||||
threading.Thread(target=_push, daemon=True, name='status-push').start()
|
||||
|
||||
log.info(f"PylonisAmp v{VERSION} gotowy — http://0.0.0.0:{WEB_PORT}")
|
||||
|
||||
def _full_status() -> dict:
|
||||
sm = app.source
|
||||
return {
|
||||
**sm.get_all_status(),
|
||||
'volume': sm.volume,
|
||||
'uart': app.display.connected if app.display else False,
|
||||
'cd_ready': False,
|
||||
'cd_disc': None,
|
||||
}
|
||||
|
||||
# ── Routes ──────────────────────────────────────────────────────────────────
|
||||
@app.route('/')
|
||||
def index():
|
||||
return render_template('index.html', version=VERSION)
|
||||
|
||||
# ── WebSocket ───────────────────────────────────────────────────────────────
|
||||
@socketio.on('connect')
|
||||
def ws_connect():
|
||||
emit('status', _full_status())
|
||||
|
||||
@socketio.on('play_radio')
|
||||
def ws_play_radio(data):
|
||||
data = data or {}
|
||||
url = data.get('url', '')
|
||||
name = data.get('name', '')
|
||||
if not url:
|
||||
return
|
||||
app.source.switch('radio')
|
||||
app.source.get('radio').play(url, name)
|
||||
emit('state', {'source': 'radio', 'state': 'buffering'}, broadcast=True)
|
||||
|
||||
@socketio.on('stop')
|
||||
def ws_stop():
|
||||
src = app.source.active
|
||||
if src and hasattr(src, 'stop'):
|
||||
src.stop()
|
||||
emit('state', {'source': app.source.active_id, 'state': 'stopped'}, broadcast=True)
|
||||
|
||||
@socketio.on('set_volume')
|
||||
def ws_volume(data):
|
||||
vol = int((data or {}).get('volume', 75))
|
||||
app.source.set_volume(vol)
|
||||
if app.display:
|
||||
app.display.send_fast_update()
|
||||
emit('volume', {'volume': vol}, broadcast=True)
|
||||
|
||||
@socketio.on('set_source')
|
||||
def ws_source(data):
|
||||
sid = (data or {}).get('source', '')
|
||||
if sid:
|
||||
app.source.switch(sid)
|
||||
emit('source', app.source.get_all_status(), broadcast=True)
|
||||
|
||||
@socketio.on('set_eq')
|
||||
def ws_eq(data):
|
||||
data = data or {}
|
||||
sid = data.get('source', 'radio')
|
||||
gains = data.get('gains', [])
|
||||
if len(gains) == 10:
|
||||
app.source.set_eq(sid, gains)
|
||||
emit('eq', {'source': sid, 'gains': gains}, broadcast=True)
|
||||
|
||||
# ── Main ────────────────────────────────────────────────────────────────────
|
||||
if __name__ == '__main__':
|
||||
init_app()
|
||||
socketio.run(app, host='0.0.0.0', port=WEB_PORT,
|
||||
debug=False, use_reloader=False,
|
||||
allow_unsafe_werkzeug=True)
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"version": "3.0",
|
||||
"last_source": "radio",
|
||||
"last_station_id": "trancepulse",
|
||||
"volume": 30,
|
||||
"balance": 0,
|
||||
"loudness": true,
|
||||
"mono": false,
|
||||
"autogain": true,
|
||||
"direct": false,
|
||||
"meter_mode": "spectrum",
|
||||
"uart_port": "/dev/ttyAMA0",
|
||||
"uart_baud": 115200,
|
||||
"source_gains": {
|
||||
"radio": 3.0
|
||||
},
|
||||
"eq": {
|
||||
"radio": [
|
||||
6,
|
||||
5,
|
||||
3,
|
||||
1,
|
||||
0,
|
||||
-3,
|
||||
1,
|
||||
3,
|
||||
6,
|
||||
7
|
||||
],
|
||||
"bluetooth": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"phono": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"line1": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"line2": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"spdif": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
]
|
||||
},
|
||||
"user_presets": {},
|
||||
"preset_names": {}
|
||||
}
|
||||
+475
@@ -0,0 +1,475 @@
|
||||
#!/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)
|
||||
@@ -0,0 +1,228 @@
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <TFT_eSPI.h>
|
||||
#include <U8g2_for_TFT_eSPI.h>
|
||||
#include <Adafruit_NeoPixel.h>
|
||||
|
||||
#define FW_VERSION "0.2.13"
|
||||
|
||||
// <<< DO NOT MODIFY HARDWARE CONFIG START >>>
|
||||
#define BAUD_RATE 500000
|
||||
#define NUM_LEDS 8
|
||||
#define PIN_WS2812 2
|
||||
#define PIN_TFT_BL 22
|
||||
#define PYLONIS_BLUE 0x249E
|
||||
#define PYLONIS_DARK 0x0841
|
||||
|
||||
TFT_eSPI tft = TFT_eSPI();
|
||||
U8g2_for_TFT_eSPI u8g2;
|
||||
Adafruit_NeoPixel ring(NUM_LEDS, PIN_WS2812, NEO_GRB + NEO_KHZ800);
|
||||
TFT_eSprite bottomBar = TFT_eSprite(&tft);
|
||||
TFT_eSprite spectrumSprite = TFT_eSprite(&tft);
|
||||
// <<< DO NOT MODIFY HARDWARE CONFIG END >>>
|
||||
|
||||
// GLOBALNE ZMIENNE
|
||||
char np_station[64] = "RADIO", np_title[128] = "Czekam...", np_artist[128] = "";
|
||||
String display_mode = "spectrum";
|
||||
uint32_t last_data_rx = 0;
|
||||
bool is_warning_state = false;
|
||||
bool img_loaded = false;
|
||||
uint32_t last_hb = 0;
|
||||
|
||||
// Bufor szeregowy
|
||||
char serial_buf[256];
|
||||
int serial_idx = 0;
|
||||
|
||||
// <<< STABLE CORE: TOUCH & METERS START >>>
|
||||
void draw_meters(JsonArray data) {
|
||||
if (display_mode == "none") {
|
||||
spectrumSprite.fillSprite(TFT_BLACK);
|
||||
spectrumSprite.pushSprite(245, 180);
|
||||
return;
|
||||
}
|
||||
spectrumSprite.fillSprite(TFT_BLACK);
|
||||
|
||||
// FIX #6: UV mode — Pico dostaje 2 wartości [rms_l, rms_r] zamiast 32 pasm
|
||||
if (display_mode == "uv") {
|
||||
// Dla UV: data powinno mieć co najmniej 2 elementy
|
||||
int l = 0, r = 0;
|
||||
if (data.size() >= 2) {
|
||||
l = map(constrain(data[0].as<int>(), -60, 0), -60, 0, 0, 90);
|
||||
r = map(constrain(data[1].as<int>(), -60, 0), -60, 0, 0, 90);
|
||||
}
|
||||
spectrumSprite.fillRect(20, 90-l, 80, l, PYLONIS_BLUE);
|
||||
spectrumSprite.fillRect(135, 90-r, 80, r, PYLONIS_BLUE);
|
||||
} else {
|
||||
// Spectrum: 32 pasma (lub mniej jeśli mniej danych)
|
||||
int num_bands = min((int)data.size(), 32);
|
||||
int bar_w = max(2, 235 / max(num_bands, 1) - 2); // dynamiczna szerokość
|
||||
for (int i = 0; i < num_bands; i++) {
|
||||
int h = map(constrain(data[i].as<int>(), -60, 0), -60, 0, 0, 90);
|
||||
int x = i * (bar_w + 2);
|
||||
spectrumSprite.fillRect(x, 90 - h, bar_w, h, PYLONIS_BLUE);
|
||||
}
|
||||
}
|
||||
spectrumSprite.pushSprite(245, 180);
|
||||
}
|
||||
|
||||
void check_touch() {
|
||||
uint16_t tx, ty;
|
||||
if (tft.getTouch(&tx, &ty)) {
|
||||
static uint32_t last_touch_ms = 0;
|
||||
if (millis() - last_touch_ms > 400) {
|
||||
last_touch_ms = millis();
|
||||
if (display_mode == "spectrum") display_mode = "uv";
|
||||
else if (display_mode == "uv") display_mode = "none";
|
||||
else display_mode = "spectrum";
|
||||
Serial.printf("{\"evt\":\"touch\",\"x\":%d,\"y\":%d,\"mode\":\"%s\"}\n", tx, ty, display_mode.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
// <<< STABLE CORE: TOUCH & METERS END >>>
|
||||
|
||||
void setup() {
|
||||
Serial.begin(BAUD_RATE);
|
||||
while(Serial.available() > 0) { Serial.read(); }
|
||||
|
||||
ring.begin();
|
||||
ring.setBrightness(25);
|
||||
ring.show();
|
||||
pinMode(PIN_TFT_BL, OUTPUT);
|
||||
digitalWrite(PIN_TFT_BL, HIGH);
|
||||
tft.init();
|
||||
tft.setRotation(1);
|
||||
tft.fillScreen(TFT_BLACK);
|
||||
uint16_t calData[5] = { 280, 3500, 350, 3300, 6 };
|
||||
tft.setTouch(calData);
|
||||
bottomBar.createSprite(480, 60);
|
||||
spectrumSprite.createSprite(235, 100);
|
||||
|
||||
u8g2.begin(tft);
|
||||
u8g2.setFont(u8g2_font_unifont_t_polish);
|
||||
u8g2.setForegroundColor(TFT_WHITE);
|
||||
u8g2.setBackgroundColor(TFT_BLACK);
|
||||
|
||||
// Test czcionki
|
||||
strncpy(np_title, "Zażółć gęślą jaźń", 127);
|
||||
strncpy(np_artist, "TEST UTF-8", 127);
|
||||
draw_full_ui();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// 1. Emergency flush: jeśli Pico nie nadąża, czyścimy bufor
|
||||
if (Serial.available() > 256) {
|
||||
while(Serial.available() > 64) Serial.read();
|
||||
}
|
||||
|
||||
// 2. Heartbeat: Pico prosi o dane (co 100ms)
|
||||
static uint32_t last_req = 0;
|
||||
if (millis() - last_req > 100) {
|
||||
Serial.println("{\"cmd\":\"req\"}");
|
||||
last_req = millis();
|
||||
}
|
||||
|
||||
check_touch();
|
||||
update_leds();
|
||||
|
||||
while (Serial.available() > 0) {
|
||||
char c = Serial.read();
|
||||
if (c == '\n') {
|
||||
serial_buf[serial_idx] = 0;
|
||||
handle_json(String(serial_buf));
|
||||
serial_idx = 0;
|
||||
} else if (serial_idx < 255) {
|
||||
serial_buf[serial_idx++] = c;
|
||||
}
|
||||
}
|
||||
|
||||
// FIX #7: Resetuj watchdog przy każdym odbiorze danych (nie tylko cmd)
|
||||
// Watchdog
|
||||
if (millis() - last_data_rx > 2000) {
|
||||
is_warning_state = true;
|
||||
}
|
||||
|
||||
delay(1); // Pozwala stosowi USB na przetworzenie danych
|
||||
}
|
||||
|
||||
void update_leds() {
|
||||
uint32_t now = millis();
|
||||
static uint32_t last_led_move = 0;
|
||||
static int current_led = 0;
|
||||
|
||||
if (is_warning_state) {
|
||||
// Ostrzeżenie: Pomarańczowy puls
|
||||
ring.clear();
|
||||
for(int i=0; i<NUM_LEDS; i++) ring.setPixelColor(i, ring.Color(50, 20, 0));
|
||||
ring.show();
|
||||
return;
|
||||
}
|
||||
|
||||
if (now - last_led_move > 500) {
|
||||
last_led_move = now;
|
||||
current_led = (current_led + 1) % NUM_LEDS;
|
||||
}
|
||||
|
||||
uint32_t cycle_ms = now % 2000;
|
||||
int v = (cycle_ms < 1000) ? map(cycle_ms, 0, 1000, 10, 50) : map(cycle_ms, 1000, 2000, 50, 10);
|
||||
|
||||
ring.clear();
|
||||
for(int i=0; i<NUM_LEDS; i++) {
|
||||
int bri = (i == current_led) ? v : v/5;
|
||||
ring.setPixelColor(i, ring.Color(0, bri/2, bri));
|
||||
}
|
||||
ring.show();
|
||||
}
|
||||
|
||||
void handle_json(String line) {
|
||||
JsonDocument doc;
|
||||
if (deserializeJson(doc, line)) return;
|
||||
const char* cmd = doc["cmd"] | "";
|
||||
|
||||
// FIX #7b: Resetuj watchdog przy KAŻDYM poprawnym JSONie (nie tylko cmd)
|
||||
last_data_rx = millis();
|
||||
is_warning_state = false;
|
||||
|
||||
if (strcmp(cmd, "state") == 0) {
|
||||
const char* new_artist = doc["artist"] | "";
|
||||
const char* new_title = doc["title"] | "";
|
||||
|
||||
// Dirty checking: jeśli dane się zmieniły, resetuj okładkę
|
||||
if (strcmp(np_artist, new_artist) != 0 || strcmp(np_title, new_title) != 0) {
|
||||
strncpy(np_artist, new_artist, 127);
|
||||
strncpy(np_title, new_title, 127);
|
||||
strncpy(np_station, doc["station"] | "", 63);
|
||||
|
||||
img_loaded = false; // Reset statusu okładki
|
||||
tft.fillRect(245, 120, 235, 120, TFT_BLACK); // Wyczyść obszar okładki
|
||||
draw_full_ui();
|
||||
}
|
||||
} else if (strcmp(cmd, "meters") == 0) {
|
||||
// FIX #8: Sprawdź czy data istnieje
|
||||
if (doc.containsKey("data")) {
|
||||
draw_meters(doc["data"].as<JsonArray>());
|
||||
}
|
||||
} else if (strcmp(cmd, "fast") == 0) {
|
||||
// FIX #9: Obsługa fast update (volume, time) bez pełnego renderowania
|
||||
// Można tu dodać aktualizację volume na ekranie jeśli potrzebna
|
||||
} else if (strcmp(cmd, "eq") == 0) {
|
||||
// FIX #10: Obsługa EQ od Pythona
|
||||
// TODO: Zaimplementować wyświetlanie EQ na ekranie
|
||||
} else if (strcmp(cmd, "img_qoi") == 0) {
|
||||
// FIX #11: Obsługa transferu okładki
|
||||
// TODO: Zaimplementować odbiór chunków QOI
|
||||
}
|
||||
}
|
||||
|
||||
void draw_full_ui() {
|
||||
tft.fillRect(0, 0, 480, 38, PYLONIS_DARK);
|
||||
tft.drawFastHLine(0, 38, 480, TFT_DARKGREY);
|
||||
|
||||
u8g2.setCursor(10, 25);
|
||||
u8g2.print(np_station);
|
||||
|
||||
// Dodatkowe rysowanie tytułu i artysty
|
||||
u8g2.setCursor(10, 55);
|
||||
u8g2.print(np_title);
|
||||
u8g2.setCursor(10, 80);
|
||||
u8g2.print(np_artist);
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Bluetooth Manager — fasada nad BluetoothSource.
|
||||
Udostępnia API dla routes.py: scan, pair, connect, disconnect, list.
|
||||
Obsługuje też auto-connect przy starcie.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from typing import Optional, List
|
||||
from source import BluetoothSource
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BTManager:
|
||||
def __init__(self, bt_source: BluetoothSource):
|
||||
self._src = bt_source
|
||||
self._scan_thread: Optional[threading.Thread] = None
|
||||
self._scanning = False
|
||||
|
||||
def get_paired(self) -> List[dict]:
|
||||
return self._src.get_paired_devices()
|
||||
|
||||
def scan_async(self, duration: int = 10, callback=None):
|
||||
"""Skanuj w tle, wywołaj callback(devices) po zakończeniu."""
|
||||
if self._scanning:
|
||||
return
|
||||
self._scanning = True
|
||||
def _do():
|
||||
try:
|
||||
devices = self._src.scan_devices(duration)
|
||||
if callback:
|
||||
callback(devices)
|
||||
finally:
|
||||
self._scanning = False
|
||||
self._scan_thread = threading.Thread(target=_do, daemon=True, name='bt-scan')
|
||||
self._scan_thread.start()
|
||||
|
||||
def pair(self, mac: str) -> bool:
|
||||
return self._src.pair_device(mac)
|
||||
|
||||
def connect(self, mac: str) -> bool:
|
||||
return self._src.connect_device(mac)
|
||||
|
||||
def disconnect(self, mac: str):
|
||||
self._src.disconnect_device(mac)
|
||||
|
||||
def remove(self, mac: str):
|
||||
self._src.remove_device(mac)
|
||||
|
||||
def set_mode(self, mode: str):
|
||||
"""'sink' lub 'source'."""
|
||||
self._src.set_mode(mode)
|
||||
|
||||
@property
|
||||
def scanning(self) -> bool:
|
||||
return self._scanning
|
||||
|
||||
@property
|
||||
def mode(self) -> str:
|
||||
return self._src._mode
|
||||
|
||||
@property
|
||||
def connected_device(self) -> Optional[str]:
|
||||
return self._src._connected_dev
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
PylonisAmp — CD Manager
|
||||
Detekcja napędu CD/DVD przez pyudev.
|
||||
Emituje eventy: cd_drive_added, cd_drive_removed, cd_disc_inserted, cd_disc_ejected
|
||||
"""
|
||||
import logging
|
||||
import threading
|
||||
try:
|
||||
import pyudev
|
||||
PYUDEV_OK = True
|
||||
except ImportError:
|
||||
PYUDEV_OK = False
|
||||
|
||||
log = logging.getLogger('cd_manager')
|
||||
|
||||
class CDManager:
|
||||
def __init__(self, on_event=None):
|
||||
self._on_event = on_event # callback(event, data)
|
||||
self._drive = None # /dev/sr0
|
||||
self._disc_ready = False
|
||||
self._running = False
|
||||
self._thread = None
|
||||
|
||||
def start(self):
|
||||
if not PYUDEV_OK:
|
||||
log.warning("pyudev nie zainstalowane — detekcja CD wyłączona")
|
||||
return
|
||||
self._running = True
|
||||
self._thread = threading.Thread(target=self._monitor, daemon=True)
|
||||
self._thread.start()
|
||||
log.info("CD monitor started")
|
||||
|
||||
def stop(self):
|
||||
self._running = False
|
||||
|
||||
@property
|
||||
def drive_present(self):
|
||||
return self._drive is not None
|
||||
|
||||
@property
|
||||
def disc_ready(self):
|
||||
return self._disc_ready
|
||||
|
||||
def _monitor(self):
|
||||
context = pyudev.Context()
|
||||
# Sprawdź istniejące urządzenia przy starcie
|
||||
for dev in context.list_devices(subsystem='block', DEVTYPE='disk'):
|
||||
if dev.get('ID_TYPE') == 'cd':
|
||||
self._drive = dev.device_node
|
||||
log.info(f"CD drive found at start: {self._drive}")
|
||||
self._check_disc(dev)
|
||||
if self._on_event:
|
||||
self._on_event('cd_drive_added', {'drive': self._drive})
|
||||
|
||||
monitor = pyudev.Monitor.from_netlink(context)
|
||||
monitor.filter_by('block')
|
||||
for device in iter(monitor.poll, None):
|
||||
if not self._running:
|
||||
break
|
||||
if device.get('ID_TYPE') != 'cd':
|
||||
continue
|
||||
action = device.action
|
||||
if action == 'add':
|
||||
self._drive = device.device_node
|
||||
log.info(f"CD drive added: {self._drive}")
|
||||
if self._on_event:
|
||||
self._on_event('cd_drive_added', {'drive': self._drive})
|
||||
elif action == 'remove':
|
||||
log.info(f"CD drive removed: {self._drive}")
|
||||
self._drive = None
|
||||
self._disc_ready = False
|
||||
if self._on_event:
|
||||
self._on_event('cd_drive_removed', {})
|
||||
elif action == 'change':
|
||||
self._check_disc(device)
|
||||
|
||||
def _check_disc(self, device):
|
||||
# ID_CDROM_MEDIA=1 gdy płyta jest włożona
|
||||
media = device.get('ID_CDROM_MEDIA') == '1'
|
||||
if media and not self._disc_ready:
|
||||
self._disc_ready = True
|
||||
log.info("CD disc inserted")
|
||||
if self._on_event:
|
||||
self._on_event('cd_disc_inserted', {'drive': self._drive})
|
||||
elif not media and self._disc_ready:
|
||||
self._disc_ready = False
|
||||
log.info("CD disc ejected")
|
||||
if self._on_event:
|
||||
self._on_event('cd_disc_ejected', {})
|
||||
@@ -0,0 +1,240 @@
|
||||
"""
|
||||
PylonisAmp — Cover Manager
|
||||
Pobiera okładki albumów i loga stacji radiowych.
|
||||
|
||||
Priorytet:
|
||||
1. MusicBrainz Cover Art Archive
|
||||
2. iTunes Search API
|
||||
3. Last.fm API
|
||||
4. Logo stacji radiowej (gdy brak artysty/tytułu)
|
||||
5. placeholder (None)
|
||||
|
||||
Cache: streamer/covers/{hash}.jpg (240×240 JPEG)
|
||||
"""
|
||||
|
||||
import os
|
||||
import hashlib
|
||||
import logging
|
||||
import requests
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
|
||||
log = logging.getLogger('cover_manager')
|
||||
|
||||
COVERS_DIR = Path(__file__).parent.parent / 'covers'
|
||||
COVER_SIZE = (240, 240)
|
||||
JPEG_QUALITY = 95
|
||||
HTTP_TIMEOUT = 10 # sekundy
|
||||
|
||||
COVERS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
# ── Główny interfejs ─────────────────────────────────────────────────────────
|
||||
|
||||
def get_cover(artist: str, title: str, station_name: str = '') -> str | None:
|
||||
"""
|
||||
Zwróć ścieżkę do pliku okładki (240×240 JPEG).
|
||||
Jeśli nie ma w cache — pobierz i zapisz.
|
||||
Zwróć None jeśli nie udało się pobrać.
|
||||
"""
|
||||
cover_id = _make_id(artist, title, station_name)
|
||||
cache_path = COVERS_DIR / f'{cover_id}.jpg'
|
||||
|
||||
if cache_path.exists():
|
||||
log.debug(f'Cover cache hit: {cover_id}')
|
||||
return str(cache_path)
|
||||
|
||||
log.info(f'Cover cache miss: {cover_id} — pobieranie...')
|
||||
img_url = None
|
||||
|
||||
if artist and title:
|
||||
# Szukaj okładki albumu
|
||||
img_url = (_try_musicbrainz(artist, title)
|
||||
or _try_itunes(artist, title)
|
||||
or _try_lastfm(artist, title))
|
||||
|
||||
if not img_url and station_name:
|
||||
# Brak okładki — spróbuj logo stacji
|
||||
img_url = _try_station_logo(station_name)
|
||||
|
||||
if not img_url:
|
||||
log.debug(f'Brak okładki dla: {artist} — {title} / {station_name}')
|
||||
return None
|
||||
|
||||
return _download_and_cache(img_url, cache_path)
|
||||
|
||||
def get_cover_url(artist: str, title: str, station_name: str = '') -> str | None:
|
||||
"""Zwróć URL do serwowania przez /api/cover — relative path."""
|
||||
path = get_cover(artist, title, station_name)
|
||||
if not path:
|
||||
return None
|
||||
return f'/api/cover/{os.path.basename(path)}'
|
||||
|
||||
|
||||
def cover_id_for(artist: str, title: str, station_name: str = '') -> str:
|
||||
return _make_id(artist, title, station_name)
|
||||
|
||||
|
||||
# ── Źródła ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def _try_musicbrainz(artist: str, title: str) -> str | None:
|
||||
"""MusicBrainz Cover Art Archive."""
|
||||
try:
|
||||
# Szukaj nagrania
|
||||
url = 'https://musicbrainz.org/ws/2/recording'
|
||||
params = {
|
||||
'query': f'recording:"{title}" AND artist:"{artist}"',
|
||||
'fmt': 'json',
|
||||
'limit': 5,
|
||||
}
|
||||
headers = {'User-Agent': 'PylonisAmp/1.0 (pylonisamp@localhost)'}
|
||||
r = requests.get(url, params=params, headers=headers, timeout=HTTP_TIMEOUT)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
|
||||
data = r.json()
|
||||
recordings = data.get('recordings', [])
|
||||
|
||||
for rec in recordings:
|
||||
for release in rec.get('releases', []):
|
||||
rid = release.get('id')
|
||||
if not rid:
|
||||
continue
|
||||
# Sprawdź Cover Art Archive
|
||||
ca_url = f'https://coverartarchive.org/release/{rid}/front-250'
|
||||
try:
|
||||
cr = requests.head(ca_url, timeout=HTTP_TIMEOUT, allow_redirects=True)
|
||||
if cr.status_code == 200:
|
||||
log.debug(f'MusicBrainz cover: {ca_url}')
|
||||
return ca_url
|
||||
except Exception:
|
||||
continue
|
||||
except Exception as e:
|
||||
log.debug(f'MusicBrainz error: {e}')
|
||||
return None
|
||||
|
||||
def _try_itunes(artist: str, title: str) -> str | None:
|
||||
"""iTunes Search API."""
|
||||
try:
|
||||
r = requests.get(
|
||||
'https://itunes.apple.com/search',
|
||||
params={'term': f'{artist} {title}', 'media': 'music', 'limit': 3},
|
||||
timeout=HTTP_TIMEOUT
|
||||
)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
results = r.json().get('results', [])
|
||||
for item in results:
|
||||
art = item.get('artworkUrl100', '')
|
||||
if art:
|
||||
# Zamień 100x100 na 240x240
|
||||
art = art.replace('100x100', '240x240')
|
||||
log.debug(f'iTunes cover: {art}')
|
||||
return art
|
||||
except Exception as e:
|
||||
log.debug(f'iTunes error: {e}')
|
||||
return None
|
||||
|
||||
def _try_lastfm(artist: str, title: str) -> str | None:
|
||||
"""
|
||||
Last.fm API - wymaga klucza API.
|
||||
Jeśli nie masz klucza, zostaw 'LASTFM_API_KEY_PLACEHOLDER'
|
||||
a ta funkcja zwróci None bez próby zapytania.
|
||||
|
||||
Jak uzyskać klucz: https://www.last.fm/api/account/create
|
||||
"""
|
||||
# Sprawdź czy mamy prawdziwy klucz API
|
||||
api_key = 'LASTFM_API_KEY_PLACEHOLDER'
|
||||
if not api_key or api_key == 'LASTFM_API_KEY_PLACEHOLDER' or len(api_key) < 10:
|
||||
# Brak klucza - pomiń Last.fm
|
||||
return None
|
||||
|
||||
try:
|
||||
r = requests.get(
|
||||
'https://ws.audioscrobbler.com/2.0/',
|
||||
params={
|
||||
'method': 'track.getInfo',
|
||||
'artist': artist,
|
||||
'track': title,
|
||||
'api_key': api_key,
|
||||
'format': 'json',
|
||||
},
|
||||
timeout=HTTP_TIMEOUT
|
||||
)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
data = r.json()
|
||||
images = data.get('track', {}).get('album', {}).get('image', [])
|
||||
# Wybierz największy rozmiar
|
||||
for img in reversed(images):
|
||||
url = img.get('#text', '')
|
||||
if url and 'noimage' not in url:
|
||||
log.debug(f'Last.fm cover: {url}')
|
||||
return url
|
||||
except Exception as e:
|
||||
log.debug(f'Last.fm error: {e}')
|
||||
return None
|
||||
|
||||
def _try_station_logo(station_name: str) -> str | None:
|
||||
"""
|
||||
Pobierz logo stacji radiowej.
|
||||
Używa RadioBrowser API — darmowe, bez klucza.
|
||||
"""
|
||||
try:
|
||||
r = requests.get(
|
||||
'https://de1.api.radio-browser.info/json/stations/byname/' +
|
||||
requests.utils.quote(station_name),
|
||||
params={'limit': 3},
|
||||
headers={'User-Agent': 'PylonisAmp/1.0'},
|
||||
timeout=HTTP_TIMEOUT
|
||||
)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
stations = r.json()
|
||||
for station in stations:
|
||||
favicon = station.get('favicon', '')
|
||||
if favicon and favicon.startswith('http'):
|
||||
log.debug(f'Station logo: {favicon}')
|
||||
return favicon
|
||||
except Exception as e:
|
||||
log.debug(f'Station logo error: {e}')
|
||||
return None
|
||||
|
||||
|
||||
# ── Cache helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
def _make_id(artist: str, title: str, station: str) -> str:
|
||||
"""Generuj unikalny ID dla kombinacji artysta+tytuł lub stacja."""
|
||||
key = f'{artist.lower()}|{title.lower()}|{station.lower()}'
|
||||
return hashlib.md5(key.encode()).hexdigest()[:12]
|
||||
|
||||
|
||||
def _download_and_cache(url: str, path: Path) -> str | None:
|
||||
"""Pobierz obraz, przeskaluj do 240×240, zapisz jako JPEG."""
|
||||
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 ({url}): {e}')
|
||||
return None
|
||||
|
||||
|
||||
def cleanup_cache(max_mb: int = 500):
|
||||
"""Usuń najstarsze okładki gdy cache przekracza max_mb MB."""
|
||||
files = sorted(COVERS_DIR.glob('*.jpg'), key=lambda f: f.stat().st_mtime)
|
||||
total = sum(f.stat().st_size for f in files)
|
||||
limit = max_mb * 1024 * 1024
|
||||
while total > limit and files:
|
||||
f = files.pop(0)
|
||||
total -= f.stat().st_size
|
||||
f.unlink()
|
||||
log.info(f'Cover cache evicted: {f.name}')
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
EQ Manager — zarządza nastawnymi 10-pasm EQ per źródło.
|
||||
Predefiniowane presety, zapis/odczyt z config.json.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import logging
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
CONFIG_PATH = os.path.join(os.path.dirname(__file__), '..', 'config.json')
|
||||
|
||||
EQ_BANDS = ['31Hz','63Hz','125Hz','250Hz','500Hz','1kHz','2kHz','4kHz','8kHz','16kHz']
|
||||
|
||||
PRESETS = {
|
||||
'flat': [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
'bass': [ 6, 5, 4, 2, 0, 0, 0, 0, 0, 0],
|
||||
'treble': [ 0, 0, 0, 0, 0, 1, 2, 4, 5, 6],
|
||||
'vocal': [-1, -1, 0, 2, 4, 4, 3, 1, 0, -1],
|
||||
'loudness': [ 4, 2, 0, 0, 0, 0, 0, 1, 2, 3],
|
||||
'pop': [-1, 0, 2, 3, 2, 0, -1, 0, 1, 2],
|
||||
'rock': [ 3, 2, 0, -1, -1, 1, 3, 4, 4, 3],
|
||||
'jazz': [ 3, 2, 0, 2, 3, 3, 2, 1, 2, 3],
|
||||
'classical': [ 0, 0, 0, 0, 0, 0, -2, -2, -2, -3],
|
||||
'user1': [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
'user2': [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
}
|
||||
|
||||
# Nazwy user presetów — mogą być zmienione przez użytkownika
|
||||
USER_PRESET_NAMES = {
|
||||
'user1': 'User 1',
|
||||
'user2': 'User 2',
|
||||
}
|
||||
|
||||
SOURCE_DEFAULTS = {
|
||||
'radio': [ 0, 2, 3, 2, 0, -1, 0, 1, 2, 1],
|
||||
'bluetooth': [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
'phono': [ 3, 2, 1, 0, 0, 0, -1, -1, 0, 1],
|
||||
'line1': [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
'line2': [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
'spdif': [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
}
|
||||
|
||||
|
||||
class EQManager:
|
||||
def __init__(self):
|
||||
self._eq = self._load()
|
||||
|
||||
def get(self, source_id: str) -> list:
|
||||
return self._eq.get(source_id, SOURCE_DEFAULTS.get(source_id, [0]*10))[:]
|
||||
|
||||
def set(self, source_id: str, gains: list) -> list:
|
||||
if len(gains) != 10:
|
||||
raise ValueError("gains must have 10 elements")
|
||||
clamped = [max(-24.0, min(12.0, g)) for g in gains]
|
||||
self._eq[source_id] = clamped
|
||||
self._save()
|
||||
return clamped
|
||||
|
||||
def set_band(self, source_id: str, band: int, gain: float) -> list:
|
||||
gains = self.get(source_id)
|
||||
gains[band] = max(-24.0, min(12.0, gain))
|
||||
return self.set(source_id, gains)
|
||||
|
||||
def apply_preset(self, source_id: str, preset_name: str) -> list:
|
||||
if preset_name not in PRESETS:
|
||||
raise ValueError(f"Unknown preset: {preset_name}. Available: {list(PRESETS)}")
|
||||
return self.set(source_id, PRESETS[preset_name][:])
|
||||
|
||||
def reset(self, source_id: str) -> list:
|
||||
return self.set(source_id, SOURCE_DEFAULTS.get(source_id, [0]*10)[:])
|
||||
|
||||
def get_presets(self) -> dict:
|
||||
return {name: gains[:] for name, gains in PRESETS.items()}
|
||||
|
||||
def get_preset_names(self) -> dict:
|
||||
"""Zwróć nazwy user presetów."""
|
||||
try:
|
||||
with open(CONFIG_PATH) as f:
|
||||
cfg = json.load(f)
|
||||
names = cfg.get('preset_names', {})
|
||||
except Exception:
|
||||
names = {}
|
||||
return {k: names.get(k, v) for k, v in USER_PRESET_NAMES.items()}
|
||||
|
||||
def set_preset_name(self, preset_id: str, name: str) -> str:
|
||||
"""Zmień nazwe user presetu."""
|
||||
if preset_id not in USER_PRESET_NAMES:
|
||||
raise ValueError(f"Only user presets can be renamed: {list(USER_PRESET_NAMES)}")
|
||||
name = name.strip()[:32]
|
||||
try:
|
||||
with open(CONFIG_PATH) as f:
|
||||
cfg = json.load(f)
|
||||
except Exception:
|
||||
cfg = {}
|
||||
if 'preset_names' not in cfg:
|
||||
cfg['preset_names'] = {}
|
||||
cfg['preset_names'][preset_id] = name
|
||||
with open(CONFIG_PATH, 'w') as f:
|
||||
json.dump(cfg, f, indent=2, ensure_ascii=False)
|
||||
return name
|
||||
|
||||
def save_user_preset(self, preset_id: str, gains: list) -> list:
|
||||
"""Zapisz bieżące nastawy jako user preset."""
|
||||
if preset_id not in USER_PRESET_NAMES:
|
||||
raise ValueError(f"Not a user preset: {preset_id}")
|
||||
PRESETS[preset_id] = [max(-24.0, min(12.0, g)) for g in gains]
|
||||
self._save_preset_gains(preset_id, PRESETS[preset_id])
|
||||
return PRESETS[preset_id][:]
|
||||
|
||||
def _save_preset_gains(self, preset_id: str, gains: list):
|
||||
try:
|
||||
with open(CONFIG_PATH) as f:
|
||||
cfg = json.load(f)
|
||||
except Exception:
|
||||
cfg = {}
|
||||
if 'user_presets' not in cfg:
|
||||
cfg['user_presets'] = {}
|
||||
cfg['user_presets'][preset_id] = gains
|
||||
with open(CONFIG_PATH, 'w') as f:
|
||||
json.dump(cfg, f, indent=2, ensure_ascii=False)
|
||||
|
||||
def _load(self) -> dict:
|
||||
try:
|
||||
with open(CONFIG_PATH) as f:
|
||||
cfg = json.load(f)
|
||||
# Wczytaj user preset gains jeśli zapisane
|
||||
for pid in USER_PRESET_NAMES:
|
||||
if pid in cfg.get('user_presets', {}):
|
||||
PRESETS[pid] = cfg['user_presets'][pid]
|
||||
return cfg.get('eq', {})
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def get_band_names(self) -> list:
|
||||
return EQ_BANDS[:]
|
||||
|
||||
# ── Persistence ────────────────────────────────────────────
|
||||
|
||||
|
||||
def _save(self):
|
||||
try:
|
||||
try:
|
||||
with open(CONFIG_PATH) as f:
|
||||
cfg = json.load(f)
|
||||
except Exception:
|
||||
cfg = {}
|
||||
cfg['eq'] = self._eq
|
||||
with open(CONFIG_PATH, 'w') as f:
|
||||
json.dump(cfg, f, indent=2, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
log.error(f"EQ save error: {e}")
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
LED Manager - Obsługa asynchronicznego oddychania turkusowego
|
||||
Każda z 8 diod oddycha niezależnie z randomowym offsetem
|
||||
"""
|
||||
|
||||
import time
|
||||
import threading
|
||||
import json
|
||||
import logging
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
class LEDManager:
|
||||
def __init__(self, uart_manager=None):
|
||||
"""
|
||||
Inicjalizuj LED manager
|
||||
uart_manager - opcjonalnie, jeśli masz dostęp do UART/USB
|
||||
"""
|
||||
self.uart = uart_manager
|
||||
self.running = False
|
||||
self.thread = None
|
||||
|
||||
def start(self):
|
||||
"""Uruchom pętlę LED"""
|
||||
if self.running:
|
||||
return
|
||||
|
||||
self.running = True
|
||||
self.thread = threading.Thread(target=self._loop, daemon=True)
|
||||
self.thread.start()
|
||||
log.info("✅ LED manager uruchomiony")
|
||||
|
||||
def stop(self):
|
||||
"""Zatrzymaj pętlę LED"""
|
||||
self.running = False
|
||||
if self.thread:
|
||||
self.thread.join(timeout=1)
|
||||
|
||||
def _loop(self):
|
||||
"""
|
||||
GŁÓWNA PĘTLA LED
|
||||
Oddychanie turkusowe - każda dioda asynchronicznie
|
||||
"""
|
||||
while self.running:
|
||||
now = time.time() * 1000 # milliseconds
|
||||
|
||||
# Tablica jasności dla 8 diod
|
||||
brightness = [0] * 8
|
||||
|
||||
for led_idx in range(8):
|
||||
# RANDOMOWY OFFSET dla każdej diody
|
||||
# 875ms delay między diodami = 8 diod × ~1s świecenia
|
||||
offset = (led_idx * 875)
|
||||
|
||||
# Pełny cykl: 7 sekund
|
||||
cycle_time = (now + offset) % 7000
|
||||
|
||||
# FAZY ODDYCHANIA:
|
||||
if cycle_time < 2000:
|
||||
# FAZA 1: 0-2s PAUSE (ciemno)
|
||||
brightness[led_idx] = 0
|
||||
|
||||
elif cycle_time < 4000:
|
||||
# FAZA 2: 2-4s NARASTANIE (0% → 20%)
|
||||
progress = (cycle_time - 2000) / 2000.0
|
||||
brightness[led_idx] = int(20 * progress)
|
||||
|
||||
elif cycle_time < 5000:
|
||||
# FAZA 3: 4-5s ŚWIECENIE (20% jasności)
|
||||
brightness[led_idx] = 20
|
||||
|
||||
else:
|
||||
# FAZA 4: 5-7s WYGASZANIE (20% → 0%)
|
||||
progress = (7000 - cycle_time) / 2000.0
|
||||
brightness[led_idx] = int(20 * progress)
|
||||
|
||||
# Wyślij do firmware
|
||||
self._send_led_command(brightness)
|
||||
|
||||
# 50ms refresh (20 Hz)
|
||||
time.sleep(0.05)
|
||||
|
||||
def _send_led_command(self, brightness_values):
|
||||
"""Wyślij komendy LED do firmware"""
|
||||
if not self.uart or not self.uart._fp:
|
||||
return
|
||||
|
||||
try:
|
||||
# Format: {"cmd":"leds","brightness":[b0,b1,b2,b3,b4,b5,b6,b7]}
|
||||
# Gdzie każde b = 0-20 (procent jasności)
|
||||
cmd = {
|
||||
"cmd": "leds",
|
||||
"brightness": brightness_values
|
||||
}
|
||||
|
||||
self.uart._fp._send(cmd)
|
||||
except Exception as e:
|
||||
log.debug(f"LED send error: {e}")
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Network Manager — WiFi przez nmcli (NetworkManager).
|
||||
Scan, connect, status, aktualne IP.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import logging
|
||||
import re
|
||||
from typing import List, Optional
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _run(cmd: list, timeout: int = 15) -> tuple:
|
||||
"""Uruchom polecenie, zwróć (stdout, stderr, returncode)."""
|
||||
try:
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
||||
return r.stdout.strip(), r.stderr.strip(), r.returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
return '', 'timeout', -1
|
||||
except FileNotFoundError:
|
||||
return '', 'nmcli not found', -1
|
||||
|
||||
|
||||
class NetworkManager:
|
||||
|
||||
def get_status(self) -> dict:
|
||||
"""Zwróć status połączenia sieciowego (WiFi lub Ethernet)."""
|
||||
# Aktywne połączenia
|
||||
stdout, _, rc = _run(['nmcli', '-t', '-f',
|
||||
'DEVICE,TYPE,STATE,CONNECTION',
|
||||
'device'])
|
||||
result = {
|
||||
'connected': False,
|
||||
'ssid': '',
|
||||
'ip': '',
|
||||
'signal': None,
|
||||
'interface': '',
|
||||
}
|
||||
if rc != 0:
|
||||
return result
|
||||
|
||||
# Szukaj najpierw Ethernet (preferowany), potem WiFi
|
||||
wifi_line = None
|
||||
eth_line = None
|
||||
for line in stdout.splitlines():
|
||||
parts = line.split(':')
|
||||
if len(parts) < 3:
|
||||
continue
|
||||
device = parts[0]
|
||||
dev_type = parts[1]
|
||||
state = parts[2]
|
||||
if 'connected' not in state.lower():
|
||||
continue
|
||||
if dev_type not in ('wifi', 'ethernet'):
|
||||
continue
|
||||
if dev_type == 'wifi' and wifi_line is None:
|
||||
wifi_line = [device, dev_type, state] + parts[3:]
|
||||
elif dev_type == 'ethernet' and eth_line is None:
|
||||
eth_line = [device, dev_type, state] + parts[3:]
|
||||
|
||||
chosen = eth_line or wifi_line # eth0 ma priorytet nad wlan0
|
||||
if chosen:
|
||||
dev_type = chosen[1]
|
||||
result['connected'] = True
|
||||
result['interface'] = chosen[0]
|
||||
result['ssid'] = chosen[3] if len(chosen) > 3 and dev_type == 'wifi' else ''
|
||||
result['ip'] = self._get_ip(chosen[0])
|
||||
result['signal'] = self._get_signal(chosen[0]) if dev_type == 'wifi' else None
|
||||
# Zawsze pobierz IP bezpośrednio — nmcli może zwrócić wlan0 mimo że eth0 ma IP
|
||||
if result['connected'] and not result['ip']:
|
||||
result['ip'] = self._get_ip(result['interface'])
|
||||
# Ostateczny fallback
|
||||
if not result['ip']:
|
||||
for iface in ['eth0', 'wlan0', 'end0']:
|
||||
ip = self._get_ip(iface)
|
||||
if ip:
|
||||
result['connected'] = True
|
||||
result['ip'] = ip
|
||||
if not result['interface']:
|
||||
result['interface'] = iface
|
||||
break
|
||||
|
||||
return result
|
||||
|
||||
def scan(self) -> List[dict]:
|
||||
"""Skanuj dostępne sieci WiFi."""
|
||||
# Odśwież listę
|
||||
_run(['nmcli', 'device', 'wifi', 'rescan'], timeout=5)
|
||||
|
||||
stdout, _, rc = _run(['nmcli', '-t', '-f',
|
||||
'SSID,SIGNAL,SECURITY,IN-USE',
|
||||
'device', 'wifi', 'list'])
|
||||
networks = []
|
||||
seen = set()
|
||||
if rc != 0:
|
||||
return networks
|
||||
|
||||
for line in stdout.splitlines():
|
||||
parts = line.split(':')
|
||||
if len(parts) < 4:
|
||||
continue
|
||||
ssid = parts[0]
|
||||
signal = self._safe_int(parts[1], 0)
|
||||
security = parts[2]
|
||||
in_use = parts[3] == '*'
|
||||
|
||||
if not ssid or ssid in seen:
|
||||
continue
|
||||
seen.add(ssid)
|
||||
networks.append({
|
||||
'ssid': ssid,
|
||||
'signal': signal,
|
||||
'security': security or 'Open',
|
||||
'in_use': in_use,
|
||||
})
|
||||
|
||||
# Sortuj: aktywne pierwsze, potem po sile sygnału
|
||||
networks.sort(key=lambda n: (not n['in_use'], -n['signal']))
|
||||
return networks
|
||||
|
||||
def connect(self, ssid: str, password: str = '') -> dict:
|
||||
"""Połącz z siecią WiFi."""
|
||||
if password:
|
||||
cmd = ['nmcli', 'device', 'wifi', 'connect', ssid,
|
||||
'password', password]
|
||||
else:
|
||||
cmd = ['nmcli', 'device', 'wifi', 'connect', ssid]
|
||||
|
||||
stdout, stderr, rc = _run(cmd, timeout=30)
|
||||
if rc == 0:
|
||||
return {'status': 'connected', 'ssid': ssid}
|
||||
else:
|
||||
return {'status': 'error', 'message': stderr or stdout}
|
||||
|
||||
def disconnect(self) -> dict:
|
||||
"""Rozłącz aktywne WiFi."""
|
||||
stdout, stderr, rc = _run(['nmcli', 'device', 'disconnect', 'wlan0'])
|
||||
if rc == 0:
|
||||
return {'status': 'disconnected'}
|
||||
return {'status': 'error', 'message': stderr}
|
||||
|
||||
def get_ip(self, interface: str = 'wlan0') -> Optional[str]:
|
||||
return self._get_ip(interface)
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────
|
||||
|
||||
def _get_ip(self, interface: str) -> str:
|
||||
# Sprawdź podany interface
|
||||
stdout, _, rc = _run(['ip', '-4', 'addr', 'show', interface])
|
||||
if rc == 0:
|
||||
m = re.search(r'inet (\d+\.\d+\.\d+\.\d+)', stdout)
|
||||
if m:
|
||||
return m.group(1)
|
||||
# Fallback: znajdź IP na dowolnym aktywnym interfejsie (eth0, wlan0)
|
||||
for iface in ['eth0', 'wlan0', 'end0']:
|
||||
stdout, _, rc = _run(['ip', '-4', 'addr', 'show', iface])
|
||||
if rc == 0:
|
||||
m = re.search(r'inet (\d+\.\d+\.\d+\.\d+)', stdout)
|
||||
if m and not m.group(1).startswith('127.'):
|
||||
return m.group(1)
|
||||
return ''
|
||||
|
||||
def _get_interface(self) -> str:
|
||||
"""Zwróć nazwę aktywnego interfejsu sieciowego."""
|
||||
for iface in ['eth0', 'wlan0', 'end0']:
|
||||
stdout, _, rc = _run(['ip', '-4', 'addr', 'show', iface])
|
||||
if rc == 0:
|
||||
m = re.search(r'inet (\d+\.\d+\.\d+\.\d+)', stdout)
|
||||
if m and not m.group(1).startswith('127.'):
|
||||
return iface
|
||||
return ''
|
||||
|
||||
def set_wifi_enabled(self, enabled: bool) -> bool:
|
||||
"""Włącz lub wyłącz WiFi przez nmcli."""
|
||||
cmd = 'on' if enabled else 'off'
|
||||
_, _, rc = _run(['nmcli', 'radio', 'wifi', cmd])
|
||||
return rc == 0
|
||||
|
||||
def get_wifi_enabled(self) -> bool:
|
||||
"""Sprawdź czy WiFi jest włączone."""
|
||||
stdout, _, rc = _run(['nmcli', 'radio', 'wifi'])
|
||||
return rc == 0 and 'enabled' in stdout.lower()
|
||||
|
||||
def _get_ip_legacy(self, interface: str) -> str:
|
||||
stdout, _, rc = _run(['ip', '-4', 'addr', 'show', interface])
|
||||
if rc != 0:
|
||||
return ''
|
||||
m = re.search(r'inet (\d+\.\d+\.\d+\.\d+)', stdout)
|
||||
return m.group(1) if m else ''
|
||||
|
||||
def _get_signal(self, interface: str) -> Optional[int]:
|
||||
stdout, _, rc = _run(['nmcli', '-t', '-f', 'SIGNAL',
|
||||
'device', 'wifi'])
|
||||
if rc == 0:
|
||||
for line in stdout.splitlines():
|
||||
try:
|
||||
return int(line.strip())
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
def _safe_int(self, s: str, default: int = 0) -> int:
|
||||
try:
|
||||
return int(s)
|
||||
except (ValueError, TypeError):
|
||||
return default
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"version": "3.0",
|
||||
"stations": [
|
||||
{
|
||||
"id": "rmf",
|
||||
"name": "RMF FM",
|
||||
"url": "https://rs201-krk.rmfstream.pl/rmf_fm",
|
||||
"genre": "Pop/Rock",
|
||||
"bitrate": 128,
|
||||
"codec": "MP3",
|
||||
"favorite": false,
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"id": "tok",
|
||||
"name": "TOK FM",
|
||||
"url": "https://n-22-14.dcs.redcdn.pl/sc/o2/Eurozet/live/tokfm.livx?audio=5",
|
||||
"genre": "News",
|
||||
"bitrate": 128,
|
||||
"codec": "AAC",
|
||||
"favorite": false,
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"id": "trancepulse",
|
||||
"name": "TrancePulse",
|
||||
"url": "http://stream.trance.ie:8000/tpmixes",
|
||||
"genre": "Trance",
|
||||
"bitrate": 1400,
|
||||
"codec": "FLAC",
|
||||
"favorite": true,
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"id": "radioclubtr",
|
||||
"name": "Radio Club Trance",
|
||||
"url": "https://stream.radioclubtrance.com/stream",
|
||||
"genre": "Trance",
|
||||
"bitrate": 128,
|
||||
"codec": "MP3",
|
||||
"favorite": false,
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"id": "dhectar",
|
||||
"name": "DHECTAR Hits",
|
||||
"url": "https://stream.dhectar.com/hits",
|
||||
"genre": "Hits",
|
||||
"bitrate": 128,
|
||||
"codec": "MP3",
|
||||
"favorite": false,
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"id": "intense",
|
||||
"name": "Intense Radio",
|
||||
"url": "https://www.intenseradio.com/stream",
|
||||
"genre": "Electronic",
|
||||
"bitrate": 256,
|
||||
"codec": "MP3",
|
||||
"favorite": true,
|
||||
"enabled": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
PylonisAmp — source.py
|
||||
Silnik audio: playbin (GStreamer) + zarządzanie źródłami.
|
||||
"""
|
||||
|
||||
import gi
|
||||
gi.require_version('Gst', '1.0')
|
||||
gi.require_version('GLib', '2.0')
|
||||
from gi.repository import Gst, GLib
|
||||
|
||||
import os, re, json, time, logging, threading, subprocess
|
||||
from typing import Optional, List
|
||||
|
||||
Gst.init(None)
|
||||
log = logging.getLogger('source')
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
CONFIG_PATH = os.path.join(BASE_DIR, 'config.json')
|
||||
STATIONS_PATH = os.path.join(BASE_DIR, 'radio', 'stations.json')
|
||||
|
||||
# ── Spectrum: 4 pasma ręczne + 28 logarytmicznych ─────────────────────────────
|
||||
MANUAL_BANDS = [(0, 80), (80, 160), (160, 320), (320, 640)]
|
||||
|
||||
def _log_edges(n=28, f_lo=640.0, f_hi=20000.0):
|
||||
return [f_lo * (f_hi / f_lo) ** (i / n) for i in range(n + 1)]
|
||||
|
||||
_LOG_EDGES = _log_edges()
|
||||
_RE_MAG = re.compile(r'magnitude=\(float\)\{([^}]+)\}')
|
||||
|
||||
def map_spectrum(raw: List[float], sample_rate: int = 44100) -> List[float]:
|
||||
n_in = len(raw)
|
||||
if not n_in: return [-60.0] * 32
|
||||
hz = (sample_rate / 2.0) / n_in
|
||||
result = []
|
||||
for f_lo, f_hi in MANUAL_BANDS:
|
||||
lo = max(0, int(f_lo / hz))
|
||||
hi = min(n_in - 1, int(f_hi / hz))
|
||||
result.append(max(-60.0, min(0.0, float(max(raw[lo:hi+1]) if lo <= hi else raw[lo]))))
|
||||
for i in range(28):
|
||||
lo = max(0, int(_LOG_EDGES[i] / hz))
|
||||
hi = min(n_in - 1, int(_LOG_EDGES[i+1] / hz))
|
||||
result.append(max(-60.0, min(0.0, float(max(raw[lo:hi+1]) if lo <= hi else raw[lo]))))
|
||||
return result
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
# RadioSource — playbin przez Python API
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class RadioSource:
|
||||
SOURCE_ID = 'radio'
|
||||
SOURCE_NAME = 'Internet Radio'
|
||||
|
||||
def __init__(self, alsa_device='hw:1,0', on_state=None, on_meta=None):
|
||||
self._alsa = alsa_device
|
||||
self._on_state = on_state
|
||||
self._on_meta = on_meta
|
||||
self._playbin: Optional[Gst.Element] = None
|
||||
self._url = ''
|
||||
self._station = ''
|
||||
self._title = ''
|
||||
self._artist = ''
|
||||
self._state = 'stopped'
|
||||
self._vol = 0.5
|
||||
self._reconnect = ''
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# Pomiary
|
||||
self._rms_l = self._rms_r = self._peak_l = self._peak_r = -60.0
|
||||
self._bands: List[float] = [-60.0] * 32
|
||||
|
||||
# Jeden GLib loop dla bus messages
|
||||
self._glib = GLib.MainLoop()
|
||||
threading.Thread(target=self._glib.run, daemon=True,
|
||||
name='radio-glib').start()
|
||||
|
||||
def play(self, url: str, station: str = ''):
|
||||
log.info(f"Radio play: {station!r} → {url}")
|
||||
self._url = url
|
||||
self._station = station
|
||||
self._title = ''
|
||||
self._artist = ''
|
||||
self._reconnect = url
|
||||
self._stop_playbin()
|
||||
self._start_playbin(url)
|
||||
|
||||
def stop(self):
|
||||
self._reconnect = ''
|
||||
self._stop_playbin()
|
||||
self._set_state('stopped')
|
||||
|
||||
def set_volume(self, vol: int):
|
||||
"""Zmiana głośności bez restartu — natychmiastowa."""
|
||||
self._vol = max(0, min(100, int(vol))) / 100.0
|
||||
if self._playbin:
|
||||
self._playbin.set_property('volume', self._vol)
|
||||
log.debug(f"Volume: {self._vol:.2f}")
|
||||
|
||||
def get_status(self) -> dict:
|
||||
return {
|
||||
'source': self.SOURCE_ID,
|
||||
'state': self._state,
|
||||
'url': self._url,
|
||||
'station': self._station,
|
||||
'title': self._title,
|
||||
'artist': self._artist,
|
||||
}
|
||||
|
||||
def get_meters(self) -> dict:
|
||||
return {
|
||||
'rms_l': round(self._rms_l, 1),
|
||||
'rms_r': round(self._rms_r, 1),
|
||||
'peak_l': round(self._peak_l, 1),
|
||||
'peak_r': round(self._peak_r, 1),
|
||||
'bands': [round(b, 1) for b in self._bands],
|
||||
}
|
||||
|
||||
# ── Pipeline ──────────────────────────────────────────────────────────────
|
||||
|
||||
def _start_playbin(self, url: str):
|
||||
try:
|
||||
playbin = Gst.ElementFactory.make('playbin', 'player')
|
||||
if not playbin:
|
||||
raise RuntimeError("playbin not available")
|
||||
|
||||
# Audio sink z level + spectrum dla pomiarów
|
||||
audio_sink_str = (
|
||||
f'level name=lvl interval=33000000 post-messages=true ! '
|
||||
f'spectrum name=spec bands=1024 interval=33000000 '
|
||||
f'threshold=-70 post-messages=true '
|
||||
f'message-magnitude=true message-phase=false ! '
|
||||
f'alsasink device={self._alsa} sync=false'
|
||||
)
|
||||
audio_sink = Gst.parse_bin_from_description(audio_sink_str, True)
|
||||
|
||||
playbin.set_property('uri', url)
|
||||
playbin.set_property('volume', self._vol)
|
||||
playbin.set_property('audio-sink', audio_sink)
|
||||
|
||||
bus = playbin.get_bus()
|
||||
bus.add_signal_watch()
|
||||
bus.connect('message', self._on_msg, playbin)
|
||||
|
||||
with self._lock:
|
||||
self._playbin = playbin
|
||||
|
||||
ret = playbin.set_state(Gst.State.PLAYING)
|
||||
if ret == Gst.StateChangeReturn.FAILURE:
|
||||
log.error("playbin FAILURE")
|
||||
self._set_state('error')
|
||||
self._schedule_reconnect()
|
||||
else:
|
||||
self._set_state('buffering')
|
||||
log.info(f"playbin started: {url[:60]}")
|
||||
|
||||
except Exception as e:
|
||||
log.error(f"playbin error: {e}", exc_info=True)
|
||||
self._set_state('error')
|
||||
self._schedule_reconnect()
|
||||
|
||||
def _stop_playbin(self):
|
||||
with self._lock:
|
||||
if self._playbin:
|
||||
p, self._playbin = self._playbin, None
|
||||
p.set_state(Gst.State.NULL)
|
||||
p.get_state(Gst.SECOND // 2)
|
||||
|
||||
# ── Bus messages ──────────────────────────────────────────────────────────
|
||||
|
||||
def _on_msg(self, bus, msg, playbin):
|
||||
if playbin is not self._playbin:
|
||||
return
|
||||
|
||||
t = msg.type
|
||||
|
||||
if t == Gst.MessageType.ERROR:
|
||||
err, _ = msg.parse_error()
|
||||
log.warning(f"GST error: {err.message}")
|
||||
self._set_state('buffering')
|
||||
self._schedule_reconnect()
|
||||
|
||||
elif t == Gst.MessageType.EOS:
|
||||
log.info("EOS — reconnecting")
|
||||
self._schedule_reconnect(delay_ms=500)
|
||||
|
||||
elif t == Gst.MessageType.STATE_CHANGED:
|
||||
if msg.src == playbin:
|
||||
_, new, _ = msg.parse_state_changed()
|
||||
if new == Gst.State.PLAYING and self._state != 'playing':
|
||||
self._set_state('playing')
|
||||
|
||||
elif t == Gst.MessageType.BUFFERING:
|
||||
pct = msg.parse_buffering()
|
||||
if pct < 100:
|
||||
playbin.set_state(Gst.State.PAUSED)
|
||||
self._set_state('buffering')
|
||||
else:
|
||||
playbin.set_state(Gst.State.PLAYING)
|
||||
self._set_state('playing')
|
||||
|
||||
elif t == Gst.MessageType.TAG:
|
||||
self._on_tags(msg.parse_tag())
|
||||
|
||||
elif t == Gst.MessageType.ELEMENT:
|
||||
s = msg.get_structure()
|
||||
if s:
|
||||
n = s.get_name()
|
||||
if n == 'level': self._on_level(s)
|
||||
elif n == 'spectrum': self._on_spectrum(s)
|
||||
|
||||
def _on_tags(self, tags):
|
||||
changed = False
|
||||
for gst_tag, attr in [('artist', '_artist'), ('title', '_title')]:
|
||||
ok, val = tags.get_string(gst_tag)
|
||||
if ok and val and val.strip() != getattr(self, attr):
|
||||
setattr(self, attr, val.strip())
|
||||
changed = True
|
||||
if changed and self._on_meta:
|
||||
self._on_meta(self.SOURCE_ID, {
|
||||
'station': self._station,
|
||||
'artist': self._artist,
|
||||
'title': self._title,
|
||||
})
|
||||
|
||||
def _on_level(self, s):
|
||||
try:
|
||||
rms = s.get_value('rms')
|
||||
peak = s.get_value('peak')
|
||||
self._rms_l = float(rms[0])
|
||||
self._rms_r = float(rms[1] if len(rms) > 1 else rms[0])
|
||||
self._peak_l = float(peak[0])
|
||||
self._peak_r = float(peak[1] if len(peak) > 1 else peak[0])
|
||||
except Exception: pass
|
||||
|
||||
def _on_spectrum(self, s):
|
||||
try:
|
||||
m = _RE_MAG.search(s.to_string())
|
||||
if m:
|
||||
raw = [float(x.strip()) for x in m.group(1).split(',') if x.strip()]
|
||||
if raw: self._bands = map_spectrum(raw)
|
||||
except Exception: pass
|
||||
|
||||
# ── Reconnect ─────────────────────────────────────────────────────────────
|
||||
|
||||
def _schedule_reconnect(self, delay_ms: int = 2000):
|
||||
if self._reconnect:
|
||||
GLib.timeout_add(delay_ms, self._do_reconnect, self._reconnect)
|
||||
|
||||
def _do_reconnect(self, url: str) -> bool:
|
||||
if self._reconnect != url:
|
||||
return False
|
||||
log.info(f"Reconnecting: {url[:50]}")
|
||||
|
||||
def _restart():
|
||||
self._stop_playbin()
|
||||
time.sleep(0.3)
|
||||
if self._reconnect == url:
|
||||
self._start_playbin(url)
|
||||
|
||||
threading.Thread(target=_restart, daemon=True,
|
||||
name='radio-reconnect').start()
|
||||
return False
|
||||
|
||||
def _set_state(self, s: str):
|
||||
if s != self._state:
|
||||
self._state = s
|
||||
if self._on_state:
|
||||
self._on_state(self.SOURCE_ID, s)
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
# BluetoothSource
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class BluetoothSource:
|
||||
SOURCE_ID = 'bluetooth'
|
||||
SOURCE_NAME = 'Bluetooth'
|
||||
|
||||
def __init__(self, on_state=None, on_meta=None):
|
||||
self._on_state = on_state
|
||||
self._state = 'stopped'
|
||||
self._connected = None
|
||||
self._connected_dev = None
|
||||
self._bus = None
|
||||
self._init_dbus()
|
||||
|
||||
def _init_dbus(self):
|
||||
try:
|
||||
import dbus, dbus.mainloop.glib
|
||||
ml = dbus.mainloop.glib.DBusGMainLoop(set_as_default=False)
|
||||
self._bus = dbus.SystemBus(mainloop=ml)
|
||||
loop = GLib.MainLoop()
|
||||
threading.Thread(target=loop.run, daemon=True, name='bt-dbus').start()
|
||||
except Exception as e:
|
||||
log.warning(f"BlueZ: {e}")
|
||||
|
||||
def activate(self):
|
||||
self._set_discoverable(True)
|
||||
subprocess.run(['sudo', 'systemctl', 'start', 'bluealsa-aplay'],
|
||||
capture_output=True)
|
||||
self._set_state('idle')
|
||||
|
||||
def deactivate(self):
|
||||
self._set_discoverable(False)
|
||||
subprocess.run(['sudo', 'systemctl', 'stop', 'bluealsa-aplay'],
|
||||
capture_output=True)
|
||||
self._set_state('stopped')
|
||||
|
||||
def get_status(self) -> dict:
|
||||
return {'source': self.SOURCE_ID, 'state': self._state,
|
||||
'connected': self._connected}
|
||||
|
||||
def get_meters(self) -> dict:
|
||||
return {'rms_l': -60.0, 'rms_r': -60.0,
|
||||
'peak_l': -60.0, 'peak_r': -60.0, 'bands': [-60.0] * 32}
|
||||
|
||||
def get_paired_devices(self) -> list:
|
||||
if not self._bus: return []
|
||||
try:
|
||||
import dbus
|
||||
mgr = dbus.Interface(self._bus.get_object('org.bluez', '/'),
|
||||
'org.freedesktop.DBus.ObjectManager')
|
||||
return [{'mac': str(d.get('Address', '')),
|
||||
'name': str(d.get('Name', '')),
|
||||
'connected': bool(d.get('Connected', False)),
|
||||
'trusted': bool(d.get('Trusted', False))}
|
||||
for _, ifaces in mgr.GetManagedObjects().items()
|
||||
for d in [ifaces.get('org.bluez.Device1')]
|
||||
if d and bool(d.get('Paired', False))]
|
||||
except Exception as e:
|
||||
log.error(f"BT devices: {e}"); return []
|
||||
|
||||
def connect_device(self, mac: str) -> bool:
|
||||
ok = self._dev_call(mac, 'Connect')
|
||||
if ok: self._connected = mac; self._connected_dev = mac
|
||||
return ok
|
||||
|
||||
def disconnect_device(self, mac: str):
|
||||
self._dev_call(mac, 'Disconnect')
|
||||
self._connected = self._connected_dev = None
|
||||
|
||||
def remove_device(self, mac: str):
|
||||
if not self._bus: return
|
||||
try:
|
||||
import dbus
|
||||
dbus.Interface(self._bus.get_object('org.bluez', '/org/bluez/hci0'),
|
||||
'org.bluez.Adapter1').RemoveDevice(self._mac_path(mac))
|
||||
except Exception as e: log.error(f"BT remove: {e}")
|
||||
|
||||
def _dev_call(self, mac, method):
|
||||
if not self._bus: return False
|
||||
try:
|
||||
import dbus
|
||||
getattr(dbus.Interface(
|
||||
self._bus.get_object('org.bluez', self._mac_path(mac)),
|
||||
'org.bluez.Device1'), method)()
|
||||
return True
|
||||
except Exception as e:
|
||||
log.error(f"BT {method}: {e}"); return False
|
||||
|
||||
def _mac_path(self, mac):
|
||||
return f"/org/bluez/hci0/dev_{mac.replace(':', '_')}"
|
||||
|
||||
def _set_discoverable(self, enable):
|
||||
if not self._bus: return
|
||||
try:
|
||||
import dbus
|
||||
props = dbus.Interface(
|
||||
self._bus.get_object('org.bluez', '/org/bluez/hci0'),
|
||||
'org.freedesktop.DBus.Properties')
|
||||
props.Set('org.bluez.Adapter1', 'Discoverable', dbus.Boolean(enable))
|
||||
if enable:
|
||||
props.Set('org.bluez.Adapter1', 'DiscoverableTimeout', dbus.UInt32(0))
|
||||
except Exception: pass
|
||||
|
||||
def _set_state(self, s):
|
||||
if s != self._state:
|
||||
self._state = s
|
||||
if self._on_state: self._on_state(self.SOURCE_ID, s)
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
# AnalogSource (szkielet)
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class AnalogSource:
|
||||
def __init__(self, source_id, name, channel, on_state=None, on_meta=None):
|
||||
self.SOURCE_ID = source_id
|
||||
self.SOURCE_NAME = name
|
||||
self.CHANNEL = channel
|
||||
self._on_state = on_state
|
||||
self._state = 'stopped'
|
||||
|
||||
def activate(self):
|
||||
self._state = 'active'
|
||||
if self._on_state: self._on_state(self.SOURCE_ID, 'active')
|
||||
|
||||
def deactivate(self): self._state = 'stopped'
|
||||
|
||||
def get_status(self): return {'source': self.SOURCE_ID, 'state': self._state}
|
||||
def get_meters(self): return {'rms_l': -60.0, 'rms_r': -60.0,
|
||||
'peak_l': -60.0, 'peak_r': -60.0,
|
||||
'bands': [-60.0] * 32}
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
# SourceEngine
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class SourceEngine:
|
||||
_config_lock = threading.Lock()
|
||||
|
||||
def __init__(self, alsa_device='hw:1,0', on_state=None, on_meta=None):
|
||||
self._on_state = on_state
|
||||
self._on_meta = on_meta
|
||||
self._active_src = None
|
||||
self._cfg = self._load_config()
|
||||
self.alsa_device = alsa_device
|
||||
self._dirty = False
|
||||
|
||||
common = dict(on_state=self._fwd_state, on_meta=self._fwd_meta)
|
||||
self._sources = {
|
||||
'radio': RadioSource(alsa_device=alsa_device, **common),
|
||||
'bluetooth': BluetoothSource(**common),
|
||||
'line1': AnalogSource('line1', 'Line In 1', 1, **common),
|
||||
'line2': AnalogSource('line2', 'Line In 2', 2, **common),
|
||||
'phono': AnalogSource('phono', 'Phono', 0, **common),
|
||||
'spdif': AnalogSource('spdif', 'S/PDIF', 3, **common),
|
||||
}
|
||||
threading.Thread(target=self._save_loop, daemon=True,
|
||||
name='cfg-saver').start()
|
||||
|
||||
def restore(self):
|
||||
vol = self._cfg.get('volume', 50)
|
||||
last_src = self._cfg.get('last_source', 'radio')
|
||||
self.switch(last_src)
|
||||
src = self._sources.get(last_src)
|
||||
if src and hasattr(src, 'set_volume'): src.set_volume(vol)
|
||||
if last_src == 'radio': self._restore_radio()
|
||||
|
||||
def _restore_radio(self):
|
||||
radio = self._sources['radio']
|
||||
station = (self._find_station(self._cfg.get('last_station_id'))
|
||||
or self._first_station())
|
||||
if station:
|
||||
radio.play(station['url'], station.get('name', ''))
|
||||
log.info(f"Restored: {station.get('name')}")
|
||||
else:
|
||||
log.warning("Brak stacji")
|
||||
|
||||
def switch(self, source_id: str) -> bool:
|
||||
if source_id not in self._sources: return False
|
||||
if self._active_src and self._active_src.SOURCE_ID == source_id: return True
|
||||
log.info(f"Switch: {self.active_id} → {source_id}")
|
||||
if self._active_src:
|
||||
try:
|
||||
fn = (getattr(self._active_src, 'deactivate', None)
|
||||
or getattr(self._active_src, 'stop', None))
|
||||
if fn: fn()
|
||||
except Exception as e: log.error(f"Deactivate: {e}")
|
||||
src = self._sources[source_id]
|
||||
try:
|
||||
if hasattr(src, 'activate'): src.activate()
|
||||
except Exception as e: log.error(f"Activate: {e}"); return False
|
||||
self._active_src = src
|
||||
self._cfg['last_source'] = source_id
|
||||
self._dirty = True
|
||||
return True
|
||||
|
||||
@property
|
||||
def volume(self) -> int: return self._cfg.get('volume', 50)
|
||||
def get_volume(self) -> int: return self.volume
|
||||
|
||||
def set_volume(self, vol: int):
|
||||
vol = max(0, min(100, int(vol)))
|
||||
self._cfg['volume'] = vol
|
||||
src = self._active_src
|
||||
if src and hasattr(src, 'set_volume'): src.set_volume(vol)
|
||||
self._dirty = True
|
||||
|
||||
def set_eq(self, source_id, gains):
|
||||
if len(gains) != 10: return
|
||||
self._cfg.setdefault('eq', {})[source_id] = gains
|
||||
self._dirty = True
|
||||
|
||||
def get_eq(self, source_id):
|
||||
return self._cfg.get('eq', {}).get(source_id, [0.0] * 10)
|
||||
|
||||
def get_meters(self) -> dict:
|
||||
src = self._active_src
|
||||
return (src.get_meters() if src and hasattr(src, 'get_meters')
|
||||
else {'rms_l': -60.0, 'rms_r': -60.0,
|
||||
'peak_l': -60.0, 'peak_r': -60.0, 'bands': [-60.0] * 32})
|
||||
|
||||
@property
|
||||
def active(self): return self._active_src
|
||||
@property
|
||||
def active_id(self): return self._active_src.SOURCE_ID if self._active_src else None
|
||||
def get(self, sid): return self._sources.get(sid)
|
||||
def get_status(self): return self._active_src.get_status() if self._active_src else {}
|
||||
def get_all_status(self):
|
||||
return {'active': self.active_id, 'volume': self.volume,
|
||||
'status': self.get_status(),
|
||||
'sources': [{'id': sid, 'name': src.SOURCE_NAME,
|
||||
'active': bool(self._active_src
|
||||
and self._active_src.SOURCE_ID == sid)}
|
||||
for sid, src in self._sources.items()]}
|
||||
|
||||
def set_config(self, key, value): self._cfg[key] = value; self._dirty = True
|
||||
def get_config(self, key, default=None): return self._cfg.get(key, default)
|
||||
def save_source(self, sid): self._cfg['last_source'] = sid; self._dirty = True
|
||||
def get_source_gain(self, sid):
|
||||
return float(self._cfg.get('source_gains', {}).get(sid, 0.0))
|
||||
def set_source_gain(self, sid, gain):
|
||||
gain = max(-20.0, min(20.0, float(gain)))
|
||||
self._cfg.setdefault('source_gains', {})[sid] = gain
|
||||
self._dirty = True
|
||||
return gain
|
||||
|
||||
def get_stations(self):
|
||||
try:
|
||||
with open(STATIONS_PATH) as f: return json.load(f).get('stations', [])
|
||||
except Exception: return []
|
||||
|
||||
def _find_station(self, sid):
|
||||
if not sid: return None
|
||||
return next((s for s in self.get_stations()
|
||||
if s.get('id') == sid and s.get('enabled', True)), None)
|
||||
|
||||
def _first_station(self):
|
||||
return next((s for s in self.get_stations()
|
||||
if s.get('enabled', True)), None)
|
||||
|
||||
def _load_config(self):
|
||||
defaults = {'last_source': 'radio', 'last_station_id': None,
|
||||
'volume': 50, 'eq': {}, 'source_gains': {}}
|
||||
try:
|
||||
with open(CONFIG_PATH) as f: saved = json.load(f)
|
||||
for k, v in saved.items():
|
||||
if isinstance(v, dict) and isinstance(defaults.get(k), dict):
|
||||
defaults[k].update(v)
|
||||
else: defaults[k] = v
|
||||
except Exception: pass
|
||||
return defaults
|
||||
|
||||
def _save_loop(self):
|
||||
while True:
|
||||
time.sleep(5)
|
||||
if self._dirty:
|
||||
self._dirty = False
|
||||
self._do_save()
|
||||
|
||||
def _do_save(self):
|
||||
with self._config_lock:
|
||||
try:
|
||||
try:
|
||||
with open(CONFIG_PATH) as f: current = json.load(f)
|
||||
except Exception: current = {}
|
||||
current.update(self._cfg)
|
||||
with open(CONFIG_PATH, 'w') as f:
|
||||
json.dump(current, f, indent=2, ensure_ascii=False)
|
||||
except Exception as e: log.error(f"Config save: {e}")
|
||||
|
||||
def _fwd_state(self, sid, state):
|
||||
if self._on_state: self._on_state(sid, state)
|
||||
|
||||
def _fwd_meta(self, sid, meta):
|
||||
if self._on_meta: self._on_meta(sid, meta)
|
||||
@@ -0,0 +1,31 @@
|
||||
[Unit]
|
||||
Description=PylonisAmp
|
||||
After=network-online.target bluetooth.target sound.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=tom
|
||||
Group=tom
|
||||
WorkingDirectory=/home/tom/streamer
|
||||
ExecStart=/usr/bin/python3 /home/tom/streamer/app.py
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=streamer
|
||||
|
||||
# Audio
|
||||
SupplementaryGroups=audio bluetooth gpio
|
||||
|
||||
# Środowisko
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
Environment=ALSA_DEVICE=hw:sndrpihifiberry,0
|
||||
Environment=WEB_PORT=8000
|
||||
|
||||
# Pico USB CDC
|
||||
DeviceAllow=/dev/ttyACM0 rw
|
||||
DeviceAllow=/dev/ttyACM1 rw
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,77 @@
|
||||
body {
|
||||
background-color: #121212;
|
||||
color: #ffffff;
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.header {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
margin-bottom: 20px;
|
||||
color: #4dabf7; /* Chłodny niebieski */
|
||||
}
|
||||
|
||||
/* Siatka źródeł */
|
||||
.source-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 15px;
|
||||
margin-bottom: 30px;
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.source-btn {
|
||||
background-color: #1e1e1e;
|
||||
border: 2px solid #333;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.source-btn:hover {
|
||||
border-color: #4dabf7;
|
||||
}
|
||||
|
||||
/* Aktywne źródło */
|
||||
.source-btn.active {
|
||||
background-color: #4dabf7;
|
||||
color: #000;
|
||||
border-color: #4dabf7;
|
||||
}
|
||||
|
||||
/* Kontrolki głośności i odtwarzacza */
|
||||
.controls-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
background-color: #1e1e1e;
|
||||
padding: 20px;
|
||||
border-radius: 12px;
|
||||
width: 100%;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.btn-action {
|
||||
background-color: #333;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.btn-action:hover {
|
||||
background-color: #555;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user