Survive a dead local status URL, and go unavailable when the spa is not reporting (#2)

This commit was merged in pull request #2.
This commit is contained in:
dfritz committed 2026-11-15 04:51:23 +00:00
1 parent 46a353071d
commit 5af5412248
13 files changed
+264 -15

No files matched your search

+35
View File
@@ -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
@@ -87,6 +88,24 @@ class HotSpringSpa:
self._client.loop_stop()
self._client.disconnect()
def subscribe(self) -> None:
"""Start reading telemetry from the broker (also after a reconnect)."""
self._subscribe = True
if self._client and self._connected.is_set():
self._client.subscribe(STATUS_WILDCARD.format(root=self.root_topic), qos=1)
def unsubscribe(self) -> None:
"""Stop reading telemetry from the broker and drop what it delivered.
Used when the local ``/status`` source takes over, so a stale cloud
value can never shadow a fresh local one.
"""
self._subscribe = False
if self._client and self._connected.is_set():
self._client.unsubscribe(STATUS_WILDCARD.format(root=self.root_topic))
self.state = {}
self.merged = {}
@property
def connected(self) -> bool:
return bool(self._client) and self._connected.is_set()
@@ -106,7 +125,13 @@ 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
suffix = msg.topic[len(self.root_topic) + 1:]
try:
payload = json.loads(msg.payload.decode("utf-8", "replace"))
@@ -118,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 {}
+2 -2
View File
@@ -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]
@@ -82,6 +82,34 @@ class HotSpringConfigFlow(ConfigFlow, domain=DOMAIN):
step_id="user", data_schema=_schema(user_input), errors=errors
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Change the local ``/status`` URL without signing in again.
The dongle takes its address from DHCP, so this is the one setting that
goes stale on its own.
"""
entry = self._get_reconfigure_entry()
if user_input is not None:
url = (user_input.get(CONF_LOCAL_STATUS_URL) or "").strip()
return self.async_update_reload_and_abort(
entry, data_updates={CONF_LOCAL_STATUS_URL: url}
)
return self.async_show_form(
step_id="reconfigure",
data_schema=vol.Schema(
{
vol.Optional(
CONF_LOCAL_STATUS_URL,
description={
"suggested_value": entry.data.get(CONF_LOCAL_STATUS_URL, "")
},
): str,
}
),
)
async def _validate(self, data: dict[str, Any]) -> str | None:
"""Return None on success, or an error key."""
cert_dir = data[CONF_CERT_DIR]
+15 -1
View File
@@ -82,9 +82,23 @@ CONF_CERT_DIR = "cert_dir"
# Optional: the dongle's local ``/status`` URL (e.g. http://<spa-ip>/status).
# When set, telemetry is polled locally instead of subscribed over the cloud MQTT
# broker, so monitoring stays on-LAN and off the vendor cloud. Control still uses
# the cloud MQTT connection. Only reachable when HA is on the spa's LAN.
# the cloud MQTT connection. Only reachable when HA is on the spa's LAN. The
# dongle has no DNS name and takes its address from DHCP, so this URL goes stale
# when the lease changes; the coordinator then reads from the cloud until the
# URL is corrected (reconfigure the entry) or answers again.
CONF_LOCAL_STATUS_URL = "local_status_url"
LOCAL_POLL_INTERVAL = 30 # seconds
# Consecutive failed local polls before telemetry is read from the cloud instead.
# 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
+107 -3
View File
@@ -6,12 +6,16 @@ Read path:
* If ``local_status_url`` is configured — poll the dongle's local ``/status``
endpoint instead, keeping monitoring on-LAN and off the vendor cloud. The MQTT
connection is still opened (control is cloud-only) but not subscribed.
* If that local endpoint does not answer (the dongle's DHCP address changed, or
it is off the LAN) — read from the cloud until it does. A dead local URL must
never take the whole integration, and with it control, down.
"""
from __future__ import annotations
import logging
import os
import time
from datetime import timedelta
from homeassistant.config_entries import ConfigEntry
@@ -21,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,
@@ -30,7 +35,10 @@ from .constants import (
DEFAULT_CERT_DIR,
DOMAIN,
KEY_FILE,
LOCAL_FAILURES_BEFORE_CLOUD,
LOCAL_POLL_INTERVAL,
STALE_AFTER,
WATCHDOG_INTERVAL,
)
_LOGGER = logging.getLogger(__name__)
@@ -45,6 +53,14 @@ class HotSpringCoordinator(DataUpdateCoordinator[dict]):
self.spa_info: Spa | None = None
self._local_url: str | None = entry.data.get(CONF_LOCAL_STATUS_URL) or None
self._unsub_poll = None
# True while telemetry comes from the local URL; False while the cloud
# 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)
@@ -69,10 +85,22 @@ class HotSpringCoordinator(DataUpdateCoordinator[dict]):
self.spa_info = spas[0]
creds = cloud.fetch_mqtt_credentials()
spa = HotSpringSpa(self.spa_info.root_topic, creds, on_status=self._on_status)
# Local read source -> connect for control only (no MQTT subscribe).
spa.connect(subscribe=not local)
status = None
if local:
spa.ingest_status(fetch_local_status(local))
try:
status = fetch_local_status(local)
except HotSpringApiError as err:
_LOGGER.warning(
"Spa local status URL %s does not answer (%s); reading "
"telemetry from the cloud until it does",
local,
err,
)
self._local_ok = status is not None
# Local read source -> connect for control only (no MQTT subscribe).
spa.connect(subscribe=status is None)
if status is not None:
spa.ingest_status(status)
else:
spa.wait_for_state()
return spa
@@ -80,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(
@@ -95,13 +126,83 @@ class HotSpringCoordinator(DataUpdateCoordinator[dict]):
)
except HotSpringApiError as err:
_LOGGER.debug("local /status poll failed: %s", err)
self._local_failures += 1
if self._local_ok and self._local_failures >= LOCAL_FAILURES_BEFORE_CLOUD:
self._local_ok = False
_LOGGER.warning(
"Spa local status URL %s stopped answering (%s); reading "
"telemetry from the cloud until it does",
self._local_url,
err,
)
await self.hass.async_add_executor_job(self.spa.subscribe)
return
self._local_failures = 0
if not self._local_ok:
self._local_ok = True
_LOGGER.info("Spa local status URL %s answers again", self._local_url)
await self.hass.async_add_executor_job(self.spa.unsubscribe)
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)
@@ -124,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
+19
View File
@@ -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
+1 -1
View File
@@ -8,5 +8,5 @@
"iot_class": "cloud_push",
"integration_type": "hub",
"requirements": [],
"version": "0.1.0"
"version": "0.2.0"
}
+2 -2
View File
@@ -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
+2 -2
View File
@@ -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
+12 -1
View File
@@ -13,6 +13,16 @@
"data_description": {
"local_status_url": "If Home Assistant is on the spa's LAN, e.g. http://<spa-ip>/status, monitoring is polled locally instead of over the cloud; control still uses the cloud."
}
},
"reconfigure": {
"title": "Hot Spring Connected Spa",
"description": "Change where monitoring is read from. The spa's address comes from DHCP and can change; while the URL does not answer, monitoring is read from the cloud.",
"data": {
"local_status_url": "Local /status URL (optional)"
},
"data_description": {
"local_status_url": "e.g. http://<spa-ip>/status. Leave blank to read from the cloud."
}
}
},
"error": {
@@ -22,7 +32,8 @@
"unknown": "Unexpected error."
},
"abort": {
"already_configured": "This spa account is already configured."
"already_configured": "This spa account is already configured.",
"reconfigure_successful": "Monitoring source updated."
}
},
"entity": {
+2 -2
View File
@@ -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
@@ -13,6 +13,16 @@
"data_description": {
"local_status_url": "If Home Assistant is on the spa's LAN, e.g. http://<spa-ip>/status, monitoring is polled locally instead of over the cloud; control still uses the cloud."
}
},
"reconfigure": {
"title": "Hot Spring Connected Spa",
"description": "Change where monitoring is read from. The spa's address comes from DHCP and can change; while the URL does not answer, monitoring is read from the cloud.",
"data": {
"local_status_url": "Local /status URL (optional)"
},
"data_description": {
"local_status_url": "e.g. http://<spa-ip>/status. Leave blank to read from the cloud."
}
}
},
"error": {
@@ -22,7 +32,8 @@
"unknown": "Unexpected error."
},
"abort": {
"already_configured": "This spa account is already configured."
"already_configured": "This spa account is already configured.",
"reconfigure_successful": "Monitoring source updated."
}
},
"entity": {