Add reconfigure flow to Watergate (#189370)

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
adam-the-hero
2026-10-29 09:30:27 +01:00
committed by GitHub
co-authored by Claude Sonnet 5.5
parent 96afd04c9d
commit 12167c1387
4 changed files with 174 additions and 23 deletions
@@ -29,6 +29,26 @@ WATERGATE_SCHEMA = probatio.Schema(
class WatergateConfigFlow(ConfigFlow, domain=DOMAIN):
"""Watergate config flow."""
async def _async_get_serial_number(
self, ip_address: str, errors: dict[str, str]
) -> str | None:
"""Return the device serial number or record a connection error."""
watergate_client = WatergateLocalApiClient(
base_url=self.prepare_ip_address(ip_address),
session=async_get_clientsession(self.hass),
)
try:
state = await watergate_client.async_get_device_state()
except WatergateApiException as exception:
_LOGGER.error("Error connecting to Watergate device: %s", exception)
errors[CONF_IP_ADDRESS] = "cannot_connect"
return None
if state is None:
_LOGGER.error("Device state returned as None")
errors[CONF_IP_ADDRESS] = "cannot_connect"
return None
return state.serial_number
@override
async def async_step_user(
self, user_input: dict[str, str] | None = None
@@ -36,31 +56,46 @@ class WatergateConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a flow initiated by the user."""
errors: dict[str, str] = {}
if user_input is not None:
watergate_client = WatergateLocalApiClient(
base_url=self.prepare_ip_address(user_input[CONF_IP_ADDRESS]),
session=async_get_clientsession(self.hass),
serial_number = await self._async_get_serial_number(
user_input[CONF_IP_ADDRESS], errors
)
try:
state = await watergate_client.async_get_device_state()
except WatergateApiException as exception:
_LOGGER.error("Error connecting to Watergate device: %s", exception)
errors[CONF_IP_ADDRESS] = "cannot_connect"
else:
if state is None:
_LOGGER.error("Device state returned as None")
errors[CONF_IP_ADDRESS] = "cannot_connect"
else:
await self.async_set_unique_id(state.serial_number)
self._abort_if_unique_id_configured()
return self.async_create_entry(
data={**user_input, CONF_WEBHOOK_ID: webhook_generate_id()},
title=SONIC,
)
if serial_number is not None:
await self.async_set_unique_id(serial_number)
self._abort_if_unique_id_configured()
return self.async_create_entry(
data={**user_input, CONF_WEBHOOK_ID: webhook_generate_id()},
title=SONIC,
)
return self.async_show_form(
step_id="user", data_schema=WATERGATE_SCHEMA, errors=errors
)
async def async_step_reconfigure(
self, user_input: dict[str, str] | None = None
) -> ConfigFlowResult:
"""Handle reconfiguration of the device IP address."""
errors: dict[str, str] = {}
entry = self._get_reconfigure_entry()
if user_input is not None:
serial_number = await self._async_get_serial_number(
user_input[CONF_IP_ADDRESS], errors
)
if serial_number is not None:
await self.async_set_unique_id(serial_number)
self._abort_if_unique_id_mismatch(reason="wrong_device")
return self.async_update_reload_and_abort(
entry, data_updates=user_input
)
return self.async_show_form(
step_id="reconfigure",
data_schema=self.add_suggested_values_to_schema(
WATERGATE_SCHEMA, user_input or entry.data
),
errors=errors,
)
def prepare_ip_address(self, ip_address: str) -> str:
"""Prepare the IP address for the Watergate device."""
return ip_address if ip_address.startswith("http") else f"http://{ip_address}"
@@ -68,7 +68,7 @@ rules:
entity-translations: done
exception-translations: todo
icon-translations: done
reconfiguration-flow: todo
reconfiguration-flow: done
repair-issues: todo
stale-devices: todo
@@ -1,12 +1,22 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"wrong_device": "The device at this address is not the one that was originally configured."
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]"
},
"step": {
"reconfigure": {
"data": {
"ip_address": "[%key:common::config_flow::data::ip%]"
},
"data_description": {
"ip_address": "[%key:component::watergate::config::step::user::data_description::ip_address%]"
},
"title": "Reconfigure Watergate device"
},
"user": {
"data": {
"ip_address": "[%key:common::config_flow::data::ip%]"
+108 -2
View File
@@ -5,13 +5,19 @@ from collections.abc import Generator
import pytest
from pytest_homeassistant.common import AsyncMock, HomeAssistant, MockConfigEntry
from watergate_local_api import WatergateApiException
from watergate_local_api.models import DeviceState
from homeassistant.components.watergate.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.config_entries import SOURCE_USER, ConfigEntryState
from homeassistant.const import CONF_IP_ADDRESS, CONF_WEBHOOK_ID
from homeassistant.data_entry_flow import FlowResultType
from .const import DEFAULT_DEVICE_STATE, DEFAULT_SERIAL_NUMBER, MOCK_WEBHOOK_ID
from .const import (
DEFAULT_DEVICE_STATE,
DEFAULT_SERIAL_NUMBER,
MOCK_CONFIG,
MOCK_WEBHOOK_ID,
)
async def test_step_user_form(
@@ -104,3 +110,103 @@ async def test_abort_if_id_is_not_unique(
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reconfigure_success(
hass: HomeAssistant,
mock_watergate_client: Generator[AsyncMock],
mock_entry: MockConfigEntry,
user_input: dict[str, str],
) -> None:
"""Test reconfiguring the IP address reloads the entry with the new host."""
mock_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
assert mock_entry.state is ConfigEntryState.LOADED
result = await mock_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
(ip_key,) = result["data_schema"].schema
assert ip_key.description == {"suggested_value": "http://localhost"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_entry.data[CONF_IP_ADDRESS] == user_input[CONF_IP_ADDRESS]
assert mock_entry.data[CONF_WEBHOOK_ID] == MOCK_WEBHOOK_ID
assert mock_entry.state is ConfigEntryState.LOADED
# The reload re-ran setup, which registers the webhook URL on the device again.
assert mock_watergate_client.async_set_webhook_url.await_count == 2
@pytest.mark.parametrize(
"client_result",
[AsyncMock(return_value=None), AsyncMock(side_effect=WatergateApiException)],
)
async def test_reconfigure_cannot_connect_then_success(
hass: HomeAssistant,
mock_watergate_client: Generator[AsyncMock],
mock_entry: MockConfigEntry,
user_input: dict[str, str],
client_result: AsyncMock,
) -> None:
"""Test connection errors are shown and the flow recovers on retry."""
mock_entry.add_to_hass(hass)
mock_watergate_client.async_get_device_state = client_result
result = await mock_entry.start_reconfigure_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"][CONF_IP_ADDRESS] == "cannot_connect"
mock_watergate_client.async_get_device_state = AsyncMock(
return_value=DEFAULT_DEVICE_STATE
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_entry.data[CONF_IP_ADDRESS] == user_input[CONF_IP_ADDRESS]
async def test_reconfigure_wrong_device(
hass: HomeAssistant,
mock_watergate_client: Generator[AsyncMock],
mock_entry: MockConfigEntry,
user_input: dict[str, str],
) -> None:
"""Test reconfiguring to a different physical device is refused."""
mock_entry.add_to_hass(hass)
other_state = DeviceState(
"open",
"on",
True,
True,
"battery",
"1.0.0",
100,
DEFAULT_DEVICE_STATE.water_meter,
"another_serial",
)
mock_watergate_client.async_get_device_state = AsyncMock(return_value=other_state)
result = await mock_entry.start_reconfigure_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "wrong_device"
assert mock_entry.data[CONF_IP_ADDRESS] == MOCK_CONFIG[CONF_IP_ADDRESS]