From a10eeeb1cf10a1f5dbc8ef2148b04dfe1bbf2d9b Mon Sep 17 00:00:00 2001 From: David Magyarics Date: Tue, 24 Nov 2026 15:55:59 +0100 Subject: [PATCH] =?UTF-8?q?Add=20air=20conditioning=20climate=20entity=20t?= =?UTF-8?q?o=20=C5=A0koda=20(#191817)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- homeassistant/components/skoda/__init__.py | 1 + homeassistant/components/skoda/climate.py | 196 ++++++++ homeassistant/components/skoda/strings.json | 8 + .../skoda/snapshots/test_climate.ambr | 213 +++++++++ tests/components/skoda/test_climate.py | 420 ++++++++++++++++++ 5 files changed, 838 insertions(+) create mode 100644 homeassistant/components/skoda/climate.py create mode 100644 tests/components/skoda/snapshots/test_climate.ambr create mode 100644 tests/components/skoda/test_climate.py diff --git a/homeassistant/components/skoda/__init__.py b/homeassistant/components/skoda/__init__.py index 7a038f7d55dd..7c0a6a3ab69d 100644 --- a/homeassistant/components/skoda/__init__.py +++ b/homeassistant/components/skoda/__init__.py @@ -11,6 +11,7 @@ from .coordinator import SkodaConfigEntry, SkodaData, SkodaUpdateCoordinator _PLATFORMS: list[Platform] = [ Platform.BINARY_SENSOR, + Platform.CLIMATE, Platform.DEVICE_TRACKER, Platform.NUMBER, Platform.SENSOR, diff --git a/homeassistant/components/skoda/climate.py b/homeassistant/components/skoda/climate.py new file mode 100644 index 000000000000..3afaf52908ac --- /dev/null +++ b/homeassistant/components/skoda/climate.py @@ -0,0 +1,196 @@ +"""Support for Škoda climate control.""" + +from typing import Any, override + +from skoda_public_api.models.enums import ( + AirConditioningState, + TemperatureUnit, + VehicleCapability, + VehicleOperationName, +) + +from homeassistant.components.climate import ( + ATTR_HVAC_MODE, + ClimateEntity, + ClimateEntityDescription, + ClimateEntityFeature, + HVACAction, + HVACMode, +) +from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature +from homeassistant.core import HomeAssistant, callback +from homeassistant.exceptions import ServiceValidationError +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.util.unit_conversion import TemperatureConverter + +from .const import DOMAIN +from .coordinator import SkodaConfigEntry, SkodaUpdateCoordinator +from .entity import SkodaEntity + +PARALLEL_UPDATES = 1 + +_REQUIRED_OPERATIONS = frozenset( + { + VehicleOperationName.START_AIR_CONDITIONING, + VehicleOperationName.STOP_AIR_CONDITIONING, + } +) + +_HVAC_ACTION_MAP = { + AirConditioningState.OFF: HVACAction.OFF, + AirConditioningState.COMPLETED: HVACAction.OFF, + AirConditioningState.COOLING: HVACAction.COOLING, + AirConditioningState.HEATING: HVACAction.HEATING, + AirConditioningState.HEATING_AUXILIARY: HVACAction.HEATING, + AirConditioningState.VENTILATION: HVACAction.FAN, +} + +_HVAC_MODE_MAP = { + HVACAction.OFF: HVACMode.OFF, + HVACAction.COOLING: HVACMode.HEAT_COOL, + HVACAction.HEATING: HVACMode.HEAT_COOL, + HVACAction.FAN: HVACMode.HEAT_COOL, +} + +CLIMATE_DESCRIPTION = ClimateEntityDescription( + key="air_conditioning", + translation_key="air_conditioning", +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SkodaConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up Škoda climate control from ConfigEntry runtime_data.""" + coordinator = entry.runtime_data.coordinator + vehicle_response = coordinator.data.vehicle_response + capabilities = vehicle_response.supported_capabilities() + operations = vehicle_response.supported_operations() + + # The operations list can be temporarily unavailable, in which case only the + # capability is checked so a transient error does not hide the entity. + if VehicleCapability.AIR_CONDITIONING in capabilities and ( + operations is None or operations >= _REQUIRED_OPERATIONS + ): + async_add_entities([SkodaClimate(coordinator)]) + + +class SkodaClimate(SkodaEntity, ClimateEntity): + """Air conditioning of a Škoda vehicle.""" + + _attr_hvac_modes = [HVACMode.OFF, HVACMode.HEAT_COOL] + _attr_supported_features = ( + ClimateEntityFeature.TARGET_TEMPERATURE + | ClimateEntityFeature.TURN_ON + | ClimateEntityFeature.TURN_OFF + ) + _attr_native_temperature_unit = UnitOfTemperature.CELSIUS + _attr_min_temp = 16.0 + _attr_max_temp = 30.0 + _attr_target_temperature_step = 0.5 + + def __init__(self, coordinator: SkodaUpdateCoordinator) -> None: + """Initialize the climate entity.""" + self.entity_description = CLIMATE_DESCRIPTION + super().__init__(coordinator, coordinator.vin) + self._reported_target_temperature: float | None = None + self._update_attrs() + + def _vehicle_target_temperature(self) -> float | None: + """Return the target temperature reported by the vehicle in Celsius.""" + air_conditioning = self.open_api_air_conditioning + if air_conditioning is None or air_conditioning.target_temperature is None: + return None + target = air_conditioning.target_temperature + if target.unit == TemperatureUnit.FAHRENHEIT: + return round( + TemperatureConverter.convert( + target.value, + UnitOfTemperature.FAHRENHEIT, + UnitOfTemperature.CELSIUS, + ), + 1, + ) + return target.value + + def _update_attrs(self) -> None: + """Update the entity attributes from the latest vehicle data.""" + air_conditioning = self.open_api_air_conditioning + action = ( + _HVAC_ACTION_MAP.get(air_conditioning.state) + if air_conditioning is not None + else None + ) + self._attr_hvac_action = action + self._attr_hvac_mode = _HVAC_MODE_MAP.get(action) if action else None + + # Keep a target temperature chosen in Home Assistant until the vehicle + # reports a different one. A poll without a target does not count. + reported = self._vehicle_target_temperature() + if reported is not None and reported != self._reported_target_temperature: + self._reported_target_temperature = reported + self._attr_native_target_temperature = reported + + @callback + @override + def _handle_coordinator_update(self) -> None: + """Update the climate state from the latest vehicle data.""" + self._update_attrs() + super()._handle_coordinator_update() + + async def _async_start(self, temperature: float | None) -> None: + """Start the air conditioning, using the vehicle's own target if unknown.""" + await self.async_send_command( + self.coordinator.openapi.start_air_conditioning(self.vin, temperature) + ) + self._attr_hvac_mode = HVACMode.HEAT_COOL + + async def _async_stop(self) -> None: + """Stop the air conditioning.""" + await self.async_send_command( + self.coordinator.openapi.stop_air_conditioning(self.vin) + ) + self._attr_hvac_mode = HVACMode.OFF + + @override + async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: + """Start or stop the air conditioning.""" + if hvac_mode == HVACMode.HEAT_COOL: + await self._async_start(self.native_target_temperature) + else: + await self._async_stop() + self.async_write_ha_state() + + @override + async def async_turn_on(self) -> None: + """Start the air conditioning.""" + await self.async_set_hvac_mode(HVACMode.HEAT_COOL) + + @override + async def async_turn_off(self) -> None: + """Stop the air conditioning.""" + await self.async_set_hvac_mode(HVACMode.OFF) + + @override + async def async_set_temperature(self, **kwargs: Any) -> None: + """Set the target temperature, applying a requested HVAC mode as well.""" + temperature: float = kwargs[ATTR_TEMPERATURE] + if (hvac_mode := kwargs.get(ATTR_HVAC_MODE)) is None: + hvac_mode = self.hvac_mode + elif hvac_mode not in self.hvac_modes: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="invalid_hvac_mode", + translation_placeholders={ + "hvac_mode": hvac_mode, + "hvac_modes": ", ".join(self.hvac_modes), + }, + ) + if hvac_mode == HVACMode.HEAT_COOL: + await self._async_start(temperature) + elif hvac_mode == HVACMode.OFF and self.hvac_mode != HVACMode.OFF: + await self._async_stop() + self._attr_native_target_temperature = temperature + self.async_write_ha_state() diff --git a/homeassistant/components/skoda/strings.json b/homeassistant/components/skoda/strings.json index ad00195bb742..4e93068ed7d5 100644 --- a/homeassistant/components/skoda/strings.json +++ b/homeassistant/components/skoda/strings.json @@ -68,6 +68,11 @@ "name": "Windows" } }, + "climate": { + "air_conditioning": { + "name": "Air conditioning" + } + }, "number": { "charge_limit": { "name": "Charge limit" @@ -151,6 +156,9 @@ "command_not_supported": { "message": "The vehicle does not support this command." }, + "invalid_hvac_mode": { + "message": "HVAC mode {hvac_mode} is not supported. Supported modes are: {hvac_modes}." + }, "invalid_step": { "message": "The value {value} does not match the supported increment of {step}." }, diff --git a/tests/components/skoda/snapshots/test_climate.ambr b/tests/components/skoda/snapshots/test_climate.ambr new file mode 100644 index 000000000000..6f8b33cd4cec --- /dev/null +++ b/tests/components/skoda/snapshots/test_climate.ambr @@ -0,0 +1,213 @@ +# serializer version: 1 +# name: test_climate[vehicle_electric.json][climate.enyaq_coupe_air_conditioning-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + , + , + ]), + : 30.0, + : 16.0, + : 0.5, + : , + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'climate', + 'entity_category': None, + 'entity_id': 'climate.enyaq_coupe_air_conditioning', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Air conditioning', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Air conditioning', + 'platform': 'skoda', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'air_conditioning', + 'unique_id': 'TMBJM7NP2M1TMP511_air_conditioning', + 'unit_of_measurement': None, + }) +# --- +# name: test_climate[vehicle_electric.json][climate.enyaq_coupe_air_conditioning-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : None, + : 'Enyaq Coupé Air conditioning', + : , + : list([ + , + , + ]), + : 30.0, + : 16.0, + : , + : 0.5, + : 21.5, + : , + }), + 'context': , + 'entity_id': 'climate.enyaq_coupe_air_conditioning', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_climate[vehicle_hybrid.json][climate.superb_air_conditioning-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + , + , + ]), + : 30.0, + : 16.0, + : 0.5, + : , + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'climate', + 'entity_category': None, + 'entity_id': 'climate.superb_air_conditioning', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Air conditioning', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Air conditioning', + 'platform': 'skoda', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'air_conditioning', + 'unique_id': 'TMBJM7NP2M1TMP511_air_conditioning', + 'unit_of_measurement': None, + }) +# --- +# name: test_climate[vehicle_hybrid.json][climate.superb_air_conditioning-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : None, + : 'Superb Air conditioning', + : , + : list([ + , + , + ]), + : 30.0, + : 16.0, + : , + : 0.5, + : 22.2, + : , + }), + 'context': , + 'entity_id': 'climate.superb_air_conditioning', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'heat_cool', + }) +# --- +# name: test_climate[vehicle_unavailable.json][climate.skoda_tmbjm7np2m1tmp511_air_conditioning-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + , + , + ]), + : 30.0, + : 16.0, + : 0.5, + : , + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'climate', + 'entity_category': None, + 'entity_id': 'climate.skoda_tmbjm7np2m1tmp511_air_conditioning', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Air conditioning', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Air conditioning', + 'platform': 'skoda', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'air_conditioning', + 'unique_id': 'TMBJM7NP2M1TMP511_air_conditioning', + 'unit_of_measurement': None, + }) +# --- +# name: test_climate[vehicle_unavailable.json][climate.skoda_tmbjm7np2m1tmp511_air_conditioning-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : None, + : 'Škoda TMBJM7NP2M1TMP511 Air conditioning', + : list([ + , + , + ]), + : 30.0, + : 16.0, + : , + : 0.5, + : None, + : , + }), + 'context': , + 'entity_id': 'climate.skoda_tmbjm7np2m1tmp511_air_conditioning', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- diff --git a/tests/components/skoda/test_climate.py b/tests/components/skoda/test_climate.py new file mode 100644 index 000000000000..065ed1588415 --- /dev/null +++ b/tests/components/skoda/test_climate.py @@ -0,0 +1,420 @@ +"""Test the Škoda climate platform.""" + +from collections.abc import Generator +from unittest.mock import AsyncMock, patch + +from freezegun.api import FrozenDateTimeFactory +import pytest +from pytest_homeassistant.common import ( + MockConfigEntry, + async_fire_time_changed, + async_load_json_object_fixture, + snapshot_platform, +) +from skoda_public_api.api_layer.exceptions import OpenApiError +from skoda_public_api.models.enums import AirConditioningState +from skoda_public_api.models.vehicle import VehicleResponse +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.climate import ( + DOMAIN as CLIMATE_DOMAIN, + ClimateEntityStateAttribute, + ClimateService, + ClimateServiceArgument, + HVACAction, + HVACMode, +) +from homeassistant.components.skoda.const import DOMAIN +from homeassistant.components.skoda.coordinator import UPDATE_INTERVAL +from homeassistant.const import STATE_UNKNOWN, Platform, TargetKey +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers import entity_registry as er + +from . import setup_integration +from .conftest import VIN + +ENYAQ = "climate.enyaq_coupe_air_conditioning" +SUPERB = "climate.superb_air_conditioning" + + +@pytest.fixture(autouse=True) +def platforms() -> Generator[None]: + """Only set up the climate platform.""" + with patch("homeassistant.components.skoda._PLATFORMS", [Platform.CLIMATE]): + yield + + +@pytest.mark.usefixtures("mock_skoda_client") +@pytest.mark.parametrize( + "vehicle_fixture", + ["vehicle_electric.json", "vehicle_hybrid.json", "vehicle_unavailable.json"], +) +async def test_climate( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test the Škoda climate entities against a snapshot.""" + await setup_integration(hass, mock_config_entry) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.usefixtures("mock_skoda_client") +@pytest.mark.parametrize("vehicle_fixture", ["vehicle_combustion.json"]) +async def test_no_climate_without_air_conditioning( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test no climate entity is created for a vehicle without air conditioning.""" + await setup_integration(hass, mock_config_entry) + + assert not hass.states.async_entity_ids(CLIMATE_DOMAIN) + + +async def test_no_climate_without_operation( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, +) -> None: + """Test no climate entity is created when the vehicle cannot start it remotely.""" + vehicle = await async_load_json_object_fixture( + hass, "vehicle_electric.json", DOMAIN + ) + vehicle["vehicle"]["operations"] = [{"name": "startCharging"}] + mock_skoda_client.get_vehicle.return_value = VehicleResponse.model_validate(vehicle) + + await setup_integration(hass, mock_config_entry) + + assert not hass.states.async_entity_ids(CLIMATE_DOMAIN) + + +@pytest.mark.parametrize("vehicle_fixture", ["vehicle_incomplete.json"]) +async def test_climate_when_operations_unavailable( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, +) -> None: + """Test the climate entity is created from capabilities when operations are unknown.""" + await setup_integration(hass, mock_config_entry) + + assert (state := hass.states.get(SUPERB)) + assert state.state == HVACMode.HEAT_COOL + + +async def test_start_air_conditioning( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, +) -> None: + """Test starting the air conditioning uses the target temperature.""" + await setup_integration(hass, mock_config_entry) + + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.SET_HVAC_MODE, + { + TargetKey.ENTITY_ID: ENYAQ, + ClimateServiceArgument.HVAC_MODE: HVACMode.HEAT_COOL, + }, + blocking=True, + ) + + mock_skoda_client.start_air_conditioning.assert_awaited_once_with(VIN, 21.5) + assert (state := hass.states.get(ENYAQ)) + assert state.state == HVACMode.HEAT_COOL + + +@pytest.mark.parametrize("vehicle_fixture", ["vehicle_incomplete.json"]) +async def test_start_without_target_temperature( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, +) -> None: + """Test starting without a known target temperature keeps the vehicle's own.""" + await setup_integration(hass, mock_config_entry) + + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.TURN_ON, + {TargetKey.ENTITY_ID: SUPERB}, + blocking=True, + ) + + mock_skoda_client.start_air_conditioning.assert_awaited_once_with(VIN, None) + + +@pytest.mark.parametrize("vehicle_fixture", ["vehicle_hybrid.json"]) +async def test_stop_air_conditioning( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, +) -> None: + """Test turning the air conditioning off stops it.""" + await setup_integration(hass, mock_config_entry) + + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.TURN_OFF, + {TargetKey.ENTITY_ID: SUPERB}, + blocking=True, + ) + + mock_skoda_client.stop_air_conditioning.assert_awaited_once_with(VIN) + assert (state := hass.states.get(SUPERB)) + assert state.state == HVACMode.OFF + + +@pytest.mark.parametrize("vehicle_fixture", ["vehicle_hybrid.json"]) +async def test_set_temperature_while_running( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, +) -> None: + """Test changing the target temperature restarts the running air conditioning.""" + await setup_integration(hass, mock_config_entry) + + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.SET_TEMPERATURE, + {TargetKey.ENTITY_ID: SUPERB, ClimateServiceArgument.TEMPERATURE: 25}, + blocking=True, + ) + + mock_skoda_client.start_air_conditioning.assert_awaited_once_with(VIN, 25) + assert (state := hass.states.get(SUPERB)) + assert state.attributes[ClimateEntityStateAttribute.TARGET_TEMPERATURE] == 25 + + +async def test_set_temperature_while_off( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a target temperature set while off is kept and used on the next start.""" + await setup_integration(hass, mock_config_entry) + + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.SET_TEMPERATURE, + {TargetKey.ENTITY_ID: ENYAQ, ClimateServiceArgument.TEMPERATURE: 23}, + blocking=True, + ) + mock_skoda_client.start_air_conditioning.assert_not_awaited() + + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert (state := hass.states.get(ENYAQ)) + assert state.attributes[ClimateEntityStateAttribute.TARGET_TEMPERATURE] == 23 + + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.TURN_ON, + {TargetKey.ENTITY_ID: ENYAQ}, + blocking=True, + ) + mock_skoda_client.start_air_conditioning.assert_awaited_once_with(VIN, 23) + + +async def test_vehicle_target_temperature_change( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a new target temperature reported by the vehicle replaces the shown one.""" + await setup_integration(hass, mock_config_entry) + + vehicle = mock_skoda_client.get_vehicle.return_value.vehicle + vehicle.air_conditioning.target_temperature.value = 19.0 + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert (state := hass.states.get(ENYAQ)) + assert state.attributes[ClimateEntityStateAttribute.TARGET_TEMPERATURE] == 19.0 + + +async def test_target_temperature_kept_without_vehicle_target( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a chosen target temperature survives a poll without a vehicle target.""" + await setup_integration(hass, mock_config_entry) + + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.SET_TEMPERATURE, + {TargetKey.ENTITY_ID: ENYAQ, ClimateServiceArgument.TEMPERATURE: 23}, + blocking=True, + ) + + air_conditioning = ( + mock_skoda_client.get_vehicle.return_value.vehicle.air_conditioning + ) + reported_target = air_conditioning.target_temperature + air_conditioning.target_temperature = None + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + air_conditioning.target_temperature = reported_target + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert (state := hass.states.get(ENYAQ)) + assert state.attributes[ClimateEntityStateAttribute.TARGET_TEMPERATURE] == 23 + + +@pytest.mark.parametrize( + ( + "vehicle_fixture", + "entity_id", + "hvac_mode", + "sent_command", + "skipped_command", + "expected_mode", + ), + [ + ( + "vehicle_electric.json", + ENYAQ, + HVACMode.HEAT_COOL, + "start_air_conditioning", + "stop_air_conditioning", + HVACMode.HEAT_COOL, + ), + ( + "vehicle_hybrid.json", + SUPERB, + HVACMode.OFF, + "stop_air_conditioning", + "start_air_conditioning", + HVACMode.OFF, + ), + ], +) +async def test_set_temperature_with_hvac_mode( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, + entity_id: str, + hvac_mode: HVACMode, + sent_command: str, + skipped_command: str, + expected_mode: HVACMode, +) -> None: + """Test setting the temperature together with a mode applies the mode too.""" + await setup_integration(hass, mock_config_entry) + + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.SET_TEMPERATURE, + { + TargetKey.ENTITY_ID: entity_id, + ClimateServiceArgument.TEMPERATURE: 23, + ClimateServiceArgument.HVAC_MODE: hvac_mode, + }, + blocking=True, + ) + + getattr(mock_skoda_client, sent_command).assert_awaited_once() + getattr(mock_skoda_client, skipped_command).assert_not_awaited() + assert (state := hass.states.get(entity_id)) + assert state.state == expected_mode + assert state.attributes[ClimateEntityStateAttribute.TARGET_TEMPERATURE] == 23 + + +async def test_set_temperature_with_unsupported_hvac_mode( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, +) -> None: + """Test an unsupported mode is rejected without sending or changing anything.""" + await setup_integration(hass, mock_config_entry) + + with pytest.raises(ServiceValidationError) as exc_info: + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.SET_TEMPERATURE, + { + TargetKey.ENTITY_ID: ENYAQ, + ClimateServiceArgument.TEMPERATURE: 23, + ClimateServiceArgument.HVAC_MODE: HVACMode.HEAT, + }, + blocking=True, + ) + + assert exc_info.value.translation_key == "invalid_hvac_mode" + mock_skoda_client.start_air_conditioning.assert_not_awaited() + mock_skoda_client.stop_air_conditioning.assert_not_awaited() + assert (state := hass.states.get(ENYAQ)) + assert state.attributes[ClimateEntityStateAttribute.TARGET_TEMPERATURE] == 21.5 + + +@pytest.mark.parametrize( + ("air_conditioning_state", "expected_mode", "expected_action"), + [ + (AirConditioningState.COOLING, HVACMode.HEAT_COOL, HVACAction.COOLING), + (AirConditioningState.HEATING, HVACMode.HEAT_COOL, HVACAction.HEATING), + ( + AirConditioningState.HEATING_AUXILIARY, + HVACMode.HEAT_COOL, + HVACAction.HEATING, + ), + (AirConditioningState.VENTILATION, HVACMode.HEAT_COOL, HVACAction.FAN), + (AirConditioningState.COMPLETED, HVACMode.OFF, HVACAction.OFF), + (AirConditioningState.UNKNOWN, STATE_UNKNOWN, None), + ], +) +async def test_climate_follows_vehicle_state( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, + freezer: FrozenDateTimeFactory, + air_conditioning_state: AirConditioningState, + expected_mode: str, + expected_action: HVACAction | None, +) -> None: + """Test the climate mode and action follow the air conditioning state.""" + await setup_integration(hass, mock_config_entry) + + vehicle = mock_skoda_client.get_vehicle.return_value.vehicle + vehicle.air_conditioning.state = air_conditioning_state + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert (state := hass.states.get(ENYAQ)) + assert state.state == expected_mode + assert ( + state.attributes.get(ClimateEntityStateAttribute.HVAC_ACTION) == expected_action + ) + + +async def test_climate_action_error( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_skoda_client: AsyncMock, +) -> None: + """Test a failed command raises a translated error and keeps the state.""" + await setup_integration(hass, mock_config_entry) + mock_skoda_client.start_air_conditioning.side_effect = OpenApiError("boom") + + with pytest.raises(HomeAssistantError) as exc_info: + await hass.services.async_call( + CLIMATE_DOMAIN, + ClimateService.TURN_ON, + {TargetKey.ENTITY_ID: ENYAQ}, + blocking=True, + ) + + assert exc_info.value.translation_key == "command_failed" + assert (state := hass.states.get(ENYAQ)) + assert state.state == HVACMode.OFF