diff --git a/README.md b/README.md index 7f63fd9..1db1310 100644 --- a/README.md +++ b/README.md @@ -52,3 +52,18 @@ GitHub Actions runs Python compilation, JSON checks, basic protocol regression t ## License MIT. Community integration, not affiliated with the device manufacturer. + +## Winter mode (hivernage) + +The integration uses `input_boolean.mode_hivernage`. If it does not exist, +BrioWil creates a native Home Assistant input_boolean entity at startup, +initially off, with a snowflake icon. The automatically created entity is +recreated after each restart and restores its previous state. It is not a +UI-managed Helper stored in Home Assistant's shared helper storage. An existing +helper with this entity ID is always reused untouched. + +When the helper is **on**, BrioWil makes no TCP status requests and its light, +effect speed, refresh-frequency number and diagnostics are `unavailable`. +Switching it **off** requests fresh status immediately. Hardware control +commands are blocked while winter mode is on. This avoids repeated network +errors when the pool controller is disconnected for winter. diff --git a/custom_components/briowil/__init__.py b/custom_components/briowil/__init__.py index 8ebb036..869c24a 100644 --- a/custom_components/briowil/__init__.py +++ b/custom_components/briowil/__init__.py @@ -1,75 +1,103 @@ -"""Integration entry point: create the shared TCP polling coordinator; reload when options change.""" +"""BrioWil setup and its optional winter-mode input boolean. -from homeassistant.const import Platform - -from .const import DOMAIN -from .coordinator import BrioWilCoordinator +A missing input_boolean.mode_hivernage is created as a genuine Home Assistant +InputBoolean entity. It is recreated on startup, restores its previous state, +and is never written directly into Home Assistant's shared .storage files. +An existing helper is reused without modification. +""" -PLATFORMS = [ - Platform.LIGHT, - Platform.NUMBER, - Platform.SELECT, - Platform.SENSOR, -] +import logging +from homeassistant.components.input_boolean.const import DATA_INPUT_BOOLEAN +from homeassistant.components.input_boolean.entity import InputBoolean +from homeassistant.const import Platform +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.event import async_track_state_change_event -async def async_setup_entry( - hass, - entry, -): +from .const import DOMAIN, WINTER_MODE_ENTITY_ID +from .coordinator import BrioWilCoordinator - coordinator = BrioWilCoordinator( - hass, - entry, - ) +_LOGGER = logging.getLogger(__name__) + +PLATFORMS = [Platform.LIGHT, Platform.NUMBER, Platform.SELECT, Platform.SENSOR] + + +async def _async_ensure_winter_helper(hass, coordinator): + """Add a working input_boolean only if the requested ID is unused.""" + registry = er.async_get(hass) + if hass.states.get(WINTER_MODE_ENTITY_ID) or registry.async_get( + WINTER_MODE_ENTITY_ID + ): + _LOGGER.debug("Using existing %s", WINTER_MODE_ENTITY_ID) + return + + config = { + "id": "mode_hivernage", + "name": "Mode hivernage", + "icon": "mdi:snowflake", + } + # Preserve the state when this config entry reloads inside a HA session. + cached = hass.data[DOMAIN].get("_winter_state") + if cached is not None: + config["initial"] = cached + + helper = InputBoolean.from_yaml(config) + # Avoid a stale registry entry on a Home Assistant restart. The entity + # remains a genuine input_boolean with turn_on/off and restore_state. + helper._attr_unique_id = None + await hass.data[DATA_INPUT_BOOLEAN].component.async_add_entities([helper]) + coordinator.created_winter_helper = True + _LOGGER.info("Created %s for BrioWil", WINTER_MODE_ENTITY_ID) + + +async def async_setup_entry(hass, entry): + """Create optional helper before starting TCP polling.""" + hass.data.setdefault(DOMAIN, {}) + coordinator = BrioWilCoordinator(hass, entry) + await _async_ensure_winter_helper(hass, coordinator) await coordinator.async_config_entry_first_refresh() - - hass.data.setdefault( - DOMAIN, - {}, - ) - hass.data[DOMAIN][entry.entry_id] = coordinator - - await hass.config_entries.async_forward_entry_setups( - entry, - PLATFORMS, - ) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + async def _winter_changed(event): + """Immediately publish unavailable, or poll when winter ends.""" + new_state = event.data.get("new_state") + _LOGGER.debug( + "Winter mode changed: %s", + new_state.state if new_state else "removed", + ) + if coordinator.is_winter_mode: + coordinator.async_set_updated_data(None) + else: + await coordinator.async_request_refresh() entry.async_on_unload( - entry.add_update_listener( - _async_update_listener - ) + async_track_state_change_event(hass, [WINTER_MODE_ENTITY_ID], _winter_changed) ) - + entry.async_on_unload(entry.add_update_listener(_async_update_listener)) return True -async def _async_update_listener( - hass, - entry, -): +async def _async_update_listener(hass, entry): + await hass.config_entries.async_reload(entry.entry_id) - await hass.config_entries.async_reload( - entry.entry_id - ) +async def async_unload_entry(hass, entry): + coordinator = hass.data.get(DOMAIN, {}).get(entry.entry_id) + if coordinator is not None and coordinator.created_winter_helper: + # Cache state before unloading so an options-triggered reload keeps it. + state = hass.states.get(WINTER_MODE_ENTITY_ID) + if state is not None and state.state in ("on", "off"): + hass.data[DOMAIN]["_winter_state"] = state.state == "on" -async def async_unload_entry( - hass, - entry, -): + unloaded = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + if not unloaded: + return False - unload_ok = await hass.config_entries.async_unload_platforms( - entry, - PLATFORMS, - ) - - if unload_ok: - hass.data[DOMAIN].pop( - entry.entry_id, - None, + if coordinator is not None and coordinator.created_winter_helper: + await hass.data[DATA_INPUT_BOOLEAN].component.async_remove_entity( + WINTER_MODE_ENTITY_ID ) - - return unload_ok \ No newline at end of file + hass.data[DOMAIN].pop(entry.entry_id, None) + return True diff --git a/custom_components/briowil/const.py b/custom_components/briowil/const.py index 66d2396..604f8c3 100644 --- a/custom_components/briowil/const.py +++ b/custom_components/briowil/const.py @@ -80,4 +80,6 @@ EFFECT_SPEED_NUMBER_TO_NAME = { value: key for key, value in EFFECT_SPEED_MAP.items() -} \ No newline at end of file +} +# Optional global helper used to suspend all pool-controller communications. +WINTER_MODE_ENTITY_ID = "input_boolean.mode_hivernage" diff --git a/custom_components/briowil/coordinator.py b/custom_components/briowil/coordinator.py index 8b0bcd4..0bc54cd 100644 --- a/custom_components/briowil/coordinator.py +++ b/custom_components/briowil/coordinator.py @@ -16,6 +16,7 @@ CONF_REFRESH_INTERVAL, DEFAULT_REFRESH_INTERVAL, COLOR_NUMBER_TO_NAME, + WINTER_MODE_ENTITY_ID, ) _LOGGER = logging.getLogger(__name__) @@ -255,6 +256,7 @@ def __init__( ): self.entry = entry + self.created_winter_helper = False self.server_ip = entry.data[ "server_ip" @@ -281,15 +283,20 @@ def __init__( ), ) - async def _async_update_data( - self, - ): + @property + def is_winter_mode(self): + """True when the Home Assistant winter-mode helper is on.""" + return self.hass.states.is_state(WINTER_MODE_ENTITY_ID, "on") - _LOGGER.debug( - "Polling BrioWil status" - ) + async def _async_update_data(self): + """Skip all socket activity during winter mode.""" + if self.is_winter_mode: + _LOGGER.debug("Winter mode enabled: skipping BrioWil TCP poll") + return None - return await self.hass.async_add_executor_job( - get_pool_light_status, - self.server_ip, - ) \ No newline at end of file + _LOGGER.debug("Polling BrioWil status") + result = await self.hass.async_add_executor_job( + get_pool_light_status, self.server_ip + ) + # A toggle can occur while a network request is already in flight. + return None if self.is_winter_mode else result \ No newline at end of file diff --git a/custom_components/briowil/light.py b/custom_components/briowil/light.py index d7b265a..33476ff 100644 --- a/custom_components/briowil/light.py +++ b/custom_components/briowil/light.py @@ -13,6 +13,7 @@ LightEntityFeature, ) +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity @@ -174,7 +175,8 @@ def device_info(self): @property def available(self): return ( - self.coordinator.last_update_success + not self.coordinator.is_winter_mode + and self.coordinator.last_update_success and self.coordinator.data is not None ) @@ -236,6 +238,8 @@ async def async_turn_on( self, **kwargs, ): + if self.coordinator.is_winter_mode: + raise HomeAssistantError("BrioWil is unavailable during winter mode") # # Brightness changes are handled separately. @@ -377,6 +381,8 @@ async def async_turn_off( self, **kwargs, ): + if self.coordinator.is_winter_mode: + raise HomeAssistantError("BrioWil is unavailable during winter mode") _LOGGER.debug( "Turning light off" ) diff --git a/custom_components/briowil/manifest.json b/custom_components/briowil/manifest.json index bb76a6d..33bb7e8 100644 --- a/custom_components/briowil/manifest.json +++ b/custom_components/briowil/manifest.json @@ -8,10 +8,13 @@ "@papou-github" ], "config_flow": true, + "dependencies": [ + "input_boolean" + ], "documentation": "https://github.com/papou-github/briowil", "integration_type": "device", "iot_class": "local_polling", "issue_tracker": "https://github.com/papou-github/briowil/issues", "requirements": [], - "version": "1.0.1" + "version": "1.0.2" } diff --git a/custom_components/briowil/number.py b/custom_components/briowil/number.py index ccc9964..16a967c 100644 --- a/custom_components/briowil/number.py +++ b/custom_components/briowil/number.py @@ -5,6 +5,7 @@ from homeassistant.components.number import ( NumberEntity, ) +from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( DOMAIN, @@ -41,6 +42,7 @@ async def async_setup_entry( class BrioWilRefreshFrequency( + CoordinatorEntity, NumberEntity, ): @@ -51,9 +53,9 @@ def __init__( coordinator, ): + super().__init__(coordinator) self.hass = hass self.entry = entry - self.coordinator = coordinator self._attr_name = ( "Refresh Frequency" @@ -92,6 +94,10 @@ def device_info( "model": "TCP Pool Controller", } + @property + def available(self): + return not self.coordinator.is_winter_mode + @property def native_value( self, diff --git a/custom_components/briowil/select.py b/custom_components/briowil/select.py index 95974e9..6375369 100644 --- a/custom_components/briowil/select.py +++ b/custom_components/briowil/select.py @@ -8,6 +8,7 @@ SelectEntity, ) +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, ) @@ -123,6 +124,14 @@ def device_info( "model": "TCP Pool Controller", } + @property + def available(self): + return ( + not self.coordinator.is_winter_mode + and self.coordinator.last_update_success + and self.coordinator.data is not None + ) + @property def current_option( self, @@ -143,6 +152,8 @@ async def async_select_option( self, option, ): + if self.coordinator.is_winter_mode: + raise HomeAssistantError("BrioWil is unavailable during winter mode") speed_number = EFFECT_SPEED_MAP[ option diff --git a/custom_components/briowil/sensor.py b/custom_components/briowil/sensor.py index aff6974..0bed25e 100644 --- a/custom_components/briowil/sensor.py +++ b/custom_components/briowil/sensor.py @@ -131,6 +131,14 @@ def device_info( "model": "TCP Pool Controller", } + @property + def available(self): + return ( + not self.coordinator.is_winter_mode + and self.coordinator.last_update_success + and self.coordinator.data is not None + ) + @property def native_value( self, diff --git a/tests/test_winter_mode.py b/tests/test_winter_mode.py new file mode 100644 index 0000000..c8aad7d --- /dev/null +++ b/tests/test_winter_mode.py @@ -0,0 +1,28 @@ +"""Static checks for BrioWil winter-mode integration logic.""" +import ast +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] / "custom_components" / "briowil" + +class WinterModeTests(unittest.TestCase): + def test_python_syntax(self): + for path in ROOT.glob("*.py"): + ast.parse(path.read_text(), filename=str(path)) + + def test_coordinator_skips_tcp_during_winter(self): + content = (ROOT / "coordinator.py").read_text() + self.assertIn("if self.is_winter_mode:", content) + self.assertIn("return None", content) + self.assertIn("WINTER_MODE_ENTITY_ID", content) + + def test_helper_creation_and_listener(self): + content = (ROOT / "__init__.py").read_text() + self.assertIn("InputBoolean.from_yaml", content) + self.assertIn("async_track_state_change_event", content) + self.assertIn("async_set_updated_data(None)", content) + + def test_all_platforms_unavailable(self): + for name in ("light.py", "sensor.py", "select.py", "number.py"): + content = (ROOT / name).read_text() + self.assertIn("self.coordinator.is_winter_mode", content, name)