Packaged as a Home Assistant add-on, with a field guide

Turns the reference RS485 controller into something a technician can install
at a client site: a typed config form instead of YAML, an ingress UI that
names misconfiguration in words, and persistent state that cannot be broken by
a timezone.

Why an add-on rather than YAML packages or blueprints:

- Blueprints cannot create helpers, and the maintenance cycle is a state
  machine whose phase and completion date must survive restarts.
- YAML packages need filesystem access, a configuration.yaml edit and a
  restart - none of which belong in a client install.
- Add-ons authenticate with SUPERVISOR_TOKEN, so there is no long-lived token
  to generate, store or leak on someone else's machine.
- Requires HA OS/Supervised. Container and Core installs cannot run add-ons at
  all, which is a market decision, not an oversight.

The control law and the maintenance machine are pure functions with no Home
Assistant imports, and both ship with runnable checks (22 and 22 assertions).
Every assertion corresponds to a rule whose absence caused an observed failure
on hardware - the saturation duration term, the clamp-before-slew ordering, the
deadband, the sign convention.

One behaviour deliberately differs from the implementation it replaces: when
its inputs go missing this commands 0 W rather than replaying the last
setpoint. The reference version kept replaying, which the hardware watchdog
cannot catch - from the ESP32's side, Home Assistant is still talking to it.

Includes the ESPHome firmware (now parameterised: node name, inverter rating,
watchdog timeout) and the optional RS485 e-stop. FIELD-GUIDE.md carries the
commissioning gates, all judged on the wire rather than on how Home Assistant
looks, plus the written statement a site without an e-stop needs signed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016NckgXecasQb2eSsPYNSW6
This commit is contained in:
2026-08-23 01:15:25 +02:00
co-authored by Claude Opus 5
commit 0a1e61dbc9
24 changed files with 2737 additions and 0 deletions
+83
View File
@@ -0,0 +1,83 @@
"""Persistent state, in /data (the add-on's only durable volume).
The maintenance cycle is month-scale state: it MUST survive add-on restarts,
HA restarts and power cuts, or the battery quietly stops being maintained and
nothing says so.
Times are stored as ISO-8601 with an explicit UTC offset and parsed back to
aware datetimes. That is not fussiness: the YAML implementation this replaces
was disabled for hours by exactly one naive-vs-aware subtraction, and it failed
silently - the automation never even recorded itself as triggered.
"""
import json
import logging
import os
import tempfile
from datetime import datetime, timezone
_LOG = logging.getLogger("goodwe.store")
DEFAULTS = {
"phase": "idle",
"phase_started": None,
"last_completed": None,
"last_start_attempt": None,
"auto": False,
}
class Store:
def __init__(self, path: str = "/data/state.json"):
self.path = path
self.data = dict(DEFAULTS)
self.load()
def load(self) -> None:
try:
with open(self.path, "r", encoding="utf-8") as fh:
loaded = json.load(fh)
if isinstance(loaded, dict):
self.data = {**DEFAULTS, **loaded}
_LOG.info("state restored: phase=%s last_completed=%s",
self.data.get("phase"), self.data.get("last_completed"))
except FileNotFoundError:
_LOG.info("no saved state, starting fresh")
except (json.JSONDecodeError, OSError) as err:
# A corrupt state file must not stop the controller: losing the
# maintenance history is recoverable, refusing to run is not.
_LOG.warning("state unreadable (%s) - starting fresh", err)
def save(self) -> None:
# Atomic replace: a power cut mid-write must not leave a truncated file
# that reads as "no maintenance ever ran".
try:
os.makedirs(os.path.dirname(self.path), exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(self.path))
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(self.data, fh, indent=1)
os.replace(tmp, self.path)
except OSError as err:
_LOG.error("could not persist state: %s", err)
# -- typed helpers ------------------------------------------------------
def get_time(self, key: str):
raw = self.data.get(key)
if not raw:
return None
try:
parsed = datetime.fromisoformat(raw)
except (TypeError, ValueError):
_LOG.warning("unparseable timestamp for %s: %r", key, raw)
return None
# Anything that ever escaped without an offset is treated as UTC rather
# than raising later in an arithmetic expression.
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
def set_time(self, key: str, when: datetime | None) -> None:
self.data[key] = when.astimezone(timezone.utc).isoformat() if when else None
self.save()
def set(self, key: str, value) -> None:
self.data[key] = value
self.save()