thermal.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 SNAPSHOT_FIELDS, SNAPSHOT_PAYLOAD_LENGTH
  9. class ThermalBackend(Protocol):
  10. def set_target(self, temperature_c: int) -> None: ...
  11. def get_snapshot_payload(self) -> bytes: ...
  12. def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None: ...
  13. def _unix_target(path: str) -> str:
  14. if path.startswith("unix:"):
  15. return path
  16. if not path.startswith("/"):
  17. raise ValueError(f"Unix socket path must be absolute, got {path!r}")
  18. return f"unix://{path}"
  19. class GrpcThermalBackend:
  20. """Synchronous gRPC/UDS backend. It never opens a serial device."""
  21. def __init__(
  22. self,
  23. *,
  24. device_id: str,
  25. observe_socket: str,
  26. control_socket: str,
  27. timeout: float,
  28. ) -> None:
  29. try:
  30. import grpc
  31. from hth_sdk.generated.hth.api.v1 import hth_pb2, hth_pb2_grpc
  32. except ImportError as exc:
  33. raise RuntimeError("install hth-sdk[live] for gRPC thermal access") from exc
  34. self._grpc = grpc
  35. self._pb2 = hth_pb2
  36. self._device_id = device_id
  37. self._timeout = timeout
  38. self._observe_channel = grpc.insecure_channel(_unix_target(observe_socket))
  39. self._control_channel = grpc.insecure_channel(_unix_target(control_socket))
  40. self._observe = hth_pb2_grpc.ThermalObserveServiceStub(self._observe_channel)
  41. self._control = hth_pb2_grpc.ThermalControlServiceStub(self._control_channel)
  42. def close(self) -> None:
  43. self._observe_channel.close()
  44. self._control_channel.close()
  45. def set_target(self, temperature_c: int) -> None:
  46. self._control.SetTarget(
  47. self._pb2.SetThermalTargetRequest(
  48. device_id=self._device_id, temperature_c=temperature_c
  49. ),
  50. timeout=self._timeout,
  51. )
  52. def get_snapshot_payload(self) -> bytes:
  53. response = self._observe.GetSnapshot(
  54. self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
  55. timeout=self._timeout,
  56. )
  57. return bytes(response.snapshot.raw_payload)
  58. def capture_snapshot_payload(self) -> bytes:
  59. response = self._observe.CaptureSnapshot(
  60. self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
  61. timeout=self._timeout,
  62. )
  63. return bytes(response.snapshot.raw_payload)
  64. def run_stimulus(
  65. self,
  66. duration_seconds: int,
  67. ptc: Sequence[int],
  68. front: Sequence[int],
  69. rear: Sequence[int],
  70. ) -> None:
  71. self._control.RunStimulus(
  72. self._pb2.RunThermalStimulusRequest(
  73. device_id=self._device_id,
  74. duration_seconds=duration_seconds,
  75. ptc_duty=ptc,
  76. front_fan_duty=front,
  77. rear_fan_duty=rear,
  78. ),
  79. timeout=self._timeout,
  80. )
  81. def _field(payload: bytes, name: str):
  82. field = SNAPSHOT_FIELDS[name]
  83. offset = field["offset"]
  84. count = field.get("count", 1)
  85. kind = field["type"]
  86. if kind == "u8":
  87. values = list(payload[offset : offset + count])
  88. elif kind == "u16":
  89. values = list(struct.unpack_from("<" + "H" * count, payload, offset))
  90. elif kind == "bytes":
  91. values = list(payload[offset : offset + count])
  92. else:
  93. raise ValueError(f"unsupported snapshot field type {kind}")
  94. return values[0] if count == 1 else values
  95. def _mask(values: Sequence[int], count: int) -> list[bool]:
  96. return [bool(values[index // 8] & (1 << (index % 8))) for index in range(count)]
  97. def decode_snapshot(payload: bytes) -> dict[str, object]:
  98. if len(payload) != SNAPSHOT_PAYLOAD_LENGTH:
  99. raise ValueError(f"snapshot length {len(payload)} != {SNAPSHOT_PAYLOAD_LENGTH}")
  100. decoded = {name: _field(payload, name) for name in SNAPSHOT_FIELDS}
  101. decoded["bmc_valid"] = _mask(decoded.pop("bmc_valid_mask"), 24)
  102. decoded["ct_valid"] = _mask(decoded.pop("ct_valid_mask"), 27)
  103. decoded["safety_override"] = _mask(decoded.pop("safety_override_mask"), 24)
  104. lane_mask = int(decoded.pop("lane_fault_mask"))
  105. decoded["lane_fault"] = [bool(lane_mask & (1 << lane)) for lane in range(4)]
  106. decoded["host_target_seen"] = bool(decoded["host_target_seen"])
  107. decoded["global_fault"] = bool(decoded["global_fault"])
  108. return decoded
  109. @dataclass(frozen=True)
  110. class Snapshot:
  111. payload: bytes
  112. decoded: dict[str, object]
  113. request_monotonic_ns: int
  114. response_monotonic_ns: int
  115. class ThermalHTH:
  116. def __init__(self, backend: ThermalBackend, *, identification: bool = False):
  117. self._backend = backend
  118. self._identification = identification
  119. def set_target(self, temperature_c: int) -> None:
  120. if temperature_c != 0 and not 20 <= temperature_c <= 70:
  121. raise ValueError("temperature must be 0 or 20..70 C")
  122. self._backend.set_target(temperature_c)
  123. def stop(self) -> None:
  124. self.set_target(0)
  125. def close(self) -> None:
  126. close = getattr(self._backend, "close", None)
  127. if close is not None:
  128. close()
  129. def __enter__(self) -> "ThermalHTH":
  130. return self
  131. def __exit__(self, *_exc: object) -> None:
  132. self.close()
  133. def get_snapshot(self) -> Snapshot:
  134. start = time.monotonic_ns()
  135. payload = self._backend.get_snapshot_payload()
  136. end = time.monotonic_ns()
  137. return Snapshot(payload, decode_snapshot(payload), start, end)
  138. def capture_snapshot(self) -> Snapshot:
  139. start = time.monotonic_ns()
  140. capture = getattr(self._backend, "capture_snapshot_payload", None)
  141. payload = capture() if capture is not None else self._backend.get_snapshot_payload()
  142. end = time.monotonic_ns()
  143. return Snapshot(payload, decode_snapshot(payload), start, end)
  144. def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None:
  145. if not self._identification:
  146. raise NotImplementedError("stimulus is not supported by production firmware")
  147. if not 1 <= duration_seconds <= 255:
  148. raise ValueError("duration must be 1..255 seconds")
  149. if len(ptc) != 24 or len(front) != 4 or len(rear) != 4:
  150. raise ValueError("stimulus requires 24 PTC, 4 front, and 4 rear duties")
  151. if any(value < 0 or value > 100 for value in [*ptc, *front, *rear]):
  152. raise ValueError("stimulus duties must be 0..100")
  153. self._backend.run_stimulus(duration_seconds, ptc, front, rear)
  154. def connect_thermal(
  155. *,
  156. device_id: str = "prod2u-6400-0",
  157. observe_socket: str = DEFAULT_OBSERVE_SOCKET,
  158. control_socket: str = DEFAULT_CONTROL_SOCKET,
  159. firmware_profile: str = "production",
  160. timeout: float = 3.0,
  161. ) -> ThermalHTH:
  162. backend = GrpcThermalBackend(
  163. device_id=device_id,
  164. observe_socket=observe_socket,
  165. control_socket=control_socket,
  166. timeout=timeout,
  167. )
  168. return ThermalHTH(
  169. backend,
  170. identification=firmware_profile in {"identification", "6400-identification"},
  171. )