From 3bec44d0470b044bb41febd5c7f4046f02bd2fb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ab=C3=ADlio=20Costa?= Date: Fri, 23 Oct 2026 09:44:38 +0100 Subject: [PATCH] Add receiver support to Radio Frequency (#186720) --- .../components/radio_frequency/__init__.py | 68 +++- .../components/radio_frequency/const.py | 8 +- .../components/radio_frequency/entity.py | 136 +++++++- .../components/radio_frequency/helpers.py | 201 +++++++++-- .../components/radio_frequency/icons.json | 3 + .../components/radio_frequency/strings.json | 11 +- .../radio_frequency/websocket_api.py | 46 +-- homeassistant/generated/device_classes.json | 4 + .../checkers/class_module.py | 2 + .../components/radio_frequency/__init__.py | 1 + .../components/radio_frequency/common.py | 42 ++- .../pytest_homeassistant/plugins.py | 17 +- script/hassfest/device_classes.py | 2 + .../snapshots/test_diagnostics.ambr | 1 + .../radio_frequency/test_helpers.py | 116 +++++++ tests/components/radio_frequency/test_init.py | 315 +++++++++++++++++- .../radio_frequency/test_websocket_api.py | 32 +- 17 files changed, 917 insertions(+), 88 deletions(-) create mode 100644 tests/components/radio_frequency/test_helpers.py diff --git a/homeassistant/components/radio_frequency/__init__.py b/homeassistant/components/radio_frequency/__init__.py index 1a390b766d08..164194d77a99 100644 --- a/homeassistant/components/radio_frequency/__init__.py +++ b/homeassistant/components/radio_frequency/__init__.py @@ -15,21 +15,37 @@ from homeassistant.helpers.typing import ConfigType from . import websocket_api from .const import DATA_COMPONENT, DOMAIN from .entity import ( + RadioFrequencyDeviceClass, + RadioFrequencyReceivedSignal, + RadioFrequencyReceiverEntity, + RadioFrequencyReceiverEntityDescription, RadioFrequencyTransmitterEntity, RadioFrequencyTransmitterEntityDescription, ) -from .helpers import RadioFrequencyTransmitterConsumerEntity, async_send_command +from .helpers import ( + RadioFrequencyReceiverConsumerEntity, + RadioFrequencyTransmitterConsumerEntity, + async_send_command, + async_subscribe_receiver, +) __all__ = [ "DATA_COMPONENT", "DOMAIN", "ModulationType", "RadioFrequencyCommand", + "RadioFrequencyDeviceClass", + "RadioFrequencyReceivedSignal", + "RadioFrequencyReceiverConsumerEntity", + "RadioFrequencyReceiverEntity", + "RadioFrequencyReceiverEntityDescription", "RadioFrequencyTransmitterConsumerEntity", "RadioFrequencyTransmitterEntity", "RadioFrequencyTransmitterEntityDescription", + "async_get_receivers", "async_get_transmitters", "async_send_command", + "async_subscribe_receiver", ] _LOGGER = logging.getLogger(__name__) @@ -43,7 +59,7 @@ SCAN_INTERVAL = timedelta(seconds=30) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the radio_frequency domain.""" component = hass.data[DATA_COMPONENT] = EntityComponent[ - RadioFrequencyTransmitterEntity + RadioFrequencyTransmitterEntity | RadioFrequencyReceiverEntity ](_LOGGER, DOMAIN, hass, SCAN_INTERVAL) await component.async_setup(config) @@ -90,7 +106,11 @@ def async_get_transmitters( translation_key="component_not_loaded", ) - entities = list(component.entities) + entities = [ + entity + for entity in component.entities + if isinstance(entity, RadioFrequencyTransmitterEntity) + ] if not entities: raise HomeAssistantError( translation_domain=DOMAIN, @@ -103,3 +123,45 @@ def async_get_transmitters( if entity.supports_modulation(modulation) and entity.supports_frequency(frequency) ] + + +@callback +def async_get_receivers( + hass: HomeAssistant, + frequency: int, + modulation: ModulationType, +) -> list[str]: + """Get entity IDs of all RF receivers supporting the given frequency. + + Receivers are filtered by both their supported frequency ranges and + their supported modulation types. An empty list means no compatible + receivers. + + Raises: + HomeAssistantError: If the component is not loaded or if no + receivers exist. + """ + component = hass.data.get(DATA_COMPONENT) + if component is None: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="component_not_loaded", + ) + + entities = [ + entity + for entity in component.entities + if isinstance(entity, RadioFrequencyReceiverEntity) + ] + if not entities: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="no_receivers", + ) + + return [ + entity.entity_id + for entity in entities + if entity.supports_modulation(modulation) + and entity.supports_frequency(frequency) + ] diff --git a/homeassistant/components/radio_frequency/const.py b/homeassistant/components/radio_frequency/const.py index 059613787b76..3e5c7fc4ecb3 100644 --- a/homeassistant/components/radio_frequency/const.py +++ b/homeassistant/components/radio_frequency/const.py @@ -5,10 +5,10 @@ from typing import Final from homeassistant.helpers.entity_component import EntityComponent from homeassistant.util.hass_dict import HassKey -from .entity import RadioFrequencyTransmitterEntity +from .entity import RadioFrequencyReceiverEntity, RadioFrequencyTransmitterEntity DOMAIN: Final = "radio_frequency" -DATA_COMPONENT: HassKey[EntityComponent[RadioFrequencyTransmitterEntity]] = HassKey( - DOMAIN -) +DATA_COMPONENT: HassKey[ + EntityComponent[RadioFrequencyTransmitterEntity | RadioFrequencyReceiverEntity] +] = HassKey(DOMAIN) diff --git a/homeassistant/components/radio_frequency/entity.py b/homeassistant/components/radio_frequency/entity.py index 4d55c1e02cd3..e7aa60c3ace2 100644 --- a/homeassistant/components/radio_frequency/entity.py +++ b/homeassistant/components/radio_frequency/entity.py @@ -1,31 +1,51 @@ """Base entity for the radio frequency integration.""" from abc import abstractmethod +from collections.abc import Callable +from dataclasses import dataclass +from enum import StrEnum +import logging from typing import final, override +from propcache.api import cached_property from rf_protocols import ModulationType, RadioFrequencyCommand -from homeassistant.const import STATE_UNAVAILABLE -from homeassistant.core import callback +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import CALLBACK_TYPE, callback from homeassistant.helpers.entity import EntityDescription from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.util import dt as dt_util - -class RadioFrequencyTransmitterEntityDescription( - EntityDescription, frozen_or_thawed=True -): - """Describes radio frequency transmitter entities.""" +_LOGGER = logging.getLogger(__name__) -class RadioFrequencyTransmitterEntity(RestoreEntity): - """Base class for radio frequency transmitter entities.""" +class RadioFrequencyDeviceClass(StrEnum): + """Device class for radio frequency entities.""" - entity_description: RadioFrequencyTransmitterEntityDescription + TRANSMITTER = "transmitter" + RECEIVER = "receiver" + + +@dataclass(frozen=True, slots=True) +class RadioFrequencyReceivedSignal: + """Represents a received RF signal.""" + + timings: list[int] + frequency: int | None = None + modulation: ModulationType = ModulationType.OOK + + +class _RadioFrequencyEntity(RestoreEntity): + """Common base for radio frequency transmitter and receiver entities.""" + + _attr_device_class: RadioFrequencyDeviceClass _attr_should_poll = False _attr_state: None = None - __last_command_sent: str | None = None + @override + def _default_to_device_class_name(self) -> bool: + """Return True if an unnamed entity should be named by its device class.""" + return self.device_class is not None @property @abstractmethod @@ -35,7 +55,7 @@ class RadioFrequencyTransmitterEntity(RestoreEntity): @callback @final def supports_frequency(self, frequency: int) -> bool: - """Return whether the transmitter supports the given frequency.""" + """Return whether the entity supports the given frequency.""" return any( low <= frequency <= high for low, high in self.supported_frequency_ranges ) @@ -43,9 +63,24 @@ class RadioFrequencyTransmitterEntity(RestoreEntity): @callback @final def supports_modulation(self, modulation: ModulationType) -> bool: - """Return whether the transmitter supports the given modulation.""" + """Return whether the entity supports the given modulation.""" return modulation == ModulationType.OOK + +class RadioFrequencyTransmitterEntityDescription( + EntityDescription, frozen_or_thawed=True +): + """Describes radio frequency transmitter entities.""" + + +class RadioFrequencyTransmitterEntity(_RadioFrequencyEntity): + """Base class for radio frequency transmitter entities.""" + + entity_description: RadioFrequencyTransmitterEntityDescription + _attr_device_class = RadioFrequencyDeviceClass.TRANSMITTER + + __last_command_sent: str | None = None + @property @final @override @@ -82,3 +117,78 @@ class RadioFrequencyTransmitterEntity(RestoreEntity): Raises: HomeAssistantError: If transmission fails. """ + + +class RadioFrequencyReceiverEntityDescription(EntityDescription, frozen_or_thawed=True): + """Describes radio frequency receiver entities.""" + + +class RadioFrequencyReceiverEntity(_RadioFrequencyEntity): + """Base class for radio frequency receiver entities.""" + + entity_description: RadioFrequencyReceiverEntityDescription + _attr_device_class = RadioFrequencyDeviceClass.RECEIVER + + __last_signal_received: str | None = None + + @cached_property + def __signal_callbacks( + self, + ) -> set[Callable[[RadioFrequencyReceivedSignal], None]]: + """Subscriber callback set, lazily initialized on first access.""" + return set() + + @property + @final + @override + def state(self) -> str | None: + """Return the entity state.""" + return self.__last_signal_received + + @final + @override + async def async_internal_added_to_hass(self) -> None: + """Call when the radio frequency entity is added to hass.""" + await super().async_internal_added_to_hass() + state = await self.async_get_last_state() + if state is not None and state.state not in ( + STATE_UNAVAILABLE, + STATE_UNKNOWN, + None, + ): + self.__last_signal_received = state.state + + @final + def _handle_received_signal(self, signal: RadioFrequencyReceivedSignal) -> None: + """Handle a received RF signal. + + Should not be overridden. To be called by platform implementations when a + signal is received. + """ + self.__last_signal_received = dt_util.utcnow().isoformat( + timespec="milliseconds" + ) + self.async_write_ha_state() + for signal_callback in tuple(self.__signal_callbacks): + try: + signal_callback(signal) + except Exception: + _LOGGER.exception("Error in signal callback for %s", self.entity_id) + + @callback + def async_subscribe_received_signal( + self, + signal_callback: Callable[[RadioFrequencyReceivedSignal], None], + ) -> CALLBACK_TYPE: + """Subscribe to received RF signals. + + Returns a callable to unsubscribe. + """ + callbacks = self.__signal_callbacks + callbacks.add(signal_callback) + + @callback + def remove_callback() -> None: + callbacks.discard(signal_callback) + + return remove_callback diff --git a/homeassistant/components/radio_frequency/helpers.py b/homeassistant/components/radio_frequency/helpers.py index 6511ede8fc57..2a3be6fea7d9 100644 --- a/homeassistant/components/radio_frequency/helpers.py +++ b/homeassistant/components/radio_frequency/helpers.py @@ -1,12 +1,16 @@ -"""Helper base entities for integrations that consume RF transmitters.""" +"""Helper base entities for integrations that consume RF transmitters/receivers.""" +from abc import abstractmethod +from collections.abc import Callable import logging from typing import override +import probatio from rf_protocols import RadioFrequencyCommand from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import ( + CALLBACK_TYPE, Context, Event, EventStateChangedData, @@ -19,6 +23,11 @@ from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_state_change_event from .const import DATA_COMPONENT, DOMAIN +from .entity import ( + RadioFrequencyReceivedSignal, + RadioFrequencyReceiverEntity, + RadioFrequencyTransmitterEntity, +) _LOGGER = logging.getLogger(__name__) @@ -47,7 +56,7 @@ async def async_send_command( ent_reg = er.async_get(hass) entity_id = er.async_validate_entity_id(ent_reg, entity_id_or_uuid) entity = component.get_entity(entity_id) - if entity is None: + if entity is None or not isinstance(entity, RadioFrequencyTransmitterEntity): raise HomeAssistantError( translation_domain=DOMAIN, translation_key="entity_not_found", @@ -80,8 +89,113 @@ async def async_send_command( await entity.async_send_command_internal(command) +@callback +def async_subscribe_receiver( + hass: HomeAssistant, + entity_id_or_uuid: str, + signal_callback: Callable[[RadioFrequencyReceivedSignal], None], +) -> CALLBACK_TYPE: + """Subscribe to RF signals from a specific receiver entity. + + Raises: + HomeAssistantError: If the receiver entity is not found. + """ + component = hass.data.get(DATA_COMPONENT) + if component is None: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="component_not_loaded", + ) + + ent_reg = er.async_get(hass) + try: + entity_id = er.async_validate_entity_id(ent_reg, entity_id_or_uuid) + except probatio.Invalid as err: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="receiver_not_found", + translation_placeholders={"entity_id": entity_id_or_uuid}, + ) from err + + entity = component.get_entity(entity_id) + if entity is None or not isinstance(entity, RadioFrequencyReceiverEntity): + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="receiver_not_found", + translation_placeholders={"entity_id": entity_id}, + ) + + return entity.async_subscribe_received_signal(signal_callback) + + # pylint: disable-next=home-assistant-enforce-class-module -class RadioFrequencyTransmitterConsumerEntity(Entity): +class RadioFrequencyConsumerEntity(Entity): + """Base class for entities that track the availability of RF entities. + + The entity is available only while all tracked RF entities are available. + """ + + _rf_availability: dict[str, bool] + + @override + async def async_added_to_hass(self) -> None: + """Initialize RF availability tracking.""" + await super().async_added_to_hass() + self._rf_availability = {} + + @callback + def _async_track_availability(self, rf_entity_id: str) -> CALLBACK_TYPE: + """Track the availability of an RF entity. + + Sets initial availability and subscribes to state changes. + Returns an unsubscribe callback. + """ + + @callback + def state_changed(event: Event[EventStateChangedData]) -> None: + new_state = event.data["new_state"] + rf_available = ( + new_state is not None and new_state.state != STATE_UNAVAILABLE + ) + if rf_available == self._rf_availability[rf_entity_id]: + return + _LOGGER.info( + "Radio frequency entity %s used by %s is %s", + rf_entity_id, + self.entity_id, + "available" if rf_available else "unavailable", + ) + self._rf_availability[rf_entity_id] = rf_available + available = all(self._rf_availability.values()) + if available != self.available: + self._async_rf_availability_changed(available) + + @callback + def unsubscribe() -> None: + remove_listener() + self._rf_availability.pop(rf_entity_id, None) + + rf_state = self.hass.states.get(rf_entity_id) + self._rf_availability[rf_entity_id] = ( + rf_state is not None and rf_state.state != STATE_UNAVAILABLE + ) + available = all(self._rf_availability.values()) + if available != self.available: + self._async_rf_availability_changed(available) + + remove_listener = async_track_state_change_event( + self.hass, [rf_entity_id], state_changed + ) + return unsubscribe + + @callback + def _async_rf_availability_changed(self, available: bool) -> None: + """Update availability. Override to react to changes.""" + self._attr_available = available + self.async_write_ha_state() + + +class RadioFrequencyTransmitterConsumerEntity(RadioFrequencyConsumerEntity): """Base entity for integrations that send commands via an RF transmitter. Tracks the availability of the underlying RF transmitter entity. @@ -94,17 +208,8 @@ class RadioFrequencyTransmitterConsumerEntity(Entity): async def async_added_to_hass(self) -> None: """Subscribe to RF entity state changes.""" await super().async_added_to_hass() - self.async_on_remove( - async_track_state_change_event( - self.hass, - [self._rf_transmitter_entity_id], - self._async_rf_state_changed, - ) - ) - rf_state = self.hass.states.get(self._rf_transmitter_entity_id) - self._attr_available = ( - rf_state is not None and rf_state.state != STATE_UNAVAILABLE + self._async_track_availability(self._rf_transmitter_entity_id) ) async def _send_command(self, command: RadioFrequencyCommand) -> None: @@ -116,18 +221,60 @@ class RadioFrequencyTransmitterConsumerEntity(Entity): context=self._context, ) - @callback - def _async_rf_state_changed(self, event: Event[EventStateChangedData]) -> None: - """Handle RF entity state changes.""" - new_state = event.data["new_state"] - rf_available = new_state is not None and new_state.state != STATE_UNAVAILABLE - if rf_available != self.available: - _LOGGER.info( - "Radio frequency entity %s used by %s is %s", - event.data["entity_id"], - self.entity_id, - "available" if rf_available else "unavailable", - ) - self._attr_available = rf_available - self.async_write_ha_state() +class RadioFrequencyReceiverConsumerEntity(RadioFrequencyConsumerEntity): + """Base entity for integrations that consume signals from an RF receiver. + + Tracks the availability of the underlying RF receiver entity and + manages the subscription to received RF signals. + """ + + _attr_should_poll = False + _rf_receiver_entity_id: str + _remove_signal_subscription: CALLBACK_TYPE | None = None + + @override + async def async_added_to_hass(self) -> None: + """Subscribe to RF entity state changes and receiver signals.""" + await super().async_added_to_hass() + self.async_on_remove( + self._async_track_availability(self._rf_receiver_entity_id) + ) + + self._async_update_receiver_subscription() + self.async_on_remove(self._async_unsubscribe_receiver) + + @override + @callback + def _async_rf_availability_changed(self, available: bool) -> None: + """Update availability and manage receiver subscription.""" + super()._async_rf_availability_changed(available) + self._async_update_receiver_subscription() + + @callback + @abstractmethod + def _handle_signal(self, signal: RadioFrequencyReceivedSignal) -> None: + """Handle a received RF signal.""" + + @callback + def _async_unsubscribe_receiver(self) -> None: + """Unsubscribe from the current RF receiver.""" + if self._remove_signal_subscription is None: + return + self._remove_signal_subscription() + self._remove_signal_subscription = None + + @callback + def _async_update_receiver_subscription(self) -> None: + """Update the RF receiver subscription when availability changes.""" + if not self.available: + self._async_unsubscribe_receiver() + elif self._remove_signal_subscription is None: + _LOGGER.debug( + "Subscribing to radio frequency receiver entity %s for %s", + self._rf_receiver_entity_id, + self.entity_id, + ) + self._remove_signal_subscription = async_subscribe_receiver( + self.hass, self._rf_receiver_entity_id, self._handle_signal + ) diff --git a/homeassistant/components/radio_frequency/icons.json b/homeassistant/components/radio_frequency/icons.json index c7587d1f7707..57440ff92c12 100644 --- a/homeassistant/components/radio_frequency/icons.json +++ b/homeassistant/components/radio_frequency/icons.json @@ -2,6 +2,9 @@ "entity_component": { "_": { "default": "mdi:radio-tower" + }, + "receiver": { + "default": "mdi:antenna" } } } diff --git a/homeassistant/components/radio_frequency/strings.json b/homeassistant/components/radio_frequency/strings.json index 84f924dee1a3..bbfe0bcab153 100644 --- a/homeassistant/components/radio_frequency/strings.json +++ b/homeassistant/components/radio_frequency/strings.json @@ -1,6 +1,9 @@ { "entity_component": { - "_": { + "receiver": { + "name": "Radio frequency receiver" + }, + "transmitter": { "name": "Radio frequency transmitter" } }, @@ -11,9 +14,15 @@ "entity_not_found": { "message": "Radio Frequency entity `{entity_id}` not found" }, + "no_receivers": { + "message": "No Radio Frequency receivers available" + }, "no_transmitters": { "message": "No Radio Frequency transmitters available" }, + "receiver_not_found": { + "message": "Radio Frequency receiver entity `{entity_id}` not found" + }, "unsupported_frequency": { "message": "Radio Frequency entity `{entity_id}` does not support frequency {frequency} Hz" }, diff --git a/homeassistant/components/radio_frequency/websocket_api.py b/homeassistant/components/radio_frequency/websocket_api.py index f24d4554cdc6..da7b57292692 100644 --- a/homeassistant/components/radio_frequency/websocket_api.py +++ b/homeassistant/components/radio_frequency/websocket_api.py @@ -10,25 +10,26 @@ from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import entity_registry as er from .const import DATA_COMPONENT +from .entity import RadioFrequencyTransmitterEntity @callback def async_setup(hass: HomeAssistant) -> None: """Set up the radio frequency websocket API.""" - websocket_api.async_register_command(hass, ws_list_transmitters) + websocket_api.async_register_command(hass, ws_list_entities) @websocket_api.require_admin @websocket_api.websocket_command({probatio.Required("type"): "radio_frequency/list"}) @callback -def ws_list_transmitters( +def ws_list_entities( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: - """Return the available radio frequency transmitters. + """Return the available radio frequency transmitters and receivers. - Each transmitter is described by its entity id, the device and config + Each entity is described by its entity id, the device and config entry it belongs to (when registered), the frequency ranges it can operate on and the modulation types it supports. """ @@ -36,22 +37,27 @@ def ws_list_transmitters( ent_reg = er.async_get(hass) transmitters: list[dict[str, Any]] = [] + receivers: list[dict[str, Any]] = [] for entity in component.entities: entry = ent_reg.async_get(entity.entity_id) - transmitters.append( - { - "entity_id": entity.entity_id, - "device_id": entry.device_id if entry else None, - "config_entry_id": entry.config_entry_id if entry else None, - "supported_frequency_ranges": [ - [low, high] for low, high in entity.supported_frequency_ranges - ], - "supported_modulations": [ - modulation.value - for modulation in ModulationType - if entity.supports_modulation(modulation) - ], - } - ) + entity_info = { + "entity_id": entity.entity_id, + "device_id": entry.device_id if entry else None, + "config_entry_id": entry.config_entry_id if entry else None, + "supported_frequency_ranges": [ + [low, high] for low, high in entity.supported_frequency_ranges + ], + "supported_modulations": [ + modulation.value + for modulation in ModulationType + if entity.supports_modulation(modulation) + ], + } + if isinstance(entity, RadioFrequencyTransmitterEntity): + transmitters.append(entity_info) + else: + receivers.append(entity_info) - connection.send_result(msg["id"], {"transmitters": transmitters}) + connection.send_result( + msg["id"], {"transmitters": transmitters, "receivers": receivers} + ) diff --git a/homeassistant/generated/device_classes.json b/homeassistant/generated/device_classes.json index c2c19177da35..29723251355c 100644 --- a/homeassistant/generated/device_classes.json +++ b/homeassistant/generated/device_classes.json @@ -126,6 +126,10 @@ "wind_direction", "wind_speed" ], + "radio_frequency": [ + "receiver", + "transmitter" + ], "sensor": [ "absolute_humidity", "apparent_power", diff --git a/packages/pylint-home-assistant/pylint_home_assistant/checkers/class_module.py b/packages/pylint-home-assistant/pylint_home_assistant/checkers/class_module.py index f1ee9c1ba6bc..aac4c6901ce8 100644 --- a/packages/pylint-home-assistant/pylint_home_assistant/checkers/class_module.py +++ b/packages/pylint-home-assistant/pylint_home_assistant/checkers/class_module.py @@ -68,6 +68,8 @@ _MODULES: dict[str, set[str]] = { Platform.NOTIFY: {"NotifyEntity", "NotifyEntityDescription"}, Platform.NUMBER: {"NumberEntity", "NumberEntityDescription", "RestoreNumber"}, Platform.RADIO_FREQUENCY: { + "RadioFrequencyReceiverEntity", + "RadioFrequencyReceiverEntityDescription", "RadioFrequencyTransmitterEntity", "RadioFrequencyTransmitterEntityDescription", }, diff --git a/packages/pytest-home-assistant/pytest_homeassistant/components/radio_frequency/__init__.py b/packages/pytest-home-assistant/pytest_homeassistant/components/radio_frequency/__init__.py index 4900ebd01c72..836fb1328d76 100644 --- a/packages/pytest-home-assistant/pytest_homeassistant/components/radio_frequency/__init__.py +++ b/packages/pytest-home-assistant/pytest_homeassistant/components/radio_frequency/__init__.py @@ -1,3 +1,4 @@ """Radio frequency helpers.""" ENTITY_ID = "radio_frequency.test_rf_transmitter" +RECEIVER_ENTITY_ID = "radio_frequency.test_rf_receiver" diff --git a/packages/pytest-home-assistant/pytest_homeassistant/components/radio_frequency/common.py b/packages/pytest-home-assistant/pytest_homeassistant/components/radio_frequency/common.py index 407a6b24b178..59806279ecd5 100644 --- a/packages/pytest-home-assistant/pytest_homeassistant/components/radio_frequency/common.py +++ b/packages/pytest-home-assistant/pytest_homeassistant/components/radio_frequency/common.py @@ -6,6 +6,7 @@ from rf_protocols import ModulationType, RadioFrequencyCommand from homeassistant.components.radio_frequency import ( DATA_COMPONENT, + RadioFrequencyReceiverEntity, RadioFrequencyTransmitterEntity, ) from homeassistant.components.radio_frequency.const import DOMAIN @@ -45,15 +46,17 @@ class MockRadioFrequencyEntity(RadioFrequencyTransmitterEntity): """Mock radio frequency entity for testing.""" _attr_has_entity_name = True - _attr_name = "Test RF transmitter" def __init__( self, unique_id: str, frequency_ranges: list[tuple[int, int]] | None = None, + name: str | None = "Test RF transmitter", ) -> None: """Initialize mock entity.""" self._attr_unique_id = unique_id + if name is not None: + self._attr_name = name self._frequency_ranges = ( [(433_000_000, 434_000_000)] if frequency_ranges is None @@ -73,6 +76,33 @@ class MockRadioFrequencyEntity(RadioFrequencyTransmitterEntity): ) +class MockRadioFrequencyReceiverEntity(RadioFrequencyReceiverEntity): + """Mock radio frequency receiver entity for testing.""" + + _attr_has_entity_name = True + + def __init__( + self, + unique_id: str, + frequency_ranges: list[tuple[int, int]] | None = None, + name: str | None = "Test RF receiver", + ) -> None: + """Initialize mock receiver entity.""" + self._attr_unique_id = unique_id + if name is not None: + self._attr_name = name + self._frequency_ranges = ( + [(433_000_000, 434_000_000)] + if frequency_ranges is None + else frequency_ranges + ) + + @property + def supported_frequency_ranges(self) -> list[tuple[int, int]]: + """Return supported frequency ranges.""" + return self._frequency_ranges + + async def init_radio_frequency_fixture_helper(hass: HomeAssistant) -> None: """Set up the Radio Frequency integration for testing.""" assert await async_setup_component(hass, DOMAIN, {}) @@ -87,3 +117,13 @@ async def mock_rf_entity_fixture_helper( component = hass.data[DATA_COMPONENT] await component.async_add_entities([entity]) return entity + + +async def mock_rf_receiver_entity_fixture_helper( + hass: HomeAssistant, +) -> MockRadioFrequencyReceiverEntity: + """Add a mock radio frequency receiver entity to the running integration.""" + entity = MockRadioFrequencyReceiverEntity("test_rf_receiver") + component = hass.data[DATA_COMPONENT] + await component.async_add_entities([entity]) + return entity diff --git a/packages/pytest-home-assistant/pytest_homeassistant/plugins.py b/packages/pytest-home-assistant/pytest_homeassistant/plugins.py index 7c82d02e1078..48f9917300c4 100644 --- a/packages/pytest-home-assistant/pytest_homeassistant/plugins.py +++ b/packages/pytest-home-assistant/pytest_homeassistant/plugins.py @@ -134,7 +134,10 @@ if TYPE_CHECKING: MockInfraredEmitterEntity, MockInfraredReceiverEntity, ) - from .components.radio_frequency.common import MockRadioFrequencyEntity + from .components.radio_frequency.common import ( + MockRadioFrequencyEntity, + MockRadioFrequencyReceiverEntity, + ) pytest.register_assert_rewrite("pytest_homeassistant.common") @@ -2104,6 +2107,18 @@ async def mock_rf_entity_fixture( return await mock_rf_entity_fixture_helper(hass) +@pytest.fixture(name="mock_rf_receiver_entity") +async def mock_rf_receiver_entity_fixture( + hass: HomeAssistant, init_radio_frequency: None +) -> MockRadioFrequencyReceiverEntity: + """Return a mock radio frequency receiver entity.""" + from .components.radio_frequency.common import ( # noqa: PLC0415 + mock_rf_receiver_entity_fixture_helper, + ) + + return await mock_rf_receiver_entity_fixture_helper(hass) + + # Infrared test fixtures @pytest.fixture(name="init_infrared") async def init_infrared_fixture(hass: HomeAssistant) -> None: diff --git a/script/hassfest/device_classes.py b/script/hassfest/device_classes.py index 0a3032292422..ba29ef711ef0 100644 --- a/script/hassfest/device_classes.py +++ b/script/hassfest/device_classes.py @@ -10,6 +10,7 @@ from homeassistant.components.humidifier import HumidifierDeviceClass from homeassistant.components.infrared import InfraredDeviceClass from homeassistant.components.media_player import MediaPlayerDeviceClass from homeassistant.components.number import NumberDeviceClass +from homeassistant.components.radio_frequency import RadioFrequencyDeviceClass from homeassistant.components.sensor import SensorDeviceClass from homeassistant.components.switch import SwitchDeviceClass from homeassistant.components.update import UpdateDeviceClass @@ -35,6 +36,7 @@ def _generate() -> str: Platform.INFRARED: InfraredDeviceClass, Platform.MEDIA_PLAYER: MediaPlayerDeviceClass, Platform.NUMBER: NumberDeviceClass, + Platform.RADIO_FREQUENCY: RadioFrequencyDeviceClass, Platform.SENSOR: SensorDeviceClass, Platform.SWITCH: SwitchDeviceClass, Platform.UPDATE: UpdateDeviceClass, diff --git a/tests/components/novy_cooker_hood/snapshots/test_diagnostics.ambr b/tests/components/novy_cooker_hood/snapshots/test_diagnostics.ambr index 78211d98e797..e335529726f4 100644 --- a/tests/components/novy_cooker_hood/snapshots/test_diagnostics.ambr +++ b/tests/components/novy_cooker_hood/snapshots/test_diagnostics.ambr @@ -99,6 +99,7 @@ 'entity_id': 'radio_frequency.test_rf_transmitter', 'state': dict({ 'attributes': dict({ + 'device_class': 'transmitter', 'friendly_name': 'Test RF transmitter', }), 'entity_id': 'radio_frequency.test_rf_transmitter', diff --git a/tests/components/radio_frequency/test_helpers.py b/tests/components/radio_frequency/test_helpers.py new file mode 100644 index 000000000000..e8ad419b4f75 --- /dev/null +++ b/tests/components/radio_frequency/test_helpers.py @@ -0,0 +1,116 @@ +"""Tests for the Radio Frequency consumer entity helpers.""" + +from typing import override + +import pytest +from pytest_homeassistant.common import MockEntityPlatform +from pytest_homeassistant.components.common import ( + assert_availability_follows_source_entity, +) +from pytest_homeassistant.components.radio_frequency import ( + ENTITY_ID, + RECEIVER_ENTITY_ID, +) +from pytest_homeassistant.components.radio_frequency.common import ( + MockRadioFrequencyCommand, + MockRadioFrequencyEntity, + MockRadioFrequencyReceiverEntity, +) + +from homeassistant.components.radio_frequency import ( + RadioFrequencyReceivedSignal, + RadioFrequencyReceiverConsumerEntity, + RadioFrequencyTransmitterConsumerEntity, +) +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import HomeAssistant, callback + +CONSUMER_ENTITY_ID = "test_domain.consumer" + +TEST_SIGNAL = RadioFrequencyReceivedSignal( + timings=[350, -1050, 350, -350], frequency=433_920_000 +) + + +class MockConsumerEntity( + RadioFrequencyTransmitterConsumerEntity, RadioFrequencyReceiverConsumerEntity +): + """Mock entity consuming an RF transmitter and an RF receiver.""" + + _attr_name = "Consumer" + + def __init__(self, transmitter: str, receiver: str) -> None: + """Initialize the mock consumer entity.""" + self._rf_transmitter_entity_id = transmitter + self._rf_receiver_entity_id = receiver + self.received_signals: list[RadioFrequencyReceivedSignal] = [] + + @callback + @override + def _handle_signal(self, signal: RadioFrequencyReceivedSignal) -> None: + """Store the received signal.""" + self.received_signals.append(signal) + + +@pytest.fixture +async def mock_consumer_entity( + hass: HomeAssistant, + mock_rf_entity: MockRadioFrequencyEntity, + mock_rf_receiver_entity: MockRadioFrequencyReceiverEntity, +) -> MockConsumerEntity: + """Add a consumer entity referencing the RF entities.""" + entity = MockConsumerEntity(ENTITY_ID, RECEIVER_ENTITY_ID) + await MockEntityPlatform(hass).async_add_entities([entity]) + await hass.async_block_till_done() + return entity + + +@pytest.mark.usefixtures("mock_consumer_entity") +async def test_availability_follows_rf_entities(hass: HomeAssistant) -> None: + """Test the consumer is available only while all RF entities are available.""" + await assert_availability_follows_source_entity( + hass, CONSUMER_ENTITY_ID, [ENTITY_ID, RECEIVER_ENTITY_ID] + ) + + +async def test_send_command( + mock_rf_entity: MockRadioFrequencyEntity, + mock_consumer_entity: MockConsumerEntity, +) -> None: + """Test the consumer sends commands through the transmitter.""" + command = MockRadioFrequencyCommand() + await mock_consumer_entity._send_command(command) + + assert len(mock_rf_entity.send_command_calls) == 1 + assert mock_rf_entity.send_command_calls[0].command is command + + +async def test_receiver_resubscribes_after_receiver_unavailable( + hass: HomeAssistant, + mock_rf_receiver_entity: MockRadioFrequencyReceiverEntity, + mock_consumer_entity: MockConsumerEntity, +) -> None: + """Test the consumer resubscribes when the receiver becomes available again.""" + hass.states.async_set(RECEIVER_ENTITY_ID, STATE_UNAVAILABLE) + await hass.async_block_till_done() + assert (state := hass.states.get(CONSUMER_ENTITY_ID)) is not None + assert state.state == STATE_UNAVAILABLE + + hass.states.async_set(RECEIVER_ENTITY_ID, STATE_UNKNOWN) + await hass.async_block_till_done() + assert (state := hass.states.get(CONSUMER_ENTITY_ID)) is not None + assert state.state != STATE_UNAVAILABLE + + mock_rf_receiver_entity._handle_received_signal(TEST_SIGNAL) + assert mock_consumer_entity.received_signals == [TEST_SIGNAL] + + +async def test_receiver_unsubscribed_on_remove( + mock_rf_receiver_entity: MockRadioFrequencyReceiverEntity, + mock_consumer_entity: MockConsumerEntity, +) -> None: + """Test the consumer unsubscribes from the receiver when removed.""" + await mock_consumer_entity.async_remove() + + mock_rf_receiver_entity._handle_received_signal(TEST_SIGNAL) + assert mock_consumer_entity.received_signals == [] diff --git a/tests/components/radio_frequency/test_init.py b/tests/components/radio_frequency/test_init.py index a55e64b99196..75aeb4ae227a 100644 --- a/tests/components/radio_frequency/test_init.py +++ b/tests/components/radio_frequency/test_init.py @@ -1,29 +1,49 @@ """Tests for the Radio Frequency integration setup.""" -from unittest.mock import AsyncMock +import re +from unittest.mock import AsyncMock, Mock from freezegun.api import FrozenDateTimeFactory import pytest -from pytest_homeassistant.common import mock_restore_cache -from pytest_homeassistant.components.radio_frequency import ENTITY_ID +from pytest_homeassistant.common import ( + MockConfigEntry, + MockModule, + MockPlatform, + mock_config_flow, + mock_integration, + mock_platform, + mock_restore_cache, +) +from pytest_homeassistant.components.radio_frequency import ( + ENTITY_ID, + RECEIVER_ENTITY_ID, +) from pytest_homeassistant.components.radio_frequency.common import ( MockRadioFrequencyCommand, MockRadioFrequencyEntity, + MockRadioFrequencyReceiverEntity, ) from rf_protocols import ModulationType from homeassistant.components.radio_frequency import ( DATA_COMPONENT, DOMAIN, + RadioFrequencyReceivedSignal, + async_get_receivers, async_get_transmitters, async_send_command, + async_subscribe_receiver, ) -from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.config_entries import ConfigEntry, ConfigFlow +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant, State from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util +TEST_DOMAIN = "test" + async def test_get_transmitters_component_not_loaded(hass: HomeAssistant) -> None: """Test getting transmitters raises when the component is not loaded.""" @@ -60,13 +80,69 @@ async def test_get_transmitters_filters_by_modulation(hass: HomeAssistant) -> No assert result == [] +@pytest.mark.usefixtures("mock_rf_receiver_entity") +async def test_get_transmitters_ignores_receivers(hass: HomeAssistant) -> None: + """Test receivers are not returned as transmitters.""" + with pytest.raises( + HomeAssistantError, + match="No Radio Frequency transmitters available", + ): + async_get_transmitters(hass, 433_920_000, ModulationType.OOK) + + +async def test_get_receivers_component_not_loaded(hass: HomeAssistant) -> None: + """Test getting receivers raises when the component is not loaded.""" + with pytest.raises(HomeAssistantError, match="component_not_loaded"): + async_get_receivers(hass, 433_920_000, ModulationType.OOK) + + @pytest.mark.usefixtures("mock_rf_entity") -async def test_rf_entity_initial_state(hass: HomeAssistant) -> None: - """Test radio frequency entity has no state before any command is sent.""" +async def test_get_receivers_no_receivers(hass: HomeAssistant) -> None: + """Test getting receivers raises when none are registered.""" + with pytest.raises( + HomeAssistantError, + match="No Radio Frequency receivers available", + ): + async_get_receivers(hass, 433_920_000, ModulationType.OOK) + + +@pytest.mark.usefixtures("mock_rf_entity", "mock_rf_receiver_entity") +async def test_get_entities_filters_by_type(hass: HomeAssistant) -> None: + """Test get_transmitters/get_receivers return only entities of matching type.""" + assert async_get_transmitters(hass, 433_920_000, ModulationType.OOK) == [ENTITY_ID] + assert async_get_receivers(hass, 433_920_000, ModulationType.OOK) == [ + RECEIVER_ENTITY_ID + ] + + +@pytest.mark.usefixtures("mock_rf_receiver_entity") +async def test_get_receivers_with_frequency_ranges(hass: HomeAssistant) -> None: + """Test receiver with frequency ranges filters correctly.""" + result = async_get_receivers(hass, 433_920_000, ModulationType.OOK) + assert result == [RECEIVER_ENTITY_ID] + + result = async_get_receivers(hass, 868_000_000, ModulationType.OOK) + assert result == [] + + +@pytest.mark.usefixtures("mock_rf_receiver_entity") +async def test_get_receivers_filters_by_modulation(hass: HomeAssistant) -> None: + """Test receivers are filtered by supported modulation.""" + result = async_get_receivers(hass, 433_920_000, "no_matching_modulation") # type: ignore[arg-type] + assert result == [] + + +@pytest.mark.usefixtures("mock_rf_entity", "mock_rf_receiver_entity") +async def test_rf_entities_initial_state(hass: HomeAssistant) -> None: + """Test radio frequency entities have no state before any command is sent.""" state = hass.states.get(ENTITY_ID) assert state is not None assert state.state == STATE_UNKNOWN + state = hass.states.get(RECEIVER_ENTITY_ID) + assert state is not None + assert state.state == STATE_UNKNOWN + async def test_async_send_command_success( hass: HomeAssistant, @@ -123,6 +199,20 @@ async def test_async_send_command_entity_not_found(hass: HomeAssistant) -> None: await async_send_command(hass, "radio_frequency.nonexistent_entity", command) +async def test_async_send_command_rejects_receiver( + hass: HomeAssistant, + mock_rf_receiver_entity: MockRadioFrequencyReceiverEntity, +) -> None: + """Test async_send_command rejects a receiver entity.""" + command = MockRadioFrequencyCommand(frequency=433_920_000) + + with pytest.raises( + HomeAssistantError, + match=f"Radio Frequency entity `{RECEIVER_ENTITY_ID}` not found", + ): + await async_send_command(hass, RECEIVER_ENTITY_ID, command) + + async def test_async_send_command_unsupported_frequency( hass: HomeAssistant, mock_rf_entity: MockRadioFrequencyEntity, @@ -186,16 +276,225 @@ async def test_rf_entity_state_restore( expected_state: str, ) -> None: """Test radio frequency entity state restore.""" - mock_restore_cache(hass, [State(ENTITY_ID, restored_value)]) + mock_restore_cache( + hass, + [State(ENTITY_ID, restored_value), State(RECEIVER_ENTITY_ID, restored_value)], + ) assert await async_setup_component(hass, DOMAIN, {}) await hass.async_block_till_done() component = hass.data[DATA_COMPONENT] await component.async_add_entities( - [MockRadioFrequencyEntity("test_rf_transmitter")] + [ + MockRadioFrequencyEntity("test_rf_transmitter"), + MockRadioFrequencyReceiverEntity("test_rf_receiver"), + ] ) state = hass.states.get(ENTITY_ID) assert state is not None assert state.state == expected_state + + state = hass.states.get(RECEIVER_ENTITY_ID) + assert state is not None + assert state.state == expected_state + + +async def test_async_subscribe_receiver_success( + hass: HomeAssistant, + mock_rf_receiver_entity: MockRadioFrequencyReceiverEntity, + freezer: FrozenDateTimeFactory, +) -> None: + """Test subscribing to a receiver via async_subscribe_receiver helper.""" + now = dt_util.utcnow() + freezer.move_to(now) + + signal_callback = Mock() + unsubscribe = async_subscribe_receiver(hass, RECEIVER_ENTITY_ID, signal_callback) + + signal = RadioFrequencyReceivedSignal( + timings=[350, -1050, 350, -350], frequency=433_920_000 + ) + mock_rf_receiver_entity._handle_received_signal(signal) + + assert signal_callback.call_count == 1 + assert signal_callback.call_args[0][0] is signal + + state = hass.states.get(RECEIVER_ENTITY_ID) + assert state is not None + assert state.state == now.isoformat(timespec="milliseconds") + + unsubscribe() + mock_rf_receiver_entity._handle_received_signal(signal) + assert signal_callback.call_count == 1 + + +async def test_handle_received_signal_isolates_callback_errors( + hass: HomeAssistant, + mock_rf_receiver_entity: MockRadioFrequencyReceiverEntity, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test a failing subscriber does not prevent other subscribers from running.""" + failing_callback = Mock(side_effect=RuntimeError("boom")) + working_callback = Mock() + async_subscribe_receiver(hass, RECEIVER_ENTITY_ID, failing_callback) + async_subscribe_receiver(hass, RECEIVER_ENTITY_ID, working_callback) + + signal = RadioFrequencyReceivedSignal(timings=[350, -1050, 350, -350]) + mock_rf_receiver_entity._handle_received_signal(signal) + + failing_callback.assert_called_once_with(signal) + working_callback.assert_called_once_with(signal) + assert "Error in signal callback" in caplog.text + + +async def test_handle_received_signal_unsubscribe_during_dispatch( + hass: HomeAssistant, + mock_rf_receiver_entity: MockRadioFrequencyReceiverEntity, +) -> None: + """Test a subscriber can unsubscribe itself during dispatch without error.""" + other_callback = Mock() + + def unsubscribing_callback(signal: RadioFrequencyReceivedSignal) -> None: + unsubscribe() + + self_unsub_mock = Mock(side_effect=unsubscribing_callback) + unsubscribe = async_subscribe_receiver(hass, RECEIVER_ENTITY_ID, self_unsub_mock) + async_subscribe_receiver(hass, RECEIVER_ENTITY_ID, other_callback) + + signal = RadioFrequencyReceivedSignal(timings=[350, -1050, 350, -350]) + mock_rf_receiver_entity._handle_received_signal(signal) + + self_unsub_mock.assert_called_once_with(signal) + other_callback.assert_called_once_with(signal) + + mock_rf_receiver_entity._handle_received_signal(signal) + self_unsub_mock.assert_called_once_with(signal) + assert other_callback.call_count == 2 + + +@pytest.mark.usefixtures("init_radio_frequency") +@pytest.mark.parametrize( + "entity_id_or_uuid", + ["radio_frequency.nonexistent_entity", "invalid-id"], +) +async def test_async_subscribe_receiver_not_found( + hass: HomeAssistant, entity_id_or_uuid: str +) -> None: + """Test async_subscribe_receiver raises when the entity is missing or invalid.""" + with pytest.raises( + HomeAssistantError, + match=re.escape( + f"Radio Frequency receiver entity `{entity_id_or_uuid}` not found" + ), + ): + async_subscribe_receiver(hass, entity_id_or_uuid, lambda _: None) + + +@pytest.mark.usefixtures("mock_rf_entity") +async def test_async_subscribe_receiver_rejects_transmitter( + hass: HomeAssistant, +) -> None: + """Test async_subscribe_receiver rejects a transmitter entity.""" + with pytest.raises( + HomeAssistantError, + match=re.escape(f"Radio Frequency receiver entity `{ENTITY_ID}` not found"), + ): + async_subscribe_receiver(hass, ENTITY_ID, lambda _: None) + + +async def test_async_subscribe_receiver_component_not_loaded( + hass: HomeAssistant, +) -> None: + """Test async_subscribe_receiver raises error when component not loaded.""" + with pytest.raises(HomeAssistantError, match="component_not_loaded"): + async_subscribe_receiver(hass, "radio_frequency.some_entity", lambda _: None) + + +@pytest.mark.usefixtures("init_radio_frequency") +async def test_name(hass: HomeAssistant) -> None: + """Test entity name / device class naming fallback.""" + + async def async_setup_entry_init( + hass: HomeAssistant, config_entry: ConfigEntry + ) -> bool: + """Set up test config entry.""" + await hass.config_entries.async_forward_entry_setups( + config_entry, [Platform.RADIO_FREQUENCY] + ) + return True + + class MockFlow(ConfigFlow): + """Test flow.""" + + mock_platform(hass, f"{TEST_DOMAIN}.config_flow") + mock_integration( + hass, + MockModule( + TEST_DOMAIN, + async_setup_entry=async_setup_entry_init, + ), + ) + + # Unnamed transmitter without has_entity_name -> no name + transmitter1 = MockRadioFrequencyEntity("test_transmitter1", name=None) + transmitter1.entity_id = "radio_frequency.test_transmitter1" + transmitter1._attr_has_entity_name = False + + # Unnamed transmitter with has_entity_name True -> name set from device class + transmitter2 = MockRadioFrequencyEntity("test_transmitter2", name=None) + transmitter2.entity_id = "radio_frequency.test_transmitter2" + transmitter2._attr_has_entity_name = True + + # Unnamed receiver without has_entity_name -> no name + receiver1 = MockRadioFrequencyReceiverEntity("test_receiver1", name=None) + receiver1.entity_id = "radio_frequency.test_receiver1" + receiver1._attr_has_entity_name = False + + # Unnamed receiver with has_entity_name True -> name set from device class + receiver2 = MockRadioFrequencyReceiverEntity("test_receiver2", name=None) + receiver2.entity_id = "radio_frequency.test_receiver2" + receiver2._attr_has_entity_name = True + + async def async_setup_entry_platform( + hass: HomeAssistant, + config_entry: ConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, + ) -> None: + """Set up test radio frequency platform via config entry.""" + async_add_entities([transmitter1, transmitter2, receiver1, receiver2]) + + mock_platform( + hass, + f"{TEST_DOMAIN}.{DOMAIN}", + MockPlatform(async_setup_entry=async_setup_entry_platform), + ) + + config_entry = MockConfigEntry(domain=TEST_DOMAIN) + config_entry.add_to_hass(hass) + with mock_config_flow(TEST_DOMAIN, MockFlow): + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + state_tx1 = hass.states.get("radio_frequency.test_transmitter1") + assert state_tx1 is not None + assert state_tx1.attributes == {"device_class": "transmitter"} + + state_tx2 = hass.states.get("radio_frequency.test_transmitter2") + assert state_tx2 is not None + assert state_tx2.attributes == { + "device_class": "transmitter", + "friendly_name": "Radio frequency transmitter", + } + + state_rx1 = hass.states.get("radio_frequency.test_receiver1") + assert state_rx1 is not None + assert state_rx1.attributes == {"device_class": "receiver"} + + state_rx2 = hass.states.get("radio_frequency.test_receiver2") + assert state_rx2 is not None + assert state_rx2.attributes == { + "device_class": "receiver", + "friendly_name": "Radio frequency receiver", + } diff --git a/tests/components/radio_frequency/test_websocket_api.py b/tests/components/radio_frequency/test_websocket_api.py index ae13bf5448e1..6efb6c90adc2 100644 --- a/tests/components/radio_frequency/test_websocket_api.py +++ b/tests/components/radio_frequency/test_websocket_api.py @@ -1,7 +1,10 @@ """Tests for the Radio Frequency websocket API.""" import pytest -from pytest_homeassistant.components.radio_frequency import ENTITY_ID +from pytest_homeassistant.components.radio_frequency import ( + ENTITY_ID, + RECEIVER_ENTITY_ID, +) from pytest_homeassistant.components.radio_frequency.common import ( MockRadioFrequencyEntity, ) @@ -11,11 +14,11 @@ from homeassistant.components.radio_frequency import DATA_COMPONENT from homeassistant.core import HomeAssistant -@pytest.mark.usefixtures("mock_rf_entity") -async def test_list_transmitters( +@pytest.mark.usefixtures("mock_rf_entity", "mock_rf_receiver_entity") +async def test_list_entities( hass: HomeAssistant, hass_ws_client: WebSocketGenerator ) -> None: - """Test listing radio frequency transmitters.""" + """Test listing radio frequency transmitters and receivers.""" client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "radio_frequency/list"}) response = await client.receive_json() @@ -30,21 +33,30 @@ async def test_list_transmitters( "supported_frequency_ranges": [[433_000_000, 434_000_000]], "supported_modulations": ["OOK"], } - ] + ], + "receivers": [ + { + "entity_id": RECEIVER_ENTITY_ID, + "device_id": None, + "config_entry_id": None, + "supported_frequency_ranges": [[433_000_000, 434_000_000]], + "supported_modulations": ["OOK"], + } + ], } @pytest.mark.usefixtures("init_radio_frequency") -async def test_list_transmitters_empty( +async def test_list_entities_empty( hass: HomeAssistant, hass_ws_client: WebSocketGenerator ) -> None: - """Test listing transmitters when none are registered.""" + """Test listing entities when none are registered.""" client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "radio_frequency/list"}) response = await client.receive_json() assert response["success"] - assert response["result"] == {"transmitters": []} + assert response["result"] == {"transmitters": [], "receivers": []} @pytest.mark.usefixtures("init_radio_frequency") @@ -84,12 +96,12 @@ async def test_list_multiple_transmitters_with_ranges( @pytest.mark.usefixtures("mock_rf_entity") -async def test_list_transmitters_requires_admin( +async def test_list_entities_requires_admin( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, hass_read_only_access_token: str, ) -> None: - """Test listing transmitters is only allowed for admins.""" + """Test listing entities is only allowed for admins.""" client = await hass_ws_client(hass, hass_read_only_access_token) await client.send_json_auto_id({"type": "radio_frequency/list"}) response = await client.receive_json()