"""指令下发与超时管理:为每条指令建立 pending future,超时/离线时回填错误。""" from __future__ import annotations import asyncio import json import logging import time from typing import Any from .hub import DeviceConnection, Hub from .protocol import ( DEFAULT_COMMAND_TIMEOUT, Envelope, ErrorCode, STATUS_ERROR, STATUS_SUCCESS, TYPE_RESPONSE, error_payload, ) from .storage import Storage logger = logging.getLogger(__name__) def redact_transfer_payload(action: str, payload: dict[str, Any] | None) -> dict[str, Any]: """Keep binary chunks out of persistent command audit rows.""" result = dict(payload or {}) if action in {"file.upload.chunk", "file.download.chunk"}: data = result.pop("data", None) if isinstance(data, str): result["encodedLength"] = len(data) return result class DeviceOfflineError(Exception): pass class CommandTimeoutError(Exception): pass class CommandDispatcher: def __init__(self, hub: Hub, storage: Storage): self._hub = hub self._storage = storage async def send_command( self, device_id: str, action: str, payload: dict[str, Any] | None = None, timeout: float | None = None, ) -> dict[str, Any]: """向设备下发指令并等待响应。返回 response.payload。 异常:DeviceOfflineError / CommandTimeoutError / RuntimeError(设备返回 error) """ conn = self._hub.get_connection(device_id) if conn is None: raise DeviceOfflineError(f"设备 {device_id} 不在线") timeout = timeout if timeout is not None else DEFAULT_COMMAND_TIMEOUT envelope = Envelope.command(action, device_id, payload) fut: asyncio.Future = asyncio.get_running_loop().create_future() conn.pending[envelope.id] = fut audit_payload = redact_transfer_payload(action, payload) self._storage.log_command(envelope.id, device_id, action, json.dumps(audit_payload, ensure_ascii=False), time.time()) try: await conn.send(envelope) try: result = await asyncio.wait_for(fut, timeout) except asyncio.CancelledError: if fut.cancelled(): # 设备连接断开时 hub 会取消 pending future raise DeviceOfflineError(f"设备 {device_id} 连接中断") from None raise return result except asyncio.TimeoutError: raise CommandTimeoutError(f"指令 {action} 超时 ({timeout}s)") finally: conn.pending.pop(envelope.id, None) def handle_response(self, conn: DeviceConnection, envelope: Envelope) -> None: """处理设备回执:写入审计日志并唤醒等待者。""" status = STATUS_SUCCESS if envelope.status == STATUS_SUCCESS else STATUS_ERROR self._storage.finish_command( envelope.id, status, json.dumps(redact_transfer_payload(envelope.action, envelope.payload), ensure_ascii=False), time.time(), ) fut = conn.pending.get(envelope.id) if fut is not None and not fut.done(): if status == STATUS_SUCCESS: fut.set_result(envelope.payload) else: code = int(envelope.payload.get("code", ErrorCode.BAD_REQUEST)) msg = str(envelope.payload.get("message", "")) fut.set_exception(RuntimeError(f"设备返回错误 [{code}] {msg}"))