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>
237 lines
9.0 KiB
Python
237 lines
9.0 KiB
Python
"""Coordinator: owns the cloud session + MQTT connection for one spa and exposes
|
|
the latest telemetry to entities.
|
|
|
|
Read path:
|
|
* Default — subscribe to the spa's MQTT topics (cloud push).
|
|
* 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
|
|
from homeassistant.core import HomeAssistant, callback
|
|
from homeassistant.helpers.event import async_track_time_interval
|
|
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,
|
|
CONF_EMAIL,
|
|
CONF_LOCAL_STATUS_URL,
|
|
CONF_PASSWORD,
|
|
DEFAULT_CERT_DIR,
|
|
DOMAIN,
|
|
KEY_FILE,
|
|
LOCAL_FAILURES_BEFORE_CLOUD,
|
|
LOCAL_POLL_INTERVAL,
|
|
STALE_AFTER,
|
|
WATCHDOG_INTERVAL,
|
|
)
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
class HotSpringCoordinator(DataUpdateCoordinator[dict]):
|
|
def __init__(self, hass: HomeAssistant, entry: ConfigEntry):
|
|
super().__init__(hass, _LOGGER, name=DOMAIN)
|
|
self.entry = entry
|
|
self.cloud: HotSpringCloud | None = None
|
|
self.spa: HotSpringSpa | None = None
|
|
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)
|
|
return (
|
|
os.path.join(d, CERT_FILE),
|
|
os.path.join(d, KEY_FILE),
|
|
os.path.join(d, CA_FILE),
|
|
)
|
|
|
|
async def async_setup(self) -> None:
|
|
cert, key, ca = self._cert_paths()
|
|
cloud = HotSpringCloud(
|
|
self.entry.data[CONF_EMAIL], self.entry.data[CONF_PASSWORD], cert, key, ca
|
|
)
|
|
local = self._local_url
|
|
|
|
def _blocking_connect() -> HotSpringSpa:
|
|
cloud.login()
|
|
spas = cloud.get_spas()
|
|
if not spas:
|
|
raise RuntimeError("account has no spas")
|
|
self.spa_info = spas[0]
|
|
creds = cloud.fetch_mqtt_credentials()
|
|
spa = HotSpringSpa(self.spa_info.root_topic, creds, on_status=self._on_status)
|
|
status = None
|
|
if 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
|
|
|
|
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(
|
|
self.hass, self._async_poll_local, timedelta(seconds=LOCAL_POLL_INTERVAL)
|
|
)
|
|
|
|
async def _async_poll_local(self, _now) -> None:
|
|
if self.spa is None or not self._local_url:
|
|
return
|
|
try:
|
|
status = await self.hass.async_add_executor_job(
|
|
fetch_local_status, self._local_url
|
|
)
|
|
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)
|
|
|
|
async def _run(self, method_name: str, *args) -> None:
|
|
if self.spa is None:
|
|
raise RuntimeError("spa not connected")
|
|
await self.hass.async_add_executor_job(getattr(self.spa, method_name), *args)
|
|
|
|
async def async_set_temperature(self, value: int) -> None:
|
|
await self._run("set_temperature", value)
|
|
|
|
async def async_set_salt_level(self, value: int) -> None:
|
|
await self._run("set_water_care_level", value)
|
|
|
|
async def async_set_lights(self, on: bool) -> None:
|
|
await self._run("set_lights", on)
|
|
|
|
async def async_set_jets(self, on: bool) -> None:
|
|
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
|
|
if self.spa is not None:
|
|
await self.hass.async_add_executor_job(self.spa.disconnect)
|
|
await super().async_shutdown()
|