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,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)
|
||||
Reference in new issue
Block a user