diff --git a/custom_components/hotspring/api/spa.py b/custom_components/hotspring/api/spa.py index 3207469..5941d4c 100644 --- a/custom_components/hotspring/api/spa.py +++ b/custom_components/hotspring/api/spa.py @@ -87,6 +87,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() @@ -107,6 +125,8 @@ class HotSpringSpa: self._connected.set() 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")) diff --git a/custom_components/hotspring/config_flow.py b/custom_components/hotspring/config_flow.py index 1e6a521..57134d4 100644 --- a/custom_components/hotspring/config_flow.py +++ b/custom_components/hotspring/config_flow.py @@ -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] diff --git a/custom_components/hotspring/constants.py b/custom_components/hotspring/constants.py index 9a05c06..8f8580b 100644 --- a/custom_components/hotspring/constants.py +++ b/custom_components/hotspring/constants.py @@ -82,9 +82,15 @@ CONF_CERT_DIR = "cert_dir" # Optional: the dongle's local ``/status`` URL (e.g. http:///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 # 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 diff --git a/custom_components/hotspring/coordinator.py b/custom_components/hotspring/coordinator.py index a8403f1..b2ab653 100644 --- a/custom_components/hotspring/coordinator.py +++ b/custom_components/hotspring/coordinator.py @@ -6,6 +6,9 @@ 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 @@ -30,6 +33,7 @@ from .constants import ( DEFAULT_CERT_DIR, DOMAIN, KEY_FILE, + LOCAL_FAILURES_BEFORE_CLOUD, LOCAL_POLL_INTERVAL, ) @@ -45,6 +49,10 @@ 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 def _cert_paths(self) -> tuple[str, str, str]: d = self.entry.data.get(CONF_CERT_DIR, DEFAULT_CERT_DIR) @@ -69,10 +77,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 @@ -95,7 +115,22 @@ 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) diff --git a/custom_components/hotspring/manifest.json b/custom_components/hotspring/manifest.json index d3aab3e..1f77145 100644 --- a/custom_components/hotspring/manifest.json +++ b/custom_components/hotspring/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_push", "integration_type": "hub", "requirements": [], - "version": "0.1.0" + "version": "0.1.1" } diff --git a/custom_components/hotspring/strings.json b/custom_components/hotspring/strings.json index 24329ed..8e9b656 100644 --- a/custom_components/hotspring/strings.json +++ b/custom_components/hotspring/strings.json @@ -13,6 +13,16 @@ "data_description": { "local_status_url": "If Home Assistant is on the spa's LAN, e.g. http:///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:///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": { diff --git a/custom_components/hotspring/translations/en.json b/custom_components/hotspring/translations/en.json index 24329ed..8e9b656 100644 --- a/custom_components/hotspring/translations/en.json +++ b/custom_components/hotspring/translations/en.json @@ -13,6 +13,16 @@ "data_description": { "local_status_url": "If Home Assistant is on the spa's LAN, e.g. http:///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:///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": {