Solar charges the car from the signed spare sun (car + battery charge - grid import), less the batteries' room (Batteries first) and the sun kept back, whole amps rounded down, at most one change per 30 s and only on 1 A. It starts after ev_start_min of enough sun, holds 6 A for ev_pause_min, then 0 A. Auto phases through EV-04's safe sequence (4.5 kW / 3 min up, 4.0 kW / 5 min down, one switch per 10 min). What the peak guard would ask the batteries for is taken off the car first, at once. Every way out of Solar ends at 0 A, written once; at shutdown before the inverters go to 0 W. - app/carmode.py: SolarPlan (pure) and SolarWriter (ManualWriter's one write site, its sequence and watch); spare_w, car_target_w, amps_for. - app/ctl_car.py: Solar inputs, the cut, the solar kWh, EV-15's grace for Solar's own 0 A, no "set by the car" for Solar; main.py: shutdown order. - Home card, HA select.goodwe_car_sun_first, sensor car_today_solar_kwh, three options with defaults, strings EN/NL, DOCS, DECISIONS, CHANGELOG. - test_ev05.py, test_ev05_long.py, tools/ev05_sun.py; test_ev03/ev04 checks that pinned "Solar is refused" / "three entities" updated. Co-Authored-By: Claude <noreply@anthropic.com>
691 lines
33 KiB
Python
691 lines
33 KiB
Python
"""EV-04 and EV-05: the Controller's side of the car's Manual and Solar modes.
|
|
|
|
The writes themselves are `carmode.ManualWriter`'s; this mixin owns the state
|
|
(mode, current, phases: 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.
|
|
EV-05 (DECISIONS/EV-05-solar-mode.md): Solar's inputs (`car_sun_inputs`), the
|
|
peak guard's excess taken off the car first (`car_cycle`), the 0 A at shutdown
|
|
before the inverters, and the solar kWh of today.
|
|
"""
|
|
|
|
import asyncio
|
|
import dataclasses
|
|
import logging
|
|
import math
|
|
from datetime import timezone
|
|
|
|
from . import carmode, chargers, messages, packmode, packshare, peakguard
|
|
from .tariff import QUARTER_S
|
|
|
|
_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
|
|
CAR_SUN_KEY = "car_sun" # EV-05: {day, kwh} charged from the sun today
|
|
# EV-05: at shutdown the charger's 0 A waits at most this long, then the
|
|
# inverters are released whatever the charger did.
|
|
RELEASE_WAIT_S = 15.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 {}
|
|
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-05
|
|
first = data.get(carmode.KEY_FIRST)
|
|
self.car_first = first if first in carmode.FIRSTS \
|
|
else carmode.DEFAULT_FIRST
|
|
self.car_cut_w = 0.0
|
|
self._car_key = None
|
|
self._car_late_s = None
|
|
self._car_sun_last = None
|
|
self._car_error_notified = False
|
|
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_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_batt_prev = None
|
|
self._car_need_real = self._car_need_excl = False # EV-10 latches
|
|
self._car_latch_block = None
|
|
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 {}
|
|
|
|
@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_solar_mode(self) -> bool:
|
|
"""EV-05: 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_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")}
|
|
self.car_mode = value
|
|
self.store.set(carmode.KEY_MODE, value)
|
|
elif what == "car_sun_first":
|
|
# EV-05: arithmetic only, from the next cycle; not a user change of
|
|
# the writers (the 30 s rule and the other-writer 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()
|
|
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
|
|
self._car_task = asyncio.ensure_future(self._car_run())
|
|
|
|
def _car_hold_kick(self) -> None:
|
|
"""EV-05: a cycle that holds for a missing or late reading returns
|
|
before `car_kick()`. Solar still steps (it holds, counts its dwell from
|
|
the first missing reading, and an exit still writes its 0 A); Manual is
|
|
left exactly as it was."""
|
|
if self.car_solar_engaged():
|
|
self.car_cut_w = 0.0
|
|
self.car_kick()
|
|
|
|
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
|
|
|
|
def car_solar_engaged(self) -> bool:
|
|
"""EV-05: Solar is the mode, or its 0 A on the way out is still due."""
|
|
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))
|
|
|
|
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. Solar (EV-05): 0 A, once, waited for at most
|
|
`RELEASE_WAIT_S` (`Controller.shutdown` calls this first 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:
|
|
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
|
|
_LOG.warning("The car charger could not be set to 0 A before "
|
|
"the add-on stopped: 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_step(self) -> None:
|
|
"""One step of Manual. Reads nothing from the world (the cycle's read
|
|
did) and writes only through `carmode.ManualWriter`."""
|
|
if not self.charger.configured():
|
|
return
|
|
now = self.car_now()
|
|
if self.car_mode != carmode.SOLAR:
|
|
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:
|
|
await w.step(
|
|
self.charger, self.car.reading, mode=self.car_mode,
|
|
sun=(self.car_sun_inputs(now)
|
|
if self.car_mode == carmode.SOLAR else None),
|
|
clamp=self.car_clamp(), now=now, tracker=self.car,
|
|
writing=self.car_writing(), status=self.car.status(now, True),
|
|
clock=self.car_now)
|
|
|
|
# ------------------------------------------------------- EV-05: Solar
|
|
def car_may_charge(self, inv) -> bool:
|
|
"""May this battery take the sun? On (battery modes), not refusing a
|
|
charge, its level read and under full."""
|
|
if self.modes_on and not self.pack_mode(inv).use:
|
|
return False
|
|
if (inv.refused or 0) < 0 or inv.sign_wd.tripped:
|
|
return False
|
|
if len(self.inverters) == 1 and (self.batt_refused or 0) < 0:
|
|
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, readings late past the stale bound,
|
|
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.
|
|
age = self.p1.age_s()
|
|
if age is None or age > stale:
|
|
return None
|
|
r = self.car.reading
|
|
if r is None or not r.available or not self.car.fresh(mono):
|
|
return None
|
|
if r.charging is True:
|
|
car = self.car.car_w_trusted(mono)
|
|
else:
|
|
car = 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"]))
|
|
self._car_sun_last = carmode.SunInputs(
|
|
target_w=carmode.car_target_w(spare, room, margin,
|
|
self.car_first),
|
|
hold=hold, cut_w=self.car_cut_w,
|
|
car_w=self.car.car_w(mono), key=self._car_key,
|
|
auto=ph not in ("1", "3"), fixed_n=3 if ph == "3" else 1,
|
|
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)
|
|
return self._car_sun_last
|
|
|
|
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 or self.car_sun.get("day") != self.car.day:
|
|
return None if self.car.today_kwh is None else 0.0
|
|
return max(0.0, min(float(self.car_sun["kwh"]),
|
|
float(self.car.today_kwh)))
|
|
|
|
async def check_car_error(self) -> None:
|
|
"""EV-05: in Solar a charger error sets the car to 0 A and raises one
|
|
warning notification; it is taken down when the error clears."""
|
|
bad = self.car_solar_mode() and self.car_solar.fault == "error"
|
|
if bad and not self._car_error_notified:
|
|
self._car_error_notified = True
|
|
await self.hass.call("persistent_notification", "create",
|
|
messages.charger_error().data())
|
|
elif not bad and self._car_error_notified:
|
|
self._car_error_notified = False
|
|
await self.hass.call("persistent_notification", "dismiss",
|
|
messages.charger_error_gone().data())
|
|
|
|
# ------------------------------------------- the car and the peak guard
|
|
def car_alarm_w(self):
|
|
"""The car's power for the guard's alarm path: Manual and Solar, 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_manual() or self.car_solar_mode()):
|
|
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."""
|
|
if self.car_solar_mode():
|
|
return self._car_solar_pause(mono)
|
|
wr = getattr(self, "car_writer", None)
|
|
if wr is None or (wr.seq is None and wr.phase_done_at is None
|
|
and wr.zero_sent_at is None) or wr.hold:
|
|
return False
|
|
r = self.car.reading
|
|
if not (self.car_manual() 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
|
|
return 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S
|
|
|
|
def _car_solar_pause(self, mono) -> bool:
|
|
"""EV-05: Solar's own 0 A (a pause, the peak cut, the phase change)
|
|
gets EV-15's grace, bounded the same way: from the moment it is sent,
|
|
at most `OWN_PAUSE_MAX_S`; a phase change as in Manual. None for Stop,
|
|
shadow, an unplugged car or another writer."""
|
|
wr = getattr(self, "car_solar", None)
|
|
r = self.car.reading
|
|
if wr is None or wr.hold or not self.car_writing() or r is None \
|
|
or not r.available or r.state == "A":
|
|
return False
|
|
q = wr.seq
|
|
if q is not None:
|
|
return not q.get("failed") and 0.0 <= mono - q["t0"] \
|
|
<= OWN_PAUSE_MAX_S
|
|
if wr.zero_sent_at is not None:
|
|
return 0.0 <= mono - wr.zero_sent_at <= OWN_PAUSE_MAX_S
|
|
if wr.zero_at is not None 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_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-05: only a charge you set can be "set by the car";
|
|
# a Solar charge runs on spare sun and is cut first.
|
|
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()
|
|
# EV-05: the period's own key, and the excess Solar takes off the car
|
|
# first (the writer step that follows this cycle acts on it at once).
|
|
self._car_key = None if real_proj is None else real_proj.block_start
|
|
self.car_cut_w = 0.0
|
|
# What the guard would ASK the batteries to give (`wanted_w`, its floor
|
|
# before the rating) is taken off the car instead, up to the excess:
|
|
# batteries that only stop charging are not asked for anything.
|
|
if self.car_solar_mode() and real_proj is not None \
|
|
and target_w is not None and real_proj.block_start is not None \
|
|
and guard is not None and guard.engaged and guard.blind is None:
|
|
ex = peakguard.excess_w(real_proj, target_w)
|
|
want = guard.wanted_w
|
|
if ex is not None and want is not None and math.isfinite(ex) \
|
|
and math.isfinite(want) and ex > 0.0 and want > 0.0:
|
|
self.car_cut_w = float(min(ex, want))
|
|
self._car_sun_tick(mono)
|
|
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.
|
|
wg = w
|
|
if w is None and self._car_own_pause(mono):
|
|
wg = self.car.car_w_paused(mono)
|
|
self._car_quarter(real_proj, w, mono, wg)
|
|
self._car_session_tick(mono)
|
|
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.
|
|
graded = self._car_explains_alarm(real_proj, guard, target_w, wg)
|
|
if self.car_solar_mode():
|
|
# EV-05: Solar is cut first, so it is never "over"; its own
|
|
# 0 A must not leave the house's alarm graded with the car.
|
|
explains = graded
|
|
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_gone = None
|
|
|
|
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. That latch is kept here twice, on the period as it is
|
|
(`_car_need_real`) and without the car (`_car_need_excl`), from the
|
|
same `misses_aim` and the same batteries reading. Both reset at a new
|
|
quarter and when the guard no longer wants power, whatever the cover
|
|
option says (this runs every cycle). A car that is 0 W, or untrusted
|
|
(`w` None sets the second latch), makes the two equal and explains
|
|
nothing."""
|
|
batt, prev = self.site_batt_w, self._car_batt_prev
|
|
self._car_batt_prev = batt
|
|
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:
|
|
self._car_latch_block = real_proj.block_start
|
|
self._car_need_real = self._car_need_excl = False
|
|
if not wants:
|
|
self._car_need_real = self._car_need_excl = False
|
|
if batt is not None and prev is not None:
|
|
batt = min(float(batt), float(prev))
|
|
excl = self.car_exclude_alarm(real_proj, w)
|
|
if wants:
|
|
if batt is None:
|
|
self._car_need_real = self._car_need_excl = True
|
|
else:
|
|
self._car_need_real = self._car_need_real or \
|
|
peakguard.misses_aim(real_proj, batt_w=batt,
|
|
target_w=target_w)
|
|
self._car_need_excl = self._car_need_excl or w is None or \
|
|
peakguard.misses_aim(excl, batt_w=batt, target_w=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_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))
|
|
|
|
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
|
|
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
|
|
_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
|