diff --git a/homeassistant/components/otbr/config_flow.py b/homeassistant/components/otbr/config_flow.py index 500ff8ab65ab..9b1ad1b69039 100644 --- a/homeassistant/components/otbr/config_flow.py +++ b/homeassistant/components/otbr/config_flow.py @@ -16,6 +16,7 @@ from homeassistant.components.homeassistant_yellow import hardware as yellow_har from homeassistant.components.thread import async_get_preferred_dataset from homeassistant.config_entries import ( SOURCE_HASSIO, + SOURCE_RECONFIGURE, ConfigEntry, ConfigEntryState, ConfigFlow, @@ -121,6 +122,8 @@ class OTBRConfigFlow(ConfigFlow, domain=DOMAIN): """Return True if another config entry's OTBR has the same border agent id.""" config_entry: OTBRConfigEntry for config_entry in self.hass.config_entries.async_loaded_entries(DOMAIN): + if config_entry.entry_id == self.context.get("entry_id"): + continue data = config_entry.runtime_data try: other_border_agent_id = await data.get_border_agent_id() @@ -148,6 +151,10 @@ class OTBRConfigFlow(ConfigFlow, domain=DOMAIN): border_agent_id = await api.get_border_agent_id() _LOGGER.debug("border agent id for url %s: %s", otbr_url, border_agent_id.hex()) + if self.source == SOURCE_RECONFIGURE: + await self.async_set_unique_id(border_agent_id.hex()) + self._abort_if_unique_id_mismatch() + if await self._is_border_agent_id_configured(border_agent_id): raise AlreadyConfigured @@ -187,6 +194,47 @@ class OTBRConfigFlow(ConfigFlow, domain=DOMAIN): step_id="user", data_schema=data_schema, errors=errors ) + async def async_step_reconfigure( + self, user_input: dict[str, str] | None = None + ) -> ConfigFlowResult: + """Handle reconfiguration of the OTBR URL.""" + errors = {} + entry = self._get_reconfigure_entry() + + if entry.source == SOURCE_HASSIO: + return self.async_abort(reason="addon_managed") + + if user_input is not None: + url = user_input[CONF_URL].rstrip("/") + try: + await self._connect_and_configure_router(url) + except AlreadyConfigured: + errors["base"] = "already_configured" + except ( + python_otbr_api.OTBRError, + aiohttp.ClientError, + TimeoutError, + ) as exc: + _LOGGER.debug("Failed to communicate with OTBR@%s: %s", url, exc) + errors["base"] = "cannot_connect" + else: + # The update listener is only registered after a successful setup + if entry.update_listeners: + return self.async_update_and_abort( + entry, data_updates={CONF_URL: url} + ) + return self.async_update_reload_and_abort( + entry, data_updates={CONF_URL: url} + ) + + return self.async_show_form( + step_id="reconfigure", + data_schema=self.add_suggested_values_to_schema( + probatio.Schema({CONF_URL: str}), user_input or entry.data + ), + errors=errors, + ) + @callback def _async_find_legacy_entry_by_host(self, host: str) -> ConfigEntry | None: """Return an entry created by the first version of the integration. diff --git a/homeassistant/components/otbr/strings.json b/homeassistant/components/otbr/strings.json index 6cf1716dc556..f4fbf8b52d81 100644 --- a/homeassistant/components/otbr/strings.json +++ b/homeassistant/components/otbr/strings.json @@ -1,7 +1,9 @@ { "config": { "abort": { + "addon_managed": "This Thread border router is managed by an app. Its URL is updated automatically.", "already_configured": "The Thread border router is already configured", + "unique_id_mismatch": "The Thread border router at this URL is not the one that was originally set up.", "unknown": "[%key:common::config_flow::error::unknown%]" }, "error": { @@ -9,6 +11,12 @@ "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]" }, "step": { + "reconfigure": { + "data": { + "url": "[%key:common::config_flow::data::url%]" + }, + "description": "[%key:component::otbr::config::step::user::description%]" + }, "user": { "data": { "url": "[%key:common::config_flow::data::url%]" diff --git a/tests/components/otbr/test_config_flow.py b/tests/components/otbr/test_config_flow.py index 9a74d1402598..7265c7d5fdf0 100644 --- a/tests/components/otbr/test_config_flow.py +++ b/tests/components/otbr/test_config_flow.py @@ -1238,3 +1238,201 @@ async def test_hassio_discovery_reload( assert len(callback.mock_calls) == 2 assert len(hass.config_entries.async_entries(otbr.DOMAIN)) == 1 + + +async def _setup_user_entry(hass: HomeAssistant) -> MockConfigEntry: + """Set up a config entry created by the user flow.""" + mock_integration(hass, MockModule("hassio")) + config_entry = MockConfigEntry( + data={"url": "http://custom_url:1234"}, + domain=otbr.DOMAIN, + options={}, + source="user", + title="OpenThread Border Router", + unique_id=TEST_BORDER_AGENT_ID.hex(), + ) + config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(config_entry.entry_id) + return config_entry + + +@pytest.mark.usefixtures( + "get_active_dataset_tlvs", + "get_border_agent_id", + "get_extended_address", + "get_coprocessor_version", +) +async def test_reconfigure_flow(hass: HomeAssistant) -> None: + """Test the reconfigure flow.""" + config_entry = await _setup_user_entry(hass) + + result = await 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"], {"url": "http://new_url:1234/"} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert config_entry.data == {"url": "http://new_url:1234"} + assert config_entry.state is ConfigEntryState.LOADED + + +@pytest.mark.usefixtures( + "get_active_dataset_tlvs", + "get_extended_address", + "get_coprocessor_version", +) +async def test_reconfigure_flow_setup_retry( + hass: HomeAssistant, get_border_agent_id: AsyncMock +) -> None: + """Test the reconfigure flow reloads an entry that failed to set up.""" + mock_integration(hass, MockModule("hassio")) + config_entry = MockConfigEntry( + data={"url": "http://custom_url:1234"}, + domain=otbr.DOMAIN, + options={}, + source="user", + title="OpenThread Border Router", + unique_id=TEST_BORDER_AGENT_ID.hex(), + ) + config_entry.add_to_hass(hass) + get_border_agent_id.side_effect = TimeoutError + assert not await hass.config_entries.async_setup(config_entry.entry_id) + assert config_entry.state is ConfigEntryState.SETUP_RETRY + + get_border_agent_id.side_effect = None + result = await config_entry.start_reconfigure_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"url": "http://new_url:1234"} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert config_entry.data == {"url": "http://new_url:1234"} + assert config_entry.state is ConfigEntryState.LOADED + + +@pytest.mark.parametrize( + "error", + [ + pytest.param(TimeoutError, id="timeout"), + pytest.param(python_otbr_api.OTBRError, id="otbr_error"), + pytest.param(aiohttp.ClientError, id="client_error"), + ], +) +@pytest.mark.usefixtures( + "get_active_dataset_tlvs", + "get_extended_address", + "get_coprocessor_version", +) +async def test_reconfigure_flow_cannot_connect( + hass: HomeAssistant, get_border_agent_id: AsyncMock, error: type[Exception] +) -> None: + """Test the reconfigure flow recovers from a connection error.""" + config_entry = await _setup_user_entry(hass) + + result = await config_entry.start_reconfigure_flow(hass) + get_border_agent_id.side_effect = error + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"url": "http://new_url:1234"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reconfigure" + assert result["errors"] == {"base": "cannot_connect"} + + get_border_agent_id.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"url": "http://new_url:1234"} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert config_entry.data == {"url": "http://new_url:1234"} + + +@pytest.mark.usefixtures( + "get_active_dataset_tlvs", + "get_border_agent_id", + "get_extended_address", + "get_coprocessor_version", +) +async def test_reconfigure_flow_already_configured(hass: HomeAssistant) -> None: + """Test the reconfigure flow when another entry uses the same router.""" + config_entry = await _setup_user_entry(hass) + # The mocked router reports the same border agent id for every URL + other_entry = MockConfigEntry( + data={"url": "http://other_url:1234"}, + domain=otbr.DOMAIN, + options={}, + source="user", + title="OpenThread Border Router", + unique_id=TEST_BORDER_AGENT_ID_2.hex(), + ) + other_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(other_entry.entry_id) + + result = await config_entry.start_reconfigure_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"url": "http://new_url:1234"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reconfigure" + assert result["errors"] == {"base": "already_configured"} + + assert await hass.config_entries.async_remove(other_entry.entry_id) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"url": "http://new_url:1234"} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert config_entry.data == {"url": "http://new_url:1234"} + + +@pytest.mark.usefixtures( + "get_active_dataset_tlvs", + "get_extended_address", + "get_coprocessor_version", +) +async def test_reconfigure_flow_unique_id_mismatch( + hass: HomeAssistant, get_border_agent_id: AsyncMock +) -> None: + """Test the reconfigure flow aborts when pointed at another router.""" + config_entry = await _setup_user_entry(hass) + + result = await config_entry.start_reconfigure_flow(hass) + get_border_agent_id.return_value = TEST_BORDER_AGENT_ID_2 + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"url": "http://new_url:1234"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unique_id_mismatch" + assert config_entry.data == {"url": "http://custom_url:1234"} + + +async def test_reconfigure_flow_addon_managed(hass: HomeAssistant) -> None: + """Test the reconfigure flow aborts for entries managed by an app.""" + config_entry = MockConfigEntry( + data={"url": "http://core-silabs-multiprotocol:8081"}, + domain=otbr.DOMAIN, + options={}, + source="hassio", + title="Silicon Labs Multiprotocol", + unique_id=HASSIO_DATA.uuid, + ) + config_entry.add_to_hass(hass) + + result = await config_entry.start_reconfigure_flow(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "addon_managed"