mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 12:50:45 -04:00
Hide NeoPool AUX relays assigned to a built-in function (#192122)
This commit is contained in:
@@ -13,9 +13,14 @@ from neopool_modbus.capabilities import (
|
||||
is_ph_module_present,
|
||||
is_redox_module_present,
|
||||
)
|
||||
from neopool_modbus.registers import HIDRO_COVER_ENABLE_BIT, is_valid_relay_gpio
|
||||
from neopool_modbus.registers import (
|
||||
HIDRO_COVER_ENABLE_BIT,
|
||||
aux_relay_available,
|
||||
is_valid_relay_gpio,
|
||||
)
|
||||
|
||||
from homeassistant.components.binary_sensor import (
|
||||
DOMAIN as BINARY_SENSOR_DOMAIN,
|
||||
BinarySensorDeviceClass,
|
||||
BinarySensorEntity,
|
||||
BinarySensorEntityDescription,
|
||||
@@ -34,6 +39,7 @@ from .const import (
|
||||
)
|
||||
from .coordinator import NeoPoolConfigEntry, NeoPoolCoordinator
|
||||
from .entity import NeoPoolEntity
|
||||
from .helpers import cleanup_occupied_aux_entities
|
||||
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
@@ -100,24 +106,28 @@ BINARY_SENSOR_DESCRIPTIONS: dict[str, NeoPoolBinarySensorEntityDescription] = {
|
||||
translation_key="aux",
|
||||
translation_placeholders={"number": "1"},
|
||||
device_class=BinarySensorDeviceClass.POWER,
|
||||
supported_fn=lambda data: aux_relay_available(1, data),
|
||||
),
|
||||
"AUX2": NeoPoolBinarySensorEntityDescription(
|
||||
key="AUX2",
|
||||
translation_key="aux",
|
||||
translation_placeholders={"number": "2"},
|
||||
device_class=BinarySensorDeviceClass.POWER,
|
||||
supported_fn=lambda data: aux_relay_available(2, data),
|
||||
),
|
||||
"AUX3": NeoPoolBinarySensorEntityDescription(
|
||||
key="AUX3",
|
||||
translation_key="aux",
|
||||
translation_placeholders={"number": "3"},
|
||||
device_class=BinarySensorDeviceClass.POWER,
|
||||
supported_fn=lambda data: aux_relay_available(3, data),
|
||||
),
|
||||
"AUX4": NeoPoolBinarySensorEntityDescription(
|
||||
key="AUX4",
|
||||
translation_key="aux",
|
||||
translation_placeholders={"number": "4"},
|
||||
device_class=BinarySensorDeviceClass.POWER,
|
||||
supported_fn=lambda data: aux_relay_available(4, data),
|
||||
),
|
||||
"pH module control status": NeoPoolBinarySensorEntityDescription(
|
||||
key="pH module control status",
|
||||
@@ -357,6 +367,10 @@ async def async_setup_entry(
|
||||
coordinator = entry.runtime_data
|
||||
options = entry.options
|
||||
|
||||
cleanup_occupied_aux_entities(
|
||||
hass, entry.entry_id, BINARY_SENSOR_DOMAIN, coordinator.data
|
||||
)
|
||||
|
||||
async_add_entities(
|
||||
NeoPoolBinarySensor(coordinator, key, desc)
|
||||
for key, desc in BINARY_SENSOR_DESCRIPTIONS.items()
|
||||
@@ -387,6 +401,15 @@ class NeoPoolBinarySensor(NeoPoolEntity, BinarySensorEntity):
|
||||
f"{self.coordinator.config_entry.unique_id}_{key.lower()}"
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def available(self) -> bool:
|
||||
"""Return False when the relay becomes occupied after setup."""
|
||||
desc = self.entity_description
|
||||
return super().available and (
|
||||
desc.supported_fn is None or desc.supported_fn(self.coordinator.data)
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def is_on(self) -> bool | None:
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Any, override
|
||||
|
||||
from neopool_modbus import async_probe_serial_unit
|
||||
from neopool_modbus.exceptions import NeoPoolModbusError, NeoPoolTimeoutError
|
||||
from neopool_modbus.registers import DEFAULT_MODBUS_FRAMER
|
||||
from neopool_modbus.registers import DEFAULT_MODBUS_FRAMER, aux_relay_available
|
||||
import probatio
|
||||
|
||||
from homeassistant.components.modbus import async_get_temporary_unit
|
||||
@@ -272,40 +272,60 @@ class NeoPoolConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
class NeoPoolOptionsFlowHandler(OptionsFlowWithReload):
|
||||
"""Handle options flow for NeoPool integration."""
|
||||
|
||||
# AUX option key per physical AUX relay number (AUX1=relay4 .. AUX4=relay7).
|
||||
_AUX_OPTION_KEYS: dict[int, str] = {
|
||||
1: CONF_USE_AUX1,
|
||||
2: CONF_USE_AUX2,
|
||||
3: CONF_USE_AUX3,
|
||||
4: CONF_USE_AUX4,
|
||||
}
|
||||
|
||||
async def async_step_init(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the initial step of the options flow."""
|
||||
# The AUX relay gating reads the live capability snapshot off the
|
||||
# coordinator, so the entry has to be loaded before the form is built.
|
||||
if self.config_entry.state is not ConfigEntryState.LOADED:
|
||||
return self.async_abort(reason="entry_not_loaded")
|
||||
|
||||
data = self.config_entry.runtime_data.data
|
||||
|
||||
# AUXn whose physical relay the device has assigned to a built-in
|
||||
# function cannot be driven directly, so hide its checkbox.
|
||||
aux_available = {
|
||||
aux: aux_relay_available(aux, data) for aux in self._AUX_OPTION_KEYS
|
||||
}
|
||||
|
||||
if user_input is not None:
|
||||
# Clear the enabled flag of any AUX relay the device has claimed: the
|
||||
# relay assignment is a hardware setting that rarely changes, so a
|
||||
# stale "on" toggle the controller will never honour is dropped
|
||||
# rather than preserved.
|
||||
for aux, option_key in self._AUX_OPTION_KEYS.items():
|
||||
if not aux_available[aux]:
|
||||
user_input[option_key] = False
|
||||
return self.async_create_entry(title="", data=user_input)
|
||||
|
||||
options = self.config_entry.options
|
||||
schema = probatio.Schema(
|
||||
{
|
||||
probatio.Optional(
|
||||
CONF_USE_LIGHT,
|
||||
default=options.get(CONF_USE_LIGHT, False),
|
||||
): bool,
|
||||
probatio.Optional(
|
||||
CONF_USE_COVER_SENSOR,
|
||||
default=options.get(CONF_USE_COVER_SENSOR, False),
|
||||
): bool,
|
||||
probatio.Optional(
|
||||
CONF_USE_AUX1,
|
||||
default=options.get(CONF_USE_AUX1, False),
|
||||
): bool,
|
||||
probatio.Optional(
|
||||
CONF_USE_AUX2,
|
||||
default=options.get(CONF_USE_AUX2, False),
|
||||
): bool,
|
||||
probatio.Optional(
|
||||
CONF_USE_AUX3,
|
||||
default=options.get(CONF_USE_AUX3, False),
|
||||
): bool,
|
||||
probatio.Optional(
|
||||
CONF_USE_AUX4,
|
||||
default=options.get(CONF_USE_AUX4, False),
|
||||
): bool,
|
||||
}
|
||||
)
|
||||
schema_dict: dict[Any, Any] = {
|
||||
probatio.Optional(
|
||||
CONF_USE_LIGHT,
|
||||
default=options.get(CONF_USE_LIGHT, False),
|
||||
): bool,
|
||||
probatio.Optional(
|
||||
CONF_USE_COVER_SENSOR,
|
||||
default=options.get(CONF_USE_COVER_SENSOR, False),
|
||||
): bool,
|
||||
}
|
||||
for aux, option_key in self._AUX_OPTION_KEYS.items():
|
||||
if aux_available[aux]:
|
||||
schema_dict[
|
||||
probatio.Optional(
|
||||
option_key,
|
||||
default=options.get(option_key, False),
|
||||
)
|
||||
] = bool
|
||||
|
||||
schema = probatio.Schema(schema_dict)
|
||||
return self.async_show_form(step_id="init", data_schema=schema)
|
||||
|
||||
@@ -12,6 +12,7 @@ from neopool_modbus.exceptions import NeoPoolError
|
||||
from neopool_modbus.registers import (
|
||||
MAX_RELAY_GPIO,
|
||||
TIMER_BLOCKS,
|
||||
aux_relay_available,
|
||||
find_corrupted_gpio_registers,
|
||||
is_valid_relay_gpio,
|
||||
)
|
||||
@@ -185,6 +186,12 @@ class NeoPoolCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
data.get("MBF_PAR_LIGHTING_GPIO", 0) or 0
|
||||
):
|
||||
continue
|
||||
# AUX relay occupied: the time entities gate the same check, so
|
||||
# the timer block would have no consumer.
|
||||
if key.startswith("relay_aux"):
|
||||
aux_number = int(key.removeprefix("relay_aux").rstrip("b"))
|
||||
if not aux_relay_available(aux_number, data):
|
||||
continue
|
||||
enabled.append(key)
|
||||
enabled += [ft for ft in _FILT_TIMERS if ft in active]
|
||||
return enabled
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
|
||||
from collections.abc import Mapping
|
||||
import datetime as dt
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
from modbus_connection import ModbusSerialParams, ModbusTcpParams
|
||||
from neopool_modbus.decoders import encode_device_time
|
||||
from neopool_modbus.registers import framer_to_socket_name
|
||||
from neopool_modbus.registers import aux_relay_available, framer_to_socket_name
|
||||
|
||||
from homeassistant.const import CONF_DEVICE, CONF_HOST, CONF_PORT, CONF_TYPE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
import homeassistant.util.dt as dt_util
|
||||
|
||||
from .const import (
|
||||
@@ -21,6 +23,10 @@ from .const import (
|
||||
TYPE_TCP,
|
||||
)
|
||||
|
||||
# AUX relay number embedded in an entity unique_id, e.g. "..._aux1" or
|
||||
# "..._relay_aux2b_period". All AUX entity keys carry an "aux<n>" token.
|
||||
_AUX_UNIQUE_ID_RE = re.compile(r"aux([1-4])")
|
||||
|
||||
|
||||
def prepare_device_time(hass: HomeAssistant) -> int:
|
||||
"""Return the unix timestamp the device should display as local wall-clock."""
|
||||
@@ -68,3 +74,27 @@ def build_modbus_params(
|
||||
return ModbusSerialParams(
|
||||
device=f"socket://{device_host}:{port}", framer=serial_framer, baudrate=115200
|
||||
)
|
||||
|
||||
|
||||
def cleanup_occupied_aux_entities(
|
||||
hass: HomeAssistant,
|
||||
entry_id: str,
|
||||
platform: str,
|
||||
data: Mapping[str, Any],
|
||||
) -> None:
|
||||
"""Remove disabled registry entries for AUX relays claimed by a function.
|
||||
|
||||
An AUX whose physical relay the device has assigned to a built-in function
|
||||
is no longer created (supported_fn gates it out). On an existing install its
|
||||
registry entry would otherwise linger as a restored, unavailable entity.
|
||||
Only disabled entries are removed, so a user-enabled AUX that later becomes
|
||||
occupied keeps its customisations; the relay assignment is reversible on the
|
||||
device.
|
||||
"""
|
||||
registry = er.async_get(hass)
|
||||
for entry in registry.entities.get_entries_for_config_entry_id(entry_id):
|
||||
if entry.domain != platform or not entry.disabled:
|
||||
continue
|
||||
match = _AUX_UNIQUE_ID_RE.search(entry.unique_id)
|
||||
if match and not aux_relay_available(int(match.group(1)), data):
|
||||
registry.async_remove(entry.entity_id)
|
||||
|
||||
@@ -32,10 +32,15 @@ from neopool_modbus.registers import (
|
||||
RelayKind,
|
||||
RelayMode,
|
||||
TimerRelayMode,
|
||||
aux_relay_available,
|
||||
is_valid_relay_gpio,
|
||||
)
|
||||
|
||||
from homeassistant.components.select import SelectEntity, SelectEntityDescription
|
||||
from homeassistant.components.select import (
|
||||
DOMAIN as SELECT_DOMAIN,
|
||||
SelectEntity,
|
||||
SelectEntityDescription,
|
||||
)
|
||||
from homeassistant.const import EntityCategory
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
|
||||
@@ -53,6 +58,7 @@ from .const import (
|
||||
)
|
||||
from .coordinator import NeoPoolConfigEntry, NeoPoolCoordinator
|
||||
from .entity import NeoPoolEntity
|
||||
from .helpers import cleanup_occupied_aux_entities
|
||||
|
||||
PARALLEL_UPDATES = 1
|
||||
|
||||
@@ -309,6 +315,11 @@ def _light_gpio_supported(data: dict[str, Any]) -> bool:
|
||||
return is_valid_relay_gpio(data.get("MBF_PAR_LIGHTING_GPIO", 0) or 0)
|
||||
|
||||
|
||||
def _aux_available(n: int) -> Callable[[dict[str, Any]], bool]:
|
||||
"""Return a supported_fn gating an AUX select on relay availability."""
|
||||
return lambda data: aux_relay_available(n, data)
|
||||
|
||||
|
||||
SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
"MBF_PAR_FILT_MODE": NeoPoolSelectEntityDescription(
|
||||
key="MBF_PAR_FILT_MODE",
|
||||
@@ -471,6 +482,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
translation_placeholders={"number": "1", "subtimer": "1"},
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
select_type="timer_period",
|
||||
supported_fn=_aux_available(1),
|
||||
write_fn=_write_timer_period,
|
||||
),
|
||||
"relay_aux1b_period": NeoPoolSelectEntityDescription(
|
||||
@@ -480,6 +492,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
select_type="timer_period",
|
||||
entity_registry_enabled_default=False,
|
||||
supported_fn=_aux_available(1),
|
||||
write_fn=_write_timer_period,
|
||||
),
|
||||
"relay_aux2_period": NeoPoolSelectEntityDescription(
|
||||
@@ -488,6 +501,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
translation_placeholders={"number": "2", "subtimer": "1"},
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
select_type="timer_period",
|
||||
supported_fn=_aux_available(2),
|
||||
write_fn=_write_timer_period,
|
||||
),
|
||||
"relay_aux2b_period": NeoPoolSelectEntityDescription(
|
||||
@@ -497,6 +511,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
select_type="timer_period",
|
||||
entity_registry_enabled_default=False,
|
||||
supported_fn=_aux_available(2),
|
||||
write_fn=_write_timer_period,
|
||||
),
|
||||
"relay_aux3_period": NeoPoolSelectEntityDescription(
|
||||
@@ -505,6 +520,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
translation_placeholders={"number": "3", "subtimer": "1"},
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
select_type="timer_period",
|
||||
supported_fn=_aux_available(3),
|
||||
write_fn=_write_timer_period,
|
||||
),
|
||||
"relay_aux3b_period": NeoPoolSelectEntityDescription(
|
||||
@@ -514,6 +530,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
select_type="timer_period",
|
||||
entity_registry_enabled_default=False,
|
||||
supported_fn=_aux_available(3),
|
||||
write_fn=_write_timer_period,
|
||||
),
|
||||
"relay_aux4_period": NeoPoolSelectEntityDescription(
|
||||
@@ -522,6 +539,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
translation_placeholders={"number": "4", "subtimer": "1"},
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
select_type="timer_period",
|
||||
supported_fn=_aux_available(4),
|
||||
write_fn=_write_timer_period,
|
||||
),
|
||||
"relay_aux4b_period": NeoPoolSelectEntityDescription(
|
||||
@@ -531,6 +549,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
select_type="timer_period",
|
||||
entity_registry_enabled_default=False,
|
||||
supported_fn=_aux_available(4),
|
||||
write_fn=_write_timer_period,
|
||||
),
|
||||
"relay_light_period": NeoPoolSelectEntityDescription(
|
||||
@@ -547,6 +566,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
translation_placeholders={"number": "1"},
|
||||
options_map={1: "auto", 4: "manual"},
|
||||
select_type="relay_mode",
|
||||
supported_fn=_aux_available(1),
|
||||
write_fn=_write_relay_mode,
|
||||
),
|
||||
"relay_aux2_mode": NeoPoolSelectEntityDescription(
|
||||
@@ -555,6 +575,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
translation_placeholders={"number": "2"},
|
||||
options_map={1: "auto", 4: "manual"},
|
||||
select_type="relay_mode",
|
||||
supported_fn=_aux_available(2),
|
||||
write_fn=_write_relay_mode,
|
||||
),
|
||||
"relay_aux3_mode": NeoPoolSelectEntityDescription(
|
||||
@@ -563,6 +584,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
translation_placeholders={"number": "3"},
|
||||
options_map={1: "auto", 4: "manual"},
|
||||
select_type="relay_mode",
|
||||
supported_fn=_aux_available(3),
|
||||
write_fn=_write_relay_mode,
|
||||
),
|
||||
"relay_aux4_mode": NeoPoolSelectEntityDescription(
|
||||
@@ -571,6 +593,7 @@ SELECT_DESCRIPTIONS: dict[str, NeoPoolSelectEntityDescription] = {
|
||||
translation_placeholders={"number": "4"},
|
||||
options_map={1: "auto", 4: "manual"},
|
||||
select_type="relay_mode",
|
||||
supported_fn=_aux_available(4),
|
||||
write_fn=_write_relay_mode,
|
||||
),
|
||||
"relay_light_mode": NeoPoolSelectEntityDescription(
|
||||
@@ -612,6 +635,8 @@ async def async_setup_entry(
|
||||
coordinator = entry.runtime_data
|
||||
options = entry.options
|
||||
|
||||
cleanup_occupied_aux_entities(hass, entry.entry_id, SELECT_DOMAIN, coordinator.data)
|
||||
|
||||
async_add_entities(
|
||||
NeoPoolSelect(coordinator, key, desc)
|
||||
for key, desc in SELECT_DESCRIPTIONS.items()
|
||||
@@ -673,6 +698,15 @@ class NeoPoolSelect(NeoPoolEntity, SelectEntity):
|
||||
translation_placeholders={"error": str(err)},
|
||||
) from err
|
||||
|
||||
@property
|
||||
@override
|
||||
def available(self) -> bool:
|
||||
"""Return False when the relay becomes occupied after setup."""
|
||||
desc = self.entity_description
|
||||
return super().available and (
|
||||
desc.supported_fn is None or desc.supported_fn(self.coordinator.data)
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def options(self) -> list[str]:
|
||||
|
||||
@@ -606,6 +606,9 @@
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"abort": {
|
||||
"entry_not_loaded": "The options can be changed once the device has been set up."
|
||||
},
|
||||
"step": {
|
||||
"init": {
|
||||
"data": {
|
||||
|
||||
@@ -25,10 +25,15 @@ from neopool_modbus.registers import (
|
||||
FiltValveMode,
|
||||
RelayKind,
|
||||
TimerRelayMode,
|
||||
aux_relay_available,
|
||||
is_valid_relay_gpio,
|
||||
)
|
||||
|
||||
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
|
||||
from homeassistant.components.switch import (
|
||||
DOMAIN as SWITCH_DOMAIN,
|
||||
SwitchEntity,
|
||||
SwitchEntityDescription,
|
||||
)
|
||||
from homeassistant.const import EntityCategory
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
|
||||
@@ -44,6 +49,7 @@ from .const import (
|
||||
)
|
||||
from .coordinator import NeoPoolConfigEntry, NeoPoolCoordinator
|
||||
from .entity import NeoPoolEntity
|
||||
from .helpers import cleanup_occupied_aux_entities
|
||||
|
||||
PARALLEL_UPDATES = 1
|
||||
|
||||
@@ -248,6 +254,7 @@ SWITCH_DESCRIPTIONS: dict[str, NeoPoolSwitchEntityDescription] = {
|
||||
translation_placeholders={"number": "1"},
|
||||
write_fn=_make_write_relay_state(RelayKind.AUX1),
|
||||
is_on_fn=_make_is_on_from_key("AUX1"),
|
||||
supported_fn=lambda data: aux_relay_available(1, data),
|
||||
),
|
||||
"aux2": NeoPoolSwitchEntityDescription(
|
||||
key="aux2",
|
||||
@@ -255,6 +262,7 @@ SWITCH_DESCRIPTIONS: dict[str, NeoPoolSwitchEntityDescription] = {
|
||||
translation_placeholders={"number": "2"},
|
||||
write_fn=_make_write_relay_state(RelayKind.AUX2),
|
||||
is_on_fn=_make_is_on_from_key("AUX2"),
|
||||
supported_fn=lambda data: aux_relay_available(2, data),
|
||||
),
|
||||
"aux3": NeoPoolSwitchEntityDescription(
|
||||
key="aux3",
|
||||
@@ -262,6 +270,7 @@ SWITCH_DESCRIPTIONS: dict[str, NeoPoolSwitchEntityDescription] = {
|
||||
translation_placeholders={"number": "3"},
|
||||
write_fn=_make_write_relay_state(RelayKind.AUX3),
|
||||
is_on_fn=_make_is_on_from_key("AUX3"),
|
||||
supported_fn=lambda data: aux_relay_available(3, data),
|
||||
),
|
||||
"aux4": NeoPoolSwitchEntityDescription(
|
||||
key="aux4",
|
||||
@@ -269,6 +278,7 @@ SWITCH_DESCRIPTIONS: dict[str, NeoPoolSwitchEntityDescription] = {
|
||||
translation_placeholders={"number": "4"},
|
||||
write_fn=_make_write_relay_state(RelayKind.AUX4),
|
||||
is_on_fn=_make_is_on_from_key("AUX4"),
|
||||
supported_fn=lambda data: aux_relay_available(4, data),
|
||||
),
|
||||
}
|
||||
|
||||
@@ -292,6 +302,8 @@ async def async_setup_entry(
|
||||
coordinator = entry.runtime_data
|
||||
options = entry.options
|
||||
|
||||
cleanup_occupied_aux_entities(hass, entry.entry_id, SWITCH_DOMAIN, coordinator.data)
|
||||
|
||||
async_add_entities(
|
||||
NeoPoolSwitch(coordinator, desc)
|
||||
for key, desc in SWITCH_DESCRIPTIONS.items()
|
||||
@@ -374,6 +386,15 @@ class NeoPoolSwitch(NeoPoolEntity, SwitchEntity):
|
||||
self.coordinator.async_set_updated_data({**self.coordinator.data, **overrides})
|
||||
self.coordinator.request_refresh_with_followup()
|
||||
|
||||
@property
|
||||
@override
|
||||
def available(self) -> bool:
|
||||
"""Return False when the relay becomes occupied after setup."""
|
||||
desc = self.entity_description
|
||||
return super().available and (
|
||||
desc.supported_fn is None or desc.supported_fn(self.coordinator.data)
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def is_on(self) -> bool:
|
||||
|
||||
@@ -5,9 +5,13 @@ from dataclasses import dataclass
|
||||
from datetime import time as dt_time
|
||||
from typing import Any, Literal, override
|
||||
|
||||
from neopool_modbus.registers import is_valid_relay_gpio
|
||||
from neopool_modbus.registers import aux_relay_available, is_valid_relay_gpio
|
||||
|
||||
from homeassistant.components.time import TimeEntity, TimeEntityDescription
|
||||
from homeassistant.components.time import (
|
||||
DOMAIN as TIME_DOMAIN,
|
||||
TimeEntity,
|
||||
TimeEntityDescription,
|
||||
)
|
||||
from homeassistant.const import EntityCategory
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
@@ -21,6 +25,7 @@ from .const import (
|
||||
)
|
||||
from .coordinator import NeoPoolConfigEntry, NeoPoolCoordinator
|
||||
from .entity import NeoPoolDebouncedWriteEntity
|
||||
from .helpers import cleanup_occupied_aux_entities
|
||||
|
||||
# The platform coalesces rapid writes per entity via a debounce timer. Each
|
||||
# start/stop entity flushes its own endpoint independently, so a platform
|
||||
@@ -38,13 +43,6 @@ class NeoPoolTimeEntityDescription(TimeEntityDescription):
|
||||
translation_placeholders: dict[str, str] | None = None
|
||||
|
||||
|
||||
def _option_supported(
|
||||
opt_flag: str,
|
||||
) -> Callable[[dict[str, Any], Mapping[str, Any]], bool]:
|
||||
"""Return a supported_fn gating an entity on the given option flag."""
|
||||
return lambda _data, opts: bool(opts.get(opt_flag))
|
||||
|
||||
|
||||
def _light_supported(data: dict[str, Any], opts: Mapping[str, Any]) -> bool:
|
||||
"""Gate the light timer on its option and a valid lighting GPIO.
|
||||
|
||||
@@ -55,6 +53,15 @@ def _light_supported(data: dict[str, Any], opts: Mapping[str, Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _aux_supported(
|
||||
opt_flag: str, aux_number: int
|
||||
) -> Callable[[dict[str, Any], Mapping[str, Any]], bool]:
|
||||
"""Return a supported_fn gating an AUX timer on its option and relay availability."""
|
||||
return lambda data, opts: (
|
||||
bool(opts.get(opt_flag)) and aux_relay_available(aux_number, data)
|
||||
)
|
||||
|
||||
|
||||
# Filtration timers exist on every device; aux and light timers gate on options.
|
||||
_TIMER_BLOCKS: tuple[tuple[str, str | None, bool], ...] = (
|
||||
("filtration1", None, True),
|
||||
@@ -96,8 +103,10 @@ def _build_descriptions() -> dict[str, NeoPoolTimeEntityDescription]:
|
||||
supported_fn: (
|
||||
Callable[[dict[str, Any], Mapping[str, Any]], bool] | None
|
||||
) = _light_supported
|
||||
elif opt_flag is not None:
|
||||
supported_fn = _option_supported(opt_flag)
|
||||
elif block.startswith("relay_aux") and opt_flag is not None:
|
||||
digits = block.removeprefix("relay_aux")
|
||||
aux_number = int(digits.rstrip("b"))
|
||||
supported_fn = _aux_supported(opt_flag, aux_number)
|
||||
else:
|
||||
supported_fn = None
|
||||
out[key] = NeoPoolTimeEntityDescription(
|
||||
@@ -124,6 +133,8 @@ async def async_setup_entry(
|
||||
"""Set up NeoPool time entities from a config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
cleanup_occupied_aux_entities(hass, entry.entry_id, TIME_DOMAIN, coordinator.data)
|
||||
|
||||
async_add_entities(
|
||||
NeoPoolTime(coordinator, key, desc)
|
||||
for key, desc in TIME_DESCRIPTIONS.items()
|
||||
@@ -175,6 +186,18 @@ class NeoPoolTime(NeoPoolDebouncedWriteEntity[int], TimeEntity):
|
||||
second=seconds % 60,
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def available(self) -> bool:
|
||||
"""Return False when the relay becomes occupied after setup."""
|
||||
desc = self.entity_description
|
||||
return super().available and (
|
||||
desc.supported_fn is None
|
||||
or desc.supported_fn(
|
||||
self.coordinator.data, self.coordinator.config_entry.options
|
||||
)
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_value(self) -> dt_time | None:
|
||||
|
||||
@@ -51,13 +51,17 @@ MOCK_POOL_DATA: dict[str, Any] = {
|
||||
"MBF_PAR_MODEL": 0x0003,
|
||||
"MBF_PAR_SERNUM": int(MOCK_SERIAL),
|
||||
"MBF_PAR_FILTRATION_CONF": 1,
|
||||
# Built-in functions share the low physical relays (1..3) so that physical
|
||||
# relays 4..7, i.e. AUX1..AUX4, stay free. The AUX relay gating hides an AUX
|
||||
# entity whose relay a function has claimed, so the default fixture keeps all
|
||||
# four AUX relays unassigned.
|
||||
"MBF_PAR_FILT_GPIO": 1,
|
||||
"MBF_PAR_LIGHTING_GPIO": 2,
|
||||
"MBF_PAR_HEATING_GPIO": 3,
|
||||
"MBF_PAR_PH_ACID_RELAY_GPIO": 4,
|
||||
"MBF_PAR_PH_BASE_RELAY_GPIO": 5,
|
||||
"MBF_PAR_RX_RELAY_GPIO": 6,
|
||||
"MBF_PAR_CL_RELAY_GPIO": 7,
|
||||
"MBF_PAR_PH_ACID_RELAY_GPIO": 1,
|
||||
"MBF_PAR_PH_BASE_RELAY_GPIO": 2,
|
||||
"MBF_PAR_RX_RELAY_GPIO": 3,
|
||||
"MBF_PAR_CL_RELAY_GPIO": 1,
|
||||
"MBF_PAR_CD_RELAY_GPIO": 0,
|
||||
"MBF_PAR_UV_RELAY_GPIO": 1,
|
||||
"MBF_PAR_FILTVALVE_GPIO": 1,
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
'MBF_MEASURE_RX': 650,
|
||||
'MBF_MEASURE_TEMPERATURE': 250,
|
||||
'MBF_PAR_CD_RELAY_GPIO': 0,
|
||||
'MBF_PAR_CL_RELAY_GPIO': 7,
|
||||
'MBF_PAR_CL_RELAY_GPIO': 1,
|
||||
'MBF_PAR_FILTRATION_CONF': 1,
|
||||
'MBF_PAR_FILTVALVE_ENABLE': 1,
|
||||
'MBF_PAR_FILTVALVE_GPIO': 1,
|
||||
@@ -73,10 +73,10 @@
|
||||
'MBF_PAR_INTELLIGENT_TT_NEXT_INTERVAL': 7200,
|
||||
'MBF_PAR_LIGHTING_GPIO': 2,
|
||||
'MBF_PAR_MODEL': 3,
|
||||
'MBF_PAR_PH_ACID_RELAY_GPIO': 4,
|
||||
'MBF_PAR_PH_BASE_RELAY_GPIO': 5,
|
||||
'MBF_PAR_PH_ACID_RELAY_GPIO': 1,
|
||||
'MBF_PAR_PH_BASE_RELAY_GPIO': 2,
|
||||
'MBF_PAR_RELAY_PH': 0,
|
||||
'MBF_PAR_RX_RELAY_GPIO': 6,
|
||||
'MBF_PAR_RX_RELAY_GPIO': 3,
|
||||
'MBF_PAR_SERNUM': '**REDACTED**',
|
||||
'MBF_PAR_TEMPERATURE_ACTIVE': 1,
|
||||
'MBF_PAR_UICFG_MACHINE': 0,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
@@ -14,7 +14,13 @@ from pytest_homeassistant.common import (
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
|
||||
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNKNOWN, Platform
|
||||
from homeassistant.const import (
|
||||
STATE_OFF,
|
||||
STATE_ON,
|
||||
STATE_UNAVAILABLE,
|
||||
STATE_UNKNOWN,
|
||||
Platform,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
@@ -269,3 +275,62 @@ async def test_opt_in_entities_absent_without_options(
|
||||
)
|
||||
is not None
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
@pytest.mark.parametrize(
|
||||
("occupied_relay", "hidden_key"),
|
||||
[(4, "AUX1"), (5, "AUX2"), (6, "AUX3"), (7, "AUX4")],
|
||||
)
|
||||
async def test_aux_binary_sensor_absent_when_relay_assigned_to_function(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_binary_sensor: MockConfigEntry,
|
||||
occupied_relay: int,
|
||||
hidden_key: str,
|
||||
) -> None:
|
||||
"""An AUX binary sensor is suppressed when its relay serves a function.
|
||||
|
||||
The option is enabled (mock_config_entry_binary_sensor), so this covers the
|
||||
entity-level safety net rather than the option gate.
|
||||
"""
|
||||
data = {**mock_neopool_client.async_read_all.return_value}
|
||||
data["MBF_PAR_PH_BASE_RELAY_GPIO"] = occupied_relay
|
||||
mock_neopool_client.async_read_all = AsyncMock(return_value=data)
|
||||
with patch("homeassistant.components.neopool.PLATFORMS", [Platform.BINARY_SENSOR]):
|
||||
await setup_integration(hass, mock_config_entry_binary_sensor)
|
||||
|
||||
assert _binary_state(hass, mock_config_entry_binary_sensor, hidden_key) is None
|
||||
# The other three AUX relays stay free and keep their sensors.
|
||||
for key in {"AUX1", "AUX2", "AUX3", "AUX4"} - {hidden_key}:
|
||||
assert _binary_state(hass, mock_config_entry_binary_sensor, key) is not None
|
||||
|
||||
|
||||
async def test_aux_binary_sensor_becomes_unavailable_when_relay_occupied_mid_run(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_binary_sensor: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""AUX binary sensor becomes unavailable when its relay is claimed mid-run.
|
||||
|
||||
The supported_fn gate runs only at setup. The available property must
|
||||
re-evaluate it on every coordinator update so that an occupied relay
|
||||
makes existing entities unavailable.
|
||||
"""
|
||||
with patch("homeassistant.components.neopool.PLATFORMS", [Platform.BINARY_SENSOR]):
|
||||
await setup_integration(hass, mock_config_entry_binary_sensor)
|
||||
|
||||
state = _binary_state(hass, mock_config_entry_binary_sensor, "AUX1")
|
||||
assert state is not None
|
||||
assert state.state != STATE_UNAVAILABLE
|
||||
|
||||
occupied_data = {**MOCK_POOL_DATA, "MBF_PAR_HEATING_GPIO": 4} # relay 4 == AUX1
|
||||
mock_neopool_client.async_read_all.return_value = occupied_data
|
||||
freezer.tick(timedelta(seconds=60))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = _binary_state(hass, mock_config_entry_binary_sensor, "AUX1")
|
||||
assert state is not None
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
@@ -14,7 +14,13 @@ from homeassistant.components.neopool.const import (
|
||||
CONF_BAUDRATE,
|
||||
CONF_MODBUS_FRAMER,
|
||||
CONF_UNIT_ID,
|
||||
CONF_USE_AUX1,
|
||||
CONF_USE_AUX2,
|
||||
CONF_USE_AUX3,
|
||||
CONF_USE_AUX4,
|
||||
CONF_USE_COVER_SENSOR,
|
||||
CONF_USE_LIGHT,
|
||||
CURRENT_VERSION,
|
||||
DEFAULT_BAUDRATE,
|
||||
DEFAULT_UNIT_ID,
|
||||
DOMAIN,
|
||||
@@ -599,3 +605,77 @@ async def test_options_flow_save_changes(
|
||||
|
||||
await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def test_options_flow_aborts_when_entry_not_loaded(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""The options flow needs the coordinator snapshot, so it aborts if unloaded."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
# No setup_integration: the entry is NOT_LOADED and has no runtime_data.
|
||||
result = await hass.config_entries.options.async_init(mock_config_entry.entry_id)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "entry_not_loaded"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_neopool_client")
|
||||
async def test_options_flow_hides_occupied_aux_checkbox(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""An AUX whose physical relay a function claims is omitted from the form."""
|
||||
# Assign the pH base pump to relay 4 (AUX1); leave AUX2-4 free.
|
||||
data = {**mock_neopool_client.async_read_all.return_value}
|
||||
data["MBF_PAR_PH_BASE_RELAY_GPIO"] = 4
|
||||
mock_neopool_client.async_read_all = AsyncMock(return_value=data)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
result = await hass.config_entries.options.async_init(mock_config_entry.entry_id)
|
||||
keys = {str(marker) for marker in result["data_schema"].schema}
|
||||
assert CONF_USE_AUX1 not in keys
|
||||
assert {CONF_USE_AUX2, CONF_USE_AUX3, CONF_USE_AUX4} <= keys
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_neopool_client")
|
||||
async def test_options_flow_forces_occupied_aux_off_on_submit(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
) -> None:
|
||||
"""A stale enabled flag for an occupied AUX relay is cleared on submit."""
|
||||
data = {**mock_neopool_client.async_read_all.return_value}
|
||||
data["MBF_PAR_PH_BASE_RELAY_GPIO"] = 4 # AUX1 occupied
|
||||
mock_neopool_client.async_read_all = AsyncMock(return_value=data)
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id=MOCK_SERIAL,
|
||||
version=CURRENT_VERSION,
|
||||
data={
|
||||
CONF_HOST: MOCK_HOST,
|
||||
CONF_PORT: MOCK_PORT,
|
||||
CONF_MODBUS_FRAMER: "tcp",
|
||||
SECTION_MORE_OPTIONS: {CONF_UNIT_ID: DEFAULT_UNIT_ID},
|
||||
},
|
||||
# A stale option left over from before the relay was assigned.
|
||||
options={CONF_USE_AUX1: True},
|
||||
)
|
||||
await setup_integration(hass, entry)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
CONF_USE_LIGHT: False,
|
||||
CONF_USE_COVER_SENSOR: False,
|
||||
CONF_USE_AUX2: False,
|
||||
CONF_USE_AUX3: False,
|
||||
CONF_USE_AUX4: False,
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert entry.options[CONF_USE_AUX1] is False
|
||||
|
||||
await hass.config_entries.async_unload(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -434,3 +434,91 @@ async def test_aux_b_subtimer_polls_when_enabled(
|
||||
assert enabled_timers is not None
|
||||
assert "relay_aux1" in enabled_timers
|
||||
assert "relay_aux1b" in enabled_timers
|
||||
|
||||
|
||||
async def test_occupied_aux_relay_skipped_even_when_option_enabled(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""With use_aux1=True but AUX1 relay occupied from the start, both blocks are skipped.
|
||||
|
||||
When a device function (e.g. heating) is wired to the AUX1 relay before
|
||||
setup, the switch and time entities are suppressed and no context is ever
|
||||
registered, so both relay_aux1 and relay_aux1b stay out of the read.
|
||||
"""
|
||||
occupied_data = dict(MOCK_POOL_DATA)
|
||||
occupied_data["MBF_PAR_HEATING_GPIO"] = 4 # relay 4 == AUX1
|
||||
mock_neopool_client.async_read_all.return_value = occupied_data
|
||||
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="Pool",
|
||||
unique_id="neopool_gate_aux_occupied",
|
||||
version=CURRENT_VERSION,
|
||||
data={
|
||||
"host": "192.0.2.24",
|
||||
"port": 502,
|
||||
"name": "Pool",
|
||||
CONF_UNIT_ID: 1,
|
||||
CONF_MODBUS_FRAMER: "tcp",
|
||||
},
|
||||
options={CONF_MODBUS_FRAMER: "tcp", CONF_USE_AUX1: True},
|
||||
)
|
||||
calls = _capture_timer_calls(mock_neopool_client)
|
||||
await setup_integration(hass, entry)
|
||||
await _poll_once_more(hass, entry.runtime_data, freezer)
|
||||
|
||||
enabled_timers = calls[-1][0]
|
||||
assert enabled_timers is not None
|
||||
assert "relay_aux1" not in enabled_timers
|
||||
assert "relay_aux1b" not in enabled_timers
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
async def test_relay_becomes_occupied_excludes_both_aux_blocks(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Both AUX1 blocks are excluded once the relay becomes occupied mid-run.
|
||||
|
||||
Start with a free AUX1 relay so relay_aux1 and relay_aux1b both poll (all
|
||||
entities enabled). Then simulate the device assigning the relay to a
|
||||
function and verify that the next poll excludes both blocks via the new
|
||||
aux_relay_available gate, not just the b subtimer's context check.
|
||||
"""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="Pool",
|
||||
unique_id="neopool_gate_aux_becomes_occupied",
|
||||
version=CURRENT_VERSION,
|
||||
data={
|
||||
"host": "192.0.2.25",
|
||||
"port": 502,
|
||||
"name": "Pool",
|
||||
CONF_UNIT_ID: 1,
|
||||
CONF_MODBUS_FRAMER: "tcp",
|
||||
},
|
||||
options={CONF_MODBUS_FRAMER: "tcp", CONF_USE_AUX1: True},
|
||||
)
|
||||
calls = _capture_timer_calls(mock_neopool_client)
|
||||
await setup_integration(hass, entry)
|
||||
await _poll_once_more(hass, entry.runtime_data, freezer)
|
||||
|
||||
# Both blocks poll while relay is free.
|
||||
assert calls[-1][0] is not None
|
||||
assert "relay_aux1" in calls[-1][0]
|
||||
assert "relay_aux1b" in calls[-1][0]
|
||||
|
||||
# Device assigns relay 4 (AUX1) to heating mid-run.
|
||||
occupied_data = dict(MOCK_POOL_DATA)
|
||||
occupied_data["MBF_PAR_HEATING_GPIO"] = 4 # relay 4 == AUX1
|
||||
mock_neopool_client.async_read_all.return_value = occupied_data
|
||||
|
||||
await _poll_once_more(hass, entry.runtime_data, freezer)
|
||||
|
||||
enabled_timers = calls[-1][0]
|
||||
assert enabled_timers is not None
|
||||
assert "relay_aux1" not in enabled_timers
|
||||
assert "relay_aux1b" not in enabled_timers
|
||||
|
||||
@@ -22,7 +22,7 @@ from homeassistant.components.select import (
|
||||
SelectService,
|
||||
SelectServiceArgument,
|
||||
)
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.const import STATE_UNAVAILABLE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
@@ -878,6 +878,65 @@ async def test_relay_mode_maps_communication_error_to_home_assistant_error(
|
||||
await _select_option(hass, entity_id, "auto")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("occupied_relay", "hidden_aux_number"),
|
||||
[(4, 1), (5, 2), (6, 3), (7, 4)],
|
||||
)
|
||||
async def test_aux_select_absent_when_relay_assigned_to_function(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_timers: MockConfigEntry,
|
||||
occupied_relay: int,
|
||||
hidden_aux_number: int,
|
||||
) -> None:
|
||||
"""AUX selects are suppressed when their relay serves a built-in function.
|
||||
|
||||
The option is enabled (mock_config_entry_timers), so this exercises the
|
||||
entity-level safety net, not the option gate.
|
||||
"""
|
||||
data = {**mock_neopool_client.async_read_all.return_value}
|
||||
data["MBF_PAR_PH_BASE_RELAY_GPIO"] = occupied_relay
|
||||
mock_neopool_client.async_read_all = AsyncMock(return_value=data)
|
||||
with patch("homeassistant.components.neopool.PLATFORMS", [Platform.SELECT]):
|
||||
await setup_integration(hass, mock_config_entry_timers)
|
||||
|
||||
all_entries = er.async_entries_for_config_entry(
|
||||
entity_registry, mock_config_entry_timers.entry_id
|
||||
)
|
||||
present_aux_suffixes = {
|
||||
suffix
|
||||
for n in range(1, 5)
|
||||
for suffix in (
|
||||
f"relay_aux{n}_mode",
|
||||
f"relay_aux{n}_period",
|
||||
f"relay_aux{n}b_period",
|
||||
)
|
||||
if any(
|
||||
e.domain == SELECT_DOMAIN and e.unique_id.endswith(f"_{suffix}")
|
||||
for e in all_entries
|
||||
)
|
||||
}
|
||||
hidden_suffixes = {
|
||||
f"relay_aux{hidden_aux_number}_mode",
|
||||
f"relay_aux{hidden_aux_number}_period",
|
||||
f"relay_aux{hidden_aux_number}b_period",
|
||||
}
|
||||
assert not (present_aux_suffixes & hidden_suffixes)
|
||||
# The other three AUX relays stay free and keep their selects.
|
||||
free_aux_numbers = {1, 2, 3, 4} - {hidden_aux_number}
|
||||
expected_free = {
|
||||
suffix
|
||||
for n in free_aux_numbers
|
||||
for suffix in (
|
||||
f"relay_aux{n}_mode",
|
||||
f"relay_aux{n}_period",
|
||||
f"relay_aux{n}b_period",
|
||||
)
|
||||
}
|
||||
assert expected_free.issubset(present_aux_suffixes)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_neopool_client")
|
||||
async def test_all_entities(
|
||||
hass: HomeAssistant,
|
||||
@@ -909,3 +968,32 @@ async def test_setup_when_modules_absent(
|
||||
await snapshot_platform(
|
||||
hass, entity_registry, snapshot, mock_config_entry_timers.entry_id
|
||||
)
|
||||
|
||||
|
||||
async def test_aux_select_becomes_unavailable_when_relay_occupied_mid_run(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_timers: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""AUX select becomes unavailable when its relay is claimed mid-run.
|
||||
|
||||
The supported_fn gate runs only at setup. The available property must
|
||||
re-evaluate it on every coordinator update so that an occupied relay
|
||||
makes existing entities unavailable instead of leaving them writable
|
||||
with stale values.
|
||||
"""
|
||||
with patch("homeassistant.components.neopool.PLATFORMS", [Platform.SELECT]):
|
||||
await setup_integration(hass, mock_config_entry_timers)
|
||||
|
||||
entity_id = _select_entity_id(hass, mock_config_entry_timers, "relay_aux1_mode")
|
||||
assert hass.states.get(entity_id) is not None
|
||||
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
|
||||
|
||||
occupied_data = {**MOCK_POOL_DATA, "MBF_PAR_HEATING_GPIO": 4} # relay 4 == AUX1
|
||||
mock_neopool_client.async_read_all.return_value = occupied_data
|
||||
freezer.tick(timedelta(seconds=60))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from neopool_modbus import InvalidStateReason, NeoPoolInvalidStateError
|
||||
@@ -23,13 +23,14 @@ from pytest_homeassistant.common import (
|
||||
)
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.neopool.const import FOLLOW_UP_REFRESH_DELAY
|
||||
from homeassistant.components.neopool.const import DOMAIN, FOLLOW_UP_REFRESH_DELAY
|
||||
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SwitchService
|
||||
from homeassistant.const import (
|
||||
SERVICE_TURN_OFF,
|
||||
SERVICE_TURN_ON,
|
||||
STATE_OFF,
|
||||
STATE_ON,
|
||||
STATE_UNAVAILABLE,
|
||||
Platform,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -628,6 +629,83 @@ async def test_aux_and_cover_absent_when_options_off(
|
||||
assert gated == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("occupied_relay", "hidden_suffix"),
|
||||
[(4, "_aux1"), (5, "_aux2"), (6, "_aux3"), (7, "_aux4")],
|
||||
)
|
||||
async def test_aux_switch_absent_when_relay_assigned_to_function(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_switch: MockConfigEntry,
|
||||
occupied_relay: int,
|
||||
hidden_suffix: str,
|
||||
) -> None:
|
||||
"""An AUX switch is not created when its relay is assigned to a function.
|
||||
|
||||
The option is enabled (mock_config_entry_switch), so this exercises the
|
||||
entity-level safety net, not the option gate.
|
||||
"""
|
||||
data = {**mock_neopool_client.async_read_all.return_value}
|
||||
data["MBF_PAR_PH_BASE_RELAY_GPIO"] = occupied_relay
|
||||
mock_neopool_client.async_read_all = AsyncMock(return_value=data)
|
||||
await setup_integration(hass, mock_config_entry_switch)
|
||||
|
||||
aux_suffixes = {
|
||||
suffix
|
||||
for suffix in ("_aux1", "_aux2", "_aux3", "_aux4")
|
||||
for e in er.async_entries_for_config_entry(
|
||||
entity_registry, mock_config_entry_switch.entry_id
|
||||
)
|
||||
if e.domain == SWITCH_DOMAIN and e.unique_id.endswith(suffix)
|
||||
}
|
||||
assert hidden_suffix not in aux_suffixes
|
||||
# The other three AUX relays stay free and keep their switches.
|
||||
assert aux_suffixes == {"_aux1", "_aux2", "_aux3", "_aux4"} - {hidden_suffix}
|
||||
|
||||
|
||||
async def test_occupied_aux_cleanup_removes_only_disabled_entities(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_switch: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Setup removes a disabled occupied-AUX entry but keeps an enabled one.
|
||||
|
||||
On an existing install the gate alone leaves a registered AUX entity as a
|
||||
restored, unavailable state. The cleanup drops such a stale entry only when
|
||||
it is disabled, so a user-enabled AUX keeps its customisations even once its
|
||||
relay becomes occupied.
|
||||
"""
|
||||
mock_config_entry_switch.add_to_hass(hass)
|
||||
# AUX1 relay 4 and AUX2 relay 5 are both claimed by a function.
|
||||
data = {**mock_neopool_client.async_read_all.return_value}
|
||||
data["MBF_PAR_PH_ACID_RELAY_GPIO"] = 4
|
||||
data["MBF_PAR_PH_BASE_RELAY_GPIO"] = 5
|
||||
mock_neopool_client.async_read_all = AsyncMock(return_value=data)
|
||||
serial = mock_config_entry_switch.unique_id
|
||||
# A stale disabled AUX1 entry (should be removed) and an enabled, customised
|
||||
# AUX2 entry (should be kept).
|
||||
disabled = entity_registry.async_get_or_create(
|
||||
SWITCH_DOMAIN,
|
||||
DOMAIN,
|
||||
f"{serial}_aux1",
|
||||
config_entry=mock_config_entry_switch,
|
||||
disabled_by=er.RegistryEntryDisabler.USER,
|
||||
)
|
||||
enabled = entity_registry.async_get_or_create(
|
||||
SWITCH_DOMAIN,
|
||||
DOMAIN,
|
||||
f"{serial}_aux2",
|
||||
config_entry=mock_config_entry_switch,
|
||||
)
|
||||
|
||||
await setup_integration(hass, mock_config_entry_switch)
|
||||
|
||||
assert entity_registry.async_get(disabled.entity_id) is None
|
||||
assert entity_registry.async_get(enabled.entity_id) is not None
|
||||
|
||||
|
||||
async def test_switch_write_schedules_follow_up_refresh(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
@@ -661,3 +739,32 @@ async def test_all_entities(
|
||||
await snapshot_platform(
|
||||
hass, entity_registry, snapshot, mock_config_entry_switch.entry_id
|
||||
)
|
||||
|
||||
|
||||
async def test_aux_switch_becomes_unavailable_when_relay_occupied_mid_run(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_switch: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""AUX switch becomes unavailable when its relay is claimed mid-run.
|
||||
|
||||
The supported_fn gate runs only at setup. The available property must
|
||||
re-evaluate it on every coordinator update so that an occupied relay
|
||||
makes existing entities unavailable instead of leaving them writable
|
||||
with stale values.
|
||||
"""
|
||||
with patch("homeassistant.components.neopool.PLATFORMS", [Platform.SWITCH]):
|
||||
await setup_integration(hass, mock_config_entry_switch)
|
||||
|
||||
entity_id = _entity_id_by_suffix(hass, mock_config_entry_switch, "_aux1")
|
||||
assert hass.states.get(entity_id) is not None
|
||||
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
|
||||
|
||||
occupied_data = {**MOCK_POOL_DATA, "MBF_PAR_HEATING_GPIO": 4} # relay 4 == AUX1
|
||||
mock_neopool_client.async_read_all.return_value = occupied_data
|
||||
freezer.tick(timedelta(seconds=60))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
|
||||
|
||||
@@ -21,7 +21,7 @@ from homeassistant.components.time import (
|
||||
TimeService,
|
||||
TimeServiceArgument,
|
||||
)
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.const import STATE_UNAVAILABLE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import entity_platform as ep, entity_registry as er
|
||||
@@ -986,6 +986,68 @@ async def test_client_close_waits_for_all_overlapping_flushes(
|
||||
assert close_saw_write_active is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("occupied_relay", "hidden_aux_number"),
|
||||
[(4, 1), (5, 2), (6, 3), (7, 4)],
|
||||
)
|
||||
async def test_aux_timer_absent_when_relay_assigned_to_function(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_timers: MockConfigEntry,
|
||||
occupied_relay: int,
|
||||
hidden_aux_number: int,
|
||||
) -> None:
|
||||
"""AUX timers are suppressed when their relay serves a built-in function.
|
||||
|
||||
The option is enabled (mock_config_entry_timers), so this exercises the
|
||||
entity-level safety net, not the option gate.
|
||||
"""
|
||||
data = {**mock_neopool_client.async_read_all.return_value}
|
||||
data["MBF_PAR_PH_BASE_RELAY_GPIO"] = occupied_relay
|
||||
mock_neopool_client.async_read_all = AsyncMock(return_value=data)
|
||||
with patch("homeassistant.components.neopool.PLATFORMS", [Platform.TIME]):
|
||||
await setup_integration(hass, mock_config_entry_timers)
|
||||
|
||||
all_entries = er.async_entries_for_config_entry(
|
||||
entity_registry, mock_config_entry_timers.entry_id
|
||||
)
|
||||
present_aux_suffixes = {
|
||||
suffix
|
||||
for n in range(1, 5)
|
||||
for suffix in (
|
||||
f"relay_aux{n}_start",
|
||||
f"relay_aux{n}_stop",
|
||||
f"relay_aux{n}b_start",
|
||||
f"relay_aux{n}b_stop",
|
||||
)
|
||||
if any(
|
||||
e.domain == TIME_DOMAIN and e.unique_id.endswith(f"_{suffix}")
|
||||
for e in all_entries
|
||||
)
|
||||
}
|
||||
hidden_suffixes = {
|
||||
f"relay_aux{hidden_aux_number}_start",
|
||||
f"relay_aux{hidden_aux_number}_stop",
|
||||
f"relay_aux{hidden_aux_number}b_start",
|
||||
f"relay_aux{hidden_aux_number}b_stop",
|
||||
}
|
||||
assert not (present_aux_suffixes & hidden_suffixes)
|
||||
# The other three AUX relays stay free and keep their timers.
|
||||
free_aux_numbers = {1, 2, 3, 4} - {hidden_aux_number}
|
||||
expected_free = {
|
||||
suffix
|
||||
for n in free_aux_numbers
|
||||
for suffix in (
|
||||
f"relay_aux{n}_start",
|
||||
f"relay_aux{n}_stop",
|
||||
f"relay_aux{n}b_start",
|
||||
f"relay_aux{n}b_stop",
|
||||
)
|
||||
}
|
||||
assert expected_free.issubset(present_aux_suffixes)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_neopool_client")
|
||||
async def test_all_entities(
|
||||
hass: HomeAssistant,
|
||||
@@ -1017,3 +1079,32 @@ async def test_setup_when_modules_absent(
|
||||
await snapshot_platform(
|
||||
hass, entity_registry, snapshot, mock_config_entry_timers.entry_id
|
||||
)
|
||||
|
||||
|
||||
async def test_aux_timer_becomes_unavailable_when_relay_occupied_mid_run(
|
||||
hass: HomeAssistant,
|
||||
mock_neopool_client: MagicMock,
|
||||
mock_config_entry_timers: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""AUX timer becomes unavailable when its relay is claimed mid-run.
|
||||
|
||||
The supported_fn gate runs only at setup. The available property must
|
||||
re-evaluate it on every coordinator update so that an occupied relay
|
||||
makes existing entities unavailable instead of leaving them writable
|
||||
with stale values.
|
||||
"""
|
||||
with patch("homeassistant.components.neopool.PLATFORMS", [Platform.TIME]):
|
||||
await setup_integration(hass, mock_config_entry_timers)
|
||||
|
||||
entity_id = _time_entity_id(hass, mock_config_entry_timers, "relay_aux1_start")
|
||||
assert hass.states.get(entity_id) is not None
|
||||
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
|
||||
|
||||
occupied_data = {**MOCK_POOL_DATA, "MBF_PAR_HEATING_GPIO": 4} # relay 4 == AUX1
|
||||
mock_neopool_client.async_read_all.return_value = occupied_data
|
||||
freezer.tick(timedelta(seconds=60))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
|
||||
|
||||
Reference in New Issue
Block a user