diff --git a/homeassistant/components/twinkly/config_flow.py b/homeassistant/components/twinkly/config_flow.py index 5f56377423e7..f2582698f13e 100644 --- a/homeassistant/components/twinkly/config_flow.py +++ b/homeassistant/components/twinkly/config_flow.py @@ -1,14 +1,15 @@ """Config flow to configure the Twinkly integration.""" import logging -from typing import Any, override +from typing import TYPE_CHECKING, Any, override from aiohttp import ClientError from probatio import Required, Schema from ttls.client import Twinkly -from homeassistant.config_entries import ConfigFlow, ConfigFlowResult +from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_ID, CONF_MODEL, CONF_NAME +from homeassistant.helpers import device_registry as dr from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo @@ -38,11 +39,7 @@ class TwinklyConfigFlow(ConfigFlow, domain=DOMAIN): errors = {} if host is not None: - try: - device_info = await Twinkly( - host, async_get_clientsession(self.hass), timeout=DEVICE_TIMEOUT - ).get_details() - except TimeoutError, ClientError: + if (device_info := await self._async_get_device_info(host)) is None: errors[CONF_HOST] = "cannot_connect" else: await self.async_set_unique_id( @@ -56,6 +53,69 @@ class TwinklyConfigFlow(ConfigFlow, domain=DOMAIN): step_id="user", data_schema=Schema(schema), errors=errors ) + async def async_step_reconfigure( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle reconfiguration of the device host.""" + reconfigure_entry = self._get_reconfigure_entry() + errors: dict[str, str] = {} + + if user_input is not None: + device_info = await self._async_get_device_info(user_input[CONF_HOST]) + if device_info is None: + errors[CONF_HOST] = "cannot_connect" + else: + if reconfigure_entry.minor_version == 1: + # The MAC migration has not run yet, so the unique ID is the + # device UUID, which is not unique across devices + if self._get_registered_mac(reconfigure_entry) != ( + dr.format_mac(device_info["mac"]) + ): + return self.async_abort(reason="unique_id_mismatch") + else: + await self.async_set_unique_id(device_info["mac"]) + self._abort_if_unique_id_mismatch() + return self.async_update_reload_and_abort( + reconfigure_entry, data_updates=user_input + ) + + return self.async_show_form( + step_id="reconfigure", + data_schema=self.add_suggested_values_to_schema( + Schema({Required(CONF_HOST): str}), + user_input or reconfigure_entry.data, + ), + errors=errors, + ) + + def _get_registered_mac(self, entry: ConfigEntry) -> str | None: + """Return the MAC address stored in the device registry for the entry.""" + if TYPE_CHECKING: + assert entry.unique_id is not None + device_registry = dr.async_get(self.hass) + device = device_registry.async_get_device_by_identifier( + (DOMAIN, entry.unique_id), entry.entry_id + ) + if device is None: + return None + return next( + ( + value + for connection_type, value in device.connections + if connection_type == dr.CONNECTION_NETWORK_MAC + ), + None, + ) + + async def _async_get_device_info(self, host: str) -> dict[str, Any] | None: + """Fetch the device details, or None if the device cannot be reached.""" + try: + return await Twinkly( + host, async_get_clientsession(self.hass), timeout=DEVICE_TIMEOUT + ).get_details() + except TimeoutError, ClientError: + return None + @override async def async_step_dhcp( self, discovery_info: DhcpServiceInfo diff --git a/homeassistant/components/twinkly/strings.json b/homeassistant/components/twinkly/strings.json index a1940ef17073..9c0af0723ef5 100644 --- a/homeassistant/components/twinkly/strings.json +++ b/homeassistant/components/twinkly/strings.json @@ -2,7 +2,8 @@ "config": { "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", - "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]" + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "unique_id_mismatch": "Please ensure you reconfigure against the same device." }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]" @@ -12,6 +13,14 @@ "discovery_confirm": { "description": "Do you want to set up {name} - {model} ({host})?" }, + "reconfigure": { + "data": { + "host": "[%key:common::config_flow::data::host%]" + }, + "data_description": { + "host": "[%key:component::twinkly::config::step::user::data_description::host%]" + } + }, "user": { "data": { "host": "[%key:common::config_flow::data::host%]" diff --git a/tests/components/twinkly/test_config_flow.py b/tests/components/twinkly/test_config_flow.py index 281c8c0f54dc..86399be8f9c6 100644 --- a/tests/components/twinkly/test_config_flow.py +++ b/tests/components/twinkly/test_config_flow.py @@ -2,14 +2,16 @@ from unittest.mock import AsyncMock +from aiohttp import ClientError import pytest from pytest_homeassistant.common import MockConfigEntry from homeassistant.components.twinkly.const import DOMAIN -from homeassistant.config_entries import SOURCE_DHCP, SOURCE_USER +from homeassistant.config_entries import SOURCE_DHCP, SOURCE_USER, ConfigEntryState from homeassistant.const import CONF_HOST, CONF_ID, CONF_MODEL, CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType +from homeassistant.helpers import device_registry as dr from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from .const import TEST_MAC, TEST_MODEL, TEST_NAME @@ -188,3 +190,190 @@ async def test_user_flow_works_discovery(hass: HomeAssistant) -> None: # Verify the discovery flow was aborted assert not hass.config_entries.flow.async_progress(DOMAIN) + + +@pytest.mark.usefixtures("mock_twinkly_client", "mock_setup_entry") +async def test_reconfigure_flow( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test reconfiguring the device host.""" + mock_config_entry.add_to_hass(hass) + + result = await mock_config_entry.start_reconfigure_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reconfigure" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_HOST: "192.168.0.124"}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert mock_config_entry.data == { + CONF_HOST: "192.168.0.124", + CONF_ID: "497dcba3-ecbf-4587-a2dd-5eb0665e6880", + CONF_NAME: TEST_NAME, + CONF_MODEL: TEST_MODEL, + } + + +@pytest.mark.usefixtures("mock_setup_entry") +@pytest.mark.parametrize( + "exception", + [ + pytest.param(TimeoutError, id="timeout"), + pytest.param(ClientError, id="client_error"), + ], +) +async def test_reconfigure_flow_cannot_connect( + hass: HomeAssistant, + mock_twinkly_client: AsyncMock, + mock_config_entry: MockConfigEntry, + exception: type[Exception], +) -> None: + """Test reconfigure flow recovers from connection errors.""" + mock_config_entry.add_to_hass(hass) + + result = await mock_config_entry.start_reconfigure_flow(hass) + + mock_twinkly_client.get_details.side_effect = exception + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_HOST: "192.168.0.124"}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reconfigure" + assert result["errors"] == {CONF_HOST: "cannot_connect"} + + mock_twinkly_client.get_details.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_HOST: "192.168.0.124"}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert mock_config_entry.data[CONF_HOST] == "192.168.0.124" + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reconfigure_flow_unique_id_mismatch( + hass: HomeAssistant, + mock_twinkly_client: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test reconfigure flow aborts when pointed at a different device.""" + mock_config_entry.add_to_hass(hass) + + result = await mock_config_entry.start_reconfigure_flow(hass) + + mock_twinkly_client.get_details.return_value = { + **mock_twinkly_client.get_details.return_value, + "mac": "aa:bb:cc:dd:ee:ff", + } + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_HOST: "192.168.0.124"}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unique_id_mismatch" + assert mock_config_entry.data[CONF_HOST] == "192.168.0.123" + + +LEGACY_DEVICE_ID = "00000000-0000-0000-0000-000000000000" + + +@pytest.mark.parametrize( + ("identifier", "connections", "reason", "state", "unique_id", "host"), + [ + pytest.param( + LEGACY_DEVICE_ID, + {(dr.CONNECTION_NETWORK_MAC, TEST_MAC)}, + "reconfigure_successful", + ConfigEntryState.LOADED, + TEST_MAC, + "192.168.0.124", + id="same_device", + ), + pytest.param( + LEGACY_DEVICE_ID, + {(dr.CONNECTION_NETWORK_MAC, "aa:bb:cc:dd:ee:ff")}, + "unique_id_mismatch", + ConfigEntryState.SETUP_RETRY, + LEGACY_DEVICE_ID, + "192.168.0.123", + id="other_device_same_uuid", + ), + pytest.param( + LEGACY_DEVICE_ID, + set(), + "unique_id_mismatch", + ConfigEntryState.SETUP_RETRY, + LEGACY_DEVICE_ID, + "192.168.0.123", + id="no_registered_mac", + ), + pytest.param( + "11111111-1111-1111-1111-111111111111", + {(dr.CONNECTION_NETWORK_MAC, TEST_MAC)}, + "unique_id_mismatch", + ConfigEntryState.SETUP_RETRY, + LEGACY_DEVICE_ID, + "192.168.0.123", + id="no_registered_device", + ), + ], +) +async def test_reconfigure_flow_before_mac_migration( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + mock_twinkly_client: AsyncMock, + identifier: str, + connections: set[tuple[str, str]], + reason: str, + state: ConfigEntryState, + unique_id: str, + host: str, +) -> None: + """Test reconfiguring an entry that still has its legacy unique ID.""" + # The device is unreachable at its old address, so the migration is pending + mock_twinkly_client.get_details.side_effect = TimeoutError + entry = MockConfigEntry( + domain=DOMAIN, + minor_version=1, + unique_id=LEGACY_DEVICE_ID, + data={ + CONF_HOST: "192.168.0.123", + CONF_ID: LEGACY_DEVICE_ID, + CONF_NAME: TEST_NAME, + CONF_MODEL: TEST_MODEL, + }, + ) + entry.add_to_hass(hass) + device_registry.async_get_or_create( + config_entry_id=entry.entry_id, + identifiers={(DOMAIN, identifier)}, + connections=connections, + ) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.SETUP_RETRY + + result = await entry.start_reconfigure_flow(hass) + + # The fixture reports the same legacy UUID, only the MAC tells devices apart + mock_twinkly_client.get_details.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_HOST: "192.168.0.124"}, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason + assert entry.state is state + assert entry.unique_id == unique_id + assert entry.data[CONF_HOST] == host