diff --git a/homeassistant/components/enocean/__init__.py b/homeassistant/components/enocean/__init__.py index 11170fbac979..574f480ce8f4 100644 --- a/homeassistant/components/enocean/__init__.py +++ b/homeassistant/components/enocean/__init__.py @@ -1,6 +1,6 @@ """Support for EnOcean devices.""" -from enocean_async import Gateway +from enocean_async import Gateway, SerialProtocol import probatio from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry @@ -14,7 +14,7 @@ from homeassistant.helpers.dispatcher import ( ) from homeassistant.helpers.typing import ConfigType -from .const import DOMAIN, SIGNAL_RECEIVE_MESSAGE, SIGNAL_SEND_MESSAGE +from .const import CONF_PROTOCOL, DOMAIN, SIGNAL_RECEIVE_MESSAGE, SIGNAL_SEND_MESSAGE type EnOceanConfigEntry = ConfigEntry[Gateway] @@ -48,7 +48,12 @@ async def async_setup_entry( hass: HomeAssistant, config_entry: EnOceanConfigEntry ) -> None: """Set up an EnOcean gateway for the given entry.""" - gateway = Gateway(port=config_entry.data[CONF_DEVICE]) + gateway = Gateway( + port=config_entry.data[CONF_DEVICE], + protocol=SerialProtocol( + config_entry.data.get(CONF_PROTOCOL, SerialProtocol.ESP3) + ), + ) gateway.add_erp1_received_callback( lambda packet: async_dispatcher_send(hass, SIGNAL_RECEIVE_MESSAGE, packet) diff --git a/homeassistant/components/enocean/config_flow.py b/homeassistant/components/enocean/config_flow.py index 9bf9ff55d83b..86aea6f543fd 100644 --- a/homeassistant/components/enocean/config_flow.py +++ b/homeassistant/components/enocean/config_flow.py @@ -1,9 +1,10 @@ """Config flows for the EnOcean integration.""" +import asyncio import glob from typing import Any, override -from enocean_async import Gateway +from enocean_async import SerialProtocol, detect_serial_protocol import probatio from homeassistant.components import usb @@ -21,7 +22,13 @@ from homeassistant.helpers.selector import ( ) from homeassistant.helpers.service_info.usb import UsbServiceInfo -from .const import DOMAIN, ERROR_INVALID_DONGLE_PATH, LOGGER, MANUFACTURER +from .const import ( + CONF_PROTOCOL, + DOMAIN, + ERROR_INVALID_DONGLE_PATH, + LOGGER, + MANUFACTURER, +) MANUAL_SCHEMA = probatio.Schema( { @@ -30,17 +37,17 @@ MANUAL_SCHEMA = probatio.Schema( ) -def _detect_usb_dongle() -> list[str]: +ENOCEAN_DONGLE_GLOBS = ["/dev/tty*FTOA2PV*", "/dev/serial/by-id/*EnOcean*"] +# Matches any USB serial adapter, so these ports are listed without probing them +GENERIC_SERIAL_GLOBS = ["/dev/tty.usbserial-*"] + + +def _detect_usb_dongle(globs_to_test: list[str]) -> list[str]: """Return a list of candidate paths for USB EnOcean dongles. This method is currently a bit simplistic, it may need to be improved to support more configurations and OS. """ - globs_to_test = [ - "/dev/tty*FTOA2PV*", - "/dev/serial/by-id/*EnOcean*", - "/dev/tty.usbserial-*", - ] found_paths = [] for current_glob in globs_to_test: found_paths.extend(glob.glob(current_glob)) @@ -102,14 +109,15 @@ class EnOceanFlowHandler(ConfigFlow, domain=DOMAIN): async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult: """Import a yaml configuration.""" - if not await self.validate_enocean_conf(import_data): + protocol = await detect_serial_protocol(import_data[CONF_DEVICE]) + if protocol is None: LOGGER.warning( "Cannot import yaml configuration: %s is not a valid dongle path", import_data[CONF_DEVICE], ) return self.async_abort(reason="invalid_dongle_path") - return self.create_enocean_entry(import_data) + return self.create_enocean_entry(import_data, protocol) @override async def async_step_user( @@ -127,7 +135,24 @@ class EnOceanFlowHandler(ConfigFlow, domain=DOMAIN): return await self.async_step_manual() return await self.async_step_manual(user_input) - devices = await self.hass.async_add_executor_job(_detect_usb_dongle) + candidates = await self.hass.async_add_executor_job( + _detect_usb_dongle, ENOCEAN_DONGLE_GLOBS + ) + # Only a port with a dongle is listed: a FAM-USB, for example, shows up as + # two serial ports, of which one is connected to the radio module. + protocols = await asyncio.gather( + *(detect_serial_protocol(path) for path in candidates) + ) + devices = [ + path + for path, protocol in zip(candidates, protocols, strict=True) + if protocol is not None + ] + devices.extend( + await self.hass.async_add_executor_job( + _detect_usb_dongle, GENERIC_SERIAL_GLOBS + ) + ) if len(devices) == 0: return await self.async_step_manual() devices.append(self.MANUAL_PATH_VALUE) @@ -153,8 +178,9 @@ class EnOceanFlowHandler(ConfigFlow, domain=DOMAIN): """Request manual USB dongle path.""" errors = {} if user_input is not None: - if await self.validate_enocean_conf(user_input): - return self.create_enocean_entry(user_input) + protocol = await detect_serial_protocol(user_input[CONF_DEVICE]) + if protocol is not None: + return self.create_enocean_entry(user_input, protocol) errors = {CONF_DEVICE: ERROR_INVALID_DONGLE_PATH} return self.async_show_form( @@ -163,21 +189,10 @@ class EnOceanFlowHandler(ConfigFlow, domain=DOMAIN): errors=errors, ) - async def validate_enocean_conf(self, user_input) -> bool: - """Return True if the user_input contains a valid dongle path.""" - dongle_path = user_input[CONF_DEVICE] - try: - # Starting the gateway will raise an exception if it can't connect - gateway = Gateway(port=dongle_path) - await gateway.start() - except ConnectionError as exception: - LOGGER.warning("Dongle path %s is invalid: %s", dongle_path, str(exception)) - return False - finally: - await gateway.stop() - - return True - - def create_enocean_entry(self, user_input): + def create_enocean_entry( + self, user_input: dict[str, Any], protocol: SerialProtocol + ) -> ConfigFlowResult: """Create an entry for the provided configuration.""" - return self.async_create_entry(title=MANUFACTURER, data=user_input) + return self.async_create_entry( + title=MANUFACTURER, data={**user_input, CONF_PROTOCOL: protocol.value} + ) diff --git a/homeassistant/components/enocean/const.py b/homeassistant/components/enocean/const.py index d08fad3c870e..ca791cff02b0 100644 --- a/homeassistant/components/enocean/const.py +++ b/homeassistant/components/enocean/const.py @@ -8,6 +8,8 @@ DOMAIN = "enocean" MANUFACTURER = "EnOcean" +CONF_PROTOCOL = "protocol" + ERROR_INVALID_DONGLE_PATH = "invalid_dongle_path" SIGNAL_RECEIVE_MESSAGE = "enocean.receive_message" diff --git a/tests/components/enocean/conftest.py b/tests/components/enocean/conftest.py index 9b84170d32da..1adeb943e5f7 100644 --- a/tests/components/enocean/conftest.py +++ b/tests/components/enocean/conftest.py @@ -30,12 +30,18 @@ def mock_config_entry() -> MockConfigEntry: @pytest.fixture -def mock_gateway() -> Generator[Mock]: - """Return a mocked EnOcean gateway.""" +def mock_gateway_class() -> Generator[Mock]: + """Return the mocked EnOcean gateway class.""" with patch( "homeassistant.components.enocean.Gateway", autospec=True ) as gateway_class: - yield gateway_class.return_value + yield gateway_class + + +@pytest.fixture +def mock_gateway(mock_gateway_class: Mock) -> Mock: + """Return a mocked EnOcean gateway.""" + return mock_gateway_class.return_value @pytest.fixture diff --git a/tests/components/enocean/test_config_flow.py b/tests/components/enocean/test_config_flow.py index 250969911484..617f3e66ac7c 100644 --- a/tests/components/enocean/test_config_flow.py +++ b/tests/components/enocean/test_config_flow.py @@ -1,11 +1,13 @@ """Tests for EnOcean config flow.""" -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import AsyncMock, patch +from enocean_async import SerialProtocol +import pytest from pytest_homeassistant.common import MockConfigEntry from homeassistant.components.enocean.config_flow import EnOceanFlowHandler -from homeassistant.components.enocean.const import DOMAIN, MANUFACTURER +from homeassistant.components.enocean.const import CONF_PROTOCOL, DOMAIN, MANUFACTURER from homeassistant.config_entries import ( SOURCE_IMPORT, SOURCE_USB, @@ -17,7 +19,7 @@ from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.service_info.usb import UsbServiceInfo -GATEWAY_CLASS = "homeassistant.components.enocean.config_flow.Gateway" +DETECT_METHOD = "homeassistant.components.enocean.config_flow.detect_serial_protocol" GLOB_METHOD = "homeassistant.components.enocean.config_flow.glob.glob" SETUP_ENTRY_METHOD = "homeassistant.components.enocean.async_setup_entry" @@ -41,7 +43,10 @@ async def test_user_flow_with_detected_dongle(hass: HomeAssistant) -> None: """Test the user flow with a detected EnOcean dongle.""" FAKE_DONGLE_PATH = "/fake/dongle" - with patch(GLOB_METHOD, side_effect=[[FAKE_DONGLE_PATH], [], []]): + with ( + patch(GLOB_METHOD, side_effect=[[FAKE_DONGLE_PATH], [], []]), + patch(DETECT_METHOD, return_value=SerialProtocol.ESP3), + ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) @@ -53,6 +58,64 @@ async def test_user_flow_with_detected_dongle(hass: HomeAssistant) -> None: assert EnOceanFlowHandler.MANUAL_PATH_VALUE in devices +@pytest.mark.parametrize( + ("found_paths", "expected_devices", "expected_probed_paths"), + [ + pytest.param( + [[], ["/fake/silent/port", "/fake/dongle"], []], + ["/fake/dongle"], + {"/fake/silent/port", "/fake/dongle"}, + id="port_without_dongle_is_hidden", + ), + pytest.param( + [[], [], ["/dev/tty.usbserial-1234"]], + ["/dev/tty.usbserial-1234"], + set(), + id="generic_serial_port_is_listed_without_probing", + ), + ], +) +async def test_user_flow_lists_answering_dongles( + hass: HomeAssistant, + found_paths: list[list[str]], + expected_devices: list[str], + expected_probed_paths: set[str], +) -> None: + """Test that the user flow only probes and lists the right ports.""" + + async def detect(port: str) -> SerialProtocol | None: + return SerialProtocol.ESP2 if port == "/fake/dongle" else None + + with ( + patch(GLOB_METHOD, side_effect=found_paths), + patch(DETECT_METHOD, side_effect=detect) as detect_mock, + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "detect" + devices = result["data_schema"].schema.get(CONF_DEVICE).config.get("options") + assert devices == [*expected_devices, EnOceanFlowHandler.MANUAL_PATH_VALUE] + probed_paths = {detect_call.args[0] for detect_call in detect_mock.call_args_list} + assert probed_paths == expected_probed_paths + + +async def test_user_flow_with_no_answering_dongle(hass: HomeAssistant) -> None: + """Test the user flow when no dongle answers on the detected ports.""" + with ( + patch(GLOB_METHOD, side_effect=[["/fake/silent/port"], [], []]), + patch(DETECT_METHOD, return_value=None), + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "manual" + + async def test_user_flow_with_no_detected_dongle(hass: HomeAssistant) -> None: """Test the user flow with no detected EnOcean dongle.""" with patch(GLOB_METHOD, return_value=[]): @@ -68,10 +131,7 @@ async def test_detection_flow_with_valid_path(hass: HomeAssistant) -> None: """Test the detection flow with a valid path selected.""" USER_PROVIDED_PATH = "/user/provided/path" - with patch( - GATEWAY_CLASS, - return_value=Mock(start=AsyncMock(), stop=AsyncMock()), - ): + with patch(DETECT_METHOD, return_value=SerialProtocol.ESP3): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "detect"}, data={CONF_DEVICE: USER_PROVIDED_PATH} ) @@ -99,13 +159,7 @@ async def test_detection_flow_with_invalid_path(hass: HomeAssistant) -> None: """Test the detection flow with an invalid path selected.""" USER_PROVIDED_PATH = "/invalid/path" - with patch( - GATEWAY_CLASS, - return_value=Mock( - start=AsyncMock(side_effect=ConnectionError("invalid path")), - stop=AsyncMock(), - ), - ): + with patch(DETECT_METHOD, return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "detect"}, @@ -117,13 +171,14 @@ async def test_detection_flow_with_invalid_path(hass: HomeAssistant) -> None: assert CONF_DEVICE in result["errors"] with ( - patch(GATEWAY_CLASS, return_value=Mock(start=AsyncMock(), stop=AsyncMock())), + patch(DETECT_METHOD, return_value=SerialProtocol.ESP3), patch(SETUP_ENTRY_METHOD, AsyncMock(return_value=None)), ): result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_DEVICE: USER_PROVIDED_PATH} ) + # pylint: disable-next=home-assistant-tests-config-flow-unique-id assert result["type"] is FlowResultType.CREATE_ENTRY @@ -131,10 +186,7 @@ async def test_manual_flow_with_valid_path(hass: HomeAssistant) -> None: """Test the manual flow with a valid path.""" USER_PROVIDED_PATH = "/user/provided/path" - with patch( - GATEWAY_CLASS, - return_value=Mock(start=AsyncMock(), stop=AsyncMock()), - ): + with patch(DETECT_METHOD, return_value=SerialProtocol.ESP3): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "manual"}, data={CONF_DEVICE: USER_PROVIDED_PATH} ) @@ -144,17 +196,41 @@ async def test_manual_flow_with_valid_path(hass: HomeAssistant) -> None: assert result["data"][CONF_DEVICE] == USER_PROVIDED_PATH +@pytest.mark.parametrize( + ("protocol", "expected_protocol"), + [ + pytest.param(SerialProtocol.ESP3, "esp3", id="esp3_dongle"), + pytest.param(SerialProtocol.ESP2, "esp2", id="esp2_dongle"), + ], +) +async def test_manual_flow_stores_the_detected_protocol( + hass: HomeAssistant, protocol: SerialProtocol, expected_protocol: str +) -> None: + """Test that the flow stores the serial protocol of the dongle.""" + USER_PROVIDED_PATH = "/user/provided/path" + + with ( + patch(DETECT_METHOD, return_value=protocol) as detect_mock, + patch(SETUP_ENTRY_METHOD, AsyncMock(return_value=None)), + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": "manual"}, data={CONF_DEVICE: USER_PROVIDED_PATH} + ) + + # pylint: disable-next=home-assistant-tests-config-flow-unique-id + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"] == { + CONF_DEVICE: USER_PROVIDED_PATH, + CONF_PROTOCOL: expected_protocol, + } + detect_mock.assert_awaited_once_with(USER_PROVIDED_PATH) + + async def test_manual_flow_with_invalid_path(hass: HomeAssistant) -> None: """Test the manual flow with an invalid path.""" USER_PROVIDED_PATH = "/user/provided/path" - with patch( - GATEWAY_CLASS, - return_value=Mock( - start=AsyncMock(side_effect=ConnectionError("invalid path")), - stop=AsyncMock(), - ), - ): + with patch(DETECT_METHOD, return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "manual"}, data={CONF_DEVICE: USER_PROVIDED_PATH} ) @@ -164,13 +240,14 @@ async def test_manual_flow_with_invalid_path(hass: HomeAssistant) -> None: assert CONF_DEVICE in result["errors"] with ( - patch(GATEWAY_CLASS, return_value=Mock(start=AsyncMock(), stop=AsyncMock())), + patch(DETECT_METHOD, return_value=SerialProtocol.ESP3), patch(SETUP_ENTRY_METHOD, AsyncMock(return_value=None)), ): result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_DEVICE: USER_PROVIDED_PATH} ) + # pylint: disable-next=home-assistant-tests-config-flow-unique-id assert result["type"] is FlowResultType.CREATE_ENTRY @@ -178,10 +255,7 @@ async def test_import_flow_with_valid_path(hass: HomeAssistant) -> None: """Test the import flow with a valid path.""" DATA_TO_IMPORT = {CONF_DEVICE: "/valid/path/to/import"} - with patch( - GATEWAY_CLASS, - return_value=Mock(start=AsyncMock(), stop=AsyncMock()), - ): + with patch(DETECT_METHOD, return_value=SerialProtocol.ESP3): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, @@ -197,13 +271,7 @@ async def test_import_flow_with_invalid_path(hass: HomeAssistant) -> None: """Test the import flow with an invalid path.""" DATA_TO_IMPORT = {CONF_DEVICE: "/invalid/path/to/import"} - with patch( - GATEWAY_CLASS, - return_value=Mock( - start=AsyncMock(side_effect=ConnectionError("invalid path")), - stop=AsyncMock(), - ), - ): + with patch(DETECT_METHOD, return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, @@ -240,10 +308,7 @@ async def test_usb_discovery( # test device path with ( - patch( - GATEWAY_CLASS, - return_value=Mock(start=AsyncMock(), stop=AsyncMock()), - ), + patch(DETECT_METHOD, return_value=SerialProtocol.ESP3), patch(SETUP_ENTRY_METHOD, AsyncMock(return_value=None)), patch( "homeassistant.components.usb.get_serial_by_id", @@ -254,7 +319,7 @@ async def test_usb_discovery( assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == MANUFACTURER - assert result["data"] == {"device": device} + assert result["data"] == {"device": device, "protocol": "esp3"} assert result["context"]["unique_id"] == "0403:6001_1234_EnOcean GmbH_USB 300" assert result["context"]["title_placeholders"] == { "name": "USB 300 - /dev/enocean0, s/n: 1234 - EnOcean GmbH - 0403:6001" diff --git a/tests/components/enocean/test_init.py b/tests/components/enocean/test_init.py index 3fcc8cc21ce1..f661b3e94004 100644 --- a/tests/components/enocean/test_init.py +++ b/tests/components/enocean/test_init.py @@ -2,9 +2,13 @@ from unittest.mock import Mock, patch +from enocean_async import SerialProtocol +import pytest from pytest_homeassistant.common import MockConfigEntry +from homeassistant.components.enocean.const import CONF_PROTOCOL, DOMAIN from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import CONF_DEVICE from homeassistant.core import HomeAssistant @@ -36,3 +40,39 @@ async def test_unload_stops_gateway( assert mock_config_entry.state is ConfigEntryState.NOT_LOADED mock_gateway.stop.assert_awaited_once() + + +@pytest.mark.parametrize( + ("entry_data", "expected_protocol"), + [ + pytest.param( + {CONF_DEVICE: "/dev/ttyUSB0"}, SerialProtocol.ESP3, id="no_protocol_stored" + ), + pytest.param( + {CONF_DEVICE: "/dev/ttyUSB0", CONF_PROTOCOL: "esp3"}, + SerialProtocol.ESP3, + id="esp3", + ), + pytest.param( + {CONF_DEVICE: "/dev/ttyUSB0", CONF_PROTOCOL: "esp2"}, + SerialProtocol.ESP2, + id="esp2", + ), + ], +) +async def test_gateway_uses_stored_protocol( + hass: HomeAssistant, + mock_gateway_class: Mock, + entry_data: dict[str, str], + expected_protocol: SerialProtocol, +) -> None: + """Test that the gateway is created with the protocol stored in the entry.""" + entry = MockConfigEntry(domain=DOMAIN, data=entry_data) + entry.add_to_hass(hass) + + await hass.config_entries.async_setup(entry.entry_id) + + assert entry.state is ConfigEntryState.LOADED + mock_gateway_class.assert_called_once_with( + port="/dev/ttyUSB0", protocol=expected_protocol + )