thermal.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. """6400 target/ACK/snapshot facade. No serial ownership exists in this module."""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. import struct
  5. import time
  6. from typing import Protocol, Sequence
  7. from hth_sdk.constants import DEFAULT_CONTROL_SOCKET, DEFAULT_OBSERVE_SOCKET
  8. from hth_sdk.generated.thermal.contract import (
  9. CANONICAL_PROFILES,
  10. CONTRACT_SHA256,
  11. PROFILE_CAPABILITIES,
  12. SNAPSHOT_FIELDS,
  13. SNAPSHOT_PAYLOAD_LENGTH,
  14. )
  15. class ThermalBackend(Protocol):
  16. def set_target(self, temperature_c: int) -> None: ...
  17. def get_snapshot_payload(self) -> bytes: ...
  18. def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None: ...
  19. def _unix_target(path: str) -> str:
  20. if path.startswith("unix:"):
  21. return path
  22. if not path.startswith("/"):
  23. raise ValueError(f"Unix socket path must be absolute, got {path!r}")
  24. return f"unix://{path}"
  25. def _canonical_profile(profile: str) -> str:
  26. if profile not in CANONICAL_PROFILES:
  27. allowed = ", ".join(CANONICAL_PROFILES)
  28. raise ValueError(f"firmware_profile must be canonical ({allowed}), got {profile!r}")
  29. return profile
  30. def _validate_binding(expected_profile: str, actual_profile: str, actual_contract: str) -> None:
  31. expected_profile = _canonical_profile(expected_profile)
  32. if actual_profile != expected_profile:
  33. raise RuntimeError(
  34. f"firmware profile mismatch: expected {expected_profile}, got {actual_profile or '<empty>'}"
  35. )
  36. if actual_contract != CONTRACT_SHA256:
  37. raise RuntimeError(
  38. f"contract hash mismatch: expected {CONTRACT_SHA256}, got {actual_contract or '<empty>'}"
  39. )
  40. class GrpcThermalBackend:
  41. """Synchronous gRPC/UDS backend. It never opens a serial device."""
  42. def __init__(
  43. self,
  44. *,
  45. device_id: str,
  46. observe_socket: str,
  47. control_socket: str,
  48. firmware_profile: str,
  49. timeout: float,
  50. ) -> None:
  51. try:
  52. import grpc
  53. from hth_sdk.generated.hth.api.v1 import hth_pb2, hth_pb2_grpc
  54. except ImportError as exc:
  55. raise RuntimeError("install hth-sdk[live] for gRPC thermal access") from exc
  56. self._grpc = grpc
  57. self._pb2 = hth_pb2
  58. self._device_id = device_id
  59. self._firmware_profile = _canonical_profile(firmware_profile)
  60. self._timeout = timeout
  61. self._observe_channel = grpc.insecure_channel(_unix_target(observe_socket))
  62. self._control_channel = grpc.insecure_channel(_unix_target(control_socket))
  63. self._observe = hth_pb2_grpc.ThermalObserveServiceStub(self._observe_channel)
  64. self._control = hth_pb2_grpc.ThermalControlServiceStub(self._control_channel)
  65. def close(self) -> None:
  66. self._observe_channel.close()
  67. self._control_channel.close()
  68. def set_target(self, temperature_c: int) -> None:
  69. response = self._control.SetTarget(
  70. self._pb2.SetThermalTargetRequest(
  71. device_id=self._device_id, temperature_c=temperature_c
  72. ),
  73. timeout=self._timeout,
  74. )
  75. _validate_binding(
  76. self._firmware_profile,
  77. response.firmware_profile,
  78. response.contract_sha256,
  79. )
  80. if not response.committed:
  81. raise RuntimeError("SET_TARGET response did not confirm an ACK-backed commit")
  82. def get_snapshot_payload(self) -> bytes:
  83. response = self._observe.GetSnapshot(
  84. self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
  85. timeout=self._timeout,
  86. )
  87. return self._validated_snapshot_payload(response.snapshot)
  88. def capture_snapshot_payload(self) -> bytes:
  89. response = self._observe.CaptureSnapshot(
  90. self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
  91. timeout=self._timeout,
  92. )
  93. return self._validated_snapshot_payload(response.snapshot)
  94. def _validated_snapshot_payload(self, snapshot) -> bytes:
  95. _validate_binding(
  96. self._firmware_profile,
  97. snapshot.firmware_profile,
  98. snapshot.contract_sha256,
  99. )
  100. return bytes(snapshot.raw_payload)
  101. def run_stimulus(
  102. self,
  103. duration_seconds: int,
  104. ptc: Sequence[int],
  105. front: Sequence[int],
  106. rear: Sequence[int],
  107. ) -> None:
  108. response = self._control.RunStimulus(
  109. self._pb2.RunThermalStimulusRequest(
  110. device_id=self._device_id,
  111. duration_seconds=duration_seconds,
  112. ptc_duty=ptc,
  113. front_fan_duty=front,
  114. rear_fan_duty=rear,
  115. ),
  116. timeout=self._timeout,
  117. )
  118. _validate_binding(
  119. self._firmware_profile,
  120. response.firmware_profile,
  121. response.contract_sha256,
  122. )
  123. if not response.committed:
  124. raise RuntimeError("SET_STIMULUS response did not confirm an ACK-backed commit")
  125. def _field(payload: bytes, name: str):
  126. field = SNAPSHOT_FIELDS[name]
  127. offset = field["offset"]
  128. count = field.get("count", 1)
  129. kind = field["type"]
  130. if kind == "u8":
  131. values = list(payload[offset : offset + count])
  132. elif kind == "u16":
  133. values = list(struct.unpack_from("<" + "H" * count, payload, offset))
  134. elif kind == "bytes":
  135. values = list(payload[offset : offset + count])
  136. else:
  137. raise ValueError(f"unsupported snapshot field type {kind}")
  138. return values[0] if count == 1 else values
  139. def _mask(values: Sequence[int], count: int) -> list[bool]:
  140. return [bool(values[index // 8] & (1 << (index % 8))) for index in range(count)]
  141. def decode_snapshot(payload: bytes) -> dict[str, object]:
  142. if len(payload) != SNAPSHOT_PAYLOAD_LENGTH:
  143. raise ValueError(f"snapshot length {len(payload)} != {SNAPSHOT_PAYLOAD_LENGTH}")
  144. decoded = {name: _field(payload, name) for name in SNAPSHOT_FIELDS}
  145. decoded["bmc_valid"] = _mask(decoded.pop("bmc_valid_mask"), 24)
  146. decoded["ct_valid"] = _mask(decoded.pop("ct_valid_mask"), 27)
  147. decoded["safety_override"] = _mask(decoded.pop("safety_override_mask"), 24)
  148. lane_mask = int(decoded.pop("lane_fault_mask"))
  149. decoded["lane_fault"] = [bool(lane_mask & (1 << lane)) for lane in range(4)]
  150. decoded["host_target_seen"] = bool(decoded["host_target_seen"])
  151. decoded["global_fault"] = bool(decoded["global_fault"])
  152. return decoded
  153. @dataclass(frozen=True)
  154. class Snapshot:
  155. payload: bytes
  156. decoded: dict[str, object]
  157. request_monotonic_ns: int
  158. response_monotonic_ns: int
  159. class ThermalHTH:
  160. def __init__(self, backend: ThermalBackend, *, firmware_profile: str = "6400-control"):
  161. self._backend = backend
  162. self._firmware_profile = _canonical_profile(firmware_profile)
  163. def set_target(self, temperature_c: int) -> None:
  164. if temperature_c != 0 and not 20 <= temperature_c <= 70:
  165. raise ValueError("temperature must be 0 or 20..70 C")
  166. self._backend.set_target(temperature_c)
  167. def stop(self) -> None:
  168. self.set_target(0)
  169. def close(self) -> None:
  170. close = getattr(self._backend, "close", None)
  171. if close is not None:
  172. close()
  173. def __enter__(self) -> "ThermalHTH":
  174. return self
  175. def __exit__(self, *_exc: object) -> None:
  176. self.close()
  177. def get_snapshot(self) -> Snapshot:
  178. start = time.monotonic_ns()
  179. payload = self._backend.get_snapshot_payload()
  180. end = time.monotonic_ns()
  181. return Snapshot(payload, decode_snapshot(payload), start, end)
  182. def capture_snapshot(self) -> Snapshot:
  183. start = time.monotonic_ns()
  184. capture = getattr(self._backend, "capture_snapshot_payload", None)
  185. payload = capture() if capture is not None else self._backend.get_snapshot_payload()
  186. end = time.monotonic_ns()
  187. return Snapshot(payload, decode_snapshot(payload), start, end)
  188. def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None:
  189. if not PROFILE_CAPABILITIES[self._firmware_profile]["stimulus"]:
  190. raise NotImplementedError("stimulus is not supported by production firmware")
  191. if not 1 <= duration_seconds <= 255:
  192. raise ValueError("duration must be 1..255 seconds")
  193. if len(ptc) != 24 or len(front) != 4 or len(rear) != 4:
  194. raise ValueError("stimulus requires 24 PTC, 4 front, and 4 rear duties")
  195. if any(value < 0 or value > 100 for value in [*ptc, *front, *rear]):
  196. raise ValueError("stimulus duties must be 0..100")
  197. self._backend.run_stimulus(duration_seconds, ptc, front, rear)
  198. def connect_thermal(
  199. *,
  200. device_id: str = "prod2u-6400-0",
  201. observe_socket: str = DEFAULT_OBSERVE_SOCKET,
  202. control_socket: str = DEFAULT_CONTROL_SOCKET,
  203. firmware_profile: str = "6400-control",
  204. timeout: float = 3.0,
  205. ) -> ThermalHTH:
  206. firmware_profile = _canonical_profile(firmware_profile)
  207. backend = GrpcThermalBackend(
  208. device_id=device_id,
  209. observe_socket=observe_socket,
  210. control_socket=control_socket,
  211. firmware_profile=firmware_profile,
  212. timeout=timeout,
  213. )
  214. return ThermalHTH(
  215. backend,
  216. firmware_profile=firmware_profile,
  217. )