#!/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) 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): """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(1, 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() store.data[unit_key("inverter-a", 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 = 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 = -5000.0, 5000.0 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)}")