Poll Overkiz executions instead of refreshing after every command (#188375)

Co-authored-by: Antoine Bertin <antoine@bertin.io>
This commit is contained in:
Mick Vleeshouwer
2026-10-25 19:54:26 +01:00
committed by GitHub
co-authored by Antoine Bertin
parent 7c8a3b17d6
commit 5cd682033f
4 changed files with 179 additions and 11 deletions
@@ -45,6 +45,9 @@ DEFAULT_HOST: Final = "gateway-xxxx-xxxx-xxxx.local:8443"
UPDATE_INTERVAL: Final = timedelta(seconds=30)
UPDATE_INTERVAL_LOCAL: Final = timedelta(seconds=5)
UPDATE_INTERVAL_ALL_ASSUMED_STATE: Final = timedelta(minutes=60)
# fetch_events allows 1 call per second, and refresh timing jitters, so leave margin.
UPDATE_INTERVAL_EXECUTION: Final = timedelta(seconds=2)
RATE_LIMIT_RETRY_AFTER: Final = timedelta(minutes=1)
PLATFORMS: list[Platform] = [
Platform.ALARM_CONTROL_PANEL,
@@ -28,7 +28,7 @@ from pyoverkiz.models import (
Place,
)
from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
OAuth2TokenRequestError,
@@ -41,7 +41,14 @@ from homeassistant.util.decorator import Registry
if TYPE_CHECKING:
from . import OverkizDataConfigEntry
from .const import DOMAIN, IGNORED_OVERKIZ_DEVICES, LOGGER, UPDATE_INTERVAL
from .const import (
DOMAIN,
IGNORED_OVERKIZ_DEVICES,
LOGGER,
RATE_LIMIT_RETRY_AFTER,
UPDATE_INTERVAL,
UPDATE_INTERVAL_EXECUTION,
)
# Events are a discriminated union; each handler narrows to its own subtype.
EVENT_HANDLERS: Registry[
@@ -104,7 +111,10 @@ class OverkizDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Device]]):
except TooManyConcurrentRequestsError as exception:
raise UpdateFailed("Too many concurrent requests.") from exception
except TooManyRequestsError as exception:
raise UpdateFailed("Too many requests, try again later.") from exception
raise UpdateFailed(
"Too many requests, try again later.",
retry_after=RATE_LIMIT_RETRY_AFTER.total_seconds(),
) from exception
except MaintenanceError as exception:
raise UpdateFailed("Server is down for maintenance.") from exception
except ServiceUnavailableError as exception:
@@ -159,6 +169,14 @@ class OverkizDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Device]]):
return areas
@callback
def async_execution_started(self) -> None:
"""Show the in-progress state and poll fast until executions finish."""
self.async_update_listeners()
if not self.is_stateless and self.update_interval != UPDATE_INTERVAL_EXECUTION:
self.update_interval = UPDATE_INTERVAL_EXECUTION
self._schedule_refresh()
def set_update_interval(self, update_interval: timedelta) -> None:
"""Set the update interval and store this value."""
self.update_interval = update_interval
@@ -234,7 +252,7 @@ async def on_execution_registered(
coordinator.executions[event.exec_id] = []
if not coordinator.is_stateless:
coordinator.update_interval = timedelta(seconds=1)
coordinator.update_interval = UPDATE_INTERVAL_EXECUTION
@EVENT_HANDLERS.register(EventName.EXECUTION_STATE_CHANGED)
+2 -2
View File
@@ -81,7 +81,7 @@ class OverkizExecutor:
}
)
if refresh_afterwards:
await self.coordinator.async_refresh()
self.coordinator.async_execution_started()
async def async_execute_commands(
self, commands: list[Command], refresh_afterwards: bool = True
@@ -120,7 +120,7 @@ class OverkizExecutor:
}
)
if refresh_afterwards:
await self.coordinator.async_refresh()
self.coordinator.async_execution_started()
async def async_cancel_command(
self, commands_to_cancel: list[OverkizCommand]
+152 -5
View File
@@ -4,6 +4,7 @@ from unittest.mock import Mock, patch
from aiohttp import ClientConnectorError
from freezegun.api import FrozenDateTimeFactory
from pyoverkiz.enums import ExecutionState
from pyoverkiz.exceptions import (
InvalidEventListenerIdError,
MaintenanceError,
@@ -15,14 +16,30 @@ from pyoverkiz.exceptions import (
import pytest
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
from homeassistant.components.overkiz.const import DOMAIN, UPDATE_INTERVAL
from homeassistant.components.cover import (
DOMAIN as COVER_DOMAIN,
SERVICE_OPEN_COVER,
CoverState,
)
from homeassistant.components.overkiz.const import (
DOMAIN,
RATE_LIMIT_RETRY_AFTER,
UPDATE_INTERVAL,
UPDATE_INTERVAL_ALL_ASSUMED_STATE,
UPDATE_INTERVAL_EXECUTION,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from .conftest import FixtureDevice, MockOverkizClient, SetupOverkizIntegration
from .helpers import async_deliver_events, device_created_event, device_removed_event
from .helpers import (
async_deliver_events,
device_created_event,
device_removed_event,
execution_state_changed_event,
)
TEMPERATURE_SENSOR = FixtureDevice(
"setup/cloud_nexity_rail_din_europe.json",
@@ -37,13 +54,25 @@ MAIN_GATEWAY_ID = "1234-1234-6233"
SECONDARY_GATEWAY_ID = "1234-1234-8983"
MAIN_GATEWAY_CHILD_URL = "io://1234-1234-6233/12184029"
SECONDARY_GATEWAY_CHILD_URL = "io://1234-1234-8983/1959462"
SHUTTER = FixtureDevice(
TAHOMA_V2_FIXTURE, MAIN_GATEWAY_CHILD_URL, "cover.office_garden_house_shutter"
)
GARAGE = FixtureDevice(
TAHOMA_V2_FIXTURE,
"io://1234-1234-6233/1166863",
"cover.living_room_main_garage_door",
)
RTS_SHUTTER = FixtureDevice(
"setup/cloud_somfy_connexoon_rts_asia.json",
"rts://1234-1234-6362/16730022",
"cover.palm_court_patio_shutter",
)
@pytest.mark.parametrize(
"exception",
[
TooManyConcurrentRequestsError("Too many concurrent requests"),
TooManyRequestsError("Too many requests"),
MaintenanceError("Server is down for maintenance"),
ServiceUnavailableError("Server is unavailable"),
SomfyServiceError("Somfy token refresh failed"),
@@ -53,7 +82,6 @@ SECONDARY_GATEWAY_CHILD_URL = "io://1234-1234-8983/1959462"
],
ids=[
"too_many_concurrent_requests",
"too_many_requests",
"maintenance",
"service_unavailable",
"somfy_service_error",
@@ -93,6 +121,125 @@ async def test_transient_error_is_retried(
assert hass.states.get(TEMPERATURE_SENSOR.entity_id).state == initial_state.state
async def test_rate_limit_delays_next_refresh(
hass: HomeAssistant,
setup_overkiz_integration: SetupOverkizIntegration,
mock_client: MockOverkizClient,
freezer: FrozenDateTimeFactory,
) -> None:
"""A rate limited refresh waits RATE_LIMIT_RETRY_AFTER before polling again."""
await setup_overkiz_integration(fixture=TEMPERATURE_SENSOR.fixture)
initial_state = hass.states.get(TEMPERATURE_SENSOR.entity_id)
mock_client.fetch_events.side_effect = TooManyRequestsError("Too many requests")
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(TEMPERATURE_SENSOR.entity_id).state == STATE_UNAVAILABLE
mock_client.fetch_events.side_effect = None
mock_client.fetch_events.return_value = []
mock_client.fetch_events.reset_mock()
# Polling at the normal interval would keep the quota exhausted.
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_client.fetch_events.await_count == 0
freezer.tick(RATE_LIMIT_RETRY_AFTER - UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_client.fetch_events.await_count == 1
assert hass.states.get(TEMPERATURE_SENSOR.entity_id).state == initial_state.state
async def test_commands_share_the_execution_poll(
hass: HomeAssistant,
setup_overkiz_integration: SetupOverkizIntegration,
mock_client: MockOverkizClient,
freezer: FrozenDateTimeFactory,
) -> None:
"""Commands don't fetch events themselves; one poll runs while they execute."""
await setup_overkiz_integration(fixture=SHUTTER.fixture)
mock_client.fetch_events.reset_mock()
for cover in (SHUTTER, GARAGE):
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: cover.entity_id},
blocking=True,
)
assert mock_client.fetch_events.await_count == 0
# The in-progress state comes from the local executions, not from a fetch.
assert hass.states.get(SHUTTER.entity_id).state == CoverState.OPENING
assert hass.states.get(GARAGE.entity_id).state == CoverState.OPENING
await async_deliver_events(
hass,
freezer,
mock_client,
[
execution_state_changed_event(
exec_id, ExecutionState.COMPLETED, ExecutionState.IN_PROGRESS
)
for exec_id in ("exec-1", "exec-2")
],
update_interval=UPDATE_INTERVAL_EXECUTION,
)
assert mock_client.fetch_events.await_count == 1
# Without pending executions, polling falls back to the default interval.
freezer.tick(UPDATE_INTERVAL_EXECUTION)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_client.fetch_events.await_count == 1
freezer.tick(UPDATE_INTERVAL - UPDATE_INTERVAL_EXECUTION)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_client.fetch_events.await_count == 2
async def test_stateless_hub_skips_the_execution_poll(
hass: HomeAssistant,
setup_overkiz_integration: SetupOverkizIntegration,
mock_client: MockOverkizClient,
freezer: FrozenDateTimeFactory,
) -> None:
"""RTS devices report no state, so commands don't speed up polling."""
await setup_overkiz_integration(fixture=RTS_SHUTTER.fixture)
mock_client.fetch_events.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: RTS_SHUTTER.entity_id},
blocking=True,
)
assert mock_client.execute_action_group.await_count == 1
freezer.tick(UPDATE_INTERVAL_EXECUTION)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_client.fetch_events.await_count == 0
freezer.tick(UPDATE_INTERVAL_ALL_ASSUMED_STATE - UPDATE_INTERVAL_EXECUTION)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_client.fetch_events.await_count == 1
async def test_device_removed_deletes_device(
hass: HomeAssistant,
setup_overkiz_integration: SetupOverkizIntegration,