diff --git a/homeassistant/components/evohome/climate.py b/homeassistant/components/evohome/climate.py index 3507967b051f..f35f3ae9605b 100644 --- a/homeassistant/components/evohome/climate.py +++ b/homeassistant/components/evohome/climate.py @@ -1,19 +1,15 @@ """Support for Climate entities of the Evohome integration.""" -from datetime import datetime, timedelta +from datetime import timedelta import logging from typing import Any, override import evohomeasync2 as evo from evohomeasync2.const import ( - SZ_CAN_BE_TEMPORARY, - SZ_DURATION, - SZ_PERIOD, SZ_SETPOINT_STATUS, SZ_SYSTEM_MODE, SZ_SYSTEM_MODE_STATUS, SZ_TEMPERATURE_STATUS, - SZ_TIMING_MODE, SZ_UNTIL, SystemMode as EvoSystemMode, ZoneMode as EvoZoneMode, @@ -31,7 +27,7 @@ from homeassistant.components.climate import ( ) from homeassistant.const import PRECISION_TENTHS, UnitOfTemperature from homeassistant.core import HomeAssistant, callback -from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.util import dt as dt_util @@ -340,9 +336,6 @@ class EvoController(EvoClimateEntity): self._attr_unique_id = evo_device.id self._attr_name = evo_device.location.name - self._evo_modes = { - m[SZ_SYSTEM_MODE].value: m for m in evo_device.allowed_system_modes - } self._attr_preset_modes = [ TCS_PRESET_TO_HA[mode] for m in evo_device.allowed_system_modes @@ -363,47 +356,16 @@ class EvoController(EvoClimateEntity): ) -> None: """Set the system mode, either indefinitely or for a duration/period.""" - # check the requested mode; not all systems support all modes... - if (mode_info := self._evo_modes.get(as_snake_case(mode))) is None: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key="mode_not_supported", - translation_placeholders={"mode": mode}, - ) - - timing_mode: str | None = None - until: datetime | None = None + # the client checks the mode is allowed, and works out when it ends + evo_mode = as_snake_case(mode) # service schema makes duration & period mutually exclusive (can be neither) if period is not None: - timing_mode, until = SZ_PERIOD, dt_util.start_of_local_day() + period - elif duration is not None: - timing_mode, until = SZ_DURATION, dt_util.utcnow() + duration + client_api = self._evo_device.set_mode(evo_mode, period=period) + else: + client_api = self._evo_device.set_mode(evo_mode, duration=duration) - if timing_mode is not None: - if not mode_info[SZ_CAN_BE_TEMPORARY]: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key="mode_cant_be_temporary", - translation_placeholders={"mode": mode}, - ) - if mode_info.get(SZ_TIMING_MODE) != timing_mode: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key=f"mode_cant_have_{timing_mode}", - translation_placeholders={"mode": mode}, - ) - - await self._set_tcs_mode(mode_info[SZ_SYSTEM_MODE], until=until) - - async def _set_tcs_mode( - self, mode: EvoSystemMode, until: datetime | None = None - ) -> None: - """Set a Controller to any of its native operating modes.""" - until = dt_util.as_utc(until) if until else None - await self.coordinator.call_client_api( - self._evo_device.set_mode(mode, until=until) - ) + await self.coordinator.call_client_api(client_api) @property @override @@ -443,28 +405,18 @@ class EvoController(EvoClimateEntity): async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set an operating mode for a Controller.""" - evo_mode: EvoSystemMode - - if hvac_mode == HVACMode.HEAT: - evo_mode = ( - EvoSystemMode.AUTO - if EvoSystemMode.AUTO in self._evo_modes - else EvoSystemMode.HEAT - ) - elif hvac_mode == HVACMode.OFF: - evo_mode = ( - EvoSystemMode.HEATING_OFF - if EvoSystemMode.HEATING_OFF in self._evo_modes - else EvoSystemMode.OFF - ) - else: - raise HomeAssistantError(f"Invalid hvac_mode: {hvac_mode}") - await self._set_tcs_mode(evo_mode) + # the client falls back to Off/Heat, if HeatingOff/Auto aren't allowed + if hvac_mode == HVACMode.OFF: + client_api = self._evo_device.set_heatingoff() + else: # HA limits hvac_mode to hvac_modes, i.e. off or heat + client_api = self._evo_device.set_auto() + await self.coordinator.call_client_api(client_api) @override async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode; if None, then revert to 'Auto' mode.""" - await self._set_tcs_mode(HA_PRESET_TO_TCS.get(preset_mode, EvoSystemMode.AUTO)) + evo_mode = HA_PRESET_TO_TCS.get(preset_mode, EvoSystemMode.AUTO) + await self.coordinator.call_client_api(self._evo_device.set_mode(evo_mode)) @callback @override diff --git a/homeassistant/components/evohome/coordinator.py b/homeassistant/components/evohome/coordinator.py index 0451b6dc38e8..3bc4d706abcd 100644 --- a/homeassistant/components/evohome/coordinator.py +++ b/homeassistant/components/evohome/coordinator.py @@ -55,7 +55,7 @@ def _api_call_error_key(err: ec2.ApiCallFailedError) -> str: # a request that the client rejected, before any API call (i.e. invalid arguments) _REQUEST_ERROR_TRANSLATION_KEYS: Final[dict[ec2.RequestErrorReason, str]] = { - ec2.RequestErrorReason.MODE_UNKNOWN: "mode_not_supported", + ec2.RequestErrorReason.MODE_UNKNOWN: "mode_unknown", ec2.RequestErrorReason.MODE_UNSUPPORTED: "mode_not_supported", ec2.RequestErrorReason.TIMESPAN_NOT_ALLOWED: "mode_cant_be_temporary", ec2.RequestErrorReason.TIMESPAN_REQUIRED: "mode_timespan_required", @@ -80,7 +80,8 @@ def _bad_request_error(err: ec2.BadApiRequestError) -> ServiceValidationError: translation_domain=DOMAIN, translation_key="request_invalid" ) - if mode in ec2.ZoneMode: # a zone/DHW override (DHW uses ZoneMode too) + # a zone/DHW override (DHW uses ZoneMode too); a system mode can't be unknown + if mode in ec2.ZoneMode and err.reason != ec2.RequestErrorReason.MODE_UNKNOWN: return ServiceValidationError( translation_domain=DOMAIN, translation_key=( diff --git a/homeassistant/components/evohome/strings.json b/homeassistant/components/evohome/strings.json index 46003ad3fe14..e3e83aadb90d 100644 --- a/homeassistant/components/evohome/strings.json +++ b/homeassistant/components/evohome/strings.json @@ -42,6 +42,9 @@ "mode_timespan_required": { "message": "The mode `{mode}` requires a 'Duration' or 'Period'" }, + "mode_unknown": { + "message": "The mode `{mode}` is not a valid system mode" + }, "override_not_in_future": { "message": "The override must end in the future (if the duration is 0, the next scheduled setpoint may have already passed)" }, diff --git a/tests/components/evohome/snapshots/test_climate.ambr b/tests/components/evohome/snapshots/test_climate.ambr index ed7d6903080a..3f9733d6c4ca 100644 --- a/tests/components/evohome/snapshots/test_climate.ambr +++ b/tests/components/evohome/snapshots/test_climate.ambr @@ -72,7 +72,7 @@ # name: test_ctl_set_hvac_mode[sys_006] list([ tuple( - , + , ), tuple( , @@ -131,7 +131,7 @@ # name: test_ctl_turn_off[sys_006] list([ tuple( - , + , ), ]) # --- diff --git a/tests/components/evohome/test_climate.py b/tests/components/evohome/test_climate.py index 07e4d96e56ff..3f9402fdc1e8 100644 --- a/tests/components/evohome/test_climate.py +++ b/tests/components/evohome/test_climate.py @@ -20,7 +20,7 @@ from homeassistant.components.climate import ( ) from homeassistant.const import TargetKey from homeassistant.core import HomeAssistant -from homeassistant.exceptions import HomeAssistantError +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from .conftest import setup_evohome from .const import TEST_INSTALLS @@ -103,9 +103,9 @@ async def test_ctl_set_hvac_mode( ) try: - mock_fcn.assert_awaited_once_with("heating_off", until=None) + mock_fcn.assert_awaited_once_with("heating_off") except AssertionError: - mock_fcn.assert_awaited_once_with("off", until=None) + mock_fcn.assert_awaited_once_with("off") results.append(mock_fcn.await_args.args) # type: ignore[union-attr] @@ -122,9 +122,9 @@ async def test_ctl_set_hvac_mode( ) try: - mock_fcn.assert_awaited_once_with("auto", until=None) + mock_fcn.assert_awaited_once_with("auto") except AssertionError: - mock_fcn.assert_awaited_once_with("heat", until=None) + mock_fcn.assert_awaited_once_with("heat") results.append(mock_fcn.await_args.args) # type: ignore[union-attr] @@ -173,15 +173,66 @@ async def test_ctl_turn_off( ) try: - mock_fcn.assert_awaited_once_with("heating_off", until=None) + mock_fcn.assert_awaited_once_with("heating_off") except AssertionError: - mock_fcn.assert_awaited_once_with("off", until=None) + mock_fcn.assert_awaited_once_with("off") results.append(mock_fcn.await_args.args) # type: ignore[union-attr] assert results == snapshot +@pytest.mark.parametrize("install", ["default"]) +@pytest.mark.parametrize( + ("preset_mode", "expected_mode"), + [ + pytest.param("away", "away", id="away"), + pytest.param("eco", "auto_with_eco", id="eco"), + ], +) +async def test_ctl_set_preset_mode( + hass: HomeAssistant, + ctl_id: str, + preset_mode: str, + expected_mode: str, +) -> None: + """Test setting the preset mode of an evohome controller.""" + + with patch("evohomeasync2.control_system.ControlSystem.set_mode") as mock_fcn: + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.SET_PRESET_MODE, + { + TargetKey.ENTITY_ID: ctl_id, + ClimateServiceArgument.PRESET_MODE: preset_mode, + }, + blocking=True, + ) + + mock_fcn.assert_awaited_once_with(expected_mode) + + +@pytest.mark.parametrize("install", ["sys_006"]) +async def test_ctl_turn_off_unsupported( + hass: HomeAssistant, + ctl_id: str, +) -> None: + """Test turning off a controller that has neither the HeatingOff nor Off mode.""" + + with pytest.raises(ServiceValidationError) as exc_info: + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.TURN_OFF, + { + TargetKey.ENTITY_ID: ctl_id, + }, + blocking=True, + ) + + assert exc_info.value.translation_key == "mode_not_supported" + assert exc_info.value.translation_placeholders == {"mode": "HeatingOff"} + + @pytest.mark.parametrize("install", ["default"]) async def test_ctl_authentication_failed( hass: HomeAssistant, @@ -230,9 +281,9 @@ async def test_ctl_turn_on( ) try: - mock_fcn.assert_awaited_once_with("auto", until=None) + mock_fcn.assert_awaited_once_with("auto") except AssertionError: - mock_fcn.assert_awaited_once_with("heat", until=None) + mock_fcn.assert_awaited_once_with("heat") results.append(mock_fcn.await_args.args) # type: ignore[union-attr] diff --git a/tests/components/evohome/test_services.py b/tests/components/evohome/test_services.py index 39792613d3bb..5ae94532fe50 100644 --- a/tests/components/evohome/test_services.py +++ b/tests/components/evohome/test_services.py @@ -1,6 +1,6 @@ """The tests for the native services of Evohome.""" -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any from unittest.mock import patch @@ -116,7 +116,6 @@ async def test_set_system_mode_untargeted(hass: HomeAssistant) -> None: async def test_set_system_mode( hass: HomeAssistant, ctl_id: str, - freezer: FrozenDateTimeFactory, ) -> None: """Test entity-targeted set_system_mode service calls.""" @@ -132,9 +131,7 @@ async def test_set_system_mode( blocking=True, ) - mock_fcn.assert_awaited_once_with("auto", until=None) - - freezer.move_to("2024-07-10T12:00:00+00:00") + mock_fcn.assert_awaited_once_with("auto", duration=None) # EvoService.SET_SYSTEM_MODE: AutoWithEco, hours=12 with patch("evohomeasync2.control_system.ControlSystem.set_mode") as mock_fcn: @@ -149,9 +146,7 @@ async def test_set_system_mode( blocking=True, ) - mock_fcn.assert_awaited_once_with( - "auto_with_eco", until=datetime(2024, 7, 11, 0, 0, tzinfo=UTC) - ) + mock_fcn.assert_awaited_once_with("auto_with_eco", duration=timedelta(hours=12)) # EvoService.SET_SYSTEM_MODE: Away, days=7 with patch("evohomeasync2.control_system.ControlSystem.set_mode") as mock_fcn: @@ -166,9 +161,7 @@ async def test_set_system_mode( blocking=True, ) - mock_fcn.assert_awaited_once_with( - "away", until=datetime(2024, 7, 16, 23, 0, tzinfo=UTC) - ) + mock_fcn.assert_awaited_once_with("away", period=timedelta(days=7)) # entity_id in the service data, rather than as a target with patch("evohomeasync2.control_system.ControlSystem.set_mode") as mock_fcn: @@ -183,9 +176,7 @@ async def test_set_system_mode( blocking=True, ) - mock_fcn.assert_awaited_once_with( - "away", until=datetime(2024, 7, 16, 23, 0, tzinfo=UTC) - ) + mock_fcn.assert_awaited_once_with("away", period=timedelta(days=7)) @pytest.mark.usefixtures("evohome") @@ -193,14 +184,6 @@ async def test_set_system_mode( @pytest.mark.parametrize( ("entity_fixture", "service", "service_data", "target", "call_args"), [ - pytest.param( - "ctl_id", - EvoService.SET_SYSTEM_MODE, - {EvoServiceArgument.MODE: "AutoWithEco"}, - "evohomeasync2.control_system.ControlSystem.set_mode", - ("auto_with_eco",), - id="system_mode", - ), pytest.param( "zone_id", EvoService.SET_ZONE_OVERRIDE, @@ -250,6 +233,53 @@ async def test_duration_spans_dst_change( ) +@pytest.mark.parametrize("install", ["default"]) +@pytest.mark.parametrize( + ("service_data", "expected_until"), + [ + pytest.param( + { + EvoServiceArgument.MODE: "AutoWithEco", + EvoServiceArgument.DURATION: {"hours": 3}, + }, + datetime(2026, 3, 29, 2, 30, tzinfo=UTC), + id="duration_spans_dst_change", + ), + pytest.param( + {EvoServiceArgument.MODE: "Away", EvoServiceArgument.PERIOD: {"days": 7}}, + datetime(2026, 4, 3, 23, 0, tzinfo=UTC), # not 2026-04-04T22:00Z (Berlin) + id="period_ends_at_location_midnight", + ), + ], +) +async def test_set_system_mode_until( + hass: HomeAssistant, + ctl_id: str, + freezer: FrozenDateTimeFactory, + service_data: dict[str, Any], + expected_until: datetime, +) -> None: + """Test the client works out when a system mode ends. + + A duration is elapsed time (even if it spans a change to/from DST), and a period + ends at midnight in the location's time zone (Europe/London), rather than HA's. + """ + + await hass.config.async_set_time_zone("Europe/Berlin") + freezer.move_to("2026-03-28T23:30:00+00:00") # the clocks go forward at 01:00Z + + with patch("evohomeasync2.control_system.ControlSystem._put_mode") as mock_fcn: + await hass.services.async_call( + DOMAIN, + EvoService.SET_SYSTEM_MODE, + service_data, + target={TargetKey.ENTITY_ID: ctl_id}, + blocking=True, + ) + + assert mock_fcn.await_args.kwargs["time_until"] == expected_until + + @pytest.mark.parametrize("install", ["default"]) async def test_set_zone_override( hass: HomeAssistant, @@ -485,6 +515,14 @@ async def test_set_system_mode_entity_not_found( _SET_SYSTEM_MODE_VALIDATOR_PARAMS = [ ( {EvoServiceArgument.MODE: "NotARealMode"}, + "mode_unknown", + ), + ( + {EvoServiceArgument.MODE: "FollowSchedule"}, # a zone mode, not a system mode + "mode_unknown", + ), + ( + {EvoServiceArgument.MODE: "Cool"}, # a valid mode, but not for this system "mode_not_supported", ), ( @@ -502,6 +540,13 @@ _SET_SYSTEM_MODE_VALIDATOR_PARAMS = [ {EvoServiceArgument.MODE: "DayOff", EvoServiceArgument.DURATION: {"hours": 1}}, "mode_cant_have_duration", ), + ( + { + EvoServiceArgument.MODE: "AutoWithEco", + EvoServiceArgument.DURATION: {"hours": 0}, + }, + "mode_timespan_not_in_future", + ), ]