| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257 |
- """6400 target/ACK/snapshot facade. No serial ownership exists in this module."""
- from __future__ import annotations
- from dataclasses import dataclass
- import struct
- import time
- from typing import Protocol, Sequence
- from hth_sdk.constants import DEFAULT_CONTROL_SOCKET, DEFAULT_OBSERVE_SOCKET
- from hth_sdk.generated.thermal.contract import (
- CANONICAL_PROFILES,
- CONTRACT_SHA256,
- PROFILE_CAPABILITIES,
- SNAPSHOT_FIELDS,
- SNAPSHOT_PAYLOAD_LENGTH,
- )
- class ThermalBackend(Protocol):
- def set_target(self, temperature_c: int) -> None: ...
- def get_snapshot_payload(self) -> bytes: ...
- def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None: ...
- def _unix_target(path: str) -> str:
- if path.startswith("unix:"):
- return path
- if not path.startswith("/"):
- raise ValueError(f"Unix socket path must be absolute, got {path!r}")
- return f"unix://{path}"
- def _canonical_profile(profile: str) -> str:
- if profile not in CANONICAL_PROFILES:
- allowed = ", ".join(CANONICAL_PROFILES)
- raise ValueError(f"firmware_profile must be canonical ({allowed}), got {profile!r}")
- return profile
- def _validate_binding(expected_profile: str, actual_profile: str, actual_contract: str) -> None:
- expected_profile = _canonical_profile(expected_profile)
- if actual_profile != expected_profile:
- raise RuntimeError(
- f"firmware profile mismatch: expected {expected_profile}, got {actual_profile or '<empty>'}"
- )
- if actual_contract != CONTRACT_SHA256:
- raise RuntimeError(
- f"contract hash mismatch: expected {CONTRACT_SHA256}, got {actual_contract or '<empty>'}"
- )
- class GrpcThermalBackend:
- """Synchronous gRPC/UDS backend. It never opens a serial device."""
- def __init__(
- self,
- *,
- device_id: str,
- observe_socket: str,
- control_socket: str,
- firmware_profile: str,
- timeout: float,
- ) -> None:
- try:
- import grpc
- from hth_sdk.generated.hth.api.v1 import hth_pb2, hth_pb2_grpc
- except ImportError as exc:
- raise RuntimeError("install hth-sdk[live] for gRPC thermal access") from exc
- self._grpc = grpc
- self._pb2 = hth_pb2
- self._device_id = device_id
- self._firmware_profile = _canonical_profile(firmware_profile)
- self._timeout = timeout
- self._observe_channel = grpc.insecure_channel(_unix_target(observe_socket))
- self._control_channel = grpc.insecure_channel(_unix_target(control_socket))
- self._observe = hth_pb2_grpc.ThermalObserveServiceStub(self._observe_channel)
- self._control = hth_pb2_grpc.ThermalControlServiceStub(self._control_channel)
- def close(self) -> None:
- self._observe_channel.close()
- self._control_channel.close()
- def set_target(self, temperature_c: int) -> None:
- response = self._control.SetTarget(
- self._pb2.SetThermalTargetRequest(
- device_id=self._device_id, temperature_c=temperature_c
- ),
- timeout=self._timeout,
- )
- _validate_binding(
- self._firmware_profile,
- response.firmware_profile,
- response.contract_sha256,
- )
- if not response.committed:
- raise RuntimeError("SET_TARGET response did not confirm an ACK-backed commit")
- def get_snapshot_payload(self) -> bytes:
- response = self._observe.GetSnapshot(
- self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
- timeout=self._timeout,
- )
- return self._validated_snapshot_payload(response.snapshot)
- def capture_snapshot_payload(self) -> bytes:
- response = self._observe.CaptureSnapshot(
- self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
- timeout=self._timeout,
- )
- return self._validated_snapshot_payload(response.snapshot)
- def _validated_snapshot_payload(self, snapshot) -> bytes:
- _validate_binding(
- self._firmware_profile,
- snapshot.firmware_profile,
- snapshot.contract_sha256,
- )
- return bytes(snapshot.raw_payload)
- def run_stimulus(
- self,
- duration_seconds: int,
- ptc: Sequence[int],
- front: Sequence[int],
- rear: Sequence[int],
- ) -> None:
- response = self._control.RunStimulus(
- self._pb2.RunThermalStimulusRequest(
- device_id=self._device_id,
- duration_seconds=duration_seconds,
- ptc_duty=ptc,
- front_fan_duty=front,
- rear_fan_duty=rear,
- ),
- timeout=self._timeout,
- )
- _validate_binding(
- self._firmware_profile,
- response.firmware_profile,
- response.contract_sha256,
- )
- if not response.committed:
- raise RuntimeError("SET_STIMULUS response did not confirm an ACK-backed commit")
- def _field(payload: bytes, name: str):
- field = SNAPSHOT_FIELDS[name]
- offset = field["offset"]
- count = field.get("count", 1)
- kind = field["type"]
- if kind == "u8":
- values = list(payload[offset : offset + count])
- elif kind == "u16":
- values = list(struct.unpack_from("<" + "H" * count, payload, offset))
- elif kind == "bytes":
- values = list(payload[offset : offset + count])
- else:
- raise ValueError(f"unsupported snapshot field type {kind}")
- return values[0] if count == 1 else values
- def _mask(values: Sequence[int], count: int) -> list[bool]:
- return [bool(values[index // 8] & (1 << (index % 8))) for index in range(count)]
- def decode_snapshot(payload: bytes) -> dict[str, object]:
- if len(payload) != SNAPSHOT_PAYLOAD_LENGTH:
- raise ValueError(f"snapshot length {len(payload)} != {SNAPSHOT_PAYLOAD_LENGTH}")
- decoded = {name: _field(payload, name) for name in SNAPSHOT_FIELDS}
- decoded["bmc_valid"] = _mask(decoded.pop("bmc_valid_mask"), 24)
- decoded["ct_valid"] = _mask(decoded.pop("ct_valid_mask"), 27)
- decoded["safety_override"] = _mask(decoded.pop("safety_override_mask"), 24)
- lane_mask = int(decoded.pop("lane_fault_mask"))
- decoded["lane_fault"] = [bool(lane_mask & (1 << lane)) for lane in range(4)]
- decoded["host_target_seen"] = bool(decoded["host_target_seen"])
- decoded["global_fault"] = bool(decoded["global_fault"])
- return decoded
- @dataclass(frozen=True)
- class Snapshot:
- payload: bytes
- decoded: dict[str, object]
- request_monotonic_ns: int
- response_monotonic_ns: int
- class ThermalHTH:
- def __init__(self, backend: ThermalBackend, *, firmware_profile: str = "6400-control"):
- self._backend = backend
- self._firmware_profile = _canonical_profile(firmware_profile)
- def set_target(self, temperature_c: int) -> None:
- if temperature_c != 0 and not 20 <= temperature_c <= 70:
- raise ValueError("temperature must be 0 or 20..70 C")
- self._backend.set_target(temperature_c)
- def stop(self) -> None:
- self.set_target(0)
- def close(self) -> None:
- close = getattr(self._backend, "close", None)
- if close is not None:
- close()
- def __enter__(self) -> "ThermalHTH":
- return self
- def __exit__(self, *_exc: object) -> None:
- self.close()
- def get_snapshot(self) -> Snapshot:
- start = time.monotonic_ns()
- payload = self._backend.get_snapshot_payload()
- end = time.monotonic_ns()
- return Snapshot(payload, decode_snapshot(payload), start, end)
- def capture_snapshot(self) -> Snapshot:
- start = time.monotonic_ns()
- capture = getattr(self._backend, "capture_snapshot_payload", None)
- payload = capture() if capture is not None else self._backend.get_snapshot_payload()
- end = time.monotonic_ns()
- return Snapshot(payload, decode_snapshot(payload), start, end)
- def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None:
- if not PROFILE_CAPABILITIES[self._firmware_profile]["stimulus"]:
- raise NotImplementedError("stimulus is not supported by production firmware")
- if not 1 <= duration_seconds <= 255:
- raise ValueError("duration must be 1..255 seconds")
- if len(ptc) != 24 or len(front) != 4 or len(rear) != 4:
- raise ValueError("stimulus requires 24 PTC, 4 front, and 4 rear duties")
- if any(value < 0 or value > 100 for value in [*ptc, *front, *rear]):
- raise ValueError("stimulus duties must be 0..100")
- self._backend.run_stimulus(duration_seconds, ptc, front, rear)
- def connect_thermal(
- *,
- device_id: str = "prod2u-6400-0",
- observe_socket: str = DEFAULT_OBSERVE_SOCKET,
- control_socket: str = DEFAULT_CONTROL_SOCKET,
- firmware_profile: str = "6400-control",
- timeout: float = 3.0,
- ) -> ThermalHTH:
- firmware_profile = _canonical_profile(firmware_profile)
- backend = GrpcThermalBackend(
- device_id=device_id,
- observe_socket=observe_socket,
- control_socket=control_socket,
- firmware_profile=firmware_profile,
- timeout=timeout,
- )
- return ThermalHTH(
- backend,
- firmware_profile=firmware_profile,
- )
|