| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291 |
- """Read-only replay client with the same async surface as MockClient."""
- from __future__ import annotations
- import json
- import os
- import tempfile
- from collections.abc import AsyncIterator
- from datetime import datetime, timedelta, timezone
- from importlib import resources
- from pathlib import Path
- from typing import Any, Optional
- from hth_sdk.exceptions import ActionRejected, HthError, InvalidResumePoint
- from hth_sdk.lease import ControlLease
- from hth_sdk.mock import default_capabilities
- from hth_sdk.profiles.prod2u import TEMPERATURE_IDS
- from hth_sdk.types import (
- ActionBatch,
- ActionResult,
- Capabilities,
- CommandedActuator,
- DeviceInfo,
- Measurement,
- Snapshot,
- SnapshotEvent,
- TelemetryEvent,
- )
- def _utcnow() -> datetime:
- return datetime.now(timezone.utc)
- def _user_cache_dir() -> Path:
- if os.name == "nt":
- root = os.environ.get("LOCALAPPDATA") or os.environ.get("TEMP") or tempfile.gettempdir()
- return Path(root) / "hth-sdk"
- xdg = os.environ.get("XDG_CACHE_HOME")
- if xdg:
- return Path(xdg) / "hth-sdk"
- return Path.home() / ".cache" / "hth-sdk"
- def bundled_sample_text() -> str:
- try:
- return resources.files("hth_sdk.data").joinpath("sample_replay.jsonl").read_text(encoding="utf-8")
- except (FileNotFoundError, ModuleNotFoundError, OSError):
- path = Path(tempfile.mkdtemp(prefix="hth-replay-")) / "sample_replay.jsonl"
- write_sample_replay(path)
- return path.read_text(encoding="utf-8")
- def default_replay_path(path: str | Path | None = None) -> Path:
- if path is not None:
- resolved = Path(path)
- if not resolved.is_file():
- raise HthError(
- "找不到回放文件。",
- code="REPLAY_NOT_FOUND",
- recoverable=True,
- suggestion="请检查路径,或使用 HTH.replay() 加载内置样本。",
- )
- return resolved
- cache = _user_cache_dir()
- dest = cache / "sample_replay.jsonl"
- try:
- cache.mkdir(parents=True, exist_ok=True)
- dest.write_text(bundled_sample_text(), encoding="utf-8")
- return dest
- except OSError:
- tmp = Path(tempfile.mkdtemp(prefix="hth-replay-")) / "sample_replay.jsonl"
- tmp.write_text(bundled_sample_text(), encoding="utf-8")
- return tmp
- class ReplayClient:
- """Plays recorded snapshots. set()/safe()/resume() are READ_ONLY."""
- def __init__(self, snapshots: list[Snapshot], *, device_id: str = "hood.0") -> None:
- if not snapshots:
- raise HthError("回放没有数据。", code="EMPTY", recoverable=False)
- self.device_id = device_id
- self._snaps = list(snapshots)
- self._i = 0
- self.has_observe = True
- self.has_control = False
- @classmethod
- def from_jsonl(cls, path: str | Path, *, device_id: str = "hood.0") -> "ReplayClient":
- resolved = Path(path)
- try:
- text = resolved.read_text(encoding="utf-8")
- except FileNotFoundError as exc:
- raise HthError(
- "找不到回放文件。",
- code="REPLAY_NOT_FOUND",
- recoverable=True,
- suggestion="请检查路径,或使用 HTH.replay() 加载内置样本。",
- ) from exc
- except OSError as exc:
- raise HthError(
- "无法读取回放文件。",
- code="REPLAY_INVALID",
- recoverable=True,
- ) from exc
- snaps = []
- try:
- for line in text.splitlines():
- line = line.strip()
- if not line:
- continue
- snaps.append(snapshot_from_simple(json.loads(line), device_id=device_id))
- except json.JSONDecodeError as exc:
- raise HthError(
- "回放文件格式不正确。",
- code="REPLAY_INVALID",
- recoverable=True,
- ) from exc
- return cls(snaps, device_id=device_id)
- async def close(self) -> None:
- return None
- async def __aenter__(self) -> "ReplayClient":
- return self
- async def __aexit__(self, *exc: object) -> None:
- await self.close()
- def _require(self, device_id: str) -> None:
- if device_id and device_id != self.device_id:
- raise ActionRejected("UNKNOWN_ID", device_id)
- async def list_devices(self) -> list[DeviceInfo]:
- s = self._snaps[self._i]
- return [
- DeviceInfo(
- device_id=self.device_id,
- display_name="replay",
- profile_id="replay",
- profile_revision="1",
- protocol_contract_hash="replay",
- backend_kind="replay",
- lifecycle=s.lifecycle,
- device_epoch=s.device_epoch,
- )
- ]
- async def get_capabilities(self, device_id: str) -> Capabilities:
- self._require(device_id)
- return default_capabilities(device_id)
- async def get_snapshot(self, device_id: str) -> Snapshot:
- self._require(device_id)
- return self._snaps[min(self._i, len(self._snaps) - 1)]
- async def get_faults(self, device_id: str, include_inactive: bool = False):
- return []
- async def subscribe_telemetry(
- self, device_id: str, resume_after_event_id: int = 0
- ) -> AsyncIterator[TelemetryEvent]:
- self._require(device_id)
- last = None
- for snap in self._snaps:
- if snap.event_id <= resume_after_event_id:
- continue
- ev = TelemetryEvent(snapshot=snap, previous_epoch=last)
- last = snap.device_epoch
- self._i = min(self._i + 1, len(self._snaps) - 1)
- yield ev
- async def subscribe_events(self, device_id: str, resume_after_event_id: int = 0):
- self._require(device_id)
- snap = await self.get_snapshot(device_id)
- if resume_after_event_id > snap.event_id:
- raise InvalidResumePoint(resume_after_event_id, snap.event_id)
- yield SnapshotEvent(
- event_id=snap.event_id,
- kind="SNAPSHOT",
- wall_time=snap.wall_time,
- device_id=device_id,
- snapshot=snap,
- )
- async def acquire_lease(self, *args: Any, **kwargs: Any) -> ControlLease:
- raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
- async def renew_lease(self, *args: Any, **kwargs: Any):
- raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
- async def release_lease(self, *args: Any, **kwargs: Any) -> None:
- return None
- async def validate(self, batch: ActionBatch) -> ActionResult:
- raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
- async def apply(self, batch: ActionBatch) -> ActionResult:
- raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
- async def enter_safe_mode(self, *args: Any, **kwargs: Any) -> ActionResult:
- raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
- async def resume_from_safe(self, *args: Any, **kwargs: Any) -> ActionResult:
- raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
- def snapshot_from_simple(row: dict[str, Any], *, device_id: str) -> Snapshot:
- temps = row.get("temperatures_c") or []
- measurements = []
- for i, sid in enumerate(TEMPERATURE_IDS):
- raw = temps[i] if i < len(temps) else None
- measurements.append(
- Measurement(
- id=sid,
- value=None if raw is None else float(raw),
- unit="degC",
- quality="INVALID" if raw is None else "VALID",
- host_time=_utcnow(),
- )
- )
- fans = row.get("fans_percent") or []
- heaters = row.get("heaters_percent") or []
- doors = row.get("doors_close_percent") or {}
- targets = []
- known = len(fans) == 4 and len(heaters) == 4 and all(k in doors for k in ("x", "y", "z"))
- if known:
- for i, v in enumerate(fans, start=1):
- targets.append(CommandedActuator(id=f"fan.chamber.{i}", commanded_target=float(v)))
- for i, v in enumerate(heaters, start=1):
- targets.append(CommandedActuator(id=f"ptc.chamber.{i}", commanded_target=float(v)))
- for axis in ("x", "y", "z"):
- targets.append(
- CommandedActuator(id=f"door.{axis}.close_percent", commanded_target=float(doors.get(axis, 0)))
- )
- wall = row.get("time")
- wt = _utcnow()
- if isinstance(wall, str):
- try:
- wt = datetime.fromisoformat(wall.replace("Z", "+00:00"))
- except ValueError:
- wt = _utcnow()
- return Snapshot(
- device_id=device_id,
- daemon_instance_id="replay",
- device_epoch=int(row.get("device_epoch") or 1),
- snapshot_seq=int(row.get("snapshot_seq") or 1),
- control_revision=int(row.get("control_revision") or 0),
- event_id=int(row.get("event_id") or 1),
- wall_time=wt,
- monotonic_ns=int(row.get("event_id") or 1),
- lifecycle=str(row.get("lifecycle") or "READY"),
- measurements=tuple(measurements),
- continuous_targets=tuple(targets),
- last_requested=None,
- last_accepted=None,
- last_dispatched=None,
- device_confirmation="UNCONFIRMED",
- active_faults=(),
- lease=None,
- dropped_telemetry_count=0,
- data_gap=bool(row.get("data_gap") or False),
- transport_state=str(row.get("transport_state") or "ONLINE"),
- device_readiness=str(row.get("device_readiness") or "READY"),
- )
- def write_sample_replay(path: Path, *, n: int = 8, seed: int = 1) -> Path:
- path.parent.mkdir(parents=True, exist_ok=True)
- lines = []
- t0 = datetime(2026, 1, 1, tzinfo=timezone.utc)
- for i in range(n):
- temps = [25.0 + 0.1 * i + (ch % 4) * 0.05 for ch in range(27)]
- row = {
- "time": (t0 + timedelta(seconds=i)).isoformat(),
- "temperatures_c": temps,
- "fans_percent": [20, 20, 20, 20],
- "heaters_percent": [10, 10, 10, 10],
- "doors_close_percent": {"x": 0, "y": 0, "z": 0},
- "snapshot_seq": i + 1,
- "event_id": i + 1,
- "device_epoch": 1,
- "control_revision": 1,
- "lifecycle": "READY",
- "device_readiness": "READY",
- "transport_state": "ONLINE",
- }
- lines.append(json.dumps(row, separators=(",", ":")))
- path.write_text("\n".join(lines) + "\n", encoding="utf-8")
- return path
|