Add reconfiguration flow in HomeWizard (#131535)

This commit is contained in:
Duco Sebel 2024-11-26 19:20:50 +01:00 committed by GitHub
parent 7ba0f54412
commit a252faf9af
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 183 additions and 6 deletions

View File

@ -9,7 +9,7 @@ from typing import Any, NamedTuple
from homewizard_energy import HomeWizardEnergyV1
from homewizard_energy.errors import DisabledError, RequestError, UnsupportedError
from homewizard_energy.v1.models import Device
from voluptuous import Required, Schema
import voluptuous as vol
from homeassistant.components import onboarding, zeroconf
from homeassistant.components.dhcp import DhcpServiceInfo
@ -17,6 +17,7 @@ from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_IP_ADDRESS, CONF_PATH
from homeassistant.data_entry_flow import AbortFlow
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.selector import TextSelector
from .const import (
CONF_API_ENABLED,
@ -69,11 +70,11 @@ class HomeWizardConfigFlow(ConfigFlow, domain=DOMAIN):
user_input = user_input or {}
return self.async_show_form(
step_id="user",
data_schema=Schema(
data_schema=vol.Schema(
{
Required(
vol.Required(
CONF_IP_ADDRESS, default=user_input.get(CONF_IP_ADDRESS)
): str,
): TextSelector(),
}
),
errors=errors,
@ -197,6 +198,43 @@ class HomeWizardConfigFlow(ConfigFlow, domain=DOMAIN):
return self.async_show_form(step_id="reauth_confirm", errors=errors)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfiguration of the integration."""
errors: dict[str, str] = {}
if user_input:
try:
device_info = await self._async_try_connect(user_input[CONF_IP_ADDRESS])
except RecoverableError as ex:
_LOGGER.error(ex)
errors = {"base": ex.error_code}
else:
await self.async_set_unique_id(
f"{device_info.product_type}_{device_info.serial}"
)
self._abort_if_unique_id_mismatch(reason="wrong_device")
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(),
data_updates=user_input,
)
reconfigure_entry = self._get_reconfigure_entry()
return self.async_show_form(
step_id="reconfigure",
data_schema=vol.Schema(
{
vol.Required(
CONF_IP_ADDRESS,
default=reconfigure_entry.data.get(CONF_IP_ADDRESS),
): TextSelector(),
}
),
description_placeholders={
"title": reconfigure_entry.title,
},
errors=errors,
)
@staticmethod
async def _async_try_connect(ip_address: str) -> Device:
"""Try to connect.

View File

@ -65,7 +65,7 @@ rules:
entity-translations: done
exception-translations: done
icon-translations: done
reconfiguration-flow: todo
reconfiguration-flow: done
repair-issues:
status: exempt
comment: |

View File

@ -17,6 +17,15 @@
},
"reauth_confirm": {
"description": "The local API is disabled. Go to the HomeWizard Energy app and enable the API in the device settings."
},
"reconfigure": {
"description": "Update configuration for {title}.",
"data": {
"ip_address": "[%key:common::config_flow::data::ip%]"
},
"data_description": {
"ip_address": "[%key:component::homewizard::config::step::user::data_description::ip_address%]"
}
}
},
"error": {
@ -29,7 +38,9 @@
"device_not_supported": "This device is not supported",
"unknown_error": "[%key:common::config_flow::error::unknown%]",
"unsupported_api_version": "Detected unsupported API version",
"reauth_successful": "Enabling API was successful"
"reauth_successful": "Enabling API was successful",
"reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]",
"wrong_device": "The configured device is not the same found on this IP address."
}
},
"entity": {

View File

@ -480,3 +480,131 @@ async def test_reauth_error(
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "api_not_enabled"}
async def test_reconfigure(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration."""
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"
assert result["errors"] == {}
# original entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "127.0.0.1"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "1.0.0.127",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
# changed entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "1.0.0.127"
async def test_reconfigure_nochange(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration without changing values."""
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"
assert result["errors"] == {}
# original entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "127.0.0.1"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "127.0.0.1",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
# changed entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "127.0.0.1"
async def test_reconfigure_wrongdevice(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test entering ip of other device and prevent changing it based on serial."""
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"
assert result["errors"] == {}
# simulate different serial number, as if user entered wrong IP
mock_homewizardenergy.device.return_value.serial = "not_5c2fafabcdef"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "1.0.0.127",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "wrong_device"
# entry should still be original entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "127.0.0.1"
@pytest.mark.parametrize(
("exception", "reason"),
[(DisabledError, "api_not_enabled"), (RequestError, "network_error")],
)
async def test_reconfigure_cannot_connect(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test reconfiguration fails when not able to connect."""
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"
assert result["errors"] == {}
mock_homewizardenergy.device.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "1.0.0.127",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
assert result["data_schema"]({}) == {CONF_IP_ADDRESS: "127.0.0.1"}
# attempt with valid IP should work
mock_homewizardenergy.device.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "1.0.0.127",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
# changed entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "1.0.0.127"