diff --git a/homeassistant/components/evohome/__init__.py b/homeassistant/components/evohome/__init__.py index 86342aebf134..bb0bc20d266a 100644 --- a/homeassistant/components/evohome/__init__.py +++ b/homeassistant/components/evohome/__init__.py @@ -109,7 +109,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: _LOGGER, ec2.EvohomeClient(token_manager), name=f"{DOMAIN}_account_coordinator", - update_interval=config[DOMAIN][CONF_SCAN_INTERVAL], + update_interval=SCAN_INTERVAL_DEFAULT, # scan_interval is only for locations client_v1=ec1.EvohomeClient(token_manager), ) if not await _async_first_refresh(account_coord): diff --git a/homeassistant/components/evohome/coordinator.py b/homeassistant/components/evohome/coordinator.py index 059255bb06cf..c10382edc95a 100644 --- a/homeassistant/components/evohome/coordinator.py +++ b/homeassistant/components/evohome/coordinator.py @@ -130,6 +130,9 @@ def _log_client_error(logger: logging.Logger, err: ec2.EvohomeError) -> None: type _Schedule = list[EvoDhwScheduleDayOfWeekT] | list[EvoZonScheduleDayOfWeekT] type _HighPrecisionTemps = dict[str, float | None] # by DHW/zone id +# keep the last high-precision temps for this many failed polls (i.e. 10 minutes) +_HIGH_PRECISION_MAX_FAILED_POLLS: Final = 2 + _ERR_SCHEDULE_UPDATE: Final = ( "%s: Failed to update the schedule (keeping any previous one): %s" ) @@ -157,7 +160,8 @@ class EvoAccountCoordinator(_EvoCoordinator[_HighPrecisionTemps]): """Coordinator for an evohome account (the user's config, high-precision temps). Its data is the latest high-precision temperatures, by DHW/zone id. They are - polled, but are not refreshed on demand (unlike a location). + polled, but are not refreshed on demand (unlike a location). If a poll fails, the + last temperatures are kept for a grace period, before the zones use their v2 ones. """ def __init__( @@ -185,6 +189,8 @@ class EvoAccountCoordinator(_EvoCoordinator[_HighPrecisionTemps]): self.data = {} + self._failed_polls = 0 + @override async def _async_setup(self) -> None: """Set up the coordinator. @@ -239,23 +245,37 @@ class EvoAccountCoordinator(_EvoCoordinator[_HighPrecisionTemps]): err, ) self.client_v1 = None - return self.data + return {} except (ec1.EvohomeError, TimeoutError) as err: - self.logger.warning( - ( - "Unable to obtain the latest high-precision temperatures. " - "They will be ignored this refresh cycle: %r" - ), - err, - ) - temps: _HighPrecisionTemps = {} # now considered stale + self._failed_polls += 1 + if self._failed_polls <= _HIGH_PRECISION_MAX_FAILED_POLLS: + self.logger.debug( + "Unable to obtain the latest high-precision temperatures, " + "so keeping the previous ones: %r", + err, + ) + return self.data - else: - temps = {} - for loc in self.client_v1.location_by_id.values(): - if loc.tcs: - temps |= await loc.tcs.get_temperatures(dont_update_status=True) + if self._failed_polls == _HIGH_PRECISION_MAX_FAILED_POLLS + 1: + self.logger.warning( + ( + "Unable to obtain the latest high-precision temperatures. " + "Standard-precision temperatures will be used until they " + "are available again: %r" + ), + err, + ) + return {} + + if self._failed_polls > _HIGH_PRECISION_MAX_FAILED_POLLS: + self.logger.info("High-precision temperatures are available again") + self._failed_polls = 0 + + temps: _HighPrecisionTemps = {} + for loc in self.client_v1.location_by_id.values(): + if loc.tcs: + temps |= await loc.tcs.get_temperatures(dont_update_status=True) self.logger.debug("Status (high-res temps) = %s", temps) return temps diff --git a/tests/components/evohome/test_coordinator.py b/tests/components/evohome/test_coordinator.py index ebd88c96c231..6adf2cbd6de5 100644 --- a/tests/components/evohome/test_coordinator.py +++ b/tests/components/evohome/test_coordinator.py @@ -74,6 +74,12 @@ async def test_setup_platform( assert state is not None and state.state != STATE_UNAVAILABLE +_MSG_HP_TEMPS_AVAILABLE: Final = "High-precision temperatures are available again" +_MSG_HP_TEMPS_UNAVAILABLE: Final = ( + "Standard-precision temperatures will be used until they are available again" +) + + def _v1_location_by_id( *temps: dict[str, float], ) -> AbstractContextManager[PropertyMock]: @@ -152,7 +158,7 @@ async def test_update_intervals( config: ConfigType, freezer: FrozenDateTimeFactory, ) -> None: - """Test scan_interval applies to the location and to high-precision temps.""" + """Test scan_interval applies to the location, but not to high-precision temps.""" config[CONF_SCAN_INTERVAL] = 600 @@ -165,12 +171,12 @@ async def test_update_intervals( await _poll(hass, freezer) # 300 seconds mock_v2.assert_not_awaited() - mock_v1.assert_not_awaited() + mock_v1.assert_awaited_once_with() await _poll(hass, freezer) # 600 seconds mock_v2.assert_awaited_once_with() - mock_v1.assert_awaited_once_with() + assert mock_v1.await_count == 2 @pytest.mark.parametrize("install", ["default"]) @@ -203,14 +209,63 @@ async def test_high_precision_temps_multiple_locations( ], ) @pytest.mark.usefixtures("evohome") -async def test_high_precision_temps_failed_poll( +async def test_high_precision_temps_grace_period( hass: HomeAssistant, freezer: FrozenDateTimeFactory, caplog: pytest.LogCaptureFixture, zone_id: str, exception: Exception, ) -> None: - """Test a failed v1 poll drops the high-precision temps, rather than keep them.""" + """Test failed v1 polls keep the high-precision temps, but only for 10 minutes.""" + + def current_temperature() -> float | None: + state = hass.states.get(zone_id) + assert state is not None + assert state.state != STATE_UNAVAILABLE + return state.attributes["current_temperature"] + + with ( + patch("evohomeasync.EvohomeClient.get_status"), + _v1_location_by_id({"3432521": 99.9}), + ): + await _poll(hass, freezer) + + assert current_temperature() == 99.9 + + with patch("evohomeasync.EvohomeClient.get_status", side_effect=exception): + for _ in range(2): # 10 minutes + await _poll(hass, freezer) + assert current_temperature() == 99.9 + + assert _MSG_HP_TEMPS_UNAVAILABLE not in caplog.text + + await _poll(hass, freezer) + assert current_temperature() is None + await _poll(hass, freezer) + + # the zone uses its v2 temperature (it has none in this fixture), warned only once + assert current_temperature() is None + assert caplog.text.count(_MSG_HP_TEMPS_UNAVAILABLE) == 1 + + with ( + patch("evohomeasync.EvohomeClient.get_status"), + _v1_location_by_id({"3432521": 19.8}), + ): + await _poll(hass, freezer) + + assert current_temperature() == 19.8 + assert _MSG_HP_TEMPS_AVAILABLE in caplog.text + + +@pytest.mark.parametrize("install", ["default"]) +@pytest.mark.usefixtures("evohome") +async def test_high_precision_temps_bad_credentials( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + caplog: pytest.LogCaptureFixture, + zone_id: str, +) -> None: + """Test the v1 API refusing the credentials drops the high-precision temps.""" with ( patch("evohomeasync.EvohomeClient.get_status"), @@ -222,17 +277,26 @@ async def test_high_precision_temps_failed_poll( assert state is not None assert state.attributes["current_temperature"] == 99.9 - with patch("evohomeasync.EvohomeClient.get_status", side_effect=exception): + with patch( + "evohomeasync.EvohomeClient.get_status", + side_effect=ec1.BadUserCredentialsError("Authentication failed"), + ): await _poll(hass, freezer) - assert "They will be ignored this refresh cycle" in caplog.text + assert "The feature will be disabled until next restart" in caplog.text + assert hass.data[EVOHOME_DATA].account.client_v1 is None - # the zone falls back to its v2 temperature (it has none in this fixture) + # there is no grace period, the zone uses its v2 temperature straight away state = hass.states.get(zone_id) assert state is not None assert state.state != STATE_UNAVAILABLE assert state.attributes["current_temperature"] is None + with patch("evohomeasync.EvohomeClient.get_status") as mock_get_status: + await _poll(hass, freezer) + + mock_get_status.assert_not_awaited() # until the next restart + @pytest.mark.parametrize("install", TEST_INSTALLS) @pytest.mark.usefixtures("evohome")