OPT-11 P2: HA entities for battery modes
checks / unit (pull_request) Successful in 11m12s
infra-pin / fresh (pull_request) Successful in 2s

Each battery gets an MQTT-discovered Mode select and Use switch, only while
battery_modes_enabled is true. Commands go through handle_action(), the
/action path; refusals are logged once. Retained commands are never applied.
Turning modes off removes exactly the configs announced (kept in the store).
With modes off the announcement is byte-identical to ed739d4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-28 23:12:04 +02:00
co-authored by Claude Opus 5.5
parent ed739d4cdb
commit b310282729
8 changed files with 716 additions and 20 deletions
+448 -2
View File
@@ -42,6 +42,7 @@ part is a diff against it, reported as `N topics, M missing, C changed, A added`
re-executed from mutated source, each one named with the property it
breaks. A property nothing breaks is a property nothing is watching.
Part 9 What these checks CANNOT see, enumerated and sized.
Part 10 OPT-11 P2: each battery's select and switch, commands, removal.
⚠️ THE FIXTURE GIVES A AND B DIFFERENT NAMES, DIFFERENT RATINGS, DIFFERENT SoC,
DIFFERENT BATTERY POWER AND DIFFERENT LATCH STATES, ON PURPOSE. A fixture whose
@@ -821,8 +822,8 @@ MUTATIONS = [
("per-unit entities announced at a roster of ONE",
[("PER_UNIT_MIN_ROSTER = 2", "PER_UNIT_MIN_ROSTER = 1")]),
("the unit is dropped from the unique_id",
[('unique_id = f"{BASE}_unit_{slug}_{key}"',
'unique_id = f"{BASE}_unit_{key}"')]),
[('return f"{BASE}_unit_{slug}_{key}"',
'return f"{BASE}_unit_{key}"')]),
("the unit is dropped from the state topic",
[('return f"unit/{slug}/{key}"', 'return f"unit/{key}"')]),
("the slug de-collision is removed (rule 9(c) does not cover this)",
@@ -944,6 +945,451 @@ for line in [
]:
print(" " + line)
# ---------------------------------------------------------------------------
print("\n10. OPT-11 P2: each battery's switch and mode as HA entities")
# ---------------------------------------------------------------------------
import logging # noqa: E402
import os # noqa: E402
import tempfile # noqa: E402
from app import messages, packmode # noqa: E402
from app.store import Store, unit_key # noqa: E402
def announce_p2(units=(), omit=(), include=(), modes=(), retract=(),
module=mqtt):
"""What `_on_connect()` sends: the announcement, then any subscriptions."""
pub = module.MqttPublisher.__new__(module.MqttPublisher)
pub.omit, pub.units, pub.include = set(omit), [str(u) for u in units], \
[str(k) for k in include]
pub.modes, pub.retract = tuple(modes), list(retract)
pub.enabled, pub.client = True, FakeClient()
subs = []
pub.client.subscribe = lambda topic, *a: subs.append(topic)
pub._on_connect()
return pub.client.msgs, subs
# --- 10a. modes off: byte-identical to ed739d4 --------------------------------
# The digest below is GENERATED from release/1.0 at ed739d4 (the base of this
# PR): the same matrix run through that commit's `_announce()`. Reproduce with
# `git show ed739d4:goodwe_controller/app/mqtt.py` and this loop.
ROSTERS = [[], ["inverter-a"], ["inverter-a", "inverter-b"], ["a", "b", "c"],
["inverter-b", "Inverter B", "x", "y"], ["café"]]
ED739D4_OFF = "501a7d93782a260b"
_h, _n, _subs_off = hashlib.sha256(), 0, []
for _r in ROSTERS:
for _om in [(), ("p1_age",), ("p1_age", "grid")]:
for _inc in [(), ("pv",)]:
_m, _s = announce_p2(_r, _om, _inc)
_h.update(repr(_m).encode())
_subs_off += _s
_n += 1
print(f" modes off, {_n} configurations: digest {_h.hexdigest()[:16]} "
f"(ed739d4: {ED739D4_OFF})")
check("modes off: every configuration announces byte-for-byte what ed739d4 "
"announces, in the same order, and subscribes to nothing",
_h.hexdigest()[:16] == ED739D4_OFF and not _subs_off)
# --- 10b. modes on: the ordered payload diff ----------------------------------
MODES = packmode.MODES
ON1, SUB1 = announce_p2(["inverter-a"], modes=MODES)
m, c, a = report("roster of one, modes on", ON1)
_opt = '["Solar first", "Leftover solar"]'
MODE_N1 = [
("homeassistant/select/goodwe_ctl_unit_inverter_a_mode/config",
'{"name": "Inverter A Mode", "object_id": "goodwe_inverter_a_mode", '
'"unique_id": "goodwe_ctl_unit_inverter_a_mode", '
'"state_topic": "goodwe_ctl/unit/inverter_a/mode", '
'"command_topic": "goodwe_ctl/unit/inverter_a/mode/set", '
'"options": ' + _opt + ', "retain": false, '
'"availability_topic": "goodwe_ctl/availability", "device": ' + _DEV + ', '
'"icon": "mdi:battery-sync"}', True),
("homeassistant/switch/goodwe_ctl_unit_inverter_a_use/config",
'{"name": "Inverter A Use", "object_id": "goodwe_inverter_a_use", '
'"unique_id": "goodwe_ctl_unit_inverter_a_use", '
'"state_topic": "goodwe_ctl/unit/inverter_a/use", '
'"command_topic": "goodwe_ctl/unit/inverter_a/use/set", '
'"payload_on": "ON", "payload_off": "OFF", "retain": false, '
'"availability_topic": "goodwe_ctl/availability", "device": ' + _DEV + ', '
'"icon": "mdi:power"}', True),
]
check("modes on at a roster of one: every existing message byte-identical and "
"in place, then exactly the select and the switch, then availability",
ON1 == SITE_NOW[:-1] + MODE_N1 + SITE_NOW[-1:])
check("...and it subscribes to the two command topics, and nothing else",
SUB1 == ["goodwe_ctl/unit/+/mode/set", "goodwe_ctl/unit/+/use/set"])
ON2, _ = announce_p2(NAMES2, modes=MODES)
m, c, a = report("roster of two, modes on", ON2, TWO)
check("modes on at a roster of two: nothing missing or changed, four added, "
"and the modes-off list is an unchanged prefix",
(m, c) == ([], []) and len(a) == 4 and ON2[:len(TWO) - 1] == TWO[:-1]
and ON2[-1] == TWO[-1])
_mc = cfgs(ON2)[-4:]
check("...A's two stay on the site device with its name in front; B's two are "
"on B's own device, as TEL-07's rule has it",
[c_["name"] for c_ in _mc] == ["Inverter A Mode", "Inverter A Use",
"Mode", "Use"]
and _mc[0]["device"] == mqtt.DEVICE == _mc[1]["device"]
and _mc[2]["device"] == _mc[3]["device"]
== mqtt.unit_device("inverter-b", "inverter_b"))
check("...unique_ids are stable per battery and distinct from every other id",
[c_["unique_id"] for c_ in _mc]
== ["goodwe_ctl_unit_inverter_a_mode", "goodwe_ctl_unit_inverter_a_use",
"goodwe_ctl_unit_inverter_b_mode", "goodwe_ctl_unit_inverter_b_use"]
and len({c_["unique_id"] for c_ in cfgs(ON2)}) == len(cfgs(ON2)))
_ids = [compose(c_["device"]["name"], c_["name"]).split(".", 1)[1]
for c_ in _mc]
print(f" composed ids: {_ids}")
check("...and HA composes the ids the design names: "
"goodwe_inverter_<x>_mode and goodwe_inverter_<x>_use",
_ids == ["goodwe_inverter_a_mode", "goodwe_inverter_a_use",
"goodwe_inverter_b_mode", "goodwe_inverter_b_use"])
check("every mode has a plain label, in MODES order, and a later mode only "
"appends an option: no existing option or id changes",
all(k in mqtt.MODE_LABELS for k in MODES)
and len(set(mqtt.MODE_LABELS.values())) == len(mqtt.MODE_LABELS)
and json.loads(MODE_N1[0][1])["options"]
== [mqtt.MODE_LABELS[k] for k in MODES])
_later = dict(mqtt.MODE_LABELS, cheap_hours="Cheap hours only")
_orig = mqtt.MODE_LABELS
mqtt.MODE_LABELS = _later
try:
_p3 = mqtt.mode_payloads(NAMES2, MODES + ("cheap_hours",))
finally:
mqtt.MODE_LABELS = _orig
_p2 = mqtt.mode_payloads(NAMES2, MODES)
check("...(simulated P3: adding `cheap_hours` changes only the options list, "
"by one entry at its end)",
[t for t, _ in _p3] == [t for t, _ in _p2]
and all({k: v for k, v in x.items() if k != "options"}
== {k: v for k, v in y.items() if k != "options"}
for (_, x), (_, y) in zip(_p3, _p2))
and _p3[0][1]["options"] == _p2[0][1]["options"] + ["Cheap hours only"])
# --- 10c. modes turned off: removal ------------------------------------------
_cur2 = [t for t, _ in mqtt.mode_payloads(NAMES2, MODES)]
_ret = mqtt.mode_retractions(_cur2, [])
OFF2, _subs = announce_p2(NAMES2, retract=_ret)
check("modes turned off: the modes-off list, then an EMPTY retained config "
"for each of the four, then availability, and no subscription",
OFF2 == TWO[:-1] + [(t, "", True) for t in _cur2] + TWO[-1:]
and not _subs)
check("...the store keeps what was announced, so a roster that shrinks removes "
"only the battery that left",
mqtt.mode_retractions(_cur2, [t for t, _ in
mqtt.mode_payloads(["inverter-a"], MODES)])
== _cur2[2:])
check("...and nothing from the store is removed that is not one of our mode "
"configs: a non-list, a number, a site sensor, another add-on's select",
mqtt.mode_retractions("homeassistant/select/x/config", []) == []
and mqtt.mode_retractions(
[3, None, "homeassistant/sensor/goodwe_ctl_grid/config",
"homeassistant/select/other_mode/config",
"homeassistant/select/goodwe_ctl_unit_a_mode/config/x",
"homeassistant/select/goodwe_ctl_unit_a_mode/config"], [])
== ["homeassistant/select/goodwe_ctl_unit_a_mode/config"])
# --- 10d. state topics, from the store ----------------------------------------
_tmp = tempfile.mkdtemp()
OPTS2M = dict(OPTS2, battery_modes_enabled=True)
def ctl_for(opts, path):
pub = _Pub()
pub.sent = []
pub.publish = lambda values, _p=pub: (_p.sent.append(dict(values)),
setattr(_p, "last", dict(values)))
return Controller(dict(opts), None, Store(path), pub,
stop=asyncio.Event()), pub
_path = os.path.join(_tmp, "state.json")
ctlm, pubm = ctl_for(OPTS2M, _path)
ctlm.publish()
_fed = {f"{mqtt.BASE}/{k}" for k in pubm.last
if k.endswith("/mode") or k.endswith("/use")}
check("every announced mode entity is fed, and nothing else is: the state "
"topics published are exactly the ones announced",
_fed == {c_["state_topic"] for c_ in _mc})
check("...defaults with nothing in the store: both On, both Solar first",
[pubm.last[k] for k in ("unit/inverter_a/mode", "unit/inverter_a/use",
"unit/inverter_b/mode", "unit/inverter_b/use")]
== ["Solar first", "ON", "Solar first", "ON"])
_c_off, _p_off = ctl_for(dict(OPTS2, battery_modes_enabled=False),
os.path.join(_tmp, "off2.json"))
_c_off.publish()
_c_abs, _p_abs = ctl_for(OPTS2, os.path.join(_tmp, "off3.json"))
_c_abs.publish()
check("modes off (false or absent): the controller publishes the same keys as "
"before, with no mode or switch topic",
set(_p_off.last) == set(_p_abs.last) == set(vals2)
and not [k for k in _p_off.last if k.endswith(("/mode", "/use"))])
# --- 10e. commands: the /action path, validated -------------------------------
class _Logs(logging.Handler):
def __init__(self):
super().__init__(logging.DEBUG)
self.rows = []
def emit(self, record):
self.rows.append((record.levelno, record.getMessage()))
_logs = _Logs()
logging.getLogger("goodwe").addHandler(_logs)
logging.getLogger("goodwe").setLevel(logging.DEBUG)
_calls = []
_real_handle = ctlm.handle_action
async def _spy(what, **kw):
_calls.append((what, kw))
return await _real_handle(what, **kw)
ctlm.handle_action = _spy
def cmd(topic, payload, retained=False, ctl=None):
ctl = ctl or ctlm
asyncio.run(ctl.mqtt_command(topic, payload, retained))
def stored(ctl=None):
d = (ctl or ctlm).store.data
return {k: d.get(k) for k in (unit_key("inverter-a", "pack_use"),
unit_key("inverter-a", "pack_mode"),
unit_key("inverter-b", "pack_use"),
unit_key("inverter-b", "pack_mode"))}
T_A = "goodwe_ctl/unit/inverter_a"
T_B = "goodwe_ctl/unit/inverter_b"
pubm.sent.clear()
cmd(f"{T_B}/use/set", b"OFF")
cmd(f"{T_A}/mode/set", b"Leftover solar")
check("good commands go through handle_action() with the /action arguments",
_calls == [("pack_use", {"unit": "inverter-b", "value": False}),
("pack_mode", {"unit": "inverter-a",
"value": "leftover_solar"})])
check("...and reach the store under P1's keys, and nowhere else",
stored() == {unit_key("inverter-a", "pack_use"): None,
unit_key("inverter-a", "pack_mode"): "leftover_solar",
unit_key("inverter-b", "pack_use"): False,
unit_key("inverter-b", "pack_mode"): None})
check("...and the state topics say so at once, from the store",
pubm.sent and pubm.sent[-1] == {
"unit/inverter_a/mode": "Leftover solar", "unit/inverter_a/use": "ON",
"unit/inverter_b/mode": "Solar first", "unit/inverter_b/use": "OFF"})
check("...and the action log records each change",
any("inverter-b switched off" in e for e in ctlm.events)
and any("inverter-a mode set to leftover solar" in e
for e in ctlm.events))
_before = stored()
_n_calls = len(_calls)
BAD = [
(f"{T_A}/use/set", b"on"), (f"{T_A}/use/set", b"ON\n"),
(f"{T_A}/use/set", b"true"), (f"{T_A}/use/set", b"1"),
(f"{T_A}/use/set", b""),
(f"{T_A}/mode/set", b"solar_first"), # a key, not the option
(f"{T_A}/mode/set", b"Cheap hours only"), # not offered before P3
(f"{T_A}/mode/set", b"solar first"),
(f"{T_A}/mode/set", "Sοlar first".encode()), # Greek omicron
(f"{T_A}/mode/set", b"Solar first\x00"),
(f"{T_A}/mode/set", b'{"action": "pack_use", "value": false}'),
(f"{T_A}/mode/set", b"Solar first; rm -rf /"),
(f"{T_A}/mode/set", b"' OR 1=1 --"),
(f"{T_A}/use/set", b"\xff\xfe"), # not UTF-8
(f"{T_A}/mode/set", b"Solar first" * 10), # too long
("goodwe_ctl/unit/inverter_z/use/set", b"OFF"), # no such battery
("goodwe_ctl/unit/../use/set", b"OFF"),
("goodwe_ctl/unit/inverter_a/soc/set", b"OFF"),
("goodwe_ctl/unit/inverter_a/use/set/x", b"OFF"),
("goodwe_ctl/unit/Inverter_A/use/set", b"OFF"),
(f"{T_A}/use/set", None),
]
for _t, _p in BAD:
cmd(_t, _p)
check(f"all {len(BAD)} bad commands are refused: the store is unchanged",
stored() == _before)
_passed = [c_ for c_ in _calls[_n_calls:]]
check("...those that reach handle_action() carry a value /action also refuses "
"(None) or no known battery; nothing is coerced into a valid choice",
all(kw["value"] is None or kw["unit"] is None for _, kw in _passed))
# Log once per topic and reason.
_logs.rows.clear()
for _ in range(5):
cmd(f"{T_B}/use/set", b"maybe")
_warn = [r for r in _logs.rows if r[0] >= logging.WARNING]
check("a refused command repeated 5 times is logged once at WARNING, in plain "
"words, and at DEBUG the other times",
len(_warn) == 1 and messages.pack_refused("value") in _warn[0][1]
and len([r for r in _logs.rows if r[0] == logging.DEBUG]) == 5)
_logs.rows.clear()
_flood, _ = ctl_for(OPTS2M, os.path.join(_tmp, "flood.json"))
for _i in range(100):
cmd(f"goodwe_ctl/unit/x{_i}/use/set", b"OFF", ctl=_flood)
check("...and a flood of 100 different bad topics logs 32 WARNINGs, no more",
len([r for r in _logs.rows if r[0] >= logging.WARNING]) == 32)
# Modes off: refused on the same path, even if a message arrives.
cmd(f"{T_A}/use/set", b"OFF", ctl=_c_off)
check("with modes off a command is refused by the same check /action makes",
stored(_c_off)[unit_key("inverter-a", "pack_use")] is None)
# --- 10f. a retained command after a restart ----------------------------------
_logs.rows.clear()
_before = stored()
_n_calls = len(_calls)
cmd(f"{T_A}/use/set", b"OFF", retained=True)
cmd(f"{T_B}/use/set", b"ON", retained=True)
check("a RETAINED command (the broker replays it on subscribe, e.g. after a "
"restart) is never applied, and never reaches handle_action()",
stored() == _before and len(_calls) == _n_calls)
check("...and it is logged once, in plain words",
any(messages.pack_refused("retained") in r[1]
for r in _logs.rows if r[0] >= logging.WARNING))
ctl_r, pub_r = ctl_for(OPTS2M, _path) # a restart: same state file
ctl_r.publish()
check("after a restart the state topics come from the store: A Leftover solar "
"and on, B off",
[pub_r.last[k] for k in ("unit/inverter_a/mode", "unit/inverter_a/use",
"unit/inverter_b/use")]
== ["Leftover solar", "ON", "OFF"])
logging.getLogger("goodwe").removeHandler(_logs)
# --- 10g. the paho side ----------------------------------------------------------
class _Msg:
def __init__(self, topic, payload, retain):
self.topic, self.payload, self.retain = topic, payload, retain
_got = []
async def _handler(*args):
_got.append(args)
async def _drive():
pub = mqtt.MqttPublisher.__new__(mqtt.MqttPublisher)
pub._on_message(None, None, _Msg("t", b"x", 0)) # not bound: dropped
pub.bind(asyncio.get_running_loop(), _handler)
pub._on_message(None, None, _Msg(f"{T_A}/use/set", b"OFF", 1))
await asyncio.sleep(0.05)
asyncio.run(_drive())
check("paho's thread hands (topic, bytes, retained) to the controller's loop, "
"and drops a message that arrives before the controller exists",
_got == [(f"{T_A}/use/set", b"OFF", True)])
_kws = {k.arg: ast.unparse(k.value) for c_ in _call for k in c_.keywords}
_main_src = (HERE / "app" / "main.py").read_text()
check("(source read) main() passes modes and retractions to the publisher, "
"and binds its commands to the controller",
_kws.get("modes") == "_modes" and _kws.get("retract") == "_retract"
and "pub.bind(asyncio.get_running_loop(), controller.mqtt_command)"
in _main_src)
# --- 10h. the guards, broken one at a time --------------------------------------
def p2_properties(mod):
out = {}
try:
off, s_off = announce_p2(NAMES2, module=mod)
on1, s_on = announce_p2(["inverter-a"], modes=MODES, module=mod)
on2, _ = announce_p2(NAMES2, modes=MODES, module=mod)
out["off identical"] = off == TWO and not s_off
out["on payloads"] = on1 == ON1 and on2 == ON2
out["subscribes when on"] = s_on == SUB1
cur = [t for t, _ in mod.mode_payloads(NAMES2, MODES)]
out["retract filters store"] = mod.mode_retractions(
[3, "homeassistant/sensor/goodwe_ctl_grid/config",
"homeassistant/select/other/config"] + cur, cur) == []
out["retract keeps current"] = mod.mode_retractions(cur, cur) == []
out["retract published"] = announce_p2(
NAMES2, retract=cur[:1], module=mod)[0] == \
TWO[:-1] + [(cur[0], "", True)] + TWO[-1:]
pc = mod.parse_command
out["retained dropped"] = pc(f"{T_A}/use/set", b"OFF", True,
MODES)[3] == "retained"
out["size capped"] = pc(f"{T_A}/mode/set", b"Solar first" * 10,
False, MODES)[3] == "size"
out["utf-8 only"] = pc(f"{T_A}/use/set", b"\xff", False,
MODES)[3] == "encoding"
out["switch exact"] = (
pc(f"{T_A}/use/set", b"on", False, MODES)[2] is None
and pc(f"{T_A}/use/set", b"OFF", False, MODES)[2] is False)
out["select labels only"] = (
pc(f"{T_A}/mode/set", b"solar_first", False, MODES)[2] is None
and pc(f"{T_A}/mode/set", b"Leftover solar", False,
MODES)[2] == "leftover_solar")
out["select offered only"] = pc(
f"{T_A}/mode/set", b"Solar first", False, ("leftover_solar",))[2] \
is None
out["topic exact"] = all(
pc(t, b"OFF", False, MODES)[3] == "topic"
for t in ("goodwe_ctl/unit/../use/set", "goodwe_ctl/unit/a/b/use/set",
"goodwe_ctl/unit/a/use/set/x", "x/goodwe_ctl/unit/a/use/set"))
except Exception as err: # noqa: BLE001
out["did not raise"] = False
out["__error__"] = repr(err)[:70]
return out
P2_SHIPPED = p2_properties(mqtt)
check("the shipped module has every P2 property (so a red below is the "
"mutation)", all(v is True for v in P2_SHIPPED.values()))
P2_MUTATIONS = [
("mode entities announced with modes off",
[(" if not modes:\n return []\n", " modes = modes or ('solar_first', 'leftover_solar')\n")]),
("subscribed with modes off", [(" if self.modes:\n", " if True:\n")]),
("retained commands applied", [(" if retained:\n", " if False:\n")]),
("no payload size cap", [("or len(payload) > MAX_COMMAND_BYTES", "or False")]),
("bad UTF-8 replaced, not refused",
[('.decode("utf-8")', '.decode("utf-8", "replace")')]),
("switch payload case-folded",
[("{USE_ON: True, USE_OFF: False}.get(text)",
"{USE_ON: True, USE_OFF: False}.get(text.upper())")]),
("select accepts mode keys too",
[("if MODE_LABELS.get(k) == text", "if text in (k, MODE_LABELS.get(k))")]),
("select accepts any labelled mode, offered or not",
[("(k for k in modes if MODE_LABELS.get(k) == text)",
"(k for k in MODE_LABELS if MODE_LABELS.get(k) == text)")]),
("command topic loosened", [('/([a-z0-9_]+)/(mode|use)/set")', '/(.+)/(mode|use)/set")')]),
("command topic matched as a prefix",
[("_COMMAND_RE.fullmatch(topic)", "_COMMAND_RE.search(topic)")]),
("store list not filtered",
[("and _MODE_CONFIG_RE.fullmatch(t) and t not in keep", "and t not in keep")]),
("current configs also removed", [("_MODE_CONFIG_RE.fullmatch(t) and t not in keep", "_MODE_CONFIG_RE.fullmatch(t)")]),
("commands published retained by HA", [('cfg["retain"] = False', 'cfg["retain"] = True')]),
("retractions not published",
[(' self.client.publish(topic, "", retain=True)\n', " pass\n")]),
]
_p2_surv = []
for label, pairs in P2_MUTATIONS:
got = properties(load(pairs))
got.update(p2_properties(load(pairs)))
broke = sorted(k for k, v in {**SHIPPED, **P2_SHIPPED}.items()
if v is True and got.get(k) is not True)
print(f" {'RED ' if broke else 'GREEN'} {label}"
+ (f" (breaks: {', '.join(broke)})" if broke else ""))
if not broke:
_p2_surv.append(label)
check(f"all {len(P2_MUTATIONS)} P2 mutations of app/mqtt.py are red",
not _p2_surv)
# ---------------------------------------------------------------------------
print()
if fails: