"""ActionBatch builder driven by server Capabilities. The generic builder does not hard-code fan/PTC/door IDs, 0..100 ranges, or 2-second deadlines. Those belong to a profile helper or to Capabilities. """ from __future__ import annotations import uuid from datetime import datetime, timedelta, timezone from typing import Optional, Self from hth_sdk.exceptions import ActionRejected from hth_sdk.types import ActionBatch, ActuatorCapability, Capabilities, TimingCapabilities def _utcnow() -> datetime: return datetime.now(timezone.utc) class ActionBatchBuilder: def __init__( self, device_id: str, client_id: str = "hth-sdk", *, capabilities: Optional[Capabilities] = None, allow_unverified: bool = False, recommended_ttl: Optional[timedelta] = None, ) -> None: if not device_id: raise ActionRejected("INVALID_ARGUMENT", "device_id is required") if capabilities is None and not allow_unverified: raise ActionRejected( "INVALID_ARGUMENT", "capabilities required; pass Capabilities from GetCapabilities " "or allow_unverified=True for offline unit tests only", ) self._device_id = device_id self._client_id = client_id self._command_id = uuid.uuid4().hex self._lease_id = "" self._lease_epoch = 0 self._snapshot_seq = 0 self._control_revision = 0 self._valid_until: datetime | None = None self._targets: dict[str, float] = {} self._discrete: list[tuple[str, str, float]] = [] self._allow_clamp = False self._policy_version = "" self._caps = capabilities self._recommended_ttl = recommended_ttl if recommended_ttl is None and capabilities is not None and capabilities.timing is not None: ms = capabilities.timing.recommended_action_ttl_ms if ms > 0: self._recommended_ttl = timedelta(milliseconds=ms) self._strict_known_ids = True def command_id(self, command_id: str) -> Self: if not command_id: raise ActionRejected("INVALID_ARGUMENT", "command_id must be non-empty") self._command_id = command_id return self def client_id(self, client_id: str) -> Self: self._client_id = client_id return self def lease(self, lease_id: str, lease_epoch: int) -> Self: self._lease_id = lease_id self._lease_epoch = int(lease_epoch) return self def based_on(self, snapshot_seq: int, control_revision: int) -> Self: self._snapshot_seq = int(snapshot_seq) self._control_revision = int(control_revision) return self def valid_for(self, ttl: timedelta) -> Self: self._valid_until = _utcnow() + ttl return self def valid_until(self, when: datetime) -> Self: self._valid_until = when return self def allow_clamp(self, allow: bool = True) -> Self: self._allow_clamp = bool(allow) return self def policy_version(self, version: str) -> Self: self._policy_version = version return self def strict_known_ids(self, enabled: bool = True) -> Self: self._strict_known_ids = bool(enabled) return self def set(self, actuator_id: str, value: float) -> Self: """Set a continuous target using Capabilities range/resolution when present.""" self._check_id(actuator_id) self._check_range(actuator_id, value) self._targets[actuator_id] = float(value) return self def add_discrete(self, actuator_id: str, name: str, value: float = 0.0) -> Self: act = self._lookup(actuator_id) if act is not None and not act.one_shot: raise ActionRejected( "NOT_SUPPORTED", f"{actuator_id} does not advertise discrete/one-shot commands", ) self._discrete.append((actuator_id, name, float(value))) return self def _lookup(self, actuator_id: str) -> Optional[ActuatorCapability]: if self._caps is None: return None return self._caps.actuator(actuator_id) def _check_id(self, actuator_id: str) -> None: if not actuator_id: raise ActionRejected("INVALID_ARGUMENT", "actuator id is empty") if self._caps is not None: if self._lookup(actuator_id) is None: raise ActionRejected("UNKNOWN_ID", f"unknown actuator id {actuator_id!r}") # Without Capabilities the generic builder does not assume a product ID catalog. def _check_range(self, actuator_id: str, value: float) -> None: if value != value: # NaN raise ActionRejected("OUT_OF_RANGE", f"{actuator_id} is NaN") act = self._lookup(actuator_id) if act is None: return lo = act.command_min hi = act.command_max res = act.resolution if act.resolution > 0 else 0.0 if value < lo or value > hi: raise ActionRejected( "OUT_OF_RANGE", f"{actuator_id}={value} outside {lo}..{hi}", ) if res > 0 and abs(value / res - round(value / res)) > 1e-9: raise ActionRejected( "OUT_OF_RANGE", f"{actuator_id}={value} is not an integer multiple of resolution {res}", ) def build(self) -> ActionBatch: if not self._targets and not self._discrete: raise ActionRejected("INVALID_ARGUMENT", "batch has no targets") if self._valid_until is None: if self._recommended_ttl is None: raise ActionRejected( "INVALID_ARGUMENT", "valid_until required; set valid_for() from Capabilities.timing " "or pass recommended_ttl (do not assume 2s)", ) self._valid_until = _utcnow() + self._recommended_ttl items = tuple(sorted(self._targets.items())) return ActionBatch( device_id=self._device_id, command_id=self._command_id, lease_id=self._lease_id, lease_epoch=self._lease_epoch, based_on_snapshot_seq=self._snapshot_seq, expected_control_revision=self._control_revision, valid_until=self._valid_until, continuous_targets=items, discrete_commands=tuple(self._discrete), allow_clamp=self._allow_clamp, client_id=self._client_id, policy_version=self._policy_version, ) def recommended_ttl(timing: Optional[TimingCapabilities]) -> timedelta: if timing is None or timing.recommended_action_ttl_ms <= 0: raise ActionRejected( "INVALID_ARGUMENT", "timing capabilities missing; cannot default action TTL", ) return timedelta(milliseconds=timing.recommended_action_ttl_ms)