diff --git a/homeassistant/components/homewizard/config_flow.py b/homeassistant/components/homewizard/config_flow.py index c38b7758fd0b..fa8dd479360f 100644 --- a/homeassistant/components/homewizard/config_flow.py +++ b/homeassistant/components/homewizard/config_flow.py @@ -2,6 +2,8 @@ import asyncio from collections.abc import Mapping +from contextlib import suppress +import ipaddress from typing import TYPE_CHECKING, Any, override from homewizard_energy import ( @@ -183,15 +185,23 @@ class HomeWizardConfigFlow(ConfigFlow, domain=DOMAIN): ): return self.async_abort(reason="invalid_discovery_parameters") - self.ip_address = discovery_info.host self.product_type = discovery_info.properties[CONF_PRODUCT_TYPE] self.product_name = discovery_info.properties[CONF_PRODUCT_NAME] self.serial = discovery_info.properties[CONF_SERIAL] - await self.async_set_unique_id(f"{self.product_type}_{self.serial}") - self._abort_if_unique_id_configured( - updates={CONF_IP_ADDRESS: discovery_info.host} + unique_id = f"{self.product_type}_{self.serial}" + await self.async_set_unique_id(unique_id) + + current_ip_address: str | None = None + if entry := self.hass.config_entries.async_entry_for_domain_unique_id( + DOMAIN, unique_id + ): + current_ip_address = entry.data.get(CONF_IP_ADDRESS) + + self.ip_address = _select_discovery_ip_address( + discovery_info, current_ip_address ) + self._abort_if_unique_id_configured(updates={CONF_IP_ADDRESS: self.ip_address}) return await self.async_step_discovery_confirm() @@ -350,6 +360,31 @@ class HomeWizardConfigFlow(ConfigFlow, domain=DOMAIN): ) +def _select_discovery_ip_address( + discovery_info: ZeroconfServiceInfo, current_ip_address: str | None +) -> str: + """Select the IP address to use for a device found with zeroconf. + + Devices can advertise both an IPv4 and an IPv6 address. Keep the configured + address while the device still advertises it, so the entry isn't updated + and reloaded on every discovery. Otherwise prefer IPv4, which is also the + address DHCP discovery updates the entry with. + """ + addresses = [ + address + for address in discovery_info.ip_addresses + if not address.is_link_local and not address.is_unspecified + ] + if current_ip_address is not None: + with suppress(ValueError): + if ipaddress.ip_address(current_ip_address) in addresses: + return current_ip_address + return next( + (str(address) for address in addresses if address.version == 4), + discovery_info.host, + ) + + async def async_try_connect(ip_address: str, token: str | None = None) -> Device: """Try to connect. diff --git a/tests/components/homewizard/test_config_flow.py b/tests/components/homewizard/test_config_flow.py index 762f63100b55..336f3341d0d7 100644 --- a/tests/components/homewizard/test_config_flow.py +++ b/tests/components/homewizard/test_config_flow.py @@ -388,6 +388,99 @@ async def test_discovery_flow_updates_new_ip( assert mock_config_entry.data[CONF_IP_ADDRESS] == "1.0.0.127" +@pytest.mark.parametrize( + ("current_ip_address", "discovered_ip_addresses", "expected_ip_address"), + [ + # Keep the configured IPv4 address while it's still advertised + ("127.0.0.1", ["2001:db8::1", "127.0.0.1"], "127.0.0.1"), + # Keep a configured IPv6 address while it's still advertised + ("2001:db8::1", ["127.0.0.1", "2001:db8::1"], "2001:db8::1"), + # Prefer IPv4 when the configured address isn't advertised anymore + ( + "127.0.0.1", + ["2001:db8::1", "fe80::1", "169.254.1.1", "1.0.0.127"], + "1.0.0.127", + ), + ("2001:db8::1", ["2001:db8::2", "1.0.0.127"], "1.0.0.127"), + ("p1meter.local", ["2001:db8::1", "1.0.0.127"], "1.0.0.127"), + # Use IPv6 when the device doesn't advertise an IPv4 address + ("127.0.0.1", ["2001:db8::1", "fe80::1"], "2001:db8::1"), + ], +) +async def test_discovery_flow_selects_ip_address( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + current_ip_address: str, + discovered_ip_addresses: list[str], + expected_ip_address: str, +) -> None: + """Test discovery keeps the configured address or prefers IPv4.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, + data={**mock_config_entry.data, CONF_IP_ADDRESS: current_ip_address}, + ) + ip_addresses = [ip_address(address) for address in discovered_ip_addresses] + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_ZEROCONF}, + data=ZeroconfServiceInfo( + ip_address=ip_addresses[0], + ip_addresses=ip_addresses, + port=80, + hostname="p1meter-ddeeff.local.", + type="", + name="", + properties={ + "api_enabled": "1", + "path": "/api/v1", + "product_name": "P1 Meter", + "product_type": "HWE-P1", + "serial": "5c2fafabcdef", + }, + ), + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + assert mock_config_entry.data[CONF_IP_ADDRESS] == expected_ip_address + + +@pytest.mark.usefixtures("mock_homewizardenergy", "mock_setup_entry") +async def test_discovery_flow_new_device_prefers_ipv4(hass: HomeAssistant) -> None: + """Test discovery of a new device uses its IPv4 address.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_ZEROCONF}, + data=ZeroconfServiceInfo( + ip_address=ip_address("2001:db8::1"), + ip_addresses=[ip_address("2001:db8::1"), ip_address("127.0.0.1")], + port=80, + hostname="p1meter-ddeeff.local.", + type="", + name="", + properties={ + "api_enabled": "1", + "path": "/api/v1", + "product_name": "P1 meter", + "product_type": "HWE-P1", + "serial": "5c2fafabcdef", + }, + ), + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "discovery_confirm" + + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "HWE-P1_5c2fafabcdef" + assert result["data"][CONF_IP_ADDRESS] == "127.0.0.1" + + @pytest.mark.usefixtures("mock_homewizardenergy", "mock_setup_entry") async def test_manual_flow_ignores_pending_discovery_for_same_device( hass: HomeAssistant,