batch.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """ActionBatch builder driven by server Capabilities.
  2. The generic builder does not hard-code fan/PTC/door IDs, 0..100 ranges, or
  3. 2-second deadlines. Those belong to a profile helper or to Capabilities.
  4. """
  5. from __future__ import annotations
  6. import uuid
  7. from datetime import datetime, timedelta, timezone
  8. from typing import Optional, Self
  9. from hth_sdk.exceptions import ActionRejected
  10. from hth_sdk.types import ActionBatch, ActuatorCapability, Capabilities, TimingCapabilities
  11. def _utcnow() -> datetime:
  12. return datetime.now(timezone.utc)
  13. class ActionBatchBuilder:
  14. def __init__(
  15. self,
  16. device_id: str,
  17. client_id: str = "hth-sdk",
  18. *,
  19. capabilities: Optional[Capabilities] = None,
  20. allow_unverified: bool = False,
  21. recommended_ttl: Optional[timedelta] = None,
  22. ) -> None:
  23. if not device_id:
  24. raise ActionRejected("INVALID_ARGUMENT", "device_id is required")
  25. if capabilities is None and not allow_unverified:
  26. raise ActionRejected(
  27. "INVALID_ARGUMENT",
  28. "capabilities required; pass Capabilities from GetCapabilities "
  29. "or allow_unverified=True for offline unit tests only",
  30. )
  31. self._device_id = device_id
  32. self._client_id = client_id
  33. self._command_id = uuid.uuid4().hex
  34. self._lease_id = ""
  35. self._lease_epoch = 0
  36. self._snapshot_seq = 0
  37. self._control_revision = 0
  38. self._valid_until: datetime | None = None
  39. self._targets: dict[str, float] = {}
  40. self._discrete: list[tuple[str, str, float]] = []
  41. self._allow_clamp = False
  42. self._policy_version = ""
  43. self._caps = capabilities
  44. self._recommended_ttl = recommended_ttl
  45. if recommended_ttl is None and capabilities is not None and capabilities.timing is not None:
  46. ms = capabilities.timing.recommended_action_ttl_ms
  47. if ms > 0:
  48. self._recommended_ttl = timedelta(milliseconds=ms)
  49. self._strict_known_ids = True
  50. def command_id(self, command_id: str) -> Self:
  51. if not command_id:
  52. raise ActionRejected("INVALID_ARGUMENT", "command_id must be non-empty")
  53. self._command_id = command_id
  54. return self
  55. def client_id(self, client_id: str) -> Self:
  56. self._client_id = client_id
  57. return self
  58. def lease(self, lease_id: str, lease_epoch: int) -> Self:
  59. self._lease_id = lease_id
  60. self._lease_epoch = int(lease_epoch)
  61. return self
  62. def based_on(self, snapshot_seq: int, control_revision: int) -> Self:
  63. self._snapshot_seq = int(snapshot_seq)
  64. self._control_revision = int(control_revision)
  65. return self
  66. def valid_for(self, ttl: timedelta) -> Self:
  67. self._valid_until = _utcnow() + ttl
  68. return self
  69. def valid_until(self, when: datetime) -> Self:
  70. self._valid_until = when
  71. return self
  72. def allow_clamp(self, allow: bool = True) -> Self:
  73. self._allow_clamp = bool(allow)
  74. return self
  75. def policy_version(self, version: str) -> Self:
  76. self._policy_version = version
  77. return self
  78. def strict_known_ids(self, enabled: bool = True) -> Self:
  79. self._strict_known_ids = bool(enabled)
  80. return self
  81. def set(self, actuator_id: str, value: float) -> Self:
  82. """Set a continuous target using Capabilities range/resolution when present."""
  83. self._check_id(actuator_id)
  84. self._check_range(actuator_id, value)
  85. self._targets[actuator_id] = float(value)
  86. return self
  87. def add_discrete(self, actuator_id: str, name: str, value: float = 0.0) -> Self:
  88. act = self._lookup(actuator_id)
  89. if act is not None and not act.one_shot:
  90. raise ActionRejected(
  91. "NOT_SUPPORTED",
  92. f"{actuator_id} does not advertise discrete/one-shot commands",
  93. )
  94. self._discrete.append((actuator_id, name, float(value)))
  95. return self
  96. def _lookup(self, actuator_id: str) -> Optional[ActuatorCapability]:
  97. if self._caps is None:
  98. return None
  99. return self._caps.actuator(actuator_id)
  100. def _check_id(self, actuator_id: str) -> None:
  101. if not actuator_id:
  102. raise ActionRejected("INVALID_ARGUMENT", "actuator id is empty")
  103. if self._caps is not None:
  104. if self._lookup(actuator_id) is None:
  105. raise ActionRejected("UNKNOWN_ID", f"unknown actuator id {actuator_id!r}")
  106. # Without Capabilities the generic builder does not assume a product ID catalog.
  107. def _check_range(self, actuator_id: str, value: float) -> None:
  108. if value != value: # NaN
  109. raise ActionRejected("OUT_OF_RANGE", f"{actuator_id} is NaN")
  110. act = self._lookup(actuator_id)
  111. if act is None:
  112. return
  113. lo = act.command_min
  114. hi = act.command_max
  115. res = act.resolution if act.resolution > 0 else 0.0
  116. if value < lo or value > hi:
  117. raise ActionRejected(
  118. "OUT_OF_RANGE",
  119. f"{actuator_id}={value} outside {lo}..{hi}",
  120. )
  121. if res > 0 and abs(value / res - round(value / res)) > 1e-9:
  122. raise ActionRejected(
  123. "OUT_OF_RANGE",
  124. f"{actuator_id}={value} is not an integer multiple of resolution {res}",
  125. )
  126. def build(self) -> ActionBatch:
  127. if not self._targets and not self._discrete:
  128. raise ActionRejected("INVALID_ARGUMENT", "batch has no targets")
  129. if self._valid_until is None:
  130. if self._recommended_ttl is None:
  131. raise ActionRejected(
  132. "INVALID_ARGUMENT",
  133. "valid_until required; set valid_for() from Capabilities.timing "
  134. "or pass recommended_ttl (do not assume 2s)",
  135. )
  136. self._valid_until = _utcnow() + self._recommended_ttl
  137. items = tuple(sorted(self._targets.items()))
  138. return ActionBatch(
  139. device_id=self._device_id,
  140. command_id=self._command_id,
  141. lease_id=self._lease_id,
  142. lease_epoch=self._lease_epoch,
  143. based_on_snapshot_seq=self._snapshot_seq,
  144. expected_control_revision=self._control_revision,
  145. valid_until=self._valid_until,
  146. continuous_targets=items,
  147. discrete_commands=tuple(self._discrete),
  148. allow_clamp=self._allow_clamp,
  149. client_id=self._client_id,
  150. policy_version=self._policy_version,
  151. )
  152. def recommended_ttl(timing: Optional[TimingCapabilities]) -> timedelta:
  153. if timing is None or timing.recommended_action_ttl_ms <= 0:
  154. raise ActionRejected(
  155. "INVALID_ARGUMENT",
  156. "timing capabilities missing; cannot default action TTL",
  157. )
  158. return timedelta(milliseconds=timing.recommended_action_ttl_ms)