Add reconfigure flow to Coolmaster (#177995)

Co-authored-by: Erwin Douna <e.douna@gmail.com>
This commit is contained in:
Doug Rathbone
2026-08-06 15:15:57 +02:00
committed by GitHub
co-authored by Erwin Douna
parent f05e9b77f6
commit e967d992eb
3 changed files with 372 additions and 69 deletions
@@ -48,8 +48,8 @@ DATA_SCHEMA = vol.Schema(
)
async def _validate_connection(host: str, send_wakeup_prompt: bool) -> bool:
cool = CoolMasterNet(host, DEFAULT_PORT, send_initial_line_feed=send_wakeup_prompt)
async def _validate_connection(host: str, port: int, send_wakeup_prompt: bool) -> bool:
cool = CoolMasterNet(host, port, send_initial_line_feed=send_wakeup_prompt)
units = await cool.status()
return bool(units)
@@ -62,15 +62,14 @@ class CoolmasterConfigFlow(ConfigFlow, domain=DOMAIN):
@callback
def _async_get_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
more_options = data.get(CONF_MORE_OPTIONS, {})
supported_modes = [
key for (key, value) in data.items() if key in AVAILABLE_MODES and value
]
return self.async_create_entry(
title=data[CONF_HOST],
data={
CONF_HOST: data[CONF_HOST],
CONF_PORT: DEFAULT_PORT,
CONF_SUPPORTED_MODES: supported_modes,
CONF_SUPPORTED_MODES: [
mode for mode in AVAILABLE_MODES if data.get(mode)
],
CONF_SWING_SUPPORT: data[CONF_SWING_SUPPORT],
CONF_SEND_WAKEUP_PROMPT: more_options.get(
CONF_SEND_WAKEUP_PROMPT, False
@@ -78,6 +77,25 @@ class CoolmasterConfigFlow(ConfigFlow, domain=DOMAIN):
},
)
async def _async_validate_input(
self, user_input: dict[str, Any], port: int
) -> dict[str, str]:
"""Check we can still talk to the bridge and that it reports units."""
more_options = user_input.get(CONF_MORE_OPTIONS, {})
errors: dict[str, str] = {}
try:
has_units = await _validate_connection(
user_input[CONF_HOST],
port,
more_options.get(CONF_SEND_WAKEUP_PROMPT, False),
)
except OSError:
errors["base"] = "cannot_connect"
else:
if not has_units:
errors["base"] = "no_units"
return errors
@override
async def async_step_user(
self, user_input: dict[str, Any] | None = None
@@ -88,23 +106,61 @@ class CoolmasterConfigFlow(ConfigFlow, domain=DOMAIN):
self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
errors = {}
host = user_input[CONF_HOST]
more_options = user_input.get(CONF_MORE_OPTIONS, {})
try:
result = await _validate_connection(
host, more_options.get(CONF_SEND_WAKEUP_PROMPT, False)
)
if not result:
errors["base"] = "no_units"
except OSError:
errors["base"] = "cannot_connect"
if errors:
if errors := await self._async_validate_input(user_input, DEFAULT_PORT):
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)
return self._async_get_entry(user_input)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfiguration of an existing entry."""
reconfigure_entry = self._get_reconfigure_entry()
entry_data = reconfigure_entry.data
errors: dict[str, str] = {}
if user_input is not None:
self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
more_options = user_input.get(CONF_MORE_OPTIONS, {})
# The port is not part of the form, so keep validating the stored one.
if not (
errors := await self._async_validate_input(
user_input, entry_data[CONF_PORT]
)
):
return self.async_update_reload_and_abort(
reconfigure_entry,
title=user_input[CONF_HOST],
data_updates={
CONF_HOST: user_input[CONF_HOST],
CONF_SUPPORTED_MODES: [
mode for mode in AVAILABLE_MODES if user_input.get(mode)
],
CONF_SWING_SUPPORT: user_input[CONF_SWING_SUPPORT],
CONF_SEND_WAKEUP_PROMPT: more_options.get(
CONF_SEND_WAKEUP_PROMPT, False
),
},
)
supported_modes = entry_data.get(CONF_SUPPORTED_MODES, AVAILABLE_MODES)
return self.async_show_form(
step_id="reconfigure",
data_schema=self.add_suggested_values_to_schema(
DATA_SCHEMA,
user_input
or {
CONF_HOST: entry_data[CONF_HOST],
**{mode: mode in supported_modes for mode in AVAILABLE_MODES},
CONF_SWING_SUPPORT: entry_data.get(CONF_SWING_SUPPORT, False),
CONF_MORE_OPTIONS: {
CONF_SEND_WAKEUP_PROMPT: entry_data.get(
CONF_SEND_WAKEUP_PROMPT, False
)
},
},
),
errors=errors,
)
@@ -1,13 +1,48 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]"
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"no_units": "Could not find any HVAC units in CoolMasterNet host."
},
"step": {
"reconfigure": {
"data": {
"cool": "[%key:component::coolmaster::config::step::user::data::cool%]",
"dry": "[%key:component::coolmaster::config::step::user::data::dry%]",
"fan_only": "[%key:component::coolmaster::config::step::user::data::fan_only%]",
"heat": "[%key:component::coolmaster::config::step::user::data::heat%]",
"heat_cool": "[%key:component::coolmaster::config::step::user::data::heat_cool%]",
"host": "[%key:common::config_flow::data::host%]",
"off": "[%key:component::coolmaster::config::step::user::data::off%]",
"swing_support": "[%key:component::coolmaster::config::step::user::data::swing_support%]"
},
"data_description": {
"cool": "[%key:component::coolmaster::config::step::user::data_description::cool%]",
"dry": "[%key:component::coolmaster::config::step::user::data_description::dry%]",
"fan_only": "[%key:component::coolmaster::config::step::user::data_description::fan_only%]",
"heat": "[%key:component::coolmaster::config::step::user::data_description::heat%]",
"heat_cool": "[%key:component::coolmaster::config::step::user::data_description::heat_cool%]",
"host": "[%key:component::coolmaster::config::step::user::data_description::host%]",
"off": "[%key:component::coolmaster::config::step::user::data_description::off%]",
"swing_support": "[%key:component::coolmaster::config::step::user::data_description::swing_support%]"
},
"description": "Update your CoolMasterNet connection details and supported modes.",
"sections": {
"more_options": {
"data": {
"send_wakeup_prompt": "[%key:component::coolmaster::config::step::user::sections::more_options::data::send_wakeup_prompt%]"
},
"data_description": {
"send_wakeup_prompt": "[%key:component::coolmaster::config::step::user::sections::more_options::data_description::send_wakeup_prompt%]"
},
"name": "[%key:component::coolmaster::config::step::user::sections::more_options::name%]"
}
}
},
"user": {
"data": {
"cool": "Support cool mode",
@@ -20,7 +55,14 @@
"swing_support": "Control swing mode"
},
"data_description": {
"host": "The hostname or IP address of your CoolMasterNet device."
"cool": "Enable if your units can cool.",
"dry": "Enable if your units have a dry (dehumidify) mode.",
"fan_only": "Enable if your units can run the fan without heating or cooling.",
"heat": "Enable if your units can heat.",
"heat_cool": "Enable if your units can switch between heating and cooling automatically.",
"host": "The hostname or IP address of your CoolMasterNet device.",
"off": "Allow the units to be turned off from Home Assistant.",
"swing_support": "Expose a swing mode control. This adds one request per unit on every update, so polling is slower."
},
"description": "Set up your CoolMasterNet connection details.",
"sections": {
+251 -46
View File
@@ -1,27 +1,44 @@
"""Test the Coolmaster config flow."""
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant import config_entries
from homeassistant.components.climate import HVACMode
from homeassistant.components.coolmaster.config_flow import AVAILABLE_MODES
from homeassistant.components.coolmaster.const import DOMAIN
from homeassistant.config_entries import ConfigFlowResult
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
def _flow_data(send_wakeup_prompt: bool = False) -> dict:
options: dict = {"host": "1.1.1.1"}
def _flow_data(
send_wakeup_prompt: bool = False,
host: str = "1.1.1.1",
modes: list[str] | None = None,
swing_support: bool = False,
) -> dict:
options: dict = {"host": host}
for mode in AVAILABLE_MODES:
options[mode] = True
options["swing_support"] = False
options[mode] = mode in modes if modes is not None else True
options["swing_support"] = swing_support
options["more_options"] = {"send_wakeup_prompt": send_wakeup_prompt}
return options
def _suggested_values(result: ConfigFlowResult) -> dict[str, Any]:
"""Pull the values suggested to the user out of a form result."""
return {
str(key): key.description["suggested_value"]
for key in result["data_schema"].schema
if key.description and "suggested_value" in key.description
}
@pytest.mark.parametrize("send_wakeup_prompt", [True, False])
async def test_form(hass: HomeAssistant, send_wakeup_prompt: bool) -> None:
"""Test we get the form."""
@@ -59,58 +76,35 @@ async def test_form(hass: HomeAssistant, send_wakeup_prompt: bool) -> None:
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_timeout(hass: HomeAssistant) -> None:
"""Test we handle a connection timeout."""
@pytest.mark.parametrize(
("side_effect", "return_value", "error"),
[
pytest.param(OSError(), None, "cannot_connect", id="cannot_connect"),
pytest.param(None, {}, "no_units", id="no_units"),
],
)
async def test_form_errors(
hass: HomeAssistant,
side_effect: Exception | None,
return_value: dict | None,
error: str,
) -> None:
"""Test we handle errors from the bridge."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
side_effect=TimeoutError(),
side_effect=side_effect,
return_value=return_value,
):
result2 = await hass.config_entries.flow.async_configure(
result = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data()
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "cannot_connect"}
async def test_form_connection_refused(hass: HomeAssistant) -> None:
"""Test we handle a connection error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
side_effect=ConnectionRefusedError(),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data()
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "cannot_connect"}
async def test_form_no_units(hass: HomeAssistant) -> None:
"""Test we handle no units found."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
return_value={},
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data()
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "no_units"}
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error}
async def test_form_duplicate_host(hass: HomeAssistant) -> None:
@@ -134,3 +128,214 @@ async def test_form_duplicate_host(hass: HomeAssistant) -> None:
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
"new_host",
[
pytest.param("1.2.3.4", id="same_host"),
pytest.param("5.6.7.8", id="changed_host"),
],
)
async def test_reconfigure(
hass: HomeAssistant, load_int: MockConfigEntry, new_host: str
) -> None:
"""Test reconfiguring an existing entry updates the supported modes."""
result = await load_int.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
# The entry stores modes as a list but the form uses a boolean per mode.
suggested = _suggested_values(result)
assert suggested["host"] == "1.2.3.4"
assert suggested[HVACMode.OFF] is True
assert suggested[HVACMode.COOL] is True
assert suggested[HVACMode.HEAT] is True
assert suggested[HVACMode.DRY] is False
assert suggested[HVACMode.HEAT_COOL] is False
assert suggested[HVACMode.FAN_ONLY] is False
with (
patch(
"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
return_value={"test_id": "test_unit"},
),
patch(
"homeassistant.components.coolmaster.async_setup_entry",
return_value=True,
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
_flow_data(
host=new_host,
modes=[HVACMode.OFF, HVACMode.COOL, HVACMode.HEAT, HVACMode.DRY],
),
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert load_int.data["host"] == new_host
assert load_int.data["supported_modes"] == [
HVACMode.OFF,
HVACMode.HEAT,
HVACMode.COOL,
HVACMode.DRY,
]
# Untouched keys are preserved.
assert load_int.data["port"] == 1234
@pytest.mark.parametrize(
("side_effect", "return_value", "error"),
[
pytest.param(OSError(), None, "cannot_connect", id="cannot_connect"),
pytest.param(None, {}, "no_units", id="no_units"),
],
)
async def test_reconfigure_errors(
hass: HomeAssistant,
load_int: MockConfigEntry,
side_effect: Exception | None,
return_value: dict | None,
error: str,
) -> None:
"""Test reconfigure surfaces errors and recovers."""
result = await load_int.start_reconfigure_flow(hass)
with patch(
"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
side_effect=side_effect,
return_value=return_value,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data()
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {"base": error}
# The entry is left untouched by the failed attempt.
assert load_int.data["host"] == "1.2.3.4"
with (
patch(
"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
return_value={"test_id": "test_unit"},
),
patch(
"homeassistant.components.coolmaster.async_setup_entry",
return_value=True,
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data()
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert load_int.data["host"] == "1.1.1.1"
assert load_int.data["supported_modes"] == AVAILABLE_MODES
async def test_reconfigure_uses_stored_port(
hass: HomeAssistant, load_int: MockConfigEntry
) -> None:
"""Test reconfigure validates against the port stored on the entry."""
result = await load_int.start_reconfigure_flow(hass)
with (
patch(
"homeassistant.components.coolmaster.config_flow.CoolMasterNet",
autospec=True,
) as mock_coolmaster,
patch(
"homeassistant.components.coolmaster.async_setup_entry",
return_value=True,
),
):
mock_coolmaster.return_value.status.return_value = {"test_id": "test_unit"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data()
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
# The entry stores port 1234, which must be used over the default 10102.
assert mock_coolmaster.call_args.args[1] == 1234
assert load_int.data["port"] == 1234
async def test_reconfigure_duplicate_host(
hass: HomeAssistant, load_int: MockConfigEntry
) -> None:
"""Test reconfigure aborts when another entry already uses the host."""
other_entry = MockConfigEntry(
domain=DOMAIN,
data={
"host": "9.9.9.9",
"port": 10102,
"supported_modes": AVAILABLE_MODES,
},
)
other_entry.add_to_hass(hass)
result = await load_int.start_reconfigure_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data(host="9.9.9.9")
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert load_int.data["host"] == "1.2.3.4"
@pytest.mark.parametrize(
("initial", "updated"),
[
pytest.param(True, False, id="enabled_to_disabled"),
pytest.param(False, True, id="disabled_to_enabled"),
],
)
async def test_reconfigure_toggles_swing_support(
hass: HomeAssistant, initial: bool, updated: bool
) -> None:
"""Test the swing support flag round-trips through the reconfigure form."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
"host": "1.2.3.4",
"port": 10102,
"supported_modes": AVAILABLE_MODES,
"swing_support": initial,
},
)
entry.add_to_hass(hass)
result = await entry.start_reconfigure_flow(hass)
assert _suggested_values(result)["swing_support"] is initial
with (
patch(
"homeassistant.components.coolmaster.config_flow.CoolMasterNet.status",
return_value={"test_id": "test_unit"},
),
patch(
"homeassistant.components.coolmaster.async_setup_entry",
return_value=True,
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], _flow_data(host="1.2.3.4", swing_support=updated)
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert entry.data["swing_support"] is updated