EV-20: Car Solar mode, spare sun to the car (charging only)
checks / unit (pull_request) Successful in 57m6s
infra-pin / fresh (pull_request) Successful in 3s

Solar as a second writer next to Manual (carmode.SolarPlan, SolarWriter on
ManualWriter's one write site, safe phase sequence and other-writer watch):
signed spare, Batteries first on the batteries' ratings, the margin, whole
amps rounded down, the 30 s / 1 A rule, start and pause dwells, auto phases,
a one-phase car. Every way out ends at 0 A, retried by EV-04's rule; at
shutdown before the inverters, three tries inside 15 s (D3); start-up and a
returning charger or HA write 0 A first (D2); never over another writer's
hold. The peak guard treats a Solar car as a Manual car (D1 wording). Solar
kWh sensor and card line; select.goodwe_car_sun_first; ev_margin_w,
ev_start_min, ev_pause_min with config, validator, translations, DOCS,
DECISIONS and CHANGELOG.

Checks: test_ev20.py, test_ev20_exits.py, test_ev20_writers.py,
test_ev20_guard.py, test_ev20_long.py, test_ev20_long_car.py,
test_ev20_fuzz.py (harness tools/ev20_sun.py, ev20_kit.py, ev20_day.py);
test_ev03/test_ev04 no longer use Solar as the refused example.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
This commit is contained in:
Claude
2026-11-22 20:31:26 +01:00
parent 885528ab48
commit 226e5a1e8b
35 changed files with 4647 additions and 123 deletions
+180
View File
@@ -0,0 +1,180 @@
"""EV-20, T53: the acceptance sim day, shared by test_ev20_long.py (Batteries
first) and test_ev20_long_car.py (Car first).
The real Controller, N=2 (A 40 % and may charge, B full), 08:00-18:00 of sun
(9 kW at noon) with 12 clouds of 1 to 8 minutes, a house of 0.4 to 2.5 kW with
three +3 kW steps of a little under 5 minutes. The cycle order of `step` over
the whole day, of `step_race` over the cloudiest three hours, and a car-Off
twin over the quarters around the house steps for the alarms.
What is checked, per priority and cycle order:
- starts: at most one per stretch in which the car's target stayed under
6 A worth longer than `ev_pause_min` (the morning counts as one), so no cloud
or house step shorter than that starts or pauses the car;
- no start and no pause inside a cloud of 300 s or less;
- selects at least 600 s apart;
- the car's grid energy outside its holds: SETTLED (not within 20 s of a step
of the sun, the house or the car's own current) at most 10 Wh; the zero-grid
loop's slew after such a step (500 W per cycle) is reported apart;
- house-caused alarms at the same seconds as the car-Off twin, +2 s.
"""
import math
import random
import ev20_sun as S
DAY = 36000 # 08:00 to 18:00, 1 s cycles
PAUSE_S = 300.0
MARGIN = 100.0
_rnd = random.Random(53)
CLOUDS = []
_t = 1800
for _k in range(12):
_t += _rnd.randint(1200, 2400)
CLOUDS.append((_t, _t + _rnd.randint(60, 480)))
STEPS = [(9000, 9290), (19000, 19290), (27000, 27290)]
SOCS = {"a": 40.0, "b": 100.0}
RACE = (7200, 7200 + 10800) # the cloudiest three hours
def sun(t):
base = 9000.0 * max(0.0, math.sin(math.pi * t / DAY))
for a, b in CLOUDS:
if a <= t < b:
return 0.15 * base
return base
def house(t):
w = 400.0 + 2100.0 * (0.5 + 0.5 * math.sin(t / 1700.0))
for a, b in STEPS:
if a <= t < b:
w += 3000.0
return w
def cur_writes(r):
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
if x[0] == "current"]
def low_stretches(r, first, longer=PAUSE_S):
"""Stretches in which the car's target was under 6 A worth on 1 phase for
longer than `longer`: (start, end); the last may run to the day's end."""
out, since = [], None
for x in r["trace"]:
sp = x["spare"]
room = x.get("room") or 0.0
tgt = None if sp is None else sp - (room if first == "batteries"
else 0.0) - MARGIN
low = tgt is None or tgt < 6.0 * 230.0
if low and since is None:
since = x["t"]
if not low and since is not None:
if x["t"] - since > longer:
out.append((since, x["t"]))
since = None
if since is not None and r["trace"] \
and r["trace"][-1]["t"] - since > longer:
out.append((since, r["trace"][-1]["t"]))
return out
def grid_split(r):
"""The car's grid energy outside its holds (W s): settled, and within 20 s
of a step of the sun, the house or the car's own current."""
tr = r["trace"]
marks = []
for i in range(1, len(tr)):
a, b = tr[i - 1], tr[i]
if abs(b["sun"] - a["sun"]) > 200.0 or abs(b["house"] - a["house"]) \
> 200.0 or b["sp"] != a["sp"] or b["ph"] != a["ph"]:
marks.append(b["t"])
settled = slew = 0.0
j = 0
for x in tr:
imp = max(0.0, min(x["car"], x["grid"])) \
if x["why"] != "hold" and x["sp"] > 0 else 0.0
if imp <= 0.0:
continue
while j < len(marks) and marks[j] < x["t"] - 20.0:
j += 1
near = j < len(marks) and marks[j] <= x["t"]
if near:
slew += imp
else:
settled += imp
return settled, slew
def run_day(first, check):
"""Run the day for one priority and grade it through `check`."""
long_c = [(a, b) for a, b in CLOUDS if b - a > PAUSE_S]
short_c = [(a, b) for a, b in CLOUDS if b - a <= PAUSE_S]
print(f" clouds (start, length): {[(a, b - a) for a, b in CLOUDS]}")
runs = {"step": S.drive(house, sun, dur=DAY, first=first, socs=dict(SOCS),
race=False),
"race": S.drive(house, sun, dur=RACE[1] - RACE[0], t0=RACE[0],
first=first, socs=dict(SOCS), race=True)}
for tag, r in runs.items():
w = cur_writes(r)
# A pause: a 0 A that is not a phase change's (no select within
# 30 s); a start: the first current after a pause or at the start.
log = r["c"].car_solar.log
sel_t = [t for k, a, t, ok in log if k == "phases"]
starts, pauses, paused = [], [], True
for kind, a, t, ok in log:
if kind != "current":
continue
if a == 0.0:
if not [1 for t2 in sel_t if t <= t2 <= t + 30.0]:
pauses.append(t)
paused = True
elif paused:
starts.append(t)
paused = False
lows = low_stretches(r, first)
check(f"T53 [{first} first, {tag}]: {len(starts)} starts, at most one "
f"per stretch under 6 A worth longer than the pause "
f"({len(lows)}: {lows[:6]})", len(starts) <= len(lows) + 1)
# A pause or start inside a short cloud is the cloud's only when the
# low stretch it ends began with that cloud.
every = low_stretches(r, first, longer=-1.0)
bad = []
for t in pauses + starts:
for a, b in short_c:
if a <= t <= b + 1:
began = [s0 for s0, e0 in every if s0 <= t <= e0 + 1]
if not began or began[-1] >= a - 1:
bad.append((t, a, b))
check(f"T53 [{first} first, {tag}]: no start and no pause from a "
f"cloud of 300 s or less ({bad[:2]}; {len(long_c)} clouds are "
f"longer)", not bad)
sel = [x[0] for x in r["sim"].log if x[1] == "phases"]
check(f"T53 [{first} first, {tag}]: selects at least 600 s apart "
f"({sel})", all(b - a >= 600.0 for a, b in zip(sel, sel[1:])))
settled, slew = grid_split(r)
print(f" [{first} first, {tag}] writes {len(w)}; car grid energy "
f"outside holds: settled {settled / 3600.0:.1f} Wh, loop slew "
f"after a step {slew / 3600.0:.1f} Wh; sun "
f"{r['c'].car_sun_kwh()} of {r['c'].car.today_kwh} kWh")
check(f"T53 [{first} first, {tag}]: the car's settled grid energy "
f"outside its holds is at most 10 Wh ({settled / 3600.0:.1f} Wh)",
settled <= 10.0 * 3600.0)
r = runs["step"]
for a, _b in STEPS:
t0 = float(a - a % 900 - 900)
off = S.drive(house, sun, dur=2700, t0=t0, first=first, mode="off",
plug=False, socs=dict(SOCS))
win = (t0 + 900.0, t0 + 2700.0) # the first quarter warms up
al = [t for t, n in r["raised"] if n in S.ALARMS
and win[0] <= t < win[1]]
ao = [t for t, n in off["raised"] if n in S.ALARMS
and win[0] <= t < win[1]]
check(f"T53 [{first} first]: house-caused alarms around the +3 kW "
f"step at {a} s at the same seconds as the car-Off twin, +2 s "
f"({al[:3]} vs {ao[:3]})",
len(al) == len(ao) and all(abs(x - y) <= 2
for x, y in zip(al, ao)))
return runs
+251
View File
@@ -0,0 +1,251 @@
"""EV-20: shared pieces of the Solar checks (test_ev20*.py): the Std run,
the write logs, a charger model with refusals in time windows, the Never
checks every run can carry, and the shutdown and fault shapes.
Each check file imports `check`, `fails` and `LOG` from here and is its own
process, so they are its own."""
import asyncio
import logging
import os
import sys
_KIT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _KIT)
sys.path.insert(0, os.path.dirname(_KIT))
from app import carmode, main as app_main # noqa: E402
import ev20_sun as S # noqa: E402
from chargersim import SimCharger # noqa: E402
fails = []
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
class _Log(logging.Handler):
def __init__(self):
super().__init__(logging.DEBUG)
self.rec = []
def emit(self, r):
self.rec.append((r.levelname, r.getMessage(), bool(r.exc_info)))
def mark(self):
return len(self.rec)
def since(self, n, level=None):
return [m for lv, m, _x in self.rec[n:] if level in (None, lv)]
def tracebacks(self, n=0):
return [m for lv, m, x in self.rec[n:] if x]
LOG = _Log()
_g = logging.getLogger("goodwe")
_g.addHandler(LOG)
_g.setLevel(logging.DEBUG)
_g.propagate = False
FULL = {"a": 100.0, "b": 100.0}
SET = S.SET
def const(w):
return S.const(w)
def step_fn(*pairs, base=0.0):
"""A function of t: `base`, then each (from_t, value) in order. The meter
is sampled 0.3 s before each cycle, so a change "at t0" is the cycle of
t0's."""
def f(t):
v = base
for t0, x in pairs:
if t >= t0 - 0.5:
v = x
return float(v)
return f
def at_s(t):
"""The cycle second a meter sample at `t` belongs to."""
return int(round(t))
def std(dur, *, sun=None, house=None, events=None, race=False, sim=None,
first="car", socs=None, **kw):
return S.drive(house or const(500.0), sun or const(2900.0), dur=dur,
first=first, socs=socs or dict(FULL), events=events,
race=race, sim=sim, **kw)
def cur_writes(r):
"""(cycle second, amps, ok) of every current write Solar made."""
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
if x[0] == "current"]
def attempts(r):
"""(second, amps) of every current write that reached Home Assistant,
refused ones included."""
return [(t, v) for t, e, v in r["plant"].sets if e == SET]
def selects(r):
return [x for x in r["sim"].log if x[1] == "phases"]
def act(what, value, out=None, key=None):
async def f(p, c):
res = await c.handle_action(what, value=value)
if out is not None:
out[key or what] = res
return f
def mqtt_cmd(topic, payload, retained=False):
async def f(p, c):
await c.mqtt_command(topic, payload, retained)
return f
def both(*fns):
async def f(p, c):
for fn in fns:
x = fn(p, c)
if asyncio.iscoroutine(x):
await x
return f
class TSim(SimCharger):
"""The model with refusals in time windows of its own clock: (t0, t1,
"error" | "ignore")."""
def __init__(self, *a, windows=(), **kw):
super().__init__(*a, **kw)
self.windows = list(windows)
def _mode(self):
for t0, t1, kind in self.windows:
if t0 <= self.t <= t1:
return kind
return None
def request_current(self, a):
keep, self.refuse = self.refuse, self._mode() or self.refuse
try:
return super().request_current(a)
finally:
self.refuse = keep
def nevers(r, tag, *, clamp=16.0, gap=600.0):
"""N1, N2, N5 and N13 over one run: no write above the clamp and no
clamp fault; a select only at 0 A with the car under 100 W, one per 600 s;
no two non-zero decisions under 30 s apart or under 1 A apart; no
Traceback."""
bad = []
sim, c = r["sim"], r["c"]
if c.charger.clamp_faults:
bad.append(("N1 clamp fault", c.charger.clamp_faults))
for t, what, v, power, sp in sim.log:
if what == "current" and v > clamp + 1e-9:
bad.append(("N1 over the clamp", t, v))
last = None
for t, what, v, power, sp in sim.log:
if what != "phases":
continue
if sp > 0.0 or power >= carmode.QUIET_W:
bad.append(("N2 select under load", t, sp, power))
if last is not None and t - last < gap:
bad.append(("N2 two selects", last, t))
last = t
prev = None
for t, a, ok in cur_writes(r):
if a <= 0.0:
continue
if prev is not None and a != prev[1]:
if t - prev[0] < carmode.SOLAR_WRITE_S - 1e-9:
bad.append(("N5 under 30 s", prev, (t, a)))
if abs(a - prev[1]) < carmode.SOLAR_STEP_A:
bad.append(("N5 under 1 A", prev, (t, a)))
if prev is None or a != prev[1]:
prev = (t, a)
if LOG.tracebacks(r.get("_log", 0)):
bad.append(("N13 Traceback", LOG.tracebacks(r.get("_log", 0))[:1]))
check(f"{tag}: N1, N2, N5, N13 hold ({bad[:2]})", not bad)
return bad
def run(tag, fn, *a, **kw):
n = LOG.mark()
r = fn(*a, **kw)
r["_log"] = n
return r
def sets_order(r):
return [(t, e, v) for t, e, v in r["plant"].sets]
async def _shutdown(p, c):
await c.shutdown()
def _until(r, t0):
"""Seconds from `t0` to the first inverter 0 W at shutdown."""
z = [t for t, e, v in r["plant"].sets
if e.startswith("number.sp_") and t >= t0 and v == 0.0]
return (z[0] - t0) if z else None
def _err(p, c):
p.ch.error = "12: Socket error"
p.ch.fault("E")
async def _dies(p, c):
async def boom():
raise RuntimeError("control died")
stop, died = asyncio.Event(), []
task = asyncio.ensure_future(boom())
await asyncio.gather(task, return_exceptions=True)
app_main.control_task_done(task, controller=c, stop=stop, died=died)
p.died = (stop.is_set(), len(died))
await c.shutdown()
def _freeze_after_write(p, c):
p.ch.freeze()
class HangPlant(S.SunPlant):
"""Home Assistant that never answers a charger write."""
hang = False
async def set_number(self, e, v):
if e == SET and self.hang:
await asyncio.sleep(3600)
return await super().set_number(e, v)
def report():
print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}")
for f in fails:
print(" FAIL:", f)
sys.exit(1 if fails else 0)
+313
View File
@@ -0,0 +1,313 @@
#!/usr/bin/env python3
"""EV-20: the real Controller on a sunny plant with N batteries and a car.
python3 tools/ev20_sun.py # mock-up scenario 2, both priorities
A 1 s cycle, a P1 meter that publishes 0.3 s before each cycle, N batteries
each with ITS OWN rating and level (switched On, so the zero-grid loop charges
them from the export), and `chargersim.SimCharger` behind the same Home
Assistant. The meter sees `house + car - sun - batteries` (battery discharge
positive), so the spare sun the add-on computes is `sun - house` whatever it
does. A battery at 100 % takes no charge. `events` is `{second: fn(plant, c)}`,
run before that cycle. `race=True` uses the production order (read, the writer
task settles, then the cycle), as test_ev04.py's `World.step_race`.
Used by test_ev20.py and test_ev20_long.py. Adapted from EV-05's harness
(branch EV-05, never merged), without the peak cut."""
import asyncio
import logging
import os
import sys
import tempfile
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
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
from app import p1 as _p1 # 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")
RESPONSE_S = 0.5 # a battery reaches its new command this much later
SAMPLE_LEAD_S = 0.3
class SunPlant:
"""The house, the sun, N batteries and the charger on one meter."""
def __init__(self, house, sun, ratings, socs, charger):
self.house, self.sun = house, sun
self.ratings, self.socs = dict(ratings), dict(socs)
self.ch = charger
self.t = 0.0
self.hists = {u: [(-1e9, 0.0)] for u in self.ratings}
self.notes = [] # (t, notification id) raised
self.dismissed = []
self.sets = [] # (t, entity, value): every number write
# Every charger write the model took, as `SimCharger.log` has it but
# on THIS clock (the model's own runs ahead while a write waits).
self.wlog = []
self.meter = 0.0
self.meter_on = True # False: the meter stops publishing
self.batt_nan = set() # units whose battery figure reads None
self.utc_off = 0.0 # the wall clock jumps, the model clock not
self.ha_down = False # Home Assistant answers nothing (SAFETY-112)
self.response_s = RESPONSE_S # a slow battery takes longer
def batt_of(self, u, at):
w = 0.0
for when, v in self.hists[u]:
if when <= at:
w = v
r = self.ratings[u]
w = max(-r, min(r, float(round(w))))
if self.socs[u] >= 100.0 and w < 0.0:
w = 0.0 # a full battery takes no charge
return w
def batt(self, at):
return sum(self.batt_of(u, at) for u in self.ratings)
def grid(self, at):
return self.house(at) + self.ch.power_w - self.sun(at) - self.batt(at)
# -- Home Assistant -----------------------------------------------------
async def limits(self, e):
return (-5000.0, 5000.0, 1.0)
async def state(self, entity_id):
if self.ha_down:
return None
return self.ch.states().get(entity_id)
async def states(self):
if self.ha_down:
return []
return list(self.ch.states().values())
async def call(self, domain, service, data=None):
if self.ha_down:
return False
if service == "create":
self.notes.append((self.t, (data or {}).get("notification_id")))
if service == "dismiss":
self.dismissed.append((self.t, (data or {}).get("notification_id")))
if domain == "select" and service == "select_option":
n = 3 if "3" in str((data or {}).get("option")) else 1
return self._logged("phases", n, self.ch.request_phases)
return True
def _logged(self, what, v, fn):
n0, row = len(self.ch.log), (self.t, what, v, self.ch.power_w,
self.ch.setpoint_a)
ok = fn(v)
if len(self.ch.log) > n0:
self.wlog.append(row)
return ok
async def number(self, e, invert=False):
if self.ha_down:
return None
for u in self.ratings:
if e == "sensor.soc_" + u:
return self.socs[u]
if e == "sensor.batt_" + u:
return None if u in self.batt_nan else self.batt_of(u, self.t)
if e in ("sensor.grid", "sensor.net"):
return self.meter
return None
async def set_number(self, e, v):
if self.ha_down:
return False
self.sets.append((self.t, e, float(v)))
if e == SET:
return self._logged("current", float(v), self.ch.request_current)
if e.startswith("number.sp_"):
self.hists[e[-1]].append((self.t + self.response_s, float(v)))
return True
def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0,
margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar",
first="batteries", events=None, sim=None, store=None, race=False,
on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None,
rows=False, plant_cls=None):
"""Run it. Returns a dict: plant, controller, charger, notifications with
their second, and a per-second trace. `caps` ({unit: kWh}) lets each
battery's level move with what it charges or gives; without it the
levels stand still. `finale(plant, c)` (a coroutine) runs after the last
cycle, on the model clock (a shutdown, for instance); `rows=True` keeps
the ids of the amber and red rows of every cycle in the trace."""
ratings = ratings or {"a": 5000.0, "b": 4600.0}
socs = socs or {u: 50.0 for u in ratings}
sim = sim or SimCharger(setpoint_a=setpoint)
if plug:
sim.plug_in(car_phases=car_phases)
sim.phases_allowed = phases
units = sorted(ratings)
o = rig._options(len(units), 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,
"ev_charger": "alfen_ha", "ev_max_a": 16, "ev_phases": "auto",
"ev_current_entity": SET}, **(opts or {})))
if len(units) == 1:
o["max_w"] = ratings[units[0]]
else:
o["inverters"] = [dict(x, max_w=ratings[x["name"][-1]])
for x in o["inverters"]]
store = store or rig._Store()
store.data["car_mode"] = mode
store.data["car_sun_first"] = first
for u in units:
store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = True
db = os.path.join(tempfile.mkdtemp(prefix="ev20-"), "tariff.db")
out = {}
events_in = events or {}
async def go():
plant = (plant_cls or SunPlant)(house, sun, ratings, socs, sim)
c = Controller(o, plant, store, rig._Pub(), stop=asyncio.Event(),
peak_db_path=db)
for i in c.inverters:
r = ratings[i.name[-1]] if len(units) > 1 else ratings[units[0]]
i.dev_min, i.dev_max = -r, r
c.auto = True
clock = [t0]
plant.clock = clock # a finale may move the model clock
c.car_now = lambda: clock[0]
real_time = _p1.time
class _Time:
"""The meter's age on the model clock, so a silent meter goes
stale in model seconds."""
def __getattr__(self, k):
return getattr(real_time, k)
@staticmethod
def monotonic():
return clock[0]
_p1.time = _Time()
if hasattr(c.charger, "_sleep"):
async def sleep(s):
sim.tick(s)
clock[0] += s
plant.t = clock[0]
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] + plant.utc_off)
main_files.live.datetime = _DT
trace = []
try:
t = t0
while t < t0 + dur:
plant.t = clock[0] = t
fn = events_in.get(int(t)) if t == int(t) else None
if fn is not None:
r = fn(plant, c)
if asyncio.iscoroutine(r):
await r
sim.tick(1.0)
ts = t - SAMPLE_LEAD_S
if plant.meter_on and not plant.ha_down:
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=ts))
await c.read_inputs(now_mono=t)
if race:
await c.car_settle()
await c.cycle()
else:
await c.cycle()
await c.car_settle()
w = c.car_solar
g = c.peak_guard
trace.append(dict(
t=t, a=w.plan.a, why=w.plan.why, n=w.plan.n,
sp=sim.setpoint_a, rb=sim.readback_a,
ph=sim.phases_allowed, car=sim.power_w, st=sim.state,
grid=plant.grid(t), batt=plant.batt(t),
house=plant.house(t), sun=plant.sun(t),
explains=c.car_explains, over=c.car_over,
lim=bool(g is not None and (g.floor_limited
or g.saturated)),
floor=(None if g is None else g.floor_w),
excess=(None if g is None else g.excess_w),
want=(None if g is None else g.wanted_w),
socs=dict(plant.socs),
proj=(None if g is None else g.projected_w),
target=(None if g is None else g.target_w),
would=w.would, single=w.single,
spare=c.car_spare_w(t), ok=w.plan.ok_since,
hold=w.hold, gave_up=w.gave_up, sent=w.sent_a,
room=(None if w.sun is None else w.sun.room_w),
taken=w.taken,
red=[x["id"] for x in c.checks()
if x["ok"] is False and not x["warn"]]
if on_cycle == "rows" or rows else [],
amber=[x["id"] for x in c.checks()
if x["ok"] is False and x["warn"]]
if rows else [],
own=c._car_own_pause(c.car_now()),
alarm_w=c.car_alarm_w(), peak_q=dict(c.car_peak_q),
other=w.other, mismatch=w.mismatch_since,
fails=w.fails, fault=w.fault))
if callable(on_cycle):
on_cycle(plant, c, t)
for u, kwh in (caps or {}).items():
# 1 s of W, as a percent of kWh: W / 3600 / (kWh x 1000) x 100
lv = plant.socs[u] - plant.batt_of(u, t) / 36000.0 / kwh
plant.socs[u] = max(0.0, min(100.0, lv))
t += 1.0
await c.car_settle()
if finale is not None:
plant.t = clock[0]
await finale(plant, c)
finally:
main_files.live.datetime = real_dt
_p1.time = real_time
out.update(plant=plant, c=c, sim=sim, trace=trace, store=store,
raised=list(plant.notes), clock=clock)
asyncio.run(go())
return out
def ids(out, *wanted):
return [(t, n) for t, n in out["raised"] if n in wanted]
def writes(out, what="current"):
"""(t, value) of every charger write of that kind, in model seconds."""
return [(x[0], x[2]) for x in out["sim"].writes(what)]
def const(w):
return lambda t: float(w)
if __name__ == "__main__":
logging.disable(logging.CRITICAL)
for first in ("batteries", "car"):
r = drive(const(900.0), const(7900.0), dur=600, first=first,
socs={"a": 71.0, "b": 100.0})
print(f"scenario 2, {first} first: writes {writes(r)} phases "
f"{writes(r, 'phases')} batteries {r['plant'].batt(599):.0f} W "
f"grid {r['plant'].grid(599):.0f} W")