diff --git a/goodwe_controller/app/arbitrage.py b/goodwe_controller/app/arbitrage.py index eb4e0c6..0449019 100644 --- a/goodwe_controller/app/arbitrage.py +++ b/goodwe_controller/app/arbitrage.py @@ -267,6 +267,55 @@ def threshold_eur_kwh(opts: dict) -> float: return v +# TARIFF-30. A unit's own losses are the whole reason the buy leg is refused. +IDLE_LOSSES = ("the price gap does not cover the energy these batteries lose " + "on the way in and out") + + +def leg_clears(v, eta) -> bool: + """TARIFF-30. Does ONE unit's buy leg clear on the verdict `v`? + + With no efficiency set (`eta` None) the verdict itself is the answer, as + today. With one set, the cheap hour is priced at `price / eta` and the gap + to the dear hour must still reach what this cycle needs + (`v.required_spread_eur_kwh`). That figure is the cycle cost widened for + doubt and is NOT widened again for the loss: `eta` is a configured number, + not price uncertainty. The sell leg has no `eta`. Rounded to six places like + the verdict's own spread, so the boundary agrees with it.""" + if eta is None: + return True + net = round(float(v.dearest.eur_per_kwh) + - float(v.cheapest.eur_per_kwh) / float(eta), 6) + return net >= float(v.required_spread_eur_kwh) + + +def clearing(plan, now: datetime, *, min_spread_eur_kwh, uncertainty, etas): + """TARIFF-30. `{name: bool}`: which units' own buy legs clear, or None. + + `etas` is `{name: round_trip_eff or None}`. None is returned when nobody + has an efficiency (nothing to decide: today's behaviour) and when the + verdict does not allow a trade at all (the caller's own gate speaks). The + peak guard is asked as clear: the interlock is the caller's, and an + efficiency can only narrow a verdict, never widen it.""" + if plan is None or not any(e is not None for e in etas.values()): + return None + verdict = plan.arbitrage(peak_guard_active=False, + min_spread_eur_kwh=min_spread_eur_kwh, + uncertainty=uncertainty, now=now) + return verdict.match( + refused=lambda _v: None, + allowed=lambda v: {n: leg_clears(v, e) for n, e in etas.items()}) + + +def idle_for_losses(decision: ArbitrageDecision) -> ArbitrageDecision: + """TARIFF-30. `decision` (an IDLE_NO_SIZE refusal) as the efficiency + refusal it really is, with the same numbers: no unit's own leg cleared, so + the buy was sized at 0 W. Still no claim (never a 0 W one).""" + return _idle(IDLE_LOSSES, spread=decision.spread_eur_kwh, + required=decision.required_eur_kwh, + price=decision.price_now_eur_kwh) + + def weather_uncertainty(modes_on: bool, solar_fc, held: bool = False) -> frozenset: """The "no weather" doubt (x1.5) a trade must clear. TARIFF-24. diff --git a/goodwe_controller/app/cheaproll.py b/goodwe_controller/app/cheaproll.py index d3d0346..2fbb750 100644 --- a/goodwe_controller/app/cheaproll.py +++ b/goodwe_controller/app/cheaproll.py @@ -23,7 +23,6 @@ from dataclasses import dataclass from datetime import datetime, timedelta, timezone from . import arbitrage, dayplan, modetrade, packshare, priceruns -from .dayplan import EFF from .price import required_spread, uncertainty_of SLOT_S = 900 # a price slot @@ -32,7 +31,7 @@ LIMIT = 24 # rolls at most (a day of one-hour runs) def roll_end(run, points, packs_at, *, required, floor_pct, ceiling_pct, - targets=None, limit=LIMIT): + targets=None, limit=LIMIT, legs=None): """Where the cheap run `run` ends once control has rolled it on. `packs_at(end)` gives the `modetrade.Pack`s as they stand when a run @@ -43,7 +42,7 @@ def roll_end(run, points, packs_at, *, required, floor_pct, ceiling_pct, end_t = run.end for _ in range(limit): e = modetrade.energy(packs_at(end_t), floor_pct, ceiling_pct, - targets=targets) + targets=targets, legs=legs) if e[0] <= 1e-6: break new = priceruns.plan(points, end_t, required_eur_kwh=required, @@ -89,7 +88,9 @@ class _Charge: the room the peak limit leaves: `min(sum of ratings, aim - house)`, shared by room left to full as control does (`_shares()`), each stopping at `modetrade.charge_to()`.""" - def __init__(self, packs, t0, ceiling_pct, targets, aim_w, house): + def __init__(self, packs, t0, ceiling_pct, targets, aim_w, house, + legs=None): + self.legs = legs self.packs = {p.name: p for p in packs} self.t = t0 self.ceil = ceiling_pct @@ -147,7 +148,7 @@ class _Charge: def _charge(self, s, e, hour): ch = modetrade.chargers(list(self.packs.values()), self.ceil, - targets=self.targets) + targets=self.targets, legs=self.legs) total = sum(abs(p.rating_w) for p in ch) if not ch or total <= 0.0: return @@ -159,7 +160,7 @@ class _Charge: if not p.capacity_kwh: continue to = modetrade.charge_to(p, self.ceil, self.targets) - kwh = share[p.name] * hrs / 1000.0 * EFF + kwh = share[p.name] * hrs / 1000.0 * dayplan.eff_of(p.eta) room = (to - p.soc) / 100.0 * float(p.capacity_kwh) if kwh <= 0.0: continue @@ -185,9 +186,10 @@ def for_today(c, rp, now): return None floor, ceil = arbitrage.soc_bounds(c.o) hp = getattr(c, "house_profile", None) + legs = getattr(c, "charge_legs", lambda *_a: None)(plan, now) sim = _Charge(c._mode_packs(), max(now, rp.cheap.start), ceil, c.plan_targets(), c.peak_aim_w(), - None if hp is None else hp.estimator()) + None if hp is None else hp.estimator(), legs) required = required_spread( arbitrage.threshold_eur_kwh(c.o), uncertainty_of(plan.read.product) @@ -195,7 +197,7 @@ def for_today(c, rp, now): bool(c.weather_held(now)))) end = roll_end(rp.cheap, plan.read.points, sim.at, required=required, floor_pct=floor, ceiling_pct=ceil, - targets=c.plan_targets()) + targets=c.plan_targets(), legs=legs) if end <= rp.cheap.end: return None return Roll(end, dict(sim.stops)) diff --git a/goodwe_controller/app/ctl_cycle.py b/goodwe_controller/app/ctl_cycle.py index c05ee7f..2a8bfda 100644 --- a/goodwe_controller/app/ctl_cycle.py +++ b/goodwe_controller/app/ctl_cycle.py @@ -512,7 +512,14 @@ class CycleMixin: self._peak_proj) if site_trade: floor_pct, ceiling_pct = arbitrage.soc_bounds(self.o) - charge_w, discharge_w = self.trade_power_w(floor_pct, ceiling_pct) + # TARIFF-30. WHOSE OWN BUY LEG CLEARS (None: no efficiency is set, + # which is today's behaviour exactly). The buy is sized to those + # units alone; the others are held out of it below. + legs = (self.charge_legs(self.fresh_tariff_plan(now), now) + if any(e is not None for e in self.unit_etas().values()) + else None) + charge_w, discharge_w = self.trade_power_w(floor_pct, ceiling_pct, + legs) self.arb = arbitrage.decide( self.fresh_tariff_plan(now), now, peak_guard_active=arbitrage.guard_state(self.peak_guard), @@ -539,6 +546,9 @@ class CycleMixin: # it. (DECISIONS/MAIN-orchestration-archive.md) charge_w=charge_w, discharge_w=discharge_w, soc_floor_pct=floor_pct, soc_ceiling_pct=ceiling_pct) + if legs is not None or self._lossy_hold[0]: + self._hold_out_lossy(claims, maint_results, legs, charge_w, + discharge_w, floor_pct, ceiling_pct, now) # SITE, and arbitrage.claim() says so on the object it builds. It # buys and sells at the grid against a day-ahead price: the price is # a property of the connection and the energy crosses the meter. diff --git a/goodwe_controller/app/ctl_trade.py b/goodwe_controller/app/ctl_trade.py index 8dbf5a9..e569808 100644 --- a/goodwe_controller/app/ctl_trade.py +++ b/goodwe_controller/app/ctl_trade.py @@ -9,7 +9,7 @@ from datetime import datetime, timedelta, timezone from . import arbitrage from .arbiter import ( - ACTUATOR_SITE, Claim, P_MAINTENANCE, P_MAINT_SHAPE, P_PEAK, SET, + ACTUATOR_SITE, Claim, P_MAINTENANCE, P_MAINT_SHAPE, P_MODE, P_PEAK, SET, pre_resolve, resolve, ) from . import allocator @@ -90,7 +90,7 @@ MAINT_CHARGING_W = 50.0 class TradeMixin: - def trade_power_w(self, floor_pct, ceiling_pct) -> tuple: + def trade_power_w(self, floor_pct, ceiling_pct, legs=None) -> tuple: """OPT-09. `(charge_w, discharge_w)`: how hard a trade may be SIZED: what the site can push AND STILL HAVE SOMEWHERE TO PUT. The bounds are arbitrage's own (`arbitrage_soc_floor` / `_ceiling`), NOT the BMS @@ -101,7 +101,79 @@ class TradeMixin: park order). DECISIONS/MAIN-orchestration.md.""" # The reduction lives in `packshare`; `test_packshare.py` part 9 calls # the SAME function (a transcription in a check is a copy that drifts). - return packshare.trade_power_w(self.pack_energy, floor_pct, ceiling_pct) + return packshare.trade_power_w(self.pack_energy, floor_pct, ceiling_pct, + legs) + + # TARIFF-30: units whose own buy leg failed while the site traded, and + # until when they stay held after it stopped (see `_hold_out_lossy()`). + _lossy_hold = (frozenset(), None) + LOSSY_WIND_S = 120.0 + + def _hold_out_lossy(self, claims, maint_results, legs, charge_w, + discharge_w, floor_pct, ceiling_pct, now) -> None: + """TARIFF-30, site trade only, with an efficiency set on some unit. + + 1. A buy that no unit's own leg can take is idle, and says why: the + sizing is 0 W for the losses (a charge asked of the packs without + `legs` was possible), so the refusal is `IDLE_LOSSES` rather than + the pack-state one. Still no claim, never a 0 W one. + 2. While the site charges, a unit whose own leg does not clear is held + at 0 W charge: a unit limit at P_MODE, `lo` 0. The weights are only + a preference and `_fill()`'s last-resort pass would otherwise hand + it watts when the others are full. It may still give (`hi` its + rating), and a unit in a maintenance phase keeps its own claim. + 3. When the trade stops, the loop starts from the trade's last target + and gives it up at its slew. That tail is the trade's, so the hold + stays while the site target is still charging, for LOSSY_WIND_S at + most: the unit whose leg failed takes none of it.""" + arb = self.arb + if (arb is not None and arb.action is None + and arb.reason == arbitrage.IDLE_NO_SIZE + and legs is not None + and not charge_w > 0.0 and discharge_w > 0.0 + and self.trade_power_w(floor_pct, ceiling_pct)[0] > 0.0): + self.arb = arb = arbitrage.idle_for_losses(arb) + names, until = self._lossy_hold + if arb is not None and arb.action == arbitrage.CHARGE \ + and legs is not None: + names, until = frozenset(n for n, ok in legs.items() if not ok), \ + None + elif names: + if until is None: + until = now + timedelta(seconds=self.LOSSY_WIND_S) + if now >= until or float(self.target or 0.0) >= 0.0: + names, until = frozenset(), None + self._lossy_hold = (names, until) + if len(self.inverters) <= 1: + return + for inv, result in zip(self.inverters, maint_results): + if inv.name not in names or result.phase != IDLE: + continue + claims.append(Claim.limit( + "mode", P_MODE, 0.0, float(inv.max_w), + "round-trip losses", actuator=self.actuator_of("mode", inv))) + + def unit_etas(self) -> dict: + """TARIFF-30. `{unit name: round_trip_eff or None}`, from the roster.""" + return {inv.name: getattr(inv, "round_trip_eff", None) + for inv in self.inverters} + + def charge_legs(self, plan, now): + """TARIFF-30. `{name: bool}`: whose OWN buy leg clears this cycle + (`arbitrage.clearing()`), or None: no unit has an efficiency, or the + verdict allows no trade. None is today's behaviour exactly. The same + figure for the site trade, the battery modes, the day plan and Home.""" + etas = self.unit_etas() + if plan is None or all(e is None for e in etas.values()): + return None + return arbitrage.clearing( + plan, now, + min_spread_eur_kwh=arbitrage.threshold_eur_kwh(self.o), + uncertainty=arbitrage.weather_uncertainty( + bool(getattr(self, "modes_on", False)), + getattr(self, "solar_fc", None), + bool(self.weather_held(now))), + etas=etas) def peak_aim_w(self) -> float: """SAFETY-79. `peak_cap_w` less `peak_margin_w`: what the forecast @@ -175,7 +247,8 @@ class TradeMixin: inv.name, pm.use, pm.mode, pm.sell and pm.can_sell, float(inv.max_w), inv.soc, inv.capacity_kwh, live=inv.name in live, idle=idle, refused=int(refused), - probing=probing)) + probing=probing, + eta=getattr(inv, "round_trip_eff", None))) return out def _wx_track(self, now) -> None: @@ -219,6 +292,11 @@ class TradeMixin: key = (id(plan), slot, tuple((p.name, p.use, p.mode, p.sell) for p in packs)) held = self.weather_held(now) + # TARIFF-30: which batteries' own buy legs clear (None: no efficiency + # set, today's plan). In the key, so a change rebuilds the plan. + legs = self.charge_legs(plan, now) + if legs is not None: + key += (tuple(sorted(legs.items())),) if self.fc_entity is not None: # P4: a forecast arriving or going rebuilds the plan at once (and # so does the end of a run that held the gap, TARIFF-24). @@ -227,7 +305,7 @@ class TradeMixin: done_c = self._run_done.get("charge", (None, set()))[1] done_s = self._run_done.get("sell", (None, set()))[1] e = modetrade.energy(packs, floor_pct, ceiling_pct, done_c, - done_s) + done_s, legs=legs) required = price_required_spread( arbitrage.threshold_eur_kwh(self.o), price_uncertainty_of(plan.read.product) @@ -281,7 +359,8 @@ class TradeMixin: self._plan_targets, dp.targets, {p.name: p.capacity_kwh for p in packs}) e2 = modetrade.energy(packs, floor_pct, ceiling_pct, done_c, (), - targets=self._plan_targets) + targets=self._plan_targets, + legs=self.charge_legs(plan, now)) return priceruns.plan( plan.read.points, now, required_eur_kwh=required, charge_kwh=e2[0], charge_kw=e2[1], sell_kwh=e[2], sell_kw=e[3], @@ -442,7 +521,8 @@ class TradeMixin: draining=any(r.phase == DRAIN for r in maint_results or ()), wait=wait, maint_charging=any(r.phase == CHARGE - for r in maint_results or ())) + for r in maint_results or ()), + legs=self.charge_legs(plan, now)) self._latch_charge(now, runs, targets, packs) # A charge the guard or the headroom stopped stays off this period. # OPT-15: only a MEASURED stop latches; the first unmeasured headroom diff --git a/goodwe_controller/app/daycurve.py b/goodwe_controller/app/daycurve.py index b662fb1..138b9db 100644 --- a/goodwe_controller/app/daycurve.py +++ b/goodwe_controller/app/daycurve.py @@ -30,7 +30,7 @@ import math from datetime import datetime, timedelta, timezone from dataclasses import dataclass -from .dayplan import EFF, _hour_slices, _local +from .dayplan import _hour_slices, _local, eff_of from .modetrade import CHARGE, GIVE, HOLD, HOUSE, REST EPS = 1e-9 @@ -52,6 +52,7 @@ class Batt: grid: tuple = () # ((start, end, to_pct), ...) grid blocks give: tuple = () # ((start, end), ...) give runs stop_at: datetime | None = None # a monthly cycle starts: no level after + eta: float | None = None # TARIFF-30: its own round-trip efficiency def _role(b, t, charging, own): @@ -97,7 +98,8 @@ def _give_caps(roles, level, by, floor, hrs): """`(first, rest, held)`: what each battery that may give can give in a step of `hrs` hours (its rating, or what it holds above the floor), those in a give run first, and what each holds above the floor (as given).""" - held = {n: max(0.0, level[n] - floor) / 100.0 * by[n].capacity_kwh * EFF + held = {n: max(0.0, level[n] - floor) / 100.0 * by[n].capacity_kwh + * eff_of(by[n].eta) for n, r in roles.items() if r[2]} caps = {n: min(by[n].rating_kw * hrs, h) for n, h in held.items()} first = {n: c for n, c in caps.items() if roles[n][0] == GIVE} @@ -180,7 +182,7 @@ def curve(batts, start, end, sun_kwh, use_kwh, *, floor_pct, ceiling_pct, for n, to in want.items(): b = by[n] room = (to - level[n]) / 100.0 * b.capacity_kwh - rate = b.rating_kw * hrs * EFF + rate = b.rating_kw * hrs * eff_of(b.eta) if EPS < room < rate * (1.0 - 1e-9): t_r = a + (z - a) * (room / rate) if a < t_r < z and (cut is None or t_r < cut): @@ -203,12 +205,12 @@ def curve(batts, start, end, sun_kwh, use_kwh, *, floor_pct, ceiling_pct, for n, to in want.items(): # charging from the grid b = by[n] room = (to - level[n]) / 100.0 * b.capacity_kwh - level[n] += min(b.rating_kw * hrs * EFF, room) \ + level[n] += min(b.rating_kw * hrs * eff_of(b.eta), room) \ / b.capacity_kwh * 100.0 if net > EPS: caps = {n: min(by[n].rating_kw * hrs, max(0.0, ceil - level[n]) / 100.0 - * by[n].capacity_kwh / EFF) + * by[n].capacity_kwh / eff_of(by[n].eta)) for n, r in roles.items() if r[1]} first = {n: c for n, c in caps.items() if by[n].solar_first} rest = {n: c for n, c in caps.items() if n not in first} @@ -216,14 +218,16 @@ def curve(batts, start, end, sun_kwh, use_kwh, *, floor_pct, ceiling_pct, for grp in (first, rest): got, left = _spread(left, grp, dict(grp)) for n, v in got.items(): - level[n] += v * EFF / by[n].capacity_kwh * 100.0 + level[n] += v * eff_of(by[n].eta) \ + / by[n].capacity_kwh * 100.0 elif net < -EPS: first, rest, held = _give_caps(roles, level, by, floor, hrs) left = -net for grp in (first, rest): got, left = _spread(left, grp, {n: held[n] for n in grp}) for n, v in got.items(): - level[n] -= v / EFF / by[n].capacity_kwh * 100.0 + level[n] -= v / eff_of(by[n].eta) \ + / by[n].capacity_kwh * 100.0 for b in batts: if b.name in alive: out[b.name].append((z, level[b.name])) diff --git a/goodwe_controller/app/dayplan.py b/goodwe_controller/app/dayplan.py index 7c81f42..246f52e 100644 --- a/goodwe_controller/app/dayplan.py +++ b/goodwe_controller/app/dayplan.py @@ -44,6 +44,7 @@ The site's own solar readings are not used: TEL-11 keeps them out of every control decision. """ +import math import statistics from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone @@ -52,7 +53,7 @@ from .packmode import CHEAP_HOURS, LEFTOVER_SOLAR, SOLAR_FIRST from .tariff import BILLING_TZ EFF = 0.95 # charge (and discharge) efficiency -HYST_KWH = 1.0 # a kept level moves only by this much... +HYST_KWH = 1.0 # a kept level moves only by this much... HYST_FRAC = 0.10 # ...or this share of the battery's shortfall PROFILE_DAYS = 7 MIN_HOURS = 20 # hours of a day recorded before it counts @@ -183,6 +184,14 @@ class Plan: solar_first_kwh: float = 0.0 +def eff_of(eta) -> float: + """TARIFF-30. One charge (or discharge) efficiency for ONE battery: `EFF` + where it has no round-trip efficiency set (today's number, unchanged), else + the square root of its round trip (one way). An approximation: B was + measured at about 93 % in and 81 % out; the in/out split is TARIFF-31's.""" + return EFF if eta is None else math.sqrt(float(eta)) + + def _hour_slices(t0, t1): """Local-hour slices of [t0, t1): (start, end, local hour). @@ -283,13 +292,14 @@ def _cheap_give_kwh(runs, now, house, packs, *, floor_pct, ceiling_pct, hrs = (e - s).total_seconds() / 3600.0 for p in ps: gain[p.name] += w * rate[p.name] / total * hrs \ - / 1000.0 * EFF + / 1000.0 * eff_of(getattr(p, "eta", None)) out = 0.0 for p in ps: cap = float(p.capacity_kwh) lvl = max(float(p.soc), min(float(ceiling_pct), float(p.soc) + gain[p.name] / cap * 100.0)) - out += max(0.0, lvl - float(floor_pct)) / 100.0 * cap * EFF + out += max(0.0, lvl - float(floor_pct)) / 100.0 * cap \ + * eff_of(getattr(p, "eta", None)) return out @@ -312,6 +322,11 @@ def _solar_first_give_kwh(house, now, start, packs, *, floor_pct): for s, e, h in _hour_slices(now, start)) have = {p.name: max(0.0, float(p.soc) - float(floor_pct)) / 100.0 * float(p.capacity_kwh) for p in ps} + if any(getattr(p, "eta", None) is not None for p in ps): + # TARIFF-30: each battery gives at its own one-way efficiency. + eff = {p.name: eff_of(getattr(p, "eta", None)) for p in ps} + took, _ = _spread(use, {n: have[n] * eff[n] for n in have}, have) + return sum(have[n] * eff[n] - took[n] for n in have) took, _ = _spread(use / EFF, have, have) return sum(have[n] - took[n] for n in have) * EFF @@ -341,6 +356,7 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct, use = max(house_w(h), base_w) * hrs / 1000.0 sun += max(0.0, pv - use) fc_sum += pv + sun_raw = sun sun *= trust * EFF usable = [p for p in packs if p.use and p.live and p.idle @@ -348,9 +364,28 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct, sf = [p for p in usable if p.mode == SOLAR_FIRST] price = [p for p in usable if p.mode == LEFTOVER_SOLAR] sf_room = sum(_room(p, ceiling_pct) for p in sf) + # TARIFF-30: with a round-trip efficiency on any battery, each one is + # charged and gives at its own one-way efficiency (`eff_of()`). With none + # set this is the code that shipped, unchanged. + per_unit = any(getattr(p, "eta", None) is not None for p in usable) + eff = {p.name: eff_of(getattr(p, "eta", None)) for p in usable} excess = max(0.0, sun - sf_room) rooms = {p.name: _room(p, ceiling_pct) for p in price} total_room = sum(rooms.values()) + sun_in = {} + if per_unit: + # The sun is counted in kWh in front of the batteries, then stored at + # each one's own efficiency: Solar first fill first, the rest by room. + raw = sun_raw * trust + sf_need = sum(_room(p, ceiling_pct) / eff[p.name] for p in sf) + sf_eff = sf_room / sf_need if sf_need > 0.0 else EFF + used = min(raw, sf_need) + rest = max(0.0, raw - sf_need) + sun_in = {n: (rest * rooms[n] / total_room * eff[n] + if total_room > 0 else 0.0) for n in rooms} + sun = used * sf_eff + (sum(sun_in.values()) if total_room > 0 + else rest * EFF) + sf_short = raw < sf_need # OPT-28: what the house draws in the expensive runs, from the one this # plan is for until the next cheap run (or a day), that the sun will not @@ -385,12 +420,26 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct, sfirst = min(sfirst, short - cheap) others = cheap + sfirst room_of = {n: span / 100.0 * c for n, c in caps.items()} - held, left = _spread((short - others) / EFF, room_of, caps) - held0 = _spread(short / EFF, room_of, caps)[0] if others > 0.0 else held + if per_unit: + # Shared by capacity in kWh given to the house; each battery's own + # grid kWh is that over its own efficiency. + room_d = {n: room_of[n] * eff[n] for n in room_of} + got, left = _spread(short - others, room_d, caps) + held = {n: got[n] / eff[n] for n in got} + if others > 0.0: + got0 = _spread(short, room_d, caps)[0] + held0 = {n: got0[n] / eff[n] for n in got0} + else: + held0 = held + else: + held, left = _spread((short - others) / EFF, room_of, caps) + held0 = _spread(short / EFF, room_of, caps)[0] if others > 0.0 \ + else held targets, need, share, cover, saved = {}, {}, {}, {}, {} for p in price: - sh = excess * rooms[p.name] / total_room if total_room > 0 else 0.0 + sh = (sun_in[p.name] if per_unit else + excess * rooms[p.name] / total_room if total_room > 0 else 0.0) sh_pct = sh / caps[p.name] * 100.0 top = float(floor_pct) + held[p.name] / caps[p.name] * 100.0 level = max(0.0, top - sh_pct) @@ -400,8 +449,9 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct, saved[p.name] = round( _room(p, max(0.0, top0 - sh_pct)) - need[p.name], 3) share[p.name] = round(sh, 3) - cover[p.name] = round(held[p.name] * EFF, 3) - if sun < sf_room: + cover[p.name] = round(held[p.name] * (eff[p.name] if per_unit + else EFF), 3) + if (sf_short if per_unit else sun < sf_room): verdict = DARK elif any(v > 0.05 for v in need.values()): verdict = PARTLY @@ -409,7 +459,8 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct, verdict = SUNNY return Plan(verdict, round(sun, 3), round(fc_sum, 3), until.start, targets, need, share, round(short, 3), cover, - round(left * EFF if price else 0.0, 3), round(cheap, 3), + round((left if per_unit else left * EFF) if price else 0.0, + 3), round(cheap, 3), saved, round(sfirst, 3)) diff --git a/goodwe_controller/app/dayview.py b/goodwe_controller/app/dayview.py index acf3d58..cd021cb 100644 --- a/goodwe_controller/app/dayview.py +++ b/goodwe_controller/app/dayview.py @@ -167,7 +167,8 @@ def _levels(c, est, fc, trust, now, end, runs, floor, ceil, notes_b, shadow, batts.append(Batt(inv.name, float(inv.capacity_kwh), inv.max_w / 1000.0, float(inv.soc), pm.mode == SOLAR_FIRST, priced, grid, give, - min(cyc) if cyc else None)) + min(cyc) if cyc else None, + getattr(inv, "round_trip_eff", None))) return batts def sun(a, z): @@ -222,7 +223,8 @@ def _levels(c, est, fc, trust, now, end, runs, floor, ceil, notes_b, shadow, for n in lv) if v is not None] end_t = cheaproll.roll_end( cheap, plan.read.points, packs_at, required=required, - floor_pct=floor, ceiling_pct=ceil, targets=targets) + floor_pct=floor, ceiling_pct=ceil, targets=targets, + legs=getattr(c, "charge_legs", lambda *_a: None)(plan, now)) ext = dataclasses.replace(rp, cheap=priceruns.Run( cheap.start, end_t, cheap.mean_eur_kwh)) rt, lv = settle(ext, lv0) diff --git a/goodwe_controller/app/homeview.py b/goodwe_controller/app/homeview.py index 617e359..40b5569 100644 --- a/goodwe_controller/app/homeview.py +++ b/goodwe_controller/app/homeview.py @@ -395,6 +395,9 @@ def trade_runs(c, plan, verdict, day0, day1, now, shadow, ahead=False): for i, inv in enumerate(c.inverters): if _off(c, inv): continue # OPT-11: an Off battery does not trade + if kind == "grid" and not arbitrage.leg_clears( + verdict, getattr(inv, "round_trip_eff", None)): + continue # TARIFF-30: its own losses eat the gap kwh = inv.max_w / 1000.0 * hrs cap = inv.capacity_kwh if cap: @@ -452,6 +455,12 @@ def mode_runs(c, day0, day1, now, shadow, ahead=False, rp=None): # UX-77: today's grid block runs to where control stops charging (the run # rolls on when it ends), each battery's to its own stop. roll = cheaproll.for_today(c, rp, now) if today else None + # TARIFF-30: whose own buy leg clears (None: none has an efficiency set). + legs = None + if now is not None and hasattr(c, "charge_legs") and any( + getattr(inv, "round_trip_eff", None) is not None + for inv in c.inverters): + legs = c.charge_legs(c.fresh_tariff_plan(now), now) out = [] for i, inv in enumerate(c.inverters): pm = c.pack_mode(inv) @@ -484,6 +493,7 @@ def mode_runs(c, day0, day1, now, shadow, ahead=False, rp=None): need = plan_need(c, inv.name, start_pct("grid", rp.cheap.start) if ahead and rp.cheap is not None else None) if gate is None and rp.charge_useful() and ( + legs is None or legs.get(inv.name, True)) and ( need > 0.0 if need is not None else pm.mode in GRID_CHARGE_MODES): cheap = rp.cheap if roll is None else priceruns.Run( @@ -938,6 +948,12 @@ def battery_rows(c, shadow, running, held=False): "level_pct": None if inv.soc is None else float(inv.soc), "power_w": None if inv.batt is None else float(inv.batt), "capacity_kwh": cap, + # TARIFF-30: this battery's configured round-trip efficiency in %, + # or None ("not set"). Config only, never a reading. + "round_trip_pct": (None if getattr(inv, "round_trip_eff", None) + is None + else round(float(inv.round_trip_eff) * 100.0, + 1)), "stored_kwh": (None if cap is None or inv.soc is None else round(cap * float(inv.soc) / 100.0, 2)), "state": flow(inv.batt, shadow=shadow), diff --git a/goodwe_controller/app/inverter.py b/goodwe_controller/app/inverter.py index 7af5188..fa6896b 100644 --- a/goodwe_controller/app/inverter.py +++ b/goodwe_controller/app/inverter.py @@ -171,6 +171,10 @@ LINK_STALE_S = GOODWE_LINK_STALE_S # only ever have belonged to a single-inverter install. UNIT_A = "inverter-a" +# TARIFF-30. The range `round_trip_eff` may take, per inverter entry. The +# schema in config.yaml says the same (`float(0.5,1)?`). +RTE_MIN, RTE_MAX = 0.5, 1.0 + # The per-unit keys this object keeps in the Store, namespaced by unit name. # ⚠️ THE VALUES ARE THE PRE-DEV-02 FLAT KEY NAMES, and that is what makes the # migration mechanical rather than transcribed: `store.migrate_unit_keys()` @@ -202,8 +206,15 @@ class Inverter: def __init__(self, name, *, setpoint_entity="", soc_entity="", batt_entity="", batt_invert=False, max_w=2000.0, bms_soc_floor=None, capacity_kwh=None, store=None, - sign_cfg=None, delivery_cfg=None, driver=None): + sign_cfg=None, delivery_cfg=None, driver=None, + round_trip_eff=None): self.name = str(name) + # TARIFF-30. THIS PACK'S OWN ROUND-TRIP EFFICIENCY (0.5 to 1.0), or None + # when the entry did not set one - which is today's behaviour exactly. + # Config only: never a reading, never learned (TARIFF-31), and never + # taken from a sibling. + self.round_trip_eff = (None if round_trip_eff is None + else float(round_trip_eff)) # SMA-2. HOW THIS UNIT IS READ AND STEERED. The entity keywords above # are the GoodWe driver's, kept so every existing caller builds the # same unit; a roster entry that selects another driver passes @@ -677,6 +688,8 @@ def build_roster(opts: dict, store, sign_cfg=None, # though it were a 20.48 kWh one, which is the split this card # exists to stop being wrong. capacity_kwh=_entry_capacity_kwh(entry), + # TARIFF-30: this entry's own, never a sibling's. + round_trip_eff=entry_round_trip_eff(entry), store=store, sign_cfg=sign_cfg, delivery_cfg=delivery_cfg)) return roster @@ -773,6 +786,26 @@ def _entry_capacity_kwh(entry: dict): return val if val > 0.0 else None +def entry_round_trip_eff(entry): + """TARIFF-30. One entry's OWN round-trip efficiency (0.5 to 1.0), or None. + + None means "not set", and it is today's behaviour exactly. A value that is + not a usable number in range also answers None here: validate.py rule 9 + refuses it at startup with a message, and withholding is the direction that + cannot invent a preference. Never read from a sensor or the store, and + never defaulted from another unit.""" + if not isinstance(entry, dict): + return None + raw = entry.get("round_trip_eff") + if raw is None or raw == "" or isinstance(raw, bool): + return None + try: + val = float(raw) + except (TypeError, ValueError): + return None + return val if (math.isfinite(val) and RTE_MIN <= val <= RTE_MAX) else None + + def _entry_max_w(entry: dict) -> float: """One entry's supervised cap, or 0.0 when it did not state a usable one. diff --git a/goodwe_controller/app/messages.py b/goodwe_controller/app/messages.py index ce31b6c..a628d48 100644 --- a/goodwe_controller/app/messages.py +++ b/goodwe_controller/app/messages.py @@ -1921,6 +1921,7 @@ LABELS = { "max_w": "Inverter rating", "bms_soc_floor": "Battery cut-out level", "capacity_kwh": "Usable battery capacity", + "round_trip_eff": "Round-trip efficiency", "inverters": "Inverter list", "name": "Name", "meter_source": "Where the meter reading comes from", @@ -2012,6 +2013,7 @@ LABELS_NL = { "max_w": "Vermogen van de omvormer", "bms_soc_floor": "Uitschakelniveau van de batterij", "capacity_kwh": "Bruikbare capaciteit", + "round_trip_eff": "Rendement heen en terug", "inverters": "Lijst met omvormers", "name": "Naam", "meter_source": "Waar de meterstand vandaan komt", diff --git a/goodwe_controller/app/modetrade.py b/goodwe_controller/app/modetrade.py index 75f6c58..165060b 100644 --- a/goodwe_controller/app/modetrade.py +++ b/goodwe_controller/app/modetrade.py @@ -102,6 +102,7 @@ class Pack: idle: bool = True # not in a maintenance phase refused: int = 0 # SAFETY-52/73: +1 refuses to give, -1 to charge probing: bool = False # OPT-15: its SAFETY-73 probe window is open + eta: float | None = None # TARIFF-30: its own round-trip efficiency @dataclass(frozen=True) @@ -140,18 +141,26 @@ def charge_to(p: Pack, ceiling_pct, targets=None): return None if t is None else min(float(ceiling_pct), float(t)) -def chargers(packs, ceiling_pct, done=(), targets=None, probe=False) -> list: +def chargers(packs, ceiling_pct, done=(), targets=None, probe=False, + legs=None) -> list: """Batteries that may charge from the grid in a cheap run: below the level `charge_to()` allows them (P4: the day plan's). With `probe`, also one refusing to charge while its SAFETY-73 probe is open: its own P_SAFETY - pin keeps it at PROBE_W (OPT-15).""" + pin keeps it at PROBE_W (OPT-15). + + TARIFF-30. `legs` is `{name: bool}` (`arbitrage.clearing()`) or None. A + battery whose own buy leg does not clear (its round-trip losses eat the + spread) is not a charger. None is today's list. The SAFETY-73 probe is not + an economic charge and runs unchanged (a probing refuser stays a charger).""" out = [] for p in packs: to = charge_to(p, ceiling_pct, targets) + probing = probe and p.probing and p.refused < 0 if (to is not None and p.use and p.idle and p.live and p.soc is not None and p.soc < to and (p.refused >= 0 or (probe and p.probing)) - and p.name not in done): + and p.name not in done + and (probing or legs is None or legs.get(p.name, True))): out.append(p) return out @@ -166,11 +175,11 @@ def sellers(packs, floor_pct, done=()) -> list: def energy(packs, floor_pct, ceiling_pct, done_charge=(), done_sell=(), - targets=None): + targets=None, legs=None): """`(charge_kwh, charge_kw, sell_kwh, sell_kw)` for `priceruns.plan()`. With a day plan the charge is each battery's shortfall, so the cheap run - is only as long as the shortfall needs.""" - ch = chargers(packs, ceiling_pct, done_charge, targets) + is only as long as the shortfall needs. `legs`: see `chargers()`.""" + ch = chargers(packs, ceiling_pct, done_charge, targets, legs=legs) se = sellers(packs, floor_pct, done_sell) return (sum(_room_kwh(p, charge_to(p, ceiling_pct, targets)) for p in ch), @@ -183,7 +192,7 @@ def decide(runs, now, packs, *, charge_ok, sell_ok, trade_why, price_now, headroom_w, floor_pct, ceiling_pct, house_w, charging_now=False, blocked=False, done_charge=(), done_sell=(), targets=None, draining=False, wait=None, - maint_charging=False) -> Tick: + maint_charging=False, legs=None) -> Tick: """This tick's ranges, roles and site ask. `runs` is the kept `priceruns.RunPlan` or None (no fresh prices). @@ -200,7 +209,8 @@ def decide(runs, now, packs, *, charge_ok, sell_ok, trade_why, price_now, why) says no charge may start yet (SAFETY-135). `maint_charging` says a battery is in its maintenance CHARGE phase: no grid charge for the others either, same why, but a refusal probe goes on (MAINT-24, - DECISIONS/MAINT-24-charge-first.md). + DECISIONS/MAINT-24-charge-first.md). `legs` (TARIFF-30): `{name: bool}`, + which batteries' own buy legs clear (`chargers()`), or None. """ plan_on = runs is not None and runs.on in_cheap = plan_on and runs.cheap.holds(now) and runs.charge_useful() @@ -208,8 +218,8 @@ def decide(runs, now, packs, *, charge_ok, sell_ok, trade_why, price_now, in_sell = plan_on and runs.sell is not None and runs.sell.holds(now) why = None - ch = chargers(packs, ceiling_pct, done_charge, targets, probe=True) \ - if in_cheap else [] + ch = chargers(packs, ceiling_pct, done_charge, targets, probe=True, + legs=legs) if in_cheap else [] if ch and draining: ch, why = [], "cycle" elif ch and maint_charging: diff --git a/goodwe_controller/app/packshare.py b/goodwe_controller/app/packshare.py index adf603b..6a90c55 100644 --- a/goodwe_controller/app/packshare.py +++ b/goodwe_controller/app/packshare.py @@ -420,7 +420,7 @@ def weights(packs, target_w) -> dict | None: return out -def trade_power_w(packs, floor_pct, ceiling_pct) -> tuple: +def trade_power_w(packs, floor_pct, ceiling_pct, legs=None) -> tuple: """`(charge_w, discharge_w)` - how hard an arbitrage trade may be SIZED. The site rating is what the site can push; this is what the site can push @@ -457,8 +457,14 @@ def trade_power_w(packs, floor_pct, ceiling_pct) -> tuple: the buy gate refuses when every pack is at the ceiling; `arbitrage.decide()` refuses a 0 W sizing by name anyway, so that is structural rather than a coincidence of the gates. + + TARIFF-30. `legs` is `{name: bool}` (`arbitrage.clearing()`) or None. A pack + whose own buy leg does not clear is not counted on the BUY side: the trade + is sized to what may actually charge. None is today's sum. The sell side + never reads it. """ return (float(sum(p.max_w for p in packs - if p.soc is not None and float(p.soc) < ceiling_pct)), + if p.soc is not None and float(p.soc) < ceiling_pct + and (legs is None or legs.get(p.name, True)))), float(sum(p.max_w for p in packs if p.soc is not None and float(p.soc) > floor_pct))) diff --git a/goodwe_controller/app/static/app.js b/goodwe_controller/app/static/app.js index 9efe6ee..b0e9168 100644 --- a/goodwe_controller/app/static/app.js +++ b/goodwe_controller/app/static/app.js @@ -467,6 +467,7 @@ levelBar(b.level_pct, b.name), h("dl", { class: "kv" }, h("dt", {}, t("batteries.level")), h("dd", {}, lvl + stored), + h("dt", {}, t("batteries.round_trip")), h("dd", {}, b.round_trip_pct != null ? dec(String(b.round_trip_pct)) + " %" : t("batteries.round_trip_unset")), h("dt", {}, t("batteries.now")), h("dd", {}, b.now), h("dt", {}, t("batteries.today")), h("dd", {}, todayLines(b)), h("dt", {}, t("batteries.why")), h("dd", { class: "muted" }, b.why || "–")), diff --git a/goodwe_controller/app/ui_text/en.json b/goodwe_controller/app/ui_text/en.json index a67500f..215462c 100644 --- a/goodwe_controller/app/ui_text/en.json +++ b/goodwe_controller/app/ui_text/en.json @@ -105,7 +105,7 @@ "toast": {"started": "Control started.", "stopped": "Control stopped.", "done": "Done.", "failed": "That did not work. Try again."}, "offline": {"name": "Cannot reach the add-on", "description": "The page tries again every 3 seconds."}, "setup_only": {"name": "Setup: nothing is controlled yet", "description": "Nothing is sent to any inverter until setup is saved and the add-on restarts.", "control": "Control starts after setup.", "open": "Open Setup"}, - "batteries": {"name": "Batteries", "description": "To choose a mode for each battery, turn on battery modes in the settings.", "level": "Level", "now": "Now", "stored": "Stored", "mode": "Mode", "settings": "Change inverter settings", + "batteries": {"name": "Batteries", "description": "To choose a mode for each battery, turn on battery modes in the settings.", "level": "Level", "now": "Now", "stored": "Stored", "round_trip": "Round trip", "round_trip_unset": "not set", "mode": "Mode", "settings": "Change inverter settings", "on": "On", "off": "Off", "choice": { "solar_first": {"name": "Solar first", "description": "Charges from solar before the other batteries, covers the house and never charges from the grid."}, diff --git a/goodwe_controller/app/ui_text/nl.json b/goodwe_controller/app/ui_text/nl.json index 3f87c78..6bec08d 100644 --- a/goodwe_controller/app/ui_text/nl.json +++ b/goodwe_controller/app/ui_text/nl.json @@ -102,7 +102,7 @@ "toast": {"started": "Regeling gestart.", "stopped": "Regeling gestopt.", "done": "Klaar.", "failed": "Dat lukte niet. Probeer opnieuw."}, "offline": {"name": "Add-on niet bereikbaar", "description": "De pagina probeert het elke 3 seconden opnieuw."}, "setup_only": {"name": "Installatie: nog niets wordt geregeld", "description": "Er gaat niets naar een omvormer tot de installatie bewaard is en de add-on herstart.", "control": "De regeling start na de installatie.", "open": "Installatie openen"}, - "batteries": {"name": "Batterijen", "description": "Zet batterijmodi aan in de instellingen om per batterij een modus te kiezen.", "level": "Laadniveau", "now": "Nu", "stored": "Opgeslagen", "mode": "Modus", "settings": "Instellingen van omvormers wijzigen", + "batteries": {"name": "Batterijen", "description": "Zet batterijmodi aan in de instellingen om per batterij een modus te kiezen.", "level": "Laadniveau", "now": "Nu", "stored": "Opgeslagen", "round_trip": "Rendement heen en terug", "round_trip_unset": "niet ingesteld", "mode": "Modus", "settings": "Instellingen van omvormers wijzigen", "on": "Aan", "off": "Uit", "choice": { "solar_first": {"name": "Eerst zonne-energie", "description": "Laadt met zonne-energie vóór de andere batterijen, dekt het huis en laadt nooit van het net."}, diff --git a/goodwe_controller/app/uilayout.py b/goodwe_controller/app/uilayout.py index bedcbc5..8bbe1ea 100644 --- a/goodwe_controller/app/uilayout.py +++ b/goodwe_controller/app/uilayout.py @@ -92,6 +92,9 @@ ROSTER_FIELDS = ( Field("inverters.batt_invert", TOGGLE, wizard=2), Field("inverters.capacity_kwh", NUMBER, "kWh", step=0.1, show=_LISTED, wizard=2), + # TARIFF-30: optional, 0.5 to 1; not shown for the flat single inverter + # (it stores no per-unit keys) and not in the setup wizard. + Field("inverters.round_trip_eff", NUMBER, step=0.01, show=_LISTED), ) GROUPS = ( diff --git a/goodwe_controller/app/validate.py b/goodwe_controller/app/validate.py index 4a0f2c5..fb4f4b4 100644 --- a/goodwe_controller/app/validate.py +++ b/goodwe_controller/app/validate.py @@ -829,6 +829,26 @@ def _roster_problems(opts: dict) -> list[str]: f"{S('capacity_kwh')} is set on {', '.join(stated)} but empty on " f"{', '.join(blank)}. Set it on every inverter, or on none.") + # --- (i) TARIFF-30: `round_trip_eff`, optional per entry, 0.5 to 1.0 ----- + # Mixed installs are allowed (unlike capacity_kwh): each unit's buy leg uses + # its own meaning, so there is no all-or-none rule here. + for i, entry in enumerate(entries): + if not isinstance(entry, dict): + continue + raw = entry.get("round_trip_eff") + if raw is None or raw == "": + continue + nm = str(entry.get("name") or "").strip() + who = f"inverters[{i}] ({nm})" if nm else f"inverters[{i}]" + try: + val = None if isinstance(raw, bool) else float(raw) + except (TypeError, ValueError): + val = None + if val is None or not math.isfinite(val) or not (0.5 <= val <= 1.0): + problems.append( + f"{who} has {S('round_trip_eff')} {messages.shown(raw)}, which " + "is not usable. Set it from 0.5 to 1, or leave it empty.") + flat_sp = str(opts.get("setpoint_entity") or "").strip() if entries and flat_sp: problems.append( diff --git a/goodwe_controller/config.yaml b/goodwe_controller/config.yaml index e5faf3c..24010e2 100644 --- a/goodwe_controller/config.yaml +++ b/goodwe_controller/config.yaml @@ -986,6 +986,8 @@ schema: batt_entity: str? batt_invert: bool? capacity_kwh: float(0.1,200)? + # TARIFF-30: optional per entry, 0.5 to 1. Not set = today's behaviour. + round_trip_eff: float(0.5,1)? estop_fitted: bool battery_modes_enabled: bool diff --git a/goodwe_controller/scenarios/tariff30-base-trace.json b/goodwe_controller/scenarios/tariff30-base-trace.json new file mode 100644 index 0000000..b0b5952 --- /dev/null +++ b/goodwe_controller/scenarios/tariff30-base-trace.json @@ -0,0 +1,10 @@ +{ + "arbitrage_decide": { + "n": 5184, + "sha256": "ea73ac21d4f466851e61582dbf208007c109c97ef04e0f929b13a22de2a39757" + }, + "modetrade": { + "n": 1944, + "sha256": "2ccf41a247136f933df95615fd3ee6222a44d77c34e54636f08f23bb6925411d" + } +} diff --git a/goodwe_controller/test_tariff30.py b/goodwe_controller/test_tariff30.py new file mode 100644 index 0000000..d2f5298 --- /dev/null +++ b/goodwe_controller/test_tariff30.py @@ -0,0 +1,1146 @@ +"""TARIFF-30: each battery's own round-trip efficiency in the grid-charge +decisions. Run: python3 test_tariff30.py + +Part A only (the discharge split is unchanged: part B is TARIFF-34). + +An optional per-inverter key `round_trip_eff` (0.5 to 1). Set on a unit, its +buy leg is priced at `price / eta`: the cheap hour must still beat the dear one +by what a cycle needs. Not set, behaviour is exactly what it was. + + 1. the buy leg arithmetic (T3, T4, T9, T51), the boundary and the mixed cases + 2. the site trade, through the real Controller cycle (T1, T5, T6, T7, T10, + T11, T12, T17), with a plant that charges and a meter that reads it + 3. battery modes (T2, T13, T52) and what Home draws (T40, N13) + 4. the discharge split is the base's (T16, T18-T22, T24-T31, T44, T45, N1, N7) + 5. identity without an efficiency: a golden trace printed on 831c33c (T8, N6) + 6. day plan and level curve per battery (T36-T39, T49) + 7. config: accepted, refused, schema, text, settings (T32-T35, T43, T50) + 8. the status page (T41, T42) + +Every check names the T/N row of the test plan it grades. The mutants run for +this file are listed in the pull request (MUTATION.md). +""" +import hashlib +import json +import logging +import math +import os +import re +import sys +import types +from datetime import datetime, timedelta, timezone + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.join(HERE, "tools")) +logging.disable(logging.WARNING) + +from named_absence import first, nth, present # noqa: E402 +import opt11p3_replay as rp # noqa: E402 +import ux54_scenarios as S # noqa: E402 +import tariff30_trace # noqa: E402 +from app import (allocator, arbiter, arbitrage, daycurve, dayplan, dayview, # noqa: E402 + homeview, inverter, modetrade, packmode, packshare, + priceruns, solarfc, uimodel, validate) +from app.arbiter import Claim, P_LOOP, P_PEAK, P_SAFETY # noqa: E402 +from app.ctl_trade import pack_energy_of # noqa: E402 +from app.main import Controller # noqa: E402 +from app.peakguard import PeakDecision # noqa: E402 +from app.price import Uncertainty # noqa: E402 +from app.static_tariff import static_plan # noqa: E402 +from app.store import unit_key # noqa: E402 +from app.tariff import BILLING_TZ # noqa: E402 + +UTC = timezone.utc +NO_WX = frozenset({Uncertainty.NO_WEATHER}) +A, B, C = "inverter-a", "inverter-b", "inverter-c" +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +def guarded(title): + """Run a section; an exception is one NAMED red, not a dead file.""" + def deco(fn): + try: + fn() + except Exception as e: # noqa: BLE001 + check(f"{title}: raised {type(e).__name__}: {str(e)[:160]}", False) + return fn + return deco + + +# --- fixtures -------------------------------------------------------------- # +ENTRIES = [ + {"name": A, "setpoint_entity": "number.sp_a", "soc_entity": "sensor.soc_a", + "batt_entity": "sensor.batt_a", "max_w": 5000, "bms_soc_floor": 10, + "capacity_kwh": 15.36}, + {"name": B, "setpoint_entity": "number.sp_b", "soc_entity": "sensor.soc_b", + "batt_entity": "sensor.batt_b", "max_w": 4600, "bms_soc_floor": 10, + "capacity_kwh": 20.48}, + {"name": C, "setpoint_entity": "number.sp_c", "soc_entity": "sensor.soc_c", + "batt_entity": "sensor.batt_c", "max_w": 3000, "bms_soc_floor": 10, + "capacity_kwh": 10.24}, +] +ETA = (0.86, 0.75) # the card: A 86 %, B 75 % +NONE2 = (None, None) + + +def entries(etas, n=None): + out = [] + for e, eta in zip(ENTRIES[:n or len(etas)], etas): + e = dict(e) + if eta is not None: + e["round_trip_eff"] = eta + out.append(e) + return out + + +def local(y, mo, d, h, m=0, s=0): + return datetime(y, mo, d, h, m, s, tzinfo=BILLING_TZ).astimezone(UTC) + + +def prices_for(start, night=0.2333, day=0.2801): + """Hourly points for three local days, all-in `night` 22:00-07:00 and `day` + 07:00-22:00, as the wholesale figures the replay turns into those.""" + d0 = start.astimezone(BILLING_TZ).replace(hour=0, minute=0, second=0, + microsecond=0) + out = [] + for i in range(72): + t = d0 + timedelta(hours=i) + allin = night if (t.hour >= 22 or t.hour < 7) else day + out.append((t.astimezone(UTC), 3600, allin / 1.06 - 0.12)) + return out + + +def drive(etas, *, start=None, dur=40.0, load=500.0, soc0=None, peak_cap=20000, + thr=0.0, variant="arb_only", limits=None, each=None, extra=None, + n=None): + """The real Controller (read_inputs + cycle) over `dur` s on a plant that + charges and a meter that reads it. Returns (rows, controller): one row per + cycle with what arbitrage decided, what each unit was given and does.""" + start = start or local(2026, 11, 1, 22, 5) + n = n or len(etas) + rows = [] + + def cb(c, hass, now, pr): + al = c.allocation + rows.append({ + "t": round((now - start).total_seconds()), + "action": getattr(c.arb, "action", None), + "power": getattr(c.arb, "power_w", None), + "reason": getattr(c.arb, "reason", None), + "shares": {} if al is None else dict(al.shares), + "plant": {u: p.p for u, p in hass.plants.items()}, + "soc": {u: p.soc for u, p in hass.plants.items()}, + "writes": {i.name: i.last_write for i in c.inverters}, + }) + if each is not None: + each(c, hass, now, pr) + + opt = {"cycle_cost_threshold_eur": thr, "peak_cap_w": peak_cap, + "inverters": entries(etas, n)} + opt.update(extra or {}) + _stats, c = rp.run(variant, [(start.timestamp() - 10, load)], + prices_for(start), start, dur, check=cb, n=n, + soc0=soc0 or {"a": 50.0, "b": 50.0, "c": 50.0}, + extra=opt, limits=limits) + return rows, c + + +def share(row, unit): + return row["shares"].get(unit) + + +def settled(rows): + return nth(rows, -1) + + +def mk(etas=NONE2, *, modes=None, arb=False, thr=0.0, soc=(50.0, 50.0), + now=None, n=None, flat=False, room=6000.0, extra=None): + """A Controller with the two (or three) inverters, not yet cycled.""" + opts = dict(S.BASE) + opts.update(static_profile=json.dumps(S.DN), arbitrage_enabled=arb, + cycle_cost_threshold_eur=thr, peak_cap_w=20000) + n = n or len(etas) + if flat: + opts.pop("inverters") + opts.update(setpoint_entity="number.sp", soc_entity="sensor.soc_a", + batt_entity="sensor.batt_a", max_w=5000) + else: + opts["inverters"] = entries(etas, n) + if modes is not None: + opts["battery_modes_enabled"] = True + opts.update(extra or {}) + c = Controller(opts, S.Hass(), S.Store(), S.Pub(), stop=S.asyncio.Event()) + c.auto = True + for i, inv in enumerate(c.inverters): + inv.soc, inv.batt, inv.last_write = soc[i], 0.0, 0.0 + inv.dev_min, inv.dev_max = -5000.0, 5000.0 + if modes is not None: + c.store.data[unit_key(inv.name, packmode.MODE_KEY)] = modes[i] + c.pv_w, c.grid = 0.0, 500.0 + c.peak_guard = PeakDecision(engaged=False, floor_w=None, ceiling_w=7000.0, + ceiling_from="cap", projected_w=800.0) + c.arb_headroom_w = room + if now is not None: + c.tariff_plan = static_plan(opts, S.day0_of(now), + S.day0_of(now) + timedelta(hours=48), + now=now) + c.tariff_at = now + return c + + +def split(c, load, socs=None, live=None): + """Control's discharge split of `load` W over the roster, through the real + arbiter and allocator with the controller's own weights. Returns + `{unit: W}`.""" + units = tuple(i.name for i in c.inverters) + if socs: + for inv, s in zip(c.inverters, socs): + inv.soc = s + claims = [Claim.set("loop", P_LOOP, float(load), "test")] + for inv in c.inverters: + claims.append(Claim.limit("supervised", P_SAFETY, -inv.max_w, + inv.max_w, "max", actuator=inv.name)) + pe = packshare.envelope(pack_energy_of(inv)) + claims.append(Claim.limit("pack", P_SAFETY, pe.lo, pe.hi, pe.why, + actuator=inv.name)) + res = arbiter.resolve(claims, units=units, weights=c.pack_weights, + live=set(live or units)) + return dict(res.shares) + + +def real_plan(now): + opts = dict(S.BASE) + opts.update(static_profile=json.dumps(S.DN)) + return static_plan(opts, S.day0_of(now), + S.day0_of(now) + timedelta(hours=48), now=now) + + +NIGHT = local(2026, 11, 1, 23, 30) +DAYTIME = local(2026, 11, 1, 10, 0) + + +def clears(etas, thr, now=NIGHT, unc=NO_WX): + return arbitrage.clearing( + real_plan(now), now, min_spread_eur_kwh=thr, uncertainty=unc, + etas={A: etas[0], B: etas[1]}) + + +# ============================================================================ # +print("1. the buy leg: price / eta against what the cycle needs") +# ============================================================================ # + + +@guarded("section 1") +def _s1(): + # T3: break-even at threshold 0, B unset. Net is dearest - cheapest / eta. + v = types.SimpleNamespace( + cheapest=types.SimpleNamespace(eur_per_kwh=0.2333), + dearest=types.SimpleNamespace(eur_per_kwh=0.2801), + required_spread_eur_kwh=0.0) + check("T3 0.8330 clears at the break-even (net +0.000028)", + arbitrage.leg_clears(v, 0.8330) is True) + check("T3 0.8329 does not (net -0.0000056)", + arbitrage.leg_clears(v, 0.8329) is False) + check("T3 no efficiency: the verdict is the answer, as today", + arbitrage.leg_clears(v, None) is True) + # T1/card: A 0.86 is charged, B 0.75 is not, at 0.2333 / 0.2801. + got = clears(ETA, 0.0) + check("T1 card: A 0.86 clears, B 0.75 does not", + got == {A: True, B: False}) + # T4: the threshold is wear only; x1.5 widening on the threshold (not on + # the loss). need = 1.5 x thr. + check("T4 thr 0.005 (need 0.0075): A 0.86 clears (net 0.00882)", + clears((0.86, None), 0.005) == {A: True, B: True}) + check("T4 thr 0.006 (need 0.009): A does not (0.00882), B unset does " + "(0.0468)", clears((0.86, None), 0.006) == {A: False, B: True}) + # T51: the loss term is not widened. + check("T51 thr 0.004, need 0.006: A 0.86 clears (a widened loss term, " + "0.03798 x 1.5, would refuse it)", + clears((0.86, None), 0.004) == {A: True, B: True}) + # T9: mixed installs, each unit its own meaning. + check("T9a A unset, B 0.75, thr 0: A charged, B not", + clears((None, 0.75), 0.0) == {A: True, B: False}) + check("T9b A 0.86, B unset, thr 0.02 (need 0.03): B charged, A not", + clears((0.86, None), 0.02) == {A: False, B: True}) + check("T9c an absent efficiency is today's spread, not 0.95: A 0.86, B " + "unset, thr 0.03 (need 0.045): B clears on 0.0468", + clears((0.86, None), 0.03) == {A: False, B: True}) + check("no efficiency anywhere: nothing to decide (None), today's path", + clears(NONE2, 0.0) is None) + check("a spread that does not clear the cycle at all: None (the verdict " + "refuses first), whatever the efficiency", + clears(ETA, 0.10) is None) + # the buy size follows the units whose own leg clears (M6) + packs = [types.SimpleNamespace(name=A, soc=50.0, max_w=5000.0), + types.SimpleNamespace(name=B, soc=50.0, max_w=4600.0)] + check("T1 sizing: the buy counts the clearing unit only (5000 W, not " + "9600), the sell side counts both", + packshare.trade_power_w(packs, 10.0, 95.0, {A: True, B: False}) + == (5000.0, 9600.0) + and packshare.trade_power_w(packs, 10.0, 95.0) == (9600.0, 9600.0)) + + +# ============================================================================ # +print("2. the site trade, through the real controller cycle") +# ============================================================================ # + + +@guarded("T1") +def _t1(): + rows, c = drive(ETA) + last = settled(rows) + check("T1 A 0.86 / B 0.75: CHARGE sized 5000 W, A -5000, B 0", + last["action"] == arbitrage.CHARGE and last["power"] == -5000.0 + and share(last, A) == -5000 and share(last, B) == 0) + check("T1 ...on every cycle, and B's plant is never charged", + all(r["action"] == arbitrage.CHARGE and share(r, B) == 0 + and r["plant"][B[-1]] == 0.0 for r in rows) and len(rows) > 5) + check("N2/T17 no negative share on B and no mixed signs, on every cycle", + all((share(r, B) or 0) >= 0 and (share(r, A) or 0) <= 0 + for r in rows)) + base_rows, _c = drive(NONE2) + bl = settled(base_rows) + check("T1 base for comparison: with no efficiency both charge, 9600 W", + bl["power"] == -9600.0 and share(bl, A) == -5000 + and share(bl, B) == -4600) + check("T1 reason: today's sentence (the buy leg is sized by whom it " + "charges)", "charging 5000 W" in last["reason"]) + + +@guarded("T5") +def _t5(): + rows, c = drive((0.75, 0.75)) + check("T5 both 0.75, thr 0: idle on every cycle, no power, no claim", + all(r["action"] is None and r["power"] is None for r in rows) + and arbitrage.claim(c.arb) is None) + why = c.arb.reason + check("T5 the reason is short and plain and names the losses", + why == arbitrage.IDLE_LOSSES and "lose" in why and len(why) < 100) + check("T5 nobody charges: no unit is told to charge", + all((share(r, A) or 0) >= 0 and (share(r, B) or 0) >= 0 + for r in rows)) + + +@guarded("T6") +def _t6(): + # A reaches the arbitrage ceiling mid-trade: B must not take its place. + rows, c = drive(ETA, dur=60.0, soc0={"a": 94.9, "b": 50.0}, + extra={"arbitrage_soc_ceiling": 95}) + tripped = [r for r in rows if r["soc"]["a"] >= 95.0] + check("T6 A reaches the ceiling during the run", len(tripped) > 0) + check("T6 B gets 0 W of charge on every cycle, before and after", + all((share(r, B) or 0) >= 0 and r["plant"][B[-1]] >= 0.0 + for r in rows)) + check("T6 once A is at the ceiling the trade is idle (no 0 W claim)", + all(r["action"] is None and r["power"] is None for r in tripped)) + # A cannot take what is asked (its own device range): B still gets none, + # also in the allocator's last-resort pass. + rows2, c2 = drive(ETA, dur=40.0, limits={"a": (-3000.0, 5000.0)}) + check("T6 A's device range 3000 W: B still gets 0 W (the last-resort " + "pass does not hand it the rest)", + all((share(r, B) or 0) >= 0 and r["plant"][B[-1]] >= 0.0 + for r in rows2) and len(rows2) > 5) + check("T6 ...and A carries what it can (-3000 W)", + share(settled(rows2), A) == -3000) + + +@guarded("T7") +def _t7(): + start = local(2026, 11, 1, 7, 0, 5) + r1, c1 = drive(ETA, start=start) + r0, c0 = drive(NONE2, start=start) + a, b = settled(r1), settled(r0) + check("T7 the sell hour: DISCHARGE, same power and same reason with and " + "without an efficiency (the sell leg has none)", + a["action"] == arbitrage.DISCHARGE and a["power"] == b["power"] + and a["reason"] == b["reason"]) + check("T7 ...and the same split over the units, cycle by cycle", + [r["shares"] for r in r1] == [r["shares"] for r in r0]) + + +@guarded("T10") +def _t10(): + r75, c75 = drive((0.75,), n=1) + check("T10 one inverter at 0.75, thr 0: idle (its own leg fails)", + all(r["action"] is None for r in r75)) + r86, c86 = drive((0.86,), n=1) + last = settled(r86) + check("T10 one inverter at 0.86: CHARGE at max_w, and the share is the " + "site target (pass-through)", + last["action"] == arbitrage.CHARGE and last["power"] == -5000.0) + check("T10 ...the plant follows it", last["plant"]["a"] < -4900.0) + + +@guarded("T11") +def _t11(): + now = NIGHT + plan = real_plan(now) + legs = clears(ETA, 0.0) + packs = [types.SimpleNamespace(name=A, soc=50.0, max_w=5000.0), + types.SimpleNamespace(name=B, soc=50.0, max_w=4600.0)] + cw, dw = packshare.trade_power_w(packs, 10.0, 95.0, legs) + + def dec(charge_w, headroom): + return arbitrage.decide( + plan, now, peak_guard_active=False, charge_headroom_w=headroom, + soc=50.0, min_spread_eur_kwh=0.0, uncertainty=NO_WX, + charge_w=charge_w, discharge_w=dw, soc_floor_pct=10.0, + soc_ceiling_pct=95.0) + d = dec(cw, 1200.0) + check("T11 headroom 1200 W: CHARGE -1200 W, the reason says it asked " + "5000 W (not 9600) and 1200 W headroom", + d.power_w == -1200.0 and "asked for 5000 W" in d.reason + and "can afford 1200 W" in d.reason) + check("T11 the buy is sized 5000 W for A alone, so A -1200 and B 0 " + "(through the cycle: the peak limit, not the unit, binds)", + cw == 5000.0) + + +@guarded("T12") +def _t12(): + now = NIGHT + plan = real_plan(now) + legs = clears(ETA, 0.0) + packs = [types.SimpleNamespace(name=A, soc=50.0, max_w=5000.0), + types.SimpleNamespace(name=B, soc=50.0, max_w=4600.0)] + cw, dw = packshare.trade_power_w(packs, 10.0, 95.0, legs) + cw0, _dw0 = packshare.trade_power_w(packs, 10.0, 95.0) + ok = True + for guard, room in ((True, 10000.0), (None, 10000.0), (False, None), + (False, 0.0)): + mk_dec = lambda w: arbitrage.decide( # noqa: E731 + plan, now, peak_guard_active=guard, charge_headroom_w=room, + soc=50.0, min_spread_eur_kwh=0.0, uncertainty=NO_WX, charge_w=w, + discharge_w=dw, soc_floor_pct=10.0, soc_ceiling_pct=95.0) + ok = ok and mk_dec(cw).action is None \ + and mk_dec(cw).reason == mk_dec(cw0).reason + check("T12 guard engaged / not covered / headroom unmeasured / no " + "headroom: refused, same text as today", ok) + # the arbiter's own clamp: P_PEAK lo over the arbitrage SET + d = arbitrage.decide(plan, now, peak_guard_active=False, + charge_headroom_w=10000.0, soc=50.0, + min_spread_eur_kwh=0.0, uncertainty=NO_WX, + charge_w=cw, discharge_w=dw, soc_floor_pct=10.0, + soc_ceiling_pct=95.0) + res = arbiter.site_resolve([arbitrage.claim(d), + Claim.limit("peak", P_PEAK, lo=-1200.0)]) + check("T12 the peak LIMIT still clamps the arbitrage SET (-5000 -> " + "-1200)", d.power_w == -5000.0 and res.target_w == -1200.0) + # the full cycle: an engaged guard refuses the trade with eta set + rows, c = drive(ETA, peak_cap=300) + check("T12 through the cycle: a quarter over its cap (peak guard " + "engaged) is no arbitrage charge, efficiency set or not", + all(r["action"] is None for r in rows) + and "peak" in (c.arb.reason or "")) + rows0, _c0 = drive(NONE2, peak_cap=300) + check("T12 ...and the same refusal as today", c.arb.reason + == _c0.arb.reason and [r["action"] for r in rows] + == [r["action"] for r in rows0]) + + +@guarded("T17") +def _t17(): + rows, c = drive(ETA) + check("T17 B in T1 is 0, never positive while A charges", + all(share(r, B) == 0 and share(r, A) < 0 for r in rows)) + c2 = mk(ETA, modes=("cheap_hours", "cheap_hours"), now=NIGHT) + tick = c2._mode_roles(NIGHT, None) + lo_b = nth(tick.ranges.get(B, (None, None)), 0) + hi_b = nth(tick.ranges.get(B, (None, None)), 1) + check("T17 modes: B rests (role rest, range lo 0): it cannot charge", + tick.roles.get(B) == modetrade.REST and lo_b == 0.0 + and hi_b is not None) + + +# ============================================================================ # +print("3. battery modes, and what Home draws") +# ============================================================================ # + + +@guarded("T2") +def _t2(): + c = mk(ETA, modes=("cheap_hours", "cheap_hours"), now=NIGHT) + tick = c._mode_roles(NIGHT, None) + plan = c.fresh_tariff_plan(NIGHT) + legs = c.charge_legs(plan, NIGHT) + packs = c._mode_packs() + check("T2 the legs: A clears, B does not", legs == {A: True, B: False}) + check("T2 chargers() = [A]", + [p.name for p in modetrade.chargers(packs, 95.0, legs=legs)] == [A]) + check("T2 roles: A charge, B rest; ask -5000 W", + tick.roles.get(A) == modetrade.CHARGE + and tick.roles.get(B) == modetrade.REST + and tick.action == modetrade.CHARGE and tick.ask_w == -5000.0) + e = modetrade.energy(packs, 10.0, 95.0, legs=legs) + check("T2 energy(): charge_kw 5.0 (A alone)", e[1] == 5.0) + c0 = mk(NONE2, modes=("cheap_hours", "cheap_hours"), now=NIGHT) + t0 = c0._mode_roles(NIGHT, None) + check("T2 base: both charge, ask -9600", + t0.roles.get(B) == modetrade.CHARGE and t0.ask_w == -9600.0) + # T13: the size rules with headroom + for room, want in ((1200.0, -1200.0), (400.0, 0.0)): + cr = mk(ETA, modes=("cheap_hours", "cheap_hours"), now=NIGHT, + room=room) + t = cr._mode_roles(NIGHT, None) + check(f"T13 headroom {room:g} W (a start needs 500): size {want:g}", + modetrade.size(t, (-9600.0, 9600.0), room) == want) + c._charge_blocked_q = int(NIGHT.timestamp() // 900) + t = c._mode_roles(NIGHT, None) + check("T13 a charge the guard stopped this period stays off: why " + "'headroom'", t.action is None and t.why == "headroom") + + +@guarded("T52") +def _t52(): + pk = lambda n, eta, **k: modetrade.Pack( # noqa: E731 + n, True, "cheap_hours", False, 5000.0, 50.0, 15.36, eta=eta, **k) + packs = [pk(A, 0.86), pk(B, 0.75, refused=-1, probing=True)] + legs = {A: True, B: False} + ch = [p.name for p in modetrade.chargers(packs, 95.0, probe=True, + legs=legs)] + base = [p.name for p in modetrade.chargers(packs, 95.0, probe=True)] + check("T52 B (leg fails) with its SAFETY-73 probe open is still a " + "charger, as on base", ch == base and B in ch and A in ch) + runs = priceruns.RunPlan( + priceruns.Run(NIGHT - timedelta(hours=1), NIGHT + timedelta(hours=7), + 0.2333), + (priceruns.Run(NIGHT + timedelta(hours=8), NIGHT + timedelta(hours=20), + 0.2801),), None, 0.2801, None, True) + + def tick(lg): + return modetrade.decide( + runs, NIGHT, packs, charge_ok=True, sell_ok=True, trade_why=None, + price_now=0.2333, headroom_w=6000.0, floor_pct=10.0, + ceiling_pct=95.0, house_w=500.0, legs=lg) + t, t0 = tick(legs), tick(None) + check("T52 the probe is PROBE_W exactly and the ask is as on base", + t.probe_w == t0.probe_w and t.probe_w > 0.0 and t.ask_w == t0.ask_w) + + +@guarded("T40") +def _t40(): + c = mk(ETA, modes=("cheap_hours", "cheap_hours"), now=NIGHT) + tick = c._mode_roles(NIGHT, None) + st = homeview.build(c, level="ok", checks=[], now=NIGHT, lang="en") + kinds = lambda i: [r for r in st["plan"]["runs"] # noqa: E731 + if r["kind"] == "grid" and r["battery"] == i] + check("T40 modes: Home draws a charge block for A and none for B (T2)", + len(kinds(0)) > 0 and len(kinds(1)) == 0 + and tick.roles.get(B) != modetrade.CHARGE) + c0 = mk(NONE2, modes=("cheap_hours", "cheap_hours"), now=NIGHT) + c0._mode_roles(NIGHT, None) + st0 = homeview.build(c0, level="ok", checks=[], now=NIGHT, lang="en") + check("T40 base: both batteries have a block", + len([r for r in st0["plan"]["runs"] if r["kind"] == "grid" + and r["battery"] == 1]) > 0) + # modes off: trade_runs reads the verdict the cycle reads + for etas, want in ((ETA, (True, False)), (NONE2, (True, True)), + ((None, 0.75), (True, False)), + ((0.86, None), (True, True))): + thr = 0.02 if etas == (0.86, None) else 0.0 + cm = mk(etas, arb=True, thr=thr, now=NIGHT) + plan = cm.fresh_tariff_plan(NIGHT) + verdict = homeview.trade_verdict(cm, plan, NIGHT)[0] + d0, d1 = homeview.local_day(NIGHT) + runs, _later, _why = homeview.trade_runs(cm, plan, verdict, d0, d1, + NIGHT, False) + got = tuple(any(r["kind"] == "grid" and r["battery"] == i + for r in runs) for i in (0, 1)) + legs = cm.charge_legs(plan, NIGHT) + ctl = (True, True) if legs is None else (legs[A], legs[B]) + if etas == (0.86, None): + ctl = (False, True) # T9b: control's answer, see section 1 + check(f"T40 site trade {etas}: a block where control charges " + f"{ctl}, drawn {got}", got == ctl or ( + etas == (0.86, None) and got == (False, True))) + + +@guarded("N13") +def _n13(): + c = mk(ETA, modes=("cheap_hours", "cheap_hours"), now=NIGHT) + c._mode_roles(NIGHT, None) + plan = c.fresh_tariff_plan(NIGHT) + rp_ = c.mode_runs + roll = homeview.cheaproll.for_today(c, rp_, NIGHT) + check("N13 the rolled cheap run (UX-77) has no stop for B: it does not " + "charge", roll is None or B not in roll.stops) + + +# ============================================================================ # +print("4. the discharge split is the base's (part B is TARIFF-34)") +# ============================================================================ # +EXPECT = {500: (214, 286), 2000: (857, 1143), 5000: (2143, 2857), + 6000: (2571, 3429), 9600: (5000, 4600)} + + +@guarded("T16/T18-T21") +def _t18(): + for etas in (ETA, (0.75, 0.86), (0.80, 0.80), NONE2): + c = mk(etas) + for load, (a, b) in EXPECT.items(): + sh = split(c, load) + check(f"T18-T21 {etas} load {load} W: A {a} / B {b} " + f"(the base's shares)", sh == {A: a, B: b}) + check(f"T16 {etas} load {load} W: sum == target, no share over " + f"max_w, none negative", + sum(sh.values()) == load and sh[A] <= 5000 + and sh[B] <= 4600 and min(sh.values()) >= 0) + + +@guarded("T22") +def _t22(): + for socs, want in (((10.0, 50.0), (0, 2000)), ((10.5, 50.0), (19, 1981))): + for etas in (ETA, NONE2): + c = mk(etas) + sh = split(c, 2000, socs=socs) + check(f"T22 A at {socs[0]:g} %, {etas}: {want}", + (sh[A], sh[B]) == want) + c = mk(ETA) + seq = [split(c, 2000, socs=(s, 50.0)) for s in (10.5, 10.0)] + c0 = mk(NONE2) + seq0 = [split(c0, 2000, socs=(s, 50.0)) for s in (10.5, 10.0)] + check("T22 the tick sequence 10.5 -> 10.0 is the base's", seq == seq0) + + +@guarded("T24-T28") +def _t24(): + for etas in ((0.86, None), (None, 0.75), ETA, (0.75, 0.86), (0.8, 0.8)): + c = mk(etas) + c0 = mk(NONE2) + for load in (500, 2000, 6000): + w = packshare.weights(c.pack_energy, float(load)) + check(f"T24/T26/T27 {etas} {load} W: Controller.pack_weights == " + f"packshare.weights, shares == base", + c.pack_weights(float(load)) == w + and split(c, load) == split(c0, load)) + check(f"T25 {etas} charging -2000 W: A -857 / B -1143 (spare room)", + split(c, -2000) == {A: -857, B: -1143}) + # T28: modes on, the same roles, eta or not + for roles, tgt in (({A: modetrade.GIVE, B: modetrade.GIVE}, 2000.0), + ({A: modetrade.HOLD, B: modetrade.SELL}, 2000.0), + ({A: modetrade.GIVE, B: modetrade.SELL}, 2000.0)): + cs = [] + for etas in (ETA, NONE2): + c = mk(etas, modes=("cheap_hours", "cheap_hours"), now=NIGHT) + c._mode_roles(NIGHT, None) + c.mode_tick = modetrade.Tick({}, dict(roles), None, 0.0, None) + cs.append(c.pack_weights(tgt)) + check(f"T28 modes on {sorted(roles.values())}: the weights are the " + f"base's", cs[0] == cs[1]) + + +@guarded("T29") +def _t29(): + for etas in ((0.86,), (None,)): + c = mk(etas, n=1) + units = (A,) + claims = [Claim.set("loop", P_LOOP, 2000.0, "t"), + Claim.limit("supervised", P_SAFETY, -5000.0, 5000.0, "m", + actuator=A)] + res = arbiter.resolve(claims, units=units, weights=c.pack_weights, + live={A}) + sh = nth(list(res.shares.values()), 0) + check(f"T29 N=1 {etas}: pass-through, 2000.0 as a float", + sh == 2000.0 and isinstance(sh, float) + and c.pack_weights(2000.0) is None) + + +@guarded("T30") +def _t30(): + for etas in ((0.86, 0.75, None), (0.86, 0.75, 0.80)): + c = mk(etas, n=3, soc=(50.0, 50.0, 50.0)) + c0 = mk((None, None, None), n=3, soc=(50.0, 50.0, 50.0)) + for load in (2000, 6000): + check(f"T30 N=3 {etas} {load} W: weights == packshare.weights, " + f"shares == base", + c.pack_weights(float(load)) + == packshare.weights(c.pack_energy, float(load)) + and split(c, load) == split(c0, load)) + + +@guarded("T31") +def _t31(): + c = mk(ETA) + c0 = mk(NONE2) + c.inverters[0].soc = c0.inverters[0].soc = None + check("T31 A's SoC unknown: no opinion (None) as today, shares == base", + c.pack_weights(2000.0) is None and c0.pack_weights(2000.0) is None + and split(c, 2000) == split(c0, 2000)) + d = arbitrage.decide(real_plan(NIGHT), NIGHT, peak_guard_active=False, + charge_headroom_w=6000.0, soc=None, + min_spread_eur_kwh=0.0, uncertainty=NO_WX, + charge_w=5000.0, discharge_w=9600.0, + soc_floor_pct=10.0, soc_ceiling_pct=95.0) + check("T31 arbitrage keeps IDLE_NO_SOC", d.reason == arbitrage.IDLE_NO_SOC) + + +@guarded("T44") +def _t44(): + edge = local(2026, 11, 1, 21, 59, 40) + for cap, tag in ((20000, "no guard"), (300, "guard engaged")): + r1, _c1 = drive(ETA, start=edge, dur=60.0, load=2000.0, peak_cap=cap, + variant="modes_off") + r0, _c0 = drive(NONE2, start=edge, dur=60.0, load=2000.0, + peak_cap=cap, variant="modes_off") + check(f"T44 across the quarter edge, {tag}: shares and commands == " + f"base on every cycle", + [(r["shares"], r["writes"]) for r in r1] + == [(r["shares"], r["writes"]) for r in r0] and len(r1) > 8) + + +@guarded("T45") +def _t45(): + def freeze(c, hass, now, pr): + if hass.t >= 10.0 and not getattr(hass, "_t30", False): + hass._t30 = True + real = hass.number + + async def number(e, invert=False): + return 1234.0 if e == "sensor.batt_a" else await real(e, invert) + hass.number = number + r1, _c1 = drive(ETA, dur=60.0, load=2000.0, variant="modes_off", + each=freeze) + r0, _c0 = drive(NONE2, dur=60.0, load=2000.0, variant="modes_off", + each=freeze) + check("T45 A's reading frozen from 10 s: the same shares and commands " + "as base, cycle by cycle (the freshness rules are untouched)", + [(r["shares"], r["writes"]) for r in r1] + == [(r["shares"], r["writes"]) for r in r0] and len(r1) > 8) + + +@guarded("N7") +def _n7(): + # SAFETY-42's detector, the peak guard, the arbiter and the allocator do + # not know an efficiency exists: the split they see is the base's. + for mod in ("delivery", "peakguard", "arbiter", "allocator", "watchdog", + "packshare"): + src = open(os.path.join(HERE, "app", mod + ".py"), + encoding="utf-8").read() + check(f"N7 app/{mod}.py never reads an efficiency (the detector, the " + f"peak guard and the split are not part of this change)", + "round_trip" not in src and "eta" not in + re.findall(r"\beta\b", src)) + + +# ============================================================================ # +print("5. identity without an efficiency: a trace printed on 831c33c") +# ============================================================================ # + + +@guarded("T8") +def _t8(): + with open(os.path.join(HERE, "scenarios", "tariff30-base-trace.json")) as f: + gold = json.load(f) + now = tariff30_trace.trace() + for k in gold: + check(f"T8/N6 {k}: {gold[k]['n']} decisions, field by field the same " + f"as the base (sha256 {gold[k]['sha256'][:12]})", + now.get(k) == gold[k]) + + +@guarded("N6") +def _n6(): + c = mk(NONE2, modes=("cheap_hours", "cheap_hours"), now=NIGHT) + check("N6 no efficiency: no legs, no hold-out, round_trip_pct None", + c.charge_legs(c.fresh_tariff_plan(NIGHT), NIGHT) is None + and all(i.round_trip_eff is None for i in c.inverters)) + ca = mk(NONE2, arb=True, now=NIGHT) + cl = [] + ca._hold_out_lossy(cl, [], {A: True, B: True}, 9600.0, 9600.0, 10.0, 95.0, + NIGHT) + check("N6 and nothing is filed when every leg clears", cl == []) + + +# ============================================================================ # +print("6. day plan and level curve, per battery") +# ============================================================================ # +FLOOR, CEIL = 10.0, 90.0 +CAP_A, CAP_B = 15.36, 20.48 +PNOW = local(2026, 10, 29, 20, 0) + + +def loc29(day, hour, minute=0): + return local(2026, 10, day, hour, minute) + + +def owner_runs(): + return priceruns.RunPlan( + priceruns.Run(loc29(29, 22), loc29(30, 7), 0.2333), + (priceruns.Run(loc29(29, 7), loc29(29, 22), 0.2801), + priceruns.Run(loc29(30, 7), loc29(30, 22), 0.2801)), + None, 0.2801, None, True) + + +def flat_profile(w): + day = PNOW.astimezone(BILLING_TZ).date() + return dayplan.HouseProfile( + {(day - timedelta(days=k)).isoformat(): {str(h): w for h in range(24)} + for k in (1, 2, 3)}) + + +def pk(name, mode, soc=FLOOR, cap=CAP_A, rating=5000.0, eta=None): + return modetrade.Pack(name, True, mode, False, rating, soc, cap, eta=eta) + + +def shaped_profile(night, day): + d = PNOW.astimezone(BILLING_TZ).date() + sh = {str(h): (night if (h < 7 or h >= 22) else day) for h in range(24)} + return dayplan.HouseProfile( + {(d - timedelta(days=k)).isoformat(): dict(sh) for k in (1, 2, 3)}) + + +def dplan(packs, w=5000.0 / 15.0, kwh=0.0, shape=None, left=0.0, now=PNOW): + """The day plan with a house of `w` W round the clock, no sun by default: + the expensive run 07-22 (15 h) is short `w x 15` Wh. `left` kWh of sun + still to come today, `kwh` tomorrow.""" + d0, _d1 = solarfc._bounds(now) + fc = solarfc.Forecast(solarfc.Day(d0, left), + solarfc.Day(d0 + timedelta(days=1), kwh), now) + prof = flat_profile(w) if shape is None else shape + return dayplan.plan(fc, prof.estimator(), owner_runs(), now, packs, + trust_pct=70, floor_pct=FLOOR, ceiling_pct=CEIL) + + +@guarded("T36-T39") +def _s6(): + b0 = dplan([pk(B, packmode.LEFTOVER_SOLAR, cap=CAP_B, rating=4600.0)]) + b1 = dplan([pk(B, packmode.LEFTOVER_SOLAR, cap=CAP_B, rating=4600.0, + eta=0.75)]) + check("T36 base: B alone, short 5 kWh: target 35.70 %", + b0 is not None and abs(b0.short_kwh - 5.0) < 0.005 + and abs(b0.targets[B] - 35.70) < 0.01) + check("T36 B eta 0.75 (one way 0.8660): target 38.19 %, cover 5.0 kWh", + b1 is not None and abs(b1.targets[B] - 38.19) < 0.01 + and abs(b1.cover_kwh[B] - 5.0) < 0.005) + two0 = dplan([pk(A, packmode.LEFTOVER_SOLAR), + pk(B, packmode.LEFTOVER_SOLAR, cap=CAP_B, rating=4600.0)]) + two1 = dplan([pk(A, packmode.LEFTOVER_SOLAR, eta=0.86), + pk(B, packmode.LEFTOVER_SOLAR, cap=CAP_B, rating=4600.0)]) + check("T37 base: both 24.69 %", abs(two0.targets[A] - 24.69) < 0.01 + and abs(two0.targets[B] - 24.69) < 0.01) + check("T37 mixed (A 0.86, B unset): B's target is unchanged, A's is " + "above base (25.04 %: the short shared by capacity in delivered " + "kWh)", + abs(two1.targets[B] - two0.targets[B]) < 0.005 + and abs(two1.targets[A] - 25.04) < 0.01 + and two1.targets[A] > two0.targets[A]) + check("T37 the covers still add up to the short (5.0 kWh)", + abs(sum(two1.cover_kwh.values()) - two1.short_kwh) < 0.005) + # T38: no efficiency is the base; 0.9025 (sqrt = 0.95) is the unset level + eq = dplan([pk(A, packmode.LEFTOVER_SOLAR, eta=0.9025), + pk(B, packmode.LEFTOVER_SOLAR, cap=CAP_B, rating=4600.0, + eta=0.9025)]) + check("T38 eta 0.9025 (one way 0.95) gives the unset targets", + eq.targets == two0.targets and eq.cover_kwh == two0.cover_kwh) + # T39: every use of EFF is the battery's own + ch0 = dplan([pk(A, packmode.LEFTOVER_SOLAR), + pk(B, packmode.CHEAP_HOURS, cap=CAP_B, rating=4600.0)], + w=1800.0) + ch1 = dplan([pk(A, packmode.LEFTOVER_SOLAR), + pk(B, packmode.CHEAP_HOURS, cap=CAP_B, rating=4600.0, + eta=0.75)], w=1800.0) + ratio = ch1.cheap_kwh / ch0.cheap_kwh + check("T39 Cheap hours B eta 0.75 in `_cheap_give_kwh`: what it gives " + "scales by 0.8660 / 0.95", + ch0.cheap_kwh > 1.0 and ch1.cheap_kwh < ch1.short_kwh + and abs(ratio - math.sqrt(0.75) / 0.95) < 0.001) + big = shaped_profile(200.0, 1800.0) + sf0 = dplan([pk(A, packmode.LEFTOVER_SOLAR), + pk(B, packmode.SOLAR_FIRST, soc=60.0, cap=CAP_B, + rating=4600.0)], shape=big) + sf1 = dplan([pk(A, packmode.LEFTOVER_SOLAR), + pk(B, packmode.SOLAR_FIRST, soc=60.0, cap=CAP_B, + rating=4600.0, eta=0.75)], shape=big) + have = (60.0 - FLOOR) / 100.0 * CAP_B + check("T39 Solar first B eta 0.75 in `_solar_first_give_kwh`: gives " + "`have x its own one-way` (the house's use is the same)", + sf1.solar_first_kwh < sf1.short_kwh - sf1.cheap_kwh + and abs((sf1.solar_first_kwh - sf0.solar_first_kwh) + - have * (math.sqrt(0.75) - 0.95)) < 0.003) + day10 = local(2026, 10, 29, 10, 0) + sun0 = dplan([pk(A, packmode.LEFTOVER_SOLAR)], left=12.0, w=200.0, + now=day10) + sun1 = dplan([pk(A, packmode.LEFTOVER_SOLAR, eta=0.75)], left=12.0, + w=200.0, now=day10) + check("T39 the sun share into A (eta 0.75) is stored at its own " + "0.8660, not 0.95", + sun0.share_kwh[A] > 0.5 + and abs(sun1.share_kwh[A] / sun0.share_kwh[A] + - math.sqrt(0.75) / 0.95) < 0.001) + # a Solar first unit with the sun: the per-unit path keeps its verdict + sfp = dplan([pk(B, packmode.SOLAR_FIRST, cap=CAP_B, rating=4600.0, + eta=0.75), pk(A, packmode.LEFTOVER_SOLAR)], kwh=12.0, + w=1800.0) + check("T39 Solar first with an efficiency still plans (a verdict, " + "targets for the Leftover battery)", + sfp is not None and A in sfp.targets and sfp.verdict in + (dayplan.SUNNY, dayplan.PARTLY, dayplan.DARK)) + + +@guarded("T49") +def _t49(): + t0 = local(2026, 10, 29, 22, 0) + t1 = t0 + timedelta(hours=8) + to = 38.19 + + def lv(eta): + b = daycurve.Batt(B, CAP_B, 4.6, FLOOR, False, True, + grid=((t0, t1, to),), give=(), eta=eta) + out = daycurve.curve([b], t0, t1, lambda a, z: 0.0, + lambda a, z: 0.0, floor_pct=FLOOR, + ceiling_pct=CEIL) + return out[B] + for eta, one in ((None, 0.95), (0.75, math.sqrt(0.75))): + pts = lv(eta) + room = (to - FLOOR) / 100.0 * CAP_B + hit = first(t for t, p in pts if p >= to - 0.01) + want = t0 + timedelta(hours=room / (4.6 * one)) + check(f"T49 curve eta {eta}: B reaches its level {to} % after " + f"room / (rating x {one:.4f})", + present(hit) and abs((hit - want).total_seconds()) < 60.0) + give_b = daycurve.Batt(B, CAP_B, 4.6, 80.0, False, True, grid=(), + give=((t0, t1),), eta=0.75) + give_0 = daycurve.Batt(B, CAP_B, 4.6, 80.0, False, True, grid=(), + give=((t0, t1),)) + use = lambda a, z: 1.0 * (z - a).total_seconds() / 3600.0 # noqa: E731 + one_h = (t0, t0 + timedelta(hours=1)) + d1 = daycurve.curve([give_b], one_h[0], one_h[1], lambda a, z: 0.0, use, + floor_pct=FLOOR, ceiling_pct=CEIL)[B] + d0 = daycurve.curve([give_0], one_h[0], one_h[1], lambda a, z: 0.0, use, + floor_pct=FLOOR, ceiling_pct=CEIL)[B] + drop = lambda pts: pts[0][1] - pts[-1][1] # noqa: E731 + check("T49 giving 1 kWh to the house costs B 1 / 0.8660 of stored " + "energy (not 1 / 0.95)", + abs(drop(d1) - 1.0 / math.sqrt(0.75) / CAP_B * 100.0) < 0.01 + and abs(drop(d0) - 1.0 / 0.95 / CAP_B * 100.0) < 0.01) + # Home's tab hands the curve each battery's own efficiency + seen = [] + real = dayview.curve + + def spy(batts, *a, **k): + seen.extend(batts) + return real(batts, *a, **k) + now = loc29(29, 23, 0) + c = S.make("owner", now) + c.inverters[1].round_trip_eff = 0.75 + st = homeview.build(c, level="ok", checks=[], now=now, lang="en") + dayview.curve = spy + try: + dayview.build(c, st, now, "en") + finally: + dayview.curve = real + etas = {b.name: b.eta for b in seen} + check("T49 dayview: the Batt handed to the curve has B's 0.75 and A's " + "None", etas.get(B) == 0.75 and etas.get(A) is None and len(seen) > 0) + + +# ============================================================================ # +print("7. config: accepted, refused, schema, text, settings") +# ============================================================================ # + + +def entry_problems(val, key="round_trip_eff"): + e = dict(ENTRIES[0]) + e[key] = val + return validate._roster_problems({"inverters": [e, dict(ENTRIES[1])]}) + + +@guarded("T32") +def _t32(): + for val in (0.5, 0.75, 1.0, "0.86", None, ""): + check(f"T32 {val!r} loads with no problem", entry_problems(val) == []) + e = dict(ENTRIES[0], round_trip_eff=0.75) + roster = inverter.build_roster(dict(S.BASE, inverters=[e, ENTRIES[1]]), + S.Store()) + check("T32 the roster carries 0.75 on A and None on B (no inheritance)", + roster[0].round_trip_eff == 0.75 and roster[1].round_trip_eff is None) + blank = inverter.build_roster(dict(S.BASE, inverters=[ + dict(ENTRIES[0], round_trip_eff=""), ENTRIES[1]]), S.Store()) + check("T32 blank == absent", blank[0].round_trip_eff is None) + check("T32 the flat single inverter has none", + inverter.build_roster(dict(S.BASE, inverters=[]), + S.Store())[0].round_trip_eff is None) + + +@guarded("T33") +def _t33(): + for val in (0.49, 1.01, 0, -0.8, "abc", True, float("nan"), float("inf")): + probs = entry_problems(val) + text = nth(probs, 0) + check(f"T33 {val!r} is refused, naming the unit and the key, in one " + f"or two short sentences", + len(probs) == 1 and "inverters[0] (inverter-a)" in text + and "Round-trip efficiency" in text + and "round_trip_eff" in text and text.count(". ") <= 1 + and len(text) < 200) + check("T33 the Dutch label exists (the refusals name it by key too)", + 'Rendement heen en terug' in open(os.path.join( + HERE, "app", "messages.py"), encoding="utf-8").read()) + + +def schema_entry(cfg): + """The `inverters:` entry of config.yaml's `schema:` as {key: spec}.""" + lines = cfg.split("\n") + at = first(i for i, ln in enumerate(lines) if ln.startswith("schema:")) + if not present(at): + return {} + spec, on = {}, False + for ln in lines[at:]: + if re.match(r"^ inverters:\s*$", ln): + on = True + continue + if on: + if re.match(r"^ [a-z_]+:", ln) and not ln.startswith(" "): + break + m = re.match(r"^\s+(?:- )?([a-z_]+): (\S+)\s*$", ln) + if m and not ln.strip().startswith("#"): + spec[m.group(1)] = m.group(2) + return spec + + +def ha_accepts(spec, value): + """The same test HA's Supervisor applies to one option: `float(lo,hi)?`.""" + m = re.match(r"^float\(([-0-9.]+),([-0-9.]+)\)(\?)?$", spec) + if not m: + return None + if value is None: + return bool(m.group(3)) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return False + return float(m.group(1)) <= float(value) <= float(m.group(2)) + + +@guarded("T50") +def _t50(): + cfg = open(os.path.join(HERE, "config.yaml"), encoding="utf-8").read() + spec = schema_entry(cfg) + check("T50 the schema's inverters entry declares round_trip_eff as an " + "optional float(0.5,1)", spec.get("round_trip_eff") == "float(0.5,1)?") + sp = spec.get("round_trip_eff", "") + check("T50 0.75 passes, 0.5 and 1 pass, no key passes", + ha_accepts(sp, 0.75) is True and ha_accepts(sp, 0.5) is True + and ha_accepts(sp, 1) is True and ha_accepts(sp, None) is True) + check("T50 0.49, 1.01 and 'abc' fail", + ha_accepts(sp, 0.49) is False and ha_accepts(sp, 1.01) is False + and ha_accepts(sp, "abc") is False) + check("T50 the other keys of the entry are still declared (name, max_w, " + "bms_soc_floor required)", + spec.get("name") == "str" and spec.get("max_w", "").startswith("int") + and spec.get("bms_soc_floor", "").startswith("int")) + + +@guarded("T34") +def _t34(): + sentence = "If you set round-trip efficiency, lower the cycle cost to " \ + "wear only." + nl_sentence = "Als u het rendement heen en terug instelt, verlaag dan " \ + "de kosten van een batterijcyclus tot alleen slijtage." + en = open(os.path.join(HERE, "translations", "en.yaml"), + encoding="utf-8").read() + nl = open(os.path.join(HERE, "translations", "nl.yaml"), + encoding="utf-8").read() + check("T34 en: the option text and the cycle cost text say it plainly", + en.count(sentence) == 2) + check("T34 nl: the same, in Dutch", nl.count(nl_sentence) == 2) + check("T34 both name the key with a unit-less label", + "round_trip_eff:" in en and "round_trip_eff:" in nl) + # the settings page keeps the key on save, in the list shape + opts = dict(S.BASE) + opts["inverters"] = entries(ETA) + back = uimodel.ui_to_options(json.loads(json.dumps( + uimodel.options_to_ui(opts)))) + got = [e.get("round_trip_eff") for e in back["inverters"]] + check("T34 a round trip through the settings page keeps 0.86 and 0.75", + got == [0.86, 0.75]) + check("T34 ...and keeps nothing where it was not set", + [e.get("round_trip_eff") for e in uimodel.ui_to_options( + json.loads(json.dumps(uimodel.options_to_ui( + dict(S.BASE, inverters=entries(NONE2))))))["inverters"]] + == [None, None]) + + +@guarded("T35") +def _t35(): + opts = dict(S.BASE) + opts.update(inverters=entries(ETA), cycle_cost_threshold_eur=0.04) + c = Controller(opts, S.Hass(), S.Store(), S.Pub(), stop=S.asyncio.Event()) + before = c.o["cycle_cost_threshold_eur"] + c.auto = True + homeview.battery_rows(c, False, True) + saved = uimodel.ui_to_options(json.loads(json.dumps( + uimodel.options_to_ui(opts)))) + check("T35 eta set: the user's cycle cost is never changed (load, " + "status, save)", before == 0.04 + and c.o["cycle_cost_threshold_eur"] == 0.04 + and saved["cycle_cost_threshold_eur"] == 0.04 + and arbitrage.threshold_eur_kwh(c.o) == 0.04) + check("T35 the shipped default is still 0.10", + validate.PRICE_OPTION_DEFAULTS["cycle_cost_threshold_eur"] == 0.10) + + +@guarded("T43") +def _t43(): + r1, c1 = drive(ETA) + r2, c2 = drive(ETA) + keys = lambda c: sorted(c.store.data) # noqa: E731 + _r0, c0 = drive(NONE2) + check("T43 restart: same options, same efficiency, the same decisions", + [(x["action"], x["power"], x["shares"]) for x in r1] + == [(x["action"], x["power"], x["shares"]) for x in r2] + and [i.round_trip_eff for i in c2.inverters] == list(ETA)) + check("T43 no new store key (efficiency is configuration, never kept)", + keys(c1) == keys(c0)) + check("N9 never read from a sensor: the efficiency is the entry's own " + "number, whatever the readings", + [i.round_trip_eff for i in c1.inverters] == list(ETA)) + + +# ============================================================================ # +print("8. the status page") +# ============================================================================ # + + +@guarded("T41") +def _t41(): + c = mk((0.86, 0.75, None), n=3, soc=(50.0, 50.0, 50.0)) + rows = homeview.battery_rows(c, False, True) + by = {r["name"]: r["round_trip_pct"] for r in rows} + check("T41 per unit: 86 %, 75 %, not set (None)", + by == {A: 86.0, B: 75.0, C: None}) + en = json.load(open(os.path.join(HERE, "app", "ui_text", "en.json"), + encoding="utf-8"))["home"]["batteries"] + nl = json.load(open(os.path.join(HERE, "app", "ui_text", "nl.json"), + encoding="utf-8"))["home"]["batteries"] + check("T41 short plain words in en and nl", + en.get("round_trip") == "Round trip" + and en.get("round_trip_unset") == "not set" + and nl.get("round_trip") and nl.get("round_trip_unset")) + js = open(os.path.join(HERE, "app", "static", "app.js"), + encoding="utf-8").read() + check("T41 the page draws the row from those words", + "batteries.round_trip" in js and "round_trip_pct" in js + and "batteries.round_trip_unset" in js) + + +@guarded("T42") +def _t42(): + c = mk(NONE2, flat=True, n=1) + rows = homeview.battery_rows(c, False, True) + check("T42 the flat single inverter: no crash, 'not set' (None)", + len(rows) == 1 and nth(rows, 0)["round_trip_pct"] is None) + + +print() +if fails: + print(f"{len(fails)} FAILED") + for f in fails: + print(" -", f) + sys.exit(1) +print("all passed") diff --git a/goodwe_controller/tools/tariff30_trace.py b/goodwe_controller/tools/tariff30_trace.py new file mode 100644 index 0000000..b3afee8 --- /dev/null +++ b/goodwe_controller/tools/tariff30_trace.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""TARIFF-30 (T8): a decision trace of the grid-charge code with NO efficiency +set, to be compared with one captured on release/1.0 831c33c. + +It uses only the API 831c33c already has, so the same file runs on the base and +on the head: `python3 tools/tariff30_trace.py` prints one JSON object, per group +the number of calls and the sha256 of every outcome in order. The golden copy in +scenarios/tariff30-base-trace.json was printed on 831c33c. The test compares +the head's against it, so with no efficiency set arbitrage.decide(), the +battery-mode charge/sell decision and its energy sizing give the same answers +as before the change, field by field. +""" +import hashlib +import itertools +import json +import os +import sys +from datetime import datetime, timedelta, timezone + +# T30_TREE: another checkout's goodwe_controller/ (how the golden was printed, +# from a 831c33c worktree, with this very file). +HERE = os.environ.get("T30_TREE") or os.path.dirname( + os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.join(HERE, "tools")) + +import ux54_scenarios as S # noqa: E402 +from app import arbitrage, modetrade, priceruns # noqa: E402 +from app.price import Uncertainty # noqa: E402 +from app.static_tariff import static_plan # noqa: E402 +from app.tariff import BILLING_TZ # noqa: E402 + +UTC = timezone.utc +NO_WX = frozenset({Uncertainty.NO_WEATHER}) + + +def _plan(now): + opts = dict(S.BASE) + opts.update(static_profile=json.dumps(S.DN)) + return static_plan(opts, S.day0_of(now), S.day0_of(now) + + timedelta(hours=48), now=now) + + +def _digest(rows): + h = hashlib.sha256() + for r in rows: + h.update(repr(r).encode()) + h.update(b"\n") + return {"n": len(rows), "sha256": h.hexdigest()} + + +def arbitrage_rows(): + """`arbitrage.decide()` over buy, sell and off-peak instants, every SoC, + headroom, guard state, threshold and size the call can be given.""" + rows = [] + for hh, mm in ((22, 5), (23, 30), (3, 0), (7, 0), (10, 0), (21, 59)): + now = datetime(2026, 11, 1, hh, mm, tzinfo=BILLING_TZ).astimezone(UTC) + plan = _plan(now) + for soc, room, guard, thr, cw, dw in itertools.product( + (None, 5.0, 50.0, 96.0), (None, 0.0, 1200.0, 10000.0), + (True, False, None), (0.0, 0.03, 0.10), (0.0, 5000.0, 9600.0), + (0.0, 9600.0)): + d = arbitrage.decide( + plan, now, peak_guard_active=guard, charge_headroom_w=room, + soc=soc, min_spread_eur_kwh=thr, uncertainty=NO_WX, + charge_w=cw, discharge_w=dw, soc_floor_pct=10.0, + soc_ceiling_pct=95.0) + rows.append((hh, mm, soc, room, guard, thr, cw, dw, d.action, + d.power_w, d.reason, d.spread_eur_kwh, + d.required_eur_kwh, d.price_now_eur_kwh)) + return rows + + +def mode_rows(): + """`modetrade.chargers()`, `energy()` and `decide()` over mode, level, + refusal and probe states of two batteries, in a cheap run.""" + rows = [] + now = datetime(2026, 11, 1, 23, 30, tzinfo=BILLING_TZ).astimezone(UTC) + plan = _plan(now) + modes = ("solar_first", "leftover_solar", "cheap_hours") + for ma, mb, soca, socb, refb, probb, ok, room, blk in itertools.product( + modes, modes, (20.0, 99.0, None), (50.0,), (0, -1, 1), + (False, True), (True, False), (None, 300.0, 6000.0), + (False, True)): + packs = [modetrade.Pack("A", True, ma, False, 5000.0, soca, 15.36), + modetrade.Pack("B", True, mb, False, 4600.0, socb, 20.48, + refused=refb, probing=probb)] + e = modetrade.energy(packs, 10.0, 95.0) + rp = priceruns.plan(plan.read.points, now, required_eur_kwh=0.0, + charge_kwh=e[0], charge_kw=e[1], sell_kwh=e[2], + sell_kw=e[3]) + ch = [p.name for p in modetrade.chargers(packs, 95.0, probe=True)] + t = modetrade.decide( + rp, now, packs, charge_ok=ok, sell_ok=ok, trade_why="not_worth", + price_now=0.2333, headroom_w=room, floor_pct=10.0, + ceiling_pct=95.0, house_w=500.0, blocked=blk) + rows.append((ma, mb, soca, socb, refb, probb, ok, room, blk, e, ch, + sorted(t.ranges.items()), sorted(t.roles.items()), + t.action, t.ask_w, t.why, t.probe_w, + modetrade.size(t, (-9600.0, 9600.0), room))) + return rows + + +def trace(): + return {"arbitrage_decide": _digest(arbitrage_rows()), + "modetrade": _digest(mode_rows())} + + +if __name__ == "__main__": + print(json.dumps(trace(), indent=1, sort_keys=True)) diff --git a/goodwe_controller/translations/en.yaml b/goodwe_controller/translations/en.yaml index c96d837..f0d3b11 100644 --- a/goodwe_controller/translations/en.yaml +++ b/goodwe_controller/translations/en.yaml @@ -79,6 +79,9 @@ configuration: capacity_kwh: name: "Usable battery capacity (kWh) (optional)" description: "This battery's usable capacity from its datasheet. Fill it in on every inverter or on none. The add-on then shares the work by the energy each battery has left." + round_trip_eff: + name: "Round-trip efficiency (0.5 to 1) (optional)" + description: "Share of the energy that comes back out of this battery after it went in, for example 0.86. Leave it empty if you do not know it. If you set round-trip efficiency, lower the cycle cost to wear only." estop_fitted: name: "Hardware · RS485 emergency stop is fitted" description: "Switch this on if the emergency stop is installed. It only changes a warning on the status page." @@ -219,7 +222,7 @@ configuration: description: "Charge in the cheapest hour and draw the battery down in the dearest, when the spread covers the cost. Turning it off does not turn the price feed off." cycle_cost_threshold_eur: name: "Tariff · Battery cycle cost (EUR/kWh)" - description: "What one full battery cycle costs per kWh. A smaller price spread is not traded, and the value is a product choice, not a measured one." + description: "What one full battery cycle costs per kWh. A smaller price spread is not traded, and the value is a product choice, not a measured one. If you set round-trip efficiency, lower the cycle cost to wear only." arbitrage_soc_floor: name: "Tariff · Trading keeps at least (%)" description: "Price trading will not draw the battery below this level. It is separate from the maintenance settings." diff --git a/goodwe_controller/translations/nl.yaml b/goodwe_controller/translations/nl.yaml index bdaf93f..14b0885 100644 --- a/goodwe_controller/translations/nl.yaml +++ b/goodwe_controller/translations/nl.yaml @@ -60,6 +60,9 @@ configuration: capacity_kwh: name: "Bruikbare capaciteit (kWh) (optioneel)" description: "De bruikbare capaciteit van deze batterij, van het datablad. Vul ze bij elke omvormer in of bij geen. Dan verdeelt de add-on het werk volgens de energie in elke batterij." + round_trip_eff: + name: "Rendement heen en terug (0,5 tot 1) (optioneel)" + description: "Het deel van de energie dat uit deze batterij terugkomt nadat het erin ging, bijvoorbeeld 0,86. Laat het leeg als u het niet weet. Als u het rendement heen en terug instelt, verlaag dan de kosten van een batterijcyclus tot alleen slijtage." estop_fitted: name: "Hardware · RS485-noodstop is geplaatst" description: "Zet dit aan als de noodstop geïnstalleerd is. Het verandert alleen een waarschuwing op de statuspagina." @@ -200,7 +203,7 @@ configuration: description: "Laden in het goedkoopste uur en de batterij laten leveren in het duurste, als het verschil de kosten dekt. Dit uitzetten zet de prijsfeed niet uit." cycle_cost_threshold_eur: name: "Tarief · Kosten van een batterijcyclus (EUR/kWh)" - description: "Wat één volledige batterijcyclus per kWh kost. Een kleiner prijsverschil wordt niet verhandeld. De waarde is een productkeuze, geen meting." + description: "Wat één volledige batterijcyclus per kWh kost. Een kleiner prijsverschil wordt niet verhandeld. De waarde is een productkeuze, geen meting. Als u het rendement heen en terug instelt, verlaag dan de kosten van een batterijcyclus tot alleen slijtage." arbitrage_soc_floor: name: "Tarief · Handel houdt minstens (%)" description: "Prijshandel laat de batterij niet onder dit niveau zakken. Dit staat los van de onderhoudsinstellingen."