"""连接池:设备 WebSocket 连接注册、离线标记、前端会话管理与事件广播。""" from __future__ import annotations import asyncio import json import logging import time from typing import Any, Callable from .protocol import Envelope, RegisterInfo, TYPE_RESPONSE from .storage import Storage logger = logging.getLogger(__name__) # 心跳超时:超过该时长未收到心跳则视为离线 HEARTBEAT_TIMEOUT = 90.0 class DeviceConnection: """一台已注册设备的 WebSocket 连接抽象。""" def __init__(self, ws: Any, register: RegisterInfo): self.ws = ws self.register = register self.connected_at = time.time() self.last_heartbeat_at = time.time() self.last_heartbeat: dict[str, Any] = {} # pending 指令:message_id -> future,由 CommandDispatcher 维护 self.pending: dict[str, asyncio.Future] = {} @property def device_id(self) -> str: return self.register.device_id async def send(self, envelope: Envelope) -> None: await self.ws.send_text(json.dumps(envelope.to_dict(), ensure_ascii=False)) async def send_json(self, data: dict[str, Any]) -> None: await self.ws.send_text(json.dumps(data, ensure_ascii=False)) class UiSession: """一个前端管理界面 WebSocket 会话。""" def __init__(self, ws: Any, session_id: str): self.ws = ws self.session_id = session_id # 该会话订阅的设备(Phase 1 简化为订阅全部设备事件) self.created_at = time.time() async def send(self, data: dict[str, Any]) -> None: await self.ws.send_text(json.dumps(data, ensure_ascii=False)) class Hub: def __init__(self, storage: Storage): self._storage = storage self._devices: dict[str, DeviceConnection] = {} self._ui_sessions: dict[str, UiSession] = {} self._loop: asyncio.AbstractEventLoop | None = None self._watchdog_task: asyncio.Task | None = None self._on_event: Callable[[str, dict[str, Any]], Any] | None = None # ---------- 事件回调(main.py 注册,用于广播给前端) ---------- def set_event_handler(self, handler: Callable[[str, dict[str, Any]], Any]) -> None: self._on_event = handler # ---------- 设备连接 ---------- def register_device(self, conn: DeviceConnection) -> None: """注册设备连接;同 deviceId 重复连接时顶掉旧连接。""" old = self._devices.get(conn.device_id) if old is not None: logger.info("设备 %s 重复注册,关闭旧连接", conn.device_id) self._devices[conn.device_id] = conn reg = conn.register self._storage.upsert_device( conn.device_id, reg.device_name, reg.os_version, reg.sdk_version, conn.connected_at ) self._storage.add_event(conn.device_id, "online", reg.device_name, conn.connected_at) logger.info("设备上线: %s (%s)", conn.device_id, reg.device_name) async def unregister_device(self, device_id: str) -> None: conn = self._devices.get(device_id) if conn is None: return # 只有当前注册的连接才移除(避免旧连接断开时误删新连接) self._devices.pop(device_id, None) now = time.time() self._storage.set_online(device_id, False, now) self._storage.add_event(device_id, "offline", "", now) # 通知挂起中的指令:设备已离线 for fut in list(conn.pending.values()): if not fut.done(): fut.cancel() logger.info("设备离线: %s", device_id) await self.broadcast_to_ui({"type": "event", "action": "device.offline", "deviceId": device_id}) def get_connection(self, device_id: str) -> DeviceConnection | None: return self._devices.get(device_id) def is_online(self, device_id: str) -> bool: return device_id in self._devices def touch_heartbeat(self, device_id: str, payload: dict[str, Any]) -> None: conn = self._devices.get(device_id) if conn is not None: conn.last_heartbeat_at = time.time() conn.last_heartbeat = payload self._storage.update_heartbeat(device_id, time.time()) # ---------- 前端会话 ---------- def register_ui(self, session: UiSession) -> None: self._ui_sessions[session.session_id] = session def unregister_ui(self, session_id: str) -> None: self._ui_sessions.pop(session_id, None) async def broadcast_to_ui(self, data: dict[str, Any], *, timeout: float | None = None) -> None: """Deliver concurrently; optionally bound each session's send time.""" async def deliver(sid: str, session: UiSession) -> None: try: if timeout is None: await session.send(data) else: await asyncio.wait_for(session.send(data), timeout=timeout) except Exception: # Never log here: delivery may itself be broadcasting a log. if self._ui_sessions.get(sid) is session: self._ui_sessions.pop(sid, None) await asyncio.gather(*( deliver(sid, session) for sid, session in list(self._ui_sessions.items()) )) # ---------- 设备快照 ---------- def device_summaries(self) -> list[dict[str, Any]]: result = [] now = time.time() for row in self._storage.list_devices(): device_id = row["device_id"] conn = self._devices.get(device_id) online = conn is not None and (now - conn.last_heartbeat_at) < HEARTBEAT_TIMEOUT result.append({ "deviceId": device_id, "deviceName": row["device_name"], "osVersion": row["os_version"], "sdkVersion": row["sdk_version"], "online": online, "lastSeen": row["last_seen"], "heartbeat": conn.last_heartbeat if conn else {}, }) return result # ---------- 心跳看门狗 ---------- def start_watchdog(self) -> None: if self._watchdog_task is not None and not self._watchdog_task.done(): return self._loop = asyncio.get_running_loop() self._watchdog_task = self._loop.create_task(self._watchdog_loop()) async def stop_watchdog(self) -> None: if self._watchdog_task is not None: self._watchdog_task.cancel() try: await self._watchdog_task except asyncio.CancelledError: pass self._watchdog_task = None async def _watchdog_loop(self) -> None: while True: await asyncio.sleep(15) now = time.time() for device_id, conn in list(self._devices.items()): if now - conn.last_heartbeat_at > HEARTBEAT_TIMEOUT: logger.warning("设备 %s 心跳超时,标记离线", device_id) try: await conn.ws.close() except Exception: pass await self.unregister_device(device_id) # ---------- 生命周期 ---------- async def shutdown(self) -> None: await self.stop_watchdog() for device_id in list(self._devices): conn = self._devices[device_id] try: await conn.ws.close() except Exception: pass await self.unregister_device(device_id)