Make spa entities unavailable when the spa is not reporting
A module that is online but cut off from the control box keeps serving and publishing a full document of blank and default values. Read literally that is an idle spa: no temperatures, salt level 0, lights and jets off, and controls that accept a value and snap back. - The spa counts as reporting only while telemetry is fresh (something arrived in the last five minutes) and carries control-box data. Otherwise every entity is unavailable, and the reason is logged once per change. - The entry still loads in that state, so entities return on their own when the spa reports again. - A watchdog catches silence between updates, and reloads the entry when the broker connection stays down for three minutes. The broker is the only control path and its credentials rotate; paho reconnects with the old ones, so only a fresh sign-in recovers it. - Version 0.2.0. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
3ba61e9c0b
commit
298df5864a
9 files changed
+120
-9
No files matched your search
@@ -74,6 +74,7 @@ class HotSpringSpa:
|
||||
cl.username_pw_set(self._creds.user, self._creds.password)
|
||||
cl.tls_set_context(ssl.create_default_context()) # broker uses a public CA
|
||||
cl.on_connect = self._on_connect
|
||||
cl.on_disconnect = self._on_disconnect
|
||||
cl.on_message = self._on_message
|
||||
cl.reconnect_delay_set(min_delay=1, max_delay=60)
|
||||
self._client = cl
|
||||
@@ -124,6 +125,10 @@ class HotSpringSpa:
|
||||
client.subscribe(STATUS_WILDCARD.format(root=self.root_topic), qos=1)
|
||||
self._connected.set()
|
||||
|
||||
def _on_disconnect(self, client, userdata, *args):
|
||||
# paho reconnects by itself; until it does, commands go nowhere.
|
||||
self._connected.clear()
|
||||
|
||||
def _on_message(self, client, userdata, msg):
|
||||
if not self._subscribe:
|
||||
return
|
||||
@@ -138,6 +143,16 @@ class HotSpringSpa:
|
||||
self._on_status(suffix, payload)
|
||||
|
||||
# -- parsed reads ---------------------------------------------------------
|
||||
def reporting(self) -> bool:
|
||||
"""True when the telemetry carries data from the spa's control box.
|
||||
|
||||
A module that is online but cut off from the control box keeps serving
|
||||
and publishing a full document of blank and default values (no
|
||||
temperatures, salt level 0, lights and jets off). Read literally that
|
||||
looks like a working, idle spa, so it has to be told apart.
|
||||
"""
|
||||
return self.setpoint() is not None or self.current_temperature() is not None
|
||||
|
||||
def _heater(self) -> dict:
|
||||
return (self.merged.get("heater") or {}).get("status") or {}
|
||||
|
||||
|
||||
@@ -11,11 +11,11 @@ from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from . import HotSpringConfigEntry
|
||||
from .constants import DOMAIN, MANUFACTURER
|
||||
from .coordinator import HotSpringCoordinator
|
||||
from .entity import HotSpringEntity
|
||||
|
||||
# Hot Spot spas run 80-104 F.
|
||||
MIN_TEMP_F = 80
|
||||
@@ -30,7 +30,7 @@ async def async_setup_entry(
|
||||
async_add_entities([HotSpringClimate(entry.runtime_data)])
|
||||
|
||||
|
||||
class HotSpringClimate(CoordinatorEntity[HotSpringCoordinator], ClimateEntity):
|
||||
class HotSpringClimate(HotSpringEntity, ClimateEntity):
|
||||
_attr_has_entity_name = True
|
||||
_attr_name = None # use the device name
|
||||
_attr_hvac_modes = [HVACMode.HEAT]
|
||||
|
||||
@@ -92,6 +92,14 @@ LOCAL_POLL_INTERVAL = 30 # seconds
|
||||
# The local poll keeps running and takes over again as soon as it answers.
|
||||
LOCAL_FAILURES_BEFORE_CLOUD = 4
|
||||
|
||||
# Health. The spa counts as reporting only while telemetry is fresh and carries
|
||||
# control-box data; otherwise every entity is unavailable. The watchdog also
|
||||
# reloads the entry when the broker connection (the only control path) stays
|
||||
# down, because broker credentials rotate and paho reconnects with the old ones.
|
||||
WATCHDOG_INTERVAL = 60 # seconds
|
||||
STALE_AFTER = 300 # seconds without any telemetry
|
||||
BROKER_DOWN_TICKS_BEFORE_RELOAD = 3 # consecutive watchdog ticks
|
||||
|
||||
# The vendor mutual-TLS client certificate is NOT shipped in this repo (it is
|
||||
# Watkins material extractable from the app APK). Place the three PEM files here
|
||||
# on the Home Assistant host; see the README.
|
||||
|
||||
@@ -15,6 +15,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import timedelta
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
@@ -24,6 +25,7 @@ from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
|
||||
|
||||
from .api import HotSpringApiError, HotSpringCloud, HotSpringSpa, Spa, fetch_local_status
|
||||
from .constants import (
|
||||
BROKER_DOWN_TICKS_BEFORE_RELOAD,
|
||||
CA_FILE,
|
||||
CERT_FILE,
|
||||
CONF_CERT_DIR,
|
||||
@@ -35,6 +37,8 @@ from .constants import (
|
||||
KEY_FILE,
|
||||
LOCAL_FAILURES_BEFORE_CLOUD,
|
||||
LOCAL_POLL_INTERVAL,
|
||||
STALE_AFTER,
|
||||
WATCHDOG_INTERVAL,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -53,6 +57,10 @@ class HotSpringCoordinator(DataUpdateCoordinator[dict]):
|
||||
# subscription is standing in for it.
|
||||
self._local_ok = False
|
||||
self._local_failures = 0
|
||||
self._unsub_watchdog = None
|
||||
self._last_status: float | None = None # monotonic time of the last telemetry
|
||||
self._reporting: bool | None = None # last health state that was logged
|
||||
self._broker_down_ticks = 0
|
||||
|
||||
def _cert_paths(self) -> tuple[str, str, str]:
|
||||
d = self.entry.data.get(CONF_CERT_DIR, DEFAULT_CERT_DIR)
|
||||
@@ -100,6 +108,9 @@ class HotSpringCoordinator(DataUpdateCoordinator[dict]):
|
||||
self.cloud = cloud
|
||||
self.spa = await self.hass.async_add_executor_job(_blocking_connect)
|
||||
self.async_set_updated_data(self.spa.merged)
|
||||
self._unsub_watchdog = async_track_time_interval(
|
||||
self.hass, self._async_watchdog, timedelta(seconds=WATCHDOG_INTERVAL)
|
||||
)
|
||||
|
||||
if local:
|
||||
self._unsub_poll = async_track_time_interval(
|
||||
@@ -134,9 +145,64 @@ class HotSpringCoordinator(DataUpdateCoordinator[dict]):
|
||||
self.spa.ingest_status(status)
|
||||
self.async_set_updated_data(self.spa.merged)
|
||||
|
||||
@property
|
||||
def spa_reporting(self) -> bool:
|
||||
"""True while fresh telemetry carries control-box data.
|
||||
|
||||
Entities are unavailable whenever this is False: the module is cut off
|
||||
from the control box, or nothing has arrived from either read path.
|
||||
"""
|
||||
if self.spa is None or self._last_status is None:
|
||||
return False
|
||||
if time.monotonic() - self._last_status > STALE_AFTER:
|
||||
return False
|
||||
return self.spa.reporting()
|
||||
|
||||
@callback
|
||||
def _note_reporting(self) -> bool:
|
||||
"""Log a health change once; return True when it changed."""
|
||||
reporting = self.spa_reporting
|
||||
if reporting == self._reporting:
|
||||
return False
|
||||
self._reporting = reporting
|
||||
if reporting:
|
||||
_LOGGER.info("Spa is reporting")
|
||||
elif self.spa is not None and self.spa.merged and not self.spa.reporting():
|
||||
_LOGGER.warning(
|
||||
"Spa is not reporting: the module answers but has no data from "
|
||||
"the control box"
|
||||
)
|
||||
else:
|
||||
_LOGGER.warning("Spa is not reporting: no telemetry is arriving")
|
||||
return True
|
||||
|
||||
@callback
|
||||
def async_set_updated_data(self, data: dict) -> None:
|
||||
self._note_reporting()
|
||||
super().async_set_updated_data(data)
|
||||
|
||||
@callback
|
||||
def _async_watchdog(self, _now) -> None:
|
||||
"""Catch what no telemetry update can: silence, and a dead control path."""
|
||||
if self._note_reporting():
|
||||
self.async_update_listeners()
|
||||
if self.spa is None or self.spa.connected:
|
||||
self._broker_down_ticks = 0
|
||||
return
|
||||
self._broker_down_ticks += 1
|
||||
if self._broker_down_ticks >= BROKER_DOWN_TICKS_BEFORE_RELOAD:
|
||||
_LOGGER.warning(
|
||||
"Spa broker connection has been down for %s s; reloading to sign "
|
||||
"in again and fetch current broker credentials",
|
||||
self._broker_down_ticks * WATCHDOG_INTERVAL,
|
||||
)
|
||||
self._broker_down_ticks = 0
|
||||
self.hass.config_entries.async_schedule_reload(self.entry.entry_id)
|
||||
|
||||
@callback
|
||||
def _on_status(self, suffix: str, payload: dict) -> None:
|
||||
"""Runs on paho's thread (MQTT) or the executor (local); hop to the loop."""
|
||||
self._last_status = time.monotonic()
|
||||
if self.spa is None:
|
||||
return
|
||||
self.hass.loop.call_soon_threadsafe(self.async_set_updated_data, self.spa.merged)
|
||||
@@ -159,6 +225,9 @@ class HotSpringCoordinator(DataUpdateCoordinator[dict]):
|
||||
await self._run("set_jets", on)
|
||||
|
||||
async def async_shutdown(self) -> None:
|
||||
if self._unsub_watchdog is not None:
|
||||
self._unsub_watchdog()
|
||||
self._unsub_watchdog = None
|
||||
if self._unsub_poll is not None:
|
||||
self._unsub_poll()
|
||||
self._unsub_poll = None
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Base entity: unavailable whenever the spa is not reporting."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from .coordinator import HotSpringCoordinator
|
||||
|
||||
|
||||
class HotSpringEntity(CoordinatorEntity[HotSpringCoordinator]):
|
||||
"""A spa entity that never presents blank or stale telemetry as a state.
|
||||
|
||||
Without this, a module cut off from the control box shows up as an idle spa
|
||||
with controls that accept a value and snap back.
|
||||
"""
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
return super().available and self.coordinator.spa_reporting
|
||||
@@ -8,5 +8,5 @@
|
||||
"iot_class": "cloud_push",
|
||||
"integration_type": "hub",
|
||||
"requirements": [],
|
||||
"version": "0.1.1"
|
||||
"version": "0.2.0"
|
||||
}
|
||||
@@ -6,11 +6,11 @@ from homeassistant.components.number import NumberEntity, NumberMode
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from . import HotSpringConfigEntry
|
||||
from .constants import DOMAIN, MANUFACTURER, SALT_LEVEL_MAX, SALT_LEVEL_MIN
|
||||
from .coordinator import HotSpringCoordinator
|
||||
from .entity import HotSpringEntity
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
@@ -21,7 +21,7 @@ async def async_setup_entry(
|
||||
async_add_entities([HotSpringSaltLevel(entry.runtime_data)])
|
||||
|
||||
|
||||
class HotSpringSaltLevel(CoordinatorEntity[HotSpringCoordinator], NumberEntity):
|
||||
class HotSpringSaltLevel(HotSpringEntity, NumberEntity):
|
||||
_attr_has_entity_name = True
|
||||
_attr_translation_key = "salt_output_level"
|
||||
_attr_native_min_value = SALT_LEVEL_MIN
|
||||
|
||||
@@ -15,11 +15,11 @@ from homeassistant.const import UnitOfTemperature
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from . import HotSpringConfigEntry
|
||||
from .constants import DOMAIN, MANUFACTURER
|
||||
from .coordinator import HotSpringCoordinator
|
||||
from .entity import HotSpringEntity
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
@@ -58,7 +58,7 @@ async def async_setup_entry(
|
||||
async_add_entities(HotSpringSensor(coordinator, d) for d in SENSORS)
|
||||
|
||||
|
||||
class HotSpringSensor(CoordinatorEntity[HotSpringCoordinator], SensorEntity):
|
||||
class HotSpringSensor(HotSpringEntity, SensorEntity):
|
||||
_attr_has_entity_name = True
|
||||
entity_description: HotSpringSensorDescription
|
||||
|
||||
|
||||
@@ -9,11 +9,11 @@ from homeassistant.components.switch import SwitchEntity, SwitchEntityDescriptio
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from . import HotSpringConfigEntry
|
||||
from .constants import DOMAIN, MANUFACTURER
|
||||
from .coordinator import HotSpringCoordinator
|
||||
from .entity import HotSpringEntity
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
@@ -49,7 +49,7 @@ async def async_setup_entry(
|
||||
async_add_entities(HotSpringSwitch(coordinator, d) for d in SWITCHES)
|
||||
|
||||
|
||||
class HotSpringSwitch(CoordinatorEntity[HotSpringCoordinator], SwitchEntity):
|
||||
class HotSpringSwitch(HotSpringEntity, SwitchEntity):
|
||||
_attr_has_entity_name = True
|
||||
entity_description: HotSpringSwitchDescription
|
||||
|
||||
|
||||
Reference in new issue
Block a user