Keep API responsive under HA events
This commit is contained in:
29
app/main.py
29
app/main.py
@@ -49,7 +49,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
app = FastAPI(
|
||||
title="SillyHome Future API",
|
||||
description="SillyHome v2 event-core side project.",
|
||||
version="2.0.0-alpha.5",
|
||||
version="2.0.0-alpha.6",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@@ -189,24 +189,31 @@ def _load_initial_ha_states(client: FutureHaClient) -> None:
|
||||
|
||||
async def _ha_listener_loop(client: FutureHaClient) -> None:
|
||||
while True:
|
||||
runtime = stores.runtime()
|
||||
runtime.websocket_status = "connecting"
|
||||
stores.save_runtime(runtime)
|
||||
await asyncio.to_thread(_set_websocket_status, "connecting")
|
||||
try:
|
||||
async for event in client.listen_state_events():
|
||||
runtime = stores.runtime()
|
||||
runtime.websocket_status = "connected"
|
||||
stores.save_runtime(runtime)
|
||||
event_core.process_state_event(event, execute=_execute_ha_decision)
|
||||
await asyncio.to_thread(_set_websocket_status, "connected")
|
||||
await asyncio.to_thread(
|
||||
event_core.process_state_event,
|
||||
event,
|
||||
execute=_execute_ha_decision,
|
||||
)
|
||||
await asyncio.sleep(0)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
runtime = stores.runtime()
|
||||
runtime.websocket_status = f"reconnecting: {exc}"
|
||||
stores.save_runtime(runtime)
|
||||
await asyncio.to_thread(_set_websocket_status, f"reconnecting: {exc}")
|
||||
await asyncio.sleep(2)
|
||||
|
||||
|
||||
def _set_websocket_status(status: str) -> None:
|
||||
runtime = stores.runtime()
|
||||
if runtime.websocket_status == status:
|
||||
return
|
||||
runtime.websocket_status = status
|
||||
stores.save_runtime(runtime)
|
||||
|
||||
|
||||
def _execute_ha_decision(decision: object) -> bool:
|
||||
if ha_client is None or not hasattr(decision, "actuator_entity_id"):
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user