feat: event-basierte Vorhersage via HA-WebSocket\n\n- Entfernt periodisches Prediction-Intervall (60s)\n- Fügt WebSocket-Listener hinzu, der bei jedem State Change sofort evaluiert\n- BehaviorEngine.handle_state_change() identifiziert betroffene Aktoren und löst evaluate() aus\n- Fallback periodische Vorhersage bleibt als Backup\n- pyproject: websockets dependency\n- tests: test_main.py für Event-Listener\n\nCloses #39

This commit is contained in:
2026-06-14 17:23:29 +02:00
parent f9c7c27e00
commit c8f491ba1a
4 changed files with 151 additions and 9 deletions

View File

@@ -1,9 +1,12 @@
import asyncio
import json
import logging
from contextlib import asynccontextmanager, suppress
from collections.abc import AsyncIterator
from pathlib import Path
from typing import cast
import websockets
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
@@ -20,13 +23,15 @@ from app.ha.reader import HaReader
from app.ml.registry.model_registry import ModelRegistry
from backend.routes.ml import init_ml_routes
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
settings = app.state.settings
client: HaClient | None = None
reconcile_task: asyncio.Task[None] | None = None
prediction_task: asyncio.Task[None] | None = None
event_listener_task: asyncio.Task[None] | None = None
app.state.registry = ModelRegistry(settings.model_store)
app.state.actuator_store = ActuatorStore(settings.actuator_store)
if hasattr(app.state, "ha_reader"):
@@ -58,7 +63,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
await asyncio.to_thread(app.state.behavior_engine.train_all)
await asyncio.to_thread(app.state.behavior_engine.evaluate_all)
reconcile_task = asyncio.create_task(_periodic_reconciliation(app))
prediction_task = asyncio.create_task(_periodic_prediction(app))
event_listener_task = asyncio.create_task(_ha_event_listener(app, client))
try:
yield
finally:
@@ -66,10 +71,10 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
reconcile_task.cancel()
with suppress(asyncio.CancelledError):
await reconcile_task
if prediction_task is not None:
prediction_task.cancel()
if event_listener_task is not None:
event_listener_task.cancel()
with suppress(asyncio.CancelledError):
await prediction_task
await event_listener_task
if client is not None:
client.close()
@@ -115,10 +120,67 @@ async def _periodic_reconciliation(app: FastAPI) -> None:
await asyncio.to_thread(engine.train_all)
async def _periodic_prediction(app: FastAPI) -> None:
async def _ha_event_listener(app: FastAPI, client: HaClient) -> None:
"""Hört auf Home-Assistant-Websocket-Events und löst sofortige Vorhersagen aus."""
settings = app.state.settings
engine = app.state.behavior_engine
store = app.state.actuator_store
if not isinstance(engine, BehaviorEngine) or not isinstance(store, ActuatorStore):
logger.error("BehaviorEngine oder ActuatorStore nicht initialisiert")
return
ha_url = str(settings.ha_url).rstrip("/")
ws_url = ha_url.replace("http://", "ws://").replace("https://", "wss://") + "/api/websocket"
auth_token = cast(str, settings.ha_token)
while True:
try:
async with websockets.connect(ws_url, extra_headers={
"Authorization": f"Bearer {auth_token}"
}) as websocket:
logger.info("WebSocket-Verbindung zu Home Assistant hergestellt")
# Authentifizierung durchführen
auth_msg = await websocket.recv()
auth_data = json.loads(auth_msg)
if auth_data.get("type") != "auth_ok":
logger.error("WebSocket-Authentifizierung fehlgeschlagen")
await asyncio.sleep(5)
continue
# Auf alle State Changes subscriben
subscribe_msg = {
"type": "subscribe_events",
"event_type": "state_changed"
}
await websocket.send(json.dumps(subscribe_msg))
while True:
message = await websocket.recv()
try:
data = json.loads(message)
if data.get("type") != "event":
continue
event = data.get("event", {})
if event.get("event_type") != "state_changed":
continue
entity_id = event.get("entity_id")
if not entity_id:
continue
# Prüfe, ob Entity ein Aktor oder relevanter Kontext ist
# Sofortige Vorhersage für betroffene Aktoren auslösen
await asyncio.to_thread(engine.handle_state_change, entity_id, event.get("new_state"))
except json.JSONDecodeError:
logger.warning("Ungültige JSON-Nachricht von HA-WebSocket")
except Exception as exc:
logger.exception("Fehler bei Event-Verarbeitung: %s", exc)
except (websockets.exceptions.ConnectionClosed, OSError) as exc:
logger.warning("WebSocket-Verbindung unterbrochen: %s. Wiederholung in 5s...", exc)
await asyncio.sleep(5)
except Exception as exc:
logger.exception("Unerwarteter Fehler im Event-Listener: %s", exc)
await asyncio.sleep(5)
# Fallback: periodische Vorhersage falls Event-Stream ausfällt
async def _fallback_prediction(app: FastAPI) -> None:
while True:
await asyncio.sleep(app.state.settings.prediction_interval_seconds)
engine = getattr(app.state, "behavior_engine", None)
if not isinstance(engine, BehaviorEngine):
continue
await asyncio.to_thread(engine.evaluate_all)
if isinstance(engine, BehaviorEngine):
await asyncio.to_thread(engine.evaluate_all)