From 93e3303cff781abc73e397ed37b9154c413ff15f Mon Sep 17 00:00:00 2001 From: "Dr.Blank" <64108942+Dr-Blank@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:51:50 +0530 Subject: [PATCH] Add Fujitsu Infrared integration (#182390) --- .strict-typing | 1 + CODEOWNERS | 2 + homeassistant/brands/fujitsu.json | 2 +- .../components/fujitsu_infrared/__init__.py | 18 + .../components/fujitsu_infrared/climate.py | 338 +++++++ .../fujitsu_infrared/config_flow.py | 120 +++ .../components/fujitsu_infrared/const.py | 9 + .../components/fujitsu_infrared/entity.py | 22 + .../components/fujitsu_infrared/icons.json | 15 + .../components/fujitsu_infrared/manifest.json | 11 + .../fujitsu_infrared/quality_scale.yaml | 122 +++ .../components/fujitsu_infrared/strings.json | 59 ++ homeassistant/generated/config_flows.py | 1 + homeassistant/generated/integrations.json | 6 + mypy.ini | 10 + tests/components/fujitsu_infrared/__init__.py | 1 + tests/components/fujitsu_infrared/conftest.py | 99 ++ .../snapshots/test_climate.ambr | 101 ++ .../fujitsu_infrared/test_climate.py | 882 ++++++++++++++++++ .../fujitsu_infrared/test_config_flow.py | 205 ++++ .../components/fujitsu_infrared/test_init.py | 21 + 21 files changed, 2044 insertions(+), 1 deletion(-) create mode 100644 homeassistant/components/fujitsu_infrared/__init__.py create mode 100644 homeassistant/components/fujitsu_infrared/climate.py create mode 100644 homeassistant/components/fujitsu_infrared/config_flow.py create mode 100644 homeassistant/components/fujitsu_infrared/const.py create mode 100644 homeassistant/components/fujitsu_infrared/entity.py create mode 100644 homeassistant/components/fujitsu_infrared/icons.json create mode 100644 homeassistant/components/fujitsu_infrared/manifest.json create mode 100644 homeassistant/components/fujitsu_infrared/quality_scale.yaml create mode 100644 homeassistant/components/fujitsu_infrared/strings.json create mode 100644 tests/components/fujitsu_infrared/__init__.py create mode 100644 tests/components/fujitsu_infrared/conftest.py create mode 100644 tests/components/fujitsu_infrared/snapshots/test_climate.ambr create mode 100644 tests/components/fujitsu_infrared/test_climate.py create mode 100644 tests/components/fujitsu_infrared/test_config_flow.py create mode 100644 tests/components/fujitsu_infrared/test_init.py diff --git a/.strict-typing b/.strict-typing index 3259526bbfa0..b9098925807e 100644 --- a/.strict-typing +++ b/.strict-typing @@ -247,6 +247,7 @@ homeassistant.components.fritzbox_callmonitor.* homeassistant.components.fronius.* homeassistant.components.frontend.* homeassistant.components.fujitsu_fglair.* +homeassistant.components.fujitsu_infrared.* homeassistant.components.fully_kiosk.* homeassistant.components.fumis.* homeassistant.components.fyta.* diff --git a/CODEOWNERS b/CODEOWNERS index 2eabb3fab28f..dd46b3b24cdc 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -658,6 +658,8 @@ AGENTS.md @home-assistant/core /tests/components/fuelprices_dk/ @MTrab /homeassistant/components/fujitsu_fglair/ @crevetor /tests/components/fujitsu_fglair/ @crevetor +/homeassistant/components/fujitsu_infrared/ @Dr-Blank +/tests/components/fujitsu_infrared/ @Dr-Blank /homeassistant/components/fully_kiosk/ @cgarwood /tests/components/fully_kiosk/ @cgarwood /homeassistant/components/fumis/ @frenck diff --git a/homeassistant/brands/fujitsu.json b/homeassistant/brands/fujitsu.json index 75d12e338513..21a25452fe50 100644 --- a/homeassistant/brands/fujitsu.json +++ b/homeassistant/brands/fujitsu.json @@ -1,5 +1,5 @@ { "domain": "fujitsu", "name": "Fujitsu", - "integrations": ["fujitsu_anywair", "fujitsu_fglair"] + "integrations": ["fujitsu_anywair", "fujitsu_fglair", "fujitsu_infrared"] } diff --git a/homeassistant/components/fujitsu_infrared/__init__.py b/homeassistant/components/fujitsu_infrared/__init__.py new file mode 100644 index 000000000000..1afe7718ac72 --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/__init__.py @@ -0,0 +1,18 @@ +"""Fujitsu IR Remote integration for Home Assistant.""" + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant + +PLATFORMS = [Platform.CLIMATE] + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Set up Fujitsu IR from a config entry.""" + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Unload a Fujitsu IR config entry.""" + return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) diff --git a/homeassistant/components/fujitsu_infrared/climate.py b/homeassistant/components/fujitsu_infrared/climate.py new file mode 100644 index 000000000000..ddf540e051ff --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/climate.py @@ -0,0 +1,338 @@ +"""Climate platform for Fujitsu IR integration — Fujitsu AC.""" + +from typing import Any, override + +from infrared_protocols.codes.fujitsu.ac import FujitsuACCode +from infrared_protocols.commands.fujitsu_ac import ( + MAX_TEMP, + MIN_TEMP, + FujitsuAcCommand, + FujitsuAcFanSpeed, + FujitsuAcFixedCommand, + FujitsuAcMode, + FujitsuAcProtocol, + FujitsuAcSwing, + temperature_step, +) + +from homeassistant.components.climate import ( + ATTR_FAN_MODE, + ATTR_HVAC_MODE, + ATTR_SWING_MODE, + FAN_AUTO, + FAN_HIGH, + FAN_LOW, + FAN_MEDIUM, + SWING_BOTH, + SWING_HORIZONTAL, + SWING_OFF, + SWING_VERTICAL, + ClimateEntity, + ClimateEntityFeature, + ClimateEntityStateAttribute, + HVACMode, +) +from homeassistant.components.infrared import ( + InfraredEmitterConsumerEntity, + InfraredReceivedSignal, + InfraredReceiverConsumerEntity, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import ( + ATTR_TEMPERATURE, + CONF_PROTOCOL, + STATE_UNAVAILABLE, + STATE_UNKNOWN, + UnitOfTemperature, +) +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.restore_state import RestoreEntity +from homeassistant.util.unit_conversion import TemperatureConverter + +from .const import ( + CONF_HVAC_MODES, + CONF_INFRARED_EMITTER_ENTITY_ID, + CONF_INFRARED_RECEIVER_ENTITY_ID, + PROTOCOL_EXTENDED, +) +from .entity import FujitsuIrEntity + +PARALLEL_UPDATES = 1 + +FAN_QUIET = "quiet" + +_HA_FAN_TO_LIB: dict[str, FujitsuAcFanSpeed] = { + FAN_AUTO: FujitsuAcFanSpeed.AUTO, + FAN_QUIET: FujitsuAcFanSpeed.QUIET, + FAN_LOW: FujitsuAcFanSpeed.LOW, + FAN_MEDIUM: FujitsuAcFanSpeed.MEDIUM, + FAN_HIGH: FujitsuAcFanSpeed.HIGH, +} +_LIB_FAN_TO_HA: dict[FujitsuAcFanSpeed, str] = {v: k for k, v in _HA_FAN_TO_LIB.items()} + +# Power is a separate message rather than a mode, so this dict intentionally has no +# HVACMode.OFF entry. +_HA_MODE_TO_LIB: dict[HVACMode, FujitsuAcMode] = { + HVACMode.HEAT_COOL: FujitsuAcMode.AUTO, + HVACMode.COOL: FujitsuAcMode.COOL, + HVACMode.HEAT: FujitsuAcMode.HEAT, + HVACMode.DRY: FujitsuAcMode.DRY, + HVACMode.FAN_ONLY: FujitsuAcMode.FAN_ONLY, +} +_LIB_MODE_TO_HA: dict[FujitsuAcMode, HVACMode] = { + v: k for k, v in _HA_MODE_TO_LIB.items() +} + +# One protocol field drives both louvres, and its four values are exactly Home +# Assistant's own swing modes. +_HA_SWING_TO_LIB: dict[str, FujitsuAcSwing] = { + SWING_OFF: FujitsuAcSwing.OFF, + SWING_VERTICAL: FujitsuAcSwing.VERTICAL, + SWING_HORIZONTAL: FujitsuAcSwing.HORIZONTAL, + SWING_BOTH: FujitsuAcSwing.BOTH, +} +_LIB_SWING_TO_HA: dict[FujitsuAcSwing, str] = { + v: k for k, v in _HA_SWING_TO_LIB.items() +} + + +def _config_entry_protocol(entry: ConfigEntry) -> FujitsuAcProtocol: + """Return the protocol the configured remote family speaks.""" + if entry.data.get(CONF_PROTOCOL) == PROTOCOL_EXTENDED: + return FujitsuAcProtocol.EXTENDED + return FujitsuAcProtocol.STANDARD + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up Fujitsu AC climate entity from config entry.""" + emitter_entity_id = entry.data[CONF_INFRARED_EMITTER_ENTITY_ID] + if receiver_entity_id := entry.data.get(CONF_INFRARED_RECEIVER_ENTITY_ID): + async_add_entities( + [FujitsuAcClimateWithReceiver(entry, emitter_entity_id, receiver_entity_id)] + ) + else: + async_add_entities([FujitsuAcClimateEntity(entry, emitter_entity_id)]) + + +class FujitsuAcClimateEntity( + FujitsuIrEntity, InfraredEmitterConsumerEntity, ClimateEntity, RestoreEntity +): + """Fujitsu AC climate entity controlled via infrared emitter.""" + + _attr_name = None + _attr_native_temperature_unit = UnitOfTemperature.CELSIUS + _attr_min_temp = float(MIN_TEMP) + _attr_max_temp = float(MAX_TEMP) + _attr_should_poll = False + _attr_assumed_state = True + _attr_translation_key = "fujitsu_ac" + # Every mode's state message carries a temperature, a fan and a swing field, so all + # of these features work regardless of which modes are configured. + _attr_supported_features = ( + ClimateEntityFeature.TARGET_TEMPERATURE + | ClimateEntityFeature.FAN_MODE + | ClimateEntityFeature.SWING_MODE + ) + _attr_fan_modes = [FAN_AUTO, FAN_QUIET, FAN_LOW, FAN_MEDIUM, FAN_HIGH] + _attr_swing_modes = [SWING_OFF, SWING_VERTICAL, SWING_HORIZONTAL, SWING_BOTH] + + def __init__(self, entry: ConfigEntry, emitter_entity_id: str) -> None: + """Initialize Fujitsu AC climate entity.""" + super().__init__(entry) + self._infrared_emitter_entity_id = emitter_entity_id + self._protocol = _config_entry_protocol(entry) + self._attr_target_temperature_step = temperature_step(self._protocol) + + configured_modes = entry.data[CONF_HVAC_MODES] + self._attr_hvac_modes = [HVACMode.OFF] + [HVACMode(m) for m in configured_modes] + self._attr_hvac_mode = HVACMode.OFF + self._attr_native_target_temperature = float(MIN_TEMP) + self._attr_fan_mode = FAN_AUTO + self._attr_swing_mode = SWING_OFF + + @override + async def async_added_to_hass(self) -> None: + """Restore the assumed state, as infrared cannot read it back from the AC.""" + await super().async_added_to_hass() + + last_state = await self.async_get_last_state() + if last_state is None or last_state.state in ( + STATE_UNAVAILABLE, + STATE_UNKNOWN, + ): + return + + attributes = last_state.attributes + if last_state.state in self._attr_hvac_modes: + self._attr_hvac_mode = HVACMode(last_state.state) + if (fan_mode := attributes.get(ATTR_FAN_MODE)) in self._attr_fan_modes: + self._attr_fan_mode = fan_mode + if (swing_mode := attributes.get(ATTR_SWING_MODE)) in self._attr_swing_modes: + self._attr_swing_mode = swing_mode + if (temperature := attributes.get(ATTR_TEMPERATURE)) is not None: + self._attr_native_target_temperature = self._snap_temperature( + TemperatureConverter.convert( + float(temperature), + attributes.get( + ClimateEntityStateAttribute.TEMPERATURE_UNIT, + self.hass.config.units.temperature_unit, + ), + self.native_temperature_unit, + ) + ) + + @override + async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: + """Set HVAC mode.""" + await self._async_send_mode(hvac_mode) + self._attr_hvac_mode = hvac_mode + self.async_write_ha_state() + + @override + async def async_set_temperature(self, **kwargs: Any) -> None: + """Set the target temperature, switching the HVAC mode when one is given.""" + temperature = self._snap_temperature(float(kwargs[ATTR_TEMPERATURE])) + hvac_mode: HVACMode | None = kwargs.get(ATTR_HVAC_MODE) + if hvac_mode is not None: + self._valid_mode_or_raise("hvac", hvac_mode, self.hvac_modes) + + effective_mode = hvac_mode or self._attr_hvac_mode or HVACMode.OFF + # A unit staying off has nothing to send the temperature with; it is kept for + # the next state message instead. + if hvac_mode is not None or effective_mode is not HVACMode.OFF: + await self._async_send_mode(effective_mode, temperature=temperature) + if hvac_mode is not None: + self._attr_hvac_mode = hvac_mode + + self._attr_native_target_temperature = temperature + self.async_write_ha_state() + + @override + async def async_set_fan_mode(self, fan_mode: str) -> None: + """Set fan mode.""" + if (mode := self._active_lib_mode) is not None: + await self._async_send_state(mode, fan_mode=fan_mode) + self._attr_fan_mode = fan_mode + self.async_write_ha_state() + + @override + async def async_set_swing_mode(self, swing_mode: str) -> None: + """Set swing mode, which drives both louvres from one protocol field.""" + if (mode := self._active_lib_mode) is not None: + await self._async_send_state(mode, swing_mode=swing_mode) + self._attr_swing_mode = swing_mode + self.async_write_ha_state() + + @property + def _active_lib_mode(self) -> FujitsuAcMode | None: + """Return the protocol mode the unit runs in, or None while it is off.""" + hvac_mode = self._attr_hvac_mode + if hvac_mode is None or hvac_mode is HVACMode.OFF: + return None + return _HA_MODE_TO_LIB[hvac_mode] + + async def _async_send_mode( + self, hvac_mode: HVACMode, *, temperature: float | None = None + ) -> None: + """Send the message that puts the unit into the given HVAC mode.""" + if hvac_mode is HVACMode.OFF: + await self._send_command(FujitsuACCode.POWER_OFF.to_command()) + return + + await self._async_send_state( + _HA_MODE_TO_LIB[hvac_mode], + # A state message only starts a unit that is off when it carries this flag. + power=self._attr_hvac_mode is HVACMode.OFF, + temperature=temperature, + ) + + async def _async_send_state( + self, + mode: FujitsuAcMode, + *, + power: bool = False, + temperature: float | None = None, + fan_mode: str | None = None, + swing_mode: str | None = None, + ) -> None: + """Send a state message, taking whatever is not given from the assumed state.""" + if temperature is None: + temperature = self._attr_native_target_temperature or float(MIN_TEMP) + swing = swing_mode or self._attr_swing_mode or SWING_OFF + await self._send_command( + FujitsuAcCommand( + protocol=self._protocol, + power=power, + mode=mode, + temperature=temperature, + fan=_HA_FAN_TO_LIB[fan_mode or self._attr_fan_mode or FAN_AUTO], + swing=_HA_SWING_TO_LIB[swing], + ) + ) + + def _snap_temperature(self, temperature: float) -> float: + """Round a temperature onto the grid the configured format can carry exactly. + + Every temperature reaching this entity from outside goes through here: Home + Assistant does not enforce the step on a service call, a restored state was + stored on whatever grid the system unit uses, and a remote can send a half + degree to a unit configured for whole ones. The protocol rejects anything else. + """ + step: float = temperature_step(self._protocol) + snapped = round(temperature / step) * step + return min(max(snapped, float(MIN_TEMP)), float(MAX_TEMP)) + + +class FujitsuAcClimateWithReceiver( + FujitsuAcClimateEntity, InfraredReceiverConsumerEntity +): + """Fujitsu AC climate entity that also tracks an infrared receiver.""" + + def __init__( + self, entry: ConfigEntry, emitter_entity_id: str, receiver_entity_id: str + ) -> None: + """Initialize Fujitsu AC climate entity with a receiver.""" + super().__init__(entry, emitter_entity_id) + self._infrared_receiver_entity_id = receiver_entity_id + + @override + @callback + def _handle_signal(self, signal: InfraredReceivedSignal) -> None: + """Update state from a physical remote signal.""" + command = FujitsuAcCommand.from_raw_timings(signal.timings) + if command is None: + # The other message a remote sends that changes this entity's state is + # power off, which carries nothing but its own type. + fixed = FujitsuAcFixedCommand.from_raw_timings(signal.timings) + if fixed is not None and fixed.code == FujitsuACCode.POWER_OFF: + self._attr_hvac_mode = HVACMode.OFF + self.async_write_ha_state() + return + + if command.protocol is not self._protocol: + return + + hvac_mode = _LIB_MODE_TO_HA[command.mode] + if hvac_mode not in self._attr_hvac_modes: + return + + self._attr_hvac_mode = hvac_mode + # A remote set to Fahrenheit sends its own scale, and this entity is Celsius. + self._attr_native_target_temperature = self._snap_temperature( + TemperatureConverter.convert( + command.temperature, + UnitOfTemperature.FAHRENHEIT, + UnitOfTemperature.CELSIUS, + ) + if command.is_fahrenheit + else command.temperature + ) + self._attr_fan_mode = _LIB_FAN_TO_HA[command.fan] + self._attr_swing_mode = _LIB_SWING_TO_HA[command.swing] + + self.async_write_ha_state() diff --git a/homeassistant/components/fujitsu_infrared/config_flow.py b/homeassistant/components/fujitsu_infrared/config_flow.py new file mode 100644 index 000000000000..4102b10525b3 --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/config_flow.py @@ -0,0 +1,120 @@ +"""Config flow for Fujitsu IR integration.""" + +from typing import Any, override + +import probatio + +from homeassistant.components.climate import HVACMode +from homeassistant.components.infrared import ( + DOMAIN as INFRARED_DOMAIN, + async_get_emitters, + async_get_receivers, +) +from homeassistant.config_entries import ConfigFlow, ConfigFlowResult +from homeassistant.const import CONF_PROTOCOL +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.selector import ( + EntitySelector, + EntitySelectorConfig, + SelectSelector, + SelectSelectorConfig, + SelectSelectorMode, +) + +from .const import ( + CONF_HVAC_MODES, + CONF_INFRARED_EMITTER_ENTITY_ID, + CONF_INFRARED_RECEIVER_ENTITY_ID, + DOMAIN, + PROTOCOL_EXTENDED, + PROTOCOL_STANDARD, +) + +_HVAC_MODE_OPTIONS = [ + HVACMode.COOL, + HVACMode.HEAT, + HVACMode.DRY, + HVACMode.FAN_ONLY, + HVACMode.HEAT_COOL, +] +_DEFAULT_HVAC_MODES = [HVACMode.COOL, HVACMode.DRY] + +_PROTOCOL_OPTIONS = [PROTOCOL_STANDARD, PROTOCOL_EXTENDED] + + +@callback +def _user_schema(hass: HomeAssistant) -> probatio.Schema: + """Return the emitter/receiver/mode selection schema.""" + return probatio.Schema( + { + probatio.Required(CONF_INFRARED_EMITTER_ENTITY_ID): EntitySelector( + EntitySelectorConfig( + domain=INFRARED_DOMAIN, + include_entities=async_get_emitters(hass), + ) + ), + probatio.Optional(CONF_INFRARED_RECEIVER_ENTITY_ID): EntitySelector( + EntitySelectorConfig( + domain=INFRARED_DOMAIN, + include_entities=async_get_receivers(hass), + ) + ), + probatio.Required( + CONF_HVAC_MODES, default=_DEFAULT_HVAC_MODES + ): probatio.All( + SelectSelector( + SelectSelectorConfig( + options=[mode.value for mode in _HVAC_MODE_OPTIONS], + translation_key=CONF_HVAC_MODES, + mode=SelectSelectorMode.LIST, + multiple=True, + ) + ), + probatio.Length(min=1, msg="no_hvac_modes"), + ), + probatio.Required(CONF_PROTOCOL, default=PROTOCOL_STANDARD): SelectSelector( + SelectSelectorConfig( + options=_PROTOCOL_OPTIONS, + translation_key=CONF_PROTOCOL, + mode=SelectSelectorMode.LIST, + ) + ), + } + ) + + +class FujitsuIrConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle config flow for Fujitsu IR.""" + + VERSION = 1 + + def _entity_name(self, entity_id: str) -> str: + ent_reg = er.async_get(self.hass) + entry = ent_reg.async_get(entity_id) + return entry.name or entry.original_name or entity_id if entry else entity_id + + @override + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle emitter, receiver and mode selection.""" + if not async_get_emitters(self.hass): + return self.async_abort(reason="no_infrared_emitters") + + if user_input is not None: + emitter_id = user_input[CONF_INFRARED_EMITTER_ENTITY_ID] + self._async_abort_entries_match( + {CONF_INFRARED_EMITTER_ENTITY_ID: emitter_id} + ) + if receiver_id := user_input.get(CONF_INFRARED_RECEIVER_ENTITY_ID): + self._async_abort_entries_match( + {CONF_INFRARED_RECEIVER_ENTITY_ID: receiver_id} + ) + + return self.async_create_entry( + title=f"Fujitsu AC via {self._entity_name(emitter_id)}", + data=user_input, + ) + + return self.async_show_form(step_id="user", data_schema=_user_schema(self.hass)) diff --git a/homeassistant/components/fujitsu_infrared/const.py b/homeassistant/components/fujitsu_infrared/const.py new file mode 100644 index 000000000000..fcba040065df --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/const.py @@ -0,0 +1,9 @@ +"""Constants for the Fujitsu IR integration.""" + +DOMAIN = "fujitsu_infrared" +CONF_INFRARED_EMITTER_ENTITY_ID = "infrared_emitter_entity_id" +CONF_INFRARED_RECEIVER_ENTITY_ID = "infrared_receiver_entity_id" +CONF_HVAC_MODES = "hvac_modes" + +PROTOCOL_STANDARD = "standard" +PROTOCOL_EXTENDED = "extended" diff --git a/homeassistant/components/fujitsu_infrared/entity.py b/homeassistant/components/fujitsu_infrared/entity.py new file mode 100644 index 000000000000..7cdb91756a08 --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/entity.py @@ -0,0 +1,22 @@ +"""Common entity for Fujitsu IR integration.""" + +from homeassistant.config_entries import ConfigEntry +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity import Entity + +from .const import DOMAIN + + +class FujitsuIrEntity(Entity): + """Fujitsu IR base entity providing common device info.""" + + _attr_has_entity_name = True + + def __init__(self, entry: ConfigEntry) -> None: + """Initialize Fujitsu IR entity.""" + self._attr_unique_id = entry.entry_id + self._attr_device_info = DeviceInfo( + identifiers={(DOMAIN, entry.entry_id)}, + name="Fujitsu AC", + manufacturer="Fujitsu General", + ) diff --git a/homeassistant/components/fujitsu_infrared/icons.json b/homeassistant/components/fujitsu_infrared/icons.json new file mode 100644 index 000000000000..6d16688267dc --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/icons.json @@ -0,0 +1,15 @@ +{ + "entity": { + "climate": { + "fujitsu_ac": { + "state_attributes": { + "fan_mode": { + "state": { + "quiet": "mdi:volume-off" + } + } + } + } + } + } +} diff --git a/homeassistant/components/fujitsu_infrared/manifest.json b/homeassistant/components/fujitsu_infrared/manifest.json new file mode 100644 index 000000000000..357ca15f8364 --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/manifest.json @@ -0,0 +1,11 @@ +{ + "domain": "fujitsu_infrared", + "name": "Fujitsu Infrared", + "codeowners": ["@Dr-Blank"], + "config_flow": true, + "dependencies": ["infrared"], + "documentation": "https://www.home-assistant.io/integrations/fujitsu_infrared", + "integration_type": "device", + "iot_class": "assumed_state", + "quality_scale": "silver" +} diff --git a/homeassistant/components/fujitsu_infrared/quality_scale.yaml b/homeassistant/components/fujitsu_infrared/quality_scale.yaml new file mode 100644 index 000000000000..d8c7c9f6a1bb --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/quality_scale.yaml @@ -0,0 +1,122 @@ +rules: + # Bronze + action-setup: + status: exempt + comment: | + This integration does not provide additional actions. + appropriate-polling: + status: exempt + comment: | + This integration does not poll. + brands: done + common-modules: done + config-flow-test-coverage: done + config-flow: done + dependency-transparency: done + docs-actions: + status: exempt + comment: | + This integration does not provide additional actions. + docs-conditions: + status: exempt + comment: This integration does not have any conditions. + docs-high-level-description: done + docs-installation-instructions: done + docs-removal-instructions: done + docs-triggers: + status: exempt + comment: This integration does not have any triggers. + entity-event-setup: done + entity-unique-id: done + has-entity-name: done + runtime-data: + status: exempt + comment: | + This integration does not store runtime data. + test-before-configure: + status: exempt + comment: | + The config flow only selects an existing infrared emitter entity and the + supported modes, so there is no device connection to validate before + creating the entry. + test-before-setup: + status: exempt + comment: | + This integration only proxies commands through an existing infrared + entity, so there is no separate connection to validate during setup. + unique-config-entry: done + # Silver + action-exceptions: + status: exempt + comment: | + This integration does not register custom actions. + config-entry-unloading: done + docs-configuration-parameters: done + docs-installation-parameters: done + entity-unavailable: done + integration-owner: done + log-when-unavailable: done + parallel-updates: done + reauthentication-flow: + status: exempt + comment: | + This integration does not require authentication. + test-coverage: done + # Gold + devices: done + diagnostics: todo + discovery-update-info: + status: exempt + comment: | + This integration does not support discovery. + discovery: + status: exempt + comment: | + This integration is configured manually via config flow. + docs-data-update: + status: exempt + comment: | + This integration does not fetch data from devices. + docs-examples: todo + docs-known-limitations: done + docs-supported-devices: done + docs-supported-functions: done + docs-troubleshooting: todo + docs-use-cases: todo + dynamic-devices: + status: exempt + comment: | + Each config entry creates a single device. + entity-category: done + entity-device-class: done + entity-disabled-by-default: + status: exempt + comment: | + No entities should be disabled by default. + entity-translations: done + exception-translations: + status: exempt + comment: | + This integration does not raise exceptions. + icon-translations: done + reconfiguration-flow: todo + repair-issues: + status: exempt + comment: | + This integration does not have repairable issues. + stale-devices: + status: exempt + comment: | + Each config entry manages exactly one device. + + # Platinum + async-dependency: + status: exempt + comment: | + This integration depends on infrared_protocols, which provides only code + definitions with no I/O, so async dependency does not apply. + inject-websession: + status: exempt + comment: | + This integration does not make HTTP requests. + strict-typing: done diff --git a/homeassistant/components/fujitsu_infrared/strings.json b/homeassistant/components/fujitsu_infrared/strings.json new file mode 100644 index 000000000000..51bc91b6bd99 --- /dev/null +++ b/homeassistant/components/fujitsu_infrared/strings.json @@ -0,0 +1,59 @@ +{ + "config": { + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", + "no_infrared_emitters": "[%key:common::config_flow::abort::no_infrared_emitters%]" + }, + "error": { + "no_hvac_modes": "Select at least one supported mode." + }, + "step": { + "user": { + "data": { + "hvac_modes": "Supported modes", + "infrared_emitter_entity_id": "[%key:common::config_flow::data::infrared_entity_id%]", + "infrared_receiver_entity_id": "[%key:common::config_flow::data::infrared_receiver_entity_id%]", + "protocol": "Temperature steps" + }, + "data_description": { + "hvac_modes": "Select the operating modes your AC unit supports. Heat is not available on all models.", + "infrared_emitter_entity_id": "[%key:common::config_flow::data_description::infrared_entity_id%]", + "infrared_receiver_entity_id": "Optional — allows the integration to update state when the physical remote is used.", + "protocol": "Half degrees are only carried by the extended message format. Select it if your remote's display shows half degrees in Celsius, such as 24.5." + }, + "description": "Select an infrared emitter and the modes your Fujitsu AC supports.", + "title": "Set up Fujitsu AC" + } + } + }, + "entity": { + "climate": { + "fujitsu_ac": { + "state_attributes": { + "fan_mode": { + "state": { + "quiet": "Quiet" + } + } + } + } + } + }, + "selector": { + "hvac_modes": { + "options": { + "cool": "Cool", + "dry": "Dry", + "fan_only": "Fan only", + "heat": "Heat", + "heat_cool": "Heat/Cool" + } + }, + "protocol": { + "options": { + "extended": "Half degrees", + "standard": "Whole degrees" + } + } + } +} diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index 5f546b38c57e..a5fc715fdccc 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -282,6 +282,7 @@ FLOWS = { "frontier_silicon", "fuelprices_dk", "fujitsu_fglair", + "fujitsu_infrared", "fully_kiosk", "fumis", "fyta", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index 4218fff68237..09cb7e182cb4 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -5008,6 +5008,12 @@ "cloud" ], "name": "FGLair" + }, + "fujitsu_infrared": { + "integration_type": "device", + "config_flow": true, + "iot_class": "assumed_state", + "name": "Fujitsu Infrared" } } }, diff --git a/mypy.ini b/mypy.ini index 68902e696ee4..f48b6c2315bb 100644 --- a/mypy.ini +++ b/mypy.ini @@ -2217,6 +2217,16 @@ disallow_untyped_defs = true warn_return_any = true warn_unreachable = true +[mypy-homeassistant.components.fujitsu_infrared.*] +check_untyped_defs = true +disallow_incomplete_defs = true +disallow_subclassing_any = true +disallow_untyped_calls = true +disallow_untyped_decorators = true +disallow_untyped_defs = true +warn_return_any = true +warn_unreachable = true + [mypy-homeassistant.components.fully_kiosk.*] check_untyped_defs = true disallow_incomplete_defs = true diff --git a/tests/components/fujitsu_infrared/__init__.py b/tests/components/fujitsu_infrared/__init__.py new file mode 100644 index 000000000000..2bcc22138ec1 --- /dev/null +++ b/tests/components/fujitsu_infrared/__init__.py @@ -0,0 +1 @@ +"""Tests for the Fujitsu Infrared integration.""" diff --git a/tests/components/fujitsu_infrared/conftest.py b/tests/components/fujitsu_infrared/conftest.py new file mode 100644 index 000000000000..8ec8d382cc36 --- /dev/null +++ b/tests/components/fujitsu_infrared/conftest.py @@ -0,0 +1,99 @@ +"""Common fixtures for the Fujitsu Infrared tests.""" + +from typing import Any +from unittest.mock import patch + +import pytest + +from homeassistant.components.climate import HVACMode +from homeassistant.components.fujitsu_infrared import PLATFORMS +from homeassistant.components.fujitsu_infrared.const import ( + CONF_HVAC_MODES, + CONF_INFRARED_EMITTER_ENTITY_ID, + CONF_INFRARED_RECEIVER_ENTITY_ID, + DOMAIN, + PROTOCOL_STANDARD, +) +from homeassistant.const import CONF_PROTOCOL, Platform +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry +from tests.components.infrared import ( + EMITTER_ENTITY_ID as MOCK_INFRARED_EMITTER_ENTITY_ID, + RECEIVER_ENTITY_ID as MOCK_INFRARED_RECEIVER_ENTITY_ID, +) +from tests.components.infrared.common import ( + MockInfraredEmitterEntity, + MockInfraredReceiverEntity, +) + +ENTRY_ID = "01JTEST0000000000000000001" + + +@pytest.fixture +def hvac_modes() -> list[HVACMode]: + """Return the HVAC modes configured on the config entry.""" + return [HVACMode.COOL, HVACMode.DRY] + + +@pytest.fixture +def has_receiver() -> bool: + """Return whether the config entry has an infrared receiver configured.""" + return True + + +@pytest.fixture +def protocol() -> str: + """Return the protocol configured on the config entry.""" + return PROTOCOL_STANDARD + + +@pytest.fixture +def extra_entry_data(hvac_modes: list[HVACMode], protocol: str) -> dict[str, Any]: + """Return the config entry data beyond the emitter/receiver ids.""" + return {CONF_HVAC_MODES: hvac_modes, CONF_PROTOCOL: protocol} + + +@pytest.fixture +def mock_config_entry( + extra_entry_data: dict[str, Any], + has_receiver: bool, +) -> MockConfigEntry: + """Return a mock config entry for the Fujitsu AC.""" + data: dict[str, Any] = { + CONF_INFRARED_EMITTER_ENTITY_ID: MOCK_INFRARED_EMITTER_ENTITY_ID, + **extra_entry_data, + } + if has_receiver: + data[CONF_INFRARED_RECEIVER_ENTITY_ID] = MOCK_INFRARED_RECEIVER_ENTITY_ID + + return MockConfigEntry( + domain=DOMAIN, + entry_id=ENTRY_ID, + title="Fujitsu AC via Test IR emitter", + data=data, + ) + + +@pytest.fixture +def platforms() -> list[Platform]: + """Return platforms to set up.""" + return PLATFORMS + + +@pytest.fixture +async def init_integration( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_infrared_emitter_entity: MockInfraredEmitterEntity, + mock_infrared_receiver_entity: MockInfraredReceiverEntity, + platforms: list[Platform], +) -> MockConfigEntry: + """Set up the Fujitsu Infrared integration for testing.""" + mock_config_entry.add_to_hass(hass) + + with patch("homeassistant.components.fujitsu_infrared.PLATFORMS", platforms): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + return mock_config_entry diff --git a/tests/components/fujitsu_infrared/snapshots/test_climate.ambr b/tests/components/fujitsu_infrared/snapshots/test_climate.ambr new file mode 100644 index 000000000000..0d1538cccfb3 --- /dev/null +++ b/tests/components/fujitsu_infrared/snapshots/test_climate.ambr @@ -0,0 +1,101 @@ +# serializer version: 1 +# name: test_entities[climate.fujitsu_ac-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'auto', + 'quiet', + 'low', + 'medium', + 'high', + ]), + : list([ + , + , + , + ]), + : 30.0, + : 16.0, + : list([ + 'off', + 'vertical', + 'horizontal', + 'both', + ]), + : 1.0, + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'climate', + 'entity_category': None, + 'entity_id': 'climate.fujitsu_ac', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': None, + 'platform': 'fujitsu_infrared', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'fujitsu_ac', + 'unique_id': '01JTEST0000000000000000001', + 'unit_of_measurement': None, + }) +# --- +# name: test_entities[climate.fujitsu_ac-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : True, + : None, + : 'auto', + : list([ + 'auto', + 'quiet', + 'low', + 'medium', + 'high', + ]), + : 'Fujitsu AC', + : list([ + , + , + , + ]), + : 30.0, + : 16.0, + : , + : 'off', + : list([ + 'off', + 'vertical', + 'horizontal', + 'both', + ]), + : 1.0, + : 16.0, + : , + }), + 'context': , + 'entity_id': 'climate.fujitsu_ac', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- diff --git a/tests/components/fujitsu_infrared/test_climate.py b/tests/components/fujitsu_infrared/test_climate.py new file mode 100644 index 000000000000..7b5e26b634af --- /dev/null +++ b/tests/components/fujitsu_infrared/test_climate.py @@ -0,0 +1,882 @@ +"""Tests for the Fujitsu Infrared climate platform.""" + +from typing import Any +from unittest.mock import patch + +from infrared_protocols.codes.fujitsu.ac import FujitsuACCode +from infrared_protocols.commands.fujitsu_ac import ( + MIN_TEMP, + FujitsuAcCommand, + FujitsuAcFanSpeed, + FujitsuAcMode, + FujitsuAcProtocol, + FujitsuAcSwing, +) +import pytest +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.climate import ( + ATTR_FAN_MODE, + ATTR_HVAC_MODE, + ATTR_SWING_MODE, + DOMAIN as CLIMATE_DOMAIN, + FAN_AUTO, + FAN_HIGH, + FAN_LOW, + FAN_MEDIUM, + SERVICE_SET_FAN_MODE, + SERVICE_SET_HVAC_MODE, + SERVICE_SET_SWING_MODE, + SERVICE_SET_TEMPERATURE, + SWING_BOTH, + SWING_HORIZONTAL, + SWING_OFF, + SWING_VERTICAL, + ClimateEntityFeature, + ClimateEntityStateAttribute, + HVACMode, +) +from homeassistant.components.fujitsu_infrared.climate import FAN_QUIET +from homeassistant.components.fujitsu_infrared.const import ( + PROTOCOL_EXTENDED, + PROTOCOL_STANDARD, +) +from homeassistant.components.infrared import InfraredReceivedSignal +from homeassistant.const import ( + ATTR_ENTITY_ID, + ATTR_TEMPERATURE, + STATE_UNAVAILABLE, + Platform, + UnitOfTemperature, +) +from homeassistant.core import HomeAssistant, State +from homeassistant.exceptions import ServiceValidationError +from homeassistant.helpers import entity_registry as er +from homeassistant.util.unit_system import ( + METRIC_SYSTEM, + US_CUSTOMARY_SYSTEM, + UnitSystem, +) + +from tests.common import MockConfigEntry, mock_restore_cache, snapshot_platform +from tests.components.common import assert_availability_follows_source_entity +from tests.components.infrared import EMITTER_ENTITY_ID, RECEIVER_ENTITY_ID +from tests.components.infrared.common import ( + MockInfraredEmitterEntity, + MockInfraredReceiverEntity, +) + +_CLIMATE_ENTITY_ID = "climate.fujitsu_ac" + +_ALL_MODES = [ + HVACMode.COOL, + HVACMode.HEAT, + HVACMode.DRY, + HVACMode.FAN_ONLY, + HVACMode.HEAT_COOL, +] + + +@pytest.fixture +def platforms() -> list[Platform]: + """Return platforms to set up.""" + return [Platform.CLIMATE] + + +@pytest.fixture +def has_receiver() -> bool: + """Return whether the config entry has an infrared receiver configured.""" + return False + + +async def _set_hvac_mode(hass: HomeAssistant, hvac_mode: HVACMode) -> None: + """Call the set_hvac_mode action on the climate entity.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_HVAC_MODE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_HVAC_MODE: hvac_mode}, + blocking=True, + ) + + +def _sent_timings(emitter: MockInfraredEmitterEntity) -> list[int]: + """Return the raw timings of the single command the emitter was given.""" + assert len(emitter.send_command_calls) == 1 + return emitter.send_command_calls[0].get_raw_timings() + + +@pytest.mark.usefixtures("init_integration") +async def test_entities( + hass: HomeAssistant, + snapshot: SnapshotAssertion, + entity_registry: er.EntityRegistry, + mock_config_entry: MockConfigEntry, +) -> None: + """Test entity state and registry snapshot.""" + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + ("has_receiver", "source_entity_ids"), + [ + pytest.param(False, [EMITTER_ENTITY_ID], id="emitter"), + pytest.param( + True, [EMITTER_ENTITY_ID, RECEIVER_ENTITY_ID], id="emitter_and_receiver" + ), + ], +) +@pytest.mark.usefixtures("init_integration") +async def test_availability_follows_sources( + hass: HomeAssistant, + source_entity_ids: list[str], +) -> None: + """Test climate entity availability follows all configured infrared entities.""" + await assert_availability_follows_source_entity( + hass, _CLIMATE_ENTITY_ID, source_entity_ids + ) + + +@pytest.mark.parametrize("has_receiver", [True]) +@pytest.mark.parametrize( + "unavailable_entity_id", + [ + pytest.param(EMITTER_ENTITY_ID, id="emitter"), + pytest.param(RECEIVER_ENTITY_ID, id="receiver"), + ], +) +@pytest.mark.usefixtures("init_integration") +async def test_initial_availability_requires_emitter_and_receiver( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + unavailable_entity_id: str, +) -> None: + """Test the entity starts unavailable if either emitter or receiver is.""" + hass.states.async_set(unavailable_entity_id, STATE_UNAVAILABLE) + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.state == STATE_UNAVAILABLE + + +@pytest.mark.usefixtures("init_integration") +async def test_supported_features(hass: HomeAssistant) -> None: + """Test every state field is offered, since every mode's message carries them.""" + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes["supported_features"] == ( + ClimateEntityFeature.TARGET_TEMPERATURE + | ClimateEntityFeature.FAN_MODE + | ClimateEntityFeature.SWING_MODE + ) + + +@pytest.mark.usefixtures("init_integration") +async def test_set_hvac_mode_off( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test turning off sends the power-off message, which carries no state.""" + await _set_hvac_mode(hass, HVACMode.OFF) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuACCode.POWER_OFF.to_command().get_raw_timings() + ) + + +@pytest.mark.parametrize("hvac_modes", [_ALL_MODES]) +@pytest.mark.usefixtures("init_integration") +@pytest.mark.parametrize( + ("hvac_mode", "lib_mode"), + [ + pytest.param(HVACMode.COOL, FujitsuAcMode.COOL, id="cool"), + pytest.param(HVACMode.HEAT, FujitsuAcMode.HEAT, id="heat"), + pytest.param(HVACMode.DRY, FujitsuAcMode.DRY, id="dry"), + pytest.param(HVACMode.FAN_ONLY, FujitsuAcMode.FAN_ONLY, id="fan_only"), + pytest.param(HVACMode.HEAT_COOL, FujitsuAcMode.AUTO, id="heat_cool"), + ], +) +async def test_set_hvac_mode_from_off_sets_power_flag( + hass: HomeAssistant, + mock_infrared_emitter_entity: MockInfraredEmitterEntity, + hvac_mode: HVACMode, + lib_mode: FujitsuAcMode, +) -> None: + """Test every mode encodes correctly and starts a unit that is off.""" + await _set_hvac_mode(hass, hvac_mode) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand( + power=True, mode=lib_mode, temperature=MIN_TEMP + ).get_raw_timings() + ) + + +@pytest.mark.parametrize("hvac_modes", [_ALL_MODES]) +@pytest.mark.usefixtures("init_integration") +async def test_set_hvac_mode_while_running_clears_power_flag( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test a running unit is not sent the flag that starts it.""" + await _set_hvac_mode(hass, HVACMode.COOL) + mock_infrared_emitter_entity.send_command_calls.clear() + + await _set_hvac_mode(hass, HVACMode.HEAT) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand( + mode=FujitsuAcMode.HEAT, temperature=MIN_TEMP + ).get_raw_timings() + ) + + +@pytest.mark.usefixtures("init_integration") +async def test_set_temperature_sends_command_when_active( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test set_temperature sends the whole state while the AC is on.""" + await _set_hvac_mode(hass, HVACMode.COOL) + mock_infrared_emitter_entity.send_command_calls.clear() + + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_TEMPERATURE: 26}, + blocking=True, + ) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand(mode=FujitsuAcMode.COOL, temperature=26).get_raw_timings() + ) + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes[ATTR_TEMPERATURE] == 26.0 + + +@pytest.mark.parametrize("protocol", [PROTOCOL_EXTENDED]) +@pytest.mark.usefixtures("init_integration") +async def test_extended_protocol_offers_half_degree_steps(hass: HomeAssistant) -> None: + """Test a half-degree remote advertises the step it can actually send.""" + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes["target_temp_step"] == 0.5 + + +@pytest.mark.parametrize("protocol", [PROTOCOL_EXTENDED]) +@pytest.mark.usefixtures("init_integration") +async def test_extended_protocol_sends_half_degrees( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test a half-degree setpoint reaches the emitter unrounded.""" + await _set_hvac_mode(hass, HVACMode.COOL) + mock_infrared_emitter_entity.send_command_calls.clear() + + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_TEMPERATURE: 24.5}, + blocking=True, + ) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand( + protocol=FujitsuAcProtocol.EXTENDED, + mode=FujitsuAcMode.COOL, + temperature=24.5, + ).get_raw_timings() + ) + + +@pytest.mark.parametrize( + ("protocol", "requested", "expected"), + [ + pytest.param( + PROTOCOL_STANDARD, 24.5, 24.0, id="standard_rounds_a_half_degree_away" + ), + pytest.param(PROTOCOL_EXTENDED, 24.2, 24.0, id="extended_rounds_down"), + pytest.param(PROTOCOL_EXTENDED, 24.4, 24.5, id="extended_rounds_up"), + ], +) +@pytest.mark.usefixtures("init_integration") +async def test_temperature_is_snapped_to_a_step_the_remote_can_send( + hass: HomeAssistant, + mock_infrared_emitter_entity: MockInfraredEmitterEntity, + requested: float, + expected: float, +) -> None: + """Test a setpoint finer than the protocol allows is rounded, not rejected. + + Home Assistant does not enforce the step, so a whole-degree remote can be asked + for 24.5 and has no field to put the half in. + """ + await _set_hvac_mode(hass, HVACMode.COOL) + mock_infrared_emitter_entity.send_command_calls.clear() + + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_TEMPERATURE: requested}, + blocking=True, + ) + + command = mock_infrared_emitter_entity.send_command_calls[0] + assert isinstance(command, FujitsuAcCommand) + assert command.temperature == expected + + +@pytest.mark.usefixtures("init_integration") +async def test_set_temperature_no_command_when_off( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test set_temperature updates state but sends nothing while the AC is off.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_TEMPERATURE: 22}, + blocking=True, + ) + + assert len(mock_infrared_emitter_entity.send_command_calls) == 0 + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes[ATTR_TEMPERATURE] == 22.0 + + +@pytest.mark.usefixtures("init_integration") +async def test_set_temperature_with_hvac_mode( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test set_temperature switches mode when one is given, even while off.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + { + ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, + ATTR_TEMPERATURE: 24, + ATTR_HVAC_MODE: HVACMode.COOL, + }, + blocking=True, + ) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand( + power=True, mode=FujitsuAcMode.COOL, temperature=24 + ).get_raw_timings() + ) + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.state == HVACMode.COOL + assert state.attributes[ATTR_TEMPERATURE] == 24.0 + + +@pytest.mark.usefixtures("init_integration") +async def test_set_temperature_with_hvac_mode_off( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test set_temperature turns the unit off when it is given the off mode.""" + await _set_hvac_mode(hass, HVACMode.COOL) + mock_infrared_emitter_entity.send_command_calls.clear() + + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + { + ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, + ATTR_TEMPERATURE: 24, + ATTR_HVAC_MODE: HVACMode.OFF, + }, + blocking=True, + ) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuACCode.POWER_OFF.to_command().get_raw_timings() + ) + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.state == HVACMode.OFF + assert state.attributes[ATTR_TEMPERATURE] == 24.0 + + +@pytest.mark.usefixtures("init_integration") +async def test_set_temperature_with_unsupported_hvac_mode( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test a mode the unit does not support is rejected instead of sent.""" + with pytest.raises(ServiceValidationError): + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + { + ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, + ATTR_TEMPERATURE: 24, + ATTR_HVAC_MODE: HVACMode.HEAT, + }, + blocking=True, + ) + + assert len(mock_infrared_emitter_entity.send_command_calls) == 0 + + +@pytest.mark.usefixtures("init_integration") +@pytest.mark.parametrize( + ("fan_mode", "lib_fan"), + [ + pytest.param(FAN_AUTO, FujitsuAcFanSpeed.AUTO, id="auto"), + pytest.param(FAN_QUIET, FujitsuAcFanSpeed.QUIET, id="quiet"), + pytest.param(FAN_LOW, FujitsuAcFanSpeed.LOW, id="low"), + pytest.param(FAN_MEDIUM, FujitsuAcFanSpeed.MEDIUM, id="medium"), + pytest.param(FAN_HIGH, FujitsuAcFanSpeed.HIGH, id="high"), + ], +) +async def test_set_fan_mode_sends_command_when_active( + hass: HomeAssistant, + mock_infrared_emitter_entity: MockInfraredEmitterEntity, + fan_mode: str, + lib_fan: FujitsuAcFanSpeed, +) -> None: + """Test every fan speed encodes correctly while the AC is on.""" + await _set_hvac_mode(hass, HVACMode.COOL) + mock_infrared_emitter_entity.send_command_calls.clear() + + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_FAN_MODE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_FAN_MODE: fan_mode}, + blocking=True, + ) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand( + mode=FujitsuAcMode.COOL, temperature=MIN_TEMP, fan=lib_fan + ).get_raw_timings() + ) + + +@pytest.mark.usefixtures("init_integration") +async def test_set_fan_mode_no_command_when_off( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test set_fan_mode updates state but sends nothing while the AC is off.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_FAN_MODE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_FAN_MODE: FAN_HIGH}, + blocking=True, + ) + + assert len(mock_infrared_emitter_entity.send_command_calls) == 0 + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes[ATTR_FAN_MODE] == FAN_HIGH + + +@pytest.mark.usefixtures("init_integration") +@pytest.mark.parametrize( + ("swing_mode", "lib_swing"), + [ + pytest.param(SWING_OFF, FujitsuAcSwing.OFF, id="off"), + pytest.param(SWING_VERTICAL, FujitsuAcSwing.VERTICAL, id="vertical"), + pytest.param(SWING_HORIZONTAL, FujitsuAcSwing.HORIZONTAL, id="horizontal"), + pytest.param(SWING_BOTH, FujitsuAcSwing.BOTH, id="both"), + ], +) +async def test_swing_mode_maps_to_the_protocol_field( + hass: HomeAssistant, + mock_infrared_emitter_entity: MockInfraredEmitterEntity, + swing_mode: str, + lib_swing: FujitsuAcSwing, +) -> None: + """Test each swing mode reaches the single two-bit protocol field.""" + await _set_hvac_mode(hass, HVACMode.COOL) + mock_infrared_emitter_entity.send_command_calls.clear() + + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_SWING_MODE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_SWING_MODE: swing_mode}, + blocking=True, + ) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand( + mode=FujitsuAcMode.COOL, temperature=MIN_TEMP, swing=lib_swing + ).get_raw_timings() + ) + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes[ATTR_SWING_MODE] == swing_mode + + +@pytest.mark.usefixtures("init_integration") +async def test_set_swing_no_command_when_off( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test the swing action updates state but sends nothing while the AC is off.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_SWING_MODE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_SWING_MODE: SWING_BOTH}, + blocking=True, + ) + + assert len(mock_infrared_emitter_entity.send_command_calls) == 0 + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes[ATTR_SWING_MODE] == SWING_BOTH + + +@pytest.mark.parametrize("has_receiver", [True]) +@pytest.mark.usefixtures("init_integration") +@pytest.mark.parametrize( + ("lib_fan", "expected_fan_mode"), + [ + pytest.param(FujitsuAcFanSpeed.AUTO, FAN_AUTO, id="auto"), + pytest.param(FujitsuAcFanSpeed.QUIET, FAN_QUIET, id="quiet"), + pytest.param(FujitsuAcFanSpeed.LOW, FAN_LOW, id="low"), + pytest.param(FujitsuAcFanSpeed.MEDIUM, FAN_MEDIUM, id="medium"), + pytest.param(FujitsuAcFanSpeed.HIGH, FAN_HIGH, id="high"), + ], +) +async def test_receiver_updates_state_on_cool_signal( + hass: HomeAssistant, + mock_infrared_receiver_entity: MockInfraredReceiverEntity, + lib_fan: FujitsuAcFanSpeed, + expected_fan_mode: str, +) -> None: + """Test a received cool signal updates mode, temperature, fan and swing.""" + mock_infrared_receiver_entity._handle_received_signal( + InfraredReceivedSignal( + timings=FujitsuAcCommand( + mode=FujitsuAcMode.COOL, + temperature=24, + fan=lib_fan, + swing=FujitsuAcSwing.BOTH, + ).get_raw_timings() + ) + ) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.state == HVACMode.COOL + assert state.attributes[ATTR_FAN_MODE] == expected_fan_mode + assert state.attributes[ATTR_TEMPERATURE] == 24.0 + assert state.attributes[ATTR_SWING_MODE] == SWING_BOTH + + +@pytest.mark.parametrize("protocol", [PROTOCOL_EXTENDED]) +@pytest.mark.parametrize("has_receiver", [True]) +@pytest.mark.usefixtures("init_integration") +async def test_receiver_converts_a_fahrenheit_signal( + hass: HomeAssistant, mock_infrared_receiver_entity: MockInfraredReceiverEntity +) -> None: + """Test a remote set to Fahrenheit updates the Celsius entity correctly. + + 75 F is what the remote displays. Converted it is 23.89 C, which is not a setpoint + this entity can send back, so it lands on the nearest half degree. + """ + mock_infrared_receiver_entity._handle_received_signal( + InfraredReceivedSignal( + timings=FujitsuAcCommand( + protocol=FujitsuAcProtocol.EXTENDED, + mode=FujitsuAcMode.COOL, + temperature=75, + is_fahrenheit=True, + ).get_raw_timings() + ) + ) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes[ATTR_TEMPERATURE] == 24.0 + + +@pytest.mark.parametrize("has_receiver", [True]) +@pytest.mark.usefixtures("init_integration") +async def test_receiver_updates_state_on_off_signal( + hass: HomeAssistant, mock_infrared_receiver_entity: MockInfraredReceiverEntity +) -> None: + """Test a received off signal sets mode to off, preserving the other state. + + The power-off message carries no state, so the last known values must survive it. + """ + mock_infrared_receiver_entity._handle_received_signal( + InfraredReceivedSignal( + timings=FujitsuAcCommand( + mode=FujitsuAcMode.COOL, + temperature=24, + fan=FujitsuAcFanSpeed.MEDIUM, + ).get_raw_timings() + ) + ) + await hass.async_block_till_done() + + mock_infrared_receiver_entity._handle_received_signal( + InfraredReceivedSignal( + timings=FujitsuACCode.POWER_OFF.to_command().get_raw_timings() + ) + ) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.state == HVACMode.OFF + assert state.attributes[ATTR_FAN_MODE] == FAN_MEDIUM + assert state.attributes[ATTR_TEMPERATURE] == 24.0 + + +@pytest.mark.parametrize("has_receiver", [True]) +@pytest.mark.usefixtures("init_integration") +async def test_receiver_ignores_unconfigured_hvac_mode( + hass: HomeAssistant, mock_infrared_receiver_entity: MockInfraredReceiverEntity +) -> None: + """Test a signal for a mode the user did not configure does not change state.""" + mock_infrared_receiver_entity._handle_received_signal( + InfraredReceivedSignal( + timings=FujitsuAcCommand( + mode=FujitsuAcMode.HEAT, + temperature=24, + fan=FujitsuAcFanSpeed.HIGH, + ).get_raw_timings() + ) + ) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.state == HVACMode.OFF + assert state.attributes[ATTR_FAN_MODE] == FAN_AUTO + + +@pytest.mark.parametrize("has_receiver", [True]) +@pytest.mark.usefixtures("init_integration") +async def test_receiver_ignores_another_protocol_family( + hass: HomeAssistant, mock_infrared_receiver_entity: MockInfraredReceiverEntity +) -> None: + """Test a frame from the other remote family does not change state. + + The entry is configured for the standard protocol, so an extended frame belongs to + a different unit and the configured one ignores it too. + """ + mock_infrared_receiver_entity._handle_received_signal( + InfraredReceivedSignal( + timings=FujitsuAcCommand( + protocol=FujitsuAcProtocol.EXTENDED, + mode=FujitsuAcMode.COOL, + temperature=29, + fan=FujitsuAcFanSpeed.HIGH, + ).get_raw_timings() + ) + ) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.state == HVACMode.OFF + assert state.attributes[ATTR_FAN_MODE] == FAN_AUTO + + +@pytest.mark.parametrize("has_receiver", [True]) +@pytest.mark.usefixtures("init_integration") +async def test_receiver_ignores_unrecognised_signal( + hass: HomeAssistant, mock_infrared_receiver_entity: MockInfraredReceiverEntity +) -> None: + """Test an unrecognised IR signal does not change state.""" + mock_infrared_receiver_entity._handle_received_signal( + InfraredReceivedSignal(timings=[500, -500, 300, -300]) + ) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.state == HVACMode.OFF + + +@pytest.mark.parametrize( + ("restored_state", "restored_attributes", "expected"), + [ + pytest.param( + HVACMode.COOL, + { + ATTR_FAN_MODE: FAN_HIGH, + ATTR_TEMPERATURE: 29.0, + ClimateEntityStateAttribute.TEMPERATURE_UNIT: UnitOfTemperature.CELSIUS, + ATTR_SWING_MODE: SWING_BOTH, + }, + (HVACMode.COOL, FAN_HIGH, 29.0, SWING_BOTH), + id="full_state", + ), + pytest.param( + STATE_UNAVAILABLE, + {}, + (HVACMode.OFF, FAN_AUTO, float(MIN_TEMP), SWING_OFF), + id="unavailable_falls_back_to_defaults", + ), + pytest.param( + HVACMode.HEAT, + {ATTR_FAN_MODE: FAN_HIGH, ATTR_TEMPERATURE: 29.0}, + (HVACMode.OFF, FAN_HIGH, 29.0, SWING_OFF), + id="mode_no_longer_configured_is_ignored", + ), + ], +) +async def test_state_restored_on_restart( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_infrared_emitter_entity: MockInfraredEmitterEntity, + platforms: list[Platform], + restored_state: str, + restored_attributes: dict[str, Any], + expected: tuple[HVACMode, str, float, str], +) -> None: + """Test the assumed state is restored, since infrared cannot read it back.""" + mock_restore_cache( + hass, [State(_CLIMATE_ENTITY_ID, restored_state, restored_attributes)] + ) + mock_config_entry.add_to_hass(hass) + + with patch("homeassistant.components.fujitsu_infrared.PLATFORMS", platforms): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + expected_mode, expected_fan, expected_temp, expected_swing = expected + assert state.state == expected_mode + assert state.attributes[ATTR_FAN_MODE] == expected_fan + assert state.attributes[ATTR_TEMPERATURE] == expected_temp + assert state.attributes[ATTR_SWING_MODE] == expected_swing + + +@pytest.mark.parametrize( + ("restored_attributes", "unit_system", "expected_temperature"), + [ + pytest.param( + { + ATTR_TEMPERATURE: 24, + ClimateEntityStateAttribute.TEMPERATURE_UNIT: UnitOfTemperature.CELSIUS, + }, + METRIC_SYSTEM, + 24, + id="celsius_to_celsius", + ), + pytest.param( + { + ATTR_TEMPERATURE: 24, + ClimateEntityStateAttribute.TEMPERATURE_UNIT: UnitOfTemperature.CELSIUS, + }, + US_CUSTOMARY_SYSTEM, + 75, + id="celsius_to_fahrenheit", + ), + pytest.param( + { + ATTR_TEMPERATURE: 75, + ClimateEntityStateAttribute.TEMPERATURE_UNIT: UnitOfTemperature.FAHRENHEIT, + }, + METRIC_SYSTEM, + 24, + id="fahrenheit_to_celsius", + ), + pytest.param( + { + ATTR_TEMPERATURE: 75, + ClimateEntityStateAttribute.TEMPERATURE_UNIT: UnitOfTemperature.FAHRENHEIT, + }, + US_CUSTOMARY_SYSTEM, + 75, + id="fahrenheit_to_fahrenheit", + ), + pytest.param({ATTR_TEMPERATURE: 24}, METRIC_SYSTEM, 24, id="legacy_celsius"), + pytest.param( + {ATTR_TEMPERATURE: 75}, US_CUSTOMARY_SYSTEM, 75, id="legacy_fahrenheit" + ), + ], +) +async def test_restore_temperature_unit( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_infrared_emitter_entity: MockInfraredEmitterEntity, + platforms: list[Platform], + restored_attributes: dict[str, Any], + unit_system: UnitSystem, + expected_temperature: int, +) -> None: + """Test restoration uses the saved unit, falling back to the configured unit.""" + hass.config.units = unit_system + mock_restore_cache( + hass, [State(_CLIMATE_ENTITY_ID, HVACMode.COOL, restored_attributes)] + ) + mock_config_entry.add_to_hass(hass) + + with patch("homeassistant.components.fujitsu_infrared.PLATFORMS", platforms): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(_CLIMATE_ENTITY_ID) + assert state is not None + assert state.attributes[ATTR_TEMPERATURE] == expected_temperature + + mock_infrared_emitter_entity.send_command_calls.clear() + await _set_hvac_mode(hass, HVACMode.COOL) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand(mode=FujitsuAcMode.COOL, temperature=24).get_raw_timings() + ) + + +@pytest.mark.usefixtures("init_integration") +async def test_restored_state_is_sent_with_the_next_command( + hass: HomeAssistant, mock_infrared_emitter_entity: MockInfraredEmitterEntity +) -> None: + """Test state set while the AC is off is carried by the message that starts it.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_TEMPERATURE: 27}, + blocking=True, + ) + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_FAN_MODE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_FAN_MODE: FAN_LOW}, + blocking=True, + ) + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_SWING_MODE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_SWING_MODE: SWING_BOTH}, + blocking=True, + ) + assert len(mock_infrared_emitter_entity.send_command_calls) == 0 + + await _set_hvac_mode(hass, HVACMode.COOL) + + assert ( + _sent_timings(mock_infrared_emitter_entity) + == FujitsuAcCommand( + power=True, + mode=FujitsuAcMode.COOL, + temperature=27, + fan=FujitsuAcFanSpeed.LOW, + swing=FujitsuAcSwing.BOTH, + ).get_raw_timings() + ) diff --git a/tests/components/fujitsu_infrared/test_config_flow.py b/tests/components/fujitsu_infrared/test_config_flow.py new file mode 100644 index 000000000000..4d7be589ad26 --- /dev/null +++ b/tests/components/fujitsu_infrared/test_config_flow.py @@ -0,0 +1,205 @@ +"""Tests for the Fujitsu Infrared config flow.""" + +import pytest + +from homeassistant.components.climate import HVACMode +from homeassistant.components.fujitsu_infrared.const import ( + CONF_HVAC_MODES, + CONF_INFRARED_EMITTER_ENTITY_ID, + CONF_INFRARED_RECEIVER_ENTITY_ID, + DOMAIN, + PROTOCOL_STANDARD, +) +from homeassistant.components.infrared import DATA_COMPONENT +from homeassistant.config_entries import SOURCE_USER +from homeassistant.const import CONF_PROTOCOL +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType, InvalidData +from homeassistant.helpers import entity_registry as er + +from tests.common import MockConfigEntry +from tests.components.infrared import ( + EMITTER_ENTITY_ID as mock_infrared_emitter_entity_id, + RECEIVER_ENTITY_ID as mock_infrared_receiver_entity_id, +) +from tests.components.infrared.common import MockInfraredEmitterEntity + + +@pytest.mark.usefixtures("mock_infrared_emitter_entity") +async def test_user_flow_success(hass: HomeAssistant) -> None: + """Test successful config flow with default modes (cool + dry).""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + CONF_INFRARED_EMITTER_ENTITY_ID: mock_infrared_emitter_entity_id, + CONF_HVAC_MODES: [HVACMode.COOL, HVACMode.DRY], + }, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "Fujitsu AC via Test IR emitter" + assert result["data"] == { + CONF_INFRARED_EMITTER_ENTITY_ID: mock_infrared_emitter_entity_id, + CONF_HVAC_MODES: [HVACMode.COOL, HVACMode.DRY], + CONF_PROTOCOL: PROTOCOL_STANDARD, + } + assert result["result"].unique_id is None + + +@pytest.mark.usefixtures( + "mock_infrared_emitter_entity", "mock_infrared_receiver_entity" +) +async def test_user_flow_with_heat_cool_and_receiver(hass: HomeAssistant) -> None: + """Test config flow with the heat/cool mode and the optional receiver.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + CONF_INFRARED_EMITTER_ENTITY_ID: mock_infrared_emitter_entity_id, + CONF_INFRARED_RECEIVER_ENTITY_ID: mock_infrared_receiver_entity_id, + CONF_HVAC_MODES: [HVACMode.COOL, HVACMode.HEAT, HVACMode.HEAT_COOL], + }, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"][CONF_HVAC_MODES] == [ + HVACMode.COOL, + HVACMode.HEAT, + HVACMode.HEAT_COOL, + ] + assert result["data"][CONF_INFRARED_RECEIVER_ENTITY_ID] == ( + mock_infrared_receiver_entity_id + ) + + +@pytest.mark.usefixtures("mock_infrared_emitter_entity") +async def test_user_flow_requires_hvac_mode(hass: HomeAssistant) -> None: + """Test the flow rejects an empty list of supported modes.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + with pytest.raises(InvalidData) as err: + await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + CONF_INFRARED_EMITTER_ENTITY_ID: mock_infrared_emitter_entity_id, + CONF_HVAC_MODES: [], + }, + ) + + assert err.value.schema_errors == {CONF_HVAC_MODES: "no_hvac_modes"} + + +@pytest.mark.usefixtures("mock_infrared_emitter_entity") +async def test_user_flow_already_configured( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test the flow aborts when the emitter is already configured.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + CONF_INFRARED_EMITTER_ENTITY_ID: mock_infrared_emitter_entity_id, + CONF_HVAC_MODES: [HVACMode.COOL, HVACMode.DRY], + }, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures( + "mock_infrared_emitter_entity", "mock_infrared_receiver_entity" +) +async def test_user_flow_receiver_already_configured( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test the flow aborts when the receiver is already configured.""" + mock_config_entry.add_to_hass(hass) + await hass.data[DATA_COMPONENT].async_add_entities( + [MockInfraredEmitterEntity("second_ir_emitter", "Second IR emitter")] + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + CONF_INFRARED_EMITTER_ENTITY_ID: "infrared.second_ir_emitter", + CONF_INFRARED_RECEIVER_ENTITY_ID: mock_infrared_receiver_entity_id, + CONF_HVAC_MODES: [HVACMode.COOL, HVACMode.DRY], + }, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures("init_infrared") +async def test_user_flow_no_emitters(hass: HomeAssistant) -> None: + """Test the flow aborts when no infrared emitters exist.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "no_infrared_emitters" + + +@pytest.mark.usefixtures("mock_infrared_receiver_entity") +async def test_user_flow_no_emitters_receiver_only(hass: HomeAssistant) -> None: + """Test the flow aborts with only a receiver, since the AC needs an emitter.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "no_infrared_emitters" + + +@pytest.mark.usefixtures("mock_infrared_emitter_entity") +@pytest.mark.parametrize( + ("entity_name", "expected_title"), + [ + pytest.param(None, "Fujitsu AC via Test IR emitter", id="original_name"), + pytest.param("AC IR emitter", "Fujitsu AC via AC IR emitter", id="custom_name"), + ], +) +async def test_user_flow_title_from_entity_name( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + entity_name: str | None, + expected_title: str, +) -> None: + """Test config entry title uses the entity name.""" + entity_registry.async_update_entity( + mock_infrared_emitter_entity_id, name=entity_name + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + CONF_INFRARED_EMITTER_ENTITY_ID: mock_infrared_emitter_entity_id, + CONF_HVAC_MODES: [HVACMode.COOL, HVACMode.DRY], + }, + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == expected_title diff --git a/tests/components/fujitsu_infrared/test_init.py b/tests/components/fujitsu_infrared/test_init.py new file mode 100644 index 000000000000..6ad0173952a3 --- /dev/null +++ b/tests/components/fujitsu_infrared/test_init.py @@ -0,0 +1,21 @@ +"""Tests for the Fujitsu Infrared integration setup.""" + +import pytest + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry + + +@pytest.mark.usefixtures("init_integration") +async def test_load_and_unload_entry( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test the config entry loads and unloads cleanly.""" + assert mock_config_entry.state is ConfigEntryState.LOADED + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED