Skip to content
20 changes: 16 additions & 4 deletions src/ha_mcp/client/rest_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import logging
import os
import ssl
import time
from typing import Any

import httpx
Expand Down Expand Up @@ -963,12 +964,18 @@ async def upsert_automation_config(
) from e
raise

# 3-attempt × 6s upper-bound budget; first poll 0.1s catches the
# typical sub-1s entity-publish window.
_POLL_CADENCE: tuple[float, ...] = (0.1, 1.0, 4.9)
# 3-attempt × 6s upper-bound budget; first poll 0.025s is a 5×
# cushion above the ~4ms HA-Core entity-registration latency
# measured by ``test_poll_cadence_measurement.py`` (#1389 — p50
# 104.1-104.8 ms on the prior 0.1s first-poll, all from the sleep
# itself with ~4 ms of real registration work).
_POLL_CADENCE: tuple[float, ...] = (0.025, 1.0, 4.975)

async def _poll_for_automation_entity(self, unique_id: str) -> str | None:
"""Poll HA state to find the entity_id assigned to a newly created automation."""
# Measure cumulative elapsed from function entry to first successful match.
# Feeds the #1389 p50/p99 validation of `_POLL_CADENCE`.
start_monotonic = time.monotonic()
try:
for sleep_time in self._POLL_CADENCE:
await asyncio.sleep(sleep_time)
Expand All @@ -978,8 +985,13 @@ async def _poll_for_automation_entity(self, unique_id: str) -> str | None:
continue
if state.get("attributes", {}).get("id") == unique_id:
entity_id = state.get("entity_id")
elapsed_ms = (time.monotonic() - start_monotonic) * 1000.0
logger.debug(
f"Found actual entity_id for unique_id {unique_id}: {entity_id}"
"entity-registration-elapsed: %.1fms "
"(unique_id=%s, entity_id=%s)",
elapsed_ms,
unique_id,
entity_id,
)
return entity_id
except HomeAssistantError as e:
Expand Down
Loading
Loading