replay.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. """Read-only replay client with the same async surface as MockClient."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import tempfile
  6. from collections.abc import AsyncIterator
  7. from datetime import datetime, timedelta, timezone
  8. from importlib import resources
  9. from pathlib import Path
  10. from typing import Any, Optional
  11. from hth_sdk.exceptions import ActionRejected, HthError, InvalidResumePoint
  12. from hth_sdk.lease import ControlLease
  13. from hth_sdk.mock import default_capabilities
  14. from hth_sdk.profiles.prod2u import TEMPERATURE_IDS
  15. from hth_sdk.types import (
  16. ActionBatch,
  17. ActionResult,
  18. Capabilities,
  19. CommandedActuator,
  20. DeviceInfo,
  21. Measurement,
  22. Snapshot,
  23. SnapshotEvent,
  24. TelemetryEvent,
  25. )
  26. def _utcnow() -> datetime:
  27. return datetime.now(timezone.utc)
  28. def _user_cache_dir() -> Path:
  29. if os.name == "nt":
  30. root = os.environ.get("LOCALAPPDATA") or os.environ.get("TEMP") or tempfile.gettempdir()
  31. return Path(root) / "hth-sdk"
  32. xdg = os.environ.get("XDG_CACHE_HOME")
  33. if xdg:
  34. return Path(xdg) / "hth-sdk"
  35. return Path.home() / ".cache" / "hth-sdk"
  36. def bundled_sample_text() -> str:
  37. try:
  38. return resources.files("hth_sdk.data").joinpath("sample_replay.jsonl").read_text(encoding="utf-8")
  39. except (FileNotFoundError, ModuleNotFoundError, OSError):
  40. path = Path(tempfile.mkdtemp(prefix="hth-replay-")) / "sample_replay.jsonl"
  41. write_sample_replay(path)
  42. return path.read_text(encoding="utf-8")
  43. def default_replay_path(path: str | Path | None = None) -> Path:
  44. if path is not None:
  45. resolved = Path(path)
  46. if not resolved.is_file():
  47. raise HthError(
  48. "找不到回放文件。",
  49. code="REPLAY_NOT_FOUND",
  50. recoverable=True,
  51. suggestion="请检查路径,或使用 HTH.replay() 加载内置样本。",
  52. )
  53. return resolved
  54. cache = _user_cache_dir()
  55. dest = cache / "sample_replay.jsonl"
  56. try:
  57. cache.mkdir(parents=True, exist_ok=True)
  58. dest.write_text(bundled_sample_text(), encoding="utf-8")
  59. return dest
  60. except OSError:
  61. tmp = Path(tempfile.mkdtemp(prefix="hth-replay-")) / "sample_replay.jsonl"
  62. tmp.write_text(bundled_sample_text(), encoding="utf-8")
  63. return tmp
  64. class ReplayClient:
  65. """Plays recorded snapshots. set()/safe()/resume() are READ_ONLY."""
  66. def __init__(self, snapshots: list[Snapshot], *, device_id: str = "hood.0") -> None:
  67. if not snapshots:
  68. raise HthError("回放没有数据。", code="EMPTY", recoverable=False)
  69. self.device_id = device_id
  70. self._snaps = list(snapshots)
  71. self._i = 0
  72. self.has_observe = True
  73. self.has_control = False
  74. @classmethod
  75. def from_jsonl(cls, path: str | Path, *, device_id: str = "hood.0") -> "ReplayClient":
  76. resolved = Path(path)
  77. try:
  78. text = resolved.read_text(encoding="utf-8")
  79. except FileNotFoundError as exc:
  80. raise HthError(
  81. "找不到回放文件。",
  82. code="REPLAY_NOT_FOUND",
  83. recoverable=True,
  84. suggestion="请检查路径,或使用 HTH.replay() 加载内置样本。",
  85. ) from exc
  86. except OSError as exc:
  87. raise HthError(
  88. "无法读取回放文件。",
  89. code="REPLAY_INVALID",
  90. recoverable=True,
  91. ) from exc
  92. snaps = []
  93. try:
  94. for line in text.splitlines():
  95. line = line.strip()
  96. if not line:
  97. continue
  98. snaps.append(snapshot_from_simple(json.loads(line), device_id=device_id))
  99. except json.JSONDecodeError as exc:
  100. raise HthError(
  101. "回放文件格式不正确。",
  102. code="REPLAY_INVALID",
  103. recoverable=True,
  104. ) from exc
  105. return cls(snaps, device_id=device_id)
  106. async def close(self) -> None:
  107. return None
  108. async def __aenter__(self) -> "ReplayClient":
  109. return self
  110. async def __aexit__(self, *exc: object) -> None:
  111. await self.close()
  112. def _require(self, device_id: str) -> None:
  113. if device_id and device_id != self.device_id:
  114. raise ActionRejected("UNKNOWN_ID", device_id)
  115. async def list_devices(self) -> list[DeviceInfo]:
  116. s = self._snaps[self._i]
  117. return [
  118. DeviceInfo(
  119. device_id=self.device_id,
  120. display_name="replay",
  121. profile_id="replay",
  122. profile_revision="1",
  123. protocol_contract_hash="replay",
  124. backend_kind="replay",
  125. lifecycle=s.lifecycle,
  126. device_epoch=s.device_epoch,
  127. )
  128. ]
  129. async def get_capabilities(self, device_id: str) -> Capabilities:
  130. self._require(device_id)
  131. return default_capabilities(device_id)
  132. async def get_snapshot(self, device_id: str) -> Snapshot:
  133. self._require(device_id)
  134. return self._snaps[min(self._i, len(self._snaps) - 1)]
  135. async def get_faults(self, device_id: str, include_inactive: bool = False):
  136. return []
  137. async def subscribe_telemetry(
  138. self, device_id: str, resume_after_event_id: int = 0
  139. ) -> AsyncIterator[TelemetryEvent]:
  140. self._require(device_id)
  141. last = None
  142. for snap in self._snaps:
  143. if snap.event_id <= resume_after_event_id:
  144. continue
  145. ev = TelemetryEvent(snapshot=snap, previous_epoch=last)
  146. last = snap.device_epoch
  147. self._i = min(self._i + 1, len(self._snaps) - 1)
  148. yield ev
  149. async def subscribe_events(self, device_id: str, resume_after_event_id: int = 0):
  150. self._require(device_id)
  151. snap = await self.get_snapshot(device_id)
  152. if resume_after_event_id > snap.event_id:
  153. raise InvalidResumePoint(resume_after_event_id, snap.event_id)
  154. yield SnapshotEvent(
  155. event_id=snap.event_id,
  156. kind="SNAPSHOT",
  157. wall_time=snap.wall_time,
  158. device_id=device_id,
  159. snapshot=snap,
  160. )
  161. async def acquire_lease(self, *args: Any, **kwargs: Any) -> ControlLease:
  162. raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
  163. async def renew_lease(self, *args: Any, **kwargs: Any):
  164. raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
  165. async def release_lease(self, *args: Any, **kwargs: Any) -> None:
  166. return None
  167. async def validate(self, batch: ActionBatch) -> ActionResult:
  168. raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
  169. async def apply(self, batch: ActionBatch) -> ActionResult:
  170. raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
  171. async def enter_safe_mode(self, *args: Any, **kwargs: Any) -> ActionResult:
  172. raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
  173. async def resume_from_safe(self, *args: Any, **kwargs: Any) -> ActionResult:
  174. raise HthError("回放模式不能发送控制。", code="READ_ONLY", recoverable=False)
  175. def snapshot_from_simple(row: dict[str, Any], *, device_id: str) -> Snapshot:
  176. temps = row.get("temperatures_c") or []
  177. measurements = []
  178. for i, sid in enumerate(TEMPERATURE_IDS):
  179. raw = temps[i] if i < len(temps) else None
  180. measurements.append(
  181. Measurement(
  182. id=sid,
  183. value=None if raw is None else float(raw),
  184. unit="degC",
  185. quality="INVALID" if raw is None else "VALID",
  186. host_time=_utcnow(),
  187. )
  188. )
  189. fans = row.get("fans_percent") or []
  190. heaters = row.get("heaters_percent") or []
  191. doors = row.get("doors_close_percent") or {}
  192. targets = []
  193. known = len(fans) == 4 and len(heaters) == 4 and all(k in doors for k in ("x", "y", "z"))
  194. if known:
  195. for i, v in enumerate(fans, start=1):
  196. targets.append(CommandedActuator(id=f"fan.chamber.{i}", commanded_target=float(v)))
  197. for i, v in enumerate(heaters, start=1):
  198. targets.append(CommandedActuator(id=f"ptc.chamber.{i}", commanded_target=float(v)))
  199. for axis in ("x", "y", "z"):
  200. targets.append(
  201. CommandedActuator(id=f"door.{axis}.close_percent", commanded_target=float(doors.get(axis, 0)))
  202. )
  203. wall = row.get("time")
  204. wt = _utcnow()
  205. if isinstance(wall, str):
  206. try:
  207. wt = datetime.fromisoformat(wall.replace("Z", "+00:00"))
  208. except ValueError:
  209. wt = _utcnow()
  210. return Snapshot(
  211. device_id=device_id,
  212. daemon_instance_id="replay",
  213. device_epoch=int(row.get("device_epoch") or 1),
  214. snapshot_seq=int(row.get("snapshot_seq") or 1),
  215. control_revision=int(row.get("control_revision") or 0),
  216. event_id=int(row.get("event_id") or 1),
  217. wall_time=wt,
  218. monotonic_ns=int(row.get("event_id") or 1),
  219. lifecycle=str(row.get("lifecycle") or "READY"),
  220. measurements=tuple(measurements),
  221. continuous_targets=tuple(targets),
  222. last_requested=None,
  223. last_accepted=None,
  224. last_dispatched=None,
  225. device_confirmation="UNCONFIRMED",
  226. active_faults=(),
  227. lease=None,
  228. dropped_telemetry_count=0,
  229. data_gap=bool(row.get("data_gap") or False),
  230. transport_state=str(row.get("transport_state") or "ONLINE"),
  231. device_readiness=str(row.get("device_readiness") or "READY"),
  232. )
  233. def write_sample_replay(path: Path, *, n: int = 8, seed: int = 1) -> Path:
  234. path.parent.mkdir(parents=True, exist_ok=True)
  235. lines = []
  236. t0 = datetime(2026, 1, 1, tzinfo=timezone.utc)
  237. for i in range(n):
  238. temps = [25.0 + 0.1 * i + (ch % 4) * 0.05 for ch in range(27)]
  239. row = {
  240. "time": (t0 + timedelta(seconds=i)).isoformat(),
  241. "temperatures_c": temps,
  242. "fans_percent": [20, 20, 20, 20],
  243. "heaters_percent": [10, 10, 10, 10],
  244. "doors_close_percent": {"x": 0, "y": 0, "z": 0},
  245. "snapshot_seq": i + 1,
  246. "event_id": i + 1,
  247. "device_epoch": 1,
  248. "control_revision": 1,
  249. "lifecycle": "READY",
  250. "device_readiness": "READY",
  251. "transport_state": "ONLINE",
  252. }
  253. lines.append(json.dumps(row, separators=(",", ":")))
  254. path.write_text("\n".join(lines) + "\n", encoding="utf-8")
  255. return path