In Solar, when the 15-minute period heads over the aim and the batteries would have to give more, the car is lowered first: floor((car - excess) / (230 x phases)) A, 0 under 6 A. At once without real headroom (saturated, floor-limited, excess beyond what the batteries can add, no battery figure, cover off, last 120 s), else after at most 15 s. One cut per episode from its start, deeper only on a growing excess; restart with the start power under the aim for the start time; none after a 2nd cut in the period. Grading (formal C2): a Solar car Solar cannot cut is graded, banked and left in the guard as in Off. A Solar car is never banked. Grey note and Why "Solar lowered the car for the peak." Manual and Off unchanged. Tests: test_ev21.py, test_ev21_paths.py, test_ev21_same.py; T49 in tools/ev20_day.py; T50 in test_ev20_fuzz.py; test_ev20_guard section 8 moved from "as Manual" to "as Off" where Solar cannot cut (T51). Co-Authored-By: Claude <noreply@anthropic.com>
1287 lines
64 KiB
Python
1287 lines
64 KiB
Python
"""EV-04 and EV-20: the Controller's side of the car's Manual and Solar modes.
|
|
|
|
The writes themselves are `carmode.ManualWriter`'s and `carmode.SolarWriter`'s;
|
|
this mixin owns the state (mode, current, phases, where spare sun goes first:
|
|
runtime state in the store, like OPT-11's modes), the actions, the background
|
|
step that never holds up a control cycle, and what the car means for the peak
|
|
guard's ALARM PATH. DECISIONS/EV-04-manual-mode.md, DECISIONS/EV-20-solar-mode.md
|
|
(Solar's inputs, its 0 A before the inverters at shutdown, today's solar kWh;
|
|
the guard treats a Solar car exactly as a Manual car).
|
|
"""
|
|
|
|
import asyncio
|
|
import copy
|
|
import dataclasses
|
|
import logging
|
|
from datetime import timezone
|
|
|
|
from . import carmode, chargers, messages, packshare, peakguard
|
|
from .tariff import QUARTER_S, next_quarter
|
|
|
|
_LOG = logging.getLogger("goodwe")
|
|
|
|
CAR_PEAK_KEY = "car_peak_q" # {quarter start iso: the car's average W}
|
|
CAR_PEAK_MIN_W = 50.0 # a quarter the car hardly touched is not kept
|
|
CAR_PEAK_KEEP = 3200 # about a month of quarters
|
|
OVER_HOLD_S = peakguard.ALARM_HOLD_S
|
|
# EV-11: the card, the row and Why stay on this long after the car stops being
|
|
# the cause: longer than the gaps seen on the rig (150 to 250 s at 50 s
|
|
# sampling) and shorter than a quarter, or until the session really ends.
|
|
OVER_OFF_HOLD_S = 180.0
|
|
# EV-15: the longest our own phase change can take (0 A wait, settle, three
|
|
# tries of a write at 5 s apart and up to 10 s each, the select's own wait);
|
|
# the grace for the alarm never outlasts it, and after the current is set
|
|
# again it lasts at most one corroboration window.
|
|
OWN_PAUSE_MAX_S = (carmode.ZERO_WAIT_S + carmode.SETTLE_S
|
|
+ carmode.MAX_TRIES * 15.0 + 10.0)
|
|
OWN_PAUSE_TAIL_S = chargers.CORR_WINDOW_S
|
|
# EV-19: the meter's house side (held - car) moved no more than this since the
|
|
# last cycle: it has not shown a battery rise the reading already shows.
|
|
RISE_STILL_W = 50.0
|
|
# EV-20: today's kWh from the sun, {day, kwh}; and a shutdown whose 0 A the
|
|
# charger did not take (D3), so the next start can take its notice down.
|
|
CAR_SUN_KEY = "car_sun"
|
|
CAR_RELEASE_KEY = "car_release_failed"
|
|
# C1 (SPIKE-05): an own 0 A of Solar's is out and not read back yet, kept with
|
|
# the mode, so a start in Off after a power cut still writes it.
|
|
CAR_EXIT_KEY = "car_exit_0a_pending"
|
|
# EV-20 (D3): at shutdown in Solar the charger's 0 A waits at most this long,
|
|
# then the inverters are released whatever the charger did.
|
|
RELEASE_WAIT_S = 15.0
|
|
# EV-21: Solar's car is cut first for the quarter peak. The cut waits at most
|
|
# CUT_WAIT_S, and only while the batteries can still raise their output; with
|
|
# CUT_NEAR_END_S or less of the period left it comes at once (waiting 15 s
|
|
# with R s left raises what must come off by R / (R - 15), at most 8/7 at
|
|
# 120 s). After CUT_MAX_Q cuts in one period, no restart until the next.
|
|
# DECISIONS/EV-21-car-cut-first.md.
|
|
CUT_WAIT_S = 15.0
|
|
CUT_NEAR_END_S = 120.0
|
|
CUT_MAX_Q = 2
|
|
# A lowering Solar sent counts as its own this long before its read-back:
|
|
# one cycle beside the write (the alarm still comes within 2 s of Off's).
|
|
CUT_SENT_S = 2.0
|
|
|
|
|
|
class CarMixin:
|
|
# ------------------------------------------------------------------ state
|
|
def car_init(self, opts, store) -> None:
|
|
"""Mode, current and phases from the store; `ev_mode_start` says what a
|
|
restart does with the mode. A site with no charger keeps defaults and
|
|
writes nothing."""
|
|
data = getattr(store, "data", None) or {}
|
|
# C1: the mode before the stop, and an exit 0 A still pending then.
|
|
stored = data.get(carmode.KEY_MODE)
|
|
self._car_stored_mode = stored if stored in carmode.MODES \
|
|
else carmode.OFF
|
|
self._car_exit_pending = bool(data.get(CAR_EXIT_KEY))
|
|
self._car_start_seen = False
|
|
self._car_start_warned = False
|
|
self.car_mode = carmode.start_mode(opts, data.get(carmode.KEY_MODE))
|
|
if carmode.start_mode(opts, carmode.MANUAL) == carmode.OFF \
|
|
and data.get(carmode.KEY_MODE) not in (None, carmode.OFF):
|
|
store.set(carmode.KEY_MODE, carmode.OFF)
|
|
clamp = carmode.clamp_for(opts, None)
|
|
a = carmode.value_a(data.get(carmode.KEY_A, carmode.DEFAULT_A), clamp)
|
|
self.car_a = carmode.DEFAULT_A if a is None else a
|
|
n = data.get(carmode.KEY_PHASES, carmode.DEFAULT_PHASES)
|
|
ok = carmode.allowed_phases(opts)
|
|
self.car_n = n if n in ok else ok[0]
|
|
self.car_rev = 0
|
|
self.car_writer = carmode.ManualWriter()
|
|
self.car_solar = carmode.SolarWriter() # EV-20
|
|
self.car_solar.on_owed = self._car_owed
|
|
if self.car_mode == carmode.OFF and self._car_exit_pending:
|
|
self.car_solar.owe_start() # C1
|
|
first = data.get(carmode.KEY_FIRST)
|
|
self.car_first = first if first in carmode.FIRSTS \
|
|
else carmode.DEFAULT_FIRST
|
|
self._car_late_s = None # EV-20: the cycle's late verdict
|
|
self._car_late_mono = None # ... and the time it was read (EV-51)
|
|
self._car_sun_now = None # ... and Solar's inputs of that cycle
|
|
sun = data.get(CAR_SUN_KEY)
|
|
self.car_sun = {"day": None, "kwh": 0.0}
|
|
if isinstance(sun, dict):
|
|
try:
|
|
self.car_sun = {"day": sun.get("day"),
|
|
"kwh": max(0.0, float(sun.get("kwh") or 0.0))}
|
|
except (TypeError, ValueError):
|
|
pass
|
|
self._car_sun_mono = None
|
|
self._car_sun_saved = round(self.car_sun["kwh"], 2)
|
|
self._car_release_failed = bool(data.get(CAR_RELEASE_KEY))
|
|
self._car_task = None
|
|
self._car_step_failed = False
|
|
self.car_explains = False # the car alone explains the excess
|
|
self.car_over = False # ... held: the card and row say so
|
|
self._car_over_since = None
|
|
self._car_over_gone = None
|
|
self._car_why_rec = None # EV-16: [shown over, since, episode]
|
|
self._car_over_ep = 0 # EV-16: bumped when car_over ends
|
|
self._car_batt_prev = self._car_batt_prev2 = None
|
|
self._car_hx_prev = None # EV-19: last cycle's (held, car W)
|
|
self._car_need_real = self._car_need_excl = False # EV-10 latches
|
|
self._car_need_house = self._car_over_now = False # EV-18 latches
|
|
self._car_latch_block = None
|
|
self._car_contra_block = None # EV-18: the quarter it was contradicted
|
|
self._car_over_notified = None # the session a notice was raised for
|
|
self._car_session = 0
|
|
self._car_prev_state = None
|
|
self._carq = {"key": None, "ws": 0.0, "ws_p": 0.0, "mono": None}
|
|
self._peak_proj_real = None
|
|
saved = data.get(CAR_PEAK_KEY)
|
|
self.car_peak_q = dict(saved) if isinstance(saved, dict) else {}
|
|
self._cut = self._cut_fresh(None) # EV-21: in memory only
|
|
self._car_cut_notified = None # EV-21: the session noted
|
|
self._car_can = False # EV-21: can-cut as graded
|
|
|
|
# ------------------------------------------------- EV-21: the peak cut
|
|
@staticmethod
|
|
def _cut_fresh(key) -> dict:
|
|
"""EV-21: no cut state, for period `key`. `since`: the episode began
|
|
(the cut first due); `car0`: the car's W then; `ex`: the largest
|
|
excess seen in it; `cap`: the cut's current, None while none stands;
|
|
`cuts`: cuts in this period; `under`: the projection with the start
|
|
power has been under the aim since."""
|
|
return {"key": key, "since": None, "car0": None, "ex": 0.0,
|
|
"cap": None, "wait": None, "cuts": 0, "under": None,
|
|
"base": None, "at": None}
|
|
|
|
def _car_cut_ramp_w(self, mono):
|
|
"""EV-21: for grading only, the car's real power while it comes down
|
|
after a cut the charger took: fresh, not stuck, never above the
|
|
current before the cut, at most `CORR_WINDOW_S` after the cut. (Its
|
|
trusted figure is capped by the new, lower read-back meanwhile.) None
|
|
otherwise: a car that does not follow is graded as in Off after
|
|
that window (T45)."""
|
|
st = self._cut
|
|
if st["cap"] is None or st["at"] is None or st["base"] is None \
|
|
or not 0.0 <= mono - st["at"] <= chargers.CORR_WINDOW_S \
|
|
or not self.car_solar_can_cut() or self.car.stuck(mono):
|
|
return None
|
|
raw = self.car.car_w(mono)
|
|
if raw is None:
|
|
return None
|
|
n = self._car_cut_n()
|
|
return min(float(raw), float(st["base"]) * chargers.CEILING_V * n)
|
|
|
|
def car_solar_can_cut(self) -> bool:
|
|
"""EV-21 (Q5): can Solar really cut the car now? Solar writes (no
|
|
shadow, Stop, safety stop or shutdown), the charger is read fresh with
|
|
no fault and no stuck reading, no other writer (no hold, no
|
|
difference) and the read-back shows the current Solar sent. A cut
|
|
written but not read back is not a cut."""
|
|
if not self.car_solar_mode() or not self.car_writing():
|
|
return False
|
|
w = self.car_solar
|
|
mono = self.car_now()
|
|
r = self.car.reading
|
|
if r is None or not r.available or r.error \
|
|
or r.state in ("E", "F") or not self.car.fresh(mono) \
|
|
or self.car.stuck(mono):
|
|
return False
|
|
if w.hold or w.mismatch_since is not None or w.fault is not None \
|
|
or w.gave_up or w.sent_a is None:
|
|
return False
|
|
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
|
if cur is None:
|
|
return False
|
|
if abs(cur - w.sent_a) <= carmode.TOL_A:
|
|
return True
|
|
# A lowering of Solar's own on its way: the cycle beside the write
|
|
# reads the charger before it answers. For CUT_SENT_S at most, and
|
|
# never once the charger refused it.
|
|
at = getattr(w, "sent_at", None)
|
|
return bool(w.sent_a < cur - carmode.TOL_A and at is not None
|
|
and 0.0 <= mono - at <= CUT_SENT_S
|
|
and (w.fail_at is None or w.fail_at < at))
|
|
|
|
def car_cut_standing(self) -> bool:
|
|
"""EV-21: a peak cut lowered the car and the charger shows it."""
|
|
st = getattr(self, "_cut", None)
|
|
w = getattr(self, "car_solar", None)
|
|
if not st or st["cap"] is None or st["base"] is None or w is None \
|
|
or st["cap"] >= float(st["base"]) - carmode.TOL_A:
|
|
return False
|
|
return bool(self.car_solar_can_cut() and w.sent_a is not None
|
|
and w.sent_a <= st["cap"] + carmode.TOL_A)
|
|
|
|
async def check_car_cut(self) -> None:
|
|
"""EV-21 (OQ5): one grey note per charging session once a cut is
|
|
taken: "Solar lowered the car for the peak.\""""
|
|
if not self.car_cut_standing() \
|
|
or self._car_cut_notified == self._car_session:
|
|
return
|
|
self._car_cut_notified = self._car_session
|
|
_LOG.info("Solar lowered the car for the peak: CAR_CUT.")
|
|
await self.hass.call("persistent_notification", "create",
|
|
messages.car_cut().data())
|
|
|
|
def _car_cut_meter_fresh(self) -> bool:
|
|
"""EV-21 (N9): the meter's own age allows sizing a cut: within
|
|
`stale_input_s`, or on `ha_signed` (whose age counts from the last
|
|
change) within `meter_max_age_s`."""
|
|
if not self.p1_enabled:
|
|
return False
|
|
age = self.p1.age_s()
|
|
if age is None:
|
|
return False
|
|
if str(self.o.get("meter_source") or "") == "ha_signed":
|
|
bound = float(self.o.get("meter_max_age_s", 30) or 30)
|
|
else:
|
|
bound = float(self.o.get("stale_input_s", 15))
|
|
return age <= bound
|
|
|
|
def _car_cut_headroom(self, guard):
|
|
"""EV-21 (Q2-Q4): the watts the batteries can still ADD, or None when
|
|
a battery figure is missing (then they count as adding nothing). A
|
|
battery adds nothing at or under its cut-out level or its peak
|
|
reserve (the guard's `held`), while it refuses to give, under a
|
|
safety stop, or switched off in battery modes; the guard's `able_w`
|
|
caps the rest. 0 while the guard is saturated or floor-limited."""
|
|
if self.site_batt_w is None \
|
|
or any(inv.batt is None for inv in self.inverters):
|
|
return None
|
|
if guard is None or guard.saturated or guard.floor_limited:
|
|
return 0.0
|
|
n = len(self.inverters)
|
|
if self.circ_wd.tripped or (n > 1 and self.site_sign_wd.tripped):
|
|
return 0.0
|
|
held = set(getattr(guard, "held", ()) or ())
|
|
top = given = stop = 0.0
|
|
for inv in self.inverters:
|
|
refused = inv.refused if n > 1 else self.batt_refused
|
|
if inv.sign_wd.tripped \
|
|
or (self.modes_on and not self.pack_mode(inv).use):
|
|
continue
|
|
if (refused or 0) > 0 or inv.name in held or inv.soc is None \
|
|
or inv.bms_soc_floor is None \
|
|
or float(inv.soc) <= float(inv.bms_soc_floor):
|
|
# Gives nothing more; a charge it takes can still stop.
|
|
stop += max(0.0, -float(inv.batt))
|
|
continue
|
|
top += float(inv.rating_w())
|
|
given += float(inv.batt)
|
|
if guard.able_w is not None:
|
|
top = min(top, float(guard.able_w))
|
|
return max(0.0, top - given) + stop
|
|
|
|
def _car_cut_n(self):
|
|
"""The phases the car draws on: 1 for a one-phase car."""
|
|
r = self.car.reading
|
|
if self.car_solar.single:
|
|
return 1
|
|
n = getattr(r, "phases_allowed", None)
|
|
return n if n in (1, 3) else self.car_solar.plan.n
|
|
|
|
def _car_cut_tick(self, real_proj, guard, target_w, mono) -> None:
|
|
"""EV-21: decide the peak cut for the writer step that follows this
|
|
cycle (`car_kick`), from the projection WITH the car. Due: Solar, a
|
|
fresh projection heading over the aim (`excess_w` > 0) and a car that
|
|
draws. Taken at once without real headroom (saturated, floor-limited,
|
|
the excess beyond what the batteries can add, no battery figure, the
|
|
cover off, the period's last 120 s), else after CUT_WAIT_S. One cut
|
|
per episode, sized from its start: `car0` less the largest excess
|
|
so far, never re-subtracted from the lowered car. While it is due or
|
|
stands, the writer's plan goes no higher (the cap). It is lifted when
|
|
the projection with the start power has been under the aim for the
|
|
start rule's time (not after CUT_MAX_Q cuts in the period), and at
|
|
the period's end."""
|
|
w = self.car_solar
|
|
if not self.car_solar_mode():
|
|
self._cut = self._cut_fresh(None)
|
|
w.cut_a = None
|
|
return
|
|
key = None if real_proj is None else real_proj.block_start
|
|
st = self._cut
|
|
if key is not None and key != st["key"]:
|
|
st = self._cut = self._cut_fresh(key) # no state over the edge
|
|
blind = guard is not None and guard.blind is not None
|
|
if key is None or target_w is None or blind \
|
|
or not self._car_cut_meter_fresh():
|
|
# N9: nothing sized from a stale projection; what stands stays.
|
|
w.cut_a = st["cap"] if st["cap"] is not None else st["wait"]
|
|
return
|
|
ex = peakguard.excess_w(real_proj, target_w)
|
|
left = QUARTER_S - float(real_proj.elapsed_s)
|
|
r = self.car.reading
|
|
cur = None if r is None or not r.available else (
|
|
r.allowed_a if r.allowed_a is not None else r.setpoint_a)
|
|
car_w = self.car.car_w_trusted(mono)
|
|
drawing = (car_w is not None and car_w > 0.0) or (
|
|
car_w is None and r is not None and r.available
|
|
and r.charging is True)
|
|
running = w.plan.a > 0.0 or (cur is not None and cur > carmode.TOL_A)
|
|
# C12: Solar's own phase change holds the car at 0 A on its way to a
|
|
# current: a cut due then ends it at that 0 A (no closing current).
|
|
seq_on = w.seq is not None and w.plan.a > 0.0
|
|
# The batteries would have to give more than now (the guard's
|
|
# `wanted_w`, on the projection WITH the car): a charge that only
|
|
# has to slow down is the loop's, not a cut. Unknown: they add
|
|
# nothing (Q4).
|
|
batt = self.site_batt_w
|
|
wants = batt is None or float(batt) + ex > 0.0
|
|
due = ex > 0.0 and wants and running and (drawing or seq_on)
|
|
n = self._car_cut_n()
|
|
if st["cap"] is not None:
|
|
# A cut stands: deeper only if the excess grows (OQ7); the
|
|
# restart rule lifts it.
|
|
if due and ex > st["ex"]:
|
|
st["ex"] = ex
|
|
a = carmode.cut_amps(st["car0"], ex, n, st["base"])
|
|
if a is not None and a < st["cap"]:
|
|
st["cap"] = a
|
|
start_w = chargers.MIN_A * carmode.VOLTS * n # OQ4
|
|
now_w = 0.0 if car_w is None else float(car_w)
|
|
plus = float(real_proj.projected_w) \
|
|
+ max(0.0, start_w - now_w) * max(0.0, left) / QUARTER_S
|
|
if plus < float(target_w):
|
|
if st["under"] is None:
|
|
st["under"] = mono
|
|
else:
|
|
st["under"] = None
|
|
start_s = 60.0 * carmode.solar_option(self.o, "ev_start_min")
|
|
if st["under"] is not None and mono - st["under"] >= start_s \
|
|
and st["cuts"] < CUT_MAX_Q:
|
|
cuts = st["cuts"]
|
|
st = self._cut = self._cut_fresh(key)
|
|
st["cuts"] = cuts
|
|
w.cut_a = st["cap"]
|
|
return
|
|
if not due:
|
|
st["since"], st["wait"] = None, None # the batteries caught it
|
|
w.cut_a = None
|
|
return
|
|
if st["since"] is None:
|
|
st["since"], st["car0"], st["ex"] = mono, car_w, ex
|
|
st["base"] = w.plan.a if w.plan.a > 0.0 else cur
|
|
st["ex"] = max(st["ex"], ex)
|
|
room = self._car_cut_headroom(guard)
|
|
now_ = (room is None or room <= 0.0 or ex > room
|
|
or not self.car_cover or left <= CUT_NEAR_END_S)
|
|
if now_ or mono - st["since"] >= CUT_WAIT_S:
|
|
a = carmode.cut_amps(st["car0"], st["ex"], n, st["base"])
|
|
st["cap"] = 0.0 if a is None else a
|
|
st["cuts"] += 1
|
|
st["wait"], st["at"] = None, mono
|
|
w.cut_a = st["cap"]
|
|
return
|
|
# C4: due and waiting: no raise meanwhile.
|
|
st["wait"] = w.plan.a if st["wait"] is None \
|
|
else min(st["wait"], w.plan.a)
|
|
w.cut_a = st["wait"]
|
|
|
|
@property
|
|
def car_cover(self) -> bool:
|
|
"""Decision 1: do the batteries help cover the car down to the peak
|
|
reserve? Default yes."""
|
|
v = self.o.get("ev_batt_cover")
|
|
return bool(chargers.EV_OPTION_DEFAULTS["ev_batt_cover"]
|
|
if v is None else v)
|
|
|
|
def car_manual(self) -> bool:
|
|
return (self.charger.configured()
|
|
and self.car_mode == carmode.MANUAL)
|
|
|
|
def _car_owed(self, pending) -> None:
|
|
"""C1: keep "an own 0 A is out, not read back" with the mode."""
|
|
pending = bool(pending)
|
|
if pending != self._car_exit_pending:
|
|
self._car_exit_pending = pending
|
|
self.store.set(CAR_EXIT_KEY, pending)
|
|
|
|
async def check_car_start(self) -> None:
|
|
"""C1: the first reading after a start that will not write (shadow,
|
|
control stopped) shows a current the add-on set before the stop
|
|
(Manual or Solar then): one warning, taken down once it is 0 A."""
|
|
r = self.car.reading
|
|
if r is None or not r.available or not self.charger.configured():
|
|
return
|
|
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
|
if not self._car_start_seen:
|
|
self._car_start_seen = True
|
|
if self._car_stored_mode in (carmode.MANUAL, carmode.SOLAR) \
|
|
and not self.car_writing() and cur is not None \
|
|
and cur > carmode.TOL_A:
|
|
self._car_start_warned = True
|
|
_LOG.warning("The charger still has a current from before "
|
|
"the restart, and the add-on does not write "
|
|
"now: CHARGER_START_CURRENT.")
|
|
_LOG.debug("The charger shows %.0f A at the start.", cur)
|
|
await self.hass.call("persistent_notification", "create",
|
|
messages.car_start_current(
|
|
f"{cur:.0f}").data())
|
|
elif self._car_start_warned and cur is not None \
|
|
and cur <= carmode.TOL_A:
|
|
self._car_start_warned = False
|
|
await self.hass.call("persistent_notification", "dismiss",
|
|
messages.car_start_current_gone().data())
|
|
|
|
def car_solar_mode(self) -> bool:
|
|
"""EV-20: a charger is set up and the mode is Solar."""
|
|
ch = getattr(self, "charger", None)
|
|
return bool(ch is not None and ch.configured()
|
|
and getattr(self, "car_mode", None) == carmode.SOLAR)
|
|
|
|
def car_controlled(self) -> bool:
|
|
"""EV-20: Manual or Solar. The peak guard's alarm path treats a Solar
|
|
car exactly as a Manual car (Expected 8)."""
|
|
return self.car_manual() or self.car_solar_mode()
|
|
|
|
def car_solar_engaged(self) -> bool:
|
|
"""EV-20: Solar is the mode, or its way-out 0 A is still owed."""
|
|
w = getattr(self, "car_solar", None)
|
|
return bool(self.charger.configured() and w is not None
|
|
and (self.car_mode == carmode.SOLAR or w.engaged))
|
|
|
|
def car_clamp(self):
|
|
return carmode.clamp_for(self.o, self.car.reading)
|
|
|
|
def car_writing(self) -> bool:
|
|
"""May the add-on write to the charger now? Control runs, shadow mode is
|
|
off, no safety stop is latched and the add-on is not shutting down. Shadow mode gates charger
|
|
writes exactly as it gates inverter writes."""
|
|
latched = (any(i.sign_wd.tripped for i in self.inverters)
|
|
or self.site_sign_wd.tripped or self.circ_wd.tripped)
|
|
return bool(self.auto and not self.shadow and not latched
|
|
and not getattr(self, "stopping", False))
|
|
|
|
# ---------------------------------------------------------------- actions
|
|
def _car_action(self, what, value, now) -> dict:
|
|
"""The mode, the current or the phases, from the page or from Home
|
|
Assistant. Store state, applied by the next step with no restart."""
|
|
if not self.charger.configured():
|
|
return {"error": messages.car_refused("off")}
|
|
if what == "car_mode":
|
|
if value not in carmode.MODES:
|
|
return {"error": messages.car_refused("value")}
|
|
if value == carmode.SOLAR and self.car_mode != carmode.SOLAR:
|
|
# A Manual phase change in the middle is not restored: Solar
|
|
# starts from the 0 A it stands at.
|
|
self.car_writer.seq = None
|
|
self.car_mode = value
|
|
self.store.set(carmode.KEY_MODE, value)
|
|
elif what == "car_sun_first":
|
|
# EV-20: arithmetic only, from the next cycle; not a change of the
|
|
# writers (the 30 s rule and another writer's hold stand).
|
|
if value not in carmode.FIRSTS:
|
|
return {"error": messages.car_refused("value")}
|
|
self.car_first = value
|
|
self.store.set(carmode.KEY_FIRST, value)
|
|
self.log_event(f"car sun first set to {value} by operator",
|
|
hint=messages.hint("car_sun_first"))
|
|
return {"mode": self.car_mode, "current": self.car_a,
|
|
"phases": self.car_n, "sun_first": self.car_first}
|
|
elif what == "car_current":
|
|
clamp = self.car_clamp()
|
|
if isinstance(value, bool):
|
|
return {"error": messages.car_refused("value")}
|
|
a = carmode.value_a(value, clamp)
|
|
try:
|
|
inside = a is not None and abs(float(value) - a) < 0.5
|
|
except (TypeError, ValueError):
|
|
inside = False
|
|
if not inside:
|
|
return {"error": messages.car_refused("value")}
|
|
self.car_a = a
|
|
self.store.set(carmode.KEY_A, a)
|
|
else:
|
|
if value not in (1, 3) or isinstance(value, bool):
|
|
return {"error": messages.car_refused("value")}
|
|
if value not in carmode.allowed_phases(self.o):
|
|
return {"error": messages.car_refused("phases")}
|
|
self.car_n = value
|
|
self.store.set(carmode.KEY_PHASES, value)
|
|
self.car_rev += 1
|
|
self.car_writer.user_changed()
|
|
if what == "car_mode" and value == carmode.SOLAR:
|
|
# EV-20: only pressing Solar lifts Solar's other-writer hold.
|
|
# Leaving Solar, or Manual's current or phases, is not the user
|
|
# handing the charger back to Solar (N10).
|
|
self.car_solar.user_changed()
|
|
self.log_event(f"car {what[4:]} set to {value} by operator",
|
|
hint=messages.hint(what))
|
|
return {"mode": self.car_mode, "current": self.car_a,
|
|
"phases": self.car_n}
|
|
|
|
def car_command_values(self) -> dict:
|
|
"""The MQTT state of the three car entities."""
|
|
return {"car_mode": carmode.MODE_LABELS[self.car_mode],
|
|
"car_current": round(self.car_a),
|
|
"car_phases": str(self.car_n),
|
|
"car_sun_first": carmode.FIRST_LABELS[self.car_first]}
|
|
|
|
# ------------------------------------------------------------- the writer
|
|
def car_kick(self) -> None:
|
|
"""Start one writer step in the background, unless one is running. A
|
|
write waits up to 10 s for the charger's read-back, and a control cycle
|
|
never waits for the charger."""
|
|
if not self.charger.configured():
|
|
return
|
|
t = self._car_task
|
|
if t is not None and not t.done():
|
|
return
|
|
# EV-20: Solar's inputs as this cycle read them. The step runs beside
|
|
# the next read, which must not hand it a new meter reading with an
|
|
# old car reading (or the other way round).
|
|
self._car_sun_now = (self.car_sun_inputs(self.car_now())
|
|
if self.car_solar_mode() else None)
|
|
self._car_task = asyncio.ensure_future(self._car_run())
|
|
|
|
def _car_hold_kick(self, now=None) -> None:
|
|
"""EV-20: a cycle that holds for a missing or late reading returns
|
|
before `car_kick()`. Solar still steps (it holds, counts its dwell,
|
|
and a way out still writes its 0 A); Manual is left as it was.
|
|
EV-21 (Q4): the peak cut is still decided, on the meter's own
|
|
projection: without a battery figure the batteries add nothing."""
|
|
if now is not None and self.car_solar_mode():
|
|
self._car_cut_hold(now)
|
|
if self.car_solar_engaged():
|
|
self.car_kick()
|
|
|
|
def _car_cut_hold(self, now) -> None:
|
|
"""EV-21: the cut in a cycle that returns before the guard: the
|
|
meter's projection (no gap filling, which has its own state; a
|
|
blind one sizes nothing), no guard, so no headroom."""
|
|
if not self.p1_enabled:
|
|
self._car_cut_tick(None, None, None, self.car_now())
|
|
return
|
|
proj = self.peak.project(self.p1.averager, now, roll=self.modes_on)
|
|
hold_s = self.p1.averager.max_hold_s
|
|
if proj is not None and len(self.inverters) > 1:
|
|
proj = next_quarter(proj, hold_s)
|
|
if proj is not None and peakguard.blindness(
|
|
proj, hold_s, False) is not None:
|
|
proj = None
|
|
reading = self.peak.peak(now)
|
|
target = peakguard.quarter_target_w(
|
|
float(self.o.get("peak_cap_w", 3500)), self.peak_margin_w,
|
|
reading)
|
|
self._car_cut_tick(proj, None, target, self.car_now())
|
|
|
|
async def car_settle(self) -> None:
|
|
"""Wait for the writer step in flight (the checks use it)."""
|
|
t = self._car_task
|
|
if t is not None:
|
|
await asyncio.gather(t, return_exceptions=True)
|
|
|
|
async def _car_run(self) -> None:
|
|
try:
|
|
await self.car_step()
|
|
except asyncio.CancelledError:
|
|
raise
|
|
except Exception: # noqa: BLE001
|
|
# Once at WARNING-and-above, then quietly: a step that fails
|
|
# fails every second.
|
|
if not self._car_step_failed:
|
|
self._car_step_failed = True
|
|
_LOG.exception("The car charger step failed")
|
|
else:
|
|
_LOG.debug("The car charger step failed again", exc_info=True)
|
|
else:
|
|
self._car_step_failed = False
|
|
|
|
async def car_shutdown(self) -> None:
|
|
"""The add-on stops: no new write. Manual: a phase change in the middle
|
|
is undone by giving the car its current back; the current stands
|
|
otherwise (Manual's fail state). Solar (EV-20, D3): 0 A, waited for at
|
|
most `RELEASE_WAIT_S` (`Controller.shutdown` calls this BEFORE the
|
|
inverters go to 0 W in Solar)."""
|
|
t, self._car_task = getattr(self, "_car_task", None), None
|
|
if t is not None and not t.done():
|
|
t.cancel()
|
|
await asyncio.gather(t, return_exceptions=True)
|
|
if self.car_solar_engaged():
|
|
try:
|
|
done = await asyncio.wait_for(self.car_solar.release(
|
|
self.charger, self.car.reading, self.car_now(), self.car),
|
|
RELEASE_WAIT_S)
|
|
except Exception: # noqa: BLE001
|
|
done = False
|
|
if done is False:
|
|
self._car_release_failed = True
|
|
self.store.set(CAR_RELEASE_KEY, True)
|
|
_LOG.warning("The charger did not take 0 A before the add-on "
|
|
"stopped, so the car may still be charging: "
|
|
"CHARGER_RELEASE.")
|
|
return
|
|
if not self.charger.configured() \
|
|
or getattr(self, "car_writer", None) is None \
|
|
or self.car_writer.seq is None:
|
|
return
|
|
try:
|
|
await asyncio.wait_for(self.car_writer.abandon(
|
|
self.charger, self.car_now(), self.car, self.car_clamp()),
|
|
15.0)
|
|
except Exception: # noqa: BLE001
|
|
_LOG.warning("The car could not be given its current back "
|
|
"before the add-on stopped: CHARGER_RESTORE.")
|
|
|
|
async def car_release_notice(self) -> None:
|
|
"""D3: after the inverters are released, one warning notice that the
|
|
car may still be charging. Bounded: the add-on is stopping."""
|
|
if not self._car_release_failed or not self.car_solar_engaged():
|
|
return
|
|
try:
|
|
await asyncio.wait_for(self.hass.call(
|
|
"persistent_notification", "create",
|
|
messages.car_release_failed().data()), 3.0)
|
|
except Exception: # noqa: BLE001
|
|
_LOG.debug("The car notice could not be raised at shutdown",
|
|
exc_info=True)
|
|
|
|
async def check_car_release(self) -> None:
|
|
"""D3: the notice of a shutdown whose 0 A was not taken comes down once
|
|
Solar has confirmed its start-up 0 A."""
|
|
w = self.car_solar
|
|
if self._car_release_failed and w.engaged and not w.fresh_start \
|
|
and w.sent_a == 0.0 and w.taken:
|
|
self._car_release_failed = False
|
|
self.store.set(CAR_RELEASE_KEY, False)
|
|
await self.hass.call("persistent_notification", "dismiss",
|
|
messages.car_release_gone().data())
|
|
|
|
async def car_step(self) -> None:
|
|
"""One step of Manual or Solar. Reads nothing from the world (the
|
|
cycle's read did) and writes only through `carmode`'s writers."""
|
|
if not self.charger.configured():
|
|
return
|
|
held = bool(self.car.held)
|
|
now = self.car_now()
|
|
sun = None
|
|
if self.car_mode == carmode.SOLAR:
|
|
sun = self.car_sun_own(getattr(self, "_car_sun_now", None)
|
|
or self.car_sun_inputs(now), now)
|
|
w0 = self.car_solar
|
|
a0, n_log = w0.plan.a, len(w0.log)
|
|
await self._car_step_run(held, now, sun)
|
|
if sun is not None and _LOG.isEnabledFor(logging.DEBUG):
|
|
self._car_step_debug(held, now, sun, a0, n_log)
|
|
|
|
def _car_step_debug(self, held, now, sun, a0, n_log) -> None:
|
|
"""EV-51: one DEBUG line per Solar writer step: the time, the meter's
|
|
age at the step, what was decided and what was written. The decision
|
|
is one word: steady, start, raise, lower, pause, hold (the
|
|
late-readings hold), wait-unknown (the spare is unknown and the pause
|
|
timer counts) or wait-held (a held charger read). Nothing at info and
|
|
above; no secrets in it."""
|
|
w = self.car_solar
|
|
a1 = w.plan.a
|
|
if a0 > 0.0 and a1 <= 0.0:
|
|
what = "pause"
|
|
elif held:
|
|
what = "wait-held"
|
|
elif sun.hold:
|
|
what = "hold"
|
|
elif a0 <= 0.0 and a1 > 0.0:
|
|
what = "start"
|
|
elif a1 > a0 + carmode.TOL_A:
|
|
what = "raise"
|
|
elif a1 < a0 - carmode.TOL_A:
|
|
what = "lower"
|
|
elif sun.target_w is None:
|
|
what = "wait-unknown"
|
|
else:
|
|
what = "steady"
|
|
sent = []
|
|
for kind, v, _t, ok in w.log[n_log:]:
|
|
if kind == "current":
|
|
sent.append(f"sent {v:g} A" + (" confirmed" if ok else ""))
|
|
else:
|
|
sent.append(f"phases {v}" + (" confirmed" if ok else ""))
|
|
age = sun.age_s
|
|
_LOG.debug("Solar step: t=%.1f age=%s decision=%s write=%s", now,
|
|
"none" if age is None else f"{age:.1f}", what,
|
|
"; ".join(sent) or "none")
|
|
|
|
def car_sun_own(self, snap, now):
|
|
"""EV-51 (PM): every decision on the meter's AGE is taken at the writer
|
|
step's own age (now minus the meter's last reading), not the age the
|
|
cycle saw one step earlier: the write block while the meter is silent
|
|
(N8), the unknown/pause timing (held reads too) and the late-readings
|
|
hold with its stale rule. The meter's VALUES (spare, target) stay the
|
|
cycle's only while the step's own age says the meter is fresh; once it
|
|
is past `meter_max_age_s` they are unknown (C23). Arrival sources'
|
|
`car_spare_w` keeps the cycle's age."""
|
|
own = copy.copy(snap)
|
|
own.silent = self._car_meter_silent()
|
|
own.unknown_s = self._car_meter_over_s()
|
|
own.age_s = self.p1.age_s() if self.p1_enabled else None
|
|
own.meter_back = snap.unknown_s > 0.0 and own.unknown_s <= 0.0
|
|
stale = float(self.o.get("stale_input_s", 15))
|
|
late = self._car_late_s # the verdict stands: it has aged since
|
|
if late is not None and self._car_late_mono is not None:
|
|
late += max(0.0, now - self._car_late_mono)
|
|
own.hold = late is not None and late < stale
|
|
if own.silent or (late is not None and late >= stale):
|
|
# The stale rule on the step's own age / own late (C23): a spare
|
|
# read from data the own age calls old starts or raises nothing.
|
|
own.spare_w = own.target_w = None
|
|
return own
|
|
|
|
async def _car_step_run(self, held, now, sun) -> None:
|
|
if held:
|
|
# EV-20 rig round 2 (PM): the charger missed a read for less than
|
|
# `stale_input_s`; the last trusted figure stands and nothing is
|
|
# decided or written from the gap. No writer steps and no plan
|
|
# count (start, phase change, hold) moves (review r3, PM design);
|
|
# a decision due now runs on the next real reading. The one
|
|
# exception: Solar's pause by the meter's age (C18).
|
|
if sun is not None and self.car_writing():
|
|
await self.car_solar.held_pause(
|
|
self.charger, self.car.reading, sun=sun, now=now,
|
|
tracker=self.car)
|
|
return
|
|
if self.car_mode != carmode.SOLAR and not held:
|
|
await self.car_writer.step(
|
|
self.charger, self.car.reading, mode=self.car_mode,
|
|
want_a=self.car_a, want_phases=self.car_n, rev=self.car_rev,
|
|
clamp=self.car_clamp(), now=now, tracker=self.car,
|
|
writing=self.car_writing(), shadow=bool(self.shadow),
|
|
status=self.car.status(now, True), clock=self.car_now)
|
|
w = self.car_solar
|
|
if self.car_mode == carmode.SOLAR or w.engaged:
|
|
# C6: one write clock: Manual's latest non-zero write counts.
|
|
w.other_at = self.car_writer.nonzero_at
|
|
await w.step(
|
|
self.charger, self.car.reading, mode=self.car_mode,
|
|
sun=sun,
|
|
clamp=self.car_clamp(), now=now, tracker=self.car,
|
|
writing=self.car_writing(), status=self.car.status(now, True),
|
|
clock=self.car_now)
|
|
|
|
# ------------------------------------------------------- EV-20: Solar
|
|
def car_may_charge(self, inv) -> bool:
|
|
"""May this battery take the sun? On (battery modes), not refusing a
|
|
charge, not under a sign stop, its level read and under full."""
|
|
if self.modes_on and not self.pack_mode(inv).use:
|
|
return False
|
|
refused = inv.refused if len(self.inverters) > 1 \
|
|
else self.batt_refused
|
|
if (refused or 0) < 0 or inv.sign_wd.tripped:
|
|
return False
|
|
return inv.soc is not None and float(inv.soc) < packshare.FULL_PCT
|
|
|
|
def car_room_w(self) -> float:
|
|
"""Batteries first: the RATINGS of the batteries that may charge."""
|
|
return float(sum(inv.rating_w() for inv in self.inverters
|
|
if self.car_may_charge(inv)))
|
|
|
|
def car_spare_w(self, mono):
|
|
"""The signed spare sun now, or None when it cannot be measured: a
|
|
missing meter or battery figure, a meter older than `stale_input_s`,
|
|
readings late past it, or a charging car whose figure is stale, stuck
|
|
or not corroborated. A paused or idle car with a fresh reading counts
|
|
as 0 W."""
|
|
if not self.inputs_ok:
|
|
return None
|
|
stale = float(self.o.get("stale_input_s", 15))
|
|
late = self._car_late_s
|
|
if late is not None and late >= stale:
|
|
return None
|
|
if self.p1_enabled:
|
|
# The meter's own bound (`meter_max_age_s`) may be longer than
|
|
# `stale_input_s`; a car write never comes from an older reading.
|
|
# Rig round 1: only where the age measures ARRIVAL. On `ha_signed`
|
|
# it measures the time since the value CHANGED (p1.py, Home
|
|
# Assistant emits changes only), so a healthy meter under a flat
|
|
# load would read as stale and pause the car; there the source's
|
|
# own `meter_max_age_s` (the cycle's `inputs_ok`) is the bound.
|
|
age = self.p1.age_s()
|
|
src = str(self.o.get("meter_source") or "")
|
|
bound = None if src == "ha_signed" else stale
|
|
if age is None or (bound is not None and age > bound):
|
|
return None
|
|
r = self.car.reading
|
|
if r is None or not r.available or not self.car.fresh(mono):
|
|
return None
|
|
car = self.car.car_w_trusted(mono) if r.charging is True else 0.0
|
|
return carmode.spare_w(car, self.site_batt_w, self.grid)
|
|
|
|
def car_sun_inputs(self, mono) -> "carmode.SunInputs":
|
|
o = self.o
|
|
spare = self.car_spare_w(mono)
|
|
late = self._car_late_s
|
|
hold = late is not None and late < float(o.get("stale_input_s", 15))
|
|
room = self.car_room_w()
|
|
margin = carmode.solar_option(o, "ev_margin_w")
|
|
ph = str(o.get("ev_phases", chargers.EV_OPTION_DEFAULTS["ev_phases"]))
|
|
return carmode.SunInputs(
|
|
target_w=carmode.car_target_w(spare, room, margin, self.car_first),
|
|
hold=hold, auto=ph not in ("1", "3"),
|
|
start_s=60.0 * carmode.solar_option(o, "ev_start_min"),
|
|
pause_s=60.0 * carmode.solar_option(o, "ev_pause_min"),
|
|
spare_w=spare, room_w=room, margin_w=margin, first=self.car_first,
|
|
unknown_s=self._car_meter_over_s() if spare is None else 0.0,
|
|
silent=self._car_meter_silent())
|
|
|
|
def _car_meter_silent(self) -> bool:
|
|
"""SPIKE-06 C17 (N8): is the meter known silent (its age past
|
|
`meter_max_age_s`)? Then Solar writes no non-zero current."""
|
|
if not self.p1_enabled:
|
|
return False
|
|
age = self.p1.age_s()
|
|
bound = float(self.o.get("meter_max_age_s", 30) or 30)
|
|
return age is not None and age > bound
|
|
|
|
def _car_meter_over_s(self) -> float:
|
|
"""EV-20 rig round 2 (PM): on `ha_signed`, how far the meter's age is
|
|
past `meter_max_age_s`, so Solar's pause comes at that age +
|
|
`ev_pause_min` (checked every cycle), not a cycle or two later."""
|
|
if not self.p1_enabled \
|
|
or str(self.o.get("meter_source") or "") != "ha_signed":
|
|
return 0.0
|
|
age = self.p1.age_s()
|
|
bound = float(self.o.get("meter_max_age_s", 30) or 30)
|
|
return 0.0 if age is None else max(0.0, age - bound)
|
|
|
|
def _car_sun_tick(self, mono) -> None:
|
|
"""Solar kWh: per cycle, in Solar only, the car's power up to the sun
|
|
it may take (`spare - room` Batteries first, `spare` Car first). The
|
|
hold's battery or grid share and Manual do not count."""
|
|
if not self.car_solar_mode():
|
|
self._car_sun_mono = None
|
|
return
|
|
day = self.car.day
|
|
if day is not None and self.car_sun.get("day") != day:
|
|
self.car_sun = {"day": day, "kwh": 0.0}
|
|
self.store.set(CAR_SUN_KEY, dict(self.car_sun))
|
|
self._car_sun_saved = 0.0
|
|
last, self._car_sun_mono = self._car_sun_mono, mono
|
|
if last is None:
|
|
return
|
|
dt = min(max(mono - last, 0.0), 5.0)
|
|
p = self.car.car_w(mono)
|
|
spare = self.car_spare_w(mono)
|
|
if p is None or spare is None or dt <= 0.0:
|
|
return
|
|
sun = spare - (self.car_room_w() if self.car_first == carmode.FIRST_BATT
|
|
else 0.0)
|
|
share = min(float(p), max(0.0, sun))
|
|
if share <= 0.0:
|
|
return
|
|
self.car_sun["kwh"] += share * dt / 3.6e6
|
|
if round(self.car_sun["kwh"], 2) != self._car_sun_saved:
|
|
self._car_sun_saved = round(self.car_sun["kwh"], 2)
|
|
self.store.set(CAR_SUN_KEY, {"day": self.car_sun["day"],
|
|
"kwh": round(self.car_sun["kwh"], 4)})
|
|
|
|
def car_sun_kwh(self):
|
|
"""Today's kWh from the sun, never above today's kWh; None without a
|
|
reading of today."""
|
|
if self.car.today_kwh is None:
|
|
return None
|
|
if self.car_sun.get("day") != self.car.day:
|
|
return 0.0
|
|
return max(0.0, min(float(self.car_sun["kwh"]),
|
|
float(self.car.today_kwh)))
|
|
|
|
def car_amps_now(self):
|
|
"""D1: the current Solar charges the car at now: the read-back, else
|
|
what Solar sent. Never Manual's stored value."""
|
|
r = self.car.reading
|
|
if r is not None and r.available:
|
|
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
|
if cur is not None:
|
|
return float(cur)
|
|
w = self.car_solar
|
|
return float(w.sent_a or 0.0)
|
|
|
|
# ------------------------------------------- the car and the peak guard
|
|
def car_alarm_w(self):
|
|
"""The car's power for the guard's alarm path: Manual, and Solar only
|
|
while it can cut the car (EV-21, Q5: otherwise as Off), fresh, not
|
|
stuck (`CarTracker.car_w_trusted`), and never above what the
|
|
read-back allows. None otherwise, and then the normal alarms stand."""
|
|
if not self.car_controlled():
|
|
return None
|
|
if self.car_solar_mode() and not self.car_solar_can_cut():
|
|
return None
|
|
return self.car.car_w_trusted(self.car_now())
|
|
|
|
def _car_own_pause(self, mono) -> bool:
|
|
"""EV-15: is the car held at 0 A by the add-on's OWN phase change? From
|
|
the moment its 0 A write is SENT (the cycle runs beside the write)
|
|
until the current is set again, then at most one corroboration window.
|
|
No when it was aborted (Off, Stop, shadow, unplug, another writer), a
|
|
write was refused, or it ran past its own maximum.
|
|
|
|
EV-20: Solar's own phase change the same way, and Solar's own 0 A
|
|
pause from the moment it is sent, at most `OWN_PAUSE_MAX_S`, and only
|
|
while the read-back still shows that 0 A (a car another writer starts
|
|
is never Solar's pause)."""
|
|
solar = self.car_solar_mode()
|
|
wr = getattr(self, "car_solar" if solar else "car_writer", None)
|
|
own_zero = solar and wr is not None and self._car_solar_zero(wr)
|
|
if wr is None or (wr.seq is None and wr.phase_done_at is None
|
|
and wr.zero_sent_at is None and not own_zero) \
|
|
or wr.hold:
|
|
return False
|
|
r = self.car.reading
|
|
if not (self.car_controlled() and self.car_writing()
|
|
and r is not None and r.available and r.state != "A"):
|
|
return False
|
|
q = wr.seq
|
|
if q is None and wr.zero_sent_at is not None: # sent, not yet back
|
|
return 0.0 <= mono - wr.zero_sent_at <= OWN_PAUSE_MAX_S
|
|
if q is not None:
|
|
return not q.get("failed") and 0.0 <= mono - q["t0"] \
|
|
<= OWN_PAUSE_MAX_S
|
|
if own_zero and 0.0 <= mono - wr.zero_at <= OWN_PAUSE_MAX_S:
|
|
return True
|
|
return wr.phase_done_at is not None \
|
|
and 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S
|
|
|
|
def _car_solar_zero(self, wr) -> bool:
|
|
"""EV-20: is Solar's own latest write a 0 A the charger took, and does
|
|
the read-back still show it? (Another writer's current ends it.)"""
|
|
if wr.zero_at is None or wr.sent_a != 0.0 or not wr.taken:
|
|
return False
|
|
r = self.car.reading
|
|
if r is None or not r.available:
|
|
return False
|
|
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
|
return cur is not None and cur <= carmode.TOL_A
|
|
|
|
def _car_contradicted(self, mono) -> bool:
|
|
"""EV-18 (owner 2026-11-19): did the charger's energy meter answer
|
|
and fall short of a fresh, not stuck figure of a charging car
|
|
(`CarTracker.contradicted`)? Then that figure stays untrusted for the
|
|
alarm to the quarter's end (`car_cycle`). An unknown energy reading
|
|
contradicts nothing."""
|
|
r = getattr(self.car, "reading", None)
|
|
if r is None or not r.available or r.charging is not True \
|
|
or not self.car_controlled():
|
|
return False
|
|
return (self.car.car_w(mono) is not None and not self.car.stuck(mono)
|
|
and self.car.contradicted(mono))
|
|
|
|
def _car_idle(self, mono) -> bool:
|
|
"""EV-18: is the car known to draw nothing? A fresh reading that says
|
|
it is not charging (mode3 A or B) at under `CAR_PEAK_MIN_W`. Not an
|
|
unknown figure: the house's own need is graded in such a cycle."""
|
|
r = getattr(self.car, "reading", None)
|
|
if r is None or not r.available or r.charging is not False:
|
|
return False
|
|
p = self.car.car_w(mono)
|
|
return p is not None and p < CAR_PEAK_MIN_W
|
|
|
|
def _car_quarter(self, proj, w, mono, wg=None) -> None:
|
|
"""The car's energy in the open quarter, for the average the guard's
|
|
house leaves out and for the peak line. `wg` (EV-15) is the figure for
|
|
grading during our own pause; its energy is kept apart (`ws_p`) so the
|
|
guard's input is unchanged."""
|
|
q = self._carq
|
|
key = None if proj is None else proj.block_start
|
|
last = q["mono"]
|
|
if key != q["key"]:
|
|
self._car_bank(q)
|
|
q["key"], q["ws"], q["ws_p"], q["ws_b"] = key, 0.0, 0.0, 0.0
|
|
if key is not None and last is not None:
|
|
dt = min(max(mono - last, 0.0), 5.0)
|
|
if w is not None:
|
|
q["ws"] += float(w) * dt
|
|
if not self.car_solar_mode():
|
|
# EV-21: a Solar car is cut first, so a period is never
|
|
# banked as its own (N4); one it cannot cut is as Off.
|
|
q["ws_b"] = q.get("ws_b", 0.0) + float(w) * dt
|
|
elif wg is not None:
|
|
q["ws_p"] = q.get("ws_p", 0.0) + float(wg) * dt
|
|
q["mono"] = mono
|
|
|
|
def _car_bank(self, q) -> None:
|
|
"""A closed quarter in which the car drew its share goes on the list."""
|
|
key = q["key"]
|
|
if key is None:
|
|
return
|
|
avg = q.get("ws_b", q["ws"]) / QUARTER_S
|
|
if avg < CAR_PEAK_MIN_W:
|
|
return
|
|
self.car_peak_q[key.astimezone(timezone.utc).isoformat()] = round(avg)
|
|
if len(self.car_peak_q) > CAR_PEAK_KEEP:
|
|
for k in sorted(self.car_peak_q)[:-CAR_PEAK_KEEP]:
|
|
del self.car_peak_q[k]
|
|
self.store.set(CAR_PEAK_KEY, dict(self.car_peak_q))
|
|
|
|
def car_avg_w(self, proj, w, graded=False) -> float:
|
|
"""The car's average over the whole open quarter: what it drew so far
|
|
and `w` for the rest. `graded` (EV-15) adds what it drew during our
|
|
own pause."""
|
|
if proj is None or w is None:
|
|
return 0.0
|
|
left = max(0.0, QUARTER_S - float(proj.elapsed_s))
|
|
so_far = self._carq["ws"] if self._carq["key"] == proj.block_start \
|
|
else 0.0
|
|
if graded and self._carq["key"] == proj.block_start:
|
|
so_far += self._carq.get("ws_p", 0.0)
|
|
return (so_far + float(w) * left) / QUARTER_S
|
|
|
|
def car_exclude(self, proj, w):
|
|
"""Decision 1 off: the projection the guard sees without the car
|
|
(`house - car_w`). Unchanged without a fresh car reading."""
|
|
if proj is None or w is None or proj.block_start is None:
|
|
return proj
|
|
avg = self.car_avg_w(proj, w)
|
|
return dataclasses.replace(
|
|
proj, projected_w=max(0.0, float(proj.projected_w) - avg),
|
|
held_w=max(0.0, float(proj.held_w) - float(w)))
|
|
|
|
def car_exclude_alarm(self, proj, w):
|
|
"""EV-10b: the period as it would be without the car, for grading the
|
|
alarm. The house alone, the batteries giving only what the house
|
|
would draw from them: the car's share of their power is not charged to
|
|
the house. The rest of the period keeps its sign (`held - car`, an
|
|
export while the batteries give more than the house uses), so
|
|
`misses_aim` adds the batteries back to exactly the house. What is
|
|
already done is clipped at 0 Ws: no export is credited for power only
|
|
the car asked for. Unchanged without a fresh car reading."""
|
|
if proj is None or w is None or proj.block_start is None:
|
|
return proj
|
|
avg = self.car_avg_w(proj, w, graded=True)
|
|
left = max(0.0, QUARTER_S - float(proj.elapsed_s))
|
|
held = float(proj.held_w)
|
|
done_ws = QUARTER_S * float(proj.projected_w) - max(held, 0.0) * left
|
|
car_ws = avg * QUARTER_S - float(w) * left # the car so far
|
|
held_x = held - float(w)
|
|
return dataclasses.replace(
|
|
proj, held_w=held_x,
|
|
projected_w=(max(0.0, done_ws - car_ws)
|
|
+ max(held_x, 0.0) * left) / QUARTER_S)
|
|
|
|
def car_cycle(self, real_proj, guard, target_w, now_utc) -> None:
|
|
"""After the guard has decided: does the car alone explain the excess?
|
|
`real_proj` is the projection WITH the car, whatever the guard saw."""
|
|
mono = self.car_now()
|
|
self._car_cut_tick(real_proj, guard, target_w, mono) # EV-21
|
|
self._car_sun_tick(mono) # EV-20: today's solar kWh
|
|
solar = self.car_solar_mode()
|
|
can = solar and self.car_solar_can_cut()
|
|
self._car_can = can # what grading saw (checks)
|
|
w = self.car_alarm_w()
|
|
# EV-15: the figure for grading only. Our own phase change holds the
|
|
# car at 0 A and the energy meter cannot corroborate it then, so for
|
|
# that bounded time its fresh, not stuck figure stands in. EV-21: in
|
|
# Solar only while it can cut the car.
|
|
own = (w is None or float(w) <= 0.0) and (can or not solar) \
|
|
and self._car_own_pause(mono)
|
|
wg = w
|
|
if w is None and own:
|
|
wg = self.car.car_w_paused(mono)
|
|
ramp = self._car_cut_ramp_w(mono) if can else None
|
|
if ramp is not None and ramp > float(wg or 0.0):
|
|
wg, own = ramp, True # EV-21: the cut's own ramp-down
|
|
self._car_quarter(real_proj, w, mono, wg)
|
|
self._car_session_tick(mono)
|
|
# EV-18 (owner 2026-11-19): a figure the meter contradicted grades no
|
|
# alarm again in that quarter, not even as our own pause's stand-in.
|
|
# The alarm decision only: the car's energy count, the guard's input
|
|
# (`car_exclude`) and, with the cover off, the car-over row keep it.
|
|
key = None if real_proj is None else real_proj.block_start
|
|
if key is not None and not own and self._car_contradicted(mono):
|
|
self._car_contra_block = key
|
|
contra = key is not None and key == self._car_contra_block
|
|
explains = over = False
|
|
if real_proj is not None and target_w is not None \
|
|
and real_proj.block_start is not None:
|
|
# EV-10: every cycle, so the latches do not depend on the option.
|
|
# EV-18: a car known to draw nothing counts as 0 W for the latches
|
|
# (the house's own need); it and a 0 W figure explain nothing,
|
|
# but in our own pause (EV-15).
|
|
idle = wg is None and self._car_idle(mono)
|
|
graded = self._car_explains_alarm(
|
|
real_proj, guard, target_w,
|
|
None if contra else 0.0 if idle else wg)
|
|
if contra or idle or (w is not None and float(w) <= 0.0
|
|
and not own):
|
|
graded = False
|
|
if solar:
|
|
# EV-21 (Q5, OQ5, OQ8): graded out only while Solar can cut
|
|
# the car, and then no car-over row: the cut works. Else as
|
|
# Off; the row and notice say the car sets the peak.
|
|
explains = graded and can
|
|
wd = None if can else self.car.car_w_trusted(mono)
|
|
if wd is not None:
|
|
ex = float(real_proj.projected_w) - float(target_w)
|
|
over = ex > 0.0 and self.car_avg_w(real_proj, wd) >= ex
|
|
elif self.car_cover:
|
|
explains = over = graded
|
|
elif w is not None:
|
|
ex = float(real_proj.projected_w) - float(target_w)
|
|
over = ex > 0.0 and self.car_avg_w(real_proj, w) >= ex
|
|
self.car_explains = explains
|
|
# EV-11: on once the condition has stood for OVER_HOLD_S, a short gap
|
|
# in it not starting that count again; off only after it has been gone
|
|
# for OVER_OFF_HOLD_S. `car_explains` (the alarm decision) has no hold.
|
|
if over:
|
|
self._car_over_gone = None
|
|
if self._car_over_since is None:
|
|
self._car_over_since = mono
|
|
if mono - self._car_over_since >= OVER_HOLD_S:
|
|
self.car_over = True
|
|
else:
|
|
if self._car_over_gone is None:
|
|
self._car_over_gone = mono
|
|
if mono - self._car_over_gone >= OVER_OFF_HOLD_S:
|
|
self.car_over, self._car_over_since = False, None
|
|
self._car_over_ep += 1 # EV-16: an episode ends
|
|
self._car_over_gone = None
|
|
self._car_why_tick(guard, mono)
|
|
|
|
def _car_why_tick(self, guard, mono) -> None:
|
|
"""EV-16, display only: control writes `_car_why_rec`, never reads it.
|
|
The Car Why text ("are at" / "give all they can") is held: it changes
|
|
only when the other state has stood for `OVER_OFF_HOLD_S` of THIS
|
|
cycle's clock (so reads of /status do not matter). State: floor-limited
|
|
with the SoC read; a guard of None, or unread SoC, never counts as
|
|
floor. Cleared when car_over is off or the cover is off."""
|
|
if not (self.car_over and self.car_cover):
|
|
self._car_why_rec = None
|
|
return
|
|
cand = None if guard is None else bool(
|
|
getattr(guard, "floor_limited", False)
|
|
and getattr(guard, "soc", None) is not None)
|
|
ep = self._car_over_ep
|
|
r = self._car_why_rec
|
|
if r is None or r[2] != ep:
|
|
self._car_why_rec = [bool(cand), None, ep]
|
|
elif cand is None or cand == r[0]:
|
|
r[1] = None
|
|
else:
|
|
if r[1] is None:
|
|
r[1] = mono
|
|
if mono - r[1] >= OVER_OFF_HOLD_S:
|
|
self._car_why_rec = [cand, None, ep]
|
|
|
|
def _car_explains_alarm(self, real_proj, guard, target_w, w) -> bool:
|
|
"""EV-10: is the alarm's own test true with the car and false without
|
|
its fresh, corroborated share (`car_exclude_alarm`), on the same landing? The
|
|
tests are the alarms': a saturated guard and a floor with other
|
|
batteries left are graded by `load_too_high` on where the period lands
|
|
(SAFETY-81 / 87); a floor that leaves nothing is graded by SAFETY-126's
|
|
`misses_aim` (the batteries at 0 W from now on), latched for the
|
|
quarter (`_car_need_real`, and `_car_need_excl` without the car).
|
|
EV-18 (owner 2026-11-19): without the car, the batteries keep giving
|
|
what they give now (the lower of two readings), re-checked every cycle;
|
|
a miss seen so (`_car_need_house`) never lets the car explain for the
|
|
rest of the quarter. The car also explains where the period with it,
|
|
on the same batteries, misses (`_car_over_now`). Only a trusted figure
|
|
latches: an untrusted car (`w` None) or an unknown battery reading
|
|
explains nothing in that cycle only. All reset at a new quarter and
|
|
when the guard no longer wants power, whatever the cover option says
|
|
(this runs every cycle). DECISIONS/EV-04-manual-mode.md (EV-18)."""
|
|
now, prev = self.site_batt_w, self._car_batt_prev
|
|
prev2, self._car_batt_prev2 = self._car_batt_prev2, prev
|
|
self._car_batt_prev = now
|
|
wants = bool(guard is not None and guard.engaged
|
|
and guard.blind is None
|
|
and (guard.wanted_w or 0.0) > 0.0)
|
|
if real_proj.block_start != self._car_latch_block or not wants:
|
|
self._car_latch_block = real_proj.block_start
|
|
self._car_need_real = self._car_need_excl = False
|
|
self._car_need_house = self._car_over_now = False
|
|
batt = now
|
|
if batt is not None and prev is not None:
|
|
batt = min(float(batt), float(prev))
|
|
excl = self.car_exclude_alarm(real_proj, w)
|
|
# EV-19: the reading can show a rise one cycle before the meter does
|
|
# (the batteries pick up the house at the reserve). While the meter's
|
|
# house side (held - car; held alone when a car figure is unknown) has
|
|
# not moved, a reading above both earlier ones is not yet counted as
|
|
# house; a meter that moved shows it (no discount).
|
|
held = float(real_proj.held_w)
|
|
hp, self._car_hx_prev = self._car_hx_prev, (held, w)
|
|
still = False
|
|
if hp is not None:
|
|
moved = held - hp[0]
|
|
if w is not None and hp[1] is not None:
|
|
moved -= float(w) - float(hp[1])
|
|
still = abs(moved) <= RISE_STILL_W
|
|
seen = now
|
|
if still and now is not None and prev is not None \
|
|
and prev2 is not None:
|
|
seen = min(float(now), max(float(prev), float(prev2)))
|
|
if wants and batt is not None:
|
|
self._car_need_real = self._car_need_real or \
|
|
peakguard.misses_aim(real_proj, batt_w=batt,
|
|
target_w=target_w)
|
|
self._car_over_now = self._car_over_now or \
|
|
self._car_lands_over(real_proj, now, batt, target_w)
|
|
if w is not None:
|
|
self._car_need_excl = self._car_need_excl or \
|
|
peakguard.misses_aim(excl, batt_w=batt, target_w=target_w)
|
|
self._car_need_house = self._car_need_house or \
|
|
self._car_lands_over(excl, seen, batt, target_w)
|
|
if w is None or batt is None or not wants \
|
|
or not (guard.saturated or guard.floor_limited):
|
|
return False
|
|
if guard.saturated:
|
|
rating = self.site_rating_w
|
|
elif (guard.floor_w or 0.0) > 0.0 and guard.able_w is not None:
|
|
rating = guard.able_w
|
|
else:
|
|
return bool(not guard.within_aim and self._car_need_real
|
|
and not self._car_need_house
|
|
and (self._car_over_now or not self._car_need_excl))
|
|
|
|
def high(p):
|
|
return peakguard.load_too_high(
|
|
p, batt_w=batt, ceiling_w=guard.ceiling_w,
|
|
achievable_w=rating)
|
|
return bool(high(real_proj) and not high(excl))
|
|
|
|
@staticmethod
|
|
def _car_lands_over(p, now, gives, target_w) -> bool:
|
|
"""EV-18: does the period end more than `ALARM_MISS_W` over the aim
|
|
with the batteries giving `gives` W from now on (`now`: what they gave
|
|
in the meter's figure)? Of what is done, only the car's energy counted
|
|
since the add-on started is the car's (a restart or a gap leaves the
|
|
rest with the house)."""
|
|
return peakguard.load_too_high(p, batt_w=now, ceiling_w=target_w,
|
|
achievable_w=gives)
|
|
|
|
def _car_session_tick(self, mono) -> None:
|
|
"""A charging session is a plug-in: the state goes from no car to a
|
|
car. The notice is raised once per session."""
|
|
s = self.car.status(mono, True)
|
|
if s in (chargers.NONE_,) and self._car_prev_state not in (
|
|
None, chargers.NONE_):
|
|
self._car_over_notified = None
|
|
# The session is over: that is a real end, with no hold.
|
|
self.car_over = False
|
|
self._car_over_since = self._car_over_gone = None
|
|
self._car_over_ep += 1 # EV-16: an episode ends
|
|
if s not in (chargers.NONE_, None) and self._car_prev_state in (
|
|
chargers.NONE_, None):
|
|
self._car_session += 1
|
|
self._car_prev_state = s
|
|
|
|
async def check_car_over(self) -> None:
|
|
"""One grey notice per charging session: the charge you set takes the
|
|
15-minute period over the peak limit. Raised nowhere else."""
|
|
if not self.car_over or self._car_over_notified == self._car_session:
|
|
return
|
|
self._car_over_notified = self._car_session
|
|
if self.car_solar_mode(): # EV-20, D1
|
|
_LOG.info("Solar's car charge takes this 15-minute period over "
|
|
"the peak limit: CAR_OVER_PEAK.")
|
|
await self.hass.call("persistent_notification", "create",
|
|
messages.car_over_solar(
|
|
f"{self.car_amps_now():.0f}").data())
|
|
return
|
|
_LOG.info("The car charge you set takes this 15-minute period over "
|
|
"the peak limit: CAR_OVER_PEAK.")
|
|
await self.hass.call("persistent_notification", "create",
|
|
messages.car_over(f"{self.car_a:.0f}").data())
|
|
|
|
def car_peak_by_car(self, reading, now):
|
|
"""`(True, local time)` when the month's peak quarter was one the car
|
|
mostly made (it drew half the peak or more), else `(False, None)`."""
|
|
if reading is None or not getattr(reading, "is_observed", False) \
|
|
or reading.quarter_start is None or not self.car_peak_q:
|
|
return False, None
|
|
avg = self.car_peak_q.get(
|
|
reading.quarter_start.astimezone(timezone.utc).isoformat())
|
|
if avg is None or reading.peak_w is None \
|
|
or 2.0 * float(avg) < float(reading.peak_w):
|
|
return False, None
|
|
return True, reading.quarter_start
|