Simplify onewire config-flow (#134952)

This commit is contained in:
epenet 2025-01-07 13:22:16 +01:00 committed by GitHub
parent 5d2a8e8208
commit 30695cfef5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -39,21 +39,16 @@ DATA_SCHEMA = vol.Schema(
) )
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, str]: async def validate_input(
"""Validate the user input allows us to connect. hass: HomeAssistant, data: dict[str, Any], errors: dict[str, str]
) -> None:
Data has the keys from DATA_SCHEMA with values provided by the user. """Validate the user input allows us to connect."""
"""
hub = OneWireHub(hass) hub = OneWireHub(hass)
try:
host = data[CONF_HOST] await hub.connect(data[CONF_HOST], data[CONF_PORT])
port = data[CONF_PORT] except CannotConnect:
# Raises CannotConnect exception on failure errors["base"] = "cannot_connect"
await hub.connect(host, port)
# Return info that you want to store in the config entry.
return {"title": host}
class OneWireFlowHandler(ConfigFlow, domain=DOMAIN): class OneWireFlowHandler(ConfigFlow, domain=DOMAIN):
@ -61,41 +56,24 @@ class OneWireFlowHandler(ConfigFlow, domain=DOMAIN):
VERSION = 1 VERSION = 1
def __init__(self) -> None:
"""Initialize 1-Wire config flow."""
self.onewire_config: dict[str, Any] = {}
async def async_step_user( async def async_step_user(
self, user_input: dict[str, Any] | None = None self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult: ) -> ConfigFlowResult:
"""Handle 1-Wire config flow start. """Handle 1-Wire config flow start."""
Let user manually input configuration.
"""
errors: dict[str, str] = {} errors: dict[str, str] = {}
if user_input: if user_input:
# Prevent duplicate entries # Prevent duplicate entries (host+port)
self._async_abort_entries_match( self._async_abort_entries_match(user_input)
{
CONF_HOST: user_input[CONF_HOST],
CONF_PORT: user_input[CONF_PORT],
}
)
self.onewire_config.update(user_input) await validate_input(self.hass, user_input, errors)
if not errors:
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
else:
return self.async_create_entry( return self.async_create_entry(
title=info["title"], data=self.onewire_config title=user_input[CONF_HOST], data=user_input
) )
return self.async_show_form( return self.async_show_form(
step_id="user", step_id="user",
data_schema=DATA_SCHEMA, data_schema=self.add_suggested_values_to_schema(DATA_SCHEMA, user_input),
errors=errors, errors=errors,
) )