Files
goodwe-addon/goodwe_controller/tools/ev04_peak.py
T
glenn schrooyenandClaude b12776c705
checks / unit (pull_request) Successful in 22m5s
infra-pin / fresh (pull_request) Successful in 2s
EV-10b: grade the alarm on the house alone without the 0 W clip
The period without the car was clipped at 0 W, so batteries covering the car
were charged to the house and the floor alarm fired (rig F-1). New
car_exclude_alarm keeps the sign of the rest of the period; car_exclude (the
cover-off guard input) is unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-16 22:16:29 +01:00

190 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""EV-04: the real Controller on the SAFETY-81 plant, plus a car charger.
python3 tools/ev04_peak.py # a few runs and what they raised
A 1 s cycle, a 3500 W cap, one battery switched Off (so only the peak guard
makes it give, at most `rating` W), a P1 meter that publishes 0.3 s before each
cycle, and `chargersim.SimCharger` behind the same Home Assistant: its power
is part of the load the meter sees, and the add-on reads and writes it through
the real driver. `events` is `{second: fn(plant, controller)}`, run before that
cycle: unplug, freeze the reading, step the house, change the user's current.
Used by test_ev04.py (sections 9 to 11) and, later, by the rig test."""
import asyncio
import logging
import os
import sys
import tempfile
import time
from datetime import timedelta
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import opt11_identity as rig # noqa: E402
import main_files # noqa: E402
import safety81_sim as s81 # noqa: E402
from app import packmode # noqa: E402
from app.main import Controller # noqa: E402
from app.p1 import make_sample, split_signed # noqa: E402
from app.store import unit_key # noqa: E402
from chargersim import SimCharger # noqa: E402
SET = "number.wallbox_power_connector_max_current_socket_1"
PHASES = "select.wallbox_installation_max_allowed_phases"
ALARMS = ("goodwe_peak_saturated", "goodwe_peak_soc_floor")
OVER = "goodwe_car_over"
class CarPlant(s81._Plant):
"""The SAFETY-81 plant with a charger on the same meter: the grid sees the
house, the car and what the battery does."""
def __init__(self, house, rating, soc, charger):
super().__init__(lambda at: house(at) + charger.power_w, rating, soc)
self.ch = charger
async def state(self, entity_id):
return self.ch.states().get(entity_id)
async def set_number(self, e, v):
if e == SET:
return self.ch.request_current(float(v))
return await super().set_number(e, v)
async def call(self, domain, service, data=None):
if domain == "select" and service == "select_option":
n = 3 if "3" in str((data or {}).get("option")) else 1
return self.ch.request_phases(n)
return await super().call(domain, service, data)
class CarPlantN(CarPlant):
"""EV-10b: N batteries, each its own setpoint, power and SoC (`soc` is a
dict {"a": %, "b": %}); `rating` is per battery. The grid sees them all."""
def __init__(self, house, rating, soc, charger):
super().__init__(house, rating, 0.0, charger)
self.socs = dict(soc)
self.hists = {u: [(-1e9, 0.0)] for u in self.socs}
def batt_of(self, u, at):
w = 0.0
for when, v in self.hists[u]:
if when <= at:
w = v
return max(-self.rating, min(self.rating, float(round(w))))
def batt(self, at):
return sum(self.batt_of(u, at) for u in self.socs)
async def number(self, e, invert=False):
for u in self.socs:
if e == "sensor.soc_" + u:
return self.socs[u]
if e == "sensor.batt_" + u:
return self.batt_of(u, self.t)
return await super().number(e, invert)
async def set_number(self, e, v):
if e.startswith("number.sp_"):
self.hists[e[-1]].append((self.t + s81.RESPONSE_S, float(v)))
return True
return await super().set_number(e, v)
def drive(house, *, dur=300.0, rating=2000.0, soc=60.0, cap=3500.0, margin=50,
opts=None, plug=True, setpoint=16, phases=3, mode="manual",
user_a=16, events=None, sim=None, store=None, n=1, plant_cls=None,
dev_w=5000.0):
"""Run it. Returns a namespace-like dict: plant, controller, charger, the
notification ids raised with their second, and the controller's rows."""
sim = sim or SimCharger(setpoint_a=setpoint)
if plug:
sim.plug_in()
sim.phases_allowed = phases
o = rig._options(n, dict({
"meter_source": "ha_signed", "p1_net_entity": "sensor.net",
"meter_phases": 1, "peak_cap_w": cap, "peak_margin_w": margin,
"battery_modes_enabled": True, "max_w": rating,
"ev_charger": "alfen_ha", "ev_max_a": 16, "ev_phases": "auto",
"ev_current_entity": SET}, **(opts or {})))
store = store or rig._Store()
for u in "ab"[:n]:
store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = False
store.data[packmode.USE_KEY] = False
db = os.path.join(tempfile.mkdtemp(prefix="ev4-"), "tariff.db")
out = {}
async def go():
plant = (plant_cls or CarPlant)(house, rating, soc, sim)
c = Controller(o, plant, store, rig._Pub(), stop=asyncio.Event(),
peak_db_path=db)
for i in c.inverters:
i.dev_min, i.dev_max = -dev_w, dev_w
c.auto = True
clock = [0.0]
c.car_now = lambda: clock[0]
if hasattr(c.charger, "_sleep"):
async def sleep(s):
sim.tick(s)
clock[0] += s
c.charger._sleep = sleep
c.charger._clock = lambda: clock[0]
real_dt = main_files.live.datetime
class _DT(real_dt):
@classmethod
def now(cls, tz=None):
return rig.BASE + timedelta(seconds=clock[0])
main_files.live.datetime = _DT
c.car_mode, c.car_n, c.car_a = mode, phases, float(user_a)
snaps = []
try:
t = 0.0
while t < dur:
plant.t = clock[0] = t
fn = events_in.get(int(t)) if t == int(t) else None
if fn is not None:
fn(plant, c)
sim.tick(1.0)
ts = t - s81.SAMPLE_LEAD_S
plant.meter = plant.grid(ts)
imp, exp = split_signed(plant.meter)
c.p1.submit(make_sample(
"ha_signed", imp, exp, phases=1,
ingest_ts=rig.BASE + timedelta(seconds=ts),
ingest_mono=time.monotonic()))
await c.read_inputs(now_mono=t)
await c.cycle()
await c.car_settle()
snaps.append((t, c.car_explains, c.car_over,
(c.peak_guard.engaged if c.peak_guard else None),
plant.batt(t), sim.power_w))
t += s81.TICK
finally:
main_files.live.datetime = real_dt
raised = [(at, nid) for at, nid in plant.notes]
out.update(plant=plant, c=c, sim=sim, raised=raised, snaps=snaps,
store=store)
events_in = events or {}
asyncio.run(go())
return out
def ids(out, *wanted):
return [(t, n) for t, n in out["raised"] if n in wanted]
if __name__ == "__main__":
logging.disable(logging.CRITICAL)
for name, kw in (
("car 11 kW, house 1.1 kW, Manual",
dict(house=s81.constant(1100.0))),
("same, Off", dict(house=s81.constant(1100.0), mode="off"))):
r = drive(**kw)
print(f"{name:34s} alarms {ids(r, *ALARMS)} "
f"car notice {ids(r, OVER)}")