From cf59160648d7505ec55159e6c7592e4a8c1694e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 17:57:07 +0000 Subject: [PATCH 01/16] feat(core,storage): battery contracts per ADR-0013 - None is the baseline, battery identity and mode (WP10) - BatteryAction is the full desired state; None = the adapter's baseline value of that field (resolve_battery_action), capabilities per field, live field ranges, round-up quantisation - core.identity.battery_identity / battery_identity_token (asset id, adapter template, role entities, site SoC and battery power, modbus hub and unit id) - operation.battery_mode (additive): a battery or site put that changes the identity drops it to shadow, an import always resets it, a restore keeps it only for the recorded identity; a full operation put cannot raise it - BatterySettings.modbus (hub, unit id, byte order, heartbeat, fallback timer) and fallback_measured (additive); mode providers report the battery mode Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- frontend/src/lib/api/openapi.json | 71 +++++++++- frontend/src/lib/api/schema.d.ts | 75 ++++++++-- frontend/src/lib/i18n/locales/de.json | 4 +- frontend/src/lib/i18n/locales/en.json | 4 +- frontend/src/lib/wizard/forms.test.ts | 2 + frontend/src/lib/wizard/goalsForm.ts | 10 +- suncore/api/validation.py | 2 + suncore/app/modes.py | 3 + suncore/app/runtime.py | 2 + suncore/core/battery.py | 168 +++++++++++++++++++++- suncore/core/config.py | 10 ++ suncore/core/decisions.py | 30 ++-- suncore/core/identity.py | 65 ++++++++- suncore/safety/modes.py | 15 ++ suncore/storage/config_store.py | 91 +++++++++++- suncore/storage/runtime.py | 3 + tests/core/test_battery_contracts.py | 194 ++++++++++++++++++++++++++ tests/storage/test_config_sections.py | 114 ++++++++++++++- 18 files changed, 829 insertions(+), 34 deletions(-) create mode 100644 tests/core/test_battery_contracts.py diff --git a/frontend/src/lib/api/openapi.json b/frontend/src/lib/api/openapi.json index 50f1ed2..579abd0 100644 --- a/frontend/src/lib/api/openapi.json +++ b/frontend/src/lib/api/openapi.json @@ -297,7 +297,7 @@ }, "BatteryAction": { "additionalProperties": false, - "description": "Battery limits for the gate (Phase 4 WP2; reviewed by ``control-safety`` in WP10).\n\nEvery field is optional, at least one must be set; a missing field leaves that limit\nas it is. Powers are magnitudes in W (battery + = charging, so ``grid_charge_w`` is a\ncharging power drawn from the grid): ``max_charge_w`` / ``max_discharge_w`` cap the\ninverter's own control, ``min_soc_pct`` is the discharge floor (discharge lock when at\nor above the current SoC), ``grid_charge_w > 0`` asks for forced charging from the\ngrid. ``grid_charge_w`` never exceeds ``max_charge_w`` when both are set (forced\ncharging cannot be above the charge cap, and a cap of 0 forbids it). Until the battery\npath exists the gate rejects this action (``safety.battery_not_supported``); nothing is\nwritten.", + "description": "Battery limits for the gate (Phase 4 WP2; semantics ADR-0013, decisions 1 and 2).\n\n**Full desired state, not a delta.** An accepted ``BatteryAction`` is the complete state\nSunCore wants the battery adapter to hold; a field that is ``None`` means \"no SunCore\nrestriction on this limit\", i.e. the adapter's **baseline** value of that field (what the\ngate read back when it took the battery over). The gate resolves the ``None`` fields from\nthe baseline before it judges, writes and reads back (``suncore.core.battery.\nresolve_battery_action``); the heartbeat re-sends the resolved state idempotently. At least\none field must be set: \"everything at baseline\" is a :class:`ReleaseAction`, never an empty\n``BatteryAction``.\n\nPowers are magnitudes in W (battery + = charging, so ``grid_charge_w`` is a charging power\ndrawn from the grid): ``max_charge_w`` / ``max_discharge_w`` cap the inverter's own\nself-consumption control (they never command a power), ``min_soc_pct`` is the discharge\nfloor (a discharge lock when at or above the current SoC), ``grid_charge_w > 0`` asks for\nforced charging from the grid. ``grid_charge_w`` never exceeds ``max_charge_w`` when both\nare set (forced charging cannot be above the charge cap, and a cap of 0 forbids it). Every\nfield needs the matching adapter capability (``BatteryCapability``); the gate rejects a\nfield the adapter cannot execute (``safety.battery_capability_missing``).", "properties": { "grid_charge_w": { "anyOf": [ @@ -699,12 +699,27 @@ "title": "Entities", "type": "object" }, + "fallback_measured": { + "default": false, + "title": "Fallback Measured", + "type": "boolean" + }, "grid_charge": { "$ref": "#/components/schemas/GridChargePolicy", "default": { "enabled": false } }, + "modbus": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModbusLink" + }, + { + "type": "null" + } + ] + }, "model": { "anyOf": [ { @@ -4509,6 +4524,56 @@ "title": "LoadTemperatureView", "type": "object" }, + "ModbusByteOrder": { + "description": "Word order of 32-bit values (Kostal register 5: ``0x00`` little, ``0x01`` big).", + "enum": [ + "little", + "big" + ], + "title": "ModbusByteOrder", + "type": "string" + }, + "ModbusLink": { + "additionalProperties": false, + "description": "How the ``kostal_modbus`` adapter reaches the inverter through ``modbus.write_register``.\n\n``hub`` is the ``name`` of the user's ``modbus:`` YAML hub (HA's default ``modbus_hub``),\n``slave`` the inverter's unit id (Kostal default 71; the action itself would default to 1,\nso it is mandatory here), ``byte_order`` what register 5 reports (the adapter never guesses\nit). ``fallback_timeout_s`` is written to register 1288 (30-10800 s) and ``heartbeat_s`` is\nthe re-write period of 1280/1282; it must be at most a third of the timeout. Research:\n``docs/research/kostal-plenticore-modbus.md`` §3.5, ``ha-websocket-api.md`` \"Modbus write\naction\". ``UNVERIFIED`` on hardware (external battery management is not enabled on the\nmaintainer's inverter yet).", + "properties": { + "byte_order": { + "$ref": "#/components/schemas/ModbusByteOrder" + }, + "fallback_timeout_s": { + "default": 60, + "maximum": 10800.0, + "minimum": 30.0, + "title": "Fallback Timeout S", + "type": "integer" + }, + "heartbeat_s": { + "default": 20.0, + "maximum": 3600.0, + "minimum": 5.0, + "title": "Heartbeat S", + "type": "number" + }, + "hub": { + "default": "modbus_hub", + "pattern": "^[A-Za-z0-9_\\-]{1,64}$", + "title": "Hub", + "type": "string" + }, + "slave": { + "maximum": 255.0, + "minimum": 1.0, + "title": "Slave", + "type": "integer" + } + }, + "required": [ + "slave", + "byte_order" + ], + "title": "ModbusLink", + "type": "object" + }, "Mode": { "additionalProperties": false, "description": "One mode of a mode-controlled device and the power it draws.", @@ -4729,6 +4794,10 @@ "additionalProperties": false, "description": "Stored operating modes. Not read by the safety gate before Phase 3.\n\nDevices that are new at ``devices`` put/import time lose any entry here (shadow).", "properties": { + "battery_mode": { + "$ref": "#/components/schemas/OperatingMode", + "default": "shadow" + }, "device_modes": { "patternProperties": { "^[a-z][a-z0-9_]{0,47}$": { diff --git a/frontend/src/lib/api/schema.d.ts b/frontend/src/lib/api/schema.d.ts index 12b7b29..85a0123 100644 --- a/frontend/src/lib/api/schema.d.ts +++ b/frontend/src/lib/api/schema.d.ts @@ -921,17 +921,25 @@ export interface components { BandPreference: "neutral" | "prefer_on" | "prefer_off"; /** * BatteryAction - * @description Battery limits for the gate (Phase 4 WP2; reviewed by ``control-safety`` in WP10). + * @description Battery limits for the gate (Phase 4 WP2; semantics ADR-0013, decisions 1 and 2). * - * Every field is optional, at least one must be set; a missing field leaves that limit - * as it is. Powers are magnitudes in W (battery + = charging, so ``grid_charge_w`` is a - * charging power drawn from the grid): ``max_charge_w`` / ``max_discharge_w`` cap the - * inverter's own control, ``min_soc_pct`` is the discharge floor (discharge lock when at - * or above the current SoC), ``grid_charge_w > 0`` asks for forced charging from the - * grid. ``grid_charge_w`` never exceeds ``max_charge_w`` when both are set (forced - * charging cannot be above the charge cap, and a cap of 0 forbids it). Until the battery - * path exists the gate rejects this action (``safety.battery_not_supported``); nothing is - * written. + * **Full desired state, not a delta.** An accepted ``BatteryAction`` is the complete state + * SunCore wants the battery adapter to hold; a field that is ``None`` means "no SunCore + * restriction on this limit", i.e. the adapter's **baseline** value of that field (what the + * gate read back when it took the battery over). The gate resolves the ``None`` fields from + * the baseline before it judges, writes and reads back (``suncore.core.battery. + * resolve_battery_action``); the heartbeat re-sends the resolved state idempotently. At least + * one field must be set: "everything at baseline" is a :class:`ReleaseAction`, never an empty + * ``BatteryAction``. + * + * Powers are magnitudes in W (battery + = charging, so ``grid_charge_w`` is a charging power + * drawn from the grid): ``max_charge_w`` / ``max_discharge_w`` cap the inverter's own + * self-consumption control (they never command a power), ``min_soc_pct`` is the discharge + * floor (a discharge lock when at or above the current SoC), ``grid_charge_w > 0`` asks for + * forced charging from the grid. ``grid_charge_w`` never exceeds ``max_charge_w`` when both + * are set (forced charging cannot be above the charge cap, and a cap of 0 forbids it). Every + * field needs the matching adapter capability (``BatteryCapability``); the gate rejects a + * field the adapter cannot execute (``safety.battery_capability_missing``). */ BatteryAction: { /** Grid Charge W */ @@ -1102,12 +1110,18 @@ export interface components { entities?: { [key: string]: components["schemas"]["EntityRef"]; }; + /** + * Fallback Measured + * @default false + */ + fallback_measured: boolean; /** * @default { * "enabled": false * } */ grid_charge: components["schemas"]["GridChargePolicy"]; + modbus?: components["schemas"]["ModbusLink"] | null; model?: components["schemas"]["BatteryModel"] | null; /** Morning Buffer Pct */ morning_buffer_pct?: number | null; @@ -2499,6 +2513,45 @@ export interface components { */ reason: "active" | "not_configured" | "too_few_days" | "no_spread"; }; + /** + * ModbusByteOrder + * @description Word order of 32-bit values (Kostal register 5: ``0x00`` little, ``0x01`` big). + * @enum {string} + */ + ModbusByteOrder: "little" | "big"; + /** + * ModbusLink + * @description How the ``kostal_modbus`` adapter reaches the inverter through ``modbus.write_register``. + * + * ``hub`` is the ``name`` of the user's ``modbus:`` YAML hub (HA's default ``modbus_hub``), + * ``slave`` the inverter's unit id (Kostal default 71; the action itself would default to 1, + * so it is mandatory here), ``byte_order`` what register 5 reports (the adapter never guesses + * it). ``fallback_timeout_s`` is written to register 1288 (30-10800 s) and ``heartbeat_s`` is + * the re-write period of 1280/1282; it must be at most a third of the timeout. Research: + * ``docs/research/kostal-plenticore-modbus.md`` §3.5, ``ha-websocket-api.md`` "Modbus write + * action". ``UNVERIFIED`` on hardware (external battery management is not enabled on the + * maintainer's inverter yet). + */ + ModbusLink: { + byte_order: components["schemas"]["ModbusByteOrder"]; + /** + * Fallback Timeout S + * @default 60 + */ + fallback_timeout_s: number; + /** + * Heartbeat S + * @default 20 + */ + heartbeat_s: number; + /** + * Hub + * @default modbus_hub + */ + hub: string; + /** Slave */ + slave: number; + }; /** * Mode * @description One mode of a mode-controlled device and the power it draws. @@ -2616,6 +2669,8 @@ export interface components { * Devices that are new at ``devices`` put/import time lose any entry here (shadow). */ OperationConfig: { + /** @default shadow */ + battery_mode: components["schemas"]["OperatingMode"]; /** Device Modes */ device_modes?: { [key: string]: components["schemas"]["OperatingMode"]; diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index 2ec9411..3e60bf7 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -946,5 +946,7 @@ "planner.status.expired": "Der Plan ist abgelaufen: SunCore regelt ohne ihn (nur Überschussregeln), bis ein neuer Plan vorliegt.", "planner.status.no_plan": "Es gibt noch keinen Plan: SunCore regelt nur nach den Überschussregeln.", "api.error.planning_unavailable": "Der Planer läuft nicht (keine Anlage eingerichtet).", - "planner.status.waiting_for_soc": "Warte auf den Ladestand der Batterie, bevor geplant wird." + "planner.status.waiting_for_soc": "Warte auf den Ladestand der Batterie, bevor geplant wird.", + "api.validation.battery_modbus_needs_adapter": "Eine Modbus-Verbindung braucht einen Batterie-Adapter; „nur beobachten“ hat keinen.", + "api.validation.modbus_heartbeat_too_slow": "Der Heartbeat ({heartbeat_s} s) darf höchstens ein Drittel der Rückfallzeit ({timeout_s} s) sein." } diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index 6d813ce..06adb76 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -946,5 +946,7 @@ "planner.status.expired": "The plan has run out: SunCore controls without it (surplus rules only) until a new plan arrives.", "planner.status.no_plan": "There is no plan yet: SunCore controls on surplus rules only.", "api.error.planning_unavailable": "The planner is not running (no site is set up).", - "planner.status.waiting_for_soc": "Waiting for the battery's state of charge before planning." + "planner.status.waiting_for_soc": "Waiting for the battery's state of charge before planning.", + "api.validation.battery_modbus_needs_adapter": "A modbus link needs a battery adapter; \"observe only\" has none.", + "api.validation.modbus_heartbeat_too_slow": "The heartbeat ({heartbeat_s} s) must be at most a third of the fallback time ({timeout_s} s)." } diff --git a/frontend/src/lib/wizard/forms.test.ts b/frontend/src/lib/wizard/forms.test.ts index 2df1808..28e06a3 100644 --- a/frontend/src/lib/wizard/forms.test.ts +++ b/frontend/src/lib/wizard/forms.test.ts @@ -905,6 +905,7 @@ describe('goals and operation', () => { schema_version: 1, mode: 'assisted', device_modes: { a: 'automatic', gone: 'automatic' }, + battery_mode: 'assisted', }); form.deviceModes.b = 'shadow'; form.deviceModes.c = 'assisted'; @@ -912,6 +913,7 @@ describe('goals and operation', () => { schema_version: 1, mode: 'assisted', device_modes: { a: 'automatic', c: 'assisted' }, + battery_mode: 'assisted', }); expect(operationFormFromConfig(null).mode).toBe('shadow'); }); diff --git a/frontend/src/lib/wizard/goalsForm.ts b/frontend/src/lib/wizard/goalsForm.ts index 4e80474..5ca6a59 100644 --- a/frontend/src/lib/wizard/goalsForm.ts +++ b/frontend/src/lib/wizard/goalsForm.ts @@ -49,10 +49,16 @@ export interface OperationForm { mode: OperatingMode; /** Explicit mode per device id; a missing entry is shadow (new devices always start there). */ deviceModes: Record; + /** The battery's mode is carried through unchanged (raised only with its identity token). */ + batteryMode: OperatingMode; } export function operationFormFromConfig(cfg: OperationConfig | null): OperationForm { - return { mode: cfg?.mode ?? 'shadow', deviceModes: { ...(cfg?.device_modes ?? {}) } }; + return { + mode: cfg?.mode ?? 'shadow', + deviceModes: { ...(cfg?.device_modes ?? {}) }, + batteryMode: cfg?.battery_mode ?? 'shadow', + }; } /** Only non-shadow entries of existing devices are stored (a missing entry means shadow). */ @@ -65,7 +71,7 @@ export function operationFromForm( const mode = form.deviceModes[id]; if (mode && mode !== 'shadow') device_modes[id] = mode; } - return { schema_version: 1, mode: form.mode, device_modes }; + return { schema_version: 1, mode: form.mode, device_modes, battery_mode: form.batteryMode }; } export const TIME_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/; diff --git a/suncore/api/validation.py b/suncore/api/validation.py index a29acaa..75faced 100644 --- a/suncore/api/validation.py +++ b/suncore/api/validation.py @@ -112,6 +112,8 @@ "suncore.battery_action_empty": "api.validation.battery_action_empty", "suncore.battery_corridor": "api.validation.battery_corridor", "suncore.battery_entities_need_adapter": "api.validation.battery_entities_need_adapter", + "suncore.battery_modbus_needs_adapter": "api.validation.battery_modbus_needs_adapter", + "suncore.modbus_heartbeat_too_slow": "api.validation.modbus_heartbeat_too_slow", "suncore.forecast_auto_weight": "api.validation.forecast_auto_weight", "suncore.forecast_manual_weight": "api.validation.forecast_manual_weight", "suncore.forecast_weather_domain": "api.validation.forecast_weather_domain", diff --git a/suncore/app/modes.py b/suncore/app/modes.py index ca7b07b..169b20b 100644 --- a/suncore/app/modes.py +++ b/suncore/app/modes.py @@ -33,5 +33,8 @@ def global_mode(self) -> OperatingMode: def device_mode(self, device_id: str) -> OperatingMode: return self._operation.device_modes.get(device_id, OperatingMode.SHADOW) + def battery_mode(self) -> OperatingMode: + return self._operation.battery_mode + __all__ = ["ConfigModes"] diff --git a/suncore/app/runtime.py b/suncore/app/runtime.py index 97e05d8..18d7185 100644 --- a/suncore/app/runtime.py +++ b/suncore/app/runtime.py @@ -1270,6 +1270,8 @@ def _reject_raise(self, new: OperationConfig) -> None: for device_id, mode in new.device_modes.items(): if mode.rank > current.device_modes.get(device_id, OperatingMode.SHADOW).rank: raise ModeRaiseRejectedError(device_id) + if new.battery_mode.rank > current.battery_mode.rank: + raise ModeRaiseRejectedError("battery") async def _sync_modes(self) -> None: if self.stack is not None: diff --git a/suncore/core/battery.py b/suncore/core/battery.py index 307c770..8de841c 100644 --- a/suncore/core/battery.py +++ b/suncore/core/battery.py @@ -12,11 +12,13 @@ from __future__ import annotations +import math +from dataclasses import dataclass from datetime import datetime, tzinfo from enum import StrEnum, unique from typing import Annotated, Final, Self -from pydantic import BaseModel, ConfigDict, Field, model_validator +from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator from suncore.core.decisions import BatteryAction from suncore.core.devices import RoleName, TemplateId @@ -41,6 +43,102 @@ class _Frozen(BaseModel): model_config = ConfigDict(frozen=True, extra="forbid") +BATTERY_ASSET_ID: Final = "battery" +"""The asset id of the (one) battery in intents, decisions and the gate (ADR-0013 decision 6).""" + + +@unique +class BatteryCapability(StrEnum): + """What a battery adapter can execute (ADR-0013 decision 1).""" + + CHARGE_LIMIT = "charge_limit" + """``max_charge_w``: cap the charging power of the inverter's own control.""" + DISCHARGE_LIMIT = "discharge_limit" + """``max_discharge_w``: cap the discharging power (0 = discharge lock).""" + MIN_SOC = "min_soc" + """``min_soc_pct``: the inverter's discharge floor (reserve, discharge lock).""" + GRID_CHARGE = "grid_charge" + """``grid_charge_w``: forced charging from the grid.""" + HARDWARE_FALLBACK = "hardware_fallback" + """The inverter falls back to its own limits when SunCore stops re-writing (Kostal §3.5).""" + + +BATTERY_ACTION_FIELDS: Final = ("max_charge_w", "max_discharge_w", "min_soc_pct", "grid_charge_w") +"""The limit fields of a :class:`BatteryAction`, in a fixed order.""" + +FIELD_CAPABILITY: Final[dict[str, BatteryCapability]] = { + "max_charge_w": BatteryCapability.CHARGE_LIMIT, + "max_discharge_w": BatteryCapability.DISCHARGE_LIMIT, + "min_soc_pct": BatteryCapability.MIN_SOC, + "grid_charge_w": BatteryCapability.GRID_CHARGE, +} +"""The capability a non-``None`` field of a :class:`BatteryAction` needs.""" + + +def action_fields(action: BatteryAction) -> dict[str, float | None]: + """The limit fields of ``action`` by name (``None`` = baseline).""" + return {name: getattr(action, name) for name in BATTERY_ACTION_FIELDS} + + +def resolve_battery_action(action: BatteryAction, baseline: BatteryAction | None) -> BatteryAction: + """The full state ``action`` asks for: every ``None`` field taken from ``baseline``. + + ADR-0013 decision 2: ``None`` = the baseline value of that field. A field the baseline does + not know either stays ``None`` (the adapter leaves it untouched). The validator of + :class:`BatteryAction` still holds: a baseline charge cap below the requested grid-charge + power is not inherited (forced charging asks for its own power; the gate bounds it), and an + inherited grid-charge power above a requested cap is lowered to the cap. + """ + if baseline is None: + return action + values = action_fields(action) + for name, value in action_fields(baseline).items(): + if values[name] is None and value is not None: + values[name] = value + grid, cap = values["grid_charge_w"], values["max_charge_w"] + if grid is not None and cap is not None and grid > cap: + if action.max_charge_w is None: + values["max_charge_w"] = None # inherited cap: forced charging brings its own power + else: + values["grid_charge_w"] = cap # inherited forced charging: SunCore's cap wins + return BatteryAction(**values) + + +@dataclass(frozen=True, slots=True) +class FieldRange: + """The live range of one battery limit (in the field's unit: W or %).""" + + low: float + high: float + step: float | None = None + """Quantisation of the entity (e.g. Kostal ``Battery:MinSoc`` step 5); ``None`` = none.""" + + def contains(self, value: float, tolerance: float = 1e-6) -> bool: + return self.low - tolerance <= value <= self.high + tolerance + + +@dataclass(frozen=True, slots=True) +class BatteryRanges: + """What the adapter can write right now, per field (``None`` = unknown, nothing allowed).""" + + max_charge_w: FieldRange | None = None + max_discharge_w: FieldRange | None = None + min_soc_pct: FieldRange | None = None + grid_charge_w: FieldRange | None = None + + def of(self, name: str) -> FieldRange | None: + value: FieldRange | None = getattr(self, name) + return value + + +def round_up_to_step(value: float, step: float | None, low: float = 0.0) -> float: + """``value`` rounded **up** onto ``low + k * step`` (a floor is never lowered by rounding).""" + if step is None or step <= 0: + return value + k = math.ceil((value - low) / step - 1e-9) + return round(low + k * step, 6) + + class BatteryModel(_Frozen): """What the planner knows about the battery. @@ -228,6 +326,51 @@ class CalibrationCharge(_Frozen): target_soc_pct: Pct = 100.0 +@unique +class ModbusByteOrder(StrEnum): + """Word order of 32-bit values (Kostal register 5: ``0x00`` little, ``0x01`` big).""" + + LITTLE = "little" + """CDAB: the low word first (Kostal default).""" + BIG = "big" + """ABCD: the high word first (SunSpec).""" + + +HubName = Annotated[str, StringConstraints(pattern=r"^[A-Za-z0-9_\-]{1,64}$")] + + +class ModbusLink(_Frozen): + """How the ``kostal_modbus`` adapter reaches the inverter through ``modbus.write_register``. + + ``hub`` is the ``name`` of the user's ``modbus:`` YAML hub (HA's default ``modbus_hub``), + ``slave`` the inverter's unit id (Kostal default 71; the action itself would default to 1, + so it is mandatory here), ``byte_order`` what register 5 reports (the adapter never guesses + it). ``fallback_timeout_s`` is written to register 1288 (30-10800 s) and ``heartbeat_s`` is + the re-write period of 1280/1282; it must be at most a third of the timeout. Research: + ``docs/research/kostal-plenticore-modbus.md`` §3.5, ``ha-websocket-api.md`` "Modbus write + action". ``UNVERIFIED`` on hardware (external battery management is not enabled on the + maintainer's inverter yet). + """ + + hub: HubName = "modbus_hub" + slave: Annotated[int, Field(ge=1, le=255)] + byte_order: ModbusByteOrder + heartbeat_s: Annotated[float, Field(ge=5, le=3600)] = 20.0 + fallback_timeout_s: Annotated[int, Field(ge=30, le=10_800)] = 60 + + @model_validator(mode="after") + def _heartbeat(self) -> Self: + if self.heartbeat_s * 3 > self.fallback_timeout_s: + raise invalid( + "modbus_heartbeat_too_slow", + "battery.modbus: heartbeat_s ({heartbeat_s}) must be at most a third of " + "fallback_timeout_s ({timeout_s})", + heartbeat_s=self.heartbeat_s, + timeout_s=self.fallback_timeout_s, + ) + return self + + BATTERY_SCHEMA_VERSION: Final = 1 @@ -264,8 +407,20 @@ class BatterySettings(_Frozen): (0.01) is a tie-breaker: it prefers self-sufficiency only where the cost difference is below 1 ct/kWh, which also removes LP degeneracy on flat tariffs; 0 = pure cost.""" + modbus: ModbusLink | None = None + """``kostal_modbus`` adapter only: hub, unit id and word order (additive in v1, WP10).""" + fallback_measured: bool = False + """The maintainer measured the adapter's hardware fallback (Kostal §3.5 timer) on the real + inverter. Until then the gate caps an adapter with ``hardware_fallback`` at **assisted** + (ADR-0013 decision 6, plan §6 question 3). Additive in v1 (WP10).""" + @model_validator(mode="after") def _consistent(self) -> Self: + if self.modbus is not None and self.adapter_template_id is None: + raise invalid( + "battery_modbus_needs_adapter", + "battery: a modbus link needs an adapter template", + ) if self.entities and self.adapter_template_id is None: raise invalid( "battery_entities_need_adapter", @@ -291,6 +446,8 @@ def entity_refs(self) -> list[EntityRef]: __all__ = [ + "BATTERY_ACTION_FIELDS", + "BATTERY_ASSET_ID", "BATTERY_SCHEMA_VERSION", "DEFAULT_AUTARKY_WEIGHT_PER_KWH", "DEFAULT_BMS_DRIFT_PCT", @@ -298,12 +455,21 @@ def entity_refs(self) -> list[EntityRef]: "DEFAULT_EFFICIENCY", "DEFAULT_GRID_CHARGE_MARGIN_PER_KWH", "DEFAULT_RESERVE_PCT", + "FIELD_CAPABILITY", "BatteryAction", + "BatteryCapability", "BatteryModel", + "BatteryRanges", "BatterySettings", "BatteryStrategy", "CalibrationCharge", + "FieldRange", "GridChargePolicy", + "ModbusByteOrder", + "ModbusLink", "RiskLevel", + "action_fields", "effective_reserve_pct", + "resolve_battery_action", + "round_up_to_step", ] diff --git a/suncore/core/config.py b/suncore/core/config.py index 6ca5f4f..9bb0fc3 100644 --- a/suncore/core/config.py +++ b/suncore/core/config.py @@ -529,6 +529,10 @@ class OperationConfig(_Frozen): mode: OperatingMode = OperatingMode.SHADOW device_modes: dict[DeviceId, OperatingMode] = Field(default_factory=dict) """Missing entry = shadow. Single store for per-device modes (ADR-0012).""" + battery_mode: OperatingMode = OperatingMode.SHADOW + """Mode of the battery asset (ADR-0013 decision 6; additive in v1, Phase 4 WP10). The + same rules as a device's: raising it needs the battery's identity token, a changed battery + identity or an import drops it to shadow.""" def without_modes_of(self, device_ids: frozenset[str]) -> Self: """Drop the non-shadow entries of ``device_ids`` (they fall back to shadow).""" @@ -541,6 +545,12 @@ def without_modes_of(self, device_ids: frozenset[str]) -> Self: return self return self.model_copy(update={"device_modes": kept}) + def without_battery_mode(self) -> Self: + """The battery back in shadow (identity changed, import).""" + if self.battery_mode is OperatingMode.SHADOW: + return self + return self.model_copy(update={"battery_mode": OperatingMode.SHADOW}) + # --- wizard ------------------------------------------------------------------- diff --git a/suncore/core/decisions.py b/suncore/core/decisions.py index 2befb82..5a1e5a7 100644 --- a/suncore/core/decisions.py +++ b/suncore/core/decisions.py @@ -181,17 +181,25 @@ class ReleaseAction(_FrozenModel): class BatteryAction(_FrozenModel): - """Battery limits for the gate (Phase 4 WP2; reviewed by ``control-safety`` in WP10). - - Every field is optional, at least one must be set; a missing field leaves that limit - as it is. Powers are magnitudes in W (battery + = charging, so ``grid_charge_w`` is a - charging power drawn from the grid): ``max_charge_w`` / ``max_discharge_w`` cap the - inverter's own control, ``min_soc_pct`` is the discharge floor (discharge lock when at - or above the current SoC), ``grid_charge_w > 0`` asks for forced charging from the - grid. ``grid_charge_w`` never exceeds ``max_charge_w`` when both are set (forced - charging cannot be above the charge cap, and a cap of 0 forbids it). Until the battery - path exists the gate rejects this action (``safety.battery_not_supported``); nothing is - written. + """Battery limits for the gate (Phase 4 WP2; semantics ADR-0013, decisions 1 and 2). + + **Full desired state, not a delta.** An accepted ``BatteryAction`` is the complete state + SunCore wants the battery adapter to hold; a field that is ``None`` means "no SunCore + restriction on this limit", i.e. the adapter's **baseline** value of that field (what the + gate read back when it took the battery over). The gate resolves the ``None`` fields from + the baseline before it judges, writes and reads back (``suncore.core.battery. + resolve_battery_action``); the heartbeat re-sends the resolved state idempotently. At least + one field must be set: "everything at baseline" is a :class:`ReleaseAction`, never an empty + ``BatteryAction``. + + Powers are magnitudes in W (battery + = charging, so ``grid_charge_w`` is a charging power + drawn from the grid): ``max_charge_w`` / ``max_discharge_w`` cap the inverter's own + self-consumption control (they never command a power), ``min_soc_pct`` is the discharge + floor (a discharge lock when at or above the current SoC), ``grid_charge_w > 0`` asks for + forced charging from the grid. ``grid_charge_w`` never exceeds ``max_charge_w`` when both + are set (forced charging cannot be above the charge cap, and a cap of 0 forbids it). Every + field needs the matching adapter capability (``BatteryCapability``); the gate rejects a + field the adapter cannot execute (``safety.battery_capability_missing``). """ kind: Literal[ActionKind.BATTERY] = ActionKind.BATTERY diff --git a/suncore/core/identity.py b/suncore/core/identity.py index 66af4f7..a807155 100644 --- a/suncore/core/identity.py +++ b/suncore/core/identity.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""Device identity: when does a stored device count as "new" (STATUS follow-up F6/A2)? +"""Device and battery identity: when does a stored asset count as "new" (STATUS F6/A2, ADR-0013)? A device that is new starts in shadow mode. Comparing ids alone is not enough: a user who re-uses an id for another template or re-maps its entities has, for the safety @@ -14,7 +14,9 @@ from collections.abc import Iterable from dataclasses import dataclass +from suncore.core.battery import BATTERY_ASSET_ID, BatterySettings from suncore.core.devices import DeviceConfig +from suncore.core.site import SiteConfig @dataclass(frozen=True, slots=True) @@ -61,8 +63,69 @@ def new_device_ids( return frozenset(d.id for d in current if is_new_device(d, before.get(d.id))) +@dataclass(frozen=True, slots=True) +class BatteryIdentity: + """What makes the battery the same controlled asset (ADR-0013 decision 6). + + The reserved asset id, the adapter template, the mapped role entities, the site's SoC and + battery power entities (what the gate judges the battery by) and, for the ``kostal_modbus`` + adapter, the modbus hub and unit id (another unit id writes to another inverter). Settings + (model, strategy, policy, byte order, timers) are not identity. + """ + + asset_id: str + template_id: str + entities: frozenset[tuple[str, str]] + soc_entity: str | None + power_entity: str | None + modbus: tuple[str, int] | None + + +def battery_identity( + settings: BatterySettings | None, site: SiteConfig | None +) -> BatteryIdentity | None: + """The battery's identity, ``None`` when it is observe-only (no adapter, nothing to write).""" + if settings is None or settings.adapter_template_id is None: + return None + site_battery = None if site is None else site.battery + return BatteryIdentity( + asset_id=BATTERY_ASSET_ID, + template_id=settings.adapter_template_id, + entities=frozenset((role, ref.entity_id) for role, ref in settings.entities.items()), + soc_entity=None if site_battery is None else site_battery.soc.entity_id, + power_entity=None if site_battery is None else site_battery.power.entity_id, + modbus=None if settings.modbus is None else (settings.modbus.hub, settings.modbus.slave), + ) + + +def battery_identity_token(settings: BatterySettings | None, site: SiteConfig | None) -> str | None: + """Opaque token of :func:`battery_identity` (``None`` = observe-only, no mode above shadow). + + Raising the battery's mode needs it (``PUT /api/v1/operation/battery``); the store records it + when the mode is granted and drops the mode when it changes. + """ + identity = battery_identity(settings, site) + if identity is None: + return None + payload = json.dumps( + [ + identity.asset_id, + identity.template_id, + sorted(identity.entities), + identity.soc_entity, + identity.power_entity, + list(identity.modbus) if identity.modbus is not None else None, + ], + separators=(",", ":"), + ) + return hashlib.sha256(payload.encode()).hexdigest()[:16] + + __all__ = [ + "BatteryIdentity", "DeviceIdentity", + "battery_identity", + "battery_identity_token", "device_identity", "identity_token", "is_new_device", diff --git a/suncore/safety/modes.py b/suncore/safety/modes.py index 156a14e..90dcefc 100644 --- a/suncore/safety/modes.py +++ b/suncore/safety/modes.py @@ -23,6 +23,10 @@ def device_mode(self, device_id: str) -> OperatingMode: """Mode of one device; an unknown device is shadow.""" ... + def battery_mode(self) -> OperatingMode: + """Mode of the battery asset (ADR-0013); shadow unless the user raised it.""" + ... + @dataclass(frozen=True, slots=True) class ModeView: @@ -46,6 +50,9 @@ def global_mode(self) -> OperatingMode: def device_mode(self, device_id: str) -> OperatingMode: # noqa: ARG002 - protocol return OperatingMode.SHADOW + def battery_mode(self) -> OperatingMode: + return OperatingMode.SHADOW + class StaticModes: """A provider over fixed values (tests, demo): ``device_modes`` missing = shadow.""" @@ -54,9 +61,11 @@ def __init__( self, global_mode: OperatingMode = OperatingMode.SHADOW, devices: dict[str, OperatingMode] | None = None, + battery: OperatingMode = OperatingMode.SHADOW, ) -> None: self._global = global_mode self._devices = dict(devices or {}) + self._battery = battery def global_mode(self) -> OperatingMode: return self._global @@ -70,6 +79,12 @@ def set_global(self, mode: OperatingMode) -> None: def set_device(self, device_id: str, mode: OperatingMode) -> None: self._devices[device_id] = mode + def battery_mode(self) -> OperatingMode: + return self._battery + + def set_battery(self, mode: OperatingMode) -> None: + self._battery = mode + def view(provider: ModeProvider, device_id: str) -> ModeView: return ModeView(provider.global_mode(), provider.device_mode(device_id)) diff --git a/suncore/storage/config_store.py b/suncore/storage/config_store.py index d4029ae..da64260 100644 --- a/suncore/storage/config_store.py +++ b/suncore/storage/config_store.py @@ -28,7 +28,7 @@ ) from suncore.core.decisions import OperatingMode from suncore.core.devices import DeviceConfig -from suncore.core.identity import device_identity, new_device_ids +from suncore.core.identity import battery_identity_token, device_identity, new_device_ids from suncore.core.site import SiteConfig, migrate_site_v1_to_v2 from suncore.storage.db import Database, Row, Transaction from suncore.storage.errors import ( @@ -38,7 +38,7 @@ UnknownSectionError, ) from suncore.storage.migrations import latest_version -from suncore.storage.runtime import KEY_MODE_IDENTITIES +from suncore.storage.runtime import KEY_BATTERY_MODE_IDENTITY, KEY_MODE_IDENTITIES log = structlog.get_logger(__name__) @@ -213,7 +213,10 @@ async def put(self, section: str, model: BaseModel) -> BaseModel: (STATUS F6/A2, ``core.identity``): putting ``devices`` removes the ``operation`` mode entries of devices that are new (id, template or mapped entities changed), so they start in shadow. Putting ``operation`` records the identity of every device that - holds a non-shadow mode; see :meth:`restore` for the history path. + holds a non-shadow mode; see :meth:`restore` for the history path. Battery (ADR-0013 + decision 6): a ``battery`` or ``site`` put that changes the battery's identity token + (``core.identity.battery_identity_token``) drops ``operation.battery_mode`` to shadow; an + ``operation`` put with a non-shadow battery mode records the token it was granted to. """ return await self._put(section, model, restoring=False) @@ -239,12 +242,86 @@ async def _put(self, section: str, model: BaseModel, *, restoring: bool) -> Base devices = await self._stored_devices(tx) if restoring: model = await self._drop_changed_identities(tx, model, devices) + model = await self._drop_changed_battery(tx, model) await self._write(tx, section, model, now) await self._record_identities(tx, model, devices, now) + await self._record_battery_identity(tx, model, now) + elif isinstance(model, BatterySettings | SiteConfig): + before = await self._battery_token(tx) + await self._write(tx, section, model, now) + if await self._battery_token(tx) != before: + await self._shadow_battery(tx, now) else: await self._write(tx, section, model, now) return model + # --- battery identity (ADR-0013 decision 6) ----------------------------------------- + + async def _battery_token(self, tx: Transaction) -> str | None: + """The stored battery's identity token (``None`` = observe-only or not configured).""" + battery_row = await tx.fetchone( + "SELECT schema_version, body FROM config_doc WHERE section = 'battery'" + ) + site_row = await tx.fetchone( + "SELECT schema_version, body FROM config_doc WHERE section = 'site'" + ) + battery = self._try_parse("battery", battery_row) + site = self._try_parse("site", site_row) + return battery_identity_token( + battery if isinstance(battery, BatterySettings) else None, + site if isinstance(site, SiteConfig) else None, + ) + + @staticmethod + async def _load_battery_record(tx: Transaction) -> str | None: + row = await tx.fetchone( + "SELECT value FROM safety_state WHERE key = ?", (KEY_BATTERY_MODE_IDENTITY,) + ) + return None if row is None or not row[0] else str(row[0]) + + @staticmethod + async def _save_battery_record(tx: Transaction, token: str | None, now: str) -> None: + await tx.execute( + "INSERT INTO safety_state (key, value, updated_at) VALUES (?, ?, ?) " + "ON CONFLICT(key) DO UPDATE SET value = excluded.value, " + "updated_at = excluded.updated_at", + (KEY_BATTERY_MODE_IDENTITY, token or "", now), + ) + + async def _record_battery_identity( + self, tx: Transaction, operation: OperationConfig, now: str + ) -> None: + """A non-shadow battery mode remembers the identity it was granted to (kept after a put + back to shadow, like the device record, so a later restore of the same battery works).""" + if operation.battery_mode is OperatingMode.SHADOW: + return + await self._save_battery_record(tx, await self._battery_token(tx), now) + + async def _drop_changed_battery( + self, tx: Transaction, operation: OperationConfig + ) -> OperationConfig: + """Restore path: a battery mode granted to another battery identity (or never recorded, + or to an observe-only battery) falls back to shadow.""" + if operation.battery_mode is OperatingMode.SHADOW: + return operation + current = await self._battery_token(tx) + if current is None or await self._load_battery_record(tx) != current: + return operation.without_battery_mode() + return operation + + async def _shadow_battery(self, tx: Transaction, now: str) -> None: + """The battery's identity changed (``battery`` or ``site`` put/restore): shadow it.""" + await self._save_battery_record(tx, None, now) + row = await tx.fetchone( + "SELECT schema_version, body FROM config_doc WHERE section = 'operation'" + ) + operation = self._try_parse("operation", row) + if not isinstance(operation, OperationConfig): + return + cleaned = operation.without_battery_mode() + if cleaned is not operation: + await self._write(tx, "operation", cleaned, now) + async def _stored_devices(self, tx: Transaction) -> list[DeviceConfig]: """Stored devices; a missing or corrupt section counts as "no devices" (all new).""" row = await tx.fetchone( @@ -536,8 +613,11 @@ async def import_json(self, data: object) -> list[str]: ) record = {k: v for k, v in old_record.items() if k in kept_ids} if isinstance(operation, OperationConfig): - # An import never carries trust over: the global mode is shadow afterwards. - operation = operation.model_copy(update={"mode": OperatingMode.SHADOW}) + # An import never carries trust over: the global mode is shadow afterwards, and so + # is the battery (ADR-0013: an imported battery is never trusted to write). + operation = operation.model_copy( + update={"mode": OperatingMode.SHADOW, "battery_mode": OperatingMode.SHADOW} + ) if isinstance(new_devices, DevicesConfig): operation = operation.without_modes_of( new_device_ids(previous, new_devices.devices) @@ -550,6 +630,7 @@ async def import_json(self, data: object) -> list[str]: operation = operation.without_modes_of(frozenset(operation.device_modes)) validated["operation"] = operation await self._save_identities(tx, record, now) + await self._save_battery_record(tx, None, now) stored = {name: self._dump(model) for name, model in validated.items()} for name, row in old.items(): if (int(str(row[0])), str(row[1])) != ( diff --git a/suncore/storage/runtime.py b/suncore/storage/runtime.py index 995dad9..ea6220d 100644 --- a/suncore/storage/runtime.py +++ b/suncore/storage/runtime.py @@ -28,6 +28,8 @@ KEY_EMERGENCY_STOP: Final = "emergency_stop" KEY_MODE_IDENTITIES: Final = "mode_identities" """Identity record of the devices that hold a non-shadow mode (see ``ConfigStore``).""" +KEY_BATTERY_MODE_IDENTITY: Final = "battery_mode_identity" +"""Battery identity token under which a non-shadow battery mode was granted (ADR-0013).""" def _now() -> datetime: @@ -135,6 +137,7 @@ async def delete(self, device_id: str) -> None: __all__ = [ + "KEY_BATTERY_MODE_IDENTITY", "KEY_EMERGENCY_STOP", "KEY_MODE_IDENTITIES", "PowerModelStateStore", diff --git a/tests/core/test_battery_contracts.py b/tests/core/test_battery_contracts.py new file mode 100644 index 0000000..1933401 --- /dev/null +++ b/tests/core/test_battery_contracts.py @@ -0,0 +1,194 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ADR-0013 contracts (WP10 step 1): ``None`` = baseline, battery identity, modbus link.""" + +from __future__ import annotations + +import pytest +from hypothesis import given +from hypothesis import strategies as st +from pydantic import ValidationError + +from suncore.core.battery import ( + BATTERY_ACTION_FIELDS, + FIELD_CAPABILITY, + BatteryAction, + BatteryCapability, + BatterySettings, + FieldRange, + ModbusByteOrder, + ModbusLink, + action_fields, + resolve_battery_action, + round_up_to_step, +) +from suncore.core.config import OperationConfig +from suncore.core.decisions import OperatingMode +from suncore.core.identity import battery_identity, battery_identity_token +from suncore.core.site import BatteryConfig, EntityRef, GridConfig, SiteConfig + +limit = st.one_of(st.none(), st.floats(min_value=0, max_value=20_000, allow_nan=False)) +soc = st.one_of(st.none(), st.floats(min_value=0, max_value=100, allow_nan=False)) + + +@st.composite +def actions(draw: st.DrawFn) -> BatteryAction: + values = { + "max_charge_w": draw(limit), + "max_discharge_w": draw(limit), + "min_soc_pct": draw(soc), + "grid_charge_w": draw(limit), + } + if all(v is None for v in values.values()): + values["min_soc_pct"] = 20.0 + grid, cap = values["grid_charge_w"], values["max_charge_w"] + if grid is not None and cap is not None and grid > cap: + values["grid_charge_w"] = cap + return BatteryAction(**values) + + +def test_every_field_has_a_capability() -> None: + assert set(FIELD_CAPABILITY) == set(BATTERY_ACTION_FIELDS) + assert BatteryCapability.HARDWARE_FALLBACK not in FIELD_CAPABILITY.values() + + +def test_an_empty_action_is_rejected_release_means_baseline() -> None: + with pytest.raises(ValidationError): + BatteryAction() + + +@given(actions(), actions()) +def test_none_is_the_baseline_and_set_fields_win( + action: BatteryAction, base: BatteryAction +) -> None: + resolved = resolve_battery_action(action, base) + for name, value in action_fields(action).items(): + if name in ("max_charge_w", "grid_charge_w") and value is None: + continue # the cap/forced-power pair keeps the validator (see the test below) + expected = value if value is not None else getattr(base, name) + assert getattr(resolved, name) == expected + + +@given(actions()) +def test_resolving_without_a_baseline_changes_nothing(action: BatteryAction) -> None: + assert resolve_battery_action(action, None) == action + + +def test_an_inherited_cap_below_the_forced_power_is_dropped() -> None: + resolved = resolve_battery_action( + BatteryAction(grid_charge_w=3000), BatteryAction(max_charge_w=1000, min_soc_pct=10) + ) + assert resolved == BatteryAction(grid_charge_w=3000, min_soc_pct=10) + + +def test_an_inherited_forced_power_above_the_requested_cap_is_lowered() -> None: + resolved = resolve_battery_action(BatteryAction(max_charge_w=0), BatteryAction(grid_charge_w=1)) + assert resolved == BatteryAction(max_charge_w=0, grid_charge_w=0) + + +@given(actions(), actions()) +def test_the_inherited_values_never_exceed_the_set_ones( + action: BatteryAction, base: BatteryAction +) -> None: + resolved = resolve_battery_action(action, base) + if action.max_charge_w is not None: + assert resolved.max_charge_w == action.max_charge_w + if action.grid_charge_w is not None: + assert resolved.grid_charge_w == action.grid_charge_w + + +@given(st.floats(0, 100), st.sampled_from([None, 1.0, 5.0, 10.0])) +def test_rounding_never_lowers_a_floor(value: float, step: float | None) -> None: + rounded = round_up_to_step(value, step) + assert rounded >= value - 1e-6 + if step is not None: + assert rounded - value < step + 1e-6 + + +def test_field_range_contains() -> None: + r = FieldRange(5, 100, 5) + assert r.contains(5) + assert r.contains(100) + assert not r.contains(4.9) + + +def _site(soc: str = "sensor.soc", power: str = "sensor.bat") -> SiteConfig: + return SiteConfig( + grid=GridConfig(power=EntityRef(entity_id="sensor.grid")), + battery=BatteryConfig(power=EntityRef(entity_id=power), soc=EntityRef(entity_id=soc)), + ) + + +def _battery(**kw: object) -> BatterySettings: + base: dict[str, object] = { + "adapter_template_id": "kostal.plenticore_rest", + "entities": {"min_soc_number": EntityRef(entity_id="number.min_soc")}, + } + return BatterySettings.model_validate(base | kw) + + +def test_observe_only_has_no_identity() -> None: + assert battery_identity(BatterySettings(), _site()) is None + assert battery_identity_token(None, _site()) is None + + +def test_identity_changes_with_template_entities_site_entities_and_modbus_unit() -> None: + base = battery_identity_token(_battery(), _site()) + assert base is not None + assert battery_identity_token(_battery(), _site()) == base + assert battery_identity_token(_battery(adapter_template_id="generic.battery"), _site()) != base + other_entity = {"min_soc_number": EntityRef(entity_id="number.other")} + assert battery_identity_token(_battery(entities=other_entity), _site()) != base + assert battery_identity_token(_battery(), _site(soc="sensor.soc2")) != base + assert battery_identity_token(_battery(), _site(power="sensor.bat2")) != base + link = ModbusLink(slave=71, byte_order=ModbusByteOrder.LITTLE) + with_link = battery_identity_token(_battery(modbus=link), _site()) + assert with_link != base + other_unit = battery_identity_token( + _battery(modbus=link.model_copy(update={"slave": 1})), _site() + ) + assert other_unit != with_link + + +def test_settings_are_not_identity() -> None: + base = battery_identity_token(_battery(), _site()) + link = ModbusLink(slave=71, byte_order=ModbusByteOrder.LITTLE) + a = battery_identity_token(_battery(modbus=link, fallback_measured=False), _site()) + b = battery_identity_token( + _battery( + modbus=link.model_copy(update={"byte_order": ModbusByteOrder.BIG}), + fallback_measured=True, + ), + _site(), + ) + assert a == b + assert base != a + inverted = _site().model_copy( + update={ + "battery": BatteryConfig( + power=EntityRef(entity_id="sensor.bat", invert_sign=True), + soc=EntityRef(entity_id="sensor.soc"), + min_soc_pct=20, + ) + } + ) + assert battery_identity_token(_battery(), inverted) == base + + +def test_modbus_link_bounds() -> None: + with pytest.raises(ValidationError): + ModbusLink(slave=71, byte_order=ModbusByteOrder.LITTLE, heartbeat_s=30) # > timeout / 3 + with pytest.raises(ValidationError): + ModbusLink(slave=0, byte_order=ModbusByteOrder.LITTLE) + with pytest.raises(ValidationError): + ModbusLink.model_validate({"slave": 71}) # the byte order is never guessed + with pytest.raises(ValidationError): + BatterySettings(modbus=ModbusLink(slave=71, byte_order=ModbusByteOrder.BIG)) + + +def test_operation_battery_mode_defaults_to_shadow_and_old_documents_load() -> None: + assert OperationConfig().battery_mode is OperatingMode.SHADOW + old = OperationConfig.model_validate({"schema_version": 1, "mode": "automatic"}) + assert old.battery_mode is OperatingMode.SHADOW + raised = old.model_copy(update={"battery_mode": OperatingMode.ASSISTED}) + assert raised.without_battery_mode().battery_mode is OperatingMode.SHADOW + assert old.without_battery_mode() is old diff --git a/tests/storage/test_config_sections.py b/tests/storage/test_config_sections.py index bd63283..916496b 100644 --- a/tests/storage/test_config_sections.py +++ b/tests/storage/test_config_sections.py @@ -42,7 +42,7 @@ PowerModel, PowerModelKind, ) -from suncore.core.site import EntityRef, GridConfig, PvArray, SiteConfig +from suncore.core.site import BatteryConfig, EntityRef, GridConfig, PvArray, SiteConfig from suncore.core.tariff import NIGHT_WINDOW from suncore.storage import ( ConfigCorruptError, @@ -704,3 +704,115 @@ async def test_put_operation_is_stored_as_given(db: Database) -> None: assert isinstance(op, OperationConfig) assert op.mode is AUTO assert op.device_modes == {"a": AUTO} + + +# --- battery identity rule (ADR-0013 decision 6) --------------------------------------- + + +def _battery_settings(entity: str = "number.min_soc") -> BatterySettings: + return BatterySettings( + adapter_template_id="kostal.plenticore_rest", + entities={"min_soc_number": EntityRef(entity_id=entity)}, + ) + + +async def _battery_assisted(store: ConfigStore) -> None: + await store.put("site", make_site()) + await store.put("battery", _battery_settings()) + await store.put("operation", OperationConfig(battery_mode=OperatingMode.ASSISTED)) + + +async def _battery_mode(store: ConfigStore) -> OperatingMode: + op = await store.get("operation") + assert isinstance(op, OperationConfig) + return op.battery_mode + + +async def test_battery_setting_change_keeps_the_battery_mode(db: Database) -> None: + store = ConfigStore(db) + await _battery_assisted(store) + await store.put( + "battery", _battery_settings().model_copy(update={"strategy": BatteryStrategy.PREFER_FULL}) + ) + assert await _battery_mode(store) is OperatingMode.ASSISTED + + +async def test_battery_remapped_falls_back_to_shadow(db: Database) -> None: + store = ConfigStore(db) + await _battery_assisted(store) + await store.put("battery", _battery_settings("number.other")) + assert await _battery_mode(store) is OperatingMode.SHADOW + + +async def test_site_battery_entities_are_part_of_the_identity(db: Database) -> None: + store = ConfigStore(db) + await _battery_assisted(store) + await store.put("site", make_site("sensor.other_grid")) # grid only: same battery + assert await _battery_mode(store) is OperatingMode.ASSISTED + moved = make_site().model_copy( + update={ + "battery": BatteryConfig( + power=EntityRef(entity_id="sensor.bat_power_2"), + soc=EntityRef(entity_id="sensor.bat_soc"), + ) + } + ) + await store.put("site", moved) + assert await _battery_mode(store) is OperatingMode.SHADOW + + +async def test_import_always_resets_the_battery_to_shadow(db: Database) -> None: + store = ConfigStore(db) + await _battery_assisted(store) + exported = await store.export_json() + await store.import_json(exported) + assert await _battery_mode(store) is OperatingMode.SHADOW + + +async def test_restore_operation_keeps_the_battery_mode_only_for_the_same_battery( + db: Database, +) -> None: + store = ConfigStore(db) + await _battery_assisted(store) + await store.put("operation", OperationConfig()) # history: battery assisted + (entry,) = [h for h in await store.history("operation") if h.body["battery_mode"] != "shadow"] + restored = await store.restore("operation", entry.id) + assert isinstance(restored, OperationConfig) + assert restored.battery_mode is OperatingMode.ASSISTED + # Re-mapped meanwhile: the old grant does not apply to the new battery. + await store.put("operation", OperationConfig()) + await store.put("battery", _battery_settings("number.other")) + (entry,) = [ + h for h in await store.history("operation") if h.body.get("battery_mode") == "assisted" + ][:1] + restored = await store.restore("operation", entry.id) + assert isinstance(restored, OperationConfig) + assert restored.battery_mode is OperatingMode.SHADOW + + +async def test_restore_operation_without_a_battery_record_is_conservative(db: Database) -> None: + store = ConfigStore(db) + await store.put("site", make_site()) + await store.put("battery", _battery_settings()) + await db.execute( + "INSERT INTO config_history (section, schema_version, body, replaced_at) " + "VALUES ('operation', 1, ?, 't')", + (OperationConfig(battery_mode=OperatingMode.AUTOMATIC).model_dump_json(),), + ) + (entry,) = await store.history("operation") + restored = await store.restore("operation", entry.id) + assert isinstance(restored, OperationConfig) + assert restored.battery_mode is OperatingMode.SHADOW + + +async def test_restore_operation_for_an_observe_only_battery_is_shadow(db: Database) -> None: + store = ConfigStore(db) + await _battery_assisted(store) + await store.put("operation", OperationConfig()) + await store.put("battery", BatterySettings()) # observe only now + (entry,) = [ + h for h in await store.history("operation") if h.body.get("battery_mode") == "assisted" + ] + restored = await store.restore("operation", entry.id) + assert isinstance(restored, OperationConfig) + assert restored.battery_mode is OperatingMode.SHADOW From 65e68d9c805065b560f19e44082d44abd86fff81 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 18:27:49 +0000 Subject: [PATCH 02/16] feat(safety): battery invariants B1-B6, B9 and the battery watchdog as pure functions (WP10) - safety/battery.py: BatteryActuator protocol (capabilities, live ranges, settle, heartbeat, hardware-fallback prepare), BatteryContext from the resolved target, live flows, the band of a fresh plan interval, the live price and the import limit - B1 floor never below the reserve nor the user's own floor (rounded up to the step), B2 grid charging bounded by battery, adapter, band and import headroom (0 when any bound is unknown), B3 only from a fresh planned interval inside the policy at the live price and below max SoC, B4 discharge lock only when planned, B5 import limit, B6 live ranges and no cap above the baseline, B9 capabilities; BatteryWatch for a frozen battery power / SoC (B8) - property tests (hypothesis) for every claim; catalogue keys en/de - the gate still rejects battery intents (wired in the next step) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- frontend/src/lib/i18n/locales/de.json | 20 + frontend/src/lib/i18n/locales/en.json | 20 + suncore/safety/battery.py | 585 ++++++++++++++++++++++++ tests/safety/test_battery_invariants.py | 529 +++++++++++++++++++++ 4 files changed, 1154 insertions(+) create mode 100644 suncore/safety/battery.py create mode 100644 tests/safety/test_battery_invariants.py diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index 3e60bf7..8663952 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -579,6 +579,7 @@ "safety.release_pending": "Nicht geschrieben: Das Gerät wird gleich in den vorherigen Zustand zurückgesetzt.", "safety.superseded": "Schreiben nicht bestätigt: Das Gerät wurde inzwischen in den vorherigen Zustand zurückgesetzt.", "safety.battery_reserve": "Nicht eingeschaltet: Der Akku entlädt bei {soc_pct} % (Reserve {reserve_pct} %).", + "safety.battery_range_unknown": "Der erlaubte Bereich von {field} ist unbekannt (Entität nicht verfügbar); nichts geschrieben.", "safety.climate_off": "Nicht eingeschaltet: Das Gerät ist aus und Einschalten ist für dieses Gerät nicht erlaubt.", "safety.comfort_band": "Sollwert {setpoint_c} °C liegt außerhalb des Komfortbands {min_c}–{max_c} °C.", "safety.comfort_band_missing": "Kein Komfortband konfiguriert; der Sollwert wurde nicht geschrieben.", @@ -899,6 +900,25 @@ "api.validation.import_formula_all_in": "Der Tarif {template_id} liefert bereits Endpreise inklusive Gebühren und Steuern; eine Preisformel würde sie doppelt zählen.", "tariff.import.tou_stored": "Ein Zeittarif (HT/NT) ist gespeichert. Er lässt sich in einer späteren Version hier bearbeiten; Speichern lässt ihn unverändert, solange du keine andere Art wählst.", "safety.battery_not_supported": "Batteriesteuerung ist noch nicht verfügbar; es wurde nichts geschrieben.", + "safety.battery_model_missing": "Kein Akkumodell (Kapazität, Grenzen, Reserve) konfiguriert: der Akku wird nur beobachtet.", + "safety.battery_min_soc_below_reserve": "Mindest-Ladestand {min_soc_pct} % liegt unter der Reserve von {reserve_pct} %.", + "safety.battery_min_soc_below_baseline": "Mindest-Ladestand {min_soc_pct} % liegt unter deiner eigenen Wechselrichter-Einstellung von {baseline_pct} %.", + "safety.battery_write_no_change": "Der Akku hat diese Grenzen schon; nichts geschrieben.", + "safety.battery_capability_missing": "Der Akku-Adapter kann {field} nicht setzen; nichts geschrieben.", + "safety.battery_out_of_range": "{field} = {value} liegt außerhalb des erlaubten Bereichs {low}–{high}.", + "safety.battery_above_baseline": "{field} = {value} W läge über deiner eigenen Einstellung von {baseline} W; SunCore schränkt nur ein.", + "safety.battery_grid_charge_unplanned": "Das aktuelle Planintervall erlaubt kein Netzladen.", + "safety.battery_grid_charge_policy": "Netzladen ist jetzt nach deiner Preisgrenze oder deinem Zeitplan nicht erlaubt (aktueller Preis {price}).", + "safety.battery_grid_charge_bound": "Netzladen mit {grid_charge_w} W liegt über den erlaubten {bound_w} W (Akku, Wechselrichter, Plan oder Bezugsgrenze).", + "safety.battery_grid_unknown": "Netz- oder Akkuleistung ist unbekannt: keine Akku-Aktion, die Netzbezug verursachen kann.", + "safety.battery_plan_stale": "Der Plan ist zu alt für diese Akku-Aktion.", + "safety.battery_soc_unknown": "Der Ladestand des Akkus ist unbekannt.", + "safety.battery_soc_frozen": "Der Ladestand bleibt bei {soc_pct} %, obwohl {moved_pct} % der Kapazität geflossen sind: Akkusteuerung pausiert.", + "safety.battery_full": "Der Akku steht bei {soc_pct} %, sein Maximum ist {max_soc_pct} %: kein Netzladen.", + "safety.battery_frozen": "Die Akkuleistung bleibt bei {battery_w} W, während sich die Netzleistung ändert: Akkusteuerung pausiert.", + "safety.battery_import_limit_unknown": "Netzladen braucht eine eingestellte Bezugsgrenze.", + "safety.battery_import_limit": "Das Haus würde {projected_w} W beziehen, über der Bezugsgrenze von {limit_w} W.", + "safety.battery_unplanned_import": "Den Akku zurückzuhalten würde Netzbezug verursachen, und der Plan sieht das nicht vor.", "action.battery": "Batterie-Limits setzen", "api.validation.forecast_workday_domain": "{entity_id} ist kein Binärsensor. Wähle den Binärsensor der Workday-Integration.", "api.validation.forecast_weather_domain": "{entity_id} ist keine Wetter-Entität.", diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index 06adb76..ed3461e 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -579,6 +579,7 @@ "safety.release_pending": "Not written: the device is about to be returned to its previous state.", "safety.superseded": "Write not confirmed: the device was returned to its previous state in the meantime.", "safety.battery_reserve": "Not switched on: the battery is discharging at {soc_pct} % (reserve {reserve_pct} %).", + "safety.battery_range_unknown": "The allowed range of {field} is unknown (entity unavailable); nothing was written.", "safety.climate_off": "Not switched on: the unit is off and switching on is not allowed for this device.", "safety.comfort_band": "Set-point {setpoint_c} °C is outside the comfort band {min_c}–{max_c} °C.", "safety.comfort_band_missing": "No comfort band is configured; the set-point was not written.", @@ -899,6 +900,25 @@ "api.validation.import_formula_all_in": "The tariff {template_id} already delivers end prices including fees and taxes; a price formula would count them twice.", "tariff.import.tou_stored": "A time-of-use tariff (HT/NT) is stored. It can be edited here in a later version; saving keeps it unchanged unless you choose another kind.", "safety.battery_not_supported": "Battery control is not available yet; nothing was written.", + "safety.battery_model_missing": "No battery model (capacity, limits, reserve) is configured: the battery is only observed.", + "safety.battery_min_soc_below_reserve": "Minimum state of charge {min_soc_pct} % is below the reserve of {reserve_pct} %.", + "safety.battery_min_soc_below_baseline": "Minimum state of charge {min_soc_pct} % is below your own inverter setting of {baseline_pct} %.", + "safety.battery_write_no_change": "The battery already holds these limits; nothing was written.", + "safety.battery_capability_missing": "The battery adapter cannot set {field}; nothing was written.", + "safety.battery_out_of_range": "{field} = {value} is outside the allowed range {low}–{high}.", + "safety.battery_above_baseline": "{field} = {value} W would be above your own setting of {baseline} W; SunCore only restricts.", + "safety.battery_grid_charge_unplanned": "The current plan interval does not allow grid charging.", + "safety.battery_grid_charge_policy": "Grid charging is not allowed now by your price level or schedule (live price {price}).", + "safety.battery_grid_charge_bound": "Grid charging with {grid_charge_w} W is above the allowed {bound_w} W (battery, inverter, plan or import limit).", + "safety.battery_grid_unknown": "Grid or battery power is unknown: no battery action that can cause import.", + "safety.battery_plan_stale": "The plan is too old to allow this battery action.", + "safety.battery_soc_unknown": "The battery's state of charge is unknown.", + "safety.battery_soc_frozen": "The state of charge has stayed at {soc_pct} % although {moved_pct} % of the capacity moved: battery control paused.", + "safety.battery_full": "The battery is at {soc_pct} %, its maximum is {max_soc_pct} %: no grid charging.", + "safety.battery_frozen": "The battery power has stayed at {battery_w} W while the grid power changed: battery control paused.", + "safety.battery_import_limit_unknown": "Grid charging needs a configured grid import limit.", + "safety.battery_import_limit": "The house would import {projected_w} W, above the import limit of {limit_w} W.", + "safety.battery_unplanned_import": "Holding the battery back would make the house import, and the plan does not ask for it.", "action.battery": "Set battery limits", "api.validation.forecast_workday_domain": "{entity_id} is not a binary sensor. Choose the binary sensor of the Workday integration.", "api.validation.forecast_weather_domain": "{entity_id} is not a weather entity.", diff --git a/suncore/safety/battery.py b/suncore/safety/battery.py new file mode 100644 index 0000000..ddd9840 --- /dev/null +++ b/suncore/safety/battery.py @@ -0,0 +1,585 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Battery invariants B1-B9 (ADR-0013) as pure functions, and the battery actuator protocol. + +The battery is the first asset SunCore writes to that can **cause grid import on purpose** +(planned grid charging, a discharge lock) and that guards energy the user relies on (the +reserve). ADR-0013 replaces the Phase 3 rule "no SunCore-caused import" for the battery - and +only for the battery - by a bounded exception: a battery action that can cause import is +accepted only when a *fresh* plan interval covering ``now`` explicitly allows it and every +live bound holds at execution time. Devices keep the Phase 3 rule unchanged. + +Everything here is pure: the gate builds a :class:`BatteryContext` from the intent, the +adapter's capabilities and live ranges, the takeover baseline, the live flows, the plan band +covering ``now``, the live import price and the battery configuration, and +:func:`evaluate_battery` returns every violation (empty = may be written). :func:`lease_violations` +is the subset the gate re-checks every tick while it holds an accepted battery state (the +lease, ADR-0013 decision 5): when the plan interval ends, the price leaves the policy, the SoC +reaches the maximum or the import limit would break, the lease ends and the gate restores the +baseline. Property tests: ``tests/safety/test_battery_invariants.py``. + +Signs and units per ``core/units.py``: grid + = import, battery + = charging, W and %. +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from dataclasses import dataclass, field +from datetime import datetime, timedelta, tzinfo +from typing import Final, Protocol, runtime_checkable + +from suncore.core.balance import FlowSnapshot +from suncore.core.battery import ( + BATTERY_ACTION_FIELDS, + FIELD_CAPABILITY, + BatteryAction, + BatteryCapability, + BatteryModel, + BatteryRanges, + GridChargePolicy, + action_fields, + round_up_to_step, +) +from suncore.core.control import BatteryBand, Plan +from suncore.core.decisions import Reason +from suncore.core.signals import Quality +from suncore.safety.actuator import Actuator + +POWER_TOLERANCE_W: Final = 1.0 +"""Read-back and bound tolerance for battery powers (the adapters write whole watts).""" +SOC_TOLERANCE_PCT: Final = 0.01 +PLAN_FRESH_INTERVALS: Final = 2 +"""A plan is fresh while it was created at most this many of its intervals ago (ADR-0013).""" +DEFAULT_INTERVAL: Final = timedelta(minutes=15) + +REASON_BATTERY_MODEL_MISSING: Final = Reason(key="safety.battery_model_missing") +REASON_BATTERY_NO_CHANGE: Final = Reason(key="safety.battery_write_no_change") + + +# --- the battery actuator -------------------------------------------------------------------- + + +@runtime_checkable +class BatteryActuator(Actuator, Protocol): + """An :class:`Actuator` for the battery asset (``suncore.devices.battery``). + + ``apply`` receives an intent whose ``BatteryAction`` the gate already resolved (``None`` = + baseline) and quantised; ``read_back`` reports the adapter's readable limits as a + ``BatteryAction`` (fields it cannot read are ``None``). Only the gate calls ``apply``, + ``release``, ``prepare`` and ``heartbeat`` (``tests/safety/test_boundary.py``). + """ + + @property + def capabilities(self) -> frozenset[BatteryCapability]: + """What the adapter can execute (ADR-0013 decision 1).""" + ... + + @property + def settle_s(self) -> float: + """Delay before the read-back (Kostal REST: one poll interval of 30 s plus margin).""" + ... + + @property + def heartbeat_s(self) -> float | None: + """Re-write period of an accepted state while the lease holds (``None`` = none).""" + ... + + def ranges(self) -> BatteryRanges: + """The live ranges of the writable limits (from the entities' attributes).""" + ... + + def refusal(self) -> Reason | None: + """A precondition that forbids every write right now (e.g. Kostal register 1080 is not + ``0x02``: external battery management is off); ``None`` = may write.""" + ... + + def prepared(self) -> bool: + """The hardware fallback is in place and confirmed by a read-back (``True`` for + adapters without one).""" + ... + + async def prepare(self) -> None: + """Write the hardware fallback (Kostal §3.5: 1284/1286 = own limits, 1288 = timeout) + before the first limit; the gate reads back with :meth:`prepared`.""" + ... + + async def heartbeat(self) -> None: + """Re-write the last applied state (idempotent; called only while the lease holds).""" + ... + + +# --- context --------------------------------------------------------------------------------- + + +@dataclass(frozen=True, slots=True) +class BatteryLive: + """The live site values the battery invariants use (``None`` = unknown or not ``OK``).""" + + soc_pct: float | None = None + grid_w: float | None = None + battery_w: float | None = None + + @classmethod + def of(cls, flows: FlowSnapshot | None) -> BatteryLive: + if flows is None: + return cls() + + def ok(value: float | None, quality: Quality) -> float | None: + return value if quality is Quality.OK else None + + return cls( + soc_pct=ok(flows.battery_soc_pct.value, flows.battery_soc_pct.quality), + grid_w=ok(flows.grid_w.value, flows.grid_w.quality), + battery_w=ok(flows.battery_w.value, flows.battery_w.quality), + ) + + @property + def house_net_w(self) -> float | None: + """House minus PV (``grid - battery``): what the grid supplies without the battery.""" + if self.grid_w is None or self.battery_w is None: + return None + return self.grid_w - self.battery_w + + @property + def deficit_w(self) -> float | None: + """The power the battery would cover now (``max(0, house - pv)``).""" + net = self.house_net_w + return None if net is None else max(0.0, net) + + +@dataclass(frozen=True, slots=True) +class BatteryContext: + """Everything the battery invariants look at for one action (or one lease renewal).""" + + requested: BatteryAction + """The intent's action as the controller sent it (``None`` fields = baseline).""" + target: BatteryAction + """``requested`` resolved against the baseline and quantised: what would be written.""" + capabilities: frozenset[BatteryCapability] + ranges: BatteryRanges + model: BatteryModel | None + reserve_pct: float | None + """``core.battery.effective_reserve_pct`` (``None`` without a model).""" + live: BatteryLive + band: BatteryBand | None + """The battery band of the plan interval covering ``now`` (``None`` = no interval).""" + plan_fresh: bool + policy: GridChargePolicy + """The effective grid-charge policy (the battery policy with the goals schedule, computed + by the composition root).""" + import_price: float | None + """The **live** import price now (currency/kWh; ``None`` = unknown).""" + tz: tzinfo + import_limit_w: float | None + reserve_w: float + """``ControlSettings.reserve_w``: kept free below the import limit.""" + now: datetime + baseline: BatteryAction | None = None + + +def plan_band(plan: Plan, now: datetime) -> tuple[BatteryBand | None, bool]: + """The band of the interval covering ``now`` and whether the plan is fresh. + + Fresh = created at most :data:`PLAN_FRESH_INTERVALS` intervals (of the covering interval's + length) before ``now``. ``Plan.default()`` (no intervals, no ``created_at``) gives no band. + """ + interval = plan.interval_at(now) + if interval is None or plan.created_at is None: + return None, False + length = interval.end - interval.start + if length <= timedelta(0): # pragma: no cover - the plan validator forbids it + length = DEFAULT_INTERVAL + fresh = timedelta(0) <= now - plan.created_at <= PLAN_FRESH_INTERVALS * length + return interval.battery, fresh + + +def quantise(action: BatteryAction, ranges: BatteryRanges) -> BatteryAction: + """Snap ``min_soc_pct`` **up** to the entity step (ADR-0013: Kostal step 5, rounded up). + + Powers are not snapped here: the adapters write whole watts and the gate compares with + :data:`POWER_TOLERANCE_W`. + """ + if action.min_soc_pct is None: + return action + soc_range = ranges.min_soc_pct + if soc_range is None or soc_range.step is None: + return action + rounded = min(100.0, round_up_to_step(action.min_soc_pct, soc_range.step, soc_range.low)) + if math.isclose(rounded, action.min_soc_pct, abs_tol=1e-9): + return action + return action.model_copy(update={"min_soc_pct": rounded}) + + +# --- derived facts --------------------------------------------------------------------------- + + +def grid_charge_w(ctx: BatteryContext) -> float: + """The forced grid-charge power the target asks for (0 = none).""" + return ctx.target.grid_charge_w or 0.0 + + +def is_discharge_lock(ctx: BatteryContext) -> bool: + """The requested limits keep the battery from covering the house (ADR-0013 decision 4). + + ``max_discharge_w`` below the current house deficit, or ``min_soc_pct`` at or above the + live SoC. Unknown live values count as a lock (the conservative direction). + """ + requested = ctx.requested + if requested.max_discharge_w is not None: + deficit = ctx.live.deficit_w + if deficit is None or requested.max_discharge_w + POWER_TOLERANCE_W < deficit: + return True + if requested.min_soc_pct is not None: + soc = ctx.live.soc_pct + if soc is None or requested.min_soc_pct >= soc - SOC_TOLERANCE_PCT: + return True + return False + + +def can_cause_import(ctx: BatteryContext) -> bool: + """Grid charging or a discharge lock: the action may make the house import.""" + return grid_charge_w(ctx) > 0 or is_discharge_lock(ctx) + + +def projected_import_w(ctx: BatteryContext) -> float | None: + """Import under the action, assuming the battery covers nothing (conservative). + + ``max(0, house - pv) + grid_charge_w``; ``None`` when grid or battery power is unknown. + """ + deficit = ctx.live.deficit_w + return None if deficit is None else deficit + grid_charge_w(ctx) + + +def grid_charge_bound_w(ctx: BatteryContext) -> float | None: + """B2: ``min(model max charge, adapter limit, band.grid_charge_max_w, import headroom)``. + + ``None`` when any bound is unknown (then no grid charging at all). Import headroom = + ``import_limit_w - max(0, house - pv) - reserve_w`` (the current import without the + battery, so a battery already charging from the grid does not count twice). + """ + model, band, limit = ctx.model, ctx.band, ctx.import_limit_w + adapter = ctx.ranges.grid_charge_w + deficit = ctx.live.deficit_w + if ( + model is None + or band is None + or band.grid_charge_max_w is None + or adapter is None + or limit is None + or deficit is None + ): + return None + headroom = limit - deficit - ctx.reserve_w + return max(0.0, min(model.max_charge_w, adapter.high, band.grid_charge_max_w, headroom)) + + +# --- invariants ------------------------------------------------------------------------------ + + +def check_capabilities(ctx: BatteryContext) -> Reason | None: + """B9: no field the adapter cannot execute.""" + for name, value in action_fields(ctx.requested).items(): + if value is not None and FIELD_CAPABILITY[name] not in ctx.capabilities: + return Reason(key="safety.battery_capability_missing", args={"field": name}) + return None + + +def check_model(ctx: BatteryContext) -> Reason | None: + """Without a battery model (and so without a reserve) the battery is observe-only.""" + if ctx.model is None or ctx.reserve_pct is None: + return REASON_BATTERY_MODEL_MISSING + return None + + +def check_min_soc(ctx: BatteryContext) -> Reason | None: + """B1: a requested floor (after rounding up) is never below the reserve nor the baseline. + + Below the reserve SunCore would allow a discharge into the user's backup energy; below the + baseline it would allow more discharge than the user's own inverter setting (SunCore's + limits only ever restrict). Together with B6 (no cap above the baseline) this is "the + battery is never discharged below the reserve by SunCore" (BRIEF §5). + """ + value = ctx.target.min_soc_pct if ctx.requested.min_soc_pct is not None else None + if value is None or ctx.reserve_pct is None: + return None + if value < ctx.reserve_pct - SOC_TOLERANCE_PCT: + return Reason( + key="safety.battery_min_soc_below_reserve", + args={"min_soc_pct": round(value, 1), "reserve_pct": round(ctx.reserve_pct, 1)}, + ) + base = None if ctx.baseline is None else ctx.baseline.min_soc_pct + if base is not None and value < base - SOC_TOLERANCE_PCT: + return Reason( + key="safety.battery_min_soc_below_baseline", + args={"min_soc_pct": round(value, 1), "baseline_pct": round(base, 1)}, + ) + return None + + +def check_ranges(ctx: BatteryContext) -> Reason | None: + """B6: every requested value inside the adapter's live range and the battery's limits; + a power cap never above the baseline (SunCore never widens the user's own limits).""" + model = ctx.model + for name in BATTERY_ACTION_FIELDS: + if getattr(ctx.requested, name) is None: + continue + value = getattr(ctx.target, name) + assert value is not None + allowed = ctx.ranges.of(name) + if allowed is None: + return Reason(key="safety.battery_range_unknown", args={"field": name}) + tolerance = SOC_TOLERANCE_PCT if name == "min_soc_pct" else POWER_TOLERANCE_W + if not allowed.contains(value, tolerance): + return Reason( + key="safety.battery_out_of_range", + args={ + "field": name, + "value": round(value, 1), + "low": round(allowed.low, 1), + "high": round(allowed.high, 1), + }, + ) + if model is not None and name != "min_soc_pct": + cap = model.max_discharge_w if name == "max_discharge_w" else model.max_charge_w + if value > cap + POWER_TOLERANCE_W: + return Reason( + key="safety.battery_out_of_range", + args={"field": name, "value": round(value, 1), "low": 0, "high": round(cap)}, + ) + base = None if ctx.baseline is None else getattr(ctx.baseline, name) + if ( + name in ("max_charge_w", "max_discharge_w") + and base is not None + and value > base + POWER_TOLERANCE_W + ): + return Reason( + key="safety.battery_above_baseline", + args={"field": name, "value": round(value), "baseline": round(base)}, + ) + return None + + +def check_grid_charge(ctx: BatteryContext) -> Reason | None: # noqa: PLR0911 - one return per rule + """B2 + B3: forced grid charging only from a fresh plan interval that allows it, inside the + grid-charge policy at the **live** price, below the maximum SoC and within every bound.""" + power = grid_charge_w(ctx) + if power <= 0: + return None + band = ctx.band + if band is None or band.grid_charge_max_w is None or band.grid_charge_max_w <= 0: + return Reason(key="safety.battery_grid_charge_unplanned") + if not ctx.plan_fresh: + return Reason(key="safety.battery_plan_stale") + if not ctx.policy.allows(ctx.now, ctx.import_price, ctx.tz): + price = ctx.import_price + return Reason( + key="safety.battery_grid_charge_policy", + args={"price": "unknown" if price is None else f"{price:.4f}"}, + ) + soc = ctx.live.soc_pct + if soc is None: + return Reason(key="safety.battery_soc_unknown") + model = ctx.model + if model is None: + return REASON_BATTERY_MODEL_MISSING + ceiling = min(band.max_soc_pct if band.max_soc_pct is not None else 100.0, model.max_soc_pct) + if soc >= ceiling - SOC_TOLERANCE_PCT: + return Reason( + key="safety.battery_full", args={"soc_pct": round(soc, 1), "max_soc_pct": ceiling} + ) + if ctx.import_limit_w is None: + return Reason(key="safety.battery_import_limit_unknown") + bound = grid_charge_bound_w(ctx) + if bound is None: + return Reason(key="safety.battery_grid_unknown") + if bound <= 0 or power > bound + POWER_TOLERANCE_W: + return Reason( + key="safety.battery_grid_charge_bound", + args={"grid_charge_w": round(power), "bound_w": round(bound)}, + ) + return None + + +def check_discharge_lock(ctx: BatteryContext) -> Reason | None: + """B4: a discharge lock only while a fresh plan interval carries ``discharge_lock``.""" + if not is_discharge_lock(ctx): + return None + band = ctx.band + if band is None or not band.discharge_lock: + return Reason(key="safety.battery_unplanned_import") + if not ctx.plan_fresh: + return Reason(key="safety.battery_plan_stale") + return None + + +def check_import_limit(ctx: BatteryContext) -> Reason | None: + """B5: the site import limit holds for every battery action that can cause import.""" + if not can_cause_import(ctx) or ctx.import_limit_w is None: + return None + projected = projected_import_w(ctx) + if projected is None: + return Reason(key="safety.battery_grid_unknown") + if projected > ctx.import_limit_w + POWER_TOLERANCE_W: + return Reason( + key="safety.battery_import_limit", + args={"projected_w": round(projected), "limit_w": round(ctx.import_limit_w)}, + ) + return None + + +STATE_CHECKS: Final = ( + check_capabilities, + check_model, + check_min_soc, + check_ranges, + check_grid_charge, + check_discharge_lock, + check_import_limit, +) +"""B1-B6 and B9: judged for every intent and re-judged for the lease every tick.""" + + +def evaluate_battery(ctx: BatteryContext) -> tuple[Reason, ...]: + """Every violated battery invariant (B1-B6, B9), in check order; empty = may be written. + + The write rate, write-on-change (B7) and the watchdog (B8) are judged by the gate, which + owns the runtime and the observed state. + """ + return tuple(r for r in (check(ctx) for check in STATE_CHECKS) if r is not None) + + +def lease_violations(ctx: BatteryContext) -> tuple[Reason, ...]: + """What ends the lease of an accepted state (re-checked every tick; ADR-0013 decision 5).""" + return evaluate_battery(ctx) + + +def same_state(a: BatteryAction | None, b: BatteryAction | None, fields: Sequence[str]) -> bool: + """Read-back comparison on ``fields`` (powers within 1 W, SoC within 0.01 %). + + A field the expected action sets must be read back with the same value; an unreadable + (``None``) observed value is a mismatch. + """ + if a is None or b is None: + return False + for name in fields: + want, got = getattr(a, name), getattr(b, name) + if want is None: + continue + if got is None: + return False + tolerance = SOC_TOLERANCE_PCT if name == "min_soc_pct" else POWER_TOLERANCE_W + if abs(want - got) > tolerance: + return False + return True + + +def readable_fields(capabilities: frozenset[BatteryCapability]) -> tuple[str, ...]: + """The action fields an adapter with ``capabilities`` writes and reads back.""" + return tuple(name for name in BATTERY_ACTION_FIELDS if FIELD_CAPABILITY[name] in capabilities) + + +# --- watchdog (B8) --------------------------------------------------------------------------- + + +@dataclass(slots=True) +class BatteryWatch: + """Hung-battery detection the site watchdog does not cover (B8). + + The site watchdog already pauses everything on an unavailable or invalid SoC/battery power + and on frozen PV in daylight. This adds, for the battery scope only: + + * **frozen battery power**: the battery power keeps one value of at least ``min_w`` for + ``frozen_s`` while the grid meter moves by more than ``grid_move_w`` (an inverter whose + battery reading hangs while the house changes); + * **frozen SoC**: the SoC keeps one value while the battery moved more than + ``soc_energy_pct`` of the capacity (a BMS/integration that stopped reporting). + + A fault pauses battery control and releases the battery; it clears when the values move. + """ + + frozen_s: float = 600.0 + min_w: float = 50.0 + grid_move_w: float = 500.0 + soc_energy_pct: float = 3.0 + _power_since: tuple[float, datetime] | None = None + _grid: list[tuple[datetime, float]] = field(default_factory=list) + _soc_since: tuple[float, datetime] | None = None + _energy_wh: float = 0.0 + _last: tuple[datetime, float] | None = None + + def reset(self) -> None: + self._power_since = None + self._grid = [] + self._soc_since = None + self._energy_wh = 0.0 + self._last = None + + def check(self, now: datetime, live: BatteryLive, capacity_wh: float | None) -> Reason | None: + """Feed one tick; the fault reason (``None`` = fine).""" + power, grid, soc = live.battery_w, live.grid_w, live.soc_pct + if power is None or grid is None: + self.reset() # the site watchdog judges missing values + return None + self._grid.append((now, grid)) + start = now - timedelta(seconds=self.frozen_s) + self._grid = [(t, g) for t, g in self._grid if t >= start] + if self._power_since is None or self._power_since[0] != power: + self._power_since = (power, now) + frozen_power = ( + abs(power) >= self.min_w + and (now - self._power_since[1]).total_seconds() >= self.frozen_s + ) + values = [g for t, g in self._grid if t >= self._power_since[1]] + if frozen_power and values and max(values) - min(values) > self.grid_move_w: + return Reason(key="safety.battery_frozen", args={"battery_w": round(power)}) + if self._last is not None: + dt_h = (now - self._last[0]).total_seconds() / 3600 + self._energy_wh += abs(self._last[1]) * max(0.0, dt_h) + self._last = (now, power) + if soc is None: + self._soc_since = None + self._energy_wh = 0.0 + return None + if self._soc_since is None or self._soc_since[0] != soc: + self._soc_since = (soc, now) + self._energy_wh = 0.0 + return None + if capacity_wh is not None and capacity_wh > 0: + moved_pct = 100 * self._energy_wh / capacity_wh + if moved_pct >= self.soc_energy_pct: + return Reason( + key="safety.battery_soc_frozen", + args={"soc_pct": round(soc, 1), "moved_pct": round(moved_pct, 1)}, + ) + return None + + +__all__ = [ + "PLAN_FRESH_INTERVALS", + "POWER_TOLERANCE_W", + "REASON_BATTERY_MODEL_MISSING", + "REASON_BATTERY_NO_CHANGE", + "STATE_CHECKS", + "BatteryActuator", + "BatteryContext", + "BatteryLive", + "BatteryWatch", + "can_cause_import", + "check_capabilities", + "check_discharge_lock", + "check_grid_charge", + "check_import_limit", + "check_min_soc", + "check_model", + "check_ranges", + "evaluate_battery", + "grid_charge_bound_w", + "grid_charge_w", + "is_discharge_lock", + "lease_violations", + "plan_band", + "projected_import_w", + "quantise", + "readable_fields", + "same_state", +] diff --git a/tests/safety/test_battery_invariants.py b/tests/safety/test_battery_invariants.py new file mode 100644 index 0000000..6985af5 --- /dev/null +++ b/tests/safety/test_battery_invariants.py @@ -0,0 +1,529 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Battery invariants B1-B6, B9 (ADR-0013) - property-based. + +Every property reads "if :func:`evaluate_battery` lets an action through, then ...": the +claims of the ADR's invariant table must hold for *any* combination of action, adapter, +baseline, live values, plan band, price and import limit hypothesis can construct. +""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import Any + +import pytest +from hypothesis import HealthCheck, Phase, assume, find, given, settings +from hypothesis import strategies as st + +from suncore.core.battery import ( + BatteryAction, + BatteryCapability, + BatteryModel, + BatteryRanges, + FieldRange, + GridChargePolicy, + resolve_battery_action, +) +from suncore.core.control import BatteryBand, Plan, PlanInterval +from suncore.core.tariff import WeeklySchedule +from suncore.safety.battery import ( + BatteryContext, + BatteryLive, + BatteryWatch, + can_cause_import, + evaluate_battery, + grid_charge_bound_w, + is_discharge_lock, + plan_band, + projected_import_w, + quantise, + same_state, +) + +NOW = datetime(2026, 10, 24, 2, 0, tzinfo=UTC) +ALL_CAPS = frozenset(BatteryCapability) + +power = st.floats(min_value=0, max_value=15_000, allow_nan=False) +maybe_power = st.one_of(st.none(), power) +pct = st.floats(min_value=0, max_value=100, allow_nan=False) +maybe_pct = st.one_of(st.none(), pct) + + +def rarely[T](draw: st.DrawFn, bad: st.SearchStrategy[T], good: st.SearchStrategy[T]) -> T: + """``bad`` one time in ten: the strategies stay mostly valid so that accepted actions are + common (every property is an implication "accepted => claim"), while each failure mode is + still explored.""" + return draw(bad) if draw(st.integers(0, 9)) == 0 else draw(good) + + +@st.composite +def actions(draw: st.DrawFn, *, grid: bool = False) -> BatteryAction: + values: dict[str, Any] = { + "max_charge_w": rarely(draw, maybe_power, st.none()), + "max_discharge_w": rarely(draw, maybe_power, st.sampled_from([None, 0.0])), + "min_soc_pct": rarely(draw, maybe_pct, st.one_of(st.none(), st.floats(20, 100))), + "grid_charge_w": draw(st.floats(1, 6000)) + if grid + else rarely(draw, maybe_power, st.one_of(st.none(), st.floats(0, 3000))), + } + if all(v is None for v in values.values()): + values["max_discharge_w"] = 0.0 + if values["grid_charge_w"] is not None and values["max_charge_w"] is not None: + values["grid_charge_w"] = min(values["grid_charge_w"], values["max_charge_w"]) + return BatteryAction(**values) + + +@st.composite +def ranges(draw: st.DrawFn) -> BatteryRanges: + def power_range() -> FieldRange | None: + return rarely( + draw, + st.one_of(st.none(), st.floats(100, 15_000).map(lambda h: FieldRange(0.0, h))), + st.just(FieldRange(0.0, 10_000.0)), + ) + + soc_range = rarely( + draw, + st.none(), + st.builds( + FieldRange, + st.sampled_from([0.0, 5.0]), + st.just(100.0), + st.sampled_from([None, 1.0, 5.0]), + ), + ) + return BatteryRanges( + max_charge_w=power_range(), + max_discharge_w=power_range(), + min_soc_pct=soc_range, + grid_charge_w=power_range(), + ) + + +@st.composite +def bands(draw: st.DrawFn) -> BatteryBand | None: + if draw(st.integers(0, 5)) == 0: + return None + grid = rarely(draw, st.one_of(st.none(), power), st.floats(2000, 5000)) + max_soc = draw(st.one_of(st.none(), st.floats(50, 100))) + return BatteryBand( + grid_charge_max_w=grid, + discharge_lock=rarely(draw, st.just(False), st.just(True)), + min_soc_pct=None, + max_soc_pct=max_soc, + ) + + +@st.composite +def contexts(draw: st.DrawFn, *, grid: bool = False) -> BatteryContext: + model = BatteryModel( + capacity_wh=10_000, + max_charge_w=draw(st.floats(1000, 12_000)), + max_discharge_w=draw(st.floats(1000, 12_000)), + reserve_pct=draw(st.floats(0, 15)), + bms_drift_margin_pct=draw(st.floats(0, 5)), + max_soc_pct=draw(st.floats(60, 100)), + ) + reserve = model.min_soc_pct + draw(st.sampled_from([0.0, 5.0])) + requested = draw(actions(grid=grid)) + baseline = rarely(draw, actions(), st.none()) + rng = draw(ranges()) + target = quantise(resolve_battery_action(requested, baseline), rng) + policy = rarely( + draw, + st.sampled_from( + [ + GridChargePolicy(), + GridChargePolicy(enabled=True, schedule=WeeklySchedule.daily("22:00", "06:00")), + ] + ), + st.just(GridChargePolicy(enabled=True, max_price=0.20)), + ) + caps = rarely(draw, st.frozensets(st.sampled_from(list(BatteryCapability))), st.just(ALL_CAPS)) + return BatteryContext( + requested=requested, + target=target, + capabilities=caps, + ranges=rng, + model=model if draw(st.integers(0, 9)) else None, + reserve_pct=reserve, + live=BatteryLive( + soc_pct=rarely(draw, maybe_pct, st.floats(10, 60)), + grid_w=rarely( + draw, st.one_of(st.none(), st.floats(-10_000, 20_000)), st.floats(-3000, 3000) + ), + battery_w=rarely( + draw, st.one_of(st.none(), st.floats(-8000, 8000)), st.floats(-3000, 3000) + ), + ), + band=draw(bands()), + plan_fresh=rarely(draw, st.just(False), st.just(True)), + policy=policy, + import_price=rarely(draw, st.one_of(st.none(), st.floats(-0.5, 0.8)), st.floats(-0.1, 0.2)), + tz=UTC, + import_limit_w=rarely( + draw, st.one_of(st.none(), st.floats(0, 30_000)), st.floats(8000, 30_000) + ), + reserve_w=100.0, + now=NOW + timedelta(hours=draw(st.integers(0, 23))), + baseline=baseline, + ) + + +def accepted(ctx: BatteryContext) -> bool: + return evaluate_battery(ctx) == () + + +PROPERTY = settings( + max_examples=150, deadline=None, suppress_health_check=[HealthCheck.filter_too_much] +) + + +@PROPERTY +@given(contexts()) +def test_b9_no_field_without_its_capability(ctx: BatteryContext) -> None: + assume(accepted(ctx)) + names = { + "max_charge_w": BatteryCapability.CHARGE_LIMIT, + "max_discharge_w": BatteryCapability.DISCHARGE_LIMIT, + "min_soc_pct": BatteryCapability.MIN_SOC, + "grid_charge_w": BatteryCapability.GRID_CHARGE, + } + for name, cap in names.items(): + if getattr(ctx.requested, name) is not None: + assert cap in ctx.capabilities + + +@PROPERTY +@given(contexts()) +def test_b1_a_written_floor_is_never_below_the_reserve_or_the_baseline(ctx: BatteryContext) -> None: + assume(accepted(ctx)) + assert ctx.model is not None + assert ctx.reserve_pct is not None + if ctx.requested.min_soc_pct is not None: + assert ctx.target.min_soc_pct is not None + assert ctx.target.min_soc_pct >= ctx.reserve_pct - 0.01 + if ctx.baseline is not None and ctx.baseline.min_soc_pct is not None: + assert ctx.target.min_soc_pct >= ctx.baseline.min_soc_pct - 0.01 + + +@PROPERTY +@given(contexts()) +def test_suncore_never_widens_the_discharge_of_the_users_settings(ctx: BatteryContext) -> None: + """B1 + B6: every accepted limit restricts discharge at least as much as the baseline.""" + assume(accepted(ctx)) + base = ctx.baseline + if ( + ctx.requested.max_discharge_w is not None + and base is not None + and base.max_discharge_w is not None + ): + assert ctx.target.max_discharge_w is not None + assert ctx.target.max_discharge_w <= base.max_discharge_w + 1.0 + + +@PROPERTY +@given(contexts(grid=True)) +def test_b2_grid_charging_within_every_bound(ctx: BatteryContext) -> None: + assume(accepted(ctx)) + grid = ctx.target.grid_charge_w or 0.0 + assume(grid > 0) + model, band = ctx.model, ctx.band + assert model is not None + assert band is not None + assert band.grid_charge_max_w is not None + assert ctx.import_limit_w is not None + assert ctx.live.deficit_w is not None + assert ctx.ranges.grid_charge_w is not None + assert grid <= model.max_charge_w + 1.0 + assert grid <= band.grid_charge_max_w + 1.0 + assert grid <= ctx.ranges.grid_charge_w.high + 1.0 + assert grid <= ctx.import_limit_w - ctx.live.deficit_w - ctx.reserve_w + 1.0 + bound = grid_charge_bound_w(ctx) + assert bound is not None + assert grid <= bound + 1.0 + + +@PROPERTY +@given(contexts(grid=True)) +def test_b3_grid_charging_only_planned_fresh_in_policy_and_below_max(ctx: BatteryContext) -> None: + assume(accepted(ctx)) + assume((ctx.target.grid_charge_w or 0.0) > 0) + assert ctx.plan_fresh + assert ctx.band is not None + assert (ctx.band.grid_charge_max_w or 0) > 0 + assert ctx.policy.allows(ctx.now, ctx.import_price, ctx.tz) + assert ctx.import_price is not None or ctx.policy.max_price is None + assert ctx.live.soc_pct is not None + assert ctx.model is not None + assert ctx.live.soc_pct < ctx.model.max_soc_pct + + +@PROPERTY +@given(contexts()) +def test_b4_a_discharge_lock_only_from_a_fresh_planned_lock(ctx: BatteryContext) -> None: + assume(accepted(ctx)) + if is_discharge_lock(ctx): + assert ctx.band is not None + assert ctx.band.discharge_lock + assert ctx.plan_fresh + + +@PROPERTY +@given(contexts()) +def test_b5_the_import_limit_holds_for_every_action_that_can_cause_import( + ctx: BatteryContext, +) -> None: + assume(accepted(ctx)) + if can_cause_import(ctx) and ctx.import_limit_w is not None: + projected = projected_import_w(ctx) + assert projected is not None + assert projected <= ctx.import_limit_w + 1.0 + + +@PROPERTY +@given(contexts()) +def test_b6_every_requested_value_is_inside_the_live_range(ctx: BatteryContext) -> None: + assume(accepted(ctx)) + for name in ("max_charge_w", "max_discharge_w", "min_soc_pct", "grid_charge_w"): + if getattr(ctx.requested, name) is None: + continue + allowed = ctx.ranges.of(name) + assert allowed is not None + value = getattr(ctx.target, name) + assert allowed.low - 1.0 <= value <= allowed.high + 1.0 + + +@PROPERTY +@given(contexts()) +def test_without_a_model_nothing_passes(ctx: BatteryContext) -> None: + if ctx.model is None: + assert not accepted(ctx) + + +# --- examples --------------------------------------------------------------------------------- + + +def _model() -> BatteryModel: + return BatteryModel(capacity_wh=10_000, max_charge_w=5000, max_discharge_w=5000) + + +def _ctx(**kw: Any) -> BatteryContext: + requested = kw.pop("requested") + baseline = kw.pop("baseline", None) + rng = kw.pop( + "ranges", + BatteryRanges( + max_charge_w=FieldRange(0, 5000), + max_discharge_w=FieldRange(0, 5000), + min_soc_pct=FieldRange(5, 100, 5), + grid_charge_w=FieldRange(0, 5000), + ), + ) + base: dict[str, Any] = { + "requested": requested, + "target": quantise(resolve_battery_action(requested, baseline), rng), + "capabilities": ALL_CAPS, + "ranges": rng, + "model": _model(), + "reserve_pct": 15.0, + "live": BatteryLive(soc_pct=40, grid_w=600, battery_w=0), + "band": BatteryBand(grid_charge_max_w=3000, discharge_lock=True), + "plan_fresh": True, + "policy": GridChargePolicy(enabled=True, max_price=0.20), + "import_price": 0.15, + "tz": UTC, + "import_limit_w": 10_000, + "reserve_w": 100.0, + "now": NOW, + "baseline": baseline, + } + base.update(kw) + return BatteryContext(**base) + + +def keys(ctx: BatteryContext) -> list[str]: + return [r.key for r in evaluate_battery(ctx)] + + +def test_a_planned_grid_charge_in_policy_passes() -> None: + assert keys(_ctx(requested=BatteryAction(grid_charge_w=3000))) == [] + + +@pytest.mark.parametrize( + ("change", "key"), + [ + ({"band": None}, "safety.battery_grid_charge_unplanned"), + ({"band": BatteryBand()}, "safety.battery_grid_charge_unplanned"), + ({"plan_fresh": False}, "safety.battery_plan_stale"), + ({"import_price": 0.30}, "safety.battery_grid_charge_policy"), + ({"import_price": None}, "safety.battery_grid_charge_policy"), + ( + {"live": BatteryLive(soc_pct=None, grid_w=600, battery_w=0)}, + "safety.battery_soc_unknown", + ), + ({"live": BatteryLive(soc_pct=100, grid_w=600, battery_w=0)}, "safety.battery_full"), + ({"import_limit_w": None}, "safety.battery_import_limit_unknown"), + ( + {"live": BatteryLive(soc_pct=40, grid_w=None, battery_w=0)}, + "safety.battery_grid_unknown", + ), + ({"import_limit_w": 3500}, "safety.battery_grid_charge_bound"), + ({"model": None}, "safety.battery_model_missing"), + ( + {"capabilities": frozenset({BatteryCapability.MIN_SOC})}, + "safety.battery_capability_missing", + ), + ], +) +def test_grid_charge_rejections(change: dict[str, Any], key: str) -> None: + assert key in keys(_ctx(requested=BatteryAction(grid_charge_w=3000), **change)) + + +def test_the_import_headroom_counts_the_house_without_the_battery() -> None: + # 600 W import of which 3000 W are the battery already charging from the grid: the house + # alone exports 2400 W - the headroom is the full limit minus the reserve. + ctx = _ctx( + requested=BatteryAction(grid_charge_w=3000), + live=BatteryLive(soc_pct=40, grid_w=600, battery_w=3000), + import_limit_w=3200, + ) + assert keys(ctx) == [] + assert grid_charge_bound_w(ctx) == pytest.approx(3000) + + +def test_min_soc_rounds_up_and_never_below_the_reserve_or_the_users_floor() -> None: + lock = _ctx(requested=BatteryAction(min_soc_pct=41)) + assert lock.target.min_soc_pct == 45 + assert keys(lock) == [] + assert keys(_ctx(requested=BatteryAction(min_soc_pct=10))) == [ + "safety.battery_min_soc_below_reserve" + ] + assert keys( + _ctx(requested=BatteryAction(min_soc_pct=20), baseline=BatteryAction(min_soc_pct=30)) + ) == ["safety.battery_min_soc_below_baseline"] + + +def test_a_discharge_lock_needs_a_planned_lock() -> None: + unplanned = _ctx(requested=BatteryAction(max_discharge_w=0), band=BatteryBand()) + assert keys(unplanned) == ["safety.battery_unplanned_import"] + assert keys(_ctx(requested=BatteryAction(max_discharge_w=0))) == [] + # 600 W deficit, a cap of 1000 W is no lock now (the battery still covers the house). + assert keys(_ctx(requested=BatteryAction(max_discharge_w=1000), band=BatteryBand())) == [] + stale = _ctx(requested=BatteryAction(max_discharge_w=0), plan_fresh=False) + assert keys(stale) == ["safety.battery_plan_stale"] + + +def test_a_lock_that_would_break_the_import_limit_is_rejected() -> None: + ctx = _ctx( + requested=BatteryAction(max_discharge_w=0), + live=BatteryLive(soc_pct=40, grid_w=0, battery_w=-6000), + import_limit_w=5000, + ) + assert keys(ctx) == ["safety.battery_import_limit"] + + +def test_ranges_and_baseline_caps() -> None: + assert keys(_ctx(requested=BatteryAction(max_charge_w=6000))) == ["safety.battery_out_of_range"] + no_range = BatteryRanges() + assert keys(_ctx(requested=BatteryAction(max_charge_w=1000), ranges=no_range)) == [ + "safety.battery_range_unknown" + ] + assert keys( + _ctx( + requested=BatteryAction(max_charge_w=3000), + baseline=BatteryAction(max_charge_w=2000), + ) + ) == ["safety.battery_above_baseline"] + + +def test_plan_freshness() -> None: + start = NOW.replace(minute=0) + interval = PlanInterval( + start=start, end=start + timedelta(minutes=15), battery=BatteryBand(discharge_lock=True) + ) + plan = Plan(created_at=start - timedelta(minutes=5), intervals=(interval,)) + band, fresh = plan_band(plan, start + timedelta(minutes=5)) + assert band is not None + assert band.discharge_lock + assert fresh + old = plan.model_copy(update={"created_at": start - timedelta(minutes=31)}) + assert plan_band(old, start + timedelta(minutes=5))[1] is False + assert plan_band(Plan.default(), start) == (None, False) + assert plan_band(plan, start + timedelta(minutes=20)) == (None, False) + + +def test_same_state_compares_the_written_fields() -> None: + a = BatteryAction(max_discharge_w=0, min_soc_pct=45) + assert same_state(a, BatteryAction(max_discharge_w=0.5, min_soc_pct=45), ["max_discharge_w"]) + assert not same_state(a, BatteryAction(max_discharge_w=0), ["max_discharge_w", "min_soc_pct"]) + assert not same_state(a, None, ["max_discharge_w"]) + + +# --- watchdog (B8) ---------------------------------------------------------------------------- + + +def test_a_frozen_battery_power_while_the_grid_moves_is_a_fault() -> None: + watch = BatteryWatch(frozen_s=300, grid_move_w=500) + reason = None + for i in range(80): + now = NOW + timedelta(seconds=5 * i) + grid = 200.0 + (800.0 if i % 20 < 10 else 0.0) + reason = watch.check(now, BatteryLive(soc_pct=50, grid_w=grid, battery_w=-1200), 10_000) + if reason is not None: + break + assert reason is not None + assert reason.key == "safety.battery_frozen" + + +def test_a_constant_battery_power_with_a_steady_grid_is_fine() -> None: + watch = BatteryWatch(frozen_s=300) + for i in range(200): + now = NOW + timedelta(seconds=5 * i) + live = BatteryLive(soc_pct=50 - i * 0.05, grid_w=10.0, battery_w=-1200) + assert watch.check(now, live, 10_000) is None + + +def test_an_idle_battery_at_zero_is_never_frozen() -> None: + watch = BatteryWatch(frozen_s=60) + for i in range(200): + now = NOW + timedelta(seconds=5 * i) + grid = 1000.0 if i % 2 else -1000.0 + assert watch.check(now, BatteryLive(soc_pct=100, grid_w=grid, battery_w=0), 10_000) is None + + +def test_a_frozen_soc_while_the_battery_moves_energy_is_a_fault() -> None: + watch = BatteryWatch(soc_energy_pct=3.0) + reason = None + for i in range(1000): + now = NOW + timedelta(seconds=5 * i) + power = -2000.0 + (i % 3) # moving power: not frozen + reason = watch.check(now, BatteryLive(soc_pct=60, grid_w=100, battery_w=power), 10_000) + if reason is not None: + elapsed_h = 5 * i / 3600 + assert elapsed_h * 2000 >= 300 # 3 % of 10 kWh moved before the fault + break + assert reason is not None + assert reason.key == "safety.battery_soc_frozen" + + +@given(st.lists(st.floats(-5000, 5000), min_size=1, max_size=50)) +def test_the_watch_never_fires_without_a_capacity_or_on_moving_values(values: list[float]) -> None: + watch = BatteryWatch(frozen_s=10_000) + for i, v in enumerate(values): + now = NOW + timedelta(seconds=5 * i) + assert watch.check(now, BatteryLive(soc_pct=50, grid_w=v, battery_w=v + i), None) is None + + +def test_the_generator_produces_accepted_actions_of_every_kind() -> None: + """The implications above are not vacuous: accepted grid charging, locks and floors exist.""" + quick = settings(phases=[Phase.generate], database=None, max_examples=500) + assert find( + contexts(grid=True), + lambda c: accepted(c) and (c.target.grid_charge_w or 0) > 0, + settings=quick, + ) + assert find(contexts(), lambda c: accepted(c) and is_discharge_lock(c), settings=quick) + assert find( + contexts(), lambda c: accepted(c) and c.requested.min_soc_pct is not None, settings=quick + ) From f50f5d873098900b4fcefd00e99fa451ef931c60 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 18:47:04 +0000 Subject: [PATCH 03/16] feat(devices,templates): battery adapters generic, kostal_plenticore and kostal_modbus (WP10) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - suncore/devices/battery behind the gate's BatteryActuator protocol: capabilities from the mapped roles, live ranges from the entity attributes, write only on change, read-back, release to the baseline; generic numbers / mode select / force-charge switch - kostal_plenticore: Battery:MinSoc only (no set-point over REST), settle 35 s for the silent REST write and the 30 s poll, the usage-mode select read only - kostal_modbus: §3.5 via modbus.write_register (a write of this adapter only, through the rate-limited ServiceCaller, never a read-only action): float32/U32 words in the configured word order, refuses unless register 1080 reads 2, arms 1284/1286/1288 before any limit, heartbeat re-write, release writes the battery's own limits explicitly - core.battery_adapter (adapter spec, mode meanings, modbus roles) so devices import only core; templates generic.battery, kostal.plenticore, kostal.plenticore_g3_modbus (driver, register map, sources, unverified lists) with conformance scenarios; boundary rules cover the battery adapters and their arm_fallback / keep_alive writes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- docs/user/compatibility.md | 8 + frontend/src/lib/api/openapi.json | 97 +++- frontend/src/lib/api/schema.d.ts | 41 +- frontend/src/lib/i18n/locales/de.json | 18 + frontend/src/lib/i18n/locales/en.json | 18 + suncore/api/models.py | 2 +- suncore/core/battery_adapter.py | 125 +++++ suncore/core/capabilities.py | 2 + suncore/devices/battery/__init__.py | 48 ++ suncore/devices/battery/base.py | 172 +++++++ suncore/devices/battery/generic.py | 343 +++++++++++++ suncore/devices/battery/kostal_modbus.py | 249 +++++++++ suncore/devices/battery/kostal_plenticore.py | 66 +++ suncore/devices/battery/modbus_codec.py | 53 ++ suncore/safety/battery.py | 6 +- suncore/templates/models.py | 147 +++++- templates/battery/generic.battery.yaml | 57 +++ templates/battery/kostal.plenticore.yaml | 45 ++ .../battery/kostal.plenticore_g3_modbus.yaml | 67 +++ templates/schema/battery.schema.json | 95 +++- templates/schema/device.schema.json | 3 +- templates/schema/forecast.schema.json | 3 +- templates/schema/region.schema.json | 3 +- templates/schema/tariff.schema.json | 3 +- templates/schema/template.schema.json | 95 +++- tests/devices/battery/__init__.py | 0 tests/devices/battery/test_battery_drivers.py | 484 ++++++++++++++++++ tests/safety/test_boundary.py | 25 +- tests/scenarios/battery/generic.battery.yaml | 22 + .../scenarios/battery/kostal.plenticore.yaml | 17 + .../battery/kostal.plenticore_g3_modbus.yaml | 39 ++ tests/scenarios/test_conformance.py | 53 +- 32 files changed, 2367 insertions(+), 39 deletions(-) create mode 100644 suncore/core/battery_adapter.py create mode 100644 suncore/devices/battery/__init__.py create mode 100644 suncore/devices/battery/base.py create mode 100644 suncore/devices/battery/generic.py create mode 100644 suncore/devices/battery/kostal_modbus.py create mode 100644 suncore/devices/battery/kostal_plenticore.py create mode 100644 suncore/devices/battery/modbus_codec.py create mode 100644 templates/battery/generic.battery.yaml create mode 100644 templates/battery/kostal.plenticore.yaml create mode 100644 templates/battery/kostal.plenticore_g3_modbus.yaml create mode 100644 tests/devices/battery/__init__.py create mode 100644 tests/devices/battery/test_battery_drivers.py create mode 100644 tests/scenarios/battery/generic.battery.yaml create mode 100644 tests/scenarios/battery/kostal.plenticore.yaml create mode 100644 tests/scenarios/battery/kostal.plenticore_g3_modbus.yaml diff --git a/docs/user/compatibility.md b/docs/user/compatibility.md index 9105793..e64fd96 100644 --- a/docs/user/compatibility.md +++ b/docs/user/compatibility.md @@ -26,6 +26,14 @@ a template only tested in the simulator has never run against real hardware. | `generic.water_heater_steps` | device | Water heater with power levels (select entity) | any | `power_measured`, `power_setpoint` | not tested on hardware | 7 | | `lg.thinq_climate` | device | LG ThinQ air conditioner | `lg_thinq` | `energy_counter`, `fan_modes`, `hvac_modes`, `power_measured`, `preset_modes`, `temperature_setpoint` | not tested on hardware | 7 | +## Batteries + +| Id | Kind | Name | Integration / platforms | Capabilities | Tested with | Unverified | +|---|---|---|---|---|---|---| +| `generic.battery` | battery | Battery with number entities (generic) | any | `charge_limit`, `discharge_limit`, `grid_charge`, `min_soc_limit` | not tested on hardware | 3 | +| `kostal.plenticore` | battery | KOSTAL PLENTICORE (Home Assistant integration, minimum SoC) | `kostal_plenticore` | `min_soc_limit` | not tested on hardware | 4 | +| `kostal.plenticore_g3_modbus` | battery | KOSTAL PLENTICORE G3 battery limits over Modbus (§3.5) | `modbus` | `charge_limit`, `discharge_limit`, `hardware_fallback` | not tested on hardware | 5 | + ## Tariffs | Id | Kind | Name | Integration / platforms | Capabilities | Tested with | Unverified | diff --git a/frontend/src/lib/api/openapi.json b/frontend/src/lib/api/openapi.json index 579abd0..66a63a2 100644 --- a/frontend/src/lib/api/openapi.json +++ b/frontend/src/lib/api/openapi.json @@ -836,6 +836,16 @@ "title": "Controls", "type": "object" }, + "driver": { + "default": "generic", + "enum": [ + "generic", + "kostal_plenticore", + "kostal_modbus" + ], + "title": "Driver", + "type": "string" + }, "id": { "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)?$", @@ -859,6 +869,16 @@ ], "title": "Min App Version" }, + "modbus": { + "anyOf": [ + { + "$ref": "#/components/schemas/ModbusRegisterMap" + }, + { + "type": "null" + } + ] + }, "name": { "maxLength": 120, "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$", @@ -1247,7 +1267,8 @@ "charge_limit", "discharge_limit", "grid_charge", - "battery_modes" + "battery_modes", + "hardware_fallback" ], "title": "Capability", "type": "string" @@ -4574,6 +4595,77 @@ "title": "ModbusLink", "type": "object" }, + "ModbusRegisterMap": { + "additionalProperties": false, + "description": "Registers of a limit-with-fallback battery interface (Kostal §3.5, ``kostal_modbus``).\n\nAddresses as the vendor document gives them (the HA action writes them verbatim). Powers\nare IEEE 754 float32 in two registers, the timeout an unsigned 32-bit value in two\nregisters; the word order comes from the battery configuration (``battery.modbus``).\n``external_control_value`` is what ``external_control_register`` must read before any\nwrite (Kostal 1080 = ``0x02``: external battery management via Modbus).", + "properties": { + "external_control_register": { + "maximum": 65535.0, + "minimum": 0.0, + "title": "External Control Register", + "type": "integer" + }, + "external_control_value": { + "maximum": 65535.0, + "minimum": 0.0, + "title": "External Control Value", + "type": "integer" + }, + "fallback_max_charge": { + "maximum": 65534.0, + "minimum": 0.0, + "title": "Fallback Max Charge", + "type": "integer" + }, + "fallback_max_discharge": { + "maximum": 65534.0, + "minimum": 0.0, + "title": "Fallback Max Discharge", + "type": "integer" + }, + "fallback_timeout": { + "maximum": 65534.0, + "minimum": 0.0, + "title": "Fallback Timeout", + "type": "integer" + }, + "fallback_timeout_max_s": { + "minimum": 1.0, + "title": "Fallback Timeout Max S", + "type": "integer" + }, + "fallback_timeout_min_s": { + "minimum": 1.0, + "title": "Fallback Timeout Min S", + "type": "integer" + }, + "max_charge": { + "maximum": 65534.0, + "minimum": 0.0, + "title": "Max Charge", + "type": "integer" + }, + "max_discharge": { + "maximum": 65534.0, + "minimum": 0.0, + "title": "Max Discharge", + "type": "integer" + } + }, + "required": [ + "max_charge", + "max_discharge", + "fallback_max_charge", + "fallback_max_discharge", + "fallback_timeout", + "fallback_timeout_min_s", + "fallback_timeout_max_s", + "external_control_register", + "external_control_value" + ], + "title": "ModbusRegisterMap", + "type": "object" + }, "Mode": { "additionalProperties": false, "description": "One mode of a mode-controlled device and the power it draws.", @@ -7860,7 +7952,8 @@ "device", "tariff", "forecast", - "region" + "region", + "battery" ], "title": "Kind", "type": "string" diff --git a/frontend/src/lib/api/schema.d.ts b/frontend/src/lib/api/schema.d.ts index 85a0123..812cd91 100644 --- a/frontend/src/lib/api/schema.d.ts +++ b/frontend/src/lib/api/schema.d.ts @@ -1167,6 +1167,12 @@ export interface components { controls?: { [key: string]: components["schemas"]["NumberLimitControl"] | components["schemas"]["ModeSelectControl"] | components["schemas"]["ForceChargeSwitchControl"]; }; + /** + * Driver + * @default generic + * @enum {string} + */ + driver: "generic" | "kostal_plenticore" | "kostal_modbus"; /** Id */ id: string; /** @@ -1176,6 +1182,7 @@ export interface components { kind: "battery"; /** Min App Version */ min_app_version?: string | null; + modbus?: components["schemas"]["ModbusRegisterMap"] | null; /** Name */ name: string; /** Roles */ @@ -1315,7 +1322,7 @@ export interface components { * @description What a template provides. * @enum {string} */ - Capability: "power_measured" | "energy_counter" | "on_off" | "power_setpoint" | "temperature_setpoint" | "hvac_modes" | "preset_modes" | "fan_modes" | "price_now" | "price_curve" | "pv_curve" | "pv_quantiles" | "feed_in_tiers" | "negative_price_rule" | "battery_soc" | "min_soc_limit" | "charge_limit" | "discharge_limit" | "grid_charge" | "battery_modes"; + Capability: "power_measured" | "energy_counter" | "on_off" | "power_setpoint" | "temperature_setpoint" | "hvac_modes" | "preset_modes" | "fan_modes" | "price_now" | "price_curve" | "pv_curve" | "pv_quantiles" | "feed_in_tiers" | "negative_price_rule" | "battery_soc" | "min_soc_limit" | "charge_limit" | "discharge_limit" | "grid_charge" | "battery_modes" | "hardware_fallback"; /** CheckItemOut */ CheckItemOut: { reason: components["schemas"]["Reason"]; @@ -2552,6 +2559,36 @@ export interface components { /** Slave */ slave: number; }; + /** + * ModbusRegisterMap + * @description Registers of a limit-with-fallback battery interface (Kostal §3.5, ``kostal_modbus``). + * + * Addresses as the vendor document gives them (the HA action writes them verbatim). Powers + * are IEEE 754 float32 in two registers, the timeout an unsigned 32-bit value in two + * registers; the word order comes from the battery configuration (``battery.modbus``). + * ``external_control_value`` is what ``external_control_register`` must read before any + * write (Kostal 1080 = ``0x02``: external battery management via Modbus). + */ + ModbusRegisterMap: { + /** External Control Register */ + external_control_register: number; + /** External Control Value */ + external_control_value: number; + /** Fallback Max Charge */ + fallback_max_charge: number; + /** Fallback Max Discharge */ + fallback_max_discharge: number; + /** Fallback Timeout */ + fallback_timeout: number; + /** Fallback Timeout Max S */ + fallback_timeout_max_s: number; + /** Fallback Timeout Min S */ + fallback_timeout_min_s: number; + /** Max Charge */ + max_charge: number; + /** Max Discharge */ + max_discharge: number; + }; /** * Mode * @description One mode of a mode-controlled device and the power it draws. @@ -3856,7 +3893,7 @@ export interface components { * Kind * @enum {string} */ - kind: "device" | "tariff" | "forecast" | "region"; + kind: "device" | "tariff" | "forecast" | "region" | "battery"; /** Name */ name: string; /** diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index 8663952..4a1220f 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -802,10 +802,27 @@ "template.open_meteo_solar_forecast.pv.role.energy_d3": "Open-Meteo-Solar-Forecast-Sensor für Tag 3 (optional)", "template.generic.pv_forecast.name": "Allgemeine PV-Prognose (Attribut eines Template-Sensors)", "template.generic.pv_forecast.role.forecast": "Sensor, dessen Attribut „forecast“ Punkte mit „start“ und „power_w“ auflistet", + "template.generic.battery.name": "Akku mit Zahlen-Entitäten (generisch)", + "template.generic.battery.role.min_soc_number": "Mindest-Ladestand (Zahl in %, optional)", + "template.generic.battery.role.max_charge_number": "Maximale Ladeleistung (Zahl in W oder kW, optional)", + "template.generic.battery.role.max_discharge_number": "Maximale Entladeleistung (Zahl in W oder kW, optional)", + "template.generic.battery.role.grid_charge_number": "Zwangsladeleistung aus dem Netz (Zahl in W oder kW, optional)", "template.tibber.price.name": "Tibber dynamischer Preis", "template.tibber.price.role.price": "Aktueller Strompreis-Sensor von Tibber (Währung pro kWh)", "template.untested": "Nicht an echter Hardware geprüft", "template.untested_long": "Diese Vorlage wurde nach dem Quellcode der Integration geschrieben und noch nicht an einem echten Gerät geprüft. Prüfe die Werte sorgfältig und lass das Gerät im Schattenmodus.", + "template.kostal.plenticore.name": "KOSTAL PLENTICORE (Home-Assistant-Integration, Mindest-Ladestand)", + "template.kostal.plenticore.role.min_soc_number": "Zahl „Battery min SoC“ des Wechselrichters (standardmäßig deaktiviert: zuerst aktivieren)", + "template.kostal.plenticore.role.charge_mode": "Auswahl „Battery charging / usage mode“ (nur lesen, optional)", + "template.kostal.plenticore_g3_modbus.name": "KOSTAL PLENTICORE G3 Akku-Grenzen über Modbus (§3.5)", + "template.kostal.plenticore_g3_modbus.role.external_control": "Modbus-Sensor von Register 1080 (externes Batteriemanagement, muss 2 sein)", + "template.kostal.plenticore_g3_modbus.role.charge_limit": "Modbus-Sensor von Register 1280 (max. Ladeleistung, W)", + "template.kostal.plenticore_g3_modbus.role.discharge_limit": "Modbus-Sensor von Register 1282 (max. Entladeleistung, W)", + "template.kostal.plenticore_g3_modbus.role.fallback_charge_limit": "Modbus-Sensor von Register 1284 (Rückfall-Ladeleistung, W)", + "template.kostal.plenticore_g3_modbus.role.fallback_discharge_limit": "Modbus-Sensor von Register 1286 (Rückfall-Entladeleistung, W)", + "template.kostal.plenticore_g3_modbus.role.fallback_timeout": "Modbus-Sensor von Register 1288 (Zeit bis zum Rückfall, s)", + "template.kostal.plenticore_g3_modbus.role.own_charge_limit": "Modbus-Sensor von Register 1076 (eigene max. Ladeleistung des Akkus, W)", + "template.kostal.plenticore_g3_modbus.role.own_discharge_limit": "Modbus-Sensor von Register 1078 (eigene max. Entladeleistung des Akkus, W)", "unit.kw": "{value} kW", "unit.mismatch": "Die Einheit passt nicht.", "unit.percent": "{value} %", @@ -919,6 +936,7 @@ "safety.battery_import_limit_unknown": "Netzladen braucht eine eingestellte Bezugsgrenze.", "safety.battery_import_limit": "Das Haus würde {projected_w} W beziehen, über der Bezugsgrenze von {limit_w} W.", "safety.battery_unplanned_import": "Den Akku zurückzuhalten würde Netzbezug verursachen, und der Plan sieht das nicht vor.", + "safety.battery_external_control_off": "Externes Batteriemanagement über Modbus ist aus (Register 1080 = {value}, nötig ist {expected}); nichts geschrieben.", "action.battery": "Batterie-Limits setzen", "api.validation.forecast_workday_domain": "{entity_id} ist kein Binärsensor. Wähle den Binärsensor der Workday-Integration.", "api.validation.forecast_weather_domain": "{entity_id} ist keine Wetter-Entität.", diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index ed3461e..6bc8a49 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -802,10 +802,27 @@ "template.open_meteo_solar_forecast.pv.role.energy_d3": "Open-Meteo Solar Forecast sensor for day 3 (optional)", "template.generic.pv_forecast.name": "Generic PV forecast (attribute of a template sensor)", "template.generic.pv_forecast.role.forecast": "Sensor whose attribute “forecast” lists points with “start” and “power_w”", + "template.generic.battery.name": "Battery with number entities (generic)", + "template.generic.battery.role.min_soc_number": "Minimum state of charge (number in %, optional)", + "template.generic.battery.role.max_charge_number": "Maximum charge power (number in W or kW, optional)", + "template.generic.battery.role.max_discharge_number": "Maximum discharge power (number in W or kW, optional)", + "template.generic.battery.role.grid_charge_number": "Forced charging power from the grid (number in W or kW, optional)", "template.tibber.price.name": "Tibber dynamic price", "template.tibber.price.role.price": "Current electricity price sensor of Tibber (currency per kWh)", "template.untested": "Not verified with real hardware", "template.untested_long": "This template was written from the integration source and has not been verified on a real device yet. Check the values carefully and keep the device in shadow mode.", + "template.kostal.plenticore.name": "KOSTAL PLENTICORE (Home Assistant integration, minimum SoC)", + "template.kostal.plenticore.role.min_soc_number": "\"Battery min SoC\" number of the inverter (disabled by default: enable it first)", + "template.kostal.plenticore.role.charge_mode": "\"Battery charging / usage mode\" select (read only, optional)", + "template.kostal.plenticore_g3_modbus.name": "KOSTAL PLENTICORE G3 battery limits over Modbus (§3.5)", + "template.kostal.plenticore_g3_modbus.role.external_control": "Modbus sensor of register 1080 (external battery management, must be 2)", + "template.kostal.plenticore_g3_modbus.role.charge_limit": "Modbus sensor of register 1280 (max charge power, W)", + "template.kostal.plenticore_g3_modbus.role.discharge_limit": "Modbus sensor of register 1282 (max discharge power, W)", + "template.kostal.plenticore_g3_modbus.role.fallback_charge_limit": "Modbus sensor of register 1284 (fallback charge power, W)", + "template.kostal.plenticore_g3_modbus.role.fallback_discharge_limit": "Modbus sensor of register 1286 (fallback discharge power, W)", + "template.kostal.plenticore_g3_modbus.role.fallback_timeout": "Modbus sensor of register 1288 (time until fallback, s)", + "template.kostal.plenticore_g3_modbus.role.own_charge_limit": "Modbus sensor of register 1076 (the battery's own max charge power, W)", + "template.kostal.plenticore_g3_modbus.role.own_discharge_limit": "Modbus sensor of register 1078 (the battery's own max discharge power, W)", "unit.kw": "{value} kW", "unit.mismatch": "The unit does not fit.", "unit.percent": "{value} %", @@ -919,6 +936,7 @@ "safety.battery_import_limit_unknown": "Grid charging needs a configured grid import limit.", "safety.battery_import_limit": "The house would import {projected_w} W, above the import limit of {limit_w} W.", "safety.battery_unplanned_import": "Holding the battery back would make the house import, and the plan does not ask for it.", + "safety.battery_external_control_off": "External battery management via Modbus is off (register 1080 = {value}, needs {expected}); nothing was written.", "action.battery": "Set battery limits", "api.validation.forecast_workday_domain": "{entity_id} is not a binary sensor. Choose the binary sensor of the Workday integration.", "api.validation.forecast_weather_domain": "{entity_id} is not a weather entity.", diff --git a/suncore/api/models.py b/suncore/api/models.py index f482978..e7bc784 100644 --- a/suncore/api/models.py +++ b/suncore/api/models.py @@ -221,7 +221,7 @@ class TemplateSummaryOut(_Model): """Gallery entry of a template.""" id: str - kind: Literal["device", "tariff", "forecast", "region"] + kind: Literal["device", "tariff", "forecast", "region", "battery"] name: str """i18n key (``template..name``).""" origin: Literal["builtin", "user"] diff --git a/suncore/core/battery_adapter.py b/suncore/core/battery_adapter.py new file mode 100644 index 0000000..d63d0fa --- /dev/null +++ b/suncore/core/battery_adapter.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: Apache-2.0 +"""What a battery adapter needs from its template, as plain core data (Phase 4 WP10). + +``suncore.devices`` imports only ``core`` (``tests/devices/test_imports.py``), so the battery +adapters cannot read ``suncore.templates`` models. The template converts itself into a +:class:`BatteryAdapterSpec` (``BatteryTemplate.adapter_spec()``) and the composition root hands +that to ``suncore.devices.battery.create_battery_driver``. The vocabulary +(:class:`BatteryModeMeaning`, the ``kostal_modbus`` roles) lives here; the template models re-use +it. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum, unique +from typing import Final, Literal + +BatteryDriverKind = Literal["generic", "kostal_plenticore", "kostal_modbus"] +"""Which adapter executes a battery template.""" + +LimitKind = Literal["min_soc", "max_charge", "max_discharge", "grid_charge_power"] +LimitUnit = Literal["W", "kW", "%"] + + +@unique +class BatteryModeMeaning(StrEnum): + """What selecting a battery mode option does.""" + + AUTO = "auto" + """The inverter's own control (the release baseline).""" + FORCE_CHARGE = "force_charge" + """Charge, also from the grid.""" + NO_DISCHARGE = "no_discharge" + NO_CHARGE = "no_charge" + OTHER = "other" + """Any other option; SunCore never selects it.""" + + +KOSTAL_MODBUS_ROLES: Final = ( + "external_control", + "charge_limit", + "discharge_limit", + "fallback_charge_limit", + "fallback_discharge_limit", + "fallback_timeout", + "own_charge_limit", + "own_discharge_limit", +) +"""Read-back roles the ``kostal_modbus`` driver needs: modbus sensors of the registers of the +register map (1080, 1280, 1282, 1284, 1286, 1288) and of the battery's own limits (1076, 1078).""" + + +@dataclass(frozen=True, slots=True) +class NumberLimitSpec: + """A ``number`` role that sets one limit (``%`` of the battery's maximum power for the + power kinds when ``unit`` is ``%``).""" + + role: str + kind: LimitKind + unit: LimitUnit + min: float + max: float + step: float | None = None + + +@dataclass(frozen=True, slots=True) +class ModeOptionSpec: + value: str + meaning: BatteryModeMeaning + + +@dataclass(frozen=True, slots=True) +class ModeSelectSpec: + role: str + options: tuple[ModeOptionSpec, ...] + + +@dataclass(frozen=True, slots=True) +class ModbusRegisterSpec: + """Register map of a limit-with-fallback interface (Kostal §3.5).""" + + max_charge: int + max_discharge: int + fallback_max_charge: int + fallback_max_discharge: int + fallback_timeout: int + fallback_timeout_min_s: int + fallback_timeout_max_s: int + external_control_register: int + external_control_value: int + + +@dataclass(frozen=True, slots=True) +class BatteryAdapterSpec: + """The template, as far as an adapter is concerned.""" + + template_id: str + driver: BatteryDriverKind + settle_s: float | None = None + numbers: tuple[NumberLimitSpec, ...] = () + mode: ModeSelectSpec | None = None + force_switch_role: str | None = None + modbus: ModbusRegisterSpec | None = None + + def control_kinds(self) -> frozenset[str]: + kinds: set[str] = {n.kind for n in self.numbers} + if self.mode is not None: + kinds.add("mode") + if self.force_switch_role is not None: + kinds.add("force_charge") + return frozenset(kinds) + + +__all__ = [ + "KOSTAL_MODBUS_ROLES", + "BatteryAdapterSpec", + "BatteryDriverKind", + "BatteryModeMeaning", + "LimitKind", + "LimitUnit", + "ModbusRegisterSpec", + "ModeOptionSpec", + "ModeSelectSpec", + "NumberLimitSpec", +] diff --git a/suncore/core/capabilities.py b/suncore/core/capabilities.py index 06569dc..36cee47 100644 --- a/suncore/core/capabilities.py +++ b/suncore/core/capabilities.py @@ -35,3 +35,5 @@ class Capability(StrEnum): DISCHARGE_LIMIT = "discharge_limit" GRID_CHARGE = "grid_charge" BATTERY_MODES = "battery_modes" + HARDWARE_FALLBACK = "hardware_fallback" + """The inverter falls back to its own limits when SunCore stops writing (Phase 4 WP10).""" diff --git a/suncore/devices/battery/__init__.py b/suncore/devices/battery/__init__.py new file mode 100644 index 0000000..780e60d --- /dev/null +++ b/suncore/devices/battery/__init__.py @@ -0,0 +1,48 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Battery adapters behind the gate's ``BatteryActuator`` protocol (Phase 4 WP10, ADR-0013). + +``generic`` (template ``controls``), ``kostal_plenticore`` (the core integration's min-SoC +number) and ``kostal_modbus`` (§3.5 limits through ``modbus.write_register``). Like the device +drivers they are imported only by ``suncore.safety``, the composition root ``suncore.app`` and +the simulator (``tests/safety/test_boundary.py``), and only the gate calls ``apply``, +``release``, ``arm_fallback`` and ``keep_alive``. +""" + +from __future__ import annotations + +from suncore.core.battery import BatterySettings +from suncore.core.battery_adapter import BatteryAdapterSpec +from suncore.devices.battery.base import BatteryDriver +from suncore.devices.battery.generic import GenericBatteryDriver +from suncore.devices.battery.kostal_modbus import KostalModbusDriver +from suncore.devices.battery.kostal_plenticore import KostalPlenticoreDriver +from suncore.devices.drivers.base import ServiceWriter, StateLookup + + +def create_battery_driver( + spec: BatteryAdapterSpec, + settings: BatterySettings, + *, + write: ServiceWriter, + states: StateLookup, +) -> BatteryDriver: + """The adapter the template's ``driver`` names (``BatteryTemplate.adapter_spec()``); raises + ``ValueError`` when it cannot be built (no model, unmapped roles, no modbus link) - the battery + then stays observe-only.""" + if settings.adapter_template_id != spec.template_id: + msg = "the battery settings name another adapter template" + raise ValueError(msg) + if spec.driver == "kostal_plenticore": + return KostalPlenticoreDriver(spec, settings, write=write, states=states) + if spec.driver == "kostal_modbus": + return KostalModbusDriver(spec, settings, write=write, states=states) + return GenericBatteryDriver(spec, settings, write=write, states=states) + + +__all__ = [ + "BatteryDriver", + "GenericBatteryDriver", + "KostalModbusDriver", + "KostalPlenticoreDriver", + "create_battery_driver", +] diff --git a/suncore/devices/battery/base.py b/suncore/devices/battery/base.py new file mode 100644 index 0000000..9506d9f --- /dev/null +++ b/suncore/devices/battery/base.py @@ -0,0 +1,172 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Shared plumbing of the battery adapters (Phase 4 WP10, ADR-0013). + +A battery adapter is a ``suncore.safety.battery.BatteryActuator`` (structurally - nothing here +imports ``safety``): the gate hands it an intent whose ``BatteryAction`` is already resolved +against the takeover baseline (``None`` = baseline) and quantised, the adapter writes it and +reports what the entities show. It never decides: the invariants (reserve, grid charging, +discharge lock, import limit, ranges) are the gate's. Like the device drivers it reads the +entity cache only (never ``get_states``) and writes through the injected, rate-limited +``ServiceWriter`` (``ServiceCaller.write``). + +Signs: the ``BatteryAction`` fields are magnitudes in W and % (battery + = charging); the +*measured* battery power is the site's (``site.battery.power`` with its ``invert_sign``), the +adapters never read or convert it. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, Final + +from suncore.core.battery import ( + BATTERY_ASSET_ID, + FIELD_CAPABILITY, + BatteryAction, + BatteryCapability, + BatteryModel, + BatteryRanges, + BatterySettings, +) +from suncore.core.decisions import Action, Intent, Reason +from suncore.devices.drivers.base import ( + UNAVAILABLE_STATES, + ActionNotSupportedError, + EntityStateView, + ServiceWriter, + StateLookup, + WriteRefusedError, + as_float, +) + +DEFAULT_SETTLE_S: Final = 10.0 + + +class BatteryDriver: + """Common base: identity, entity lookup, the single write helper, last applied state.""" + + def __init__( + self, + settings: BatterySettings, + *, + write: ServiceWriter, + states: StateLookup, + settle_s: float | None = None, + ) -> None: + if settings.model is None: + msg = "a battery adapter needs a battery model (capacity and limits)" + raise ValueError(msg) + self._settings = settings + self._model: BatteryModel = settings.model + self._write = write + self._states = states + self._settle_s = DEFAULT_SETTLE_S if settle_s is None else float(settle_s) + self._context_ids: tuple[str, ...] = () + self._applied: BatteryAction | None = None + + # --- identity --------------------------------------------------------------------------- + + @property + def asset_id(self) -> str: + return BATTERY_ASSET_ID + + @property + def settle_s(self) -> float: + return self._settle_s + + @property + def heartbeat_s(self) -> float | None: + return None + + @property + def capabilities(self) -> frozenset[BatteryCapability]: # pragma: no cover - overridden + raise NotImplementedError + + @property + def applied(self) -> BatteryAction | None: + """The state of the last successful ``apply`` (``None`` after a release).""" + return self._applied + + # --- defaults of the optional protocol parts -------------------------------------------- + + def ranges(self) -> BatteryRanges: # pragma: no cover - overridden + raise NotImplementedError + + def refusal(self) -> Reason | None: + return None + + def prepared(self) -> bool: + return True + + async def arm_fallback(self) -> None: + return None + + async def keep_alive(self) -> None: + return None + + # --- helpers -------------------------------------------------------------------------------- + + def entity_id(self, role: str) -> str | None: + ref = self._settings.entities.get(role) + return None if ref is None else ref.entity_id + + def lookup(self, entity_id: str | None) -> EntityStateView | None: + """The cached state; ``None`` if unknown to the cache or unavailable/unknown.""" + if entity_id is None: + return None + view = self._states(entity_id) + if view is None or view.state in UNAVAILABLE_STATES: + return None + return view + + def value_of(self, role: str) -> float | None: + """The numeric state of a role's entity (``None`` = unmapped, unavailable or text).""" + view = self.lookup(self.entity_id(role)) + return None if view is None else as_float(view.state) + + def battery_action(self, intent: Intent) -> BatteryAction: + action = intent.action + if not isinstance(action, BatteryAction): + msg = f"{type(self).__name__} cannot apply a {action.kind.value} action" + raise ActionNotSupportedError(msg) + missing = [ + name + for name, value in action.model_dump(exclude={"kind"}).items() + if value is not None and FIELD_CAPABILITY[name] not in self.capabilities + ] + if missing: + msg = f"{type(self).__name__} cannot set {', '.join(missing)}" + raise WriteRefusedError(msg) + return action + + async def service( + self, + domain: str, + service: str, + *, + data: Mapping[str, Any] | None = None, + entity_id: str | None = None, + ) -> str | None: + """One service call; returns the HA context id (``None`` if absent).""" + result = await self._write( + domain, + service, + service_data=dict(data) if data else None, + target={"entity_id": entity_id} if entity_id is not None else None, + ) + context_id = result.context_id + if context_id is not None: + self._context_ids = (*self._context_ids, context_id) + return context_id + + def begin(self) -> None: + self._context_ids = () + + def last_context_id(self) -> str | None: + return self._context_ids[-1] if self._context_ids else None + + async def read_back(self) -> Action | None: # pragma: no cover - overridden + raise NotImplementedError + + +__all__ = ["DEFAULT_SETTLE_S", "BatteryDriver"] diff --git a/suncore/devices/battery/generic.py b/suncore/devices/battery/generic.py new file mode 100644 index 0000000..876c01b --- /dev/null +++ b/suncore/devices/battery/generic.py @@ -0,0 +1,343 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The ``generic`` battery adapter: template kind ``battery`` roles -> limits (WP10). + +What each mapped writable role expresses comes from the template's ``controls``: + +* ``min_soc`` number (%): the discharge floor (``min_soc_pct``); +* ``max_charge`` / ``max_discharge`` / ``grid_charge_power`` numbers (W, kW or % of the battery's + maximum power): the power limits and the forced grid-charge power; +* ``mode`` select: ``no_discharge`` expresses ``max_discharge_w = 0``, ``no_charge`` + ``max_charge_w = 0``, ``force_charge`` a forced grid charge at the battery's full power; + ``auto`` is the release baseline (exactly one per select, template validation); +* ``force_charge`` switch: on = forced grid charging at the battery's full power, off = auto. + +Capabilities follow the **mapped** roles (an optional role the user left out gives nothing). +Ranges come from the entity's live ``min``/``max``/``step`` attributes intersected with the +template's; a select or switch can only express the extremes, so its range is a single value +(the gate rejects anything else, B6). ``min_soc`` is rounded **up** to the entity step by the +gate (``safety.battery.quantise``). Writes only on change, read-back is mandatory (the gate +compares after ``settle_s``). Release writes the baseline values of the numbers it holds and +``auto`` / off for a select / switch. + +``UNVERIFIED``: no real generic battery has been driven; exercised in the simulator only. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import Final + +from suncore.core.battery import ( + BatteryAction, + BatteryCapability, + BatteryRanges, + BatterySettings, + FieldRange, +) +from suncore.core.battery_adapter import ( + BatteryAdapterSpec, + BatteryModeMeaning, + ModeSelectSpec, + NumberLimitSpec, +) +from suncore.core.decisions import Action, Intent +from suncore.devices.battery.base import BatteryDriver +from suncore.devices.drivers.base import ServiceWriter, StateLookup, WriteRefusedError, as_float + +SAME_VALUE: Final = 1e-6 + +_RESTRICTIVE: Final = frozenset( + { + BatteryModeMeaning.NO_DISCHARGE, + BatteryModeMeaning.NO_CHARGE, + BatteryModeMeaning.FORCE_CHARGE, + } +) + +_FIELD_OF_KIND: Final = { + "min_soc": "min_soc_pct", + "max_charge": "max_charge_w", + "max_discharge": "max_discharge_w", + "grid_charge_power": "grid_charge_w", +} + + +@dataclass(frozen=True, slots=True) +class _Number: + role: str + entity_id: str + control: NumberLimitSpec + field: str + + +class GenericBatteryDriver(BatteryDriver): + """Battery limits through ``number`` / ``select`` / ``switch`` entities (``generic``).""" + + def __init__( + self, + spec: BatteryAdapterSpec, + settings: BatterySettings, + *, + write: ServiceWriter, + states: StateLookup, + ) -> None: + super().__init__(settings, write=write, states=states, settle_s=spec.settle_s) + self._spec = spec + self._numbers: dict[str, _Number] = {} + self._mode: tuple[str, ModeSelectSpec] | None = None + self._switch: str | None = None + for number in spec.numbers: + entity = self.entity_id(number.role) + if entity is not None: # else an optional role the user did not map + field = _FIELD_OF_KIND[number.kind] + self._numbers[field] = _Number(number.role, entity, number, field) + if spec.mode is not None: + entity = self.entity_id(spec.mode.role) + if entity is not None: + self._mode = (entity, spec.mode) + if spec.force_switch_role is not None: + self._switch = self.entity_id(spec.force_switch_role) + self._capabilities = self._derive_capabilities() + + # --- capabilities and ranges ------------------------------------------------------------- + + def _mode_meanings(self) -> set[BatteryModeMeaning]: + if self._mode is None: + return set() + return {o.meaning for o in self._mode[1].options} + + def _derive_capabilities(self) -> frozenset[BatteryCapability]: + meanings = self._mode_meanings() + caps: set[BatteryCapability] = set() + if "min_soc_pct" in self._numbers: + caps.add(BatteryCapability.MIN_SOC) + if "max_charge_w" in self._numbers or BatteryModeMeaning.NO_CHARGE in meanings: + caps.add(BatteryCapability.CHARGE_LIMIT) + if "max_discharge_w" in self._numbers or BatteryModeMeaning.NO_DISCHARGE in meanings: + caps.add(BatteryCapability.DISCHARGE_LIMIT) + if ( + "grid_charge_w" in self._numbers + or self._switch is not None + or BatteryModeMeaning.FORCE_CHARGE in meanings + ): + caps.add(BatteryCapability.GRID_CHARGE) + return frozenset(caps) + + @property + def capabilities(self) -> frozenset[BatteryCapability]: + return self._capabilities + + def _factor(self, number: _Number) -> float | None: + """Entity value x factor = W (or % for ``min_soc``); ``None`` if not convertible.""" + unit = number.control.unit + if number.field == "min_soc_pct": + return 1.0 + if unit == "W": + return 1.0 + if unit == "kW": + return 1000.0 + full = ( + self._model.max_discharge_w + if number.field == "max_discharge_w" + else self._model.max_charge_w + ) + return full / 100.0 + + def _number_range(self, number: _Number) -> FieldRange | None: + view = self.lookup(number.entity_id) + factor = self._factor(number) + if view is None or factor is None: + return None + control = number.control + low = max(control.min, as_float(view.attributes.get("min")) or control.min) + high_attr = as_float(view.attributes.get("max")) + high = min(control.max, high_attr if high_attr is not None else control.max) + step = as_float(view.attributes.get("step")) or control.step + if low > high: + return None + return FieldRange(low * factor, high * factor, None if step is None else step * factor) + + def ranges(self) -> BatteryRanges: + values: dict[str, FieldRange | None] = { + field: self._number_range(number) for field, number in self._numbers.items() + } + meanings = self._mode_meanings() + mode_ok = self._mode is not None and self.lookup(self._mode[0]) is not None + if "max_discharge_w" not in values and BatteryModeMeaning.NO_DISCHARGE in meanings: + values["max_discharge_w"] = FieldRange(0.0, 0.0) if mode_ok else None + if "max_charge_w" not in values and BatteryModeMeaning.NO_CHARGE in meanings: + values["max_charge_w"] = FieldRange(0.0, 0.0) if mode_ok else None + if "grid_charge_w" not in values: + full = self._model.max_charge_w + if self._switch is not None: + switch_ok = self.lookup(self._switch) is not None + values["grid_charge_w"] = FieldRange(full, full) if switch_ok else None + elif BatteryModeMeaning.FORCE_CHARGE in meanings: + values["grid_charge_w"] = FieldRange(full, full) if mode_ok else None + return BatteryRanges(**values) + + # --- reading ------------------------------------------------------------------------------ + + def _number_value(self, number: _Number) -> float | None: + view = self.lookup(number.entity_id) + factor = self._factor(number) + raw = None if view is None else as_float(view.state) + return None if raw is None or factor is None else raw * factor + + def _mode_meaning(self) -> BatteryModeMeaning | None: + if self._mode is None: + return None + view = self.lookup(self._mode[0]) + if view is None: + return None + for option in self._mode[1].options: + if option.value == view.state: + return option.meaning + return BatteryModeMeaning.OTHER + + async def read_back(self) -> Action | None: + """The readable limits; ``None`` when an entity the adapter holds is unavailable.""" + values: dict[str, float | None] = {} + for field, number in self._numbers.items(): + value = self._number_value(number) + if value is None: + return None + values[field] = value + meaning = self._mode_meaning() + if self._mode is not None and meaning is None: + return None + meanings = self._mode_meanings() + if "max_discharge_w" not in values and BatteryModeMeaning.NO_DISCHARGE in meanings: + discharge = meaning is BatteryModeMeaning.NO_DISCHARGE + values["max_discharge_w"] = 0.0 if discharge else self._model.max_discharge_w + if "max_charge_w" not in values and BatteryModeMeaning.NO_CHARGE in meanings: + charge = meaning is BatteryModeMeaning.NO_CHARGE + values["max_charge_w"] = 0.0 if charge else self._model.max_charge_w + if "grid_charge_w" not in values: + if self._switch is not None: + view = self.lookup(self._switch) + if view is None: + return None + values["grid_charge_w"] = self._model.max_charge_w if view.state == "on" else 0.0 + elif BatteryModeMeaning.FORCE_CHARGE in meanings: + forced = meaning is BatteryModeMeaning.FORCE_CHARGE + values["grid_charge_w"] = self._model.max_charge_w if forced else 0.0 + if not values: + return None + grid, cap = values.get("grid_charge_w"), values.get("max_charge_w") + if grid is not None and cap is not None and grid > cap: + values["max_charge_w"] = None # forced charging overrides a cap (report the force) + return BatteryAction(**values) + + # --- writing ------------------------------------------------------------------------------ + + async def apply(self, intent: Intent) -> str | None: + action = self.battery_action(intent) + self.begin() + await self._write_state(action) + self._applied = action + return self.last_context_id() + + async def _write_state(self, action: BatteryAction) -> None: + for field, number in self._numbers.items(): + value = getattr(action, field) + if value is not None: + await self._write_number(number, value) + if self._mode is not None: + await self._write_mode(action) + if self._switch is not None and "grid_charge_w" not in self._numbers: + grid = action.grid_charge_w + if grid is not None: + await self._write_switch(on=grid > 0) + + async def _write_number(self, number: _Number, value: float) -> None: + view = self.lookup(number.entity_id) + factor = self._factor(number) + if view is None or factor is None: + raise WriteRefusedError(f"{number.entity_id} is unavailable") + if not math.isfinite(value): + raise WriteRefusedError(f"{number.field} is not finite") + target = round(value / factor, 6) + current = as_float(view.state) + if current is not None and math.isclose(current, target, abs_tol=SAME_VALUE): + return # write only on change + await self.service( + "number", "set_value", data={"value": target}, entity_id=number.entity_id + ) + + def _wanted_meaning(self, action: BatteryAction) -> BatteryModeMeaning: + meanings = self._mode_meanings() + if ( + "grid_charge_w" not in self._numbers + and self._switch is None + and BatteryModeMeaning.FORCE_CHARGE in meanings + and (action.grid_charge_w or 0) > 0 + ): + return BatteryModeMeaning.FORCE_CHARGE + if ( + "max_discharge_w" not in self._numbers + and BatteryModeMeaning.NO_DISCHARGE in meanings + and action.max_discharge_w is not None + and action.max_discharge_w <= 0 + ): + return BatteryModeMeaning.NO_DISCHARGE + if ( + "max_charge_w" not in self._numbers + and BatteryModeMeaning.NO_CHARGE in meanings + and action.max_charge_w is not None + and action.max_charge_w <= 0 + ): + return BatteryModeMeaning.NO_CHARGE + return BatteryModeMeaning.AUTO + + async def _write_mode(self, action: BatteryAction) -> None: + assert self._mode is not None + entity, control = self._mode + wanted = self._wanted_meaning(action) + option = next(o.value for o in control.options if o.meaning is wanted) + view = self.lookup(entity) + if view is None: + raise WriteRefusedError(f"{entity} is unavailable") + if view.state == option: + return + if wanted is BatteryModeMeaning.AUTO and self._mode_meaning() not in _RESTRICTIVE: + return # nothing to lift: the user's own option (e.g. ``other``) stays + await self.service("select", "select_option", data={"option": option}, entity_id=entity) + + async def _write_switch(self, *, on: bool) -> None: + assert self._switch is not None + view = self.lookup(self._switch) + if view is None: + raise WriteRefusedError(f"{self._switch} is unavailable") + if (view.state == "on") == on: + return + await self.service("switch", "turn_on" if on else "turn_off", entity_id=self._switch) + + async def release(self, baseline: Action | None) -> None: + """Back to the baseline: the numbers SunCore holds, ``auto`` / off for select / switch.""" + self.begin() + self._applied = None + if isinstance(baseline, BatteryAction): + for field, number in self._numbers.items(): + value = getattr(baseline, field) + if value is not None and self.lookup(number.entity_id) is not None: + await self._write_number(number, value) + if self._mode is not None and self.lookup(self._mode[0]) is not None: + auto = next( + o.value for o in self._mode[1].options if o.meaning is BatteryModeMeaning.AUTO + ) + view = self.lookup(self._mode[0]) + if view is not None and view.state != auto: + await self.service( + "select", "select_option", data={"option": auto}, entity_id=self._mode[0] + ) + if ( + self._switch is not None + and "grid_charge_w" not in self._numbers + and self.lookup(self._switch) is not None + ): + await self._write_switch(on=False) + + +__all__ = ["GenericBatteryDriver"] diff --git a/suncore/devices/battery/kostal_modbus.py b/suncore/devices/battery/kostal_modbus.py new file mode 100644 index 0000000..39156ae --- /dev/null +++ b/suncore/devices/battery/kostal_modbus.py @@ -0,0 +1,249 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The ``kostal_modbus`` battery adapter: Kostal §3.5 limits through ``modbus.write_register``. + +Facts (``docs/research/kostal-plenticore-modbus.md`` §3.5 and "Phase 4 verification", +``ha-websocket-api.md`` "Modbus write action"): + +* registers 1280 / 1282 max charge / discharge power (W, float32 in two registers), 1284 / 1286 + the same "in the fallback case", 1288 time until fallback (U32, 30-10800 s). "As soon as + register 1280 or 1282 has been written, they must continue to be written cyclically. If this + no longer happens, after ... (register 1288) the limits in 1284 and 1286 become active": a + documented hardware watchdog; +* external battery management must be enabled: register 1080 = ``0x02``; it is read through a + modbus sensor the user configured, and the adapter refuses every write otherwise; +* ``modbus.write_register`` (hub, ``slave`` - default 1, so the unit id is always sent -, + address, value as a list of raw 16-bit words) has **no float32**, **no read action** and + **only logs a failed write**: the adapter encodes floats itself (word order from register 5, + the battery configuration) and every write is confirmed through the modbus sensors. + +Sequence: before the first limit the fallback registers 1284 / 1286 get the battery's own limits +(1076 / 1078) and 1288 the configured timeout (default 60 s), and the gate reads them back +(:meth:`prepared`) - otherwise nothing else is written. While a limit is held the gate calls +:meth:`keep_alive` every ``heartbeat_s`` (default 20 s) and the adapter re-writes 1280 / 1282. +Release stops the heartbeat and writes the battery's own limits to 1280 / 1282 explicitly; a +dead SunCore leaves the inverter in its own control after the timeout. + +``modbus.write_register`` is a **write** action of this adapter only: it goes through the same +rate-limited ``ServiceCaller.write`` as every device write and is never a read-only action. + +``UNVERIFIED`` on hardware: external battery management is not enabled on the maintainer's +inverter yet; the fallback timer has not been measured (the gate caps this adapter at assisted +until ``battery.fallback_measured``); the U32 word order; the modbus hub set-up through the UI. +""" + +from __future__ import annotations + +from typing import Final + +from suncore.core.battery import ( + BatteryAction, + BatteryCapability, + BatteryRanges, + BatterySettings, + FieldRange, + ModbusLink, +) +from suncore.core.battery_adapter import KOSTAL_MODBUS_ROLES, BatteryAdapterSpec, ModbusRegisterSpec +from suncore.core.decisions import Action, Intent, Reason +from suncore.devices.battery.base import BatteryDriver +from suncore.devices.battery.modbus_codec import float32_words, uint32_words +from suncore.devices.drivers.base import ServiceWriter, StateLookup, WriteRefusedError + +MODBUS_DOMAIN: Final = "modbus" +WRITE_REGISTER: Final = "write_register" +FALLBACK_TOLERANCE_W: Final = 1.0 +DEFAULT_MODBUS_SETTLE_S: Final = 15.0 +"""Until a modbus sensor polled the register again (the user's ``scan_interval``; UNVERIFIED).""" + +REASON_EXTERNAL_CONTROL_OFF: Final = "safety.battery_external_control_off" + + +class KostalModbusDriver(BatteryDriver): + """§3.5 charge/discharge limits with the inverter's own fallback (``kostal_modbus``).""" + + def __init__( + self, + spec: BatteryAdapterSpec, + settings: BatterySettings, + *, + write: ServiceWriter, + states: StateLookup, + ) -> None: + if spec.modbus is None: + msg = "kostal_modbus: the template has no register map" + raise ValueError(msg) + if settings.modbus is None: + msg = "kostal_modbus: battery.modbus (hub, unit id, byte order) is not configured" + raise ValueError(msg) + missing = [r for r in KOSTAL_MODBUS_ROLES if r not in settings.entities] + if missing: + msg = f"kostal_modbus: unmapped roles {', '.join(missing)}" + raise ValueError(msg) + settle = spec.settle_s if spec.settle_s is not None else DEFAULT_MODBUS_SETTLE_S + super().__init__(settings, write=write, states=states, settle_s=settle) + self._registers: ModbusRegisterSpec = spec.modbus + self._link: ModbusLink = settings.modbus + timeout = self._link.fallback_timeout_s + if not ( + self._registers.fallback_timeout_min_s + <= timeout + <= self._registers.fallback_timeout_max_s + ): + msg = "kostal_modbus: fallback_timeout_s outside the register's range" + raise ValueError(msg) + + @property + def capabilities(self) -> frozenset[BatteryCapability]: + return frozenset( + { + BatteryCapability.CHARGE_LIMIT, + BatteryCapability.DISCHARGE_LIMIT, + BatteryCapability.HARDWARE_FALLBACK, + } + ) + + @property + def heartbeat_s(self) -> float | None: + return self._link.heartbeat_s + + @property + def link(self) -> ModbusLink: + return self._link + + # --- reading ------------------------------------------------------------------------------ + + def own_limits(self) -> tuple[float, float] | None: + """The battery's own charge / discharge limits (registers 1076 / 1078).""" + charge = self.value_of("own_charge_limit") + discharge = self.value_of("own_discharge_limit") + if charge is None or discharge is None or charge < 0 or discharge < 0: + return None + return charge, discharge + + def refusal(self) -> Reason | None: + value = self.value_of("external_control") + expected = self._registers.external_control_value + if value is None or round(value) != expected: + return Reason( + key=REASON_EXTERNAL_CONTROL_OFF, + args={ + "value": "unknown" if value is None else str(round(value)), + "expected": expected, + }, + ) + if self.own_limits() is None: + return Reason(key="safety.battery_range_unknown", args={"field": "own_limits"}) + return None + + def ranges(self) -> BatteryRanges: + own = self.own_limits() + if own is None: + return BatteryRanges() + return BatteryRanges( + max_charge_w=FieldRange(0.0, min(own[0], self._model.max_charge_w)), + max_discharge_w=FieldRange(0.0, min(own[1], self._model.max_discharge_w)), + ) + + def prepared(self) -> bool: + own = self.own_limits() + charge = self.value_of("fallback_charge_limit") + discharge = self.value_of("fallback_discharge_limit") + timeout = self.value_of("fallback_timeout") + if own is None or charge is None or discharge is None or timeout is None: + return False + return ( + abs(charge - own[0]) <= FALLBACK_TOLERANCE_W + and abs(discharge - own[1]) <= FALLBACK_TOLERANCE_W + and round(timeout) == self._link.fallback_timeout_s + ) + + async def read_back(self) -> Action | None: + charge = self.value_of("charge_limit") + discharge = self.value_of("discharge_limit") + if charge is None or discharge is None: + return None + return BatteryAction(max_charge_w=max(0.0, charge), max_discharge_w=max(0.0, discharge)) + + # --- writing ------------------------------------------------------------------------------ + + async def _register(self, address: int, words: list[int]) -> None: + await self.service( + MODBUS_DOMAIN, + WRITE_REGISTER, + data={ + "hub": self._link.hub, + "slave": self._link.slave, + "address": address, + "value": words, + }, + ) + + async def _float(self, address: int, value: float) -> None: + await self._register(address, float32_words(float(value), self._link.byte_order)) + + async def arm_fallback(self) -> None: + """Fallback registers first: own limits to 1284 / 1286, the timeout to 1288.""" + if self.refusal() is not None: + raise WriteRefusedError("external battery management is not enabled (1080)") + own = self.own_limits() + assert own is not None + self.begin() + await self._float(self._registers.fallback_max_charge, own[0]) + await self._float(self._registers.fallback_max_discharge, own[1]) + await self._register( + self._registers.fallback_timeout, + uint32_words(self._link.fallback_timeout_s, self._link.byte_order), + ) + + async def _write_limits(self, action: BatteryAction) -> None: + own = self.own_limits() + assert own is not None + charge = own[0] if action.max_charge_w is None else action.max_charge_w + discharge = own[1] if action.max_discharge_w is None else action.max_discharge_w + # Both registers every time: the pair is the state the inverter holds (and re-writing + # both keeps the documented "written cyclically" condition for either). + await self._float(self._registers.max_charge, charge) + await self._float(self._registers.max_discharge, discharge) + + async def apply(self, intent: Intent) -> str | None: + action = self.battery_action(intent) + refusal = self.refusal() + if refusal is not None: + raise WriteRefusedError(refusal.key) + if not self.prepared(): + raise WriteRefusedError("the fallback registers are not confirmed") + self.begin() + await self._write_limits(action) + self._applied = action + return self.last_context_id() + + async def keep_alive(self) -> None: + """Re-write the held limits (only while the gate's lease holds).""" + action = self._applied + if action is None or self.refusal() is not None: + return + self.begin() + await self._write_limits(action) + + async def release(self, baseline: Action | None) -> None: # noqa: ARG002 - see below + """Stop the heartbeat and give the inverter its own limits back explicitly. + + The release target of §3.5 is the battery's own limits (the fallback values), not the + takeover read-back of 1280 / 1282, which may hold a stale foreign value. Without the + own limits nothing is written: the stopped heartbeat lets the inverter fall back. + """ + self._applied = None + self.begin() + own = self.own_limits() + if own is None or self.refusal() is not None: + return + await self._float(self._registers.max_charge, own[0]) + await self._float(self._registers.max_discharge, own[1]) + + +__all__ = [ + "MODBUS_DOMAIN", + "REASON_EXTERNAL_CONTROL_OFF", + "WRITE_REGISTER", + "KostalModbusDriver", +] diff --git a/suncore/devices/battery/kostal_plenticore.py b/suncore/devices/battery/kostal_plenticore.py new file mode 100644 index 0000000..6446a28 --- /dev/null +++ b/suncore/devices/battery/kostal_plenticore.py @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The ``kostal_plenticore`` battery adapter: the core integration's ``Battery:MinSoc`` number. + +Facts (``docs/research/integrations.md`` "Kostal Plenticore", HA core ``5cfe9aad`` +``components/kostal_plenticore/{number,select,coordinator}.py``): + +* ``number`` "Battery min SoC" (``devices:local`` / ``Battery:MinSoc``, %, default 5-100 step 5; + the live ``min``/``max`` attributes come from the inverter). **Disabled by default** (the user + enables it), no translation key, ``unique_id`` suffix ``devices:local_Battery:MinSoc``. +* ``number.set_value`` writes immediately over REST, then refreshes the settings coordinator. + **A failed write is silent** (``async_write_data`` swallows ``ApiException``), so a write is + believed only when the entity shows the value afterwards: the gate's read-back after + ``settle_s`` (35 s: the settings coordinator polls every 30 s - should the forced refresh not + land, the next poll does) is mandatory and a mismatch is a failed write. +* The select "Battery charging / usage mode" (``None`` / ``SmartBatteryControl`` / + ``TimeControl``) reports a written option only after the next 30 s poll; this adapter only + **reads** it (shown in the state, never written). +* **No charge or discharge power set-point** exists over REST: the capabilities are ``min_soc`` + only. A discharge lock is ``min_soc_pct`` at (rounded up to the step) the live SoC, the reserve + a floor at the effective reserve; grid charging is not executable (plan and shadow only). +* No hardware fallback: a floor SunCore wrote survives a SunCore crash until ``recover()`` at the + next start releases it (ADR-0013 risk); the gate holds it only while the plan interval asks. + +``UNVERIFIED`` on hardware: the read-back timing after the forced refresh; whether the +inverter rejects values outside its live range or clamps them. +""" + +from __future__ import annotations + +from typing import Final + +from suncore.core.battery import BatterySettings +from suncore.core.battery_adapter import BatteryAdapterSpec +from suncore.devices.battery.generic import GenericBatteryDriver +from suncore.devices.drivers.base import ServiceWriter, StateLookup + +KOSTAL_REST_SETTLE_S: Final = 35.0 +"""One settings poll (30 s) plus margin.""" +CHARGE_MODE_ROLE: Final = "charge_mode" +"""The read-only select role (``None`` / ``Battery:SmartBatteryControl:Enable`` / ...).""" + + +class KostalPlenticoreDriver(GenericBatteryDriver): + """``min_soc`` through ``number.<...>_battery_min_soc`` of ``kostal_plenticore``.""" + + def __init__( + self, + spec: BatteryAdapterSpec, + settings: BatterySettings, + *, + write: ServiceWriter, + states: StateLookup, + ) -> None: + if spec.control_kinds() != {"min_soc"}: + msg = "kostal_plenticore: the template must have exactly one `min_soc` control" + raise ValueError(msg) + super().__init__(spec, settings, write=write, states=states) + self._settle_s = max(self._settle_s, KOSTAL_REST_SETTLE_S) + + def charge_mode(self) -> str | None: + """The inverter's battery usage mode as the select shows it (read only).""" + view = self.lookup(self.entity_id(CHARGE_MODE_ROLE)) + return None if view is None else view.state + + +__all__ = ["CHARGE_MODE_ROLE", "KOSTAL_REST_SETTLE_S", "KostalPlenticoreDriver"] diff --git a/suncore/devices/battery/modbus_codec.py b/suncore/devices/battery/modbus_codec.py new file mode 100644 index 0000000..d873f70 --- /dev/null +++ b/suncore/devices/battery/modbus_codec.py @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: Apache-2.0 +"""32-bit values as two Modbus registers for ``modbus.write_register`` (pure). + +HA's ``modbus.write_register`` takes raw unsigned 16-bit words only (no float32, research +``ha-websocket-api.md`` "Modbus write action"); the adapter encodes. Kostal register 5 tells the +word order (``kostal-plenticore-modbus.md`` "Connection"): ``0x00`` little-endian = CDAB (the +low word first, the default), ``0x01`` big-endian = ABCD (the high word first, SunSpec). The +same word order is assumed for the unsigned 32-bit timeout (``UNVERIFIED``: the document states +the byte order for "float/32-bit registers"). +""" + +from __future__ import annotations + +import math +import struct + +from suncore.core.battery import ModbusByteOrder + + +def _ordered(high: int, low: int, order: ModbusByteOrder) -> list[int]: + return [high, low] if order is ModbusByteOrder.BIG else [low, high] + + +def float32_words(value: float, order: ModbusByteOrder) -> list[int]: + """IEEE 754 single precision as two 16-bit words in the given word order.""" + if not math.isfinite(value): + msg = "a register value must be finite" + raise ValueError(msg) + (raw,) = struct.unpack(">I", struct.pack(">f", value)) + return _ordered(raw >> 16, raw & 0xFFFF, order) + + +def words_float32(words: list[int], order: ModbusByteOrder) -> float: + """The inverse of :func:`float32_words` (tests, the simulator).""" + high, low = (words[0], words[1]) if order is ModbusByteOrder.BIG else (words[1], words[0]) + (value,) = struct.unpack(">f", struct.pack(">I", (high << 16) | low)) + return float(value) + + +def uint32_words(value: int, order: ModbusByteOrder) -> list[int]: + """An unsigned 32-bit value as two 16-bit words in the given word order.""" + if not 0 <= value <= 0xFFFFFFFF: + msg = "an U32 register value must lie in 0..2**32-1" + raise ValueError(msg) + return _ordered(value >> 16, value & 0xFFFF, order) + + +def words_uint32(words: list[int], order: ModbusByteOrder) -> int: + high, low = (words[0], words[1]) if order is ModbusByteOrder.BIG else (words[1], words[0]) + return (high << 16) | low + + +__all__ = ["float32_words", "uint32_words", "words_float32", "words_uint32"] diff --git a/suncore/safety/battery.py b/suncore/safety/battery.py index ddd9840..62f49e4 100644 --- a/suncore/safety/battery.py +++ b/suncore/safety/battery.py @@ -66,7 +66,7 @@ class BatteryActuator(Actuator, Protocol): ``apply`` receives an intent whose ``BatteryAction`` the gate already resolved (``None`` = baseline) and quantised; ``read_back`` reports the adapter's readable limits as a ``BatteryAction`` (fields it cannot read are ``None``). Only the gate calls ``apply``, - ``release``, ``prepare`` and ``heartbeat`` (``tests/safety/test_boundary.py``). + ``release``, ``arm_fallback`` and ``keep_alive`` (``tests/safety/test_boundary.py``). """ @property @@ -98,12 +98,12 @@ def prepared(self) -> bool: adapters without one).""" ... - async def prepare(self) -> None: + async def arm_fallback(self) -> None: """Write the hardware fallback (Kostal §3.5: 1284/1286 = own limits, 1288 = timeout) before the first limit; the gate reads back with :meth:`prepared`.""" ... - async def heartbeat(self) -> None: + async def keep_alive(self) -> None: """Re-write the last applied state (idempotent; called only while the lease holds).""" ... diff --git a/suncore/templates/models.py b/suncore/templates/models.py index 32dd05e..7b632a0 100644 --- a/suncore/templates/models.py +++ b/suncore/templates/models.py @@ -30,6 +30,16 @@ ) from suncore.core.actions import ERR_ACTION_NOT_ALLOWED, is_read_only_action +from suncore.core.battery_adapter import ( + KOSTAL_MODBUS_ROLES, + BatteryAdapterSpec, + BatteryDriverKind, + BatteryModeMeaning, + ModbusRegisterSpec, + ModeOptionSpec, + ModeSelectSpec, + NumberLimitSpec, +) from suncore.core.capabilities import Capability from suncore.core.config import REGION_ID_PATTERN from suncore.core.decisions import REASON_KEY_PATTERN @@ -749,20 +759,6 @@ def _range(self) -> Self: return self -@unique -class BatteryModeMeaning(StrEnum): - """What selecting a battery mode option does.""" - - AUTO = "auto" - """The inverter's own control (the release baseline).""" - FORCE_CHARGE = "force_charge" - """Charge, also from the grid.""" - NO_DISCHARGE = "no_discharge" - NO_CHARGE = "no_charge" - OTHER = "other" - """Any other option; SunCore never selects it.""" - - OptionValue = Annotated[str, StringConstraints(min_length=1, max_length=200)] """A select option exactly as the entity lists it (whitespace is significant).""" @@ -814,6 +810,45 @@ class ForceChargeSwitchControl(_Frozen): } +class ModbusRegisterMap(_Frozen): + """Registers of a limit-with-fallback battery interface (Kostal §3.5, ``kostal_modbus``). + + Addresses as the vendor document gives them (the HA action writes them verbatim). Powers + are IEEE 754 float32 in two registers, the timeout an unsigned 32-bit value in two + registers; the word order comes from the battery configuration (``battery.modbus``). + ``external_control_value`` is what ``external_control_register`` must read before any + write (Kostal 1080 = ``0x02``: external battery management via Modbus). + """ + + max_charge: Annotated[int, Field(ge=0, le=65_534)] + max_discharge: Annotated[int, Field(ge=0, le=65_534)] + fallback_max_charge: Annotated[int, Field(ge=0, le=65_534)] + fallback_max_discharge: Annotated[int, Field(ge=0, le=65_534)] + fallback_timeout: Annotated[int, Field(ge=0, le=65_534)] + fallback_timeout_min_s: Annotated[int, Field(ge=1)] + fallback_timeout_max_s: Annotated[int, Field(ge=1)] + external_control_register: Annotated[int, Field(ge=0, le=65_535)] + external_control_value: Annotated[int, Field(ge=0, le=65_535)] + + @model_validator(mode="after") + def _registers(self) -> Self: + words = [ + self.max_charge, + self.max_discharge, + self.fallback_max_charge, + self.fallback_max_discharge, + self.fallback_timeout, + ] + cells = [w + i for w in words for i in (0, 1)] + if len(set(cells)) != len(cells): + msg = "modbus: the two-register values overlap" + raise ValueError(msg) + if self.fallback_timeout_min_s > self.fallback_timeout_max_s: + msg = "modbus: fallback_timeout_min_s above fallback_timeout_max_s" + raise ValueError(msg) + return self + + class BatteryTemplate(TemplateHeader): """Battery adapter template (Phase 4, ADR-0006/ADR-0012 kind ``battery``). @@ -830,6 +865,13 @@ class BatteryTemplate(TemplateHeader): ) settle_s: Annotated[int, Field(ge=0, le=600)] | None = None """Delay before the read-back after a write.""" + driver: BatteryDriverKind = "generic" + """The adapter (WP10): ``generic`` (the ``controls`` above), ``kostal_plenticore`` (the core + integration: only a ``min_soc`` control, read-back after a forced refresh), ``kostal_modbus`` + (§3.5 limits through ``modbus.write_register``; needs ``modbus`` and the roles of + :data:`KOSTAL_MODBUS_ROLES`).""" + modbus: ModbusRegisterMap | None = None + """``kostal_modbus`` only: the register map.""" @model_validator(mode="after") def _battery(self) -> Self: @@ -837,6 +879,7 @@ def _battery(self) -> Self: msg = "id: must be `.`" raise ValueError(msg) _check_roles(self.roles) + self._driver() kinds: list[str] = [] for role, control in self.controls.items(): if role not in self.roles: @@ -853,8 +896,31 @@ def _battery(self) -> Self: self._capabilities(set(kinds)) return self + def _driver(self) -> None: + kinds = {c.kind for c in self.controls.values()} + if self.driver == "kostal_modbus": + if self.modbus is None: + msg = "driver `kostal_modbus` needs a `modbus` register map" + raise ValueError(msg) + missing = [r for r in KOSTAL_MODBUS_ROLES if r not in self.roles] + if missing: + msg = f"driver `kostal_modbus` needs the roles {', '.join(missing)}" + raise ValueError(msg) + if self.controls: + msg = "driver `kostal_modbus` writes registers, it takes no `controls`" + raise ValueError(msg) + return + if self.modbus is not None: + msg = "`modbus` belongs to driver `kostal_modbus` only" + raise ValueError(msg) + if self.driver == "kostal_plenticore" and kinds != {"min_soc"}: + msg = "driver `kostal_plenticore` has exactly one control, `min_soc` (no set-point)" + raise ValueError(msg) + def _capabilities(self, kinds: set[str]) -> None: caps = self.capabilities + modbus = self.driver == "kostal_modbus" + _need(caps, Capability.HARDWARE_FALLBACK, modbus, "no driver with a hardware fallback") classes = {r.matcher.device_class for r in self.roles.values()} modes = { o.meaning @@ -869,9 +935,17 @@ def _capabilities(self, kinds: set[str]) -> None: caps, Capability.POWER_MEASURED, "power" in classes, "no role with device_class power" ) _need(caps, Capability.MIN_SOC_LIMIT, "min_soc" in kinds, "no `min_soc` control") - _need(caps, Capability.CHARGE_LIMIT, "max_charge" in kinds, "no `max_charge` control") _need( - caps, Capability.DISCHARGE_LIMIT, "max_discharge" in kinds, "no `max_discharge` control" + caps, + Capability.CHARGE_LIMIT, + modbus or "max_charge" in kinds or BatteryModeMeaning.NO_CHARGE in modes, + "no `max_charge` control", + ) + _need( + caps, + Capability.DISCHARGE_LIMIT, + modbus or "max_discharge" in kinds or BatteryModeMeaning.NO_DISCHARGE in modes, + "no `max_discharge` control", ) _need( caps, @@ -885,6 +959,44 @@ def _capabilities(self, kinds: set[str]) -> None: def message_keys(self) -> list[str]: return [self.name, *(r.description for r in self.roles.values())] + def adapter_spec(self) -> BatteryAdapterSpec: + """The template as the battery adapters see it (core data, ``suncore.devices`` imports + no template model).""" + numbers: list[NumberLimitSpec] = [] + mode: ModeSelectSpec | None = None + switch: str | None = None + for role, control in self.controls.items(): + if isinstance(control, NumberLimitControl): + numbers.append( + NumberLimitSpec( + role=role, + kind=control.kind, + unit=control.unit, + min=control.min, + max=control.max, + step=control.step, + ) + ) + elif isinstance(control, ModeSelectControl): + mode = ModeSelectSpec( + role=role, + options=tuple(ModeOptionSpec(o.value, o.meaning) for o in control.options), + ) + else: + switch = role + registers = None + if self.modbus is not None: + registers = ModbusRegisterSpec(**self.modbus.model_dump()) + return BatteryAdapterSpec( + template_id=self.id, + driver=self.driver, + settle_s=None if self.settle_s is None else float(self.settle_s), + numbers=tuple(numbers), + mode=mode, + force_switch_role=switch, + modbus=registers, + ) + Template = Annotated[ DeviceTemplate | TariffTemplate | ForecastTemplate | RegionTemplate | BatteryTemplate, @@ -908,6 +1020,7 @@ def message_keys(self) -> list[str]: __all__ = [ "KIND_MODELS", + "KOSTAL_MODBUS_ROLES", "PRICE_ENERGY_FACTORS", "PRICE_UNIT_PATTERN", "REGION_ID_PATTERN", @@ -919,6 +1032,7 @@ def message_keys(self) -> list[str]: "ActionSeries", "AttributeSeries", "BatteryControl", + "BatteryDriverKind", "BatteryModeMeaning", "BatteryModeOption", "BatteryTemplate", @@ -930,6 +1044,7 @@ def message_keys(self) -> list[str]: "ForceChargeSwitchControl", "ForecastSeriesSource", "ForecastTemplate", + "ModbusRegisterMap", "ModeSelectControl", "NegativePriceRule", "NumberLimitControl", diff --git a/templates/battery/generic.battery.yaml b/templates/battery/generic.battery.yaml new file mode 100644 index 0000000..d1ae649 --- /dev/null +++ b/templates/battery/generic.battery.yaml @@ -0,0 +1,57 @@ +# yaml-language-server: $schema=../schema/battery.schema.json +# Any battery whose limits Home Assistant exposes as `number` entities (a min-SoC floor, charge +# and discharge power caps, a forced grid-charge power). Every role is optional: SunCore can only +# do what the mapped roles express (the adapter's capabilities follow the mapping). The battery's +# state of charge and power come from the site configuration, not from this template. +# Copy into /data/templates/battery/ and adapt `controls` (unit W, kW or %, min, max, step) to +# the integration; a `mode` select (meanings auto / no_discharge / no_charge / force_charge / +# other) or a `force_charge` switch are possible as well (see templates/README.md). +id: generic.battery +kind: battery +schema_version: 1 +name: template.generic.battery.name +source: + - title: "home-assistant/core number/__init__.py and const.py (set_value, value, min, max, step; branch dev)" + url: "https://github.com/home-assistant/core/blob/dev/homeassistant/components/number/__init__.py" + date: 2026-10-13 + - title: "ADR-0013 Battery as a controlled asset (limits, None = baseline, capabilities)" + url: "https://github.com/pxljake/SunCore/blob/main/docs/adr/0013-battery-as-controlled-asset.md" + date: 2026-10-24 +tested_with: [] +capabilities: [min_soc_limit, charge_limit, discharge_limit, grid_charge] +unverified: + - "Generic template, exercised in the simulator only; no real battery has been driven through it." + - "min, max and step are placeholders; the live entity's min/max/step attributes are used where they are narrower." + - "Whether an integration applies a number immediately or only after its next poll is integration specific: set settle_s accordingly." +driver: generic +settle_s: 10 +roles: + min_soc_number: + required: false + matcher: + domain: number + units: ["%"] + description: template.generic.battery.role.min_soc_number + max_charge_number: + required: false + matcher: + domain: number + units: [W, kW] + description: template.generic.battery.role.max_charge_number + max_discharge_number: + required: false + matcher: + domain: number + units: [W, kW] + description: template.generic.battery.role.max_discharge_number + grid_charge_number: + required: false + matcher: + domain: number + units: [W, kW] + description: template.generic.battery.role.grid_charge_number +controls: + min_soc_number: { kind: min_soc, unit: "%", min: 0, max: 100, step: 1 } + max_charge_number: { kind: max_charge, unit: W, min: 0, max: 30000 } + max_discharge_number: { kind: max_discharge, unit: W, min: 0, max: 30000 } + grid_charge_number: { kind: grid_charge_power, unit: W, min: 0, max: 30000 } diff --git a/templates/battery/kostal.plenticore.yaml b/templates/battery/kostal.plenticore.yaml new file mode 100644 index 0000000..ccdb4e8 --- /dev/null +++ b/templates/battery/kostal.plenticore.yaml @@ -0,0 +1,45 @@ +# yaml-language-server: $schema=../schema/battery.schema.json +# KOSTAL PLENTICORE through the Home Assistant core integration `kostal_plenticore` (REST API, +# `pykoplenti`). The only battery limit it exposes is the inverter's minimum state of charge +# (`Battery:MinSoc`): SunCore uses it as the reserve floor and as a discharge lock. There is no +# charge or discharge power set-point over REST, so grid charging is planned and shown, never +# executed through this adapter. The number entity is DISABLED BY DEFAULT in Home Assistant: +# enable "Battery min SoC" on the inverter's device page first. +id: kostal.plenticore +kind: battery +schema_version: 1 +name: template.kostal.plenticore.name +source: + - title: "home-assistant/core 5cfe9aad kostal_plenticore/number.py (Battery:MinSoc, 5-100 step 5, disabled by default, live min/max)" + url: "https://github.com/home-assistant/core/blob/5cfe9aad7cb428c2c2ebb449719ae81976780de1/homeassistant/components/kostal_plenticore/number.py" + date: 2026-10-16 + - title: "home-assistant/core 5cfe9aad kostal_plenticore/coordinator.py (a failed write is silent; settings poll 30 s)" + url: "https://github.com/home-assistant/core/blob/5cfe9aad7cb428c2c2ebb449719ae81976780de1/homeassistant/components/kostal_plenticore/coordinator.py" + date: 2026-10-16 + - title: "home-assistant/core 5cfe9aad kostal_plenticore/select.py (battery usage mode, read-back lags one 30 s poll)" + url: "https://github.com/home-assistant/core/blob/5cfe9aad7cb428c2c2ebb449719ae81976780de1/homeassistant/components/kostal_plenticore/select.py" + date: 2026-10-16 +tested_with: [] +capabilities: [min_soc_limit] +unverified: + - "Read from the integration source only; no write has been made on the maintainer's inverter yet." + - "The number has no translation key; it is matched by platform, domain and unit only (unique_id suffix devices:local_Battery:MinSoc is not visible to the matcher)." + - "A failed REST write is silent: SunCore believes a write only when the entity shows the value after settle_s (35 s, one settings poll plus margin)." + - "Whether the inverter clamps or rejects a value outside its live min/max." +driver: kostal_plenticore +settle_s: 35 +roles: + min_soc_number: + matcher: + domain: number + platforms: [kostal_plenticore] + units: ["%"] + description: template.kostal.plenticore.role.min_soc_number + charge_mode: + required: false + matcher: + domain: select + platforms: [kostal_plenticore] + description: template.kostal.plenticore.role.charge_mode +controls: + min_soc_number: { kind: min_soc, unit: "%", min: 5, max: 100, step: 5 } diff --git a/templates/battery/kostal.plenticore_g3_modbus.yaml b/templates/battery/kostal.plenticore_g3_modbus.yaml new file mode 100644 index 0000000..6f6fd16 --- /dev/null +++ b/templates/battery/kostal.plenticore_g3_modbus.yaml @@ -0,0 +1,67 @@ +# yaml-language-server: $schema=../schema/battery.schema.json +# KOSTAL PLENTICORE G3 (SW >= 03.05) battery limitation §3.5 over Modbus TCP, written through +# Home Assistant's `modbus.write_register` and read back through `modbus:` YAML sensors. +# Prerequisites (all done by the user, see the documentation): +# * a `modbus:` hub in configuration.yaml (port 1502, unit id of the inverter, default 71); +# * "External battery management via Modbus" enabled in the inverter (register 1080 = 2); +# * one float32 sensor per register 1280, 1282, 1284, 1286, 1076, 1078, one uint32 sensor for +# 1288 and one for 1080, decoded with the inverter's byte order (register 5); +# * `battery.modbus` in SunCore: hub name, unit id, byte order. +# Until the fallback timer was measured on the real inverter (`battery.fallback_measured`) the +# battery is capped at assisted mode. +id: kostal.plenticore_g3_modbus +kind: battery +schema_version: 1 +name: template.kostal.plenticore_g3_modbus.name +source: + - title: "KOSTAL PLENTICORE Modbus TCP interface description rev. 2.9: §3.5 limits 1280-1288, 1080, 1076/1078 (research summary)" + url: "https://github.com/pxljake/SunCore/blob/main/docs/research/kostal-plenticore-modbus.md" + date: 2026-10-12 + - title: "home-assistant/core 5cfe9aad modbus/services.py (write_register: hub, slave default 1, raw 16-bit words, no float32, failures only logged)" + url: "https://github.com/home-assistant/core/blob/5cfe9aad7cb428c2c2ebb449719ae81976780de1/homeassistant/components/modbus/services.py" + date: 2026-10-16 +tested_with: [] +capabilities: [charge_limit, discharge_limit, hardware_fallback] +unverified: + - "External battery management via Modbus is not enabled on the maintainer's inverter: the adapter runs in the simulator only." + - "The fallback timer (register 1288) behaviour has not been measured on hardware; the battery stays capped at assisted until it is." + - "The word order of the U32 timeout is assumed to follow register 5 like the floats." + - "Whether a modbus hub can be created from the Home Assistant UI (YAML is assumed)." + - "settle_s depends on the scan_interval of the user's modbus sensors (15 s assumed)." +driver: kostal_modbus +settle_s: 15 +modbus: + max_charge: 1280 + max_discharge: 1282 + fallback_max_charge: 1284 + fallback_max_discharge: 1286 + fallback_timeout: 1288 + fallback_timeout_min_s: 30 + fallback_timeout_max_s: 10800 + external_control_register: 1080 + external_control_value: 2 +roles: + external_control: + matcher: { domain: sensor, platforms: [modbus] } + description: template.kostal.plenticore_g3_modbus.role.external_control + charge_limit: + matcher: { domain: sensor, platforms: [modbus], units: [W] } + description: template.kostal.plenticore_g3_modbus.role.charge_limit + discharge_limit: + matcher: { domain: sensor, platforms: [modbus], units: [W] } + description: template.kostal.plenticore_g3_modbus.role.discharge_limit + fallback_charge_limit: + matcher: { domain: sensor, platforms: [modbus], units: [W] } + description: template.kostal.plenticore_g3_modbus.role.fallback_charge_limit + fallback_discharge_limit: + matcher: { domain: sensor, platforms: [modbus], units: [W] } + description: template.kostal.plenticore_g3_modbus.role.fallback_discharge_limit + fallback_timeout: + matcher: { domain: sensor, platforms: [modbus], units: [s] } + description: template.kostal.plenticore_g3_modbus.role.fallback_timeout + own_charge_limit: + matcher: { domain: sensor, platforms: [modbus], units: [W] } + description: template.kostal.plenticore_g3_modbus.role.own_charge_limit + own_discharge_limit: + matcher: { domain: sensor, platforms: [modbus], units: [W] } + description: template.kostal.plenticore_g3_modbus.role.own_discharge_limit diff --git a/templates/schema/battery.schema.json b/templates/schema/battery.schema.json index b80c294..b8fea37 100644 --- a/templates/schema/battery.schema.json +++ b/templates/schema/battery.schema.json @@ -54,7 +54,8 @@ "charge_limit", "discharge_limit", "grid_charge", - "battery_modes" + "battery_modes", + "hardware_fallback" ], "title": "Capability", "type": "string" @@ -195,6 +196,77 @@ "title": "ForceChargeSwitchControl", "type": "object" }, + "ModbusRegisterMap": { + "additionalProperties": false, + "description": "Registers of a limit-with-fallback battery interface (Kostal §3.5, ``kostal_modbus``).\n\nAddresses as the vendor document gives them (the HA action writes them verbatim). Powers\nare IEEE 754 float32 in two registers, the timeout an unsigned 32-bit value in two\nregisters; the word order comes from the battery configuration (``battery.modbus``).\n``external_control_value`` is what ``external_control_register`` must read before any\nwrite (Kostal 1080 = ``0x02``: external battery management via Modbus).", + "properties": { + "external_control_register": { + "maximum": 65535, + "minimum": 0, + "title": "External Control Register", + "type": "integer" + }, + "external_control_value": { + "maximum": 65535, + "minimum": 0, + "title": "External Control Value", + "type": "integer" + }, + "fallback_max_charge": { + "maximum": 65534, + "minimum": 0, + "title": "Fallback Max Charge", + "type": "integer" + }, + "fallback_max_discharge": { + "maximum": 65534, + "minimum": 0, + "title": "Fallback Max Discharge", + "type": "integer" + }, + "fallback_timeout": { + "maximum": 65534, + "minimum": 0, + "title": "Fallback Timeout", + "type": "integer" + }, + "fallback_timeout_max_s": { + "minimum": 1, + "title": "Fallback Timeout Max S", + "type": "integer" + }, + "fallback_timeout_min_s": { + "minimum": 1, + "title": "Fallback Timeout Min S", + "type": "integer" + }, + "max_charge": { + "maximum": 65534, + "minimum": 0, + "title": "Max Charge", + "type": "integer" + }, + "max_discharge": { + "maximum": 65534, + "minimum": 0, + "title": "Max Discharge", + "type": "integer" + } + }, + "required": [ + "max_charge", + "max_discharge", + "fallback_max_charge", + "fallback_max_discharge", + "fallback_timeout", + "fallback_timeout_min_s", + "fallback_timeout_max_s", + "external_control_register", + "external_control_value" + ], + "title": "ModbusRegisterMap", + "type": "object" + }, "ModeSelectControl": { "additionalProperties": false, "description": "A ``select`` role choosing the battery's operating mode.", @@ -415,6 +487,16 @@ "title": "Controls", "type": "object" }, + "driver": { + "default": "generic", + "enum": [ + "generic", + "kostal_plenticore", + "kostal_modbus" + ], + "title": "Driver", + "type": "string" + }, "id": { "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)?$", @@ -439,6 +521,17 @@ "default": null, "title": "Min App Version" }, + "modbus": { + "anyOf": [ + { + "$ref": "#/$defs/ModbusRegisterMap" + }, + { + "type": "null" + } + ], + "default": null + }, "name": { "maxLength": 120, "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$", diff --git a/templates/schema/device.schema.json b/templates/schema/device.schema.json index 65a4352..6a94a60 100644 --- a/templates/schema/device.schema.json +++ b/templates/schema/device.schema.json @@ -22,7 +22,8 @@ "charge_limit", "discharge_limit", "grid_charge", - "battery_modes" + "battery_modes", + "hardware_fallback" ], "title": "Capability", "type": "string" diff --git a/templates/schema/forecast.schema.json b/templates/schema/forecast.schema.json index 100b1dd..454a118 100644 --- a/templates/schema/forecast.schema.json +++ b/templates/schema/forecast.schema.json @@ -224,7 +224,8 @@ "charge_limit", "discharge_limit", "grid_charge", - "battery_modes" + "battery_modes", + "hardware_fallback" ], "title": "Capability", "type": "string" diff --git a/templates/schema/region.schema.json b/templates/schema/region.schema.json index 172aa79..108c913 100644 --- a/templates/schema/region.schema.json +++ b/templates/schema/region.schema.json @@ -22,7 +22,8 @@ "charge_limit", "discharge_limit", "grid_charge", - "battery_modes" + "battery_modes", + "hardware_fallback" ], "title": "Capability", "type": "string" diff --git a/templates/schema/tariff.schema.json b/templates/schema/tariff.schema.json index ad01729..fb02604 100644 --- a/templates/schema/tariff.schema.json +++ b/templates/schema/tariff.schema.json @@ -224,7 +224,8 @@ "charge_limit", "discharge_limit", "grid_charge", - "battery_modes" + "battery_modes", + "hardware_fallback" ], "title": "Capability", "type": "string" diff --git a/templates/schema/template.schema.json b/templates/schema/template.schema.json index 8fe0013..fab22ab 100644 --- a/templates/schema/template.schema.json +++ b/templates/schema/template.schema.json @@ -277,6 +277,16 @@ "title": "Controls", "type": "object" }, + "driver": { + "default": "generic", + "enum": [ + "generic", + "kostal_plenticore", + "kostal_modbus" + ], + "title": "Driver", + "type": "string" + }, "id": { "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)?$", @@ -301,6 +311,17 @@ "default": null, "title": "Min App Version" }, + "modbus": { + "anyOf": [ + { + "$ref": "#/$defs/ModbusRegisterMap" + }, + { + "type": "null" + } + ], + "default": null + }, "name": { "maxLength": 120, "pattern": "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$", @@ -395,7 +416,8 @@ "charge_limit", "discharge_limit", "grid_charge", - "battery_modes" + "battery_modes", + "hardware_fallback" ], "title": "Capability", "type": "string" @@ -1110,6 +1132,77 @@ "title": "ForecastTemplate", "type": "object" }, + "ModbusRegisterMap": { + "additionalProperties": false, + "description": "Registers of a limit-with-fallback battery interface (Kostal §3.5, ``kostal_modbus``).\n\nAddresses as the vendor document gives them (the HA action writes them verbatim). Powers\nare IEEE 754 float32 in two registers, the timeout an unsigned 32-bit value in two\nregisters; the word order comes from the battery configuration (``battery.modbus``).\n``external_control_value`` is what ``external_control_register`` must read before any\nwrite (Kostal 1080 = ``0x02``: external battery management via Modbus).", + "properties": { + "external_control_register": { + "maximum": 65535, + "minimum": 0, + "title": "External Control Register", + "type": "integer" + }, + "external_control_value": { + "maximum": 65535, + "minimum": 0, + "title": "External Control Value", + "type": "integer" + }, + "fallback_max_charge": { + "maximum": 65534, + "minimum": 0, + "title": "Fallback Max Charge", + "type": "integer" + }, + "fallback_max_discharge": { + "maximum": 65534, + "minimum": 0, + "title": "Fallback Max Discharge", + "type": "integer" + }, + "fallback_timeout": { + "maximum": 65534, + "minimum": 0, + "title": "Fallback Timeout", + "type": "integer" + }, + "fallback_timeout_max_s": { + "minimum": 1, + "title": "Fallback Timeout Max S", + "type": "integer" + }, + "fallback_timeout_min_s": { + "minimum": 1, + "title": "Fallback Timeout Min S", + "type": "integer" + }, + "max_charge": { + "maximum": 65534, + "minimum": 0, + "title": "Max Charge", + "type": "integer" + }, + "max_discharge": { + "maximum": 65534, + "minimum": 0, + "title": "Max Discharge", + "type": "integer" + } + }, + "required": [ + "max_charge", + "max_discharge", + "fallback_max_charge", + "fallback_max_discharge", + "fallback_timeout", + "fallback_timeout_min_s", + "fallback_timeout_max_s", + "external_control_register", + "external_control_value" + ], + "title": "ModbusRegisterMap", + "type": "object" + }, "Mode": { "additionalProperties": false, "description": "One mode of a mode-controlled device and the power it draws.", diff --git a/tests/devices/battery/__init__.py b/tests/devices/battery/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/devices/battery/test_battery_drivers.py b/tests/devices/battery/test_battery_drivers.py new file mode 100644 index 0000000..453a707 --- /dev/null +++ b/tests/devices/battery/test_battery_drivers.py @@ -0,0 +1,484 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Battery adapters (WP10): generic, kostal_plenticore, kostal_modbus - exact service calls.""" + +from __future__ import annotations + +import ast +from pathlib import Path +from typing import Any + +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from suncore.core.actions import READ_ONLY_ACTIONS +from suncore.core.battery import ( + BatteryAction, + BatteryCapability, + BatteryModel, + BatterySettings, + FieldRange, + ModbusByteOrder, + ModbusLink, +) +from suncore.core.battery_adapter import BatteryAdapterSpec +from suncore.core.decisions import ReleaseAction +from suncore.core.site import EntityRef +from suncore.devices.battery import ( + GenericBatteryDriver, + KostalModbusDriver, + KostalPlenticoreDriver, + create_battery_driver, +) +from suncore.devices.battery.modbus_codec import ( + float32_words, + uint32_words, + words_float32, + words_uint32, +) +from suncore.devices.drivers.base import ActionNotSupportedError, WriteRefusedError +from suncore.templates import BatteryTemplate, load_templates +from tests.devices.drivers.fakes import FakeHA, intent + +ROOT = Path(__file__).resolve().parents[3] +CATALOG = load_templates(ROOT / "templates") +MODEL = BatteryModel(capacity_wh=10_000, max_charge_w=5000, max_discharge_w=6000) + + +def template(template_id: str) -> BatteryAdapterSpec: + found = CATALOG.get(template_id) + assert isinstance(found, BatteryTemplate) + return found.adapter_spec() + + +def template_model(template_id: str) -> BatteryTemplate: + found = CATALOG.get(template_id) + assert isinstance(found, BatteryTemplate) + return found + + +def settings(template_id: str, entities: dict[str, str], **kw: Any) -> BatterySettings: + return BatterySettings( + adapter_template_id=template_id, + entities={r: EntityRef(entity_id=e) for r, e in entities.items()}, + model=MODEL, + **kw, + ) + + +def battery_intent(**fields: float) -> Any: + return intent(BatteryAction(**fields), asset="battery") + + +# --- generic --------------------------------------------------------------------------------- + +GENERIC_ENTITIES = { + "min_soc_number": "number.min_soc", + "max_charge_number": "number.max_charge", + "max_discharge_number": "number.max_discharge", + "grid_charge_number": "number.grid_charge", +} + + +def generic(ha: FakeHA, entities: dict[str, str] | None = None) -> GenericBatteryDriver: + ha.set("number.min_soc", "10", min=5, max=100, step=5, unit_of_measurement="%") + ha.set("number.max_charge", "5000", min=0, max=8000, step=1, unit_of_measurement="W") + ha.set("number.max_discharge", "6000", min=0, max=6000, unit_of_measurement="W") + ha.set("number.grid_charge", "0", min=0, max=4000, unit_of_measurement="W") + driver = create_battery_driver( + template("generic.battery"), + settings("generic.battery", entities or GENERIC_ENTITIES), + write=ha.write, + states=ha.lookup, + ) + assert isinstance(driver, GenericBatteryDriver) + return driver + + +async def test_generic_capabilities_follow_the_mapped_roles() -> None: + ha = FakeHA() + assert generic(ha).capabilities == frozenset( + { + BatteryCapability.MIN_SOC, + BatteryCapability.CHARGE_LIMIT, + BatteryCapability.DISCHARGE_LIMIT, + BatteryCapability.GRID_CHARGE, + } + ) + only_floor = generic(FakeHA(), {"min_soc_number": "number.min_soc"}) + assert only_floor.capabilities == frozenset({BatteryCapability.MIN_SOC}) + assert only_floor.heartbeat_s is None + assert only_floor.prepared() + assert only_floor.refusal() is None + + +async def test_generic_ranges_intersect_template_and_entity() -> None: + ranges = generic(FakeHA()).ranges() + assert ranges.min_soc_pct == FieldRange(5, 100, 5) + assert ranges.max_charge_w == FieldRange(0, 8000, 1) + assert ranges.grid_charge_w == FieldRange(0, 4000, None) + + +async def test_generic_read_back_and_writes_only_changed_numbers() -> None: + ha = FakeHA() + driver = generic(ha) + assert await driver.read_back() == BatteryAction( + max_charge_w=5000, max_discharge_w=6000, min_soc_pct=10, grid_charge_w=0 + ) + context = await driver.apply( + battery_intent(max_charge_w=5000, max_discharge_w=0, min_soc_pct=10, grid_charge_w=0) + ) + assert ha.sent == [ + ("number", "set_value", {"entity_id": "number.max_discharge"}, {"value": 0.0}), + ] + assert context == "ctx-1" + assert driver.applied is not None + + +async def test_generic_release_restores_the_baseline_numbers() -> None: + ha = FakeHA() + driver = generic(ha) + ha.set("number.max_discharge", "0", min=0, max=6000, unit_of_measurement="W") + await driver.release(BatteryAction(max_discharge_w=6000, min_soc_pct=10)) + assert ha.sent == [ + ("number", "set_value", {"entity_id": "number.max_discharge"}, {"value": 6000.0}), + ] + assert driver.applied is None + + +async def test_generic_refuses_other_actions_and_missing_capabilities() -> None: + driver = generic(FakeHA(), {"min_soc_number": "number.min_soc"}) + with pytest.raises(ActionNotSupportedError): + await driver.apply(intent(ReleaseAction(), asset="battery")) + with pytest.raises(WriteRefusedError): + await driver.apply(battery_intent(grid_charge_w=1000)) + + +async def test_generic_unavailable_entity_reads_unknown_and_refuses() -> None: + ha = FakeHA() + driver = generic(ha) + ha.set("number.max_discharge", "unavailable") + assert await driver.read_back() is None + assert driver.ranges().max_discharge_w is None + with pytest.raises(WriteRefusedError): + await driver.apply(battery_intent(max_discharge_w=0)) + + +def _with_controls(controls: dict[str, Any], roles: dict[str, Any]) -> BatteryAdapterSpec: + base = template_model("generic.battery").model_dump(mode="json", exclude_none=True) + base.update({"id": "acme.battery", "name": "template.acme.battery.name"}) + base["roles"] = roles + base["controls"] = controls + base["capabilities"] = [] + return BatteryTemplate.model_validate(base).adapter_spec() + + +async def test_select_based_lock_and_force_charge() -> None: + role = {"matcher": {"domain": "select"}, "description": "template.acme.battery.role.mode"} + tpl = _with_controls( + { + "mode": { + "kind": "mode", + "options": [ + {"value": "Auto", "meaning": "auto"}, + {"value": "Hold", "meaning": "no_discharge"}, + {"value": "Grid", "meaning": "force_charge"}, + {"value": "Service", "meaning": "other"}, + ], + } + }, + {"mode": role}, + ) + ha = FakeHA() + ha.set("select.mode", "Auto") + driver = GenericBatteryDriver( + tpl, + settings("acme.battery", {"mode": "select.mode"}), + write=ha.write, + states=ha.lookup, + ) + assert driver.capabilities == frozenset( + {BatteryCapability.DISCHARGE_LIMIT, BatteryCapability.GRID_CHARGE} + ) + assert driver.ranges().max_discharge_w == FieldRange(0, 0) + assert driver.ranges().grid_charge_w == FieldRange(5000, 5000) + assert await driver.read_back() == BatteryAction(max_discharge_w=6000, grid_charge_w=0) + await driver.apply(battery_intent(max_discharge_w=0)) + assert ha.sent[-1] == ( + "select", + "select_option", + {"entity_id": "select.mode"}, + {"option": "Hold"}, + ) + ha.set("select.mode", "Hold") + assert await driver.read_back() == BatteryAction(max_discharge_w=0, grid_charge_w=0) + await driver.apply(battery_intent(grid_charge_w=5000)) + assert ha.sent[-1][3] == {"option": "Grid"} + ha.set("select.mode", "Grid") + await driver.release(None) + assert ha.sent[-1][3] == {"option": "Auto"} + # The user's own option stays when SunCore restricts nothing. + ha.set("select.mode", "Service") + calls = len(ha.calls) + await driver.apply(battery_intent(max_discharge_w=6000)) + assert len(ha.calls) == calls + + +async def test_switch_based_force_charge() -> None: + role = {"matcher": {"domain": "switch"}, "description": "template.acme.battery.role.force"} + tpl = _with_controls({"force": {"kind": "force_charge"}}, {"force": role}) + ha = FakeHA() + ha.set("switch.force", "off") + driver = GenericBatteryDriver( + tpl, settings("acme.battery", {"force": "switch.force"}), write=ha.write, states=ha.lookup + ) + assert driver.capabilities == frozenset({BatteryCapability.GRID_CHARGE}) + await driver.apply(battery_intent(grid_charge_w=5000)) + assert ha.sent == [("switch", "turn_on", {"entity_id": "switch.force"}, None)] + ha.set("switch.force", "on") + assert await driver.read_back() == BatteryAction(grid_charge_w=5000) + await driver.release(None) + assert ha.sent[-1] == ("switch", "turn_off", {"entity_id": "switch.force"}, None) + + +async def test_percent_and_kw_numbers_are_converted() -> None: + roles = { + "charge": {"matcher": {"domain": "number"}, "description": "template.acme.battery.role.c"}, + "discharge": { + "matcher": {"domain": "number"}, + "description": "template.acme.battery.role.d", + }, + } + tpl = _with_controls( + { + "charge": {"kind": "max_charge", "unit": "kW", "min": 0, "max": 10}, + "discharge": {"kind": "max_discharge", "unit": "%", "min": 0, "max": 100}, + }, + roles, + ) + ha = FakeHA() + ha.set("number.charge", "2.5") + ha.set("number.discharge", "50") + driver = GenericBatteryDriver( + tpl, + settings("acme.battery", {"charge": "number.charge", "discharge": "number.discharge"}), + write=ha.write, + states=ha.lookup, + ) + assert await driver.read_back() == BatteryAction(max_charge_w=2500, max_discharge_w=3000) + assert driver.ranges().max_discharge_w == FieldRange(0, 6000, None) + await driver.apply(battery_intent(max_charge_w=1000, max_discharge_w=0)) + assert [c[3] for c in ha.sent] == [{"value": 1.0}, {"value": 0.0}] + + +# --- kostal_plenticore ------------------------------------------------------------------------ + + +def kostal_rest(ha: FakeHA) -> KostalPlenticoreDriver: + ha.set("number.scb_battery_min_soc", "5", min=5, max=100, step=5, unit_of_measurement="%") + ha.set("select.scb_battery_charging_usage_mode", "None") + driver = create_battery_driver( + template("kostal.plenticore"), + settings( + "kostal.plenticore", + { + "min_soc_number": "number.scb_battery_min_soc", + "charge_mode": "select.scb_battery_charging_usage_mode", + }, + ), + write=ha.write, + states=ha.lookup, + ) + assert isinstance(driver, KostalPlenticoreDriver) + return driver + + +async def test_kostal_rest_is_min_soc_only_with_a_lag_aware_settle() -> None: + ha = FakeHA() + driver = kostal_rest(ha) + assert driver.capabilities == frozenset({BatteryCapability.MIN_SOC}) + assert driver.settle_s >= 35 + assert driver.charge_mode() == "None" + assert driver.ranges().min_soc_pct == FieldRange(5, 100, 5) + assert driver.ranges().grid_charge_w is None + await driver.apply(battery_intent(min_soc_pct=45)) + assert ha.sent == [ + ("number", "set_value", {"entity_id": "number.scb_battery_min_soc"}, {"value": 45.0}) + ] + # The REST write failed silently: the entity still shows 5 - the read-back says so. + assert await driver.read_back() == BatteryAction(min_soc_pct=5) + with pytest.raises(WriteRefusedError): + await driver.apply(battery_intent(grid_charge_w=1000)) # no charge set-point over REST + + +def test_kostal_rest_template_must_have_only_a_min_soc_control() -> None: + base = template_model("kostal.plenticore").model_dump(mode="json", exclude_none=True) + base["controls"]["min_soc_number"] = {"kind": "max_charge", "unit": "W", "min": 0, "max": 1} + with pytest.raises(ValueError, match="min_soc"): + BatteryTemplate.model_validate(base) + + +# --- kostal_modbus ---------------------------------------------------------------------------- + +MODBUS_ENTITIES = { + "external_control": "sensor.k_1080", + "charge_limit": "sensor.k_1280", + "discharge_limit": "sensor.k_1282", + "fallback_charge_limit": "sensor.k_1284", + "fallback_discharge_limit": "sensor.k_1286", + "fallback_timeout": "sensor.k_1288", + "own_charge_limit": "sensor.k_1076", + "own_discharge_limit": "sensor.k_1078", +} +LINK = ModbusLink(hub="kostal", slave=71, byte_order=ModbusByteOrder.LITTLE) + + +def modbus(ha: FakeHA, *, external: str = "2", prepared: bool = False) -> KostalModbusDriver: + ha.set("sensor.k_1080", external) + ha.set("sensor.k_1280", "0") + ha.set("sensor.k_1282", "0") + ha.set("sensor.k_1284", "4800" if prepared else "0") + ha.set("sensor.k_1286", "5500" if prepared else "0") + ha.set("sensor.k_1288", "60" if prepared else "0") + ha.set("sensor.k_1076", "4800") + ha.set("sensor.k_1078", "5500") + driver = create_battery_driver( + template("kostal.plenticore_g3_modbus"), + settings("kostal.plenticore_g3_modbus", MODBUS_ENTITIES, modbus=LINK), + write=ha.write, + states=ha.lookup, + ) + assert isinstance(driver, KostalModbusDriver) + return driver + + +def register_writes(ha: FakeHA) -> list[tuple[int, list[int]]]: + out = [] + for domain, service, target, data in ha.sent: + assert (domain, service, target) == ("modbus", "write_register", {}) + assert data is not None + assert data["hub"] == "kostal" + assert data["slave"] == 71 # the action would default to 1: always sent + out.append((data["address"], data["value"])) + return out + + +async def test_modbus_refuses_without_external_battery_management() -> None: + ha = FakeHA() + driver = modbus(ha, external="0") + refusal = driver.refusal() + assert refusal is not None + assert refusal.key == "safety.battery_external_control_off" + with pytest.raises(WriteRefusedError): + await driver.arm_fallback() + with pytest.raises(WriteRefusedError): + await driver.apply(battery_intent(max_discharge_w=0)) + await driver.release(None) + assert ha.calls == [] + + +async def test_modbus_arms_the_fallback_first_and_refuses_limits_until_confirmed() -> None: + ha = FakeHA() + driver = modbus(ha) + assert driver.capabilities == frozenset( + { + BatteryCapability.CHARGE_LIMIT, + BatteryCapability.DISCHARGE_LIMIT, + BatteryCapability.HARDWARE_FALLBACK, + } + ) + assert not driver.prepared() + with pytest.raises(WriteRefusedError): + await driver.apply(battery_intent(max_discharge_w=0)) + await driver.arm_fallback() + order = ModbusByteOrder.LITTLE + assert register_writes(ha) == [ + (1284, float32_words(4800, order)), + (1286, float32_words(5500, order)), + (1288, uint32_words(60, order)), + ] + ha.set("sensor.k_1284", "4800") + ha.set("sensor.k_1286", "5500") + ha.set("sensor.k_1288", "60") + assert driver.prepared() + + +async def test_modbus_limits_heartbeat_and_release() -> None: + ha = FakeHA() + driver = modbus(ha, prepared=True) + assert driver.heartbeat_s == 20 + assert driver.ranges().max_discharge_w == FieldRange(0, 5500) + await driver.apply(battery_intent(max_charge_w=4800, max_discharge_w=0)) + order = ModbusByteOrder.LITTLE + lock = [(1280, float32_words(4800, order)), (1282, float32_words(0, order))] + assert register_writes(ha) == lock + await driver.keep_alive() + assert register_writes(ha) == lock + lock + await driver.release(BatteryAction(max_charge_w=0, max_discharge_w=0)) + own = [(1280, float32_words(4800, order)), (1282, float32_words(5500, order))] + assert register_writes(ha) == lock + lock + own # own limits, not the takeover read-back + await driver.keep_alive() # the heartbeat stopped with the release + assert len(ha.calls) == 6 + + +async def test_modbus_read_back_reports_the_limit_registers() -> None: + ha = FakeHA() + driver = modbus(ha, prepared=True) + ha.set("sensor.k_1282", "0") + ha.set("sensor.k_1280", "4800") + assert await driver.read_back() == BatteryAction(max_charge_w=4800, max_discharge_w=0) + ha.set("sensor.k_1282", "unavailable") + assert await driver.read_back() is None + + +def test_modbus_needs_its_link_and_roles() -> None: + ha = FakeHA() + with pytest.raises(ValueError, match=r"battery\.modbus"): + create_battery_driver( + template("kostal.plenticore_g3_modbus"), + settings("kostal.plenticore_g3_modbus", MODBUS_ENTITIES), + write=ha.write, + states=ha.lookup, + ) + with pytest.raises(ValueError, match="unmapped"): + create_battery_driver( + template("kostal.plenticore_g3_modbus"), + settings("kostal.plenticore_g3_modbus", {"charge_limit": "sensor.x"}, modbus=LINK), + write=ha.write, + states=ha.lookup, + ) + + +@given( + st.floats(min_value=-1e6, max_value=1e6, allow_nan=False, width=32), + st.sampled_from(list(ModbusByteOrder)), +) +def test_float32_words_round_trip(value: float, order: ModbusByteOrder) -> None: + words = float32_words(value, order) + assert all(0 <= w <= 0xFFFF for w in words) + assert words_float32(words, order) == value + + +def test_float32_word_order_follows_register_5() -> None: + # 1000.0 = 0x447A0000: ABCD (big) high word first, CDAB (little, Kostal default) low first. + assert float32_words(1000.0, ModbusByteOrder.BIG) == [0x447A, 0x0000] + assert float32_words(1000.0, ModbusByteOrder.LITTLE) == [0x0000, 0x447A] + + +@given(st.integers(0, 0xFFFFFFFF), st.sampled_from(list(ModbusByteOrder))) +def test_uint32_words_round_trip(value: int, order: ModbusByteOrder) -> None: + assert words_uint32(uint32_words(value, order), order) == value + + +def test_write_register_is_a_write_of_the_modbus_adapter_only() -> None: + """``modbus.write_register`` is never a read-only action and only the ``kostal_modbus`` + adapter (and the simulator, which is the fake Home Assistant) names it.""" + assert not any(a.startswith("modbus.") for a in READ_ONLY_ACTIONS) + users = [] + for path in sorted((ROOT / "suncore").rglob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8")) + if any(isinstance(n, ast.Constant) and n.value == "write_register" for n in ast.walk(tree)): + users.append(path.relative_to(ROOT).as_posix()) + assert [u for u in users if not u.startswith("suncore/sim/")] == [ + "suncore/devices/battery/kostal_modbus.py" + ] diff --git a/tests/safety/test_boundary.py b/tests/safety/test_boundary.py index 9207593..217eeac 100644 --- a/tests/safety/test_boundary.py +++ b/tests/safety/test_boundary.py @@ -4,9 +4,12 @@ AST-based scan over ``suncore/``; no module is imported. The rules: 1. Only ``suncore.safety.gate`` may call ``.apply(...)`` and ``.release(...)`` - the - actuator write and the hardware release (Phase 3: the only write paths). + actuator write and the hardware release (Phase 3: the only write paths) - and the battery + adapters' ``.arm_fallback(...)`` / ``.keep_alive(...)`` (Phase 4 WP10: the §3.5 fallback + registers and the heartbeat re-write). 2. Only ``suncore.safety`` may import ``suncore.safety.actuator``; driver modules - (``suncore.devices.drivers``, Phase 3 WP6) may only be imported by ``suncore.safety``, + (``suncore.devices.drivers``, Phase 3 WP6, and the battery adapters + ``suncore.devices.battery``, Phase 4 WP10) may only be imported by ``suncore.safety``, the composition root ``suncore.app`` and the simulator's closed-loop composition ``suncore.sim`` (Phase 3 WP8; nothing in production imports ``suncore.sim`` but the demo). 3. Only ``suncore.ha`` and ``suncore.safety`` (and the simulator, which *is* the fake @@ -68,9 +71,10 @@ ACTUATOR_MODULE = "suncore.safety.actuator" GATE_MODULE = "suncore.safety.gate" DRIVERS = "suncore.devices.drivers" +BATTERY_DRIVERS = "suncore.devices.battery" SIM = "suncore.sim" DRIVER_IMPORTERS = (SAFETY, "suncore.app", SIM) -WRITE_CALLS = ("apply", "release") +WRITE_CALLS = ("apply", "release", "arm_fallback", "keep_alive") API = "suncore.api" API_FORBIDDEN = (SAFETY, HA, "suncore.devices") WRITE_CAPABILITY_NAMES = frozenset({"ServiceCaller", "ServiceCallerProvider"}) @@ -183,11 +187,12 @@ def test_only_the_gate_calls_apply_and_release(path: Path) -> None: def test_the_gate_is_the_single_writer() -> None: - """The write path exists exactly once: ``gate.py`` calls ``apply`` and ``release``.""" + """The write path exists exactly once: ``gate.py`` calls ``apply`` and ``release`` (and the + battery adapters' ``arm_fallback`` and ``keep_alive``).""" gate = PACKAGE / "safety" / "gate.py" tree = parse(gate) - assert list(attribute_calls(tree, "apply")), "gate.py must contain the apply() call" - assert list(attribute_calls(tree, "release")), "gate.py must contain the release() call" + for attr in ("apply", "release"): + assert list(attribute_calls(tree, attr)), f"gate.py must contain the {attr}() call" everywhere = [ line for path in SOURCES @@ -226,14 +231,18 @@ def test_drivers_are_imported_only_by_safety_and_app(path: Path) -> None: The drivers do not exist yet (WP6); the rule is in place before the first one lands. """ module = module_name(path) - if in_package(module, DRIVERS) or any(in_package(module, pkg) for pkg in DRIVER_IMPORTERS): + if ( + in_package(module, DRIVERS) + or in_package(module, BATTERY_DRIVERS) + or any(in_package(module, pkg) for pkg in DRIVER_IMPORTERS) + ): return offenders = fmt( path, ( line for line, imported in imported_modules(path, parse(path)) - if in_package(imported, DRIVERS) + if in_package(imported, DRIVERS) or in_package(imported, BATTERY_DRIVERS) ), ) assert not offenders, f"driver module imported outside safety/app: {offenders}" diff --git a/tests/scenarios/battery/generic.battery.yaml b/tests/scenarios/battery/generic.battery.yaml new file mode 100644 index 0000000..7b1cb47 --- /dev/null +++ b/tests/scenarios/battery/generic.battery.yaml @@ -0,0 +1,22 @@ +template: generic.battery +sim_scenario: summer_day +# A battery integration exposing its limits as number entities (not part of the demo house). +extra_entities: + - { entity_id: number.battery_min_soc, platform: acme_battery, unit: "%", state: "10" } + - { entity_id: number.battery_max_charge, platform: acme_battery, unit: W, state: "5000" } + - { entity_id: number.battery_max_discharge, platform: acme_battery, unit: W, state: "5000" } + - { entity_id: number.battery_grid_charge, platform: acme_battery, unit: W, state: "0" } +roles: + min_soc_number: + entity: number.battery_min_soc + criteria: [domain, units] + max_charge_number: + tied: [number.battery_max_charge, number.battery_max_discharge, number.battery_grid_charge, number.sim_heating_rod_limit] + pick: number.battery_max_charge + max_discharge_number: + tied: [number.battery_max_charge, number.battery_max_discharge, number.battery_grid_charge, number.sim_heating_rod_limit] + pick: number.battery_max_discharge + grid_charge_number: + tied: [number.battery_max_charge, number.battery_max_discharge, number.battery_grid_charge, number.sim_heating_rod_limit] + pick: number.battery_grid_charge +capabilities: [charge_limit, discharge_limit, grid_charge, min_soc] diff --git a/tests/scenarios/battery/kostal.plenticore.yaml b/tests/scenarios/battery/kostal.plenticore.yaml new file mode 100644 index 0000000..c1176fc --- /dev/null +++ b/tests/scenarios/battery/kostal.plenticore.yaml @@ -0,0 +1,17 @@ +template: kostal.plenticore +sim_scenario: summer_day +# Registry metadata as the kostal_plenticore integration creates it (number.py / select.py of +# HA core 5cfe9aad): the min-SoC number in %, the two power numbers in W, the usage-mode select. +extra_entities: + - { entity_id: number.scb_battery_min_soc, platform: kostal_plenticore, unit: "%", state: "5" } + - { entity_id: number.scb_battery_min_home_consumption, platform: kostal_plenticore, unit: W, state: "50" } + - { entity_id: number.scb_active_power_limitation, platform: kostal_plenticore, unit: W, state: "10000" } + - { entity_id: select.scb_battery_charging_usage_mode, platform: kostal_plenticore, state: "None" } +roles: + min_soc_number: + entity: number.scb_battery_min_soc + criteria: [domain, platforms, units] + charge_mode: + entity: select.scb_battery_charging_usage_mode + criteria: [domain, platforms] +capabilities: [min_soc] diff --git a/tests/scenarios/battery/kostal.plenticore_g3_modbus.yaml b/tests/scenarios/battery/kostal.plenticore_g3_modbus.yaml new file mode 100644 index 0000000..372d08a --- /dev/null +++ b/tests/scenarios/battery/kostal.plenticore_g3_modbus.yaml @@ -0,0 +1,39 @@ +template: kostal.plenticore_g3_modbus +sim_scenario: summer_day +# `modbus:` YAML sensors of the §3.5 registers (platform modbus); the power sensors tie, so the +# user picks the register for each role in the wizard. +extra_entities: + - { entity_id: sensor.kostal_1080_battery_management, platform: modbus, state: "2" } + - { entity_id: sensor.kostal_1280_max_charge, platform: modbus, unit: W, state: "10000" } + - { entity_id: sensor.kostal_1282_max_discharge, platform: modbus, unit: W, state: "10000" } + - { entity_id: sensor.kostal_1284_fallback_charge, platform: modbus, unit: W, state: "10000" } + - { entity_id: sensor.kostal_1286_fallback_discharge, platform: modbus, unit: W, state: "10000" } + - { entity_id: sensor.kostal_1288_fallback_time, platform: modbus, unit: s, state: "60" } + - { entity_id: sensor.kostal_1076_battery_charge_limit, platform: modbus, unit: W, state: "10000" } + - { entity_id: sensor.kostal_1078_battery_discharge_limit, platform: modbus, unit: W, state: "10000" } +roles: + external_control: + tied: [sensor.kostal_1080_battery_management, sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1288_fallback_time, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + pick: sensor.kostal_1080_battery_management + charge_limit: + tied: [sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + pick: sensor.kostal_1280_max_charge + discharge_limit: + tied: [sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + pick: sensor.kostal_1282_max_discharge + fallback_charge_limit: + tied: [sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + pick: sensor.kostal_1284_fallback_charge + fallback_discharge_limit: + tied: [sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + pick: sensor.kostal_1286_fallback_discharge + own_charge_limit: + tied: [sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + pick: sensor.kostal_1076_battery_charge_limit + own_discharge_limit: + tied: [sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + pick: sensor.kostal_1078_battery_discharge_limit + fallback_timeout: + entity: sensor.kostal_1288_fallback_time + criteria: [domain, platforms, units] +capabilities: [charge_limit, discharge_limit, hardware_fallback] diff --git a/tests/scenarios/test_conformance.py b/tests/scenarios/test_conformance.py index 3c7c97c..8809e68 100644 --- a/tests/scenarios/test_conformance.py +++ b/tests/scenarios/test_conformance.py @@ -37,17 +37,20 @@ import yaml from pydantic import BaseModel, ConfigDict, Field, ValidationError +from suncore.core.battery import BatteryModel, BatterySettings, ModbusByteOrder, ModbusLink from suncore.core.devices import DeviceConfig from suncore.core.entities import EntityMeta from suncore.core.series import TimeRange, floor_to_step from suncore.core.site import EntityRef from suncore.core.units import Dimension, parse_unit +from suncore.devices.battery import create_battery_driver from suncore.ha.connection import EntityState from suncore.sim.fake_ha import FakeHAConnection from suncore.sim.scenario import load_scenario from suncore.tariff import EntityReading, SourceBinding, TemplatePriceSource from suncore.tariff.units import normalise_price_unit from suncore.templates import ( + BatteryTemplate, DeviceTemplate, ForecastTemplate, RegionTemplate, @@ -124,6 +127,8 @@ class ScenarioFile(BaseModel): extra_entities: list[ExtraEntity] = Field(default_factory=list) roles: dict[str, RoleExpectation] expect: SeriesExpectation | None = None + capabilities: list[str] | None = None + """Battery templates: what the adapter built from the resolved mapping can execute.""" def _scenario_files() -> dict[str, Path]: @@ -212,7 +217,7 @@ def _check_tied( @pytest.mark.parametrize("template_id", sorted(FILES)) -async def test_template_conforms(template_id: str, fake: FakeHAConnection) -> None: +async def test_template_conforms(template_id: str, fake: FakeHAConnection) -> None: # noqa: PLR0912 - one branch per kind scenario = _load(FILES[template_id]) template = CATALOG.templates[template_id] fixture = _fixture(scenario) @@ -259,6 +264,52 @@ async def test_template_conforms(template_id: str, fake: FakeHAConnection) -> No await _check_forecast(template, fake, resolved, states) elif isinstance(template, RegionTemplate): await _check_region(template, fake) + elif isinstance(template, BatteryTemplate): + await _check_battery(template, scenario, resolved, states) + + +async def _check_battery( + template: BatteryTemplate, + scenario: ScenarioFile, + resolved: Mapping[str, EntityMeta], + states: Mapping[str, EntityState], +) -> None: + """The real adapter is built from the resolved mapping; it reports the expected + capabilities and live ranges, and its read-back works on the fixture states.""" + for name, spec in template.roles.items(): + if spec.required: + assert name in resolved, f"required role {name} unresolved" + settings = BatterySettings( + adapter_template_id=template.id, + entities={r: EntityRef(entity_id=m.entity_id) for r, m in resolved.items()}, + model=BatteryModel(capacity_wh=10_000, max_charge_w=5000, max_discharge_w=5000), + modbus=ModbusLink(slave=71, byte_order=ModbusByteOrder.LITTLE) + if template.driver == "kostal_modbus" + else None, + ) + + async def no_write(*_: object, **__: object) -> object: + msg = "conformance never writes" + raise AssertionError(msg) + + driver = create_battery_driver( + template.adapter_spec(), + settings, + write=no_write, + states=states.get, # type: ignore[arg-type] + ) + assert scenario.capabilities is not None, "battery scenarios state the capabilities" + assert sorted(c.value for c in driver.capabilities) == sorted(scenario.capabilities) + assert await driver.read_back() is not None + ranges = driver.ranges() + for field in ("max_charge_w", "max_discharge_w", "min_soc_pct", "grid_charge_w"): + capability = { + "max_charge_w": "charge_limit", + "max_discharge_w": "discharge_limit", + "min_soc_pct": "min_soc", + "grid_charge_w": "grid_charge", + }[field] + assert (ranges.of(field) is not None) == (capability in scenario.capabilities), field def _check_device( From 7ac5831756817c03acd462503bf8c53c88afff79 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 19:00:53 +0000 Subject: [PATCH 04/16] feat(safety): battery intents through the gate with the ADR-0013 invariants (WP10) - the blanket safety.battery_not_supported rejection now applies only without a battery adapter (observe-only, no model) or to another asset id; intents for the configured battery pass the battery invariants B1-B6/B9 against the takeover baseline (None = baseline), the live flows, the band of a fresh plan interval, the live import price and the import limit, the adapter's precondition and capabilities, write only on change - takeover arms and reads back the hardware fallback first; the mode is capped at assisted while the fallback is not measured; mandatory read-back, three failures trip and release - the accepted state is a lease re-judged by poll() every tick: shadow, a watchdog pause, stale inputs or any failed invariant release it; heartbeat only while it holds; a change outside SunCore is an override; a release of an adapter without fallback is read back - check_battery(): frozen battery power / SoC (B8) pause the battery scope and release - every Phase 3 release path covers the battery (emergency stop, shutdown, mode to shadow, site/device trip, reconnect, crash recovery, re-mapped battery via its identity) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- frontend/src/lib/i18n/locales/de.json | 7 +- frontend/src/lib/i18n/locales/en.json | 7 +- suncore/safety/battery.py | 47 ++- suncore/safety/gate.py | 575 +++++++++++++++++++++++++- suncore/safety/watchdog.py | 7 + tests/safety/test_battery_gate.py | 564 +++++++++++++++++++++++++ tests/safety/test_boundary.py | 2 +- tests/safety/test_gate.py | 2 +- 8 files changed, 1184 insertions(+), 27 deletions(-) create mode 100644 tests/safety/test_battery_gate.py diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index 4a1220f..e1b7385 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -579,6 +579,7 @@ "safety.release_pending": "Nicht geschrieben: Das Gerät wird gleich in den vorherigen Zustand zurückgesetzt.", "safety.superseded": "Schreiben nicht bestätigt: Das Gerät wurde inzwischen in den vorherigen Zustand zurückgesetzt.", "safety.battery_reserve": "Nicht eingeschaltet: Der Akku entlädt bei {soc_pct} % (Reserve {reserve_pct} %).", + "safety.battery_release_unconfirmed": "Nach der Freigabe zeigt der Akku seine eigenen Einstellungen nicht wieder: Akkusteuerung pausiert, bitte den Wechselrichter prüfen.", "safety.battery_range_unknown": "Der erlaubte Bereich von {field} ist unbekannt (Entität nicht verfügbar); nichts geschrieben.", "safety.climate_off": "Nicht eingeschaltet: Das Gerät ist aus und Einschalten ist für dieses Gerät nicht erlaubt.", "safety.comfort_band": "Sollwert {setpoint_c} °C liegt außerhalb des Komfortbands {min_c}–{max_c} °C.", @@ -916,13 +917,14 @@ "api.validation.grid_charge_above_cap": "Laden aus dem Netz ({grid_charge_w} W) darf die Ladegrenze ({max_charge_w} W) nicht überschreiten.", "api.validation.import_formula_all_in": "Der Tarif {template_id} liefert bereits Endpreise inklusive Gebühren und Steuern; eine Preisformel würde sie doppelt zählen.", "tariff.import.tou_stored": "Ein Zeittarif (HT/NT) ist gespeichert. Er lässt sich in einer späteren Version hier bearbeiten; Speichern lässt ihn unverändert, solange du keine andere Art wählst.", - "safety.battery_not_supported": "Batteriesteuerung ist noch nicht verfügbar; es wurde nichts geschrieben.", + "safety.battery_not_supported": "Kein Akku-Adapter konfiguriert (der Akku wird nur beobachtet); nichts geschrieben.", "safety.battery_model_missing": "Kein Akkumodell (Kapazität, Grenzen, Reserve) konfiguriert: der Akku wird nur beobachtet.", "safety.battery_min_soc_below_reserve": "Mindest-Ladestand {min_soc_pct} % liegt unter der Reserve von {reserve_pct} %.", "safety.battery_min_soc_below_baseline": "Mindest-Ladestand {min_soc_pct} % liegt unter deiner eigenen Wechselrichter-Einstellung von {baseline_pct} %.", "safety.battery_write_no_change": "Der Akku hat diese Grenzen schon; nichts geschrieben.", "safety.battery_capability_missing": "Der Akku-Adapter kann {field} nicht setzen; nichts geschrieben.", "safety.battery_out_of_range": "{field} = {value} liegt außerhalb des erlaubten Bereichs {low}–{high}.", + "safety.battery_override": "Die Akku-Grenzen wurden außerhalb von SunCore geändert: SunCore hält sich bis zum nächsten Morgen heraus.", "safety.battery_above_baseline": "{field} = {value} W läge über deiner eigenen Einstellung von {baseline} W; SunCore schränkt nur ein.", "safety.battery_grid_charge_unplanned": "Das aktuelle Planintervall erlaubt kein Netzladen.", "safety.battery_grid_charge_policy": "Netzladen ist jetzt nach deiner Preisgrenze oder deinem Zeitplan nicht erlaubt (aktueller Preis {price}).", @@ -933,8 +935,11 @@ "safety.battery_soc_frozen": "Der Ladestand bleibt bei {soc_pct} %, obwohl {moved_pct} % der Kapazität geflossen sind: Akkusteuerung pausiert.", "safety.battery_full": "Der Akku steht bei {soc_pct} %, sein Maximum ist {max_soc_pct} %: kein Netzladen.", "safety.battery_frozen": "Die Akkuleistung bleibt bei {battery_w} W, während sich die Netzleistung ändert: Akkusteuerung pausiert.", + "safety.battery_fallback_unconfirmed": "Die Rückfallgrenzen des Wechselrichters ließen sich nicht bestätigen; keine Akku-Grenze geschrieben.", + "safety.battery_fallback_unverified": "Der Rückfall-Timer des Wechselrichters ist noch nicht gemessen: der Akku läuft höchstens im Assistenzmodus.", "safety.battery_import_limit_unknown": "Netzladen braucht eine eingestellte Bezugsgrenze.", "safety.battery_import_limit": "Das Haus würde {projected_w} W beziehen, über der Bezugsgrenze von {limit_w} W.", + "safety.battery_inputs_stale": "Die Messwerte sind zu alt, um die Akku-Grenzen zu halten: zurückgegeben.", "safety.battery_unplanned_import": "Den Akku zurückzuhalten würde Netzbezug verursachen, und der Plan sieht das nicht vor.", "safety.battery_external_control_off": "Externes Batteriemanagement über Modbus ist aus (Register 1080 = {value}, nötig ist {expected}); nichts geschrieben.", "action.battery": "Batterie-Limits setzen", diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index 6bc8a49..9abbb9c 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -579,6 +579,7 @@ "safety.release_pending": "Not written: the device is about to be returned to its previous state.", "safety.superseded": "Write not confirmed: the device was returned to its previous state in the meantime.", "safety.battery_reserve": "Not switched on: the battery is discharging at {soc_pct} % (reserve {reserve_pct} %).", + "safety.battery_release_unconfirmed": "After the release the battery does not show its own settings again: battery control paused, please check the inverter.", "safety.battery_range_unknown": "The allowed range of {field} is unknown (entity unavailable); nothing was written.", "safety.climate_off": "Not switched on: the unit is off and switching on is not allowed for this device.", "safety.comfort_band": "Set-point {setpoint_c} °C is outside the comfort band {min_c}–{max_c} °C.", @@ -916,13 +917,14 @@ "api.validation.grid_charge_above_cap": "Grid charging ({grid_charge_w} W) must not exceed the charge limit ({max_charge_w} W).", "api.validation.import_formula_all_in": "The tariff {template_id} already delivers end prices including fees and taxes; a price formula would count them twice.", "tariff.import.tou_stored": "A time-of-use tariff (HT/NT) is stored. It can be edited here in a later version; saving keeps it unchanged unless you choose another kind.", - "safety.battery_not_supported": "Battery control is not available yet; nothing was written.", + "safety.battery_not_supported": "No battery adapter is configured (the battery is only observed); nothing was written.", "safety.battery_model_missing": "No battery model (capacity, limits, reserve) is configured: the battery is only observed.", "safety.battery_min_soc_below_reserve": "Minimum state of charge {min_soc_pct} % is below the reserve of {reserve_pct} %.", "safety.battery_min_soc_below_baseline": "Minimum state of charge {min_soc_pct} % is below your own inverter setting of {baseline_pct} %.", "safety.battery_write_no_change": "The battery already holds these limits; nothing was written.", "safety.battery_capability_missing": "The battery adapter cannot set {field}; nothing was written.", "safety.battery_out_of_range": "{field} = {value} is outside the allowed range {low}–{high}.", + "safety.battery_override": "The battery's limits were changed outside SunCore: SunCore keeps its hands off until the next morning.", "safety.battery_above_baseline": "{field} = {value} W would be above your own setting of {baseline} W; SunCore only restricts.", "safety.battery_grid_charge_unplanned": "The current plan interval does not allow grid charging.", "safety.battery_grid_charge_policy": "Grid charging is not allowed now by your price level or schedule (live price {price}).", @@ -933,8 +935,11 @@ "safety.battery_soc_frozen": "The state of charge has stayed at {soc_pct} % although {moved_pct} % of the capacity moved: battery control paused.", "safety.battery_full": "The battery is at {soc_pct} %, its maximum is {max_soc_pct} %: no grid charging.", "safety.battery_frozen": "The battery power has stayed at {battery_w} W while the grid power changed: battery control paused.", + "safety.battery_fallback_unconfirmed": "The inverter's fallback limits could not be confirmed; no battery limit was written.", + "safety.battery_fallback_unverified": "The inverter's fallback timer is not measured yet: the battery runs at most in assisted mode.", "safety.battery_import_limit_unknown": "Grid charging needs a configured grid import limit.", "safety.battery_import_limit": "The house would import {projected_w} W, above the import limit of {limit_w} W.", + "safety.battery_inputs_stale": "The measurements are too old to keep holding the battery's limits: given back.", "safety.battery_unplanned_import": "Holding the battery back would make the house import, and the plan does not ask for it.", "safety.battery_external_control_off": "External battery management via Modbus is off (register 1080 = {value}, needs {expected}); nothing was written.", "action.battery": "Set battery limits", diff --git a/suncore/safety/battery.py b/suncore/safety/battery.py index 62f49e4..bec2e15 100644 --- a/suncore/safety/battery.py +++ b/suncore/safety/battery.py @@ -23,7 +23,7 @@ from __future__ import annotations import math -from collections.abc import Sequence +from collections.abc import Callable, Sequence from dataclasses import dataclass, field from datetime import datetime, timedelta, tzinfo from typing import Final, Protocol, runtime_checkable @@ -41,7 +41,7 @@ round_up_to_step, ) from suncore.core.control import BatteryBand, Plan -from suncore.core.decisions import Reason +from suncore.core.decisions import Action, Reason from suncore.core.signals import Quality from suncore.safety.actuator import Actuator @@ -108,6 +108,44 @@ async def keep_alive(self) -> None: ... +# --- configuration ----------------------------------------------------------------------------- + + +PlanSource = Callable[[datetime], Plan] +"""``now -> Plan``: the plan the controller uses this tick (``ControlStack.current_plan``).""" +PriceSource = Callable[[datetime], float | None] +"""``now -> live import price`` (currency/kWh, ``None`` = unknown).""" + + +def _no_price(_: datetime) -> float | None: + return None + + +def _default_plan(_: datetime) -> Plan: + return Plan.default() + + +@dataclass(frozen=True, slots=True) +class BatteryGateConfig: + """What the gate needs to judge battery intents (built by the composition root). + + ``identity`` is ``core.identity.battery_identity_token`` of the configured battery: a runtime + taken over under another identity belongs to another battery (released, never written). + ``reserve_pct`` is ``core.battery.effective_reserve_pct``; ``policy`` the effective grid-charge + policy; ``fallback_verified`` the user's ``battery.fallback_measured`` (until it is set the + gate caps an adapter with a hardware fallback at assisted, ADR-0013 decision 6). + """ + + identity: str + model: BatteryModel | None + reserve_pct: float | None + policy: GridChargePolicy = field(default_factory=GridChargePolicy) + fallback_verified: bool = False + plan: PlanSource = _default_plan + import_price: PriceSource = _no_price + watch: BatteryWatch | None = None + + # --- context --------------------------------------------------------------------------------- @@ -453,13 +491,13 @@ def lease_violations(ctx: BatteryContext) -> tuple[Reason, ...]: return evaluate_battery(ctx) -def same_state(a: BatteryAction | None, b: BatteryAction | None, fields: Sequence[str]) -> bool: +def same_state(a: Action | None, b: Action | None, fields: Sequence[str]) -> bool: """Read-back comparison on ``fields`` (powers within 1 W, SoC within 0.01 %). A field the expected action sets must be read back with the same value; an unreadable (``None``) observed value is a mismatch. """ - if a is None or b is None: + if not isinstance(a, BatteryAction) or not isinstance(b, BatteryAction): return False for name in fields: want, got = getattr(a, name), getattr(b, name) @@ -562,6 +600,7 @@ def check(self, now: datetime, live: BatteryLive, capacity_wh: float | None) -> "STATE_CHECKS", "BatteryActuator", "BatteryContext", + "BatteryGateConfig", "BatteryLive", "BatteryWatch", "can_cause_import", diff --git a/suncore/safety/gate.py b/suncore/safety/gate.py index 654bb68..85727ab 100644 --- a/suncore/safety/gate.py +++ b/suncore/safety/gate.py @@ -32,6 +32,19 @@ change that was not judged yet becomes the baseline (what the user left is given back). A switch is recorded in the runtime when it is sent, not when the read-back confirms it. +Battery (Phase 4 WP10, ADR-0013): intents for the asset ``battery`` take the same order with +the battery invariants B1-B6/B9 (``safety.battery``) instead of the device invariants, judged +against the takeover baseline (``None`` = baseline), the live flows, the band of a fresh plan +interval, the live import price and the import limit; the adapter's precondition (Kostal 1080) +and capabilities; write only on change; an adapter with a hardware fallback gets it armed and +read back before the first limit, and the effective mode is capped at assisted until the +fallback is measured. An accepted state is a lease that :meth:`SafetyGate.poll` re-judges every +tick (heartbeat re-writes only while it holds, B7); a mode fall to shadow, a watchdog pause +(site or the battery scope of :meth:`SafetyGate.check_battery`, B8), stale inputs or any failed +invariant end it and restore the baseline. A change outside SunCore is an override (no write). +Every Phase 3 release path covers the battery. Without a battery adapter a ``BatteryAction`` is +rejected (``safety.battery_not_supported``), as before WP10. + Concurrency: a per-device ``asyncio.Lock`` serialises the write path, the release and the runtime updates. The write path re-checks the emergency stop, the effective mode, the watchdog and the hold right before ``apply()`` (after the baseline read-back, which @@ -52,6 +65,8 @@ import structlog +from suncore.core.balance import FlowSnapshot +from suncore.core.battery import BATTERY_ASSET_ID, BatteryCapability, resolve_battery_action from suncore.core.control import ControlSettings, DeviceState, GateInputs from suncore.core.decisions import ( Action, @@ -71,6 +86,20 @@ from suncore.core.site import SiteConfig from suncore.safety import overrides from suncore.safety.actuator import Actuator +from suncore.safety.battery import ( + REASON_BATTERY_NO_CHANGE, + BatteryActuator, + BatteryContext, + BatteryGateConfig, + BatteryLive, + BatteryWatch, + evaluate_battery, + lease_violations, + plan_band, + quantise, + readable_fields, + same_state, +) from suncore.safety.invariants import ( InvariantContext, action_matches, @@ -139,7 +168,21 @@ REASON_ORPHAN_DROPPED: Final = Reason(key="safety.orphan_dropped") """An orphaned runtime without the old actuator: reported, then dropped (manual check needed).""" REASON_BATTERY_NOT_SUPPORTED: Final = Reason(key="safety.battery_not_supported") -"""A battery action before the battery path exists (Phase 4 WP10): rejected, never written.""" +"""A battery action without a battery adapter (observe-only, no model, another asset id): +rejected, never written. Since WP10 a battery intent for the configured adapter is judged by the +ADR-0013 invariants instead (``control-safety`` sign-off of the ADR-0011 addendum).""" +REASON_BATTERY_FALLBACK_UNCONFIRMED: Final = Reason(key="safety.battery_fallback_unconfirmed") +"""The hardware fallback (Kostal 1284/1286/1288) did not read back: no limit is written.""" +REASON_BATTERY_RELEASE_UNCONFIRMED: Final = Reason(key="safety.battery_release_unconfirmed") +"""After a release the battery does not show its baseline: control paused, check it by hand.""" +REASON_BATTERY_OVERRIDE: Final = Reason(key="safety.battery_override") +"""The battery's limits changed outside SunCore while it held them: given back to the user.""" +REASON_BATTERY_INPUTS_STALE: Final = Reason(key="safety.battery_inputs_stale") +"""The controller's inputs are too old to renew the battery's lease.""" +REASON_BATTERY_FALLBACK_UNVERIFIED: Final = Reason(key="safety.battery_fallback_unverified") +"""Shown with the mode: the adapter's hardware fallback is not measured, at most assisted.""" +BATTERY_SCOPE: Final = BATTERY_ASSET_ID +"""The watchdog scope of the battery (its own faults; site faults pause it too).""" MAX_CONSECUTIVE_FAILURES: Final = 3 """After this many failed writes in a row the device scope trips (watchdog).""" @@ -176,14 +219,21 @@ def __init__( tz: tzinfo = UTC, sleep: Sleeper | None = None, predecessor: SafetyGate | None = None, + battery: BatteryGateConfig | None = None, ) -> None: self._clock = clock - # Actuators of devices a configuration change removed or re-mapped while their release + # Actuators of assets a configuration change removed or re-mapped while their release # failed (``handover``): used only to release them, never to write (the identity of the # runtime selects them). Dropped once the release succeeded. - self._release_only: dict[str, tuple[Actuator, DeviceConfig]] = ( + self._release_only: dict[str, tuple[Actuator, str, DeviceConfig | None]] = ( predecessor._leftovers() if predecessor is not None else {} ) + self._battery = battery + self._battery_watch = ( + battery.watch if battery is not None and battery.watch is not None else BatteryWatch() + ) + self._battery_beat: datetime | None = None + self._battery_verify: tuple[datetime, Action] | None = None self._sink = sink self._actuators: Mapping[str, Actuator] = MappingProxyType(dict(actuators or {})) self._modes: ModeProvider = modes if modes is not None else AllShadow() @@ -214,8 +264,35 @@ def mode(self) -> OperatingMode: return self._modes.global_mode() def modes_of(self, device_id: str) -> ModeView: + if device_id == BATTERY_ASSET_ID: + mode = self._modes.battery_mode() + if self.battery_mode_capped and mode.rank > OperatingMode.ASSISTED.rank: + mode = OperatingMode.ASSISTED + return ModeView(self._modes.global_mode(), mode) return view(self._modes, device_id) + @property + def battery_mode_capped(self) -> bool: + """The battery adapter has a hardware fallback that is not measured yet: at most + assisted (ADR-0013 decision 6, plan §6 question 3).""" + actuator = self._battery_actuator() + return ( + actuator is not None + and self._battery is not None + and not self._battery.fallback_verified + and BatteryCapability.HARDWARE_FALLBACK in actuator.capabilities + ) + + @property + def battery(self) -> BatteryGateConfig | None: + return self._battery + + def _battery_actuator(self) -> BatteryActuator | None: + actuator = self._actuators.get(BATTERY_ASSET_ID) + if self._battery is None or not isinstance(actuator, BatteryActuator): + return None + return actuator + @property def emergency_stopped(self) -> bool: return self._emergency_stop @@ -342,7 +419,8 @@ async def sync_modes(self) -> None: ) async def poll(self) -> tuple[Decision, ...]: - """Execute deferred releases whose protection time has elapsed (call every tick).""" + """Execute deferred releases whose protection time has elapsed (call every tick); renew + or end the battery's lease (its heartbeat) and check a battery release (WP10).""" now = self._now() decisions: list[Decision] = [] for device_id in list(self._runtimes): @@ -355,6 +433,13 @@ async def poll(self) -> tuple[Decision, ...]: else REASON_RELEASED ) decisions.append(await self.release_device(device_id, reason, origin=Origin.SAFETY)) + if not self._emergency_stop: + lease = await self._battery_lease(now) + if lease is not None: + decisions.append(lease) + check = await self._battery_release_check(now) + if check is not None: + decisions.append(check) return tuple(decisions) # --- watchdog feed ------------------------------------------------------------------- @@ -532,11 +617,8 @@ async def submit(self, intent: Intent) -> Decision: # noqa: PLR0911, PLR0912 - return await self._decide( intent, DecisionKind.REJECTED, now, (REASON_EMERGENCY_STOP,), mode ) - if isinstance(intent.action, BatteryAction): - # Explicitly unsupported until WP10 (control-safety): no invariants exist yet. - return await self._decide( - intent, DecisionKind.REJECTED, now, (REASON_BATTERY_NOT_SUPPORTED,), mode - ) + if isinstance(intent.action, BatteryAction) or device_id == BATTERY_ASSET_ID: + return await self._submit_battery(intent, now, mode) current = await self._runtime(device_id) runtime = overrides.expire(current, now) if runtime is not current: # only the expiry is saved, never a stale copy @@ -610,6 +692,440 @@ async def _claimed_write( # noqa: PLR0917 self._unclaim(intent.id, claim_ts) return decision + # --- battery (Phase 4 WP10, ADR-0013) -------------------------------------------------- + + async def _submit_battery( # noqa: PLR0911, PLR0912 - one return per verdict + self, intent: Intent, now: datetime, mode: OperatingMode + ) -> Decision: + """The battery's path through the gate (same order as a device's, ADR-0013 invariants). + + Without a battery adapter (observe-only, no model) or for another asset id every + battery action is rejected with ``safety.battery_not_supported`` - nothing is written. + """ + actuator = self._battery_actuator() + if actuator is None or intent.asset_id != BATTERY_ASSET_ID: + return await self._decide( + intent, DecisionKind.REJECTED, now, (REASON_BATTERY_NOT_SUPPORTED,), mode + ) + current = await self._runtime(BATTERY_ASSET_ID) + runtime = overrides.expire(current, now) + if runtime is not current: + await self._save(runtime) + runtime = await self._own_runtime(BATTERY_ASSET_ID, runtime) + action = intent.action + if mode is OperatingMode.SHADOW: + reasons: tuple[Reason, ...] = (REASON_SHADOW_MODE,) + if isinstance(action, BatteryAction): + observed = await actuator.read_back() + baseline = runtime.baseline if runtime.under_control else observed + reasons += evaluate_battery(self._battery_context(action, actuator, baseline, now)) + return await self._decide(intent, DecisionKind.SHADOW, now, reasons, mode) + pause = self._watchdog.pause_reason(BATTERY_SCOPE, now) + if pause is not None: + return await self._decide(intent, DecisionKind.REJECTED, now, (pause,), mode) + held_back = self._held_back(intent, runtime) + if held_back is not None: + return await self._decide(intent, DecisionKind.REJECTED, now, (held_back,), mode) + if runtime.is_held(now) and intent.origin is not Origin.USER: + return await self._decide( + intent, + DecisionKind.HELD, + now, + (REASON_OVERRIDE_HELD,), + mode, + held_until=runtime.override_until, + ) + if not isinstance(action, BatteryAction): + if isinstance(action, ReleaseAction): + return await self.release_device( + BATTERY_ASSET_ID, REASON_RELEASED, origin=intent.origin, intent=intent + ) + return await self._decide( + intent, DecisionKind.REJECTED, now, (REASON_BATTERY_NOT_SUPPORTED,), mode + ) + refusal = actuator.refusal() + if refusal is not None: + return await self._decide(intent, DecisionKind.REJECTED, now, (refusal,), mode) + observed = await actuator.read_back() + if observed is None: + return await self._decide( + intent, DecisionKind.REJECTED, now, (REASON_STATE_UNKNOWN,), mode + ) + baseline = runtime.baseline if runtime.under_control else observed + ctx = self._battery_context(action, actuator, baseline, now) + violations = evaluate_battery(ctx) + if violations: + return await self._decide(intent, DecisionKind.REJECTED, now, violations, mode) + fields = readable_fields(actuator.capabilities) + held = runtime.last_written if runtime.under_control else None + if same_state(ctx.target, observed, fields) and ( + not runtime.under_control or held == action + ): + # Write only on change (B7): the battery already holds this state. + return await self._decide( + intent, DecisionKind.REJECTED, now, (REASON_BATTERY_NO_CHANGE,), mode + ) + if mode is OperatingMode.ASSISTED and intent.origin is not Origin.USER: + expires = now + timedelta(seconds=self._settings.proposal_ttl_s) + decision = await self._decide( + intent, DecisionKind.PROPOSED, now, (REASON_PROPOSED,), mode, expires_at=expires + ) + self._proposals[intent.id] = decision + return decision + return await self._battery_write(intent, action, actuator, now, mode) + + def _battery_live(self) -> BatteryLive: + inputs = self._inputs() + if inputs is None or inputs.ts is None: + return BatteryLive() + max_age = timedelta(seconds=self._settings.inputs_max_age_ticks * self._settings.tick_s) + if self._now() - inputs.ts > max_age: + return BatteryLive() # stale inputs count as unknown + return BatteryLive.of(inputs.flows) + + def _battery_context( + self, + requested: BatteryAction, + actuator: BatteryActuator, + baseline: Action | None, + now: datetime, + ) -> BatteryContext: + config = self._battery + assert config is not None + base = baseline if isinstance(baseline, BatteryAction) else None + ranges = actuator.ranges() + try: + plan = config.plan(now) + except Exception: + log.exception("safety.battery_plan_failed") + plan = None + band, fresh = (None, False) if plan is None else plan_band(plan, now) + try: + price = config.import_price(now) + except Exception: + log.exception("safety.battery_price_failed") + price = None + inputs = self._inputs() or GateInputs() + return BatteryContext( + requested=requested, + target=quantise(resolve_battery_action(requested, base), ranges), + capabilities=actuator.capabilities, + ranges=ranges, + model=config.model, + reserve_pct=config.reserve_pct, + live=self._battery_live(), + band=band, + plan_fresh=fresh, + policy=config.policy, + import_price=price, + tz=self._tz, + import_limit_w=inputs.import_limit_w, + reserve_w=self._settings.reserve_w, + now=now, + baseline=base, + ) + + async def _battery_write( # noqa: PLR0912 - one branch per verdict + self, + intent: Intent, + requested: BatteryAction, + actuator: BatteryActuator, + now: datetime, + mode: OperatingMode, + ) -> Decision: + """Takeover (baseline, hardware fallback first), write, settle, read back.""" + config = self._battery + assert config is not None + failed: Reason | None = None + context_id: str | None = None + async with self._lock(BATTERY_ASSET_ID): + runtime = self._runtimes.get(BATTERY_ASSET_ID) or DeviceRuntime( + device_id=BATTERY_ASSET_ID + ) + blocked = self._blocked(intent, runtime, now) + if blocked is not None: + return await self._decide(intent, DecisionKind.REJECTED, now, (blocked,), mode) + previous_slot = self._limiter.last_write(BATTERY_ASSET_ID) + if not self._limiter.try_acquire(BATTERY_ASSET_ID, now): + return await self._decide( + intent, DecisionKind.REJECTED, now, (REASON_RATE_LIMITED,), mode + ) + if not runtime.under_control: + baseline = await actuator.read_back() + if baseline is None: + self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) + return await self._decide( + intent, DecisionKind.REJECTED, now, (REASON_STATE_UNKNOWN,), mode + ) + if not actuator.prepared(): + # Kostal §3.5: the fallback registers are written and read back before the + # first limit; otherwise nothing else is written (ADR-0013 decision 5). + try: + await actuator.arm_fallback() + except Exception as exc: + log.warning("safety.battery_fallback_failed", error=str(exc)[:200]) + failed = REASON_WRITE_FAILED + if failed is None: + await self._sleep(actuator.settle_s) + if not actuator.prepared(): + failed = REASON_BATTERY_FALLBACK_UNCONFIRMED + if failed is not None: + await self._save(runtime.model_copy(update={"last_write_ts": now})) + if failed is None: + blocked = self._blocked( + intent, self._runtimes.get(BATTERY_ASSET_ID, runtime), now + ) + if blocked is not None: + self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) + return await self._decide( + intent, DecisionKind.REJECTED, now, (blocked,), mode + ) + runtime = runtime.model_copy( + update={ + "baseline": baseline, + "baseline_ts": now, + "identity": config.identity, + } + ) + await self._save(runtime) + if failed is None: + ctx = self._battery_context(requested, actuator, runtime.baseline, now) + written = intent.model_copy(update={"action": ctx.target}) + try: + context_id = await actuator.apply(written) + except Exception as exc: + log.warning("safety.battery_write_failed", error=str(exc)[:200]) + failed = REASON_WRITE_FAILED + runtime = runtime.model_copy(update={"last_write_ts": now}) + await self._save(runtime) + if failed is not None: + await self._count_failure(BATTERY_ASSET_ID, now) + return await self._decide(intent, DecisionKind.FAILED, now, (failed,), mode) + await self._sleep(actuator.settle_s) + observed = await actuator.read_back() + return await self._battery_confirm( + intent, requested, actuator, now, observed=observed, context_id=context_id, mode=mode + ) + + async def _battery_confirm( + self, + intent: Intent, + requested: BatteryAction, + actuator: BatteryActuator, + now: datetime, + *, + observed: Action | None, + context_id: str | None, + mode: OperatingMode, + ) -> Decision: + """Read-back after the settle wait (mandatory: both Kostal paths fail silently).""" + after = self._now() + mismatch = False + async with self._lock(BATTERY_ASSET_ID): + runtime = self._runtimes.get(BATTERY_ASSET_ID) + if runtime is None or not runtime.under_control: + return await self._decide( + intent, + DecisionKind.FAILED, + after, + (REASON_SUPERSEDED,), + mode, + observed=observed, + ) + base = runtime.baseline if isinstance(runtime.baseline, BatteryAction) else None + target = quantise(resolve_battery_action(requested, base), actuator.ranges()) + if not same_state(target, observed, readable_fields(actuator.capabilities)): + mismatch = True + runtime = runtime.model_copy( + update={ + "last_write_context_id": context_id, + "pending_action": requested, + "pending_ts": now, + } + ) + else: + self._failures.pop(BATTERY_ASSET_ID, None) + runtime = runtime.model_copy( + update={ + "last_written": requested, + "last_write_context_id": context_id, + "pending_action": None, + "pending_ts": None, + } + ) + self._battery_beat = after # the write itself was the first beat of the lease + await self._save(runtime) + if mismatch: + await self._count_failure(BATTERY_ASSET_ID, after) + return await self._decide( + intent, + DecisionKind.FAILED, + after, + (REASON_READBACK_MISMATCH,), + mode, + observed=observed, + ) + return await self._decide( + intent, DecisionKind.ACCEPTED, after, intent.reasons, mode, observed=observed + ) + + async def _battery_lease(self, now: datetime) -> Decision | None: + """Every tick while SunCore holds battery limits (ADR-0013 decision 5, B7). + + The lease ends - and the baseline is restored - when the mode fell to shadow, the + watchdog paused the battery or the site, the controller's inputs are stale, or any + battery invariant no longer holds for the held state (the plan interval ended or is no + longer fresh, the price left the policy, the SoC reached the maximum, the import limit + would break). A change of the limits outside SunCore is a manual override: SunCore lets + go without writing and holds off per the default override policy. While the lease holds, + an adapter with a heartbeat re-writes the held state every ``heartbeat_s``. + """ + actuator = self._battery_actuator() + runtime = self._runtimes.get(BATTERY_ASSET_ID) + if ( + actuator is None + or runtime is None + or not runtime.under_control + or runtime.release_pending + or self._is_orphan(BATTERY_ASSET_ID, runtime) + ): + return None + held = runtime.last_written or runtime.pending_action + if not isinstance(held, BatteryAction): + return None + reason: Reason | None = None + if self.modes_of(BATTERY_ASSET_ID).effective is OperatingMode.SHADOW: + reason = REASON_MODE_SHADOW + if reason is None: + reason = self._watchdog.pause_reason(BATTERY_SCOPE, now) + inputs = self._inputs() + max_age = timedelta(seconds=self._settings.inputs_max_age_ticks * self._settings.tick_s) + if reason is None and (inputs is None or inputs.ts is None or now - inputs.ts > max_age): + reason = REASON_BATTERY_INPUTS_STALE + if reason is None: + violations = lease_violations( + self._battery_context(held, actuator, runtime.baseline, now) + ) + reason = violations[0] if violations else None + if reason is not None: + return await self.release_device(BATTERY_ASSET_ID, reason, origin=Origin.SAFETY) + if runtime.pending_action is None and runtime.last_written is not None: + override = await self._battery_override(actuator, runtime, now) + if override is not None: + return override + heartbeat = actuator.heartbeat_s + if ( + heartbeat is not None + and runtime.last_written is not None + and ( + self._battery_beat is None + or (now - self._battery_beat).total_seconds() >= heartbeat + ) + ): + self._battery_beat = now + try: + await actuator.keep_alive() + except Exception as exc: + log.warning("safety.battery_heartbeat_failed", error=str(exc)[:200]) + await self._count_failure(BATTERY_ASSET_ID, now) + return None + + async def _battery_override( + self, actuator: BatteryActuator, runtime: DeviceRuntime, now: datetime + ) -> Decision | None: + """The held limits changed outside SunCore (after the settle time): let go, no write.""" + last = runtime.last_write_ts + if last is None or (now - last).total_seconds() < 2 * actuator.settle_s: + return None + held = runtime.last_written + assert isinstance(held, BatteryAction) + base = runtime.baseline if isinstance(runtime.baseline, BatteryAction) else None + target = quantise(resolve_battery_action(held, base), actuator.ranges()) + observed = await actuator.read_back() + if observed is None or same_state(target, observed, readable_fields(actuator.capabilities)): + return None + async with self._lock(BATTERY_ASSET_ID): + until = overrides.resume_at(_DEFAULT_POLICY, now, self._tz) + released = overrides.hold_until(runtime, until).model_copy( + update={ + "baseline": None, + "baseline_ts": None, + "last_written": None, + "pending_action": None, + "pending_ts": None, + } + ) + await self._save(released) + self._battery_beat = None + log.info("safety.battery_override", until=until) + return await self._decide( + Intent( + id=f"override:{BATTERY_ASSET_ID}:{now.isoformat()}", + ts=now, + asset_id=BATTERY_ASSET_ID, + action=observed, + reasons=(REASON_BATTERY_OVERRIDE,), + origin=Origin.SAFETY, + ), + DecisionKind.HELD, + now, + (REASON_BATTERY_OVERRIDE,), + self.modes_of(BATTERY_ASSET_ID).effective, + held_until=until, + observed=observed, + ) + + async def _battery_release_check(self, now: datetime) -> Decision | None: + """After a release of an adapter without hardware fallback: does the battery show its + baseline? Otherwise the battery scope trips (control paused) and the user is told.""" + due = self._battery_verify + actuator = self._battery_actuator() + if due is None or now < due[0]: + return None + self._battery_verify = None + if actuator is None: + return None + expected = due[1] + observed = await actuator.read_back() + if same_state( + expected if isinstance(expected, BatteryAction) else None, + observed, + readable_fields(actuator.capabilities), + ): + return None + self._watchdog.trip(BATTERY_SCOPE, REASON_BATTERY_RELEASE_UNCONFIRMED, now) + return await self._decide( + Intent( + id=f"release-check:{BATTERY_ASSET_ID}:{now.isoformat()}", + ts=now, + asset_id=BATTERY_ASSET_ID, + action=ReleaseAction(), + reasons=(REASON_BATTERY_RELEASE_UNCONFIRMED,), + origin=Origin.SAFETY, + ), + DecisionKind.FAILED, + now, + (REASON_BATTERY_RELEASE_UNCONFIRMED,), + self.modes_of(BATTERY_ASSET_ID).effective, + observed=observed, + ) + + async def check_battery(self, flows: FlowSnapshot | None) -> Reason | None: + """B8: the battery watch on this tick's flows; a fault pauses battery control and + releases the battery (the site watchdog covers missing and implausible values).""" + config = self._battery + if config is None or self._battery_actuator() is None: + return None + now = self._now() + capacity = None if config.model is None else config.model.capacity_wh + reason = self._battery_watch.check(now, BatteryLive.of(flows), capacity) + faults = self._watchdog.report(BATTERY_SCOPE, () if reason is None else (reason,), now) + if faults: + runtime = self._runtimes.get(BATTERY_ASSET_ID) + if runtime is not None and runtime.under_control and not runtime.release_pending: + await self.release_device(BATTERY_ASSET_ID, faults[0].reason, origin=Origin.SAFETY) + return reason + # --- per-snapshot claims --------------------------------------------------------------- def _snapshot_ts(self) -> datetime | None: @@ -901,16 +1417,37 @@ async def release_device( # noqa: PLR0911 - one return per verdict self._proposals = { k: v for k, v in self._proposals.items() if v.intent.asset_id != device_id } + if device_id == BATTERY_ASSET_ID: + self._after_battery_release(actuator, runtime.baseline, now) return await self._decide( intent, DecisionKind.ACCEPTED, now, (REASON_RELEASED, reason), mode ) + def _after_battery_release( + self, actuator: Actuator, baseline: Action | None, now: datetime + ) -> None: + """The heartbeat stops with the release; an adapter without hardware fallback is read + back once after its settle time (``_battery_release_check``).""" + self._battery_beat = None + if ( + isinstance(actuator, BatteryActuator) + and BatteryCapability.HARDWARE_FALLBACK not in actuator.capabilities + and isinstance(baseline, BatteryAction) + ): + self._battery_verify = (now + timedelta(seconds=actuator.settle_s), baseline) + + def _identity_of(self, asset_id: str) -> str | None: + """The configured identity token of an asset (``None`` = not configured).""" + if asset_id == BATTERY_ASSET_ID and self._battery is not None: + return self._battery.identity + device = self._devices(asset_id) + return None if device is None else identity_token(device) + def _is_orphan(self, device_id: str, runtime: DeviceRuntime) -> bool: - """The runtime belongs to a device that is no longer configured as it was taken over.""" + """The runtime belongs to an asset that is no longer configured as it was taken over.""" if runtime.identity is None: return False - device = self._devices(device_id) - return device is None or identity_token(device) != runtime.identity + return self._identity_of(device_id) != runtime.identity def _held_back(self, intent: Intent, runtime: DeviceRuntime) -> Reason | None: """Writing waits for a release: of another device's runtime, or a deferred one.""" @@ -929,14 +1466,14 @@ async def _own_runtime(self, device_id: str, runtime: DeviceRuntime) -> DeviceRu await self._save(fresh) return fresh - def _leftovers(self) -> dict[str, tuple[Actuator, DeviceConfig]]: - """For the successor gate: what can still release a device this gate left under control.""" + def _leftovers(self) -> dict[str, tuple[Actuator, str, DeviceConfig | None]]: + """For the successor gate: what can still release an asset this gate left under control.""" out = dict(self._release_only) for device_id, runtime in self._runtimes.items(): actuator = self._actuators.get(device_id) - device = self._devices(device_id) - if runtime.under_control and actuator is not None and device is not None: - out[device_id] = (actuator, device) + identity = self._identity_of(device_id) + if runtime.under_control and actuator is not None and identity is not None: + out[device_id] = (actuator, identity, self._devices(device_id)) return out def is_orphaned(self, device_id: str) -> bool: @@ -951,9 +1488,9 @@ def _release_target( if not self._is_orphan(device_id, runtime): return self._actuators.get(device_id), self._devices(device_id) entry = self._release_only.get(device_id) - if entry is None or identity_token(entry[1]) != runtime.identity: + if entry is None or entry[1] != runtime.identity: return None, None - return entry + return entry[0], entry[2] async def _drop_orphan( self, intent: Intent, runtime: DeviceRuntime, now: datetime, mode: OperatingMode diff --git a/suncore/safety/watchdog.py b/suncore/safety/watchdog.py index 58c5a6a..d17fa48 100644 --- a/suncore/safety/watchdog.py +++ b/suncore/safety/watchdog.py @@ -232,6 +232,13 @@ def trip(self, scope: str, reason: Reason, now: datetime) -> None: """Force a scope into the safe state (e.g. repeated write failures).""" self._update(scope, (Fault(FaultKind.INVALID, scope, reason),), now) + def report(self, scope: str, reasons: tuple[Reason, ...], now: datetime) -> tuple[Fault, ...]: + """Feed the result of an external check of ``scope`` (the battery watch, WP10): faults + put it into the safe state, an empty result starts the cool-down like a device check.""" + faults = tuple(Fault(FaultKind.FROZEN, scope, r) for r in reasons) + self._update(scope, faults, now) + return faults + # --- state ---------------------------------------------------------------------- def state(self, scope: str, now: datetime) -> ScopeState: diff --git a/tests/safety/test_battery_gate.py b/tests/safety/test_battery_gate.py new file mode 100644 index 0000000..55bb60c --- /dev/null +++ b/tests/safety/test_battery_gate.py @@ -0,0 +1,564 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The gate's battery path (WP10, ADR-0013): modes, invariants, takeover, read-back, lease, +heartbeat, release paths, override, watchdog - with a fake battery adapter.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any + +import pytest + +from suncore.core.battery import ( + BATTERY_ASSET_ID, + BatteryAction, + BatteryCapability, + BatteryModel, + BatteryRanges, + FieldRange, + GridChargePolicy, + resolve_battery_action, +) +from suncore.core.control import BatteryBand, ControlSettings, GateInputs, Plan, PlanInterval +from suncore.core.decisions import ( + Action, + Decision, + DecisionKind, + Intent, + OperatingMode, + Origin, + ReleaseAction, + SwitchAction, +) +from suncore.safety.battery import BatteryActuator, BatteryGateConfig, BatteryWatch +from suncore.safety.gate import SafetyGate +from suncore.safety.modes import StaticModes +from suncore.safety.runtime import MemoryRuntimeStore +from tests.safety.helpers import T0, FakeClock, flows, make_intent + +AUTO = OperatingMode.AUTOMATIC +ALL = frozenset(BatteryCapability) - {BatteryCapability.HARDWARE_FALLBACK} +MODEL = BatteryModel(capacity_wh=10_000, max_charge_w=5000, max_discharge_w=5000) +BASE = BatteryAction(max_charge_w=5000, max_discharge_w=5000, min_soc_pct=10, grid_charge_w=0) + + +@dataclass +class FakeBattery: + """A battery adapter: ``state`` is what the entities show.""" + + caps: frozenset[BatteryCapability] = ALL + state: BatteryAction | None = BASE + settle: float = 10.0 + beat: float | None = None + armed_ok: bool = True + armed: bool = False + silent_fail: bool = False + refuse: Any = None + applied: list[BatteryAction] = field(default_factory=list) + released: list[Action | None] = field(default_factory=list) + beats: int = 0 + held: BatteryAction | None = None + + @property + def asset_id(self) -> str: + return BATTERY_ASSET_ID + + @property + def capabilities(self) -> frozenset[BatteryCapability]: + return self.caps + + @property + def settle_s(self) -> float: + return self.settle + + @property + def heartbeat_s(self) -> float | None: + return self.beat + + def ranges(self) -> BatteryRanges: + return BatteryRanges( + max_charge_w=FieldRange(0, 5000), + max_discharge_w=FieldRange(0, 5000), + min_soc_pct=FieldRange(5, 100, 5), + grid_charge_w=FieldRange(0, 5000), + ) + + def refusal(self) -> Any: + return self.refuse + + def prepared(self) -> bool: + return BatteryCapability.HARDWARE_FALLBACK not in self.caps or self.armed + + async def arm_fallback(self) -> None: + self.armed = self.armed_ok + + async def keep_alive(self) -> None: + self.beats += 1 + + async def read_back(self) -> Action | None: + return self.state + + async def apply(self, intent: Intent) -> str | None: + assert isinstance(intent.action, BatteryAction) + self.applied.append(intent.action) + self.held = intent.action + if not self.silent_fail: + self.state = resolve_battery_action(intent.action, self.state) + return "ctx" + + async def release(self, baseline: Action | None) -> None: + self.released.append(baseline) + self.held = None + if isinstance(baseline, BatteryAction): + self.state = baseline + + +def plan(*, now: Any = T0, **band: Any) -> Plan: + start = now - timedelta(minutes=5) + return Plan( + created_at=start, + intervals=( + PlanInterval( + start=start, end=start + timedelta(minutes=15), battery=BatteryBand(**band) + ), + ), + ) + + +@dataclass +class Rig: + gate: SafetyGate + battery: FakeBattery + clock: FakeClock + modes: StaticModes + decisions: list[Decision] + inputs: dict[str, GateInputs] + plans: dict[str, Plan] + prices: dict[str, float | None] + + def at(self, **kw: Any) -> None: + self.inputs["now"] = GateInputs(flows=flows(**kw), import_limit_w=10_000, ts=self.clock.now) + + async def submit(self, action: Action, *, origin: Origin = Origin.CONTROLLER) -> Decision: + intent = make_intent(action, asset_id=BATTERY_ASSET_ID, ts=self.clock.now, origin=origin) + return await self.gate.submit(intent) + + async def tick(self, seconds: float = 5.0) -> tuple[Decision, ...]: + self.clock.advance(seconds) + inputs = self.inputs["now"] + self.inputs["now"] = GateInputs( + flows=inputs.flows, import_limit_w=inputs.import_limit_w, ts=self.clock.now + ) + return await self.gate.poll() + + +def rig( + battery: FakeBattery | None = None, + *, + mode: OperatingMode = AUTO, + policy: GridChargePolicy | None = None, + fallback_verified: bool = False, + store: MemoryRuntimeStore | None = None, + identity: str = "bat-1", + settings: ControlSettings | None = None, +) -> Rig: + clock = FakeClock() + battery = battery or FakeBattery() + decisions: list[Decision] = [] + inputs: dict[str, GateInputs] = {} + plans = {"now": plan(grid_charge_max_w=3000, discharge_lock=True)} + prices: dict[str, float | None] = {"now": 0.10} + + async def sink(decision: Decision) -> None: + decisions.append(decision) + + modes = StaticModes(AUTO, battery=mode) + config = BatteryGateConfig( + identity=identity, + model=MODEL, + reserve_pct=15.0, + policy=policy or GridChargePolicy(enabled=True, max_price=0.20), + fallback_verified=fallback_verified, + plan=lambda _now: plans["now"], + import_price=lambda _now: prices["now"], + watch=BatteryWatch(frozen_s=300), + ) + gate = SafetyGate( + clock=clock, + sink=sink, + actuators={BATTERY_ASSET_ID: battery}, + modes=modes, + inputs=lambda: inputs.get("now"), + store=store or MemoryRuntimeStore(), + settings=settings or ControlSettings(), + sleep=clock.sleep, + battery=config, + ) + r = Rig(gate, battery, clock, modes, decisions, inputs, plans, prices) + r.at(grid_w=600, battery_w=0, soc_pct=40) + return r + + +def keys(decision: Decision) -> list[str]: + return [r.key for r in decision.reasons] + + +def test_the_fake_is_a_battery_actuator() -> None: + assert isinstance(FakeBattery(), BatteryActuator) + + +# --- the blanket rejection is gone only for the configured adapter ----------------------------- + + +async def test_without_battery_wiring_or_for_another_asset_nothing_is_written() -> None: + r = rig() + decision = await r.gate.submit( + make_intent(BatteryAction(max_discharge_w=0), asset_id="pool", ts=r.clock.now) + ) + assert decision.kind is DecisionKind.REJECTED + assert keys(decision) == ["safety.battery_not_supported"] + + async def sink(_: Decision) -> None: + return None + + bare = SafetyGate(clock=r.clock, sink=sink, modes=StaticModes(AUTO, battery=AUTO)) + decision = await bare.submit( + make_intent(BatteryAction(max_discharge_w=0), asset_id=BATTERY_ASSET_ID, ts=r.clock.now) + ) + assert keys(decision) == ["safety.battery_not_supported"] + assert r.battery.applied == [] + + +async def test_a_battery_starts_in_shadow_and_shadow_never_writes() -> None: + r = rig(mode=OperatingMode.SHADOW) + decision = await r.submit(BatteryAction(max_discharge_w=0)) + assert decision.kind is DecisionKind.SHADOW + assert keys(decision) == ["safety.shadow_mode"] + unplanned = await r.submit(BatteryAction(grid_charge_w=4000)) + assert "safety.battery_grid_charge_bound" in keys(unplanned) # honest "would have" reasons + assert r.battery.applied == [] + + +async def test_global_shadow_wins_over_the_battery_mode() -> None: + r = rig() + r.modes.set_global(OperatingMode.SHADOW) + assert (await r.submit(BatteryAction(max_discharge_w=0))).kind is DecisionKind.SHADOW + + +# --- writes ------------------------------------------------------------------------------------ + + +async def test_a_planned_discharge_lock_is_written_and_read_back() -> None: + r = rig() + decision = await r.submit(BatteryAction(max_discharge_w=0)) + assert decision.kind is DecisionKind.ACCEPTED, keys(decision) + # None = baseline: the adapter receives the full resolved state. + assert r.battery.applied == [ + BatteryAction(max_charge_w=5000, max_discharge_w=0, min_soc_pct=10, grid_charge_w=0) + ] + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.baseline == BASE + assert runtime.last_written == BatteryAction(max_discharge_w=0) + assert runtime.identity == "bat-1" + + +async def test_write_only_on_change() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + r.clock.advance(60) + r.at(grid_w=600, battery_w=0, soc_pct=40) + again = await r.submit(BatteryAction(max_discharge_w=0)) + assert again.kind is DecisionKind.REJECTED + assert keys(again) == ["safety.battery_write_no_change"] + assert len(r.battery.applied) == 1 + + +async def test_write_rate_limit() -> None: + r = rig(settings=ControlSettings(min_write_interval_s=120)) + await r.submit(BatteryAction(max_discharge_w=0)) + decision = await r.submit(BatteryAction(max_discharge_w=0, min_soc_pct=45)) + assert keys(decision) == ["safety.rate_limited"] + + +async def test_a_silent_write_failure_is_a_failed_read_back_and_three_trip() -> None: + r = rig(FakeBattery(silent_fail=True), settings=ControlSettings(min_write_interval_s=1)) + for i in range(3): + decision = await r.submit(BatteryAction(max_discharge_w=0, min_soc_pct=20 + 5 * i)) + assert decision.kind is DecisionKind.FAILED + assert keys(decision) == ["safety.readback_mismatch"] + r.clock.advance(2) + r.at(grid_w=600, battery_w=0, soc_pct=40) + assert r.gate.watchdog.pause_reason(BATTERY_ASSET_ID, r.clock.now) is not None + assert r.battery.released == [BASE] # the trip released it at once + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert not runtime.under_control + + +@pytest.mark.parametrize( + ("action", "key"), + [ + (BatteryAction(min_soc_pct=10), "safety.battery_min_soc_below_reserve"), + (BatteryAction(grid_charge_w=4000), "safety.battery_grid_charge_bound"), + (BatteryAction(max_charge_w=6000), "safety.battery_out_of_range"), + ], +) +async def test_invariant_violations_are_rejected(action: BatteryAction, key: str) -> None: + r = rig() + decision = await r.submit(action) + assert decision.kind is DecisionKind.REJECTED + assert key in keys(decision) + assert r.battery.applied == [] + + +async def test_an_unplanned_lock_and_grid_charge_outside_the_policy_are_rejected() -> None: + r = rig() + r.plans["now"] = plan() # no lock, no grid charging in this interval + assert keys(await r.submit(BatteryAction(max_discharge_w=0))) == [ + "safety.battery_unplanned_import" + ] + r.plans["now"] = plan(grid_charge_max_w=3000) + r.prices["now"] = 0.35 + assert keys(await r.submit(BatteryAction(grid_charge_w=2000))) == [ + "safety.battery_grid_charge_policy" + ] + r.prices["now"] = None + assert keys(await r.submit(BatteryAction(grid_charge_w=2000))) == [ + "safety.battery_grid_charge_policy" + ] + assert r.battery.applied == [] + + +async def test_missing_capability_and_adapter_refusal() -> None: + r = rig(FakeBattery(caps=frozenset({BatteryCapability.MIN_SOC}))) + assert "safety.battery_capability_missing" in keys( + await r.submit(BatteryAction(grid_charge_w=1)) + ) + refused = rig() + from suncore.core.decisions import Reason # noqa: PLC0415 + + refused.battery.refuse = Reason(key="safety.battery_external_control_off", args={"value": "0"}) + decision = await refused.submit(BatteryAction(max_discharge_w=0)) + assert keys(decision) == ["safety.battery_external_control_off"] + + +async def test_assisted_proposes_and_a_confirmation_writes() -> None: + r = rig(mode=OperatingMode.ASSISTED) + proposal = await r.submit(BatteryAction(max_discharge_w=0)) + assert proposal.kind is DecisionKind.PROPOSED + assert r.battery.applied == [] + confirmed = await r.gate.confirm(proposal.intent.id) + assert confirmed is not None + assert confirmed.kind is DecisionKind.ACCEPTED + + +async def test_an_unverified_hardware_fallback_caps_the_battery_at_assisted() -> None: + battery = FakeBattery(caps=ALL | {BatteryCapability.HARDWARE_FALLBACK}) + r = rig(battery) + assert r.gate.battery_mode_capped + assert r.gate.modes_of(BATTERY_ASSET_ID).effective is OperatingMode.ASSISTED + assert (await r.submit(BatteryAction(max_discharge_w=0))).kind is DecisionKind.PROPOSED + verified = rig( + FakeBattery(caps=ALL | {BatteryCapability.HARDWARE_FALLBACK}), fallback_verified=True + ) + assert verified.gate.modes_of(BATTERY_ASSET_ID).effective is OperatingMode.AUTOMATIC + + +async def test_the_hardware_fallback_is_armed_and_confirmed_before_the_first_limit() -> None: + battery = FakeBattery(caps=ALL | {BatteryCapability.HARDWARE_FALLBACK}, beat=20) + r = rig(battery, fallback_verified=True) + decision = await r.submit(BatteryAction(max_discharge_w=0)) + assert decision.kind is DecisionKind.ACCEPTED + assert battery.armed + unconfirmed = rig( + FakeBattery(caps=ALL | {BatteryCapability.HARDWARE_FALLBACK}, armed_ok=False), + fallback_verified=True, + ) + failed = await unconfirmed.submit(BatteryAction(max_discharge_w=0)) + assert failed.kind is DecisionKind.FAILED + assert keys(failed) == ["safety.battery_fallback_unconfirmed"] + assert unconfirmed.battery.applied == [] + + +# --- lease and heartbeat -------------------------------------------------------------------------- + + +async def test_the_heartbeat_runs_only_while_the_lease_holds() -> None: + battery = FakeBattery(caps=ALL | {BatteryCapability.HARDWARE_FALLBACK}, beat=20) + r = rig(battery, fallback_verified=True) + await r.submit(BatteryAction(max_discharge_w=0)) + for _ in range(12): # 60 s + await r.tick(5) + assert 2 <= battery.beats <= 3 + # The plan interval stops asking for the lock: the lease ends, the baseline is restored. + r.plans["now"] = plan(now=r.clock.now) + decisions = await r.tick(5) + assert [d.kind for d in decisions] == [DecisionKind.ACCEPTED] + assert "safety.battery_unplanned_import" in keys(decisions[0]) + assert battery.released == [BASE] + beats = battery.beats + for _ in range(12): + await r.tick(5) + assert battery.beats == beats # no heartbeat without a lease + + +async def test_a_stale_plan_ends_the_lease() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + for _ in range(4): + assert await r.tick(5) == () + r.plans["now"] = r.plans["now"].model_copy( + update={"created_at": r.clock.now - timedelta(minutes=40)} + ) + decisions = await r.tick(5) + assert decisions + assert "safety.battery_plan_stale" in keys(decisions[0]) + assert r.battery.state == BASE + + +async def test_grid_charging_ends_when_the_live_price_leaves_the_policy() -> None: + r = rig() + decision = await r.submit(BatteryAction(grid_charge_w=2000)) + assert decision.kind is DecisionKind.ACCEPTED, keys(decision) + assert await r.tick(5) == () + r.prices["now"] = 0.40 + decisions = await r.tick(5) + assert "safety.battery_grid_charge_policy" in keys(decisions[0]) + assert r.battery.state == BASE + + +async def test_grid_charging_ends_at_the_import_limit() -> None: + r = rig() + await r.submit(BatteryAction(grid_charge_w=3000)) + r.at(grid_w=9000, battery_w=3000, soc_pct=40) # the house alone now draws 6 kW + r.inputs["now"] = GateInputs( + flows=flows(grid_w=9000, battery_w=3000, soc_pct=40), import_limit_w=8000, ts=r.clock.now + ) + decisions = await r.tick(5) + assert decisions + assert keys(decisions[0])[1] in ( + "safety.battery_grid_charge_bound", + "safety.battery_import_limit", + ) + + +async def test_a_manual_change_is_an_override_and_is_respected() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + r.clock.advance(60) + r.battery.state = BatteryAction( + max_charge_w=5000, max_discharge_w=2500, min_soc_pct=30, grid_charge_w=0 + ) + decisions = await r.tick(5) + assert [d.kind for d in decisions] == [DecisionKind.HELD] + assert keys(decisions[0]) == ["safety.battery_override"] + assert r.battery.released == [] # the user's change is not overwritten + held = await r.submit(BatteryAction(max_discharge_w=0)) + assert held.kind is DecisionKind.HELD + + +# --- release paths ------------------------------------------------------------------------------ + + +async def test_emergency_stop_restores_the_baseline_and_blocks() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + await r.gate.emergency_stop() + assert r.battery.released == [BASE] + assert r.battery.state == BASE + assert keys(await r.submit(BatteryAction(max_discharge_w=0))) == ["safety.emergency_stop"] + + +async def test_mode_to_shadow_releases() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + r.modes.set_battery(OperatingMode.SHADOW) + await r.gate.sync_modes() + assert r.battery.released == [BASE] + + +async def test_shutdown_releases_within_the_deadline() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + await r.gate.shutdown() + assert r.battery.released == [BASE] + + +async def test_crash_recovery_releases_what_a_crash_left() -> None: + store = MemoryRuntimeStore() + r = rig(store=store) + await r.submit(BatteryAction(max_discharge_w=0)) + # the process dies; a new gate on the same store recovers + restarted = rig(r.battery, store=store) + await restarted.gate.recover() + assert r.battery.released == [BASE] + + +async def test_a_remapped_battery_is_released_never_written() -> None: + store = MemoryRuntimeStore() + r = rig(store=store) + await r.submit(BatteryAction(max_discharge_w=0)) + other = rig(FakeBattery(), store=store, identity="bat-2") + await other.gate.recover() # no actuator for the old battery: reported, dropped + assert other.battery.released == [] + assert other.battery.applied == [] + runtime = other.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert not runtime.under_control + + +async def test_a_controller_release_restores_the_baseline_and_is_verified() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + r.clock.advance(60) + decision = await r.submit(ReleaseAction()) + assert decision.kind is DecisionKind.ACCEPTED + assert r.battery.state == BASE + for _ in range(3): + assert await r.tick(5) == () # the read-back after the settle time confirms it + + +async def test_an_unconfirmed_release_pauses_battery_control() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + r.battery.silent_fail = True + + async def ignore(_: Action | None) -> None: + return None + + r.battery.release = ignore # type: ignore[method-assign] + await r.gate.emergency_stop() + await r.gate.clear_emergency_stop() + decisions = [d for _ in range(3) for d in await r.tick(5)] + assert [keys(d) for d in decisions] == [["safety.battery_release_unconfirmed"]] + assert r.gate.watchdog.pause_reason(BATTERY_ASSET_ID, r.clock.now) is not None + + +# --- watchdog (B8) ------------------------------------------------------------------------------ + + +async def test_a_frozen_battery_while_the_grid_moves_releases_and_pauses() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + reason = None + for i in range(100): + r.clock.advance(5) + grid = 300.0 + (900.0 if (i // 6) % 2 else 0.0) + reason = await r.gate.check_battery(flows(grid_w=grid, battery_w=-800, soc_pct=40)) + if reason is not None: + break + assert reason is not None + assert reason.key == "safety.battery_frozen" + assert r.battery.released == [BASE] + assert r.gate.watchdog.pause_reason(BATTERY_ASSET_ID, r.clock.now) is not None + + +async def test_a_device_never_sees_the_battery_path() -> None: + """Phase 3 device rules unchanged: a device intent still goes through the device path.""" + r = rig() + decision = await r.gate.submit( + make_intent(SwitchAction(on=True), asset_id="pool", ts=r.clock.now) + ) + assert keys(decision) == ["safety.shadow_mode"] # no mode for the device: shadow diff --git a/tests/safety/test_boundary.py b/tests/safety/test_boundary.py index 217eeac..0e2af1d 100644 --- a/tests/safety/test_boundary.py +++ b/tests/safety/test_boundary.py @@ -191,7 +191,7 @@ def test_the_gate_is_the_single_writer() -> None: battery adapters' ``arm_fallback`` and ``keep_alive``).""" gate = PACKAGE / "safety" / "gate.py" tree = parse(gate) - for attr in ("apply", "release"): + for attr in WRITE_CALLS: assert list(attribute_calls(tree, attr)), f"gate.py must contain the {attr}() call" everywhere = [ line diff --git a/tests/safety/test_gate.py b/tests/safety/test_gate.py index e05ba04..1aa21d4 100644 --- a/tests/safety/test_gate.py +++ b/tests/safety/test_gate.py @@ -1207,7 +1207,7 @@ def test_n1_a_deferred_release_is_not_re_deferred_on_every_tick() -> None: assert rt.release_pending -# --- battery actions (Phase 4 WP2): explicitly unsupported until WP10 -------------------- +# --- battery actions without a battery adapter: rejected (WP10 keeps this for the rest) --- @pytest.mark.parametrize("mode", [OperatingMode.SHADOW, OperatingMode.ASSISTED, AUTO]) From 75e6f8bc32cd8fbd637a8536a7228c226e3ec345 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 19:13:00 +0000 Subject: [PATCH 05/16] feat(controller): translate the plan's battery band into battery intents (WP10) - controller.battery.BatteryIntents: grid_charge_max_w -> grid_charge_w (rounded down, within the battery and adapter limits; an all-or-nothing switch only at full power), discharge_lock -> max_discharge_w 0 or a min-SoC floor at the live SoC rounded up (never below the reserve), nothing planned -> ReleaseAction only while the gate holds something (None = baseline) - only a fresh plan interval counts (core.control.battery_band_now, shared with the gate); reasons controller.battery.* incl. grid_charge_unsupported (Kostal REST) for the plan view - against oscillation: intents only on change, power hysteresis, a min-SoC lock moves only a full step after the SoC, one intent per interval, repeats after shadow/proposed every 15 min, property test with flapping bands - a held forced grid charge is never surplus for the consumers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- frontend/src/lib/i18n/locales/de.json | 7 + frontend/src/lib/i18n/locales/en.json | 7 + suncore/controller/battery.py | 272 +++++++++++++++++++++++ suncore/controller/loop.py | 40 +++- suncore/controller/reasons.py | 15 ++ suncore/controller/surplus.py | 11 +- suncore/core/control.py | 24 +- suncore/safety/battery.py | 21 +- tests/controller/test_battery_intents.py | 267 ++++++++++++++++++++++ 9 files changed, 641 insertions(+), 23 deletions(-) create mode 100644 suncore/controller/battery.py create mode 100644 tests/controller/test_battery_intents.py diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index e1b7385..b93a0a9 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -547,6 +547,13 @@ "controller.deficit_budget": "Rücknahme: Der Akku hat bereits {wh} Wh für gesteuerte Geräte gedeckt.", "controller.battery_reserve": "Der Akku steht bei {soc_pct} % (Reserve {reserve_pct} %): Er wird nicht für Geräte genutzt.", "controller.battery_target": "Der Akku lädt zuerst bis {target_pct} % (aktuell {soc_pct} %).", + "controller.battery.grid_charge": "Der Plan lädt den Akku jetzt mit {power_w} W aus dem Netz.", + "controller.battery.grid_charge_unsupported": "Der Plan würde mit {power_w} W aus dem Netz laden, aber der Akku-Adapter kann kein Zwangsladen: nur angezeigt.", + "controller.battery.discharge_lock": "Der Plan hält die Energie des Akkus für später zurück (jetzt keine Entladung).", + "controller.battery.discharge_lock_unsupported": "Der Plan würde den Akku zurückhalten, aber der Akku-Adapter kann das Entladen nicht begrenzen: nur angezeigt.", + "controller.battery.release": "Für den Akku ist nichts geplant: seine eigenen Einstellungen gelten wieder.", + "controller.battery.no_plan": "Kein aktueller Plan: der Akku folgt seinen eigenen Einstellungen.", + "controller.battery.blocked": "Die Akkusteuerung ist pausiert.", "controller.grid_importing": "Warten: Das Haus bezieht {grid_w} W aus dem Netz.", "controller.import_limit": "Sofortige Rücknahme: Das Haus bezieht {grid_w} W, mehr als die Grenze von {limit_w} W.", "controller.base_outside_comfort": "Dein Sollwert {setpoint_c} °C liegt außerhalb des Komfortbereichs {min_c}–{max_c} °C: SunCore verschiebt ihn nicht.", diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index 9abbb9c..9ef9f14 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -547,6 +547,13 @@ "controller.deficit_budget": "Backing off: the battery already covered {wh} Wh for controlled devices.", "controller.battery_reserve": "The battery is at {soc_pct} % (reserve {reserve_pct} %): it is not used for devices.", "controller.battery_target": "The battery charges first until {target_pct} % (now {soc_pct} %).", + "controller.battery.grid_charge": "The plan charges the battery from the grid with {power_w} W now.", + "controller.battery.grid_charge_unsupported": "The plan would charge from the grid with {power_w} W, but the battery adapter cannot force charging: shown only.", + "controller.battery.discharge_lock": "The plan holds the battery's energy for later (no discharge now).", + "controller.battery.discharge_lock_unsupported": "The plan would hold the battery back, but the battery adapter cannot limit discharging: shown only.", + "controller.battery.release": "Nothing planned for the battery: its own settings apply again.", + "controller.battery.no_plan": "No current plan: the battery follows its own settings.", + "controller.battery.blocked": "Battery control is paused.", "controller.grid_importing": "Waiting: the house is importing {grid_w} W from the grid.", "controller.import_limit": "Backing off at once: the house imports {grid_w} W, above the limit of {limit_w} W.", "controller.base_outside_comfort": "Your set-point {setpoint_c} °C is outside the comfort band {min_c}–{max_c} °C: SunCore does not shift it.", diff --git a/suncore/controller/battery.py b/suncore/controller/battery.py new file mode 100644 index 0000000..545a02e --- /dev/null +++ b/suncore/controller/battery.py @@ -0,0 +1,272 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The battery band of the plan -> ``BatteryAction`` intents (Phase 4 WP10, ADR-0013). + +Deterministic, time injected, ``core`` only. Per tick the controller translates the band of the +plan interval covering ``now`` - only while the plan is fresh, like the gate - into the state it +wants the battery adapter to hold: + +* ``grid_charge_max_w > 0`` -> ``grid_charge_w`` (rounded down to ``grid_step_w``, at most the + battery's and the adapter's limit) - only if the adapter can force charging; otherwise no + intent and the reason ``controller.battery.grid_charge_unsupported`` (the plan still shows + the planned grid charging; Kostal REST has no charge set-point); +* ``discharge_lock`` -> ``max_discharge_w = 0`` where the adapter caps discharging, else (a + ``min_soc`` adapter such as Kostal REST) ``min_soc_pct`` = the live SoC rounded **up** to + the entity step, never below the effective reserve; +* nothing planned -> ``None`` = the adapter's baseline: a ``ReleaseAction`` while the gate + still holds something, otherwise no intent at all. + +The reserve is the floor of every ``min_soc_pct`` SunCore writes; SunCore does not hold a +permanent reserve floor on the inverter (that would keep the battery under SunCore's control +around the clock and could lower the user's own floor - ``None`` = baseline). Grid charging +wins over a lock in the same interval (the planner never plans both). + +Against oscillation: intents only on change of the wanted state; a power change smaller than +``hysteresis_w`` keeps the held value; a ``min_soc`` lock is moved only when the SoC rose a full +step above it; at most one new intent per ``interval_s``; the same intent is repeated (after a +shadow, proposed or rejected decision) at most every ``repeat_s``. The battery stays in shadow +by default - the gate decides what is written. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from datetime import datetime, timedelta + +from suncore.controller.reasons import ( + BATTERY_BLOCKED, + BATTERY_DISCHARGE_LOCK, + BATTERY_DISCHARGE_LOCK_UNSUPPORTED, + BATTERY_GRID_CHARGE, + BATTERY_GRID_CHARGE_UNSUPPORTED, + BATTERY_NO_PLAN, + BATTERY_RELEASE, +) +from suncore.core.battery import ( + BATTERY_ASSET_ID, + BatteryAction, + BatteryCapability, + BatteryModel, + BatteryRanges, + round_up_to_step, +) +from suncore.core.control import Plan, battery_band_now +from suncore.core.decisions import ( + Decision, + DecisionKind, + Intent, + Origin, + Reason, + ReleaseAction, +) + + +@dataclass(frozen=True, slots=True) +class BatteryControlSettings: + interval_s: float = 60.0 + """At most one new battery intent per this many seconds.""" + repeat_s: float = 900.0 + """The same intent again (after shadow/proposed/rejected) at most this often.""" + hysteresis_w: float = 300.0 + """A grid-charge power change below this keeps the held power.""" + grid_step_w: float = 100.0 + """Grid-charge powers are multiples of this (rounded down).""" + pending_timeout_s: float = 300.0 + """An intent without a reported decision is forgotten after this (a lost submission).""" + + +@dataclass(frozen=True, slots=True) +class BatteryControlInputs: + """What the composition root tells the controller about the battery adapter each tick.""" + + capabilities: frozenset[BatteryCapability] + ranges: BatteryRanges + model: BatteryModel + reserve_pct: float + held: BatteryAction | None = None + """What the gate holds (``runtime.last_written``; ``None`` = baseline / not controlled).""" + under_control: bool = False + blocked: Reason | None = None + """Emergency stop, watchdog pause, override hold, pending release: no intents.""" + + +@dataclass(frozen=True, slots=True) +class BatteryView: + """The controller's battery decision of the tick (control state, "Why?").""" + + wanted: BatteryAction | None + """The state the plan asks for (``None`` = baseline).""" + reasons: tuple[Reason, ...] + intent_id: str | None = None + last_decision: DecisionKind | None = None + + +class BatteryIntents: + """Stateful translation of the plan's battery band into gate intents (one battery).""" + + def __init__(self, settings: BatteryControlSettings | None = None) -> None: + self._settings = settings if settings is not None else BatteryControlSettings() + self._last_submit: datetime | None = None + self._last_action: BatteryAction | ReleaseAction | None = None + self._last_kind: DecisionKind | None = None + self._pending: str | None = None + self._seq = 0 + self.view: BatteryView | None = None + + @property + def settings(self) -> BatteryControlSettings: + return self._settings + + # --- the wanted state -------------------------------------------------------------------- + + def wanted( # noqa: PLR0911 - one return per rule + self, now: datetime, plan: Plan, inputs: BatteryControlInputs, soc_pct: float | None + ) -> tuple[BatteryAction | None, tuple[Reason, ...]]: + """The state the plan asks for now and why (pure apart from the held state).""" + band, fresh = battery_band_now(plan, now) + if band is None or not fresh: + return None, (Reason(key=BATTERY_NO_PLAN),) + caps = inputs.capabilities + grid_max = band.grid_charge_max_w or 0.0 + if grid_max > 0: + grid = self._grid_power(grid_max, inputs) + if grid is None: + return None, ( + Reason(key=BATTERY_GRID_CHARGE_UNSUPPORTED, args={"power_w": round(grid_max)}), + ) + return BatteryAction(grid_charge_w=grid), ( + Reason(key=BATTERY_GRID_CHARGE, args={"power_w": round(grid)}), + ) + if band.discharge_lock: + if ( + BatteryCapability.DISCHARGE_LIMIT in caps + and inputs.ranges.max_discharge_w is not None + ): + return BatteryAction(max_discharge_w=0.0), (Reason(key=BATTERY_DISCHARGE_LOCK),) + if ( + BatteryCapability.MIN_SOC in caps + and inputs.ranges.min_soc_pct is not None + and soc_pct is not None + ): + floor = self._lock_floor(soc_pct, inputs) + return BatteryAction(min_soc_pct=floor), ( + Reason(key=BATTERY_DISCHARGE_LOCK, args={"min_soc_pct": round(floor)}), + ) + return None, (Reason(key=BATTERY_DISCHARGE_LOCK_UNSUPPORTED),) + return None, () + + def _grid_power(self, planned_w: float, inputs: BatteryControlInputs) -> float | None: + allowed = inputs.ranges.grid_charge_w + if BatteryCapability.GRID_CHARGE not in inputs.capabilities or allowed is None: + return None + if math.isclose(allowed.low, allowed.high): + # A switch or a mode option: all or nothing - only if the plan allows the full power. + return allowed.high if planned_w + 1.0 >= allowed.high else None + step = self._settings.grid_step_w + power = min(planned_w, inputs.model.max_charge_w, allowed.high) + power = math.floor(power / step) * step if step > 0 else power + if power <= 0: + return None + held = inputs.held.grid_charge_w if inputs.held is not None else None + if held is not None and held > 0 and abs(held - power) < self._settings.hysteresis_w: + return held + return power + + def _lock_floor(self, soc_pct: float, inputs: BatteryControlInputs) -> float: + soc_range = inputs.ranges.min_soc_pct + assert soc_range is not None + step = soc_range.step + held = inputs.held.min_soc_pct if inputs.held is not None else None + if held is not None and held >= inputs.reserve_pct and soc_pct < held + (step or 1.0): + # Still (almost) a lock: moved only when the SoC rose a full step above it, so a + # SoC creeping up under PV does not rewrite the floor every few minutes. + return held + floor = max(inputs.reserve_pct, soc_pct) + return min(soc_range.high, round_up_to_step(floor, step, soc_range.low)) + + # --- the intent -------------------------------------------------------------------------- + + def step( + self, + now: datetime, + plan: Plan, + inputs: BatteryControlInputs | None, + soc_pct: float | None, + ) -> Intent | None: + """The battery intent of this tick (``None`` = nothing to submit).""" + if inputs is None: + self.view = None + return None + if inputs.blocked is not None: + self.view = BatteryView(None, (Reason(key=BATTERY_BLOCKED), inputs.blocked)) + return None + if ( + self._pending is not None + and self._last_submit is not None + and now - self._last_submit > timedelta(seconds=self._settings.pending_timeout_s) + ): + self._pending = None + wanted, reasons = self.wanted(now, plan, inputs, soc_pct) + action: BatteryAction | ReleaseAction | None = wanted + if wanted is None: + action = ReleaseAction() if inputs.under_control else None + if action is not None: + reasons = (Reason(key=BATTERY_RELEASE), *reasons) + elif inputs.under_control and inputs.held == wanted: + action = None # the gate holds exactly this + self.view = BatteryView(wanted, reasons, last_decision=self._last_kind) + if action is None or self._pending is not None or not self._due(now, action): + return None + self._seq += 1 + intent = Intent( + id=f"battery:{now.isoformat()}:{self._seq}", + ts=now, + asset_id=BATTERY_ASSET_ID, + action=action, + reasons=reasons, + origin=Origin.CONTROLLER, + ) + self._last_submit = now + self._last_action = action + self._last_kind = None + self._pending = intent.id + self.view = BatteryView(wanted, reasons, intent_id=intent.id) + return intent + + def _due(self, now: datetime, action: BatteryAction | ReleaseAction) -> bool: + last = self._last_submit + if last is None: + return True + elapsed = now - last + if action != self._last_action: + return elapsed >= timedelta(seconds=self._settings.interval_s) + if self._last_kind in (DecisionKind.FAILED, None): + return elapsed >= timedelta(seconds=self._settings.interval_s) + return elapsed >= timedelta(seconds=self._settings.repeat_s) + + def report(self, decision: Decision) -> bool: + """The gate's decision on our intent; ``True`` if it was ours and pending.""" + if decision.intent.asset_id != BATTERY_ASSET_ID or decision.intent.id != self._pending: + return False + self._pending = None + self._last_kind = decision.kind + if self.view is not None: + self.view = BatteryView( + self.view.wanted, + self.view.reasons, + intent_id=decision.intent.id, + last_decision=decision.kind, + ) + return True + + def reset_pending(self) -> None: + """A submission was lost (transport error): the next tick may submit again.""" + self._pending = None + + +__all__ = [ + "BatteryControlInputs", + "BatteryControlSettings", + "BatteryIntents", + "BatteryView", +] diff --git a/suncore/controller/loop.py b/suncore/controller/loop.py index cd96068..a181462 100644 --- a/suncore/controller/loop.py +++ b/suncore/controller/loop.py @@ -22,8 +22,9 @@ * ``reserve_soc_pct``, ``import_limit_w`` from the site/battery config, ``goals``, ``plan`` (``Plan.default()`` until the planner's first plan, afterwards the current plan read **once** for the tick - ``ControlStack.tick``; a plan can only restrict the devices - and move the surplus between battery and consumers, ``BatteryBand`` limits are not - acted on before WP10); + and move the surplus between battery and consumers); ``battery`` (WP10: the adapter's + capabilities and ranges and what the gate holds) - the band of a fresh plan becomes a + ``BatteryAction`` intent (``controller.battery``); 3. ``result = await loop.tick(now, ControllerInputs(...))``. Inside, in this order: ``controller.step`` (surplus, allocation, back-off) -> ``loop.gate_inputs`` is the @@ -62,6 +63,12 @@ DeviationEvent, DeviceView, ) +from suncore.controller.battery import ( + BatteryControlInputs, + BatteryControlSettings, + BatteryIntents, + BatteryView, +) from suncore.controller.levels import ConfigQuantiser, Quantiser from suncore.controller.surplus import SiteSurplus, SurplusTracker from suncore.core.balance import FlowSnapshot @@ -94,6 +101,9 @@ class ControllerInputs: reserve_soc_pct: float | None = None goals: GoalsConfig = field(default_factory=GoalsConfig) plan: Plan = field(default_factory=Plan.default) + battery: BatteryControlInputs | None = None + """The battery adapter's capabilities, ranges and what the gate holds (``None`` = no battery + adapter: the battery is only observed, no battery intents; Phase 4 WP10).""" @dataclass(frozen=True, slots=True) @@ -110,6 +120,8 @@ class TickResult: """Free surplus before this tick's intents (``gate_inputs.surplus`` unclamped).""" allocated_draw_w: float attributable_deficit_w: float + battery: BatteryView | None = None + """The battery decision of the tick (``None`` without a battery adapter).""" class Controller: @@ -122,8 +134,10 @@ def __init__( settings: ControlSettings | None = None, tz: tzinfo = UTC, quantiser: Quantiser | None = None, + battery: BatteryControlSettings | None = None, ) -> None: self._settings = settings if settings is not None else ControlSettings() + self._battery = BatteryIntents(battery) self._tz = tz devices = list(devices) if quantiser is None: @@ -171,13 +185,22 @@ def step(self, now: datetime, inputs: ControllerInputs) -> TickResult: import_limit_w=inputs.import_limit_w, ) outcome = self._allocator.prepare(now, allocation) + held = None if inputs.battery is None else inputs.battery.held site = self._surplus.update( - now, inputs.flows, inputs.goals, band, controlled_draw=outcome.controlled_draw + now, + inputs.flows, + inputs.goals, + band, + controlled_draw=outcome.controlled_draw, + grid_charging=held is not None and (held.grid_charge_w or 0.0) > 0, ) # The gate judges this tick's intents against the free surplus *before* them # (each intent's own added demand is the gate's ``delta``). surplus = site.gate_estimate(self._settings.reserve_w, outcome.committed_w) outcome = self._allocator.run(now, site, allocation, outcome) + soc = None if inputs.flows is None else inputs.flows.battery_soc_pct.value + battery_intent = self._battery.step(now, inputs.plan, inputs.battery, soc) + intents = (*outcome.intents, battery_intent) if battery_intent else tuple(outcome.intents) gate_inputs = GateInputs( flows=inputs.flows, surplus=surplus, @@ -190,19 +213,26 @@ def step(self, now: datetime, inputs: ControllerInputs) -> TickResult: ts=now, gate_inputs=gate_inputs, site=site, - intents=tuple(outcome.intents), + intents=intents, views=MappingProxyType(dict(outcome.views)), deviations=tuple(outcome.deviations), total_w=outcome.total_w, free_w=outcome.free_w, allocated_draw_w=outcome.allocated_draw_w, attributable_deficit_w=outcome.attributable_deficit_w, + battery=self._battery.view, ) def report(self, decision: Decision) -> bool: """Feed the gate's decision on an intent back; ``True`` if it was ours and pending.""" + if self._battery.report(decision): + return True return self._allocator.report(decision) + @property + def battery(self) -> BatteryIntents: + return self._battery + class ControllerLoop: """One tick of I/O around :class:`Controller`: submit, report, poll.""" @@ -261,6 +291,8 @@ async def _submit_one(self, intent: Intent) -> None: # The gate records its own failures; a transport error here would otherwise # leave the device "in flight" until the machine's timeout. log.warning("controller.submit_failed", intent_id=intent.id, error=str(exc)[:200]) + if intent.id.startswith("battery:"): + self._controller.battery.reset_pending() return self._controller.report(decision) diff --git a/suncore/controller/reasons.py b/suncore/controller/reasons.py index 1ce5cba..5ad01f1 100644 --- a/suncore/controller/reasons.py +++ b/suncore/controller/reasons.py @@ -42,8 +42,23 @@ IDLE: Final = "controller.idle" HEAT_LIMIT: Final = "controller.heat_limit" HEAT_TEMPERATURE_UNKNOWN: Final = "controller.heat_temperature_unknown" +# Phase 4 WP10: the battery band of the plan as battery intents (``controller.battery``). +BATTERY_GRID_CHARGE: Final = "controller.battery.grid_charge" +BATTERY_DISCHARGE_LOCK: Final = "controller.battery.discharge_lock" +BATTERY_RELEASE: Final = "controller.battery.release" +BATTERY_GRID_CHARGE_UNSUPPORTED: Final = "controller.battery.grid_charge_unsupported" +BATTERY_DISCHARGE_LOCK_UNSUPPORTED: Final = "controller.battery.discharge_lock_unsupported" +BATTERY_NO_PLAN: Final = "controller.battery.no_plan" +BATTERY_BLOCKED: Final = "controller.battery.blocked" ALL_KEYS: Final[tuple[str, ...]] = ( + BATTERY_GRID_CHARGE, + BATTERY_DISCHARGE_LOCK, + BATTERY_RELEASE, + BATTERY_GRID_CHARGE_UNSUPPORTED, + BATTERY_DISCHARGE_LOCK_UNSUPPORTED, + BATTERY_NO_PLAN, + BATTERY_BLOCKED, HEAT_LIMIT, HEAT_TEMPERATURE_UNKNOWN, SURPLUS_ON, diff --git a/suncore/controller/surplus.py b/suncore/controller/surplus.py index d8a2092..06f08f2 100644 --- a/suncore/controller/surplus.py +++ b/suncore/controller/surplus.py @@ -235,13 +235,22 @@ def update( band: BatteryBand | None = None, *, controlled_draw: Mapping[str, float] | None = None, + grid_charging: bool = False, ) -> SiteSurplus: - """Add this tick's sample; ``controlled_draw`` = real draw per controllable device.""" + """Add this tick's sample; ``controlled_draw`` = real draw per controllable device. + + ``grid_charging``: SunCore holds a forced grid charge (WP10). The battery's charging power + is then never available to consumers - it is bought from the grid, and a device switched + on would only raise the import (ADR-0013: a device never uses import created for the + battery). + """ controlled_w = self._rebase(controlled_draw or {}) grid = flows.grid_w.value if flows is not None else None battery = flows.battery_w.value if flows is not None else None soc = flows.battery_soc_pct.value if flows is not None else None available, target = battery_share_available(goals, soc, band) + if grid_charging: + available = False quality = Quality.UNAVAILABLE if flows is not None: quality = Quality.worst((flows.grid_w.quality, flows.battery_w.quality)) diff --git a/suncore/core/control.py b/suncore/core/control.py index 2bab40f..c79bf71 100644 --- a/suncore/core/control.py +++ b/suncore/core/control.py @@ -11,7 +11,7 @@ import itertools from collections.abc import Mapping from dataclasses import dataclass, field -from datetime import datetime +from datetime import datetime, timedelta from enum import StrEnum, unique from typing import Annotated, Any, Final, Literal, Self @@ -387,6 +387,26 @@ def battery_band_at(self, at: datetime) -> BatteryBand: return interval.battery +PLAN_FRESH_INTERVALS: Final = 2 +"""ADR-0013: a plan allows battery actions while it was created at most this many of its +intervals before ``now``.""" + + +def battery_band_now(plan: Plan, at: datetime) -> tuple[BatteryBand | None, bool]: + """The battery band of the interval covering ``at`` and whether the plan is still fresh. + + Fresh = created at most :data:`PLAN_FRESH_INTERVALS` intervals (of the covering interval's + length) before ``at``. ``Plan.default()`` (no intervals, no ``created_at``) gives no band. + Shared by the controller (it asks only what a fresh plan allows) and the gate (B3/B4). + """ + interval = plan.interval_at(at) + if interval is None or plan.created_at is None: + return None, False + length = interval.end - interval.start + fresh = timedelta(0) <= at - plan.created_at <= PLAN_FRESH_INTERVALS * length + return interval.battery, fresh + + def plan_from_payload(payload: Mapping[str, Any]) -> Plan: """Load a stored plan of any known schema version (v1 rows are stamped v2). @@ -438,6 +458,7 @@ def heat_capped(device: DeviceConfig, state: DeviceState | None) -> bool: __all__ = [ # RESUME_TIME_DEFAULT is re-exported from core.devices (single constant) "DEFAULT_BAND", "DEFAULT_BATTERY_BAND", + "PLAN_FRESH_INTERVALS", "PLAN_SCHEMA_VERSION", "RESUME_TIME_DEFAULT", "TEMPERATURE_ROLE", @@ -454,6 +475,7 @@ def heat_capped(device: DeviceConfig, state: DeviceState | None) -> bool: "PlanSource", "PowerEstimate", "SolverStats", + "battery_band_now", "has_heat_limit", "heat_capped", "plan_from_payload", diff --git a/suncore/safety/battery.py b/suncore/safety/battery.py index bec2e15..59098e8 100644 --- a/suncore/safety/battery.py +++ b/suncore/safety/battery.py @@ -40,7 +40,7 @@ action_fields, round_up_to_step, ) -from suncore.core.control import BatteryBand, Plan +from suncore.core.control import PLAN_FRESH_INTERVALS, BatteryBand, Plan, battery_band_now from suncore.core.decisions import Action, Reason from suncore.core.signals import Quality from suncore.safety.actuator import Actuator @@ -48,9 +48,6 @@ POWER_TOLERANCE_W: Final = 1.0 """Read-back and bound tolerance for battery powers (the adapters write whole watts).""" SOC_TOLERANCE_PCT: Final = 0.01 -PLAN_FRESH_INTERVALS: Final = 2 -"""A plan is fresh while it was created at most this many of its intervals ago (ADR-0013).""" -DEFAULT_INTERVAL: Final = timedelta(minutes=15) REASON_BATTERY_MODEL_MISSING: Final = Reason(key="safety.battery_model_missing") REASON_BATTERY_NO_CHANGE: Final = Reason(key="safety.battery_write_no_change") @@ -216,19 +213,9 @@ class BatteryContext: def plan_band(plan: Plan, now: datetime) -> tuple[BatteryBand | None, bool]: - """The band of the interval covering ``now`` and whether the plan is fresh. - - Fresh = created at most :data:`PLAN_FRESH_INTERVALS` intervals (of the covering interval's - length) before ``now``. ``Plan.default()`` (no intervals, no ``created_at``) gives no band. - """ - interval = plan.interval_at(now) - if interval is None or plan.created_at is None: - return None, False - length = interval.end - interval.start - if length <= timedelta(0): # pragma: no cover - the plan validator forbids it - length = DEFAULT_INTERVAL - fresh = timedelta(0) <= now - plan.created_at <= PLAN_FRESH_INTERVALS * length - return interval.battery, fresh + """The band of the interval covering ``now`` and whether the plan is fresh + (``core.control.battery_band_now``).""" + return battery_band_now(plan, now) def quantise(action: BatteryAction, ranges: BatteryRanges) -> BatteryAction: diff --git a/tests/controller/test_battery_intents.py b/tests/controller/test_battery_intents.py new file mode 100644 index 0000000..b1c44d4 --- /dev/null +++ b/tests/controller/test_battery_intents.py @@ -0,0 +1,267 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The plan's battery band -> BatteryAction intents (WP10): mapping, hysteresis, rate, release.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import Any + +from hypothesis import given, settings +from hypothesis import strategies as st + +from suncore.controller import Controller, ControllerInputs +from suncore.controller.battery import ( + BatteryControlInputs, + BatteryControlSettings, + BatteryIntents, +) +from suncore.controller.surplus import SurplusTracker +from suncore.core.battery import ( + BATTERY_ASSET_ID, + BatteryAction, + BatteryCapability, + BatteryModel, + BatteryRanges, + FieldRange, +) +from suncore.core.config import GoalsConfig +from suncore.core.control import BatteryBand, Plan, PlanInterval +from suncore.core.decisions import Decision, DecisionKind, Intent, OperatingMode, ReleaseAction +from tests.safety.helpers import flows + +T0 = datetime(2026, 10, 24, 2, 0, tzinfo=UTC) +MODEL = BatteryModel(capacity_wh=10_000, max_charge_w=5000, max_discharge_w=5000) +FULL = BatteryRanges( + max_charge_w=FieldRange(0, 5000), + max_discharge_w=FieldRange(0, 5000), + min_soc_pct=FieldRange(5, 100, 5), + grid_charge_w=FieldRange(0, 5000), +) +CAPS = frozenset(BatteryCapability) - {BatteryCapability.HARDWARE_FALLBACK} +REST_CAPS = frozenset({BatteryCapability.MIN_SOC}) +REST_RANGES = BatteryRanges(min_soc_pct=FieldRange(5, 100, 5)) + + +def plan(at: datetime = T0, *, created: datetime | None = None, **band: Any) -> Plan: + start = at.replace(minute=(at.minute // 15) * 15, second=0, microsecond=0) + return Plan( + created_at=created if created is not None else start, + intervals=( + PlanInterval( + start=start, end=start + timedelta(minutes=15), battery=BatteryBand(**band) + ), + ), + ) + + +def inputs(**kw: Any) -> BatteryControlInputs: + base: dict[str, Any] = { + "capabilities": CAPS, + "ranges": FULL, + "model": MODEL, + "reserve_pct": 15.0, + } + base.update(kw) + return BatteryControlInputs(**base) + + +def decide(intent: Intent, kind: DecisionKind) -> Decision: + return Decision(intent=intent, kind=kind, ts=intent.ts, mode=OperatingMode.AUTOMATIC) + + +def keys(planner: BatteryIntents) -> list[str]: + assert planner.view is not None + return [r.key for r in planner.view.reasons] + + +def test_grid_charging_is_rounded_down_and_capped() -> None: + p = BatteryIntents() + intent = p.step(T0, plan(grid_charge_max_w=3456.7), inputs(), 30) + assert intent is not None + assert intent.asset_id == BATTERY_ASSET_ID + assert intent.action == BatteryAction(grid_charge_w=3400) + assert keys(p) == ["controller.battery.grid_charge"] + big = BatteryIntents().step(T0, plan(grid_charge_max_w=9000), inputs(), 30) + assert big is not None + assert big.action == BatteryAction(grid_charge_w=5000) + + +def test_grid_charging_without_the_capability_is_shown_not_asked() -> None: + p = BatteryIntents() + assert p.step(T0, plan(grid_charge_max_w=3000), inputs(capabilities=REST_CAPS), 30) is None + assert keys(p) == ["controller.battery.grid_charge_unsupported"] + switch = inputs(ranges=BatteryRanges(grid_charge_w=FieldRange(5000, 5000))) + assert BatteryIntents().step(T0, plan(grid_charge_max_w=3000), switch, 30) is None + full = BatteryIntents().step(T0, plan(grid_charge_max_w=5000), switch, 30) + assert full is not None + assert full.action == BatteryAction(grid_charge_w=5000) + + +def test_discharge_lock_by_discharge_cap_or_by_min_soc() -> None: + capped = BatteryIntents().step(T0, plan(discharge_lock=True), inputs(), 42) + assert capped is not None + assert capped.action == BatteryAction(max_discharge_w=0) + floor = BatteryIntents().step( + T0, plan(discharge_lock=True), inputs(capabilities=REST_CAPS, ranges=REST_RANGES), 42 + ) + assert floor is not None + assert floor.action == BatteryAction(min_soc_pct=45) # rounded up to the step + low = BatteryIntents().step( + T0, plan(discharge_lock=True), inputs(capabilities=REST_CAPS, ranges=REST_RANGES), 8 + ) + assert low is not None + assert low.action == BatteryAction(min_soc_pct=15) # never below the reserve + p = BatteryIntents() + assert p.step(T0, plan(discharge_lock=True), inputs(capabilities=frozenset()), 42) is None + assert keys(p) == ["controller.battery.discharge_lock_unsupported"] + + +def test_a_min_soc_lock_moves_only_a_full_step_after_the_soc() -> None: + p = BatteryIntents(BatteryControlSettings(interval_s=0)) + rest = {"capabilities": REST_CAPS, "ranges": REST_RANGES} + held = BatteryAction(min_soc_pct=45) + for soc in (42.0, 44.0, 45.0, 47.0, 49.9): + assert p.wanted(T0, plan(discharge_lock=True), inputs(held=held, **rest), soc)[0] == held + moved = p.wanted(T0, plan(discharge_lock=True), inputs(held=held, **rest), 50.2)[0] + assert moved == BatteryAction(min_soc_pct=55) + + +def test_nothing_planned_releases_only_what_the_gate_holds() -> None: + p = BatteryIntents() + assert p.step(T0, plan(), inputs(), 40) is None + released = p.step( + T0, plan(), inputs(under_control=True, held=BatteryAction(max_discharge_w=0)), 40 + ) + assert released is not None + assert isinstance(released.action, ReleaseAction) + assert keys(p)[0] == "controller.battery.release" + + +def test_a_stale_or_default_plan_asks_for_nothing() -> None: + stale = plan(discharge_lock=True, created=T0 - timedelta(hours=1)) + p = BatteryIntents() + assert p.step(T0, stale, inputs(), 40) is None + assert keys(p) == ["controller.battery.no_plan"] + assert BatteryIntents().step(T0, Plan.default(), inputs(), 40) is None + + +def test_no_intent_while_blocked_or_while_the_gate_holds_it() -> None: + from suncore.core.decisions import Reason # noqa: PLC0415 + + p = BatteryIntents() + blocked = inputs(blocked=Reason(key="safety.emergency_stop")) + assert p.step(T0, plan(discharge_lock=True), blocked, 40) is None + held = inputs(under_control=True, held=BatteryAction(max_discharge_w=0)) + assert BatteryIntents().step(T0, plan(discharge_lock=True), held, 40) is None + + +def test_hysteresis_keeps_the_held_grid_power() -> None: + p = BatteryIntents() + held = inputs(under_control=True, held=BatteryAction(grid_charge_w=3000)) + for planned in (2800, 3100, 3250, 2900): + assert p.wanted(T0, plan(grid_charge_max_w=planned), held, 30)[0] == BatteryAction( + grid_charge_w=3000 + ) + assert p.wanted(T0, plan(grid_charge_max_w=3400), held, 30)[0] == BatteryAction( + grid_charge_w=3400 + ) + + +def test_one_intent_per_interval_and_repeats_only_after_repeat_s() -> None: + p = BatteryIntents(BatteryControlSettings(interval_s=60, repeat_s=900)) + now = T0 + first = p.step(now, plan(now, discharge_lock=True), inputs(), 40) + assert first is not None + p.report(decide(first, DecisionKind.SHADOW)) + count = 1 + for _ in range(170): # 14 min of 5 s ticks, same wish in shadow + now += timedelta(seconds=5) + if p.step(now, plan(now, discharge_lock=True), inputs(), 40) is not None: + count += 1 + assert count == 1 + now += timedelta(seconds=70) + again = p.step(now, plan(now, discharge_lock=True), inputs(), 40) + assert again is not None # after repeat_s the shadow "would have" is shown again + + +def test_a_pending_intent_blocks_new_ones_until_reported_or_timed_out() -> None: + p = BatteryIntents(BatteryControlSettings(interval_s=0, pending_timeout_s=300)) + first = p.step(T0, plan(discharge_lock=True), inputs(), 40) + assert first is not None + later = T0 + timedelta(seconds=30) + assert p.step(later, plan(later, grid_charge_max_w=2000), inputs(), 40) is None + much_later = T0 + timedelta(seconds=301) + assert p.step(much_later, plan(much_later, grid_charge_max_w=2000), inputs(), 40) is not None + + +@settings(max_examples=60, deadline=None) +@given( + st.lists( + st.tuples( + st.sampled_from(["lock", "grid", "none"]), + st.floats(500, 6000), + st.floats(5, 100), + st.sampled_from(list(DecisionKind)), + ), + min_size=20, + max_size=400, + ) +) +def test_flapping_bands_never_oscillate_the_battery( + ticks: list[tuple[str, float, float, DecisionKind]], +) -> None: + """Whatever the plan and the gate do every 5 s: at most one battery intent per interval, + every floor >= reserve, every grid power within the band and the battery's limit.""" + p = BatteryIntents(BatteryControlSettings(interval_s=60)) + now = T0 + last: datetime | None = None + held: BatteryAction | None = None + for kind, power, soc, verdict in ticks: + now += timedelta(seconds=5) + band = {"lock": {"discharge_lock": True}, "grid": {"grid_charge_max_w": power}} + current = plan(now, **band.get(kind, {})) + intent = p.step(now, current, inputs(held=held, under_control=held is not None), soc) + if intent is None: + continue + if last is not None: + assert now - last >= timedelta(seconds=60) + last = now + action = intent.action + if isinstance(action, BatteryAction): + if action.min_soc_pct is not None: + assert action.min_soc_pct >= 15 + if action.grid_charge_w is not None: + assert action.grid_charge_w <= min(power, 5000) + 1 + p.report(decide(intent, verdict)) + if verdict is DecisionKind.ACCEPTED: + held = action if isinstance(action, BatteryAction) else None + + +def test_controller_submits_the_battery_intent_with_the_devices() -> None: + controller = Controller([]) + result = controller.step( + T0, + ControllerInputs( + flows=flows(grid_w=500, battery_w=0, soc_pct=40), + plan=plan(discharge_lock=True), + battery=inputs(), + ), + ) + assert [i.asset_id for i in result.intents] == [BATTERY_ASSET_ID] + assert result.battery is not None + assert result.battery.wanted == BatteryAction(max_discharge_w=0) + assert controller.report(decide(result.intents[0], DecisionKind.ACCEPTED)) + no_battery = Controller([]).step(T0, ControllerInputs(plan=plan(discharge_lock=True))) + assert no_battery.intents == () + assert no_battery.battery is None + + +def test_grid_charging_power_is_never_surplus_for_consumers() -> None: + goals = GoalsConfig(climate_before_export=True) + tracker = SurplusTracker(60) + snapshot = flows(grid_w=3000, battery_w=3000, soc_pct=40) + charging = tracker.update(T0, snapshot, goals, grid_charging=True) + assert not charging.charging_available + assert charging.latest_site_w == -3000 # the import, not the battery's charge + plain = SurplusTracker(60).update(T0, snapshot, goals) + assert plain.charging_available From a64f1a5ef9dabe7fc80fa5852451847b32a36fa5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 21:27:02 +0000 Subject: [PATCH 06/16] feat(app,api): battery in the control stack, control state and PUT /api/v1/operation/battery (WP10) - ControlStack builds the battery adapter through safety.wiring (observe-only when it cannot be built or a device uses the id "battery"), hands the gate its BatteryGateConfig (identity, model, effective reserve, effective grid-charge policy, fallback_measured, the tick's plan, the live price), runs the battery watch every tick and gives the controller the adapter's capabilities, ranges and what the gate holds - runtime: battery section loaded and applied (rebuild, resubscribe, identity rule), devices' reserve guard = effective_reserve_pct with a model, set_battery_mode with the identity token - control state: battery (identity, capabilities, modes incl. the assisted cap, limits, held, baseline, wanted, reasons, pause, last decision); PUT /api/v1/operation/battery {mode, identity} (404 observe-only, 409 stale identity); OpenAPI and frontend types regenerated Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- frontend/src/lib/api/openapi.json | 220 ++++++++++++++++++++++++++ frontend/src/lib/api/schema.d.ts | 113 +++++++++++++ frontend/src/lib/i18n/locales/de.json | 1 + frontend/src/lib/i18n/locales/en.json | 1 + suncore/api/app.py | 25 +++ suncore/api/services.py | 6 + suncore/app/control.py | 158 +++++++++++++++++- suncore/app/openapi_stub.py | 7 + suncore/app/runtime.py | 102 ++++++++++-- suncore/core/controlstate.py | 60 +++++++ suncore/devices/battery/base.py | 6 + suncore/safety/wiring.py | 7 + tests/api/conftest.py | 12 ++ tests/api/test_control_api.py | 25 +++ tests/app/test_battery_runtime.py | 73 +++++++++ 15 files changed, 804 insertions(+), 12 deletions(-) create mode 100644 tests/app/test_battery_runtime.py diff --git a/frontend/src/lib/api/openapi.json b/frontend/src/lib/api/openapi.json index 66a63a2..e977121 100644 --- a/frontend/src/lib/api/openapi.json +++ b/frontend/src/lib/api/openapi.json @@ -541,6 +541,130 @@ "title": "BatteryConfig", "type": "object" }, + "BatteryControlState": { + "additionalProperties": false, + "description": "The battery as a controlled asset (Phase 4 WP10, ADR-0013).", + "properties": { + "adapter_template_id": { + "title": "Adapter Template Id", + "type": "string" + }, + "baseline": { + "anyOf": [ + { + "$ref": "#/components/schemas/BatteryAction" + }, + { + "type": "null" + } + ] + }, + "battery_mode": { + "$ref": "#/components/schemas/OperatingMode" + }, + "capabilities": { + "items": { + "type": "string" + }, + "title": "Capabilities", + "type": "array" + }, + "effective_mode": { + "$ref": "#/components/schemas/OperatingMode" + }, + "global_mode": { + "$ref": "#/components/schemas/OperatingMode" + }, + "held": { + "anyOf": [ + { + "$ref": "#/components/schemas/BatteryAction" + }, + { + "type": "null" + } + ] + }, + "identity": { + "title": "Identity", + "type": "string" + }, + "last_decision": { + "anyOf": [ + { + "$ref": "#/components/schemas/Decision" + }, + { + "type": "null" + } + ] + }, + "limits": { + "anyOf": [ + { + "$ref": "#/components/schemas/BatteryAction" + }, + { + "type": "null" + } + ] + }, + "mode_capped": { + "title": "Mode Capped", + "type": "boolean" + }, + "paused": { + "anyOf": [ + { + "$ref": "#/components/schemas/Reason" + }, + { + "type": "null" + } + ] + }, + "reasons": { + "items": { + "$ref": "#/components/schemas/Reason" + }, + "title": "Reasons", + "type": "array" + }, + "under_control": { + "title": "Under Control", + "type": "boolean" + }, + "wanted": { + "anyOf": [ + { + "$ref": "#/components/schemas/BatteryAction" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "identity", + "adapter_template_id", + "capabilities", + "global_mode", + "battery_mode", + "effective_mode", + "mode_capped", + "limits", + "held", + "baseline", + "under_control", + "wanted", + "reasons", + "paused", + "last_decision" + ], + "title": "BatteryControlState", + "type": "object" + }, "BatteryModeMeaning": { "description": "What selecting a battery mode option does.", "enum": [ @@ -573,6 +697,33 @@ "title": "BatteryModeOption", "type": "object" }, + "BatteryModeRequest": { + "additionalProperties": false, + "description": "``PUT /api/v1/operation/battery``: the battery's operating mode (ADR-0013).\n\nLike a device: raising the mode above shadow needs ``identity``, the token from\n``GET /api/v1/control/state`` (``battery.identity``); a re-mapped battery answers 409.", + "properties": { + "identity": { + "anyOf": [ + { + "maxLength": 64, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Identity" + }, + "mode": { + "$ref": "#/components/schemas/OperatingMode" + } + }, + "required": [ + "mode" + ], + "title": "BatteryModeRequest", + "type": "object" + }, "BatteryModel": { "additionalProperties": false, "description": "What the planner knows about the battery.\n\nThe planning floor is ``reserve_pct + bms_drift_margin_pct``: the reserve is the user's\nbackup energy, the drift margin keeps SunCore off the BMS's own cut-off when the SoC\nreading sags (the maintainer's BMS drops from 10 % to 6-7 %). SunCore never plans to\ndischarge below it; ``max_soc_pct`` caps charging (battery care).", @@ -1513,6 +1664,16 @@ "title": "Active", "type": "boolean" }, + "battery": { + "anyOf": [ + { + "$ref": "#/components/schemas/BatteryControlState" + }, + { + "type": "null" + } + ] + }, "devices": { "items": { "$ref": "#/components/schemas/DeviceControlState" @@ -9667,6 +9828,65 @@ "summary": "Info" } }, + "/api/v1/operation/battery": { + "put": { + "description": "Set the battery's mode (ADR-0013). Anything above shadow needs the battery's\n``identity`` token from the control state; shadow never does. An adapter whose hardware\nfallback is not measured runs at most assisted whatever is stored.", + "operationId": "set_battery_mode_api_v1_operation_battery_put", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatteryModeRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OperationConfig" + } + } + }, + "description": "Successful Response" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOut" + } + } + }, + "description": "No battery adapter (observe-only)" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorOut" + } + } + }, + "description": "The battery changed since its identity was read" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ValidationErrorOut" + } + } + }, + "description": "Validation error" + } + }, + "summary": "Set Battery Mode" + } + }, "/api/v1/operation/devices/{device_id}": { "put": { "description": "Set one device's mode. Anything above shadow needs the device's ``identity`` token\nfrom the control state; shadow never does.", diff --git a/frontend/src/lib/api/schema.d.ts b/frontend/src/lib/api/schema.d.ts index 812cd91..323d8f2 100644 --- a/frontend/src/lib/api/schema.d.ts +++ b/frontend/src/lib/api/schema.d.ts @@ -484,6 +484,28 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/operation/battery": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Set Battery Mode + * @description Set the battery's mode (ADR-0013). Anything above shadow needs the battery's + * ``identity`` token from the control state; shadow never does. An adapter whose hardware + * fallback is not measured runs at most assisted whatever is stored. + */ + put: operations["set_battery_mode_api_v1_operation_battery_put"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/operation/devices/{device_id}": { parameters: { query?: never; @@ -1011,6 +1033,33 @@ export interface components { power: components["schemas"]["EntityRef"]; soc: components["schemas"]["EntityRef"]; }; + /** + * BatteryControlState + * @description The battery as a controlled asset (Phase 4 WP10, ADR-0013). + */ + BatteryControlState: { + /** Adapter Template Id */ + adapter_template_id: string; + baseline: components["schemas"]["BatteryAction"] | null; + battery_mode: components["schemas"]["OperatingMode"]; + /** Capabilities */ + capabilities: string[]; + effective_mode: components["schemas"]["OperatingMode"]; + global_mode: components["schemas"]["OperatingMode"]; + held: components["schemas"]["BatteryAction"] | null; + /** Identity */ + identity: string; + last_decision: components["schemas"]["Decision"] | null; + limits: components["schemas"]["BatteryAction"] | null; + /** Mode Capped */ + mode_capped: boolean; + paused: components["schemas"]["Reason"] | null; + /** Reasons */ + reasons: components["schemas"]["Reason"][]; + /** Under Control */ + under_control: boolean; + wanted: components["schemas"]["BatteryAction"] | null; + }; /** * BatteryModeMeaning * @description What selecting a battery mode option does. @@ -1023,6 +1072,18 @@ export interface components { /** Value */ value: string; }; + /** + * BatteryModeRequest + * @description ``PUT /api/v1/operation/battery``: the battery's operating mode (ADR-0013). + * + * Like a device: raising the mode above shadow needs ``identity``, the token from + * ``GET /api/v1/control/state`` (``battery.identity``); a re-mapped battery answers 409. + */ + BatteryModeRequest: { + /** Identity */ + identity?: string | null; + mode: components["schemas"]["OperatingMode"]; + }; /** * BatteryModel * @description What the planner knows about the battery. @@ -1433,6 +1494,7 @@ export interface components { ControlState: { /** Active */ active: boolean; + battery?: components["schemas"]["BatteryControlState"] | null; /** Devices */ devices: components["schemas"]["DeviceControlState"][]; /** Emergency Stop */ @@ -5117,6 +5179,57 @@ export interface operations { }; }; }; + set_battery_mode_api_v1_operation_battery_put: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["BatteryModeRequest"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["OperationConfig"]; + }; + }; + /** @description No battery adapter (observe-only) */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorOut"]; + }; + }; + /** @description The battery changed since its identity was read */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorOut"]; + }; + }; + /** @description Validation error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ValidationErrorOut"]; + }; + }; + }; + }; set_device_mode_api_v1_operation_devices__device_id__put: { parameters: { query?: never; diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index b93a0a9..fb83eba 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -23,6 +23,7 @@ "activity.importing": "Bezug", "activity.producing": "Erzeugt", "api.error.body_too_large": "Die Anfrage ist zu groß.", + "api.error.battery_not_controllable": "Kein Akku-Adapter konfiguriert: der Akku wird nur beobachtet.", "api.error.device_identity_changed": "Das Gerät hat sich inzwischen geändert. Lade neu und prüfe es, bevor du seinen Modus änderst.", "api.error.mode_raise_rejected": "Ein gespeichertes Dokument kann keinen Betriebsmodus anheben. Ändere den Modus eines Geräts einzeln.", "api.error.unknown_device": "Dieses Gerät existiert nicht.", diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index 9ef9f14..e17840d 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -23,6 +23,7 @@ "activity.importing": "Importing", "activity.producing": "Producing", "api.error.body_too_large": "The request is too large.", + "api.error.battery_not_controllable": "No battery adapter is configured: the battery is only observed.", "api.error.device_identity_changed": "This device changed in the meantime. Reload and check it before changing its mode.", "api.error.mode_raise_rejected": "A stored document cannot raise an operating mode. Change the mode of a device on its own.", "api.error.unknown_device": "This device does not exist.", diff --git a/suncore/api/app.py b/suncore/api/app.py index 7a7055c..a50f924 100644 --- a/suncore/api/app.py +++ b/suncore/api/app.py @@ -77,6 +77,8 @@ missing_action_params, ) from suncore.core.controlstate import ( + BatteryModeRequest, + BatteryNotControllableError, ControlState, DeviceControlState, DeviceIdentityChangedError, @@ -136,6 +138,7 @@ ERR_MODE_RAISE_REJECTED: Final = "api.error.mode_raise_rejected" ERR_TARIFF_NOT_CONFIGURED: Final = "api.error.tariff_not_configured" ERR_PLANNING_UNAVAILABLE: Final = "api.error.planning_unavailable" +ERR_BATTERY_NOT_CONTROLLABLE: Final = "api.error.battery_not_controllable" BODY_MAX_BYTES: Final = 64 * 1024 """Limit of the small JSON bodies of the wizard endpoints (check, preview).""" SECTION_MAX_BYTES: Final = 256 * 1024 @@ -500,6 +503,28 @@ async def set_device_mode(device_id: str, body: DeviceModeRequest) -> OperationC except DeviceIdentityChangedError as exc: raise HTTPException(status_code=409, detail=ERR_DEVICE_IDENTITY_CHANGED) from exc + @app.put( + f"{API_PREFIX}/operation/battery", + response_model=OperationConfig, + responses={ + 404: {"model": ErrorOut, "description": "No battery adapter (observe-only)"}, + 409: { + "model": ErrorOut, + "description": "The battery changed since its identity was read", + }, + }, + ) + async def set_battery_mode(body: BatteryModeRequest) -> OperationConfig: + """Set the battery's mode (ADR-0013). Anything above shadow needs the battery's + ``identity`` token from the control state; shadow never does. An adapter whose hardware + fallback is not measured runs at most assisted whatever is stored.""" + try: + return await services.set_battery_mode(body.mode, body.identity) + except BatteryNotControllableError as exc: + raise HTTPException(status_code=404, detail=ERR_BATTERY_NOT_CONTROLLABLE) from exc + except DeviceIdentityChangedError as exc: + raise HTTPException(status_code=409, detail=ERR_DEVICE_IDENTITY_CHANGED) from exc + def _register_sections(app: FastAPI, services: Services) -> None: """``GET``/``PUT /api/v1/config/
`` for every section, typed by its model. diff --git a/suncore/api/services.py b/suncore/api/services.py index 0400d80..7a7b792 100644 --- a/suncore/api/services.py +++ b/suncore/api/services.py @@ -238,6 +238,12 @@ async def set_device_mode( :class:`DeviceIdentityChangedError`.""" ... + async def set_battery_mode(self, mode: OperatingMode, identity: str | None) -> OperationConfig: + """Set the battery's mode (ADR-0013). Raising it above shadow needs the battery's current + identity token (``BatteryControlState.identity``): raises + :class:`BatteryNotControllableError` (no adapter), :class:`DeviceIdentityChangedError`.""" + ... + def add_control_listener(self, listener: Callable[[], None]) -> Callable[[], None]: """Call ``listener`` whenever the control state may have changed (tick, decision, mode).""" ... diff --git a/suncore/app/control.py b/suncore/app/control.py index c350a98..6345c61 100644 --- a/suncore/app/control.py +++ b/suncore/app/control.py @@ -36,6 +36,7 @@ import contextlib from collections import deque from collections.abc import Awaitable, Callable, Collection, Mapping, Sequence +from dataclasses import dataclass, field from datetime import datetime, tzinfo from typing import Final, cast @@ -48,8 +49,16 @@ ControllerLoop, DeviationEvent, ) +from suncore.controller.battery import BatteryControlInputs from suncore.controller.loop import TickResult from suncore.core.balance import FlowSnapshot, compute_flows +from suncore.core.battery import ( + BATTERY_ASSET_ID, + BatteryAction, + BatterySettings, + GridChargePolicy, +) +from suncore.core.battery_adapter import BatteryAdapterSpec from suncore.core.config import GoalsConfig from suncore.core.control import ( TEMPERATURE_ROLE, @@ -59,7 +68,12 @@ PowerEstimate, has_heat_limit, ) -from suncore.core.controlstate import ControlState, DeviceControlState, SiteControlState +from suncore.core.controlstate import ( + BatteryControlState, + ControlState, + DeviceControlState, + SiteControlState, +) from suncore.core.decisions import Action, Decision, Reason from suncore.core.devices import DeviceConfig, control_roles from suncore.core.identity import identity_token @@ -73,6 +87,7 @@ ) from suncore.core.signals import Quality, Sample from suncore.core.site import SiteConfig +from suncore.devices.battery import BatteryDriver, create_battery_driver from suncore.devices.drivers import ClimateDriver, NumberDriver, create_driver from suncore.devices.power import create_power_model, restore_power_model from suncore.devices.power.common import PowerEstimator @@ -84,6 +99,7 @@ HAConnection, Unsubscribe, ) +from suncore.safety.battery import BatteryGateConfig, BatteryWatch from suncore.safety.gate import ( REASON_EMERGENCY_STOP, REASON_ORPHANED, @@ -95,7 +111,7 @@ from suncore.safety.modes import ModeProvider from suncore.safety.runtime import MemoryRuntimeStore, RuntimeStore from suncore.safety.watchdog import Watchdog -from suncore.safety.wiring import StatefulActuator, WriterFn, build_actuators +from suncore.safety.wiring import StatefulActuator, WriterFn, build_actuator, build_actuators from suncore.storage import PowerModelStateStore log = structlog.get_logger(__name__) @@ -135,6 +151,31 @@ def probe_temperature_c(cache: EntityCache, device: DeviceConfig) -> float | Non return sample.value +PriceProvider = Callable[[datetime], float | None] +"""``now -> live import price`` (currency/kWh) for the battery's grid-charge policy.""" + + +def _no_price(_: datetime) -> float | None: + return None + + +@dataclass(frozen=True, slots=True) +class BatteryWiring: + """The battery as a controlled asset (Phase 4 WP10): what the runtime hands the stack. + + ``identity`` is ``core.identity.battery_identity_token``, ``reserve_pct`` + ``core.battery.effective_reserve_pct`` and ``policy`` ``core.config. + effective_grid_charge_policy`` - all computed by the runtime from the configuration. + """ + + settings: BatterySettings + spec: BatteryAdapterSpec + identity: str + reserve_pct: float | None + policy: GridChargePolicy = field(default_factory=GridChargePolicy) + import_price: PriceProvider = _no_price + + def grid_heartbeats(site: SiteConfig | None) -> tuple[tuple[str, ...], ...]: """The grid meter as one heartbeat group: the signals that must keep reporting. @@ -220,6 +261,7 @@ def __init__( # noqa: PLR0915 - the composition root of the control layer defer_recover: bool = False, plan_provider: PlanProvider | None = None, on_measurements: MeasurementSink | None = None, + battery: BatteryWiring | None = None, ) -> None: self._connection = connection self._plan_provider = plan_provider @@ -233,6 +275,7 @@ def __init__( # noqa: PLR0915 - the composition root of the control layer self._sleep = sleep self._settings = settings self._goals = goals if goals is not None else GoalsConfig(climate_before_export=True) + self._modes = modes self._import_limit_w = import_limit_w self._reserve_soc_pct = reserve_soc_pct self._cadences = dict(cadences or {}) @@ -263,6 +306,24 @@ def __init__( # noqa: PLR0915 - the composition root of the control layer self.drivers: dict[str, DeviceActuator] = build_actuators( connection, devices, self._make_driver ) + self.battery_wiring = battery + self.battery_driver: BatteryDriver | None = self._make_battery(connection, battery) + self.battery_limits: BatteryAction | None = None + """What the battery adapter's entities showed at the latest tick.""" + actuators: dict[str, StatefulActuator | BatteryDriver] = dict(self.drivers) + gate_battery: BatteryGateConfig | None = None + if battery is not None and self.battery_driver is not None: + actuators[BATTERY_ASSET_ID] = self.battery_driver + gate_battery = BatteryGateConfig( + identity=battery.identity, + model=battery.settings.model, + reserve_pct=battery.reserve_pct, + policy=battery.policy, + fallback_verified=battery.settings.fallback_measured, + plan=self.current_plan, + import_price=battery.import_price, + watch=BatteryWatch(), + ) self.models: dict[str, PowerEstimator] = { d.id: create_power_model(d, power_cadence_s=self._power_cadence(d)) for d in devices } @@ -281,7 +342,7 @@ def __init__( # noqa: PLR0915 - the composition root of the control layer self.gate = SafetyGate( clock=clock, sink=self._sink, - actuators=self.drivers, + actuators=actuators, modes=modes, devices=self._devices.get, states=self._device_state, @@ -292,6 +353,7 @@ def __init__( # noqa: PLR0915 - the composition root of the control layer tz=tz, sleep=sleep, predecessor=predecessor, + battery=gate_battery, ) self.deviations: deque[DeviationEvent] = deque(maxlen=DEVIATION_HISTORY) self.loop = ControllerLoop( @@ -328,6 +390,26 @@ def __init__( # noqa: PLR0915 - the composition root of the control layer def _make_driver(self, device: DeviceConfig, write: WriterFn) -> DeviceActuator: return cast("DeviceActuator", create_driver(device, write=write, states=self._lookup)) + def _make_battery( + self, connection: HAConnection, battery: BatteryWiring | None + ) -> BatteryDriver | None: + """The battery adapter, or ``None`` (observe-only) when it cannot be built.""" + if battery is None: + return None + if BATTERY_ASSET_ID in self._devices: + log.error("control.battery_id_conflict", device_id=BATTERY_ASSET_ID) + return None + spec, settings = battery.spec, battery.settings + + def make(write: WriterFn) -> BatteryDriver: + return create_battery_driver(spec, settings, write=write, states=self._lookup) + + try: + return build_actuator(connection, make) + except ValueError as exc: + log.warning("control.battery_adapter_unusable", error=str(exc)[:200]) + return None + def _lookup(self, entity_id: str) -> EntityState | None: entry = self.cache.get(entity_id) return None if entry is None else entry.state @@ -366,6 +448,10 @@ def entity_ids(self) -> list[str]: ids.update(dict.fromkeys(r.entity_id for r in self._site.entity_refs())) for device in self._devices.values(): ids.update(dict.fromkeys(r.entity_id for r in device.entity_refs())) + if self.battery_wiring is not None: + ids.update( + dict.fromkeys(r.entity_id for r in self.battery_wiring.settings.entity_refs()) + ) return list(ids) @property @@ -704,6 +790,7 @@ async def tick(self) -> TickResult | None: if self._site is not None: await self.gate.check_site(self._site, samples) flows = compute_flows(self._site, samples) + await self.gate.check_battery(flows) states: dict[str, DeviceState] = {} estimates: dict[str, PowerEstimate] = {} for device_id, device in self._devices.items(): @@ -728,6 +815,7 @@ async def tick(self) -> TickResult | None: reserve_soc_pct=self._reserve_soc_pct, goals=self._goals, plan=self.current_plan(now), + battery=await self._battery_inputs(now), ) self.estimates = estimates self.states = states @@ -737,6 +825,40 @@ async def tick(self) -> TickResult | None: self._notify() return self.last + def _battery_blocked(self, now: datetime) -> Reason | None: + runtime = self.gate.runtime_of(BATTERY_ASSET_ID) + if self.gate.emergency_stopped: + return REASON_EMERGENCY_STOP + if (pause := self.watchdog.pause_reason(BATTERY_ASSET_ID, now)) is not None: + return pause + if self.gate.is_orphaned(BATTERY_ASSET_ID): + return REASON_ORPHANED + if runtime is not None and runtime.release_pending: + return REASON_RELEASE_PENDING + if runtime is not None and runtime.is_held(now): + return REASON_OVERRIDE_HELD + return None + + async def _battery_inputs(self, now: datetime) -> BatteryControlInputs | None: + """The battery adapter as the controller sees it this tick (reads the cache only).""" + driver, wiring = self.battery_driver, self.battery_wiring + if driver is None or wiring is None or wiring.settings.model is None: + return None + observed = await driver.read_back() + self.battery_limits = observed if isinstance(observed, BatteryAction) else None + runtime = self.gate.runtime_of(BATTERY_ASSET_ID) + under = runtime is not None and runtime.under_control + held = runtime.last_written if under and runtime is not None else None + return BatteryControlInputs( + capabilities=driver.capabilities, + ranges=driver.ranges(), + model=wiring.settings.model, + reserve_pct=wiring.reserve_pct if wiring.reserve_pct is not None else 100.0, + held=held if isinstance(held, BatteryAction) else None, + under_control=under, + blocked=self._battery_blocked(now), + ) + def _record_measurements( self, now: datetime, @@ -801,6 +923,35 @@ def control_state(self) -> ControlState: site=site, devices=devices, proposals=list(self.gate.proposals()), + battery=self._battery_control_state(now), + ) + + def _battery_control_state(self, now: datetime) -> BatteryControlState | None: + driver, wiring = self.battery_driver, self.battery_wiring + if driver is None or wiring is None: + return None + modes = self.gate.modes_of(BATTERY_ASSET_ID) + runtime = self.gate.runtime_of(BATTERY_ASSET_ID) + under = runtime is not None and runtime.under_control + view = None if self.last is None else self.last.battery + held = runtime.last_written if under and runtime is not None else None + baseline = runtime.baseline if under and runtime is not None else None + return BatteryControlState( + identity=wiring.identity, + adapter_template_id=wiring.spec.template_id, + capabilities=sorted(c.value for c in driver.capabilities), + global_mode=modes.global_mode, + battery_mode=self._modes.battery_mode(), + effective_mode=modes.effective, + mode_capped=self.gate.battery_mode_capped, + limits=self.battery_limits, + held=held if isinstance(held, BatteryAction) else None, + baseline=baseline if isinstance(baseline, BatteryAction) else None, + under_control=under, + wanted=None if view is None else view.wanted, + reasons=[] if view is None else list(view.reasons), + paused=self._battery_blocked(now), + last_decision=self.last_decisions.get(BATTERY_ASSET_ID), ) def _device_control_state(self, device: DeviceConfig, now: datetime) -> DeviceControlState: @@ -843,6 +994,7 @@ def _device_control_state(self, device: DeviceConfig, now: datetime) -> DeviceCo __all__ = [ "DEFAULT_POWER_SAVE_INTERVAL_S", + "BatteryWiring", "ControlStack", "DeviceActuator", "probe_temperature_c", diff --git a/suncore/app/openapi_stub.py b/suncore/app/openapi_stub.py index fa1c828..ca795d1 100644 --- a/suncore/app/openapi_stub.py +++ b/suncore/app/openapi_stub.py @@ -150,6 +150,13 @@ async def set_device_mode( ) -> OperationConfig: return OperationConfig() + async def set_battery_mode( + self, + mode: OperatingMode, # noqa: ARG002 + identity: str | None, # noqa: ARG002 + ) -> OperationConfig: + return OperationConfig() + def add_control_listener(self, listener: Callable[[], None]) -> Callable[[], None]: # noqa: ARG002 return lambda: None diff --git a/suncore/app/runtime.py b/suncore/app/runtime.py index 18d7185..cdf8a66 100644 --- a/suncore/app/runtime.py +++ b/suncore/app/runtime.py @@ -33,7 +33,7 @@ build_tariff_service, ) from suncore.app.cadence import device_cadences, merge_cadences -from suncore.app.control import ControlStack +from suncore.app.control import BatteryWiring, ControlStack from suncore.app.history import rebuild_history from suncore.app.modes import ConfigModes from suncore.app.planning import ( @@ -45,7 +45,7 @@ from suncore.app.recorder import FLUSH_INTERVAL_S, MeasurementRecorder from suncore.app.settings import SUPERVISOR_INGRESS_PEER, Settings from suncore.core.balance import FlowSnapshot, compute_flows -from suncore.core.battery import BatterySettings +from suncore.core.battery import BatterySettings, effective_reserve_pct from suncore.core.config import ( DevicesConfig, ForecastConfig, @@ -53,9 +53,11 @@ OperationConfig, RegionConfig, TariffConfig, + effective_grid_charge_policy, ) from suncore.core.control import ControlSettings, Plan from suncore.core.controlstate import ( + BatteryNotControllableError, ControlState, DeviceControlState, DeviceIdentityChangedError, @@ -68,7 +70,7 @@ from suncore.core.decisions import Decision, DecisionKind, OperatingMode, Origin, Reason from suncore.core.detection import DetectedEntity, EnergySuggestions from suncore.core.devices import DeviceConfig -from suncore.core.identity import identity_token +from suncore.core.identity import battery_identity_token, identity_token from suncore.core.series import QuantileSeries from suncore.core.signals import Quality, Sample from suncore.core.site import SiteConfig @@ -129,7 +131,7 @@ from suncore.storage.timeseries import META_HISTORY_REBUILT from suncore.tariff import ExportConfigError, TariffService from suncore.tariff.report import PriceReport -from suncore.templates import TariffTemplate, TemplateCatalog +from suncore.templates import BatteryTemplate, TariffTemplate, TemplateCatalog PLANNING_SECTIONS = frozenset( {"site", "region", "tariff", "forecast", "battery", "goals", "devices"} @@ -191,6 +193,8 @@ class Runtime: risk_model: ErrorModel = field(default_factory=ErrorModel) """The learnt net energy errors (WP7), loaded at start and after the nightly job.""" tariff_config: TariffConfig | None = None + battery_config: BatterySettings | None = None + """The ``battery`` section (adapter, model, policy); ``None`` = never stored.""" tariff: TariffService | None = None """Keeps the prices fresh (``None``: no tariff, no region or an unusable template).""" timeseries_db: Database | None = None @@ -316,6 +320,9 @@ async def _load_live_sections(self) -> None: tariff = await self.config.get("tariff") assert tariff is None or isinstance(tariff, TariffConfig) self.tariff_config = tariff + battery = await self.config.get("battery") + assert battery is None or isinstance(battery, BatterySettings) + self.battery_config = battery await self._load_modes() async def _load_modes(self) -> None: @@ -497,7 +504,6 @@ def _new_stack( ) -> ControlStack: devices = list(self.devices.devices) if self.devices is not None else [] site = self.site - battery = None if site is None else site.battery settings = self.control_settings or ControlSettings( tick_s=float(self.settings.controller_interval_s) ) @@ -513,7 +519,7 @@ def _new_stack( tz=self._timezone(), goals=self.goals, import_limit_w=None if site is None else site.grid.import_limit_w, - reserve_soc_pct=None if battery is None else battery.min_soc_pct, + reserve_soc_pct=self._reserve_soc_pct(), cadences=merge_cadences(device_cadences(devices), self.extra_cadences), sink=self._record_decision, on_measurements=self.recorder.record, @@ -524,10 +530,60 @@ def _new_stack( predecessor=predecessor, defer_recover=not self._time_zone_settled(), plan_provider=None if self.planning is None else self.planning.active_plan, + battery=self._battery_wiring(), ) stack.add_listener(self._notify_control) return stack + def _battery_policy_changed(self) -> bool: + """A goals change moved the battery's effective grid-charge policy (the gate's copy).""" + stack, wiring = self.stack, self._battery_wiring() + held = None if stack is None else stack.battery_wiring + if wiring is None or held is None: + return (wiring is None) != (held is None) + return wiring.policy != held.policy + + def _reserve_soc_pct(self) -> float | None: + """The devices' battery reserve guard: ``core.battery.effective_reserve_pct`` (ADR-0013 + decision 3) with a battery model, else the site's minimum SoC as before.""" + site_battery = None if self.site is None else self.site.battery + model = None if self.battery_config is None else self.battery_config.model + if model is not None: + return effective_reserve_pct(site_battery, model) + return None if site_battery is None else site_battery.min_soc_pct + + def _live_import_price(self, now: datetime) -> float | None: + """The current quarter hour's import price from the tariff service (``None`` = unknown).""" + tariff = self.tariff + if tariff is None: + return None + try: + values = tariff.prices(0.25, now).import_price.values + except Exception: + log.exception("battery.price_failed") + return None + return values[0] if values else None + + def _battery_wiring(self) -> BatteryWiring | None: + """The battery as a controlled asset, or ``None`` (observe-only / unusable template).""" + settings = self.battery_config + if settings is None or settings.adapter_template_id is None or settings.model is None: + return None + identity = battery_identity_token(settings, self.site) + template = self.template_catalog.get(settings.adapter_template_id) + if identity is None or not isinstance(template, BatteryTemplate): + log.warning("battery.adapter_template_missing", template=settings.adapter_template_id) + return None + goals = self.goals if self.goals is not None else GoalsConfig() + return BatteryWiring( + settings=settings, + spec=template.adapter_spec(), + identity=identity, + reserve_pct=self._reserve_soc_pct(), + policy=effective_grid_charge_policy(goals, settings), + import_price=self._live_import_price, + ) + async def _rebuild_stack(self) -> None: """Replace the control stack after a ``devices``/``site``/``region`` change. @@ -1115,6 +1171,8 @@ async def _resubscribe(self) -> None: refs.extend(self.forecast.entity_refs()) if self.tariff_config is not None: refs.extend(self.tariff_config.entity_refs()) + if self.battery_config is not None: + refs.extend(self.battery_config.entity_refs()) ids = list(dict.fromkeys(r.entity_id for r in refs)) try: await self.connection.subscribe_entities(ids) @@ -1192,7 +1250,7 @@ async def put_section(self, name: str, model: BaseModel) -> BaseModel: identity token, so a stale document cannot grant a mode to a device that was re-mapped meanwhile (``ModeRaiseRejectedError``). Lowered devices are released. """ - if name in ("operation", "devices"): + if name in ("operation", "devices", "battery", "site"): # Serialised with the mode changes: the raise check and the identity rule of a # devices put judge the modes that are stored when they run. async with self._operation_lock: @@ -1225,7 +1283,7 @@ def _store_planning_input(self, name: str, stored: BaseModel) -> None: assert isinstance(stored, TariffConfig) self.tariff_config = stored - async def _apply_stored( + async def _apply_stored( # noqa: PLR0912 - one branch per section self, name: str, stored: BaseModel, @@ -1246,10 +1304,18 @@ async def _apply_stored( self.goals = stored if self.stack is not None: self.stack.set_goals(stored) + elif name == "battery": + assert isinstance(stored, BatterySettings) + self.battery_config = stored + await self._load_modes() # the identity rule may have dropped the battery mode else: self._store_planning_input(name, stored) - if name in ("site", "devices", "forecast", "tariff"): + if name == "site": + await self._load_modes() # the site's battery entities are battery identity + if name in ("site", "devices", "forecast", "tariff", "battery"): await self._resubscribe() + if name == "battery" or (name == "goals" and self._battery_policy_changed()): + await self._rebuild_stack() # adapter, reserve or grid-charge policy changed if name == "tariff" or (self.site, self.region) != before[::2]: await self._rebuild_tariff() if (self.site, self.devices, self.region) != before: @@ -1319,6 +1385,24 @@ async def set_device_mode( self._notify() return stored + async def set_battery_mode(self, mode: OperatingMode, identity: str | None) -> OperationConfig: + """The battery's mode (ADR-0013 decision 6): raising it needs its identity token.""" + async with self._operation_lock: + token = battery_identity_token(self.battery_config, self.site) + if mode is not OperatingMode.SHADOW: + if token is None: + raise BatteryNotControllableError("battery") + if identity != token: + raise DeviceIdentityChangedError("battery") + current = self.modes.operation + stored = await self.config.put( + "operation", current.model_copy(update={"battery_mode": mode}) + ) + assert isinstance(stored, OperationConfig) + await self._apply_operation(stored) + self._notify() + return stored + # --- control ---------------------------------------------------------------------- def control_state(self) -> ControlState: diff --git a/suncore/core/controlstate.py b/suncore/core/controlstate.py index 8126420..d3abd85 100644 --- a/suncore/core/controlstate.py +++ b/suncore/core/controlstate.py @@ -14,6 +14,7 @@ from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator from pydantic_core import PydanticCustomError +from suncore.core.battery import BatteryAction from suncore.core.control import DeviceState, PowerEstimate from suncore.core.decisions import Decision, OperatingMode, Reason from suncore.core.devices import DeviceKind @@ -88,6 +89,37 @@ class SiteControlState(_Frozen): soc_pct: float | None +class BatteryControlState(_Frozen): + """The battery as a controlled asset (Phase 4 WP10, ADR-0013).""" + + identity: str + """Opaque battery identity token; send it back when raising the battery's mode.""" + adapter_template_id: str + capabilities: list[str] + """What the adapter can execute (``charge_limit``, ``discharge_limit``, ``min_soc``, + ``grid_charge``, ``hardware_fallback``).""" + global_mode: OperatingMode + battery_mode: OperatingMode + """The stored mode (``operation.battery_mode``).""" + effective_mode: OperatingMode + """``min(global, battery)``, capped at assisted while ``mode_capped``.""" + mode_capped: bool + """The adapter's hardware fallback is not measured yet (``battery.fallback_measured``).""" + limits: BatteryAction | None + """What the adapter's entities show now (``None`` = unknown).""" + held: BatteryAction | None + """What SunCore holds (``None`` = the battery's own settings).""" + baseline: BatteryAction | None + """The values found at takeover, restored by a release.""" + under_control: bool + wanted: BatteryAction | None + """What the plan asks for now (``None`` = nothing / baseline).""" + reasons: list[Reason] + """The controller's reasons ("Why?").""" + paused: Reason | None + last_decision: Decision | None + + class ControlState(_Frozen): """Everything the control layer exposes after a tick.""" @@ -101,6 +133,8 @@ class ControlState(_Frozen): devices: list[DeviceControlState] proposals: list[Decision] """Open assisted-mode proposals (``DecisionKind.PROPOSED`` with ``expires_at``).""" + battery: BatteryControlState | None = None + """``None`` = no battery adapter (observe-only); Phase 4 WP10.""" OverrideAction = Literal["boost", "pause", "resume"] @@ -158,6 +192,29 @@ def _identity_for_raise(self) -> Self: return self +class BatteryModeRequest(_Frozen): + """``PUT /api/v1/operation/battery``: the battery's operating mode (ADR-0013). + + Like a device: raising the mode above shadow needs ``identity``, the token from + ``GET /api/v1/control/state`` (``battery.identity``); a re-mapped battery answers 409. + """ + + mode: OperatingMode + identity: Annotated[str, Field(min_length=1, max_length=64)] | None = None + + @model_validator(mode="after") + def _identity_for_raise(self) -> Self: + if self.mode is not OperatingMode.SHADOW and self.identity is None: + raise invalid( + "mode_identity_required", "mode: raising a device above shadow needs `identity`" + ) + return self + + +class BatteryNotControllableError(LookupError): + """No battery adapter is configured (observe-only): there is no battery mode to raise.""" + + class UnknownDeviceError(LookupError): """No configured device has this id.""" @@ -184,6 +241,9 @@ class ModeRaiseRejectedError(RuntimeError): __all__ = [ + "BatteryControlState", + "BatteryModeRequest", + "BatteryNotControllableError", "ControlState", "DeviceControlState", "DeviceIdentityChangedError", diff --git a/suncore/devices/battery/base.py b/suncore/devices/battery/base.py index 9506d9f..914f344 100644 --- a/suncore/devices/battery/base.py +++ b/suncore/devices/battery/base.py @@ -168,5 +168,11 @@ def last_context_id(self) -> str | None: async def read_back(self) -> Action | None: # pragma: no cover - overridden raise NotImplementedError + async def apply(self, intent: Intent) -> str | None: # pragma: no cover - overridden + raise NotImplementedError + + async def release(self, baseline: Action | None) -> None: # pragma: no cover - overridden + raise NotImplementedError + __all__ = ["DEFAULT_SETTLE_S", "BatteryDriver"] diff --git a/suncore/safety/wiring.py b/suncore/safety/wiring.py index b600607..1a245c1 100644 --- a/suncore/safety/wiring.py +++ b/suncore/safety/wiring.py @@ -101,6 +101,12 @@ def writer_of(source: object) -> WriterFn: return _no_capability +def build_actuator[A: Actuator](source: object, make: Callable[[WriterFn], A]) -> A: + """One actuator built by ``make(write)`` with the connection's writer (the battery adapter, + Phase 4 WP10; the composition root never names the write capability).""" + return make(writer_of(source)) + + def build_actuators[A: Actuator]( source: object, devices: Iterable[DeviceConfig], @@ -117,6 +123,7 @@ def build_actuators[A: Actuator]( "WriteOutcome", "WriteSource", "WriterFn", + "build_actuator", "build_actuators", "writer_of", ] diff --git a/tests/api/conftest.py b/tests/api/conftest.py index 50c04b9..8c7d844 100644 --- a/tests/api/conftest.py +++ b/tests/api/conftest.py @@ -32,6 +32,7 @@ from suncore.core.config import SECTION_MODELS, OperationConfig from suncore.core.control import DeviceState, PowerEstimate from suncore.core.controlstate import ( + BatteryNotControllableError, ControlState, DeviceControlState, DeviceIdentityChangedError, @@ -416,6 +417,17 @@ async def set_device_mode( self.operation = self.operation.model_copy(update={"device_modes": modes}) return self.operation + battery_identity: str | None = "bat-current" + + async def set_battery_mode(self, mode: OperatingMode, identity: str | None) -> OperationConfig: + if mode is not OperatingMode.SHADOW: + if self.battery_identity is None: + raise BatteryNotControllableError("battery") + if identity != self.battery_identity: + raise DeviceIdentityChangedError("battery") + self.operation = self.operation.model_copy(update={"battery_mode": mode}) + return self.operation + def add_control_listener(self, listener: Callable[[], None]) -> Callable[[], None]: self.control_listeners.append(listener) diff --git a/tests/api/test_control_api.py b/tests/api/test_control_api.py index 50e882a..e8c649a 100644 --- a/tests/api/test_control_api.py +++ b/tests/api/test_control_api.py @@ -61,6 +61,7 @@ async def test_control_state_shape(services: FakeServices) -> None: "site", "devices", "proposals", + "battery", } device = body["devices"][0] assert device["device_id"] == "pool" @@ -209,6 +210,30 @@ async def test_operation_mode_endpoints(services: FakeServices) -> None: assert bad.status_code == 422 +async def test_battery_mode_endpoint(services: FakeServices) -> None: + async with client_for(create_app(services)) as client: + shadow = await client.put("/api/v1/operation/battery", json={"mode": "shadow"}) + no_identity = await client.put("/api/v1/operation/battery", json={"mode": "assisted"}) + stale = await client.put( + "/api/v1/operation/battery", json={"mode": "assisted", "identity": "old"} + ) + ok = await client.put( + "/api/v1/operation/battery", json={"mode": "assisted", "identity": "bat-current"} + ) + services.battery_identity = None + observe_only = await client.put( + "/api/v1/operation/battery", json={"mode": "automatic", "identity": "bat-current"} + ) + assert shadow.json()["battery_mode"] == "shadow" + assert no_identity.status_code == 422 + assert no_identity.json()["issues"][0]["key"] == "api.validation.mode_identity_required" + assert stale.status_code == 409 + assert stale.json() == {"detail": "api.error.device_identity_changed"} + assert ok.json()["battery_mode"] == "assisted" + assert observe_only.status_code == 404 + assert observe_only.json() == {"detail": "api.error.battery_not_controllable"} + + async def test_put_operation_document_that_raises_a_mode_is_409(services: FakeServices) -> None: from suncore.core.controlstate import ModeRaiseRejectedError # noqa: PLC0415 diff --git a/tests/app/test_battery_runtime.py b/tests/app/test_battery_runtime.py new file mode 100644 index 0000000..a02cd4b --- /dev/null +++ b/tests/app/test_battery_runtime.py @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The battery in the runtime (WP10): wiring, control state, mode with identity, re-mapping.""" + +from __future__ import annotations + +import pytest + +from suncore.app.runtime import Runtime +from suncore.core.battery import BATTERY_ASSET_ID, BatteryModel, BatterySettings +from suncore.core.config import OperationConfig +from suncore.core.controlstate import ( + BatteryNotControllableError, + DeviceIdentityChangedError, + ModeRaiseRejectedError, +) +from suncore.core.decisions import OperatingMode +from suncore.core.site import EntityRef + + +def generic_battery(entity: str = "number.battery_max_discharge") -> BatterySettings: + return BatterySettings( + adapter_template_id="generic.battery", + entities={"max_discharge_number": EntityRef(entity_id=entity)}, + model=BatteryModel(capacity_wh=10_000, max_charge_w=5000, max_discharge_w=5000), + ) + + +async def test_an_observe_only_battery_has_no_mode_to_raise(demo_runtime: Runtime) -> None: + assert demo_runtime.control_state().battery is None + with pytest.raises(BatteryNotControllableError): + await demo_runtime.set_battery_mode(OperatingMode.ASSISTED, "anything") + shadow = await demo_runtime.set_battery_mode(OperatingMode.SHADOW, None) + assert shadow.battery_mode is OperatingMode.SHADOW + + +async def test_battery_mode_needs_the_identity_and_a_remap_drops_it( + demo_runtime: Runtime, +) -> None: + await demo_runtime.put_section("battery", generic_battery()) + stack = demo_runtime.stack + assert stack is not None + assert stack.battery_driver is not None + assert BATTERY_ASSET_ID in stack.gate.asset_ids + state = demo_runtime.control_state().battery + assert state is not None + assert state.battery_mode is OperatingMode.SHADOW # a battery starts in shadow + assert state.capabilities == ["discharge_limit"] + with pytest.raises(DeviceIdentityChangedError): + await demo_runtime.set_battery_mode(OperatingMode.ASSISTED, "stale") + stored = await demo_runtime.set_battery_mode(OperatingMode.ASSISTED, state.identity) + assert stored.battery_mode is OperatingMode.ASSISTED + # A full operation document may only keep or lower the battery mode. + with pytest.raises(ModeRaiseRejectedError): + await demo_runtime.put_section( + "operation", stored.model_copy(update={"battery_mode": OperatingMode.AUTOMATIC}) + ) + await demo_runtime.put_section("battery", generic_battery("number.other_discharge")) + operation = await demo_runtime.get_section("operation") + assert isinstance(operation, OperationConfig) + assert operation.battery_mode is OperatingMode.SHADOW + after = demo_runtime.control_state().battery + assert after is not None + assert after.identity != state.identity + + +async def test_the_devices_reserve_guard_uses_the_effective_reserve(demo_runtime: Runtime) -> None: + await demo_runtime.put_section("battery", generic_battery()) + battery = demo_runtime.battery_config + assert battery is not None + assert battery.model is not None + expected = battery.model.reserve_pct + battery.model.bms_drift_margin_pct + assert demo_runtime._reserve_soc_pct() is not None + assert demo_runtime._reserve_soc_pct() >= expected # type: ignore[operator] From 85b7c1b3eee1fa8108832fc05817a8aa9c145acb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 21:39:41 +0000 Subject: [PATCH 07/16] test(sim): hybrid inverter model and the five battery scenarios (WP10) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sim/inverter.py: the inverter's own self-consumption control as the fallback, min-SoC floor judged on the BMS reading, BMS drift at night, REST refresh lag and silent REST failures, Kostal §3.5 registers through modbus.write_register with the fallback timer (1288), 1080 external control, hang (frozen power, writes ignored); fake HA publishes its numbers and modbus sensors and routes number.set_value / modbus.write_register to it - runner: battery wiring from the scenario (generic, kostal.plenticore, kostal_modbus templates) - scenarios modbus_heartbeat_lost, battery_reserve_drift, kostal_rest_reserve, inverter_hang_battery (cloud flicker, write counts), grid_charge_price_level (real planner, controller and gate in automatic mode) - gate fixes found by the scenarios: the heartbeat is timed from the write (not the read-back), a new takeover supersedes the check of the previous release Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- suncore/safety/gate.py | 7 +- suncore/sim/fake_ha.py | 65 +++ suncore/sim/house.py | 31 +- suncore/sim/inverter.py | 346 +++++++++++++++ suncore/sim/runner.py | 94 +++- suncore/sim/scenario.py | 26 ++ .../sim/scenarios/battery_reserve_drift.yaml | 23 + .../scenarios/grid_charge_price_level.yaml | 21 + .../sim/scenarios/inverter_hang_battery.yaml | 33 ++ .../sim/scenarios/kostal_rest_reserve.yaml | 19 + .../sim/scenarios/modbus_heartbeat_lost.yaml | 22 + tests/safety/test_battery_gate.py | 14 + tests/sim/test_battery_scenarios.py | 406 ++++++++++++++++++ tests/sim/test_inverter.py | 78 ++++ tests/sim/test_scenario.py | 9 +- 15 files changed, 1188 insertions(+), 6 deletions(-) create mode 100644 suncore/sim/inverter.py create mode 100644 suncore/sim/scenarios/battery_reserve_drift.yaml create mode 100644 suncore/sim/scenarios/grid_charge_price_level.yaml create mode 100644 suncore/sim/scenarios/inverter_hang_battery.yaml create mode 100644 suncore/sim/scenarios/kostal_rest_reserve.yaml create mode 100644 suncore/sim/scenarios/modbus_heartbeat_lost.yaml create mode 100644 tests/sim/test_battery_scenarios.py create mode 100644 tests/sim/test_inverter.py diff --git a/suncore/safety/gate.py b/suncore/safety/gate.py index 85727ab..1883e57 100644 --- a/suncore/safety/gate.py +++ b/suncore/safety/gate.py @@ -851,6 +851,9 @@ async def _battery_write( # noqa: PLR0912 - one branch per verdict intent, DecisionKind.REJECTED, now, (REASON_RATE_LIMITED,), mode ) if not runtime.under_control: + # A new takeover supersedes the check of the previous release (it reads its own + # baseline now and the battery will show the new state, not the old baseline). + self._battery_verify = None baseline = await actuator.read_back() if baseline is None: self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) @@ -953,7 +956,9 @@ async def _battery_confirm( "pending_ts": None, } ) - self._battery_beat = after # the write itself was the first beat of the lease + # The write itself was the first beat: the next one is due ``heartbeat_s`` after the + # write, not after the read-back (the inverter's timer started at the write). + self._battery_beat = now await self._save(runtime) if mismatch: await self._count_failure(BATTERY_ASSET_ID, after) diff --git a/suncore/sim/fake_ha.py b/suncore/sim/fake_ha.py index 229ddd4..c71d7de 100644 --- a/suncore/sim/fake_ha.py +++ b/suncore/sim/fake_ha.py @@ -96,6 +96,7 @@ validate_schema, ) from suncore.sim.house import House, HouseState +from suncore.sim.inverter import SimInverter from suncore.sim.recorder import SimRecorder from suncore.sim.scenario import ManualEvent, Scenario, SimSignal @@ -688,6 +689,16 @@ async def _command(self, payload: Mapping[str, Any]) -> dict[str, Any]: ) msg = f"fake HA is {self._state.value}" raise NotConnectedError(msg) + inverter = self._house.inverter if self._house is not None else None + if inverter is not None and self._inverter_call( + inverter, now, domain, service, entity_ids, fields + ): + context = self._new_context(user_id=SUPERVISOR_USER_ID) + self._record( + CallRecord(now, domain, service, entity_ids, fields, context.id, entity_ids) + ) + self._publish_inverter(emit=True, context=context) + return {"context": {"id": context.id, "parent_id": None, "user_id": context.user_id}} try: clean = validate_schema(domain, service, fields) if not any(k in merged for k in TARGET_KEYS): @@ -736,6 +747,49 @@ def context_at( await self._sleep(blocking / self._speed) return {"context": {"id": context.id, "parent_id": None, "user_id": context.user_id}} + def _inverter_call( # noqa: PLR0917 + self, + inverter: SimInverter, + now: datetime, + domain: str, + service: str, + entity_ids: tuple[str, ...], + fields: Mapping[str, Any], + ) -> bool: + """The battery inverter's services (WP10): its numbers and ``modbus.write_register``. + + ``modbus.write_register`` has no target and fails silently (the hub only logs); a number + write to an unavailable entity is skipped silently like any other. + """ + if domain == "modbus" and service == "write_register": + inverter.write_register(now, dict(fields)) + return True + if ( + domain == "number" + and service == "set_value" + and entity_ids + and all(inverter.handles(e) for e in entity_ids) + ): + value = fields.get("value") + if not isinstance(value, int | float) or isinstance(value, bool): + raise CommandError("invalid_format", "expected float for dictionary value") + for entity_id in entity_ids: + if entity_id not in self._unavailable: + inverter.set_number(now, entity_id, float(value)) + return True + return False + + def _publish_inverter(self, *, emit: bool, context: StateContext | None = None) -> None: + inverter = self._house.inverter if self._house is not None else None + if inverter is None: + return + self._commit( + inverter.states(self._sim_now()), + context=context, + emit=emit, + only_changes=False, + ) + def _plan( self, now: datetime, @@ -998,6 +1052,17 @@ def _apply_step(self, *, emit: bool) -> None: only_changes=True, ) ) + inverter = self._house.inverter + if inverter is not None: # the battery inverter's numbers and modbus sensors (WP10) + changed.update( + self._commit( + inverter.states(house_state.time), + context=None, + emit=False, + faults=faults, + only_changes=False, + ) + ) if not emit: return if disconnected: diff --git a/suncore/sim/house.py b/suncore/sim/house.py index d423171..efd80b7 100644 --- a/suncore/sim/house.py +++ b/suncore/sim/house.py @@ -21,6 +21,8 @@ from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator +from suncore.sim.inverter import InverterParams, SimInverter + _DEFAULT_LOAD_PROFILE_W: tuple[float, ...] = ( 250, 220, 210, 210, 220, 300, 550, 700, 500, 400, 380, 450, 600, 500, 380, 380, 450, 700, 1000, 1100, 900, 650, 450, 320, @@ -89,6 +91,9 @@ class HouseParams(BaseModel): load: LoadParams = LoadParams() battery: BatteryParams = BatteryParams() seed: int = 0 + inverter: InverterParams | None = None + """Phase 4 WP10: a controllable hybrid inverter (limits, fallback timer, BMS drift) instead + of the plain self-consumption battery; ``None`` = the plain battery.""" class HouseState(BaseModel): @@ -106,6 +111,8 @@ class HouseState(BaseModel): cloud_factor: Annotated[float, Field(ge=0, le=1)] devices_w: float = 0.0 """Draw of the simulated devices (already part of ``load_w``).""" + true_soc_pct: float | None = None + """The battery's true SoC when it differs from the reported one (BMS drift, WP10).""" def sin_elevation(when: datetime, latitude: float, longitude: float) -> float: @@ -167,6 +174,21 @@ def __init__( self._rng = random.Random(params.seed) self._index = 0 self._soc_pct = params.battery.initial_soc_pct + b = params.battery + self.inverter: SimInverter | None = ( + None + if params.inverter is None or b.capacity_wh <= 0 + else SimInverter( + params.inverter, + capacity_wh=b.capacity_wh, + max_charge_w=b.max_charge_w, + max_discharge_w=b.max_discharge_w, + round_trip_efficiency=b.round_trip_efficiency, + soc_max_pct=b.soc_max_pct, + initial_soc_pct=b.initial_soc_pct, + start=start, + ) + ) @property def index(self) -> int: @@ -223,7 +245,13 @@ def step(self, extra_load_w: float = 0.0) -> HouseState: cloud = self._cloud_at(self._index) pv_w = clear_sky_w(when, self.params.pv) * cloud load_w = self._load_w(when) + extra_load_w - battery_w = self._dispatch(pv_w - load_w) + true_soc: float | None = None + if self.inverter is not None: + battery_w = self.inverter.dispatch(when, pv_w - load_w, self.step_s) + self._soc_pct = self.inverter.reported_soc_pct + true_soc = self.inverter.soc_pct + else: + battery_w = self._dispatch(pv_w - load_w) state = HouseState( time=when, pv_w=pv_w, @@ -233,6 +261,7 @@ def step(self, extra_load_w: float = 0.0) -> HouseState: grid_w=load_w + battery_w - pv_w, cloud_factor=cloud, devices_w=extra_load_w, + true_soc_pct=true_soc, ) self._index += 1 return state diff --git a/suncore/sim/inverter.py b/suncore/sim/inverter.py new file mode 100644 index 0000000..0d2da4e --- /dev/null +++ b/suncore/sim/inverter.py @@ -0,0 +1,346 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A hybrid inverter with its battery for the simulator (Phase 4 WP10). + +Deterministic and time injected. The inverter runs its **own self-consumption control** (the +fallback SunCore relies on): surplus charges, deficit discharges, both capped by its limits and +stopped at its floor ``max(min SoC setting, BMS cut-off)``. SunCore can only change the limits, +through the same entities and services a real installation offers: + +* ``kostal_plenticore`` style: ``number.sim_battery_min_soc`` (%, 5-100, step 5). A write is + applied at once and the entity reports it after ``rest_refresh_s`` (the forced refresh); with + ``rest_write_fails`` a write is **silently** ignored (``ApiException`` swallowed, research); +* ``generic``: ``number.sim_battery_max_charge`` / ``..._max_discharge`` / ``..._grid_charge`` + (W) next to the min-SoC number; +* ``kostal_modbus``: ``modbus.write_register`` on registers 1280/1282 (limits), 1284/1286 + (fallback limits) and 1288 (U32 timeout), float32 words in the configured order; modbus sensors + ``sensor.sim_modbus_`` report them (and 1080, 1076, 1078). Writes are ignored unless + register 1080 is ``2``. **Fallback timer:** once 1280/1282 were written they must be re-written + within 1288 seconds, otherwise 1284/1286 apply (Kostal §3.5). + +The SoC the integration **reports** sags below the true SoC at night (``bms_drift``): the BMS +recalibrates by up to ``max_drift_pct`` in the dark hours and catches up while charging (the +maintainer's BMS drops from 10 % to 6-7 %). A **hang** (``hang_from_s`` .. ``hang_to_s``) +freezes the battery power at its last value and ignores every write. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any, Final, Literal + +from pydantic import BaseModel, ConfigDict, Field + +from suncore.core.battery import ModbusByteOrder +from suncore.devices.battery.modbus_codec import words_float32, words_uint32 + +AdapterKind = Literal["generic", "kostal_plenticore", "kostal_modbus"] + +MIN_SOC_ID: Final = "number.sim_battery_min_soc" +MAX_CHARGE_ID: Final = "number.sim_battery_max_charge" +MAX_DISCHARGE_ID: Final = "number.sim_battery_max_discharge" +GRID_CHARGE_ID: Final = "number.sim_battery_grid_charge" +MODBUS_IDS: Final = { + 1080: "sensor.sim_modbus_1080", + 1280: "sensor.sim_modbus_1280", + 1282: "sensor.sim_modbus_1282", + 1284: "sensor.sim_modbus_1284", + 1286: "sensor.sim_modbus_1286", + 1288: "sensor.sim_modbus_1288", + 1076: "sensor.sim_modbus_1076", + 1078: "sensor.sim_modbus_1078", +} +MODBUS_ROLES: Final = { + "external_control": MODBUS_IDS[1080], + "charge_limit": MODBUS_IDS[1280], + "discharge_limit": MODBUS_IDS[1282], + "fallback_charge_limit": MODBUS_IDS[1284], + "fallback_discharge_limit": MODBUS_IDS[1286], + "fallback_timeout": MODBUS_IDS[1288], + "own_charge_limit": MODBUS_IDS[1076], + "own_discharge_limit": MODBUS_IDS[1078], +} +MODBUS_HUB: Final = "sim_kostal" +MODBUS_SLAVE: Final = 71 + + +class InverterParams(BaseModel): + """The simulated inverter's behaviour (scenario ``house.inverter``).""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + adapter: AdapterKind = "generic" + min_soc_pct: float = Field(default=10.0, ge=0, le=100) + """The inverter's own min-SoC setting (the user's floor; the release baseline).""" + bms_cutoff_pct: float = Field(default=5.0, ge=0, le=100) + max_drift_pct: float = Field(default=0.0, ge=0, le=20) + """How far the reported SoC sags below the true SoC by the end of the night.""" + drift_per_h: float = Field(default=1.0, ge=0, le=20) + rest_refresh_s: float = Field(default=2.0, ge=0, le=120) + rest_write_fails: bool = False + external_control: int = Field(default=2, ge=0, le=255) + """Register 1080 (2 = external battery management via Modbus enabled).""" + byte_order: ModbusByteOrder = ModbusByteOrder.LITTLE + fallback_timeout_s: int = Field(default=0, ge=0, le=10_800) + """Register 1288 before SunCore writes it (0 = never written).""" + hang_from_s: int | None = None + hang_to_s: int | None = None + + +@dataclass(slots=True) +class InverterLog: + """Evidence for the tests: what the inverter did, independent of SunCore's view.""" + + writes: list[tuple[datetime, str, Any]] = field(default_factory=list) + fallback_active: list[tuple[datetime, bool]] = field(default_factory=list) + + +class SimInverter: + """Battery dispatch under the inverter's own control and SunCore's limits.""" + + def __init__( + self, + params: InverterParams, + *, + capacity_wh: float, + max_charge_w: float, + max_discharge_w: float, + round_trip_efficiency: float, + soc_max_pct: float, + initial_soc_pct: float, + start: datetime, + ) -> None: + self.params = params + self.capacity_wh = capacity_wh + self.own_charge_w = max_charge_w + self.own_discharge_w = max_discharge_w + self.leg = math.sqrt(round_trip_efficiency) + self.soc_max_pct = soc_max_pct + self.soc_pct = initial_soc_pct + """The true state of charge.""" + self.drift_pct = 0.0 + self.start = start + self.min_soc_pct = params.min_soc_pct + self.max_charge_w = max_charge_w + self.max_discharge_w = max_discharge_w + self.grid_charge_w = 0.0 + self.registers: dict[int, float] = { + 1280: max_charge_w, + 1282: max_discharge_w, + 1284: 0.0, + 1286: 0.0, + 1288: float(params.fallback_timeout_s), + } + self.limits_written_at: datetime | None = None + self.battery_w = 0.0 + self.log = InverterLog() + self._shown_min_soc = params.min_soc_pct + self._min_soc_changed_at: datetime | None = None + + # --- state ------------------------------------------------------------------------------- + + def hung(self, now: datetime) -> bool: + p = self.params + if p.hang_from_s is None or p.hang_to_s is None: + return False + offset = (now - self.start).total_seconds() + return p.hang_from_s <= offset < p.hang_to_s + + @property + def reported_soc_pct(self) -> float: + return max(0.0, self.soc_pct - self.drift_pct) + + def fallback_active(self, now: datetime) -> bool: + """§3.5: the limits were written but not re-written within register 1288.""" + if self.params.adapter != "kostal_modbus" or self.limits_written_at is None: + return False + timeout = self.registers[1288] + return timeout > 0 and (now - self.limits_written_at).total_seconds() > timeout + + def caps(self, now: datetime) -> tuple[float, float]: + """Effective charge and discharge caps (W).""" + if self.params.adapter == "kostal_modbus": + if self.limits_written_at is None: + return self.own_charge_w, self.own_discharge_w + if self.fallback_active(now): + return self.registers[1284], self.registers[1286] + return self.registers[1280], self.registers[1282] + return self.max_charge_w, self.max_discharge_w + + # --- physics ----------------------------------------------------------------------------- + + def dispatch(self, now: datetime, surplus_w: float, step_s: float) -> float: + """Battery AC power (+ = charging) for one step of ``step_s``; ``surplus = pv - load``.""" + hours = step_s / 3600 + if self.hung(now): + self._integrate(self.battery_w, hours) # stuck at the last power + return self.battery_w + charge_cap, discharge_cap = self.caps(now) + # The inverter judges its floor by the BMS reading (which may sag below the true SoC). + floor = max(self.min_soc_pct, self.params.bms_cutoff_pct) + room_wh = max(0.0, (self.soc_max_pct - self.soc_pct) / 100 * self.capacity_wh) + avail_wh = max(0.0, (self.reported_soc_pct - floor) / 100 * self.capacity_wh) + charge_limit = min(charge_cap, self.own_charge_w, room_wh / (hours * self.leg)) + if self.grid_charge_w > 0 and room_wh > 0: + power = min(max(self.grid_charge_w, surplus_w), max(0.0, charge_limit)) + elif surplus_w >= 0: + power = min(surplus_w, max(0.0, charge_limit)) + else: + limit = min(discharge_cap, self.own_discharge_w, avail_wh * self.leg / hours) + power = -min(-surplus_w, max(0.0, limit)) + self._integrate(power, hours) + self._drift(now, power, hours) + self.battery_w = power + self.log.fallback_active.append((now, self.fallback_active(now))) + return power + + def _integrate(self, power: float, hours: float) -> None: + if power >= 0: + self.soc_pct += power * hours * self.leg / self.capacity_wh * 100 + else: + self.soc_pct += power * hours / self.leg / self.capacity_wh * 100 + self.soc_pct = min(self.soc_max_pct, max(0.0, self.soc_pct)) + + def _drift(self, now: datetime, power: float, hours: float) -> None: + p = self.params + if p.max_drift_pct <= 0: + return + if power <= 0 and not 6 <= now.hour < 20: + self.drift_pct = min(p.max_drift_pct, self.drift_pct + p.drift_per_h * hours) + elif power > 0: + self.drift_pct = max(0.0, self.drift_pct - 4 * p.drift_per_h * hours) + + # --- Home Assistant side ---------------------------------------------------------------- + + def entity_ids(self) -> tuple[str, ...]: + ids = [MIN_SOC_ID] + if self.params.adapter == "generic": + ids += [MAX_CHARGE_ID, MAX_DISCHARGE_ID, GRID_CHARGE_ID] + if self.params.adapter == "kostal_modbus": + ids += list(MODBUS_IDS.values()) + return tuple(ids) + + def handles(self, entity_id: str) -> bool: + return entity_id in self.entity_ids() + + def roles(self) -> dict[str, str]: + """Role -> entity of the battery template of ``adapter``.""" + if self.params.adapter == "kostal_plenticore": + return {"min_soc_number": MIN_SOC_ID} + if self.params.adapter == "kostal_modbus": + return dict(MODBUS_ROLES) + return { + "min_soc_number": MIN_SOC_ID, + "max_charge_number": MAX_CHARGE_ID, + "max_discharge_number": MAX_DISCHARGE_ID, + "grid_charge_number": GRID_CHARGE_ID, + } + + def states(self, now: datetime) -> list[tuple[str, str, dict[str, Any]]]: + rows: list[tuple[str, str, dict[str, Any]]] = [] + + def number(entity_id: str, value: float, unit: str, high: float, step: float) -> None: + rows.append( + ( + entity_id, + _text(value), + { + "unit_of_measurement": unit, + "min": 5 if unit == "%" else 0, + "max": high, + "step": step, + "mode": "box", + "friendly_name": entity_id.split(".", 1)[1].replace("_", " "), + }, + ) + ) + + number(MIN_SOC_ID, self._min_soc_shown(now), "%", 100, 5) + if self.params.adapter == "generic": + number(MAX_CHARGE_ID, self.max_charge_w, "W", self.own_charge_w, 1) + number(MAX_DISCHARGE_ID, self.max_discharge_w, "W", self.own_discharge_w, 1) + number(GRID_CHARGE_ID, self.grid_charge_w, "W", self.own_charge_w, 1) + if self.params.adapter == "kostal_modbus": + values = { + 1080: float(self.params.external_control), + 1076: self.own_charge_w, + 1078: self.own_discharge_w, + **self.registers, + } + for register, entity_id in MODBUS_IDS.items(): + unit = "s" if register == 1288 else (None if register == 1080 else "W") + attributes: dict[str, Any] = {"friendly_name": f"Kostal register {register}"} + if unit is not None: + attributes["unit_of_measurement"] = unit + rows.append((entity_id, _text(values[register]), attributes)) + return rows + + def _min_soc_shown(self, now: datetime) -> float: + """The REST integration shows a written floor only after its refresh.""" + changed = self._min_soc_changed_at + if changed is not None and (now - changed).total_seconds() >= self.params.rest_refresh_s: + self._shown_min_soc = self.min_soc_pct + self._min_soc_changed_at = None + return self._shown_min_soc + + # --- services ---------------------------------------------------------------------------- + + def set_number(self, now: datetime, entity_id: str, value: float) -> None: + """``number.set_value`` on one of the inverter's numbers (applied at once).""" + self.log.writes.append((now, entity_id, value)) + if self.hung(now) or (self.params.rest_write_fails and entity_id == MIN_SOC_ID): + return # silently ignored, like a swallowed REST ApiException + if entity_id == MIN_SOC_ID: + self.min_soc_pct = min(100.0, max(5.0, value)) + self._min_soc_changed_at = now + elif entity_id == MAX_CHARGE_ID: + self.max_charge_w = min(self.own_charge_w, max(0.0, value)) + elif entity_id == MAX_DISCHARGE_ID: + self.max_discharge_w = min(self.own_discharge_w, max(0.0, value)) + elif entity_id == GRID_CHARGE_ID: + self.grid_charge_w = min(self.own_charge_w, max(0.0, value)) + + def write_register(self, now: datetime, data: dict[str, Any]) -> None: + """``modbus.write_register``: failures are silent (HA only logs them).""" + self.log.writes.append((now, "modbus", dict(data))) + if self.params.adapter != "kostal_modbus" or self.hung(now): + return + if data.get("hub") != MODBUS_HUB or data.get("slave", 1) != MODBUS_SLAVE: + return # another hub or unit: nothing happens here + if self.params.external_control != 2: + return + address = data.get("address") + words = data.get("value") + if not isinstance(address, int) or not isinstance(words, list) or len(words) != 2: + return + order = self.params.byte_order + if address == 1288: + self.registers[1288] = float(words_uint32(words, order)) + return + if address not in (1280, 1282, 1284, 1286): + return + value = words_float32(words, order) + if address in (1280, 1282): + value = min(self.own_charge_w if address == 1280 else self.own_discharge_w, value) + self.limits_written_at = now + self.registers[address] = max(0.0, value) + + +def _text(value: float) -> str: + return f"{value:.1f}" + + +__all__ = [ + "GRID_CHARGE_ID", + "MAX_CHARGE_ID", + "MAX_DISCHARGE_ID", + "MIN_SOC_ID", + "MODBUS_HUB", + "MODBUS_IDS", + "MODBUS_ROLES", + "MODBUS_SLAVE", + "AdapterKind", + "InverterParams", + "SimInverter", +] diff --git a/suncore/sim/runner.py b/suncore/sim/runner.py index 005b059..5266390 100644 --- a/suncore/sim/runner.py +++ b/suncore/sim/runner.py @@ -37,7 +37,14 @@ from datetime import datetime, timedelta from typing import Any, Final -from suncore.app.control import PlanProvider +from suncore.app.control import BatteryWiring, PlanProvider +from suncore.core.battery import ( + BATTERY_ASSET_ID, + BatteryModel, + BatterySettings, + ModbusLink, + effective_reserve_pct, +) from suncore.core.config import GoalsConfig from suncore.core.control import ControlSettings from suncore.core.decisions import ( @@ -51,14 +58,17 @@ SwitchAction, ) from suncore.core.devices import DeviceConfig, step_power_w +from suncore.core.identity import battery_identity_token from suncore.ha.connection import RateLimiter from suncore.safety.modes import StaticModes from suncore.safety.runtime import MemoryRuntimeStore, RuntimeStore +from suncore.sim.demo_devices import sim_price from suncore.sim.devices import SimClimate, SimDevice, SimWaterHeater from suncore.sim.fake_ha import FakeHAConnection, demo_site_config +from suncore.sim.inverter import MODBUS_HUB, MODBUS_SLAVE, SimInverter from suncore.sim.scenario import Scenario, SimDeviceSpec from suncore.sim.stack import ControlStack -from suncore.templates import DeviceTemplate, TemplateCatalog +from suncore.templates import BatteryTemplate, DeviceTemplate, TemplateCatalog SETTLE_ROUNDS: Final = 6 """Event-loop rounds that let woken tasks run until they block again.""" @@ -214,6 +224,8 @@ class StepLog: battery_w: float soc_pct: float devices_w: float + true_soc_pct: float | None = None + """The battery's true SoC (BMS drift; ``None`` without the inverter model).""" @dataclass(slots=True) @@ -370,10 +382,15 @@ def __init__( store: RuntimeStore | None = None, configs: Sequence[DeviceConfig] | None = None, plan_provider: PlanProvider | None = None, + import_price: Callable[[datetime], float | None] | None = None, ) -> None: self.scenario = scenario self.catalog = catalog self.plan_provider = plan_provider + profile = scenario.prices.profile + self.import_price: Callable[[datetime], float | None] = import_price or ( + lambda now: sim_price(now, profile) + ) self.vt = VirtualTime(scenario.start) self.limiter = RateLimiter(clock=self.vt.monotonic, sleep=self.vt.sleep) self.conn = FakeHAConnection( @@ -400,7 +417,10 @@ def __init__( for spec in scenario.devices if spec.template is not None } - self.modes = StaticModes(global_mode, device_mode_map) + battery_mode = ( + scenario.battery.mode if scenario.battery is not None else OperatingMode.SHADOW + ) + self.modes = StaticModes(global_mode, device_mode_map, battery=battery_mode) self.decisions: list[Decision] = [] self.stack: ControlStack | None = None self.configs: dict[str, DeviceConfig] = {} @@ -440,8 +460,75 @@ def new_stack(self) -> ControlStack: cadences=cadences, decisions=self.decisions, plan_provider=self.plan_provider, + battery=self.battery_wiring(), + ) + + @property + def inverter(self) -> SimInverter | None: + house = self.conn._house + return None if house is None else house.inverter + + def battery_settings(self) -> BatterySettings | None: + """What the wizard would store for the scenario's battery (``None`` = observe only).""" + control, inverter = self.scenario.battery, self.scenario.house.inverter + if control is None or inverter is None: + return None + b = self.scenario.house.battery + template_id = { + "generic": "generic.battery", + "kostal_plenticore": "kostal.plenticore", + "kostal_modbus": "kostal.plenticore_g3_modbus", + }[inverter.adapter] + sim = self.inverter + assert sim is not None + return BatterySettings.model_validate( + { + "adapter_template_id": template_id, + "entities": {r: {"entity_id": e} for r, e in sim.roles().items()}, + "model": BatteryModel( + capacity_wh=b.capacity_wh, + max_charge_w=b.max_charge_w, + max_discharge_w=b.max_discharge_w, + reserve_pct=control.reserve_pct, + bms_drift_margin_pct=control.bms_drift_margin_pct, + max_soc_pct=control.max_soc_pct, + ), + "grid_charge": control.grid_charge, + "fallback_measured": control.fallback_measured, + "modbus": ModbusLink( + hub=MODBUS_HUB, + slave=MODBUS_SLAVE, + byte_order=inverter.byte_order, + heartbeat_s=control.heartbeat_s, + fallback_timeout_s=control.fallback_timeout_s, + ) + if inverter.adapter == "kostal_modbus" + else None, + } ) + def battery_wiring(self) -> BatteryWiring | None: + settings = self.battery_settings() + if settings is None or settings.model is None: + return None + assert settings.adapter_template_id is not None + template = self.catalog.get(settings.adapter_template_id) + assert isinstance(template, BatteryTemplate) + site = demo_site_config() + identity = battery_identity_token(settings, site) + assert identity is not None + return BatteryWiring( + settings=settings, + spec=template.adapter_spec(), + identity=identity, + reserve_pct=effective_reserve_pct(site.battery, settings.model), + policy=settings.grid_charge, + import_price=self.import_price, + ) + + def battery_decisions(self) -> list[Decision]: + return [d for d in self.decisions if d.intent.asset_id == BATTERY_ASSET_ID] + async def start(self) -> None: if self._connected: return @@ -486,6 +573,7 @@ def _record(self, state_time: datetime) -> None: house.battery_w, house.soc_pct, house.devices_w, + house.true_soc_pct, ) ) for device_id, device in self.sim_devices.items(): diff --git a/suncore/sim/scenario.py b/suncore/sim/scenario.py index 52fe9c9..82c0884 100644 --- a/suncore/sim/scenario.py +++ b/suncore/sim/scenario.py @@ -27,6 +27,7 @@ import yaml from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, StringConstraints, model_validator +from suncore.core.battery import GridChargePolicy from suncore.core.decisions import OperatingMode from suncore.sim.devices import DeviceParams from suncore.sim.house import House, HouseParams @@ -169,6 +170,22 @@ class PriceParams(BaseModel): """Local hour from which tomorrow's prices are published (the real market: afternoon).""" +class SimBatteryControl(BaseModel): + """The battery as SunCore controls it in a scenario (WP10; the inverter is + ``house.inverter``). Mapped onto ``BatterySettings`` by the runner.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + mode: OperatingMode = OperatingMode.SHADOW + reserve_pct: float = Field(default=10.0, ge=0, le=100) + bms_drift_margin_pct: float = Field(default=5.0, ge=0, le=100) + max_soc_pct: float = Field(default=100.0, ge=0, le=100) + grid_charge: GridChargePolicy = GridChargePolicy() + fallback_measured: bool = False + heartbeat_s: float = Field(default=20.0, ge=5, le=3600) + fallback_timeout_s: int = Field(default=60, ge=30, le=10_800) + + class Scenario(BaseModel): """A complete simulator scenario.""" @@ -187,6 +204,8 @@ class Scenario(BaseModel): manual: tuple[ManualEvent, ...] = () control: ControlParams = ControlParams() prices: PriceParams = PriceParams() + battery: SimBatteryControl | None = None + """WP10: SunCore controls the battery through ``house.inverter`` (``None`` = observe).""" @model_validator(mode="after") def _check(self) -> Scenario: @@ -212,6 +231,13 @@ def _check(self) -> Scenario: raise ValueError(msg) return self + @model_validator(mode="after") + def _battery(self) -> Scenario: + if self.battery is not None and self.house.inverter is None: + msg = "battery control needs house.inverter" + raise ValueError(msg) + return self + @property def steps(self) -> int: """Number of whole steps in the scenario.""" diff --git a/suncore/sim/scenarios/battery_reserve_drift.yaml b/suncore/sim/scenarios/battery_reserve_drift.yaml new file mode 100644 index 0000000..73f4295 --- /dev/null +++ b/suncore/sim/scenarios/battery_reserve_drift.yaml @@ -0,0 +1,23 @@ +# SPDX-License-Identifier: Apache-2.0 +name: battery_reserve_drift +description: A winter night on the core kostal_plenticore integration (min-SoC number only). The plan holds the battery from 22:00 to 02:00 (discharge lock) to keep energy for the morning. The BMS-reported SoC sags up to 4 %-points below the true SoC during the night. SunCore's floor is never below the effective reserve (reserve 10 % + drift margin 5 %), never lowered because of the sagging reading, read back after the REST refresh, and given back (the inverter's own 10 %) when the plan stops asking. +start: "2026-12-07T21:30:00+01:00" +duration_s: 18000 +step_s: 10 +house: + seed: 11 + load: {noise_fraction: 0.05} + battery: {capacity_wh: 10000, max_charge_w: 5000, max_discharge_w: 5000, initial_soc_pct: 32} + inverter: + adapter: kostal_plenticore + min_soc_pct: 10 + bms_cutoff_pct: 5 + max_drift_pct: 4 + drift_per_h: 1.5 + rest_refresh_s: 2 +control: + import_limit_w: 12000 +battery: + mode: automatic + reserve_pct: 10 + bms_drift_margin_pct: 5 diff --git a/suncore/sim/scenarios/grid_charge_price_level.yaml b/suncore/sim/scenarios/grid_charge_price_level.yaml new file mode 100644 index 0000000..f61f07b --- /dev/null +++ b/suncore/sim/scenarios/grid_charge_price_level.yaml @@ -0,0 +1,21 @@ +# SPDX-License-Identifier: Apache-2.0 +name: grid_charge_price_level +description: A dark winter night before a poor day, generic battery adapter with a grid-charge number, grid charging allowed by a price level (0.20) inside a 00:00-06:00 schedule. The real planner (every quarter hour), the controller and the gate run in automatic mode. The battery is charged from the grid only while the live price is inside the policy and only within the import limit; when the cheap window ends the lease ends and the battery's own settings return. +start: "2026-12-07T23:30:00+01:00" +duration_s: 23400 +step_s: 30 +house: + seed: 19 + load: {noise_fraction: 0.05} + battery: {capacity_wh: 10000, max_charge_w: 5000, max_discharge_w: 5000, initial_soc_pct: 20} + inverter: + adapter: generic + min_soc_pct: 10 +control: + import_limit_w: 8000 +battery: + mode: automatic + grid_charge: + enabled: true + max_price: 0.2 + schedule: {windows: [{start: "00:00", end: "06:00"}]} diff --git a/suncore/sim/scenarios/inverter_hang_battery.yaml b/suncore/sim/scenarios/inverter_hang_battery.yaml new file mode 100644 index 0000000..0ef8a54 --- /dev/null +++ b/suncore/sim/scenarios/inverter_hang_battery.yaml @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: Apache-2.0 +name: inverter_hang_battery +description: A cloudy spring day with a generic battery adapter. The plan holds the battery's energy (discharge lock) while PV charges it. At 11:00 the hybrid inverter hangs - battery power and SoC freeze while clouds keep moving the grid meter, and the inverter ignores every write. The battery watch must notice, release the battery and stop writing; the unconfirmed release pauses battery control until the inverter is back. +start: "2026-04-20T09:30:00+02:00" +duration_s: 14400 +step_s: 10 +house: + seed: 17 + pv: {kwp: 8.0} + load: {noise_fraction: 0.04} + battery: {capacity_wh: 10000, max_charge_w: 5000, max_discharge_w: 5000, initial_soc_pct: 30} + inverter: + adapter: generic + min_soc_pct: 10 + hang_from_s: 5400 + hang_to_s: 9000 +clouds: + - {at_s: 0, factor: 1.0} + - {at_s: 5700, factor: 0.2} + - {at_s: 5880, factor: 1.0} + - {at_s: 6060, factor: 0.25} + - {at_s: 6240, factor: 1.0} + - {at_s: 6420, factor: 0.2} + - {at_s: 6600, factor: 1.0} + - {at_s: 6780, factor: 0.3} + - {at_s: 6960, factor: 1.0} +faults: + - {kind: frozen, target: battery_power, from_s: 5400, to_s: 9000} + - {kind: frozen, target: battery_soc, from_s: 5400, to_s: 9000} +control: + import_limit_w: 12000 +battery: + mode: automatic diff --git a/suncore/sim/scenarios/kostal_rest_reserve.yaml b/suncore/sim/scenarios/kostal_rest_reserve.yaml new file mode 100644 index 0000000..f1f26c9 --- /dev/null +++ b/suncore/sim/scenarios/kostal_rest_reserve.yaml @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: Apache-2.0 +name: kostal_rest_reserve +description: kostal_plenticore with a REST write that fails silently (the integration swallows the ApiException) - the min-SoC number keeps its old value. The plan asks for grid charging (not executable over REST - shown only) and later for a discharge lock. SunCore must never write a charge set-point, notice every silent failure by the read-back after the 35 s settle time, trip after three and give the battery back. +start: "2026-12-08T00:30:00+01:00" +duration_s: 7200 +step_s: 10 +house: + seed: 13 + battery: {capacity_wh: 10000, max_charge_w: 5000, max_discharge_w: 5000, initial_soc_pct: 40} + inverter: + adapter: kostal_plenticore + min_soc_pct: 10 + rest_write_fails: true +control: + import_limit_w: 12000 + settings: {min_write_interval_s: 30} +battery: + mode: automatic + grid_charge: {enabled: true, max_price: 0.30} diff --git a/suncore/sim/scenarios/modbus_heartbeat_lost.yaml b/suncore/sim/scenarios/modbus_heartbeat_lost.yaml new file mode 100644 index 0000000..d7e6f7e --- /dev/null +++ b/suncore/sim/scenarios/modbus_heartbeat_lost.yaml @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: Apache-2.0 +name: modbus_heartbeat_lost +description: A winter evening. The plan holds the battery (discharge lock) and SunCore writes the Kostal §3.5 limits through modbus.write_register - fallback registers 1284/1286/1288 first, then 1282 = 0 with a heartbeat every 20 s. At 21:00 SunCore stops (a crash, no release). The inverter must fall back to its own limits within register 1288 (60 s) and cover the house again. +start: "2026-12-07T20:00:00+01:00" +duration_s: 7200 +step_s: 10 +house: + seed: 7 + load: {noise_fraction: 0.05} + battery: {capacity_wh: 10000, max_charge_w: 5000, max_discharge_w: 5000, initial_soc_pct: 60} + inverter: + adapter: kostal_modbus + min_soc_pct: 10 + external_control: 2 + byte_order: little +control: + import_limit_w: 12000 +battery: + mode: automatic + fallback_measured: true + heartbeat_s: 20 + fallback_timeout_s: 60 diff --git a/tests/safety/test_battery_gate.py b/tests/safety/test_battery_gate.py index 55bb60c..dcb143d 100644 --- a/tests/safety/test_battery_gate.py +++ b/tests/safety/test_battery_gate.py @@ -562,3 +562,17 @@ async def test_a_device_never_sees_the_battery_path() -> None: make_intent(SwitchAction(on=True), asset_id="pool", ts=r.clock.now) ) assert keys(decision) == ["safety.shadow_mode"] # no mode for the device: shadow + + +async def test_a_new_takeover_supersedes_the_release_check() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + r.clock.advance(60) + r.at(grid_w=600, battery_w=0, soc_pct=40) + await r.submit(ReleaseAction()) + r.clock.advance(6) + r.at(grid_w=600, battery_w=0, soc_pct=40) + again = await r.submit(BatteryAction(max_discharge_w=0)) + assert again.kind is DecisionKind.ACCEPTED + decisions = [d for _ in range(4) for d in await r.tick(5)] + assert not [d for d in decisions if "safety.battery_release_unconfirmed" in keys(d)] diff --git a/tests/sim/test_battery_scenarios.py b/tests/sim/test_battery_scenarios.py new file mode 100644 index 0000000..66696aa --- /dev/null +++ b/tests/sim/test_battery_scenarios.py @@ -0,0 +1,406 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Battery control in the closed loop (WP10): the simulated inverter, the real adapters, the +real controller and gate in simulated time. Evidence comes from the simulated inverter (what it +really did), not from the gate's own opinion.""" + +from __future__ import annotations + +import asyncio +import itertools +from collections.abc import Callable +from datetime import datetime, timedelta +from typing import Any + +import pytest + +from suncore.core.battery import BatteryAction +from suncore.core.control import BatteryBand, Plan, PlanInterval +from suncore.core.decisions import Decision, DecisionKind, ReleaseAction +from suncore.sim.inverter import SimInverter +from suncore.sim.runner import RunResult, ScenarioRunner +from suncore.sim.scenario import load_scenario +from tests.sim.helpers import catalog + +pytestmark = pytest.mark.simulator + +QUARTER = timedelta(minutes=15) + + +def rolling_plan(band: Callable[[datetime], BatteryBand | None]) -> Callable[[datetime], Plan]: + """A fresh plan every quarter hour whose battery band comes from ``band(now)``.""" + + def provider(now: datetime) -> Plan: + start = now - timedelta( + minutes=now.minute % 15, seconds=now.second, microseconds=now.microsecond + ) + return Plan( + created_at=start, + source="heuristic", + intervals=(PlanInterval(start=start, end=start + QUARTER, battery=band(now)),), + ) + + return provider + + +def keys(decision: Decision) -> list[str]: + return [r.key for r in decision.reasons] + + +def battery_actions(runner: ScenarioRunner, kind: DecisionKind) -> list[Decision]: + return [d for d in runner.battery_decisions() if d.kind is kind] + + +async def play( + name: str, + plan: Callable[[datetime], Plan], + *, + actions: dict[float, Callable[[ScenarioRunner], Any]] | None = None, + **kw: Any, +) -> tuple[RunResult, ScenarioRunner, SimInverter]: + runner = ScenarioRunner(load_scenario(name), catalog(), plan_provider=plan, **kw) + for at_s, action in (actions or {}).items(): + runner.at(at_s, action) + await runner.start() + inverter = runner.inverter + assert inverter is not None + result = await runner.run() + await runner.close() + return result, runner, inverter + + +# --- modbus_heartbeat_lost ------------------------------------------------------------------- + + +async def _crash(runner: ScenarioRunner) -> None: + assert runner.stack is not None + await runner.stack.crash() + + +@pytest.fixture(scope="module") +def heartbeat() -> tuple[RunResult, ScenarioRunner, SimInverter]: + lock = rolling_plan(lambda _now: BatteryBand(discharge_lock=True)) + return asyncio.run(play("modbus_heartbeat_lost", lock, actions={3600: _crash})) + + +def test_modbus_arms_the_fallback_then_locks_with_a_heartbeat( + heartbeat: tuple[RunResult, ScenarioRunner, SimInverter], +) -> None: + result, runner, inverter = heartbeat + accepted = battery_actions(runner, DecisionKind.ACCEPTED) + assert accepted, [keys(d) for d in runner.battery_decisions()][:5] + assert accepted[0].intent.action == BatteryAction(max_discharge_w=0) + writes = [w for w in inverter.log.writes if w[1] == "modbus"] + addresses = [w[2]["address"] for w in writes] + assert addresses[:3] == [1284, 1286, 1288] # the fallback first + assert inverter.registers[1284] == inverter.own_charge_w + assert inverter.registers[1286] == inverter.own_discharge_w + assert inverter.registers[1288] == 60 + # The heartbeat re-writes 1280/1282 every 20 s while the lease holds (first hour). + start = runner.scenario.start + limit_writes = [ + w[0] for w in writes if w[2]["address"] == 1282 and w[0] < start + timedelta(hours=1) + ] + gaps = [(b - a).total_seconds() for a, b in itertools.pairwise(limit_writes)] + assert gaps + assert max(gaps) <= 30 + # While SunCore held the lock the inverter never fell back and never discharged. + hour = [ + s for s in result.steps if start + timedelta(minutes=10) <= s.t < start + timedelta(hours=1) + ] + assert all(s.battery_w > -50 for s in hour) + assert not any( + active for t, active in inverter.log.fallback_active if t < start + timedelta(hours=1) + ) + + +def test_a_dead_suncore_falls_back_within_the_timer( + heartbeat: tuple[RunResult, ScenarioRunner, SimInverter], +) -> None: + result, runner, inverter = heartbeat + start = runner.scenario.start + crash = start + timedelta(hours=1) + last_write = max(w[0] for w in inverter.log.writes if w[0] <= crash + timedelta(seconds=10)) + fell_back = [t for t, active in inverter.log.fallback_active if active] + assert fell_back + assert fell_back[0] > crash - timedelta(seconds=10) + assert (fell_back[0] - last_write).total_seconds() <= 60 + runner.scenario.step_s + # The inverter covers the house again with its own limits (the armed fallback). + after = [s for s in result.steps if s.t > fell_back[0] + timedelta(minutes=1)] + assert after + assert all(s.battery_w < -100 for s in after if s.soc_pct > 15) + assert not [w for w in inverter.log.writes if w[0] > crash + timedelta(seconds=30)] + + +# --- battery_reserve_drift ----------------------------------------------------------------------- + + +def _night_lock(now: datetime) -> BatteryBand: + local = now.astimezone(now.tzinfo) + hold = local.hour >= 22 or local.hour < 2 + return BatteryBand(discharge_lock=hold) + + +@pytest.fixture(scope="module") +def drift() -> tuple[RunResult, ScenarioRunner, SimInverter]: + return asyncio.run(play("battery_reserve_drift", rolling_plan(_night_lock))) + + +def test_the_floor_is_never_below_the_reserve_and_never_follows_the_sagging_reading( + drift: tuple[RunResult, ScenarioRunner, SimInverter], +) -> None: + result, runner, inverter = drift + accepted = [ + d + for d in battery_actions(runner, DecisionKind.ACCEPTED) + if isinstance(d.intent.action, BatteryAction) + ] + assert accepted, [keys(d) for d in runner.battery_decisions()][:6] + for d in accepted: + floor = d.intent.action.min_soc_pct # type: ignore[union-attr] + assert floor is not None + assert floor >= 15 # effective reserve: reserve 10 + drift margin 5 + floors = [w for w in inverter.log.writes if w[1] == "number.sim_battery_min_soc"] + baseline = runner.scenario.house.inverter.min_soc_pct # type: ignore[union-attr] + assert all(v >= 15 or v == baseline for _, _, v in floors) + lock_writes = [v for _, _, v in floors if v >= 15] + assert 1 <= len(lock_writes) <= 3 # hysteresis: the floor is not re-written for the drift + # The reported SoC sagged below the floor without SunCore lowering it. + start = runner.scenario.start + night = [ + s + for s in result.steps + if start + timedelta(minutes=40) <= s.t < start + timedelta(hours=4, minutes=20) + ] + assert any(s.true_soc_pct is not None and s.soc_pct < s.true_soc_pct - 2 for s in night) + # No SunCore-caused discharge while the floor is held: the true SoC stays. + held = [s.true_soc_pct for s in night if s.true_soc_pct is not None] + assert max(held) - min(held) < 1.0 + + +def test_the_floor_is_given_back_when_the_plan_stops_asking( + drift: tuple[RunResult, ScenarioRunner, SimInverter], +) -> None: + result, runner, inverter = drift + releases = [ + d + for d in battery_actions(runner, DecisionKind.ACCEPTED) + if isinstance(d.intent.action, ReleaseAction) + ] + assert releases + two = runner.scenario.start.replace(hour=2, minute=0) + timedelta(days=1) + assert any(d.ts >= two for d in releases) + assert inverter.min_soc_pct == runner.scenario.house.inverter.min_soc_pct # type: ignore[union-attr] + late = [s for s in result.steps if s.t > two + timedelta(minutes=5)] + assert any(s.battery_w < -100 for s in late) # the inverter covers the house again + + +# --- kostal_rest_reserve ---------------------------------------- + + +def _rest_plan(now: datetime) -> BatteryBand: + local = now.astimezone(now.tzinfo) + if local.hour == 0: + return BatteryBand(grid_charge_max_w=3000) + return BatteryBand(discharge_lock=True) + + +@pytest.fixture(scope="module") +def rest() -> tuple[RunResult, ScenarioRunner, SimInverter, list[list[str]]]: + seen: list[list[str]] = [] + + async def look(runner: ScenarioRunner) -> None: + stack = runner.stack + assert stack is not None + view = None if stack.last is None else stack.last.battery + seen.append([] if view is None else [r.key for r in view.reasons]) + + result, runner, inverter = asyncio.run( + play("kostal_rest_reserve", rolling_plan(_rest_plan), actions={600: look, 1200: look}) + ) + return result, runner, inverter, seen + + +def test_grid_charging_over_rest_is_shown_never_written( + rest: tuple[RunResult, ScenarioRunner, SimInverter, list[list[str]]], +) -> None: + _, runner, inverter, seen = rest + assert any("controller.battery.grid_charge_unsupported" in s for s in seen) + for d in runner.battery_decisions(): + action = d.intent.action + assert not (isinstance(action, BatteryAction) and action.grid_charge_w) + assert all(w[1] == "number.sim_battery_min_soc" for w in inverter.log.writes) + + +def test_silent_rest_failures_are_caught_by_the_read_back_and_trip( + rest: tuple[RunResult, ScenarioRunner, SimInverter, list[list[str]]], +) -> None: + _, runner, inverter, _ = rest + failed = battery_actions(runner, DecisionKind.FAILED) + assert sum(keys(d) == ["safety.readback_mismatch"] for d in failed) >= 3 + assert not [ + d + for d in battery_actions(runner, DecisionKind.ACCEPTED) + if isinstance(d.intent.action, BatteryAction) + ] + tripped = [d for d in runner.battery_decisions() if "safety.repeated_failures" in keys(d)] + assert tripped + # The read-back waited for the refresh: never earlier than 35 s after the write. + for d in failed: + if keys(d) == ["safety.readback_mismatch"]: + assert (d.ts - d.intent.ts).total_seconds() >= 35 + assert inverter.min_soc_pct == 10 # nothing ever took effect + + +# --- inverter_hang_battery ---------------------------------------------------------------------- + + +@pytest.fixture(scope="module") +def hang() -> tuple[RunResult, ScenarioRunner, SimInverter]: + lock = rolling_plan(lambda _now: BatteryBand(discharge_lock=True)) + return asyncio.run(play("inverter_hang_battery", lock)) + + +def test_a_hung_inverter_is_noticed_released_and_left_alone( + hang: tuple[RunResult, ScenarioRunner, SimInverter], +) -> None: + _, runner, inverter = hang + start = runner.scenario.start + hang_from = start + timedelta(seconds=5400) + hang_to = start + timedelta(seconds=9000) + watch = {"safety.battery_frozen", "safety.battery_soc_frozen"} # B8, either reading + frozen = [d for d in runner.battery_decisions() if watch & set(keys(d))] + assert frozen, [keys(d) for d in runner.battery_decisions()] + noticed = frozen[0].ts + assert hang_from < noticed < hang_from + timedelta(minutes=25) + # Stop writing: at most the release attempt reaches the hung inverter until it is back. + during = [w for w in inverter.log.writes if noticed <= w[0] < hang_to] + assert len(during) <= 1 + assert not [ + d + for d in battery_actions(runner, DecisionKind.ACCEPTED) + if isinstance(d.intent.action, BatteryAction) and noticed <= d.ts < hang_to + ] + unconfirmed = [ + d for d in runner.battery_decisions() if "safety.battery_release_unconfirmed" in keys(d) + ] + assert unconfirmed + + +def test_cloud_flicker_does_not_make_the_battery_oscillate( + hang: tuple[RunResult, ScenarioRunner, SimInverter], +) -> None: + _, runner, inverter = hang + hours = runner.scenario.duration_s / 3600 + accepted = battery_actions(runner, DecisionKind.ACCEPTED) + assert len(accepted) <= 2 * hours # a lock and its release per hour at most + assert len(inverter.log.writes) <= 3 * hours + + +# --- grid_charge_price_level (planner + controller + gate, automatic) --- + + +PLAN_EVERY_STEPS = 30 # 15 minutes at 30 s per step + + +async def _grid_charge_run() -> tuple[RunResult, ScenarioRunner, SimInverter, list[Plan]]: + from dataclasses import replace # noqa: PLC0415 + + from suncore.app.planning import ( # noqa: PLC0415 + LiveReading, + PlanningService, + PlanningSettings, + PlanningSnapshot, + ) + from suncore.sim.planner_scenarios import situation, situation_inputs # noqa: PLC0415 + + scenario = load_scenario("grid_charge_price_level") + base = replace(situation("grid_charge_price_level"), import_limit_w=8000.0) + runner = ScenarioRunner(scenario, catalog(), import_price=base.import_price) + plans: list[Plan] = [] + + def live() -> LiveReading: + last = runner._steps[-1] if runner._steps else None + return LiveReading(soc_pct=None if last is None else last.soc_pct) + + async def collect(now, previous): # type: ignore[no-untyped-def] + soc = live().soc_pct or 20.0 + inputs = situation_inputs(replace(base, now=now, soc_pct=soc)) + return PlanningSnapshot(replace(inputs, previous=previous)) + + planning = PlanningService(collect, live, clock=runner.vt.clock, settings=PlanningSettings()) + planning.add_listener(lambda: plans.append(planning.plan)) # type: ignore[arg-type] + runner.plan_provider = planning.active_plan + await runner.start() + for index in range(scenario.steps): + if index % PLAN_EVERY_STEPS == 0: + await planning.tick() + await runner.step(index) + result = await runner.finish() + inverter = runner.inverter + assert inverter is not None + await runner.close() + return result, runner, inverter, plans + + +@pytest.fixture(scope="module") +def grid_charge() -> tuple[RunResult, ScenarioRunner, SimInverter, list[Plan]]: + return asyncio.run(_grid_charge_run()) + + +def _local_hour(t: datetime) -> float: + return t.hour + t.minute / 60 + + +def test_the_planner_plans_grid_charging_in_the_cheap_window( + grid_charge: tuple[RunResult, ScenarioRunner, SimInverter, list[Plan]], +) -> None: + _, _, _, plans = grid_charge + planned = [ + i + for p in plans + for i in p.intervals + if i.battery is not None and (i.battery.grid_charge_max_w or 0) > 0 + ] + assert planned + assert all(1 <= _local_hour(i.start) < 5 for i in planned) + + +def test_the_battery_is_charged_from_the_grid_only_inside_the_policy( + grid_charge: tuple[RunResult, ScenarioRunner, SimInverter, list[Plan]], +) -> None: + result, runner, inverter, _ = grid_charge + accepted = [ + d + for d in battery_actions(runner, DecisionKind.ACCEPTED) + if isinstance(d.intent.action, BatteryAction) and d.intent.action.grid_charge_w + ] + assert accepted, [keys(d) for d in runner.battery_decisions()][:8] + forced = [ + w for w in inverter.log.writes if w[1] == "number.sim_battery_grid_charge" and w[2] > 0 + ] + assert forced + assert all(1 <= _local_hour(t) < 5 for t, _, _ in forced) + charging = [s for s in result.steps if s.battery_w > 50 and s.pv_w < 1] + assert charging + tick = runner.scenario.step_s / 3600 * 2 # one tick plus the lease check + assert all(1 <= _local_hour(s.t) < 5 + tick for s in charging) + # The true SoC rose, and the import limit always held. + assert ( + max(s.true_soc_pct or 0 for s in charging) + > runner.scenario.house.battery.initial_soc_pct + 10 + ) + assert max(s.grid_w for s in result.steps) <= 8000 + + +def test_the_battery_gets_its_own_settings_back_after_the_window( + grid_charge: tuple[RunResult, ScenarioRunner, SimInverter, list[Plan]], +) -> None: + result, runner, inverter, _ = grid_charge + assert inverter.grid_charge_w == 0 + late = [ + s for s in result.steps if _local_hour(s.t) >= 5.1 and s.t.day != runner.scenario.start.day + ] + assert late + assert all(s.battery_w <= 50 for s in late) + hours = runner.scenario.duration_s / 3600 + assert len(battery_actions(runner, DecisionKind.ACCEPTED)) <= 4 * hours # no oscillation diff --git a/tests/sim/test_inverter.py b/tests/sim/test_inverter.py new file mode 100644 index 0000000..f00c2fb --- /dev/null +++ b/tests/sim/test_inverter.py @@ -0,0 +1,78 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The simulated hybrid inverter (WP10): own control, fallback timer, REST lag, drift, hang.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +from suncore.core.battery import ModbusByteOrder +from suncore.devices.battery.modbus_codec import float32_words, uint32_words +from suncore.sim.inverter import MIN_SOC_ID, MODBUS_HUB, MODBUS_SLAVE, InverterParams, SimInverter + +T0 = datetime(2026, 12, 7, 20, 0, tzinfo=UTC) +LE = ModbusByteOrder.LITTLE + + +def inverter(**kw: object) -> SimInverter: + return SimInverter( + InverterParams.model_validate(kw), + capacity_wh=10_000, + max_charge_w=5000, + max_discharge_w=5000, + round_trip_efficiency=0.92, + soc_max_pct=100, + initial_soc_pct=50, + start=T0, + ) + + +def write(inv: SimInverter, at: datetime, address: int, words: list[int]) -> None: + inv.write_register( + at, {"hub": MODBUS_HUB, "slave": MODBUS_SLAVE, "address": address, "value": words} + ) + + +def test_own_self_consumption_control() -> None: + inv = inverter() + assert inv.dispatch(T0, 1000, 10) == 1000 # surplus charges + assert inv.dispatch(T0, -800, 10) == -800 # deficit discharges + + +def test_the_fallback_timer_of_section_3_5() -> None: + inv = inverter(adapter="kostal_modbus") + write(inv, T0, 1284, float32_words(5000, LE)) + write(inv, T0, 1286, float32_words(5000, LE)) + write(inv, T0, 1288, uint32_words(60, LE)) + write(inv, T0, 1282, float32_words(0, LE)) + assert inv.dispatch(T0 + timedelta(seconds=30), -800, 10) == 0 # locked + assert inv.fallback_active(T0 + timedelta(seconds=61)) + assert inv.dispatch(T0 + timedelta(seconds=70), -800, 10) == -800 # fell back + + +def test_an_unarmed_fallback_stops_the_battery_and_writes_need_1080() -> None: + inv = inverter(adapter="kostal_modbus") + write(inv, T0, 1288, uint32_words(60, LE)) + write(inv, T0, 1282, float32_words(0, LE)) + assert inv.dispatch(T0 + timedelta(seconds=90), -800, 10) == 0 # fallback limits are 0 + off = inverter(adapter="kostal_modbus", external_control=0) + write(off, T0, 1282, float32_words(0, LE)) + assert off.registers[1282] == 5000 # ignored without external battery management + + +def test_rest_lag_silent_failure_drift_and_hang() -> None: + inv = inverter(adapter="kostal_plenticore", rest_refresh_s=5) + inv.set_number(T0, MIN_SOC_ID, 40) + shown = {e: v for e, v, _ in inv.states(T0 + timedelta(seconds=1))} + assert shown[MIN_SOC_ID] == "10.0" + shown = {e: v for e, v, _ in inv.states(T0 + timedelta(seconds=6))} + assert shown[MIN_SOC_ID] == "40.0" + failing = inverter(adapter="kostal_plenticore", rest_write_fails=True) + failing.set_number(T0, MIN_SOC_ID, 40) + assert failing.min_soc_pct == 10 + drifting = inverter(max_drift_pct=4, drift_per_h=2) + for i in range(360): + drifting.dispatch(T0 + timedelta(seconds=10 * i), 0, 10) + assert drifting.reported_soc_pct < drifting.soc_pct - 1.5 + hung = inverter(hang_from_s=0, hang_to_s=600) + hung.battery_w = 1234 + assert hung.dispatch(T0, -500, 10) == 1234 diff --git a/tests/sim/test_scenario.py b/tests/sim/test_scenario.py index 462eb14..006f6da 100644 --- a/tests/sim/test_scenario.py +++ b/tests/sim/test_scenario.py @@ -9,14 +9,19 @@ pytestmark = pytest.mark.simulator BUNDLED = [ + "battery_reserve_drift", "climate_counter_only", "climate_measured_slow", "climate_min_run", "cloud_flicker", + "grid_charge_price_level", "grid_limit", "ha_disconnect", "inverter_hang", + "inverter_hang_battery", + "kostal_rest_reserve", "manual_override", + "modbus_heartbeat_lost", "negative_prices", "planner_in_shadow", "sensor_dropout", @@ -146,5 +151,7 @@ def test_outdoor_temperature_is_a_daily_cosine() -> None: def test_closed_loop_scenarios_declare_devices(name: str) -> None: sc = load_scenario(name) controlled = [d for d in sc.devices if d.template is not None] - assert controlled, "a closed-loop scenario controls at least one device" + assert controlled or sc.battery is not None, ( + "a closed-loop scenario controls at least one device or the battery" + ) assert sc.step_s <= 60 # the controller tick (ControlSettings.tick_s <= 60) From d916ef5cecdcd42af6e1c8fac8a0ce2be3cf4d89 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 21:54:16 +0000 Subject: [PATCH 08/16] feat(safety,devices): battery control through the gate with the ADR-0013 invariants (WP10) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ADR-0011 addendum: control-safety sign-off - the battery_not_supported rejection is lifted only for intents to the configured battery adapter that pass B1-B9; it stays for observe-only batteries and every other asset id - architecture §4: the battery path (controller band -> BatteryAction, gate invariants, hardware fallback, lease and heartbeat, release paths) - plan phase-4 deviations for PR 4-G; templates README (battery templates, driver, register map, hardware_fallback) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- docs/adr/0011-two-control-layers.md | 9 +++++++++ docs/architecture.md | 18 ++++++++++++++++++ docs/plans/phase-4.md | 26 ++++++++++++++++++++++++++ templates/README.md | 18 +++++++++++++----- 4 files changed, 66 insertions(+), 5 deletions(-) diff --git a/docs/adr/0011-two-control-layers.md b/docs/adr/0011-two-control-layers.md index 47c1b72..6299dca 100644 --- a/docs/adr/0011-two-control-layers.md +++ b/docs/adr/0011-two-control-layers.md @@ -97,6 +97,15 @@ Decision: ADR-0013 ("Battery as a controlled asset"), which must be accepted before Phase 4 WP10 lifts the rejection. +Sign-off 2026-10-25 (`control-safety`, PR 4-G, Phase 4 WP10): the blanket rejection of +`BatteryAction` is lifted **only for intents to the configured battery adapter** that pass the +ADR-0013 invariants B1-B9 (`safety/battery.py`, property-tested; gate path +`SafetyGate._submit_battery`, lease in `poll()`; scenarios `modbus_heartbeat_lost`, +`battery_reserve_drift`, `kostal_rest_reserve`, `inverter_hang_battery`, +`grid_charge_price_level`). Without a battery adapter (observe-only, no battery model) or for any +other asset id the gate still answers `safety.battery_not_supported` and writes nothing. The +invariant table is in the PR 4-G description. + Consequence: contracts can be published ahead of their write path without weakening the single-writer guarantee; a boundary/unit test asserts that every `ActionKind` is either handled by the invariants or rejected with its diff --git a/docs/architecture.md b/docs/architecture.md index 36db97f..3d1f125 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -223,6 +223,24 @@ applies, settles, reads back and logs `accepted` or `failed`. The write path re- stop, mode, watchdog and hold right before `apply()` under a per-device lock. The free surplus is claimed per `GateInputs` snapshot, so several intents of one tick cannot together exceed it. +**The battery** (Phase 4 WP10, ADR-0013) is the asset `battery` with its own path through the +same gate. The controller turns the band of a *fresh* plan interval into a `BatteryAction` +(limits, not set-points; `None` = the adapter's baseline found at takeover): `grid_charge_max_w` +-> `grid_charge_w` where the adapter can force charging, `discharge_lock` -> `max_discharge_w` += 0 or a min-SoC floor at the live SoC (never below `effective_reserve_pct`), nothing planned -> +`ReleaseAction`. The gate judges it with the battery invariants B1-B9 (`safety/battery.py`): +floor never below the reserve or the user's own floor, grid charging only from a fresh planned +interval inside the grid-charge policy at the **live** price and within battery, adapter, band +and import-headroom bounds, a discharge lock only when planned, the import limit for every +action that can cause import, live ranges and capabilities, write only on change, mandatory +read-back. An adapter with a hardware fallback (Kostal §3.5) gets it armed and read back before +the first limit and is capped at assisted until `battery.fallback_measured`. An accepted state is +a **lease**: `gate.poll()` re-judges it every tick and restores the baseline when the mode, the +watchdog (site or battery scope, `gate.check_battery`: frozen battery power or SoC), stale inputs +or any invariant says so; the adapter's heartbeat re-writes only while it holds. Devices keep the +Phase 3 rule "no SunCore-caused import" unchanged, and the charging power of a forced grid charge +is never surplus for them. + Deviation events: the controller reports when actual SoC, PV or load leave the plan's assumption corridor; the scheduler then re-plans early (rate limited to once per 5 minutes) from Phase 4 on. diff --git a/docs/plans/phase-4.md b/docs/plans/phase-4.md index 0d5ac99..d3ba799 100644 --- a/docs/plans/phase-4.md +++ b/docs/plans/phase-4.md @@ -566,6 +566,32 @@ shadow and assisted run is the acceptance test. - WP9: the controller applies a plan's battery band only while an interval covers `now`, and judges `priority_until_soc_pct` against the live SoC. +- PR 4-G (WP10, battery control; `control-safety`): + - **Battery mode** lives in `operation.battery_mode` (additive) instead of a `device_modes` + entry under the reserved id: a device may already be called `battery`, and the gate learns it + through `ModeProvider.battery_mode()`. The identity record is a separate `safety_state` key. + A configured device with the id `battery` keeps the battery observe-only (logged). + - **Heartbeat** is driven by the gate's `poll()` (every tick, timed from the write) and executed + by the adapter's `keep_alive()`, not by a timer task inside the adapter: a hung control loop + stops the heartbeat, so the inverter's own fallback takes over (ADR-0013 5B intent). + - **Discharge lock** is judged by B4 against the deficit *now*; the lease re-judges it every + tick, so a cap that becomes a lock in the evening needs the plan's `discharge_lock` then. + - **Reserve**: SunCore never holds a permanent min-SoC floor; the effective reserve is the floor + of every min SoC it writes, and B1 also forbids writing below the user's own inverter floor. + The devices' reserve guard (`GateInputs.reserve_soc_pct`) is `effective_reserve_pct` when a + battery model exists. + - **Grid charging needs an import limit** (B2: an unknown bound means no grid charging). + - Power caps are never written above the baseline (B6), so SunCore only ever restricts. + - A manual change of the held limits is an override: SunCore lets go without writing and holds + off until the default override time (next day 04:00). + - After a release of an adapter without hardware fallback the gate reads back once after the + settle time; a mismatch pauses battery control (`safety.battery_release_unconfirmed`). + - Templates gained `driver` (`generic`, `kostal_plenticore`, `kostal_modbus`), a Modbus + register map and the capability `hardware_fallback` (additive in schema v1); the adapters read + a core `BatteryAdapterSpec` (`suncore.devices` imports only `core`). + - Kostal Modbus §3.5 runs in the simulator only (external battery management is not enabled on + the maintainer's inverter); it is capped at assisted until `battery.fallback_measured`. + ## 7. Out of scope for Phase 4 Full plan chart with device Gantt, zoom/pan, history, savings vs baselines, what-if and diff --git a/templates/README.md b/templates/README.md index a1eb70c..d0694e2 100644 --- a/templates/README.md +++ b/templates/README.md @@ -35,6 +35,9 @@ drift). | forecast | `forecast_solar.pv` | Forecast.Solar (core), hourly Wh through `energy/solar_forecast` (only if linked in the Energy dashboard), P50 only | from integration source, `UNVERIFIED` timestamp semantics | | forecast | `open_meteo_solar_forecast.pv` | Open-Meteo Solar Forecast (HACS), `wh_period_15m` (Wh per 15 min), P50 only | from integration source (tag 0.1.33) | | forecast | `generic.pv_forecast` | any sensor attribute with points `{start, power_w}` (copy and adapt for others) | SunCore's own contract | +| battery | `generic.battery` | battery limits through number entities (min SoC, charge/discharge caps, grid-charge power), driver `generic` | generic, simulator only (`UNVERIFIED`: no hardware) | +| battery | `kostal.plenticore` | KOSTAL PLENTICORE through the core integration: min SoC only (reserve floor, discharge lock), driver `kostal_plenticore` | from integration source; no write made on hardware yet | +| battery | `kostal.plenticore_g3_modbus` | KOSTAL PLENTICORE G3 §3.5 limits through `modbus.write_register` with the inverter's fallback timer, driver `kostal_modbus` | from the vendor document; simulator only, capped at assisted until the fallback is measured | | region | `de` | Germany: EUR, `Europe/Berlin`, no remuneration at negative prices for new PV | law text `UNVERIFIED` here | | region | `generic` | neutral international profile | – | @@ -69,8 +72,9 @@ unverified: [] # facts you could not verify; required if tes `power_setpoint`, `temperature_setpoint`, `hvac_modes`, `preset_modes`, `fan_modes`, `price_now`, `price_curve`, `pv_curve`, `pv_quantiles`, `feed_in_tiers`, `negative_price_rule`, and for batteries `battery_soc`, `min_soc_limit`, `charge_limit`, - `discharge_limit`, `grid_charge`, `battery_modes`. Where a validator can check the claim (for example - `pv_quantiles` needs `p10_field` and `p90_field`) an unfounded one is an error. + `discharge_limit`, `grid_charge`, `battery_modes`, `hardware_fallback`. Where a validator can + check the claim (for example `pv_quantiles` needs `p10_field` and `p90_field`) an unfounded + one is an error. - Devices write through the role(s) named by `defaults.control` (`on_off`, `steps`, `relays` (1–3 switches), `continuous` in W/A/%, `setpoint` with a maximum shift, `mode`). Mode of operation (shadow/assisted/automatic) is **not** part of a template or a device; the `operation` @@ -104,8 +108,12 @@ unverified: [] # facts you could not verify; required if tes `grid_charge_power` (number in W, kW or %), `mode` (select; every option has a `meaning`: `auto` - exactly one, the release baseline -, `force_charge`, `no_discharge`, `no_charge`, `other`) or `force_charge` (switch). The control kind - fixes the entity domain (`number`, `select`, `switch`). Every write goes through the - safety gate; a battery starts in shadow mode like every device. + fixes the entity domain (`number`, `select`, `switch`). `driver` picks the adapter: + `generic` (default, the `controls`), `kostal_plenticore` (exactly one `min_soc` control) or + `kostal_modbus` (no `controls`; a `modbus` register map and the read-back roles + `external_control`, `charge_limit`, `discharge_limit`, `fallback_charge_limit`, + `fallback_discharge_limit`, `fallback_timeout`, `own_charge_limit`, `own_discharge_limit`). + Every write goes through the safety gate; a battery starts in shadow mode like every device. - Do not invent attributes, services or registers. Cite the integration source or vendor document in `source`, otherwise list the fact under `unverified`. - Every template needs a simulator conformance scenario under @@ -148,6 +156,6 @@ Every addition is recorded below with the SunCore version that introduced it. | 0.3.0 (unreleased, Phase 2) | Initial schema v1 after the ADR-0012 review: matcher with `platforms`, `translation_key_pattern`, `unit_pattern`, digits in `domain`; `RoleSpec.same_device_as`; `PowerModelDefault` without required `nominal_w`, `counter_update_s`; `defaults.control` as `ControlSpec` (`on_off`, `steps`, `continuous`, `setpoint`, `mode`); `hysteresis_w`, `hysteresis_delay_s`, `settle_s`; `series` (`attribute` or `action`) for tariff and forecast, `price_includes`, optional `resolution_min` for tariffs; closed `capabilities` vocabulary; `min_app_version`; loader lint for unknown kind directories. | | 0.3.0 (unreleased, Phase 2) | `region.currency` is optional for `country: generic` (`None` = currency of the Home Assistant configuration). | | 0.4.0 (unreleased, Phase 3) | New `defaults.control` kind `relays` (additive union member, ADR-0012 policy): 1–3 switch roles (`roles`) and `steps`, each step naming the relays that are on (`relays`) and the power it draws (`power_w`, strictly increasing, relay sets distinct). `DeviceConfig` accepts the same control. Used by `generic.water_heater_relays`. | -| 0.5.0 (unreleased, Phase 4) | New template kind `battery` (`battery.schema.json`): `roles`, `controls` (union on `kind`: `min_soc`, `max_charge`, `max_discharge`, `grid_charge_power` numbers; `mode` select with option meanings; `force_charge` switch), optional `settle_s`. New capabilities `battery_soc`, `min_soc_limit`, `charge_limit`, `discharge_limit`, `grid_charge`, `battery_modes`. `series` of `source: attribute` takes an optional `list_path` for the generic attribute adapter and an optional `shape` (`list` default, or `mapping` for `{iso_timestamp: value}` attributes such as Forecast.Solar `wh_hours` and Open-Meteo Solar Forecast `wh_period_15m`; `fields` then holds only `value_unit`, so `fields.timestamp_field`/`value_field` became optional and are required only for lists of point objects). Tariff `price_unit` and `price_series.fields.value_unit` may be per MWh (`{currency}/MWh`, `EUR/MWh`); the value unit's currency must match `price_unit`'s (or be `{currency}`), and adapters convert to currency/kWh (`price_unit_factor`: MWh / 1000). Battery mode option `value` is kept verbatim (no whitespace stripping). HT/NT needs no template change: time windows and prices are contract data in the `tariff` configuration section (v3). | +| 0.5.0 (unreleased, Phase 4) | New template kind `battery` (`battery.schema.json`): `roles`, `controls` (union on `kind`: `min_soc`, `max_charge`, `max_discharge`, `grid_charge_power` numbers; `mode` select with option meanings; `force_charge` switch), optional `settle_s`. New capabilities `battery_soc`, `min_soc_limit`, `charge_limit`, `discharge_limit`, `grid_charge`, `battery_modes`. `series` of `source: attribute` takes an optional `list_path` for the generic attribute adapter and an optional `shape` (`list` default, or `mapping` for `{iso_timestamp: value}` attributes such as Forecast.Solar `wh_hours` and Open-Meteo Solar Forecast `wh_period_15m`; `fields` then holds only `value_unit`, so `fields.timestamp_field`/`value_field` became optional and are required only for lists of point objects). Tariff `price_unit` and `price_series.fields.value_unit` may be per MWh (`{currency}/MWh`, `EUR/MWh`); the value unit's currency must match `price_unit`'s (or be `{currency}`), and adapters convert to currency/kWh (`price_unit_factor`: MWh / 1000). Battery mode option `value` is kept verbatim (no whitespace stripping). HT/NT needs no template change: time windows and prices are contract data in the `tariff` configuration section (v3). Battery templates (WP10, additive): `driver` (`generic` default, `kostal_plenticore`, `kostal_modbus`), `modbus` register map (`kostal_modbus` only), capability `hardware_fallback`. | | 0.5.0 (unreleased, Phase 4, WP4) | Tariff price curves (all additive): `series.fields.end_field` (slot end, slot length = `end - start`; lists only); action series take `date_field` (one call per delivery date, excludes `start_field`/`end_field`) with an optional `date_tz` (IANA zone of that delivery day, e.g. Nord Pool's CET day; default the site's zone) and `params` (`name`, `required`, `description` i18n key: request fields the user supplies in the tariff configuration, e.g. Nord Pool `config_entry`, `areas`, `currency`); `response_path` may start with `*` (every entry of the response, e.g. `*` for `{area: [...]}`); the read-only action allowlist gains `nordpool.get_prices_for_date`. The `tariff` configuration section (v3) gains optional `import.role_entities`, `import.action_params`, `import.series_key` and `import.price_includes` (the user's statement overriding the template's classification). Eight tariff templates: `tibber.price` (updated), `nordpool.price`, `entsoe.price`, `entsoe.price_mwh`, `epex_spot.total_price`, `epex_spot.market_price`, `octopus_energy.rates`, `generic.price_list`. The currency symbols `€`/`£` that EPEX Spot puts in front of `/kWh` need no schema change: the matcher lists the literal units and `suncore.tariff.units.normalise_price_unit` maps them to ISO codes. | | 0.5.0 (unreleased, Phase 4, PV forecasts) | Forecast templates: `series.source: energy_solar_forecast` (new union member, `fields` holds only `value_unit`, optional `missing_is_zero`) for the Energy dashboard's `energy/solar_forecast`; optional `fallback_series` (an `action` series) used when the attribute yields nothing. New templates `forecast_solar.pv`, `open_meteo_solar_forecast.pv`, `generic.pv_forecast`; `solcast.pv` gained the optional roles `forecast_d3`, `forecast_d4` and the fallback action `query_forecast_data`. | From 4e2b94c01b0979367c18a45722d8e0f0939c607d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 22:00:29 +0000 Subject: [PATCH 09/16] docs: STATUS for PR 4-G WP10 (battery control), UNVERIFIED rows for Kostal Modbus and REST Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- docs/STATUS.md | 62 +++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 11 deletions(-) diff --git a/docs/STATUS.md b/docs/STATUS.md index de6bca3..c5caf32 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -3,12 +3,11 @@ Read this first in every session, then `CLAUDE.md` (once it exists) and the ADRs relevant to your task. Keep it short; history lives in git. -**Last update:** 2026-10-24 · **Phase:** 4 in progress – PR 4-A contracts, 4-B storage, 4-C -tariffs, 4-D PV forecast, 4-E load forecast and risk model, 4-F planner and runtime (WP8, WP9; -battery control WP10 next); Phase 3 (3-A +**Last update:** 2026-10-25 · **Phase:** 4 in progress – PR 4-A contracts, 4-B storage, 4-C +tariffs, 4-D PV forecast, 4-E load forecast and risk model, 4-F planner and runtime (WP8, WP9), +4-G battery control (WP10; UI and docs 4-H next); Phase 3 (3-A `phase-3/a-safety`, 3-B `phase-3/b-controller`, 3-C `phase-3/c-ui`) implemented, waiting for the -maintainer's shadow test · **Branch:** `phase-4/f-planner` (stacked on `phase-4/e-load-risk`, merged -with `phase-4/c-tariff`) +maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4/f-planner`) ## Done @@ -99,6 +98,42 @@ with `phase-4/c-tariff`) - Follow-ups: the weights come from the *uncalibrated* sources' MAE (a calibrated source is under-weighted until a calibrated accuracy is scored); no UI yet (4-H). +- **Phase 4 – PR 4-G (WP10, battery control; branch `phase-4/g-battery`, on 4-F; `control-safety`)**: + - Contracts (ADR-0013): `BatteryAction` = the full desired state, `None` = the adapter's baseline + (`core.battery.resolve_battery_action`), capabilities per field, live `BatteryRanges`, min SoC + rounded **up**; `core.identity.battery_identity(_token)` (asset id `battery`, adapter template, + role entities, the site's SoC/battery power, modbus hub + unit id); + `operation.battery_mode` (additive): a `battery`/`site` put that changes the identity drops it, + an import resets it, a restore keeps it only for the recorded identity, a full `operation` put + cannot raise it, `PUT /api/v1/operation/battery {mode, identity}` (404 observe-only, 409 stale); + `battery.modbus` (hub, unit id, byte order, heartbeat 20 s, fallback timer 60 s) and + `battery.fallback_measured` (additive). + - Adapters `suncore/devices/battery/` (only the gate calls `apply`, `release`, `arm_fallback`, + `keep_alive`; boundary tests): `generic` (number/select/switch roles), `kostal_plenticore` + (`Battery:MinSoc` only, settle 35 s for the silent REST write and the 30 s poll, no charge + set-point), `kostal_modbus` (§3.5 via `modbus.write_register` - a write of this adapter only, + never a read-only action; float32/U32 words in the configured order; refuses unless 1080 = 2; + 1284/1286/1288 armed and read back before any limit; heartbeat; release writes the own limits). + Templates `generic.battery`, `kostal.plenticore`, `kostal.plenticore_g3_modbus` (`driver`, + register map, capability `hardware_fallback`; schema v1 additive) with conformance scenarios. + - Safety: the blanket `safety.battery_not_supported` stays only without a battery adapter or for + other asset ids; battery intents pass B1-B9 (`safety/battery.py`, hypothesis property tests), + mode capped at assisted while the hardware fallback is not measured, mandatory read-back, a + lease re-judged every tick by `poll()` (heartbeat only while it holds), override detection, + release check, battery watch (frozen battery power / SoC), every Phase 3 release path. All + Phase 3 safety tests unchanged and green. + - Controller: `controller/battery.py` turns the band of a fresh plan interval into intents + (grid charging, discharge lock as `max_discharge_w` 0 or a min-SoC floor, release), hysteresis, + one intent per minute, `controller.battery.grid_charge_unsupported` for Kostal REST; a held + forced grid charge is never surplus for the devices. + - App: `ControlStack` battery wiring, control state `battery`, devices' reserve guard = + `effective_reserve_pct` with a battery model; OpenAPI and frontend types regenerated, no UI. + - Simulator: `sim/inverter.py` (own control as fallback, BMS drift, REST lag and silent failures, + §3.5 fallback timer, hang); scenarios `modbus_heartbeat_lost`, `battery_reserve_drift`, + `kostal_rest_reserve`, `inverter_hang_battery`, `grid_charge_price_level` (real planner, + controller and gate in automatic mode). + - Decisions and deviations: plan §"Deviations during implementation" (PR 4-G). + - **Phase 4 – PR 4-F, part WP8 planner (branch `phase-4/f-planner`, on 4-E merged with 4-C)**: - `suncore/planner/` (depends on `core` only; boundary test extended; `mypy --strict`): `inputs.py` (`build_inputs`: pure snapshot on the 15-minute grid now → +48 h from the @@ -513,10 +548,12 @@ with `phase-4/c-tariff`) (WP3) → 4-C tariffs (WP4) and 4-D PV forecast (WP5) → 4-E load + risk (WP6, WP7) → 4-F planner and runtime (WP8, WP9) → 4-G battery control (WP10) → 4-H frontend + docs (WP11, WP13); 4-I ML load (WP12, optional, after 4-E). Merge only after the Phase 3 acceptance. -- **ADR-0013 must be accepted before WP10** (4-G). Its contract changes `BatteryBand.grid_charge_max_w` - / `discharge_lock` landed with WP8 (additive, planner-only, the controller ignores them); - `BatteryAction` `None` = baseline and `battery_identity` land at the start of 4-G. -- **WP9 done** (4-F, see Done); next: 4-G battery control (WP10, ADR-0013 first). +- **WP10 done** (4-G, see Done); next: 4-H UI and docs (battery card with mode, identity and the + assisted cap; wizard step for the battery adapter incl. enabling the Kostal number and the modbus + YAML; WP13 docs). ADR-0013 file still says "proposed" - record the maintainer's acceptance. +- Maintainer questions from 4-G (PR description): permanent reserve floor on the inverter or not; + grid charging on the Kostal (generic force-charge entity or a §3.4 ADR); the fallback timer + measurement procedure for `battery.fallback_measured`. - **PR 4-C (WP4, branch `phase-4/c-tariff`)**: `suncore/tariff/` - a template-driven price adapter (`engine.py`: action or attribute source, list or mapping shape, per-MWh conversion, native grid from `end - start` or the timestamp spacing, 15/60-minute mixes as segments, gaps `None`, DST @@ -733,8 +770,11 @@ with `phase-4/c-tariff`) | Energy-Charts and aWATTar APIs and terms (not shipped in Phase 4) | `research/integrations.md` | session with network access (Phase 6) | | Open-Meteo azimuth convention in a live response (code: 0 = south, OpenAPI text contradicts); separate terms page (README only) | `research/integrations.md` | live request; maintainer reads the terms page | | Kostal REST battery/grid power sign; `ActivePowerLimitation` semantics; live entity ids | `research/integrations.md` | maintainer's HA (enable the entities, compare with the inverter display) | -| Kostal Modbus external battery management not enabled on the maintainer's inverter; how it is enabled; §3.5 fallback timer behaviour | `research/kostal-plenticore-modbus.md`, ADR-0013 | maintainer enables it and measures; `kostal_modbus` capped at assisted until then | -| Creating a modbus hub from the HA UI (else YAML) | `research/ha-websocket-api.md` | maintainer's HA | +| Kostal Modbus external battery management not enabled on the maintainer's inverter; how it is enabled; §3.5 fallback timer behaviour (the `kostal_modbus` adapter and its fallback are exercised in the simulator only, scenario `modbus_heartbeat_lost`) | `research/kostal-plenticore-modbus.md`, ADR-0013, `suncore/devices/battery/kostal_modbus.py` | maintainer enables it and measures, then sets `battery.fallback_measured`; capped at assisted until then | +| Kostal Modbus U32 word order of register 1288 assumed equal to the float order (register 5); modbus sensor `scan_interval` vs the adapter's 15 s settle time | `suncore/devices/battery/modbus_codec.py`, `templates/battery/kostal.plenticore_g3_modbus.yaml` | first Modbus write on the maintainer's inverter | +| Kostal REST: battery/grid power sign (the site's `invert_sign`), the min-SoC read-back timing after the forced refresh (35 s settle assumed), whether out-of-range values are clamped or rejected; the number is disabled by default | `suncore/devices/battery/kostal_plenticore.py`, `templates/battery/kostal.plenticore.yaml` | maintainer enables "Battery min SoC" and watches the first assisted write | +| Creating a modbus hub from the HA UI (else YAML); the hub name and unit id the user configures | `research/ha-websocket-api.md`, `battery.modbus` | maintainer's HA | +| Generic battery adapter (numbers/select/switch) and the battery watch thresholds (frozen 600 s / 50 W / grid 500 W, SoC frozen after 3 % of the capacity moved) | `suncore/devices/battery/generic.py`, `suncore/safety/battery.py` | first real battery integration; shadow run | | Supervisor proxy passes `recorder/*` and `energy/*` commands | `research/ha-websocket-api.md` | first Phase 4 run on HA OS | | Supervisor proxy forwards `recorder/statistics_during_period` (the 4-B rebuild logs a warning and retries) | `suncore/ha/statistics.py` | first run on HA OS | | `change`/`sum` rows of real energy counters (the rebuild reads them as verified from source, not tested against live counters); `backup_exclude` accepts the glob `timeseries.db.corrupt*` | `suncore/ha/statistics.py`, `addon/*/config.yaml` | maintainer's HA with an energy counter; a backup on HA OS | From 828d1dfde9b975276004cf46417f51df0972329d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 05:52:07 +0000 Subject: [PATCH 10/16] fix(safety,devices): a battery release is complete only when the baseline reads back (review B1, M3) - the battery release keeps the runtime under control with the ORIGINAL baseline until a read-back shows it (or the user set a third value, which is kept without a write); a failed release write or a read-back that still shows SunCore's state is retried with back-off (30 s doubling to 10 min) - also during an emergency stop - and never adopted as a baseline; while it is pending no takeover, write or heartbeat happens (latched in the runtime, so a healthy watchdog tick cannot clear it) - a failed battery write is pending, so a release never mistakes SunCore's partial state for the user's - generic/kostal_plenticore release raises on an unavailable entity instead of reporting success, and restores the user's own select option / switch state (review minor 4) - regression tests from the reviewer's probes (many check_battery ticks, stuck lock, new takeover, unavailable REST number); inverter_hang_battery asserts the latch until hang_to Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- frontend/src/lib/i18n/locales/de.json | 5 +- frontend/src/lib/i18n/locales/en.json | 5 +- suncore/devices/battery/generic.py | 59 +++-- suncore/safety/gate.py | 202 +++++++++++++----- tests/devices/battery/test_battery_drivers.py | 56 +++++ tests/safety/test_battery_gate.py | 116 ++++++++-- tests/sim/test_battery_scenarios.py | 19 +- 7 files changed, 368 insertions(+), 94 deletions(-) diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index fb83eba..551035d 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -587,7 +587,9 @@ "safety.release_pending": "Nicht geschrieben: Das Gerät wird gleich in den vorherigen Zustand zurückgesetzt.", "safety.superseded": "Schreiben nicht bestätigt: Das Gerät wurde inzwischen in den vorherigen Zustand zurückgesetzt.", "safety.battery_reserve": "Nicht eingeschaltet: Der Akku entlädt bei {soc_pct} % (Reserve {reserve_pct} %).", - "safety.battery_release_unconfirmed": "Nach der Freigabe zeigt der Akku seine eigenen Einstellungen nicht wieder: Akkusteuerung pausiert, bitte den Wechselrichter prüfen.", + "safety.battery_release_unconfirmed": "Der Akku zeigt seine eigenen Einstellungen noch nicht wieder: SunCore versucht weiter, ihn zurückzugeben, und schreibt bis dahin nichts anderes. Bitte den Wechselrichter prüfen.", + "safety.battery_release_check": "Prüfe, ob der Akku wieder seine eigenen Einstellungen zeigt.", + "safety.battery_release_confirmed": "Der Akku zeigt wieder seine eigenen Einstellungen: SunCore hat ihn freigegeben.", "safety.battery_range_unknown": "Der erlaubte Bereich von {field} ist unbekannt (Entität nicht verfügbar); nichts geschrieben.", "safety.climate_off": "Nicht eingeschaltet: Das Gerät ist aus und Einschalten ist für dieses Gerät nicht erlaubt.", "safety.comfort_band": "Sollwert {setpoint_c} °C liegt außerhalb des Komfortbands {min_c}–{max_c} °C.", @@ -944,7 +946,6 @@ "safety.battery_full": "Der Akku steht bei {soc_pct} %, sein Maximum ist {max_soc_pct} %: kein Netzladen.", "safety.battery_frozen": "Die Akkuleistung bleibt bei {battery_w} W, während sich die Netzleistung ändert: Akkusteuerung pausiert.", "safety.battery_fallback_unconfirmed": "Die Rückfallgrenzen des Wechselrichters ließen sich nicht bestätigen; keine Akku-Grenze geschrieben.", - "safety.battery_fallback_unverified": "Der Rückfall-Timer des Wechselrichters ist noch nicht gemessen: der Akku läuft höchstens im Assistenzmodus.", "safety.battery_import_limit_unknown": "Netzladen braucht eine eingestellte Bezugsgrenze.", "safety.battery_import_limit": "Das Haus würde {projected_w} W beziehen, über der Bezugsgrenze von {limit_w} W.", "safety.battery_inputs_stale": "Die Messwerte sind zu alt, um die Akku-Grenzen zu halten: zurückgegeben.", diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index e17840d..62a10a4 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -587,7 +587,9 @@ "safety.release_pending": "Not written: the device is about to be returned to its previous state.", "safety.superseded": "Write not confirmed: the device was returned to its previous state in the meantime.", "safety.battery_reserve": "Not switched on: the battery is discharging at {soc_pct} % (reserve {reserve_pct} %).", - "safety.battery_release_unconfirmed": "After the release the battery does not show its own settings again: battery control paused, please check the inverter.", + "safety.battery_release_unconfirmed": "The battery does not show its own settings again yet: SunCore retries giving it back and writes nothing else until it does. Please check the inverter.", + "safety.battery_release_check": "Checking that the battery shows its own settings again.", + "safety.battery_release_confirmed": "The battery shows its own settings again: SunCore has let go of it.", "safety.battery_range_unknown": "The allowed range of {field} is unknown (entity unavailable); nothing was written.", "safety.climate_off": "Not switched on: the unit is off and switching on is not allowed for this device.", "safety.comfort_band": "Set-point {setpoint_c} °C is outside the comfort band {min_c}–{max_c} °C.", @@ -944,7 +946,6 @@ "safety.battery_full": "The battery is at {soc_pct} %, its maximum is {max_soc_pct} %: no grid charging.", "safety.battery_frozen": "The battery power has stayed at {battery_w} W while the grid power changed: battery control paused.", "safety.battery_fallback_unconfirmed": "The inverter's fallback limits could not be confirmed; no battery limit was written.", - "safety.battery_fallback_unverified": "The inverter's fallback timer is not measured yet: the battery runs at most in assisted mode.", "safety.battery_import_limit_unknown": "Grid charging needs a configured grid import limit.", "safety.battery_import_limit": "The house would import {projected_w} W, above the import limit of {limit_w} W.", "safety.battery_inputs_stale": "The measurements are too old to keep holding the battery's limits: given back.", diff --git a/suncore/devices/battery/generic.py b/suncore/devices/battery/generic.py index 876c01b..9622f8f 100644 --- a/suncore/devices/battery/generic.py +++ b/suncore/devices/battery/generic.py @@ -99,6 +99,8 @@ def __init__( if spec.force_switch_role is not None: self._switch = self.entity_id(spec.force_switch_role) self._capabilities = self._derive_capabilities() + self._user_option: str | None = None + self._user_switch_on: bool | None = None # --- capabilities and ranges ------------------------------------------------------------- @@ -235,10 +237,25 @@ async def read_back(self) -> Action | None: async def apply(self, intent: Intent) -> str | None: action = self.battery_action(intent) self.begin() + if self._applied is None: + self._remember_user_options() await self._write_state(action) self._applied = action return self.last_context_id() + def _remember_user_options(self) -> None: + """At takeover: the user's own select option and switch state, restored by ``release`` + (a ``BatteryAction`` baseline cannot hold them; not persisted - after a restart the + release falls back to ``auto`` / off, the template's release baseline).""" + if self._mode is not None: + view = self.lookup(self._mode[0]) + if view is not None and any(o.value == view.state for o in self._mode[1].options): + self._user_option = view.state + if self._switch is not None: + view = self.lookup(self._switch) + if view is not None and view.state in ("on", "off"): + self._user_switch_on = view.state == "on" + async def _write_state(self, action: BatteryAction) -> None: for field, number in self._numbers.items(): value = getattr(action, field) @@ -315,29 +332,41 @@ async def _write_switch(self, *, on: bool) -> None: await self.service("switch", "turn_on" if on else "turn_off", entity_id=self._switch) async def release(self, baseline: Action | None) -> None: - """Back to the baseline: the numbers SunCore holds, ``auto`` / off for select / switch.""" + """Back to the baseline: the numbers SunCore holds, the user's own select option and + switch state (else ``auto`` / off). + + Raises :class:`WriteRefusedError` when an entity that must be restored is unavailable: + a release that cannot be written is a failed release (the gate keeps the original + baseline and retries), never a silent success (review 4-G, B1). + """ self.begin() self._applied = None if isinstance(baseline, BatteryAction): for field, number in self._numbers.items(): value = getattr(baseline, field) - if value is not None and self.lookup(number.entity_id) is not None: - await self._write_number(number, value) - if self._mode is not None and self.lookup(self._mode[0]) is not None: - auto = next( - o.value for o in self._mode[1].options if o.meaning is BatteryModeMeaning.AUTO + if value is None: + continue + if self.lookup(number.entity_id) is None: + raise WriteRefusedError(f"{number.entity_id} is unavailable") + await self._write_number(number, value) + if self._mode is not None: + entity, control = self._mode + view = self.lookup(entity) + if view is None: + raise WriteRefusedError(f"{entity} is unavailable") + option = self._user_option or next( + o.value for o in control.options if o.meaning is BatteryModeMeaning.AUTO ) - view = self.lookup(self._mode[0]) - if view is not None and view.state != auto: + if view.state != option: await self.service( - "select", "select_option", data={"option": auto}, entity_id=self._mode[0] + "select", "select_option", data={"option": option}, entity_id=entity ) - if ( - self._switch is not None - and "grid_charge_w" not in self._numbers - and self.lookup(self._switch) is not None - ): - await self._write_switch(on=False) + if self._switch is not None and "grid_charge_w" not in self._numbers: + if self.lookup(self._switch) is None: + raise WriteRefusedError(f"{self._switch} is unavailable") + await self._write_switch(on=bool(self._user_switch_on)) + self._user_option = None + self._user_switch_on = None __all__ = ["GenericBatteryDriver"] diff --git a/suncore/safety/gate.py b/suncore/safety/gate.py index 1883e57..7fa7d6c 100644 --- a/suncore/safety/gate.py +++ b/suncore/safety/gate.py @@ -174,13 +174,18 @@ REASON_BATTERY_FALLBACK_UNCONFIRMED: Final = Reason(key="safety.battery_fallback_unconfirmed") """The hardware fallback (Kostal 1284/1286/1288) did not read back: no limit is written.""" REASON_BATTERY_RELEASE_UNCONFIRMED: Final = Reason(key="safety.battery_release_unconfirmed") -"""After a release the battery does not show its baseline: control paused, check it by hand.""" +"""After a release the battery does not show its baseline: retried with back-off, battery control +stays blocked (latched in the runtime) until it does or the user changes the limits.""" +REASON_BATTERY_RELEASE_CHECK: Final = Reason(key="safety.battery_release_check") +"""The deferred read-back of a battery release (an adapter without hardware fallback).""" +REASON_BATTERY_RELEASE_CONFIRMED: Final = Reason(key="safety.battery_release_confirmed") +"""The battery shows its own settings again: control of it has ended.""" +BATTERY_RELEASE_BACKOFF_S: Final = 30.0 +BATTERY_RELEASE_BACKOFF_MAX_S: Final = 600.0 REASON_BATTERY_OVERRIDE: Final = Reason(key="safety.battery_override") """The battery's limits changed outside SunCore while it held them: given back to the user.""" REASON_BATTERY_INPUTS_STALE: Final = Reason(key="safety.battery_inputs_stale") """The controller's inputs are too old to renew the battery's lease.""" -REASON_BATTERY_FALLBACK_UNVERIFIED: Final = Reason(key="safety.battery_fallback_unverified") -"""Shown with the mode: the adapter's hardware fallback is not measured, at most assisted.""" BATTERY_SCOPE: Final = BATTERY_ASSET_ID """The watchdog scope of the battery (its own faults; site faults pause it too).""" @@ -233,7 +238,7 @@ def __init__( battery.watch if battery is not None and battery.watch is not None else BatteryWatch() ) self._battery_beat: datetime | None = None - self._battery_verify: tuple[datetime, Action] | None = None + self._release_attempts: dict[str, int] = {} self._sink = sink self._actuators: Mapping[str, Actuator] = MappingProxyType(dict(actuators or {})) self._modes: ModeProvider = modes if modes is not None else AllShadow() @@ -437,9 +442,6 @@ async def poll(self) -> tuple[Decision, ...]: lease = await self._battery_lease(now) if lease is not None: decisions.append(lease) - check = await self._battery_release_check(now) - if check is not None: - decisions.append(check) return tuple(decisions) # --- watchdog feed ------------------------------------------------------------------- @@ -851,9 +853,6 @@ async def _battery_write( # noqa: PLR0912 - one branch per verdict intent, DecisionKind.REJECTED, now, (REASON_RATE_LIMITED,), mode ) if not runtime.under_control: - # A new takeover supersedes the check of the previous release (it reads its own - # baseline now and the battery will show the new state, not the old baseline). - self._battery_verify = None baseline = await actuator.read_back() if baseline is None: self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) @@ -899,7 +898,12 @@ async def _battery_write( # noqa: PLR0912 - one branch per verdict except Exception as exc: log.warning("safety.battery_write_failed", error=str(exc)[:200]) failed = REASON_WRITE_FAILED - runtime = runtime.model_copy(update={"last_write_ts": now}) + # A failed write may have reached part of the entities: it is pending, so a + # release never mistakes SunCore's partial state for the user's (review B1). + update: dict[str, object] = {"last_write_ts": now} + if failed is not None: + update.update({"pending_action": requested, "pending_ts": now}) + runtime = runtime.model_copy(update=update) await self._save(runtime) if failed is not None: await self._count_failure(BATTERY_ASSET_ID, now) @@ -1080,41 +1084,6 @@ async def _battery_override( observed=observed, ) - async def _battery_release_check(self, now: datetime) -> Decision | None: - """After a release of an adapter without hardware fallback: does the battery show its - baseline? Otherwise the battery scope trips (control paused) and the user is told.""" - due = self._battery_verify - actuator = self._battery_actuator() - if due is None or now < due[0]: - return None - self._battery_verify = None - if actuator is None: - return None - expected = due[1] - observed = await actuator.read_back() - if same_state( - expected if isinstance(expected, BatteryAction) else None, - observed, - readable_fields(actuator.capabilities), - ): - return None - self._watchdog.trip(BATTERY_SCOPE, REASON_BATTERY_RELEASE_UNCONFIRMED, now) - return await self._decide( - Intent( - id=f"release-check:{BATTERY_ASSET_ID}:{now.isoformat()}", - ts=now, - asset_id=BATTERY_ASSET_ID, - action=ReleaseAction(), - reasons=(REASON_BATTERY_RELEASE_UNCONFIRMED,), - origin=Origin.SAFETY, - ), - DecisionKind.FAILED, - now, - (REASON_BATTERY_RELEASE_UNCONFIRMED,), - self.modes_of(BATTERY_ASSET_ID).effective, - observed=observed, - ) - async def check_battery(self, flows: FlowSnapshot | None) -> Reason | None: """B8: the battery watch on this tick's flows; a fault pauses battery control and releases the battery (the site watchdog covers missing and implausible values).""" @@ -1367,6 +1336,8 @@ async def release_device( # noqa: PLR0911 - one return per verdict intent, DecisionKind.REJECTED, now, (REASON_NO_ACTUATOR,), mode ) orphan = self._is_orphan(device_id, runtime) + if device_id == BATTERY_ASSET_ID and not orphan: + return await self._release_battery(intent, runtime, actuator, reason, now, mode) observed = await actuator.read_back() runtime = await self._adopt_user_state(device, runtime, observed, now) if not urgent and not orphan: @@ -1422,24 +1393,141 @@ async def release_device( # noqa: PLR0911 - one return per verdict self._proposals = { k: v for k, v in self._proposals.items() if v.intent.asset_id != device_id } - if device_id == BATTERY_ASSET_ID: - self._after_battery_release(actuator, runtime.baseline, now) return await self._decide( intent, DecisionKind.ACCEPTED, now, (REASON_RELEASED, reason), mode ) - def _after_battery_release( - self, actuator: Actuator, baseline: Action | None, now: datetime - ) -> None: - """The heartbeat stops with the release; an adapter without hardware fallback is read - back once after its settle time (``_battery_release_check``).""" + async def _release_battery( # noqa: PLR0917 + self, + intent: Intent, + runtime: DeviceRuntime, + actuator: Actuator, + reason: Reason, + now: datetime, + mode: OperatingMode, + ) -> Decision: + """The battery's release: restore the **original** baseline and prove it (lock held). + + A release is complete only when the battery shows its baseline again (read-back), or + the user changed the limits to a third value (then theirs is kept, nothing is written). + Until then the runtime stays under control with the original baseline and a pending + release: no takeover, no write, no heartbeat - only the release is retried, with + back-off, also during an emergency stop (``poll`` executes it). A failed release + write, an unavailable entity or a read-back that still shows SunCore's state are never + taken for a baseline (review 4-G, B1). An adapter with a hardware fallback (Kostal §3.5) + is complete once its heartbeat stopped and the write went through. + """ self._battery_beat = None + baseline = runtime.baseline + caps = actuator.capabilities if isinstance(actuator, BatteryActuator) else frozenset() + fields = readable_fields(caps) + fallback = BatteryCapability.HARDWARE_FALLBACK in caps + observed = await actuator.read_back() + held = runtime.last_written or runtime.pending_action + held_target: Action | None = None + if isinstance(held, BatteryAction) and isinstance(actuator, BatteryActuator): + base = baseline if isinstance(baseline, BatteryAction) else None + held_target = quantise(resolve_battery_action(held, base), actuator.ranges()) + checking = runtime.release_due_reason == REASON_BATTERY_RELEASE_CHECK.key + if observed is not None and same_state(baseline, observed, fields): + return await self._battery_released( + intent, + runtime, + now, + mode, + (REASON_RELEASED, REASON_BATTERY_RELEASE_CONFIRMED if checking else reason), + ) if ( - isinstance(actuator, BatteryActuator) - and BatteryCapability.HARDWARE_FALLBACK not in actuator.capabilities - and isinstance(baseline, BatteryAction) + observed is not None + and not fallback + and (held_target is None or not same_state(held_target, observed, fields)) ): - self._battery_verify = (now + timedelta(seconds=actuator.settle_s), baseline) + # Neither the baseline nor SunCore's state: the user set the limits meanwhile. + return await self._battery_released( + intent, runtime, now, mode, (REASON_RELEASED, REASON_BATTERY_OVERRIDE) + ) + attempt = self._release_attempts.get(BATTERY_ASSET_ID, 0) + try: + await actuator.release(baseline) + except Exception as exc: + log.warning("safety.battery_release_failed", error=str(exc)[:200]) + await self._retry_battery_release(runtime, now, reason.key, attempt + 1) + return await self._decide( + intent, DecisionKind.FAILED, now, (REASON_RELEASE_FAILED, reason), mode + ) + if fallback: + return await self._battery_released( + intent, runtime, now, mode, (REASON_RELEASED, reason) + ) + settle = actuator.settle_s if isinstance(actuator, BatteryActuator) else 0.0 + due = now + timedelta(seconds=max(settle, self._release_backoff_s(attempt))) + await self._save( + runtime.model_copy( + update={ + "release_due_ts": due, + "release_due_reason": REASON_BATTERY_RELEASE_CHECK.key, + "last_write_ts": now, + } + ) + ) + self._release_attempts[BATTERY_ASSET_ID] = attempt + 1 + if checking: + return await self._decide( + intent, + DecisionKind.FAILED, + now, + (REASON_BATTERY_RELEASE_UNCONFIRMED,), + mode, + observed=observed, + ) + return await self._decide( + intent, DecisionKind.ACCEPTED, now, (REASON_RELEASED, reason), mode, observed=observed + ) + + @staticmethod + def _release_backoff_s(attempt: int) -> float: + if attempt <= 0: + return 0.0 + return float( + min(BATTERY_RELEASE_BACKOFF_MAX_S, BATTERY_RELEASE_BACKOFF_S * 2.0 ** (attempt - 1)) + ) + + async def _retry_battery_release( + self, runtime: DeviceRuntime, now: datetime, reason_key: str, attempt: int + ) -> None: + self._release_attempts[BATTERY_ASSET_ID] = attempt + due = now + timedelta(seconds=self._release_backoff_s(attempt)) + await self._save( + runtime.model_copy(update={"release_due_ts": due, "release_due_reason": reason_key}) + ) + + async def _battery_released( + self, + intent: Intent, + runtime: DeviceRuntime, + now: datetime, + mode: OperatingMode, + reasons: tuple[Reason, ...], + ) -> Decision: + self._release_attempts.pop(BATTERY_ASSET_ID, None) + released = runtime.model_copy( + update={ + "baseline": None, + "baseline_ts": None, + "last_written": None, + "last_write_context_id": None, + "last_write_ts": now, + "pending_action": None, + "pending_ts": None, + "release_due_ts": None, + "release_due_reason": None, + } + ) + await self._save(released) + self._proposals = { + k: v for k, v in self._proposals.items() if v.intent.asset_id != BATTERY_ASSET_ID + } + return await self._decide(intent, DecisionKind.ACCEPTED, now, reasons, mode) def _identity_of(self, asset_id: str) -> str | None: """The configured identity token of an asset (``None`` = not configured).""" diff --git a/tests/devices/battery/test_battery_drivers.py b/tests/devices/battery/test_battery_drivers.py index 453a707..9a39484 100644 --- a/tests/devices/battery/test_battery_drivers.py +++ b/tests/devices/battery/test_battery_drivers.py @@ -482,3 +482,59 @@ def test_write_register_is_a_write_of_the_modbus_adapter_only() -> None: assert [u for u in users if not u.startswith("suncore/sim/")] == [ "suncore/devices/battery/kostal_modbus.py" ] + + +async def test_a_release_with_an_unavailable_entity_fails_loudly() -> None: + """Review 4-G B1 (probe): a REST release to an unavailable number must not report success.""" + ha = FakeHA() + driver = kostal_rest(ha) + ha.set("number.scb_battery_min_soc", "unavailable") + with pytest.raises(WriteRefusedError): + await driver.release(BatteryAction(min_soc_pct=10)) + assert ha.calls == [] + gone = FakeHA() + generic_driver = generic(gone) + gone.set("number.max_discharge", "unavailable") + with pytest.raises(WriteRefusedError): + await generic_driver.release(BatteryAction(max_discharge_w=6000)) + + +async def test_release_restores_the_users_own_select_option_and_switch_state() -> None: + role = {"matcher": {"domain": "select"}, "description": "template.acme.battery.role.mode"} + tpl = _with_controls( + { + "mode": { + "kind": "mode", + "options": [ + {"value": "Auto", "meaning": "auto"}, + {"value": "Hold", "meaning": "no_discharge"}, + {"value": "Eco", "meaning": "other"}, + ], + } + }, + {"mode": role}, + ) + ha = FakeHA() + ha.set("select.mode", "Eco") + driver = GenericBatteryDriver( + tpl, settings("acme.battery", {"mode": "select.mode"}), write=ha.write, states=ha.lookup + ) + await driver.apply(battery_intent(max_discharge_w=0)) + ha.set("select.mode", "Hold") + await driver.release(None) + assert ha.sent[-1][3] == {"option": "Eco"} + + switch_role = {"matcher": {"domain": "switch"}, "description": "template.acme.battery.role.f"} + tpl2 = _with_controls({"force": {"kind": "force_charge"}}, {"force": switch_role}) + ha2 = FakeHA() + ha2.set("switch.force", "on") # the user force-charges on their own + driver2 = GenericBatteryDriver( + tpl2, + settings("acme.battery", {"force": "switch.force"}), + write=ha2.write, + states=ha2.lookup, + ) + await driver2.apply(battery_intent(grid_charge_w=5000)) + ha2.set("switch.force", "off") + await driver2.release(None) + assert ha2.sent[-1] == ("switch", "turn_on", {"entity_id": "switch.force"}, None) diff --git a/tests/safety/test_battery_gate.py b/tests/safety/test_battery_gate.py index dcb143d..50337c3 100644 --- a/tests/safety/test_battery_gate.py +++ b/tests/safety/test_battery_gate.py @@ -291,7 +291,9 @@ async def test_a_silent_write_failure_is_a_failed_read_back_and_three_trip() -> r.clock.advance(2) r.at(grid_w=600, battery_w=0, soc_pct=40) assert r.gate.watchdog.pause_reason(BATTERY_ASSET_ID, r.clock.now) is not None - assert r.battery.released == [BASE] # the trip released it at once + # The trip released it at once: the battery still shows its baseline (every write failed + # silently), so there is nothing to write back. + assert r.battery.released == [] runtime = r.gate.runtime_of(BATTERY_ASSET_ID) assert runtime is not None assert not runtime.under_control @@ -513,27 +515,105 @@ async def test_a_controller_release_restores_the_baseline_and_is_verified() -> N r = rig() await r.submit(BatteryAction(max_discharge_w=0)) r.clock.advance(60) + r.at(grid_w=600, battery_w=0, soc_pct=40) decision = await r.submit(ReleaseAction()) assert decision.kind is DecisionKind.ACCEPTED assert r.battery.state == BASE - for _ in range(3): - assert await r.tick(5) == () # the read-back after the settle time confirms it + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.under_control # until the read-back proves the baseline + assert runtime.baseline == BASE + decisions = [d for _ in range(3) for d in await r.tick(5)] + assert [keys(d) for d in decisions] == [["safety.released", "safety.battery_release_confirmed"]] + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert not runtime.under_control -async def test_an_unconfirmed_release_pauses_battery_control() -> None: - r = rig() - await r.submit(BatteryAction(max_discharge_w=0)) - r.battery.silent_fail = True +def _stuck_release(r: Rig) -> list[Action | None]: + """The adapter accepts the release call, but the battery keeps SunCore's state.""" + calls: list[Action | None] = [] - async def ignore(_: Action | None) -> None: - return None + async def ignore(baseline: Action | None) -> None: + calls.append(baseline) r.battery.release = ignore # type: ignore[method-assign] + return calls + + +async def test_an_unconfirmed_release_is_latched_and_retried_with_back_off() -> None: + """Review 4-G B1: the pause must hold across many healthy watchdog ticks, the stuck lock is + never adopted as a new baseline, and the release is retried with back-off.""" + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + calls = _stuck_release(r) await r.gate.emergency_stop() await r.gate.clear_emergency_stop() - decisions = [d for _ in range(3) for d in await r.tick(5)] - assert [keys(d) for d in decisions] == [["safety.battery_release_unconfirmed"]] - assert r.gate.watchdog.pause_reason(BATTERY_ASSET_ID, r.clock.now) is not None + rows: list[Decision] = [] + for _ in range(240): # 20 minutes of ticks with healthy flows + r.clock.advance(5) + r.at(grid_w=600, battery_w=0, soc_pct=40) + await r.gate.check_battery(flows(grid_w=600, battery_w=0, soc_pct=40)) + rows.extend(await r.gate.poll()) + unconfirmed = [d for d in rows if keys(d) == ["safety.battery_release_unconfirmed"]] + assert 3 <= len(unconfirmed) <= 8 # back-off: not one row per tick + assert len(calls) == len(unconfirmed) + 1 + assert all(c == BASE for c in calls) # always the ORIGINAL baseline + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.under_control + assert runtime.release_pending + assert runtime.baseline == BASE + # No new takeover while the release is unconfirmed - the stuck lock is never a baseline. + r.plans["now"] = plan(now=r.clock.now) + blocked = await r.submit(BatteryAction(max_charge_w=4000)) + assert keys(blocked) == ["safety.release_pending"] + assert r.battery.applied == [ + BatteryAction(max_charge_w=5000, max_discharge_w=0, min_soc_pct=10, grid_charge_w=0) + ] + # The battery comes back: the next check confirms and control ends. + r.battery.state = BASE + r.clock.advance(700) + r.at(grid_w=600, battery_w=0, soc_pct=40) + done = await r.gate.poll() + assert [keys(d) for d in done] == [["safety.released", "safety.battery_release_confirmed"]] + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert not runtime.under_control + + +async def test_a_failed_release_write_keeps_the_original_baseline_and_retries() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + + async def unavailable(_: Action | None) -> None: + msg = "number.max_discharge is unavailable" + raise RuntimeError(msg) + + r.battery.release = unavailable # type: ignore[method-assign] + await r.gate.emergency_stop() # the retry runs during the emergency stop too + rows: list[Decision] = [] + for _ in range(60): + r.clock.advance(5) + rows.extend(await r.gate.poll()) + failed = [d for d in rows if d.kind is DecisionKind.FAILED] + assert 2 <= len(failed) <= 5 + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.under_control + assert runtime.baseline == BASE + + +async def test_a_user_change_during_the_release_is_kept() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + _stuck_release(r) + await r.gate.emergency_stop() + user = BatteryAction(max_charge_w=5000, max_discharge_w=3000, min_soc_pct=30, grid_charge_w=0) + r.battery.state = user + done = [d for _ in range(4) for d in await r.tick(5)] + assert [keys(d) for d in done] == [["safety.released", "safety.battery_override"]] + assert r.battery.state == user # --- watchdog (B8) ------------------------------------------------------------------------------ @@ -564,7 +644,7 @@ async def test_a_device_never_sees_the_battery_path() -> None: assert keys(decision) == ["safety.shadow_mode"] # no mode for the device: shadow -async def test_a_new_takeover_supersedes_the_release_check() -> None: +async def test_no_new_takeover_until_the_release_is_confirmed() -> None: r = rig() await r.submit(BatteryAction(max_discharge_w=0)) r.clock.advance(60) @@ -572,7 +652,13 @@ async def test_a_new_takeover_supersedes_the_release_check() -> None: await r.submit(ReleaseAction()) r.clock.advance(6) r.at(grid_w=600, battery_w=0, soc_pct=40) + early = await r.submit(BatteryAction(max_discharge_w=0)) + assert keys(early) == ["safety.release_pending"] + await r.tick(5) # settle time over: confirmed + r.clock.advance(60) + r.at(grid_w=600, battery_w=0, soc_pct=40) again = await r.submit(BatteryAction(max_discharge_w=0)) assert again.kind is DecisionKind.ACCEPTED - decisions = [d for _ in range(4) for d in await r.tick(5)] - assert not [d for d in decisions if "safety.battery_release_unconfirmed" in keys(d)] + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.baseline == BASE diff --git a/tests/sim/test_battery_scenarios.py b/tests/sim/test_battery_scenarios.py index 66696aa..5e5a00a 100644 --- a/tests/sim/test_battery_scenarios.py +++ b/tests/sim/test_battery_scenarios.py @@ -272,9 +272,14 @@ def test_a_hung_inverter_is_noticed_released_and_left_alone( assert frozen, [keys(d) for d in runner.battery_decisions()] noticed = frozen[0].ts assert hang_from < noticed < hang_from + timedelta(minutes=25) - # Stop writing: at most the release attempt reaches the hung inverter until it is back. + # Stop writing: only the release of the original baseline is retried (with back-off) until + # the inverter is back; never a new limit. during = [w for w in inverter.log.writes if noticed <= w[0] < hang_to] - assert len(during) <= 1 + assert during + assert all(w[1] == "number.sim_battery_max_discharge" and w[2] == 5000 for w in during) + gaps = [(b[0] - a[0]).total_seconds() for a, b in itertools.pairwise(during)] + assert gaps == sorted(gaps) # back-off: the retries thin out ... + assert max(gaps) <= 600 # ... up to one every 10 minutes assert not [ d for d in battery_actions(runner, DecisionKind.ACCEPTED) @@ -284,6 +289,13 @@ def test_a_hung_inverter_is_noticed_released_and_left_alone( d for d in runner.battery_decisions() if "safety.battery_release_unconfirmed" in keys(d) ] assert unconfirmed + # The latch holds until the inverter is back, then the read-back confirms the release. + assert all(d.ts < hang_to + timedelta(minutes=11) for d in unconfirmed) + confirmed = [ + d for d in runner.battery_decisions() if "safety.battery_release_confirmed" in keys(d) + ] + assert confirmed + assert confirmed[0].ts >= hang_to def test_cloud_flicker_does_not_make_the_battery_oscillate( @@ -293,7 +305,8 @@ def test_cloud_flicker_does_not_make_the_battery_oscillate( hours = runner.scenario.duration_s / 3600 accepted = battery_actions(runner, DecisionKind.ACCEPTED) assert len(accepted) <= 2 * hours # a lock and its release per hour at most - assert len(inverter.log.writes) <= 3 * hours + locks = [w for w in inverter.log.writes if w[2] == 0] + assert len(locks) <= hours # --- grid_charge_price_level (planner + controller + gate, automatic) --- From 8a6e4140ef520b3a35f5859d729aa1fb3aea7be0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 06:08:02 +0000 Subject: [PATCH 11/16] =?UTF-8?q?fix(safety,devices):=20judge=20locks=20on?= =?UTF-8?q?=20the=20written=20state,=20Kostal=20=C2=A73.5=20baseline=20and?= =?UTF-8?q?=20fallback=20values=20(review=20M1,=20M2,=20minors=201,=202,?= =?UTF-8?q?=203,=208)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - B4/B5 judge ctx.target, the resolved state that is written and heartbeated: an inherited max_discharge_w = 0 or floor is a discharge lock (forced grid charging is none); property test with arbitrary baselines; regression test from the reviewer's probe - takeover_baseline(): kostal_modbus takes None fields from the battery's own limits (1076/1078), never from possibly stale 1280/1282 - kostal_modbus arms 1284/1286 with the larger of the model's and the own limits and prepared() compares with the values it wrote (UNVERIFIED: 1076/1078 dynamics); register 5 is a role and must match the configured byte order before any write (minor 1) - the lease ends when the adapter refuses (no heartbeat into a refusing inverter, minor 2) and when no fresh plan interval covers the held state any more, also without import (minor 8) - the settle wait after arming runs outside the gate lock (an emergency stop is not delayed) and the invariants are judged again under the lock right before apply() (minor 3) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- frontend/src/lib/i18n/locales/de.json | 3 + frontend/src/lib/i18n/locales/en.json | 3 + suncore/core/battery_adapter.py | 4 +- suncore/devices/battery/base.py | 4 + suncore/devices/battery/kostal_modbus.py | 74 ++++++++---- suncore/safety/battery.py | 30 +++-- suncore/safety/gate.py | 110 ++++++++++++------ suncore/sim/inverter.py | 5 +- .../battery/kostal.plenticore_g3_modbus.yaml | 5 +- tests/devices/battery/test_battery_drivers.py | 56 +++++++-- tests/safety/test_battery_gate.py | 101 +++++++++++++++- tests/safety/test_battery_invariants.py | 29 ++++- .../battery/kostal.plenticore_g3_modbus.yaml | 6 +- 13 files changed, 348 insertions(+), 82 deletions(-) diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index 551035d..92f4b8e 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -834,6 +834,7 @@ "template.kostal.plenticore_g3_modbus.role.fallback_timeout": "Modbus-Sensor von Register 1288 (Zeit bis zum Rückfall, s)", "template.kostal.plenticore_g3_modbus.role.own_charge_limit": "Modbus-Sensor von Register 1076 (eigene max. Ladeleistung des Akkus, W)", "template.kostal.plenticore_g3_modbus.role.own_discharge_limit": "Modbus-Sensor von Register 1078 (eigene max. Entladeleistung des Akkus, W)", + "template.kostal.plenticore_g3_modbus.role.byte_order": "Modbus-Sensor von Register 5 (Byte-Reihenfolge: 0 Little-Endian, 1 Big-Endian)", "unit.kw": "{value} kW", "unit.mismatch": "Die Einheit passt nicht.", "unit.percent": "{value} %", @@ -941,6 +942,7 @@ "safety.battery_grid_charge_bound": "Netzladen mit {grid_charge_w} W liegt über den erlaubten {bound_w} W (Akku, Wechselrichter, Plan oder Bezugsgrenze).", "safety.battery_grid_unknown": "Netz- oder Akkuleistung ist unbekannt: keine Akku-Aktion, die Netzbezug verursachen kann.", "safety.battery_plan_stale": "Der Plan ist zu alt für diese Akku-Aktion.", + "safety.battery_plan_ended": "Kein aktuelles Planintervall verlangt die Akku-Grenzen noch: zurückgegeben.", "safety.battery_soc_unknown": "Der Ladestand des Akkus ist unbekannt.", "safety.battery_soc_frozen": "Der Ladestand bleibt bei {soc_pct} %, obwohl {moved_pct} % der Kapazität geflossen sind: Akkusteuerung pausiert.", "safety.battery_full": "Der Akku steht bei {soc_pct} %, sein Maximum ist {max_soc_pct} %: kein Netzladen.", @@ -951,6 +953,7 @@ "safety.battery_inputs_stale": "Die Messwerte sind zu alt, um die Akku-Grenzen zu halten: zurückgegeben.", "safety.battery_unplanned_import": "Den Akku zurückzuhalten würde Netzbezug verursachen, und der Plan sieht das nicht vor.", "safety.battery_external_control_off": "Externes Batteriemanagement über Modbus ist aus (Register 1080 = {value}, nötig ist {expected}); nichts geschrieben.", + "safety.battery_byte_order_mismatch": "Der Wechselrichter meldet die Byte-Reihenfolge {reported}, SunCore ist auf {configured} eingestellt: nichts wird geschrieben.", "action.battery": "Batterie-Limits setzen", "api.validation.forecast_workday_domain": "{entity_id} ist kein Binärsensor. Wähle den Binärsensor der Workday-Integration.", "api.validation.forecast_weather_domain": "{entity_id} ist keine Wetter-Entität.", diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index 62a10a4..19abdfd 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -834,6 +834,7 @@ "template.kostal.plenticore_g3_modbus.role.fallback_timeout": "Modbus sensor of register 1288 (time until fallback, s)", "template.kostal.plenticore_g3_modbus.role.own_charge_limit": "Modbus sensor of register 1076 (the battery's own max charge power, W)", "template.kostal.plenticore_g3_modbus.role.own_discharge_limit": "Modbus sensor of register 1078 (the battery's own max discharge power, W)", + "template.kostal.plenticore_g3_modbus.role.byte_order": "Modbus sensor of register 5 (byte order: 0 little-endian, 1 big-endian)", "unit.kw": "{value} kW", "unit.mismatch": "The unit does not fit.", "unit.percent": "{value} %", @@ -941,6 +942,7 @@ "safety.battery_grid_charge_bound": "Grid charging with {grid_charge_w} W is above the allowed {bound_w} W (battery, inverter, plan or import limit).", "safety.battery_grid_unknown": "Grid or battery power is unknown: no battery action that can cause import.", "safety.battery_plan_stale": "The plan is too old to allow this battery action.", + "safety.battery_plan_ended": "No current plan interval asks for the battery's limits any more: given back.", "safety.battery_soc_unknown": "The battery's state of charge is unknown.", "safety.battery_soc_frozen": "The state of charge has stayed at {soc_pct} % although {moved_pct} % of the capacity moved: battery control paused.", "safety.battery_full": "The battery is at {soc_pct} %, its maximum is {max_soc_pct} %: no grid charging.", @@ -951,6 +953,7 @@ "safety.battery_inputs_stale": "The measurements are too old to keep holding the battery's limits: given back.", "safety.battery_unplanned_import": "Holding the battery back would make the house import, and the plan does not ask for it.", "safety.battery_external_control_off": "External battery management via Modbus is off (register 1080 = {value}, needs {expected}); nothing was written.", + "safety.battery_byte_order_mismatch": "The inverter reports the byte order {reported}, SunCore is configured for {configured}: nothing is written.", "action.battery": "Set battery limits", "api.validation.forecast_workday_domain": "{entity_id} is not a binary sensor. Choose the binary sensor of the Workday integration.", "api.validation.forecast_weather_domain": "{entity_id} is not a weather entity.", diff --git a/suncore/core/battery_adapter.py b/suncore/core/battery_adapter.py index d63d0fa..a192a70 100644 --- a/suncore/core/battery_adapter.py +++ b/suncore/core/battery_adapter.py @@ -37,6 +37,7 @@ class BatteryModeMeaning(StrEnum): KOSTAL_MODBUS_ROLES: Final = ( + "byte_order", "external_control", "charge_limit", "discharge_limit", @@ -47,7 +48,8 @@ class BatteryModeMeaning(StrEnum): "own_discharge_limit", ) """Read-back roles the ``kostal_modbus`` driver needs: modbus sensors of the registers of the -register map (1080, 1280, 1282, 1284, 1286, 1288) and of the battery's own limits (1076, 1078).""" +register map (5 byte order, 1080, 1280, 1282, 1284, 1286, 1288) and of the battery's own limits +(1076, 1078).""" @dataclass(frozen=True, slots=True) diff --git a/suncore/devices/battery/base.py b/suncore/devices/battery/base.py index 914f344..57c5219 100644 --- a/suncore/devices/battery/base.py +++ b/suncore/devices/battery/base.py @@ -168,6 +168,10 @@ def last_context_id(self) -> str | None: async def read_back(self) -> Action | None: # pragma: no cover - overridden raise NotImplementedError + async def takeover_baseline(self) -> Action | None: + """What ``None`` fields mean and a release restores: the state found at takeover.""" + return await self.read_back() + async def apply(self, intent: Intent) -> str | None: # pragma: no cover - overridden raise NotImplementedError diff --git a/suncore/devices/battery/kostal_modbus.py b/suncore/devices/battery/kostal_modbus.py index 39156ae..087cf3d 100644 --- a/suncore/devices/battery/kostal_modbus.py +++ b/suncore/devices/battery/kostal_modbus.py @@ -41,6 +41,7 @@ BatteryRanges, BatterySettings, FieldRange, + ModbusByteOrder, ModbusLink, ) from suncore.core.battery_adapter import KOSTAL_MODBUS_ROLES, BatteryAdapterSpec, ModbusRegisterSpec @@ -56,6 +57,9 @@ """Until a modbus sensor polled the register again (the user's ``scan_interval``; UNVERIFIED).""" REASON_EXTERNAL_CONTROL_OFF: Final = "safety.battery_external_control_off" +REASON_BYTE_ORDER_MISMATCH: Final = "safety.battery_byte_order_mismatch" +_BYTE_ORDER: Final = {0: ModbusByteOrder.LITTLE, 1: ModbusByteOrder.BIG} +"""Register 5: ``0x00`` little-endian (CDAB), ``0x01`` big-endian (ABCD).""" class KostalModbusDriver(BatteryDriver): @@ -83,6 +87,7 @@ def __init__( super().__init__(settings, write=write, states=states, settle_s=settle) self._registers: ModbusRegisterSpec = spec.modbus self._link: ModbusLink = settings.modbus + self._fallback_written: tuple[float, float] | None = None timeout = self._link.fallback_timeout_s if not ( self._registers.fallback_timeout_min_s @@ -131,32 +136,60 @@ def refusal(self) -> Reason | None: "expected": expected, }, ) - if self.own_limits() is None: - return Reason(key="safety.battery_range_unknown", args={"field": "own_limits"}) + reported = self.value_of("byte_order") + order = None if reported is None else _BYTE_ORDER.get(round(reported)) + if order is not self._link.byte_order: + # Register 5 decides how the floats are encoded: never write with a guessed order. + return Reason( + key=REASON_BYTE_ORDER_MISMATCH, + args={ + "configured": self._link.byte_order.value, + "reported": "unknown" if order is None else order.value, + }, + ) return None + def fallback_limits(self) -> tuple[float, float]: + """What 1284/1286 get: the larger of the battery model's and the battery's own limits + (1076/1078 when known; their dynamics over temperature and SoC are ``UNVERIFIED``).""" + own = self.own_limits() + charge, discharge = self._model.max_charge_w, self._model.max_discharge_w + if own is not None: + charge, discharge = max(charge, own[0]), max(discharge, own[1]) + return charge, discharge + def ranges(self) -> BatteryRanges: own = self.own_limits() - if own is None: - return BatteryRanges() + charge, discharge = self._model.max_charge_w, self._model.max_discharge_w + if own is not None: + charge, discharge = min(own[0], charge), min(own[1], discharge) return BatteryRanges( - max_charge_w=FieldRange(0.0, min(own[0], self._model.max_charge_w)), - max_discharge_w=FieldRange(0.0, min(own[1], self._model.max_discharge_w)), + max_charge_w=FieldRange(0.0, charge), max_discharge_w=FieldRange(0.0, discharge) ) def prepared(self) -> bool: - own = self.own_limits() + """The fallback registers show what this adapter **wrote** to them (review 4-G, M2): + not the live battery limits, which may move. Nothing written yet = not prepared.""" + written = self._fallback_written charge = self.value_of("fallback_charge_limit") discharge = self.value_of("fallback_discharge_limit") timeout = self.value_of("fallback_timeout") - if own is None or charge is None or discharge is None or timeout is None: + if written is None or charge is None or discharge is None or timeout is None: return False return ( - abs(charge - own[0]) <= FALLBACK_TOLERANCE_W - and abs(discharge - own[1]) <= FALLBACK_TOLERANCE_W + abs(charge - written[0]) <= FALLBACK_TOLERANCE_W + and abs(discharge - written[1]) <= FALLBACK_TOLERANCE_W and round(timeout) == self._link.fallback_timeout_s ) + async def takeover_baseline(self) -> Action | None: + """The battery's own limits (1076/1078): what a ``None`` field means and what a release + restores. The limit registers 1280/1282 may hold a stale foreign value (review M1).""" + own = self.own_limits() + if own is None: + return None + return BatteryAction(max_charge_w=own[0], max_discharge_w=own[1]) + async def read_back(self) -> Action | None: charge = self.value_of("charge_limit") discharge = self.value_of("discharge_limit") @@ -182,22 +215,21 @@ async def _float(self, address: int, value: float) -> None: await self._register(address, float32_words(float(value), self._link.byte_order)) async def arm_fallback(self) -> None: - """Fallback registers first: own limits to 1284 / 1286, the timeout to 1288.""" + """Fallback registers first: 1284/1286 = :meth:`fallback_limits`, 1288 = the timeout.""" if self.refusal() is not None: - raise WriteRefusedError("external battery management is not enabled (1080)") - own = self.own_limits() - assert own is not None + raise WriteRefusedError("the Modbus preconditions do not hold (1080, register 5)") + charge, discharge = self.fallback_limits() self.begin() - await self._float(self._registers.fallback_max_charge, own[0]) - await self._float(self._registers.fallback_max_discharge, own[1]) + self._fallback_written = (charge, discharge) + await self._float(self._registers.fallback_max_charge, charge) + await self._float(self._registers.fallback_max_discharge, discharge) await self._register( self._registers.fallback_timeout, uint32_words(self._link.fallback_timeout_s, self._link.byte_order), ) async def _write_limits(self, action: BatteryAction) -> None: - own = self.own_limits() - assert own is not None + own = self.fallback_limits() charge = own[0] if action.max_charge_w is None else action.max_charge_w discharge = own[1] if action.max_discharge_w is None else action.max_discharge_w # Both registers every time: the pair is the state the inverter holds (and re-writing @@ -234,9 +266,9 @@ async def release(self, baseline: Action | None) -> None: # noqa: ARG002 - see """ self._applied = None self.begin() - own = self.own_limits() - if own is None or self.refusal() is not None: - return + if self.refusal() is not None: + return # nothing can be written; the stopped heartbeat lets the inverter fall back + own = self.fallback_limits() await self._float(self._registers.max_charge, own[0]) await self._float(self._registers.max_discharge, own[1]) diff --git a/suncore/safety/battery.py b/suncore/safety/battery.py index 59098e8..cd3a243 100644 --- a/suncore/safety/battery.py +++ b/suncore/safety/battery.py @@ -104,6 +104,14 @@ async def keep_alive(self) -> None: """Re-write the last applied state (idempotent; called only while the lease holds).""" ... + async def takeover_baseline(self) -> Action | None: + """The values a ``None`` field means and a release restores, read at takeover. + + Usually :meth:`read_back`; the Kostal §3.5 adapter answers the battery's own limits + (1076/1078), because its limit registers may hold a stale value (review 4-G, M1). + """ + ... + # --- configuration ----------------------------------------------------------------------------- @@ -244,19 +252,27 @@ def grid_charge_w(ctx: BatteryContext) -> float: def is_discharge_lock(ctx: BatteryContext) -> bool: - """The requested limits keep the battery from covering the house (ADR-0013 decision 4). + """The state that would be **written** keeps the battery from covering the house + (ADR-0013 decision 4). + Judged on ``ctx.target`` - the resolved full state that is written and re-sent by the + heartbeat - not on the request: a discharge cap or floor inherited from the baseline (for + example a stale ``max_discharge_w = 0``) is written too and counts (review 4-G, M1). ``max_discharge_w`` below the current house deficit, or ``min_soc_pct`` at or above the - live SoC. Unknown live values count as a lock (the conservative direction). + live SoC. While the target forces grid charging the battery charges anyway, so it is no + lock (its import is bounded by B2/B5). Unknown live values count as a lock (the conservative + direction). """ - requested = ctx.requested - if requested.max_discharge_w is not None: + target = ctx.target + if (target.grid_charge_w or 0.0) > 0: + return False + if target.max_discharge_w is not None: deficit = ctx.live.deficit_w - if deficit is None or requested.max_discharge_w + POWER_TOLERANCE_W < deficit: + if deficit is None or target.max_discharge_w + POWER_TOLERANCE_W < deficit: return True - if requested.min_soc_pct is not None: + if target.min_soc_pct is not None: soc = ctx.live.soc_pct - if soc is None or requested.min_soc_pct >= soc - SOC_TOLERANCE_PCT: + if soc is None or target.min_soc_pct >= soc - SOC_TOLERANCE_PCT: return True return False diff --git a/suncore/safety/gate.py b/suncore/safety/gate.py index 7fa7d6c..f4e7f5c 100644 --- a/suncore/safety/gate.py +++ b/suncore/safety/gate.py @@ -184,6 +184,8 @@ BATTERY_RELEASE_BACKOFF_MAX_S: Final = 600.0 REASON_BATTERY_OVERRIDE: Final = Reason(key="safety.battery_override") """The battery's limits changed outside SunCore while it held them: given back to the user.""" +REASON_BATTERY_PLAN_ENDED: Final = Reason(key="safety.battery_plan_ended") +"""No fresh plan interval covers the held battery state any more: given back.""" REASON_BATTERY_INPUTS_STALE: Final = Reason(key="safety.battery_inputs_stale") """The controller's inputs are too old to renew the battery's lease.""" BATTERY_SCOPE: Final = BATTERY_ASSET_ID @@ -718,8 +720,11 @@ async def _submit_battery( # noqa: PLR0911, PLR0912 - one return per verdict if mode is OperatingMode.SHADOW: reasons: tuple[Reason, ...] = (REASON_SHADOW_MODE,) if isinstance(action, BatteryAction): - observed = await actuator.read_back() - baseline = runtime.baseline if runtime.under_control else observed + baseline = ( + runtime.baseline + if runtime.under_control + else await actuator.takeover_baseline() + ) reasons += evaluate_battery(self._battery_context(action, actuator, baseline, now)) return await self._decide(intent, DecisionKind.SHADOW, now, reasons, mode) pause = self._watchdog.pause_reason(BATTERY_SCOPE, now) @@ -753,7 +758,7 @@ async def _submit_battery( # noqa: PLR0911, PLR0912 - one return per verdict return await self._decide( intent, DecisionKind.REJECTED, now, (REASON_STATE_UNKNOWN,), mode ) - baseline = runtime.baseline if runtime.under_control else observed + baseline = runtime.baseline if runtime.under_control else await actuator.takeover_baseline() ctx = self._battery_context(action, actuator, baseline, now) violations = evaluate_battery(ctx) if violations: @@ -827,7 +832,7 @@ def _battery_context( baseline=base, ) - async def _battery_write( # noqa: PLR0912 - one branch per verdict + async def _battery_write( # noqa: PLR0911, PLR0912, PLR0915 - one return per verdict self, intent: Intent, requested: BatteryAction, @@ -835,11 +840,18 @@ async def _battery_write( # noqa: PLR0912 - one branch per verdict now: datetime, mode: OperatingMode, ) -> Decision: - """Takeover (baseline, hardware fallback first), write, settle, read back.""" + """Takeover (hardware fallback first, then the baseline), judge again, write, read back. + + The settle wait after arming the hardware fallback runs **outside** the gate lock, so an + emergency stop or release is never delayed by it; everything that may have changed in + that wait (mode, emergency stop, watchdog, the invariants) is judged again under the + lock right before ``apply()`` (review 4-G, minor 3). + """ config = self._battery assert config is not None failed: Reason | None = None context_id: str | None = None + armed = False async with self._lock(BATTERY_ASSET_ID): runtime = self._runtimes.get(BATTERY_ASSET_ID) or DeviceRuntime( device_id=BATTERY_ASSET_ID @@ -852,35 +864,41 @@ async def _battery_write( # noqa: PLR0912 - one branch per verdict return await self._decide( intent, DecisionKind.REJECTED, now, (REASON_RATE_LIMITED,), mode ) - if not runtime.under_control: - baseline = await actuator.read_back() - if baseline is None: - self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) - return await self._decide( - intent, DecisionKind.REJECTED, now, (REASON_STATE_UNKNOWN,), mode - ) - if not actuator.prepared(): - # Kostal §3.5: the fallback registers are written and read back before the - # first limit; otherwise nothing else is written (ADR-0013 decision 5). - try: - await actuator.arm_fallback() - except Exception as exc: - log.warning("safety.battery_fallback_failed", error=str(exc)[:200]) - failed = REASON_WRITE_FAILED - if failed is None: - await self._sleep(actuator.settle_s) - if not actuator.prepared(): - failed = REASON_BATTERY_FALLBACK_UNCONFIRMED - if failed is not None: - await self._save(runtime.model_copy(update={"last_write_ts": now})) - if failed is None: - blocked = self._blocked( - intent, self._runtimes.get(BATTERY_ASSET_ID, runtime), now - ) - if blocked is not None: + if not runtime.under_control and not actuator.prepared(): + # Kostal §3.5: the fallback registers are written and read back before the + # first limit; otherwise nothing else is written (ADR-0013 decision 5). + armed = True + try: + await actuator.arm_fallback() + except Exception as exc: + log.warning("safety.battery_fallback_failed", error=str(exc)[:200]) + failed = REASON_WRITE_FAILED + await self._save(runtime.model_copy(update={"last_write_ts": now})) + if failed is None and armed: + await self._sleep(actuator.settle_s) + async with self._lock(BATTERY_ASSET_ID): + runtime = self._runtimes.get(BATTERY_ASSET_ID) or DeviceRuntime( + device_id=BATTERY_ASSET_ID + ) + took_over = False + if failed is None: + blocked = self._blocked(intent, runtime, now) + if blocked is None: + blocked = actuator.refusal() + if blocked is not None: + if not armed: self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) + return await self._decide(intent, DecisionKind.REJECTED, now, (blocked,), mode) + if failed is None and not runtime.under_control: + if not actuator.prepared(): + failed = REASON_BATTERY_FALLBACK_UNCONFIRMED + else: + baseline = await actuator.takeover_baseline() + if baseline is None: + if not armed: + self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) return await self._decide( - intent, DecisionKind.REJECTED, now, (blocked,), mode + intent, DecisionKind.REJECTED, now, (REASON_STATE_UNKNOWN,), mode ) runtime = runtime.model_copy( update={ @@ -889,9 +907,17 @@ async def _battery_write( # noqa: PLR0912 - one branch per verdict "identity": config.identity, } ) - await self._save(runtime) + took_over = True if failed is None: ctx = self._battery_context(requested, actuator, runtime.baseline, now) + violations = evaluate_battery(ctx) + if violations: + # Judged again right before the write: something changed meanwhile. + if not armed: + self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) + return await self._decide(intent, DecisionKind.REJECTED, now, violations, mode) + if took_over: + await self._save(runtime) written = intent.model_copy(update={"action": ctx.target}) try: context_id = await actuator.apply(written) @@ -978,7 +1004,7 @@ async def _battery_confirm( intent, DecisionKind.ACCEPTED, after, intent.reasons, mode, observed=observed ) - async def _battery_lease(self, now: datetime) -> Decision | None: + async def _battery_lease(self, now: datetime) -> Decision | None: # noqa: PLR0912 """Every tick while SunCore holds battery limits (ADR-0013 decision 5, B7). The lease ends - and the baseline is restored - when the mode fell to shadow, the @@ -1012,10 +1038,18 @@ async def _battery_lease(self, now: datetime) -> Decision | None: if reason is None and (inputs is None or inputs.ts is None or now - inputs.ts > max_age): reason = REASON_BATTERY_INPUTS_STALE if reason is None: - violations = lease_violations( - self._battery_context(held, actuator, runtime.baseline, now) - ) - reason = violations[0] if violations else None + # The adapter's precondition went away (Kostal 1080, register 5): no heartbeat into + # a refusing inverter - the lease ends with that reason (review 4-G, minor 2). + reason = actuator.refusal() + if reason is None: + ctx = self._battery_context(held, actuator, runtime.baseline, now) + if ctx.band is None or not ctx.plan_fresh: + # ADR-0013 5B: every held state - also one that cannot cause import - is held + # only while a fresh plan interval covers it (review 4-G, minor 8). + reason = REASON_BATTERY_PLAN_ENDED + else: + violations = lease_violations(ctx) + reason = violations[0] if violations else None if reason is not None: return await self.release_device(BATTERY_ASSET_ID, reason, origin=Origin.SAFETY) if runtime.pending_action is None and runtime.last_written is not None: diff --git a/suncore/sim/inverter.py b/suncore/sim/inverter.py index 0d2da4e..e8d971d 100644 --- a/suncore/sim/inverter.py +++ b/suncore/sim/inverter.py @@ -42,6 +42,7 @@ MAX_DISCHARGE_ID: Final = "number.sim_battery_max_discharge" GRID_CHARGE_ID: Final = "number.sim_battery_grid_charge" MODBUS_IDS: Final = { + 5: "sensor.sim_modbus_5", 1080: "sensor.sim_modbus_1080", 1280: "sensor.sim_modbus_1280", 1282: "sensor.sim_modbus_1282", @@ -52,6 +53,7 @@ 1078: "sensor.sim_modbus_1078", } MODBUS_ROLES: Final = { + "byte_order": MODBUS_IDS[5], "external_control": MODBUS_IDS[1080], "charge_limit": MODBUS_IDS[1280], "discharge_limit": MODBUS_IDS[1282], @@ -263,13 +265,14 @@ def number(entity_id: str, value: float, unit: str, high: float, step: float) -> number(GRID_CHARGE_ID, self.grid_charge_w, "W", self.own_charge_w, 1) if self.params.adapter == "kostal_modbus": values = { + 5: 1.0 if self.params.byte_order is ModbusByteOrder.BIG else 0.0, 1080: float(self.params.external_control), 1076: self.own_charge_w, 1078: self.own_discharge_w, **self.registers, } for register, entity_id in MODBUS_IDS.items(): - unit = "s" if register == 1288 else (None if register == 1080 else "W") + unit = "s" if register == 1288 else (None if register in (5, 1080) else "W") attributes: dict[str, Any] = {"friendly_name": f"Kostal register {register}"} if unit is not None: attributes["unit_of_measurement"] = unit diff --git a/templates/battery/kostal.plenticore_g3_modbus.yaml b/templates/battery/kostal.plenticore_g3_modbus.yaml index 6f6fd16..2793d5b 100644 --- a/templates/battery/kostal.plenticore_g3_modbus.yaml +++ b/templates/battery/kostal.plenticore_g3_modbus.yaml @@ -5,7 +5,7 @@ # * a `modbus:` hub in configuration.yaml (port 1502, unit id of the inverter, default 71); # * "External battery management via Modbus" enabled in the inverter (register 1080 = 2); # * one float32 sensor per register 1280, 1282, 1284, 1286, 1076, 1078, one uint32 sensor for -# 1288 and one for 1080, decoded with the inverter's byte order (register 5); +# 1288, one for 1080 and one for register 5 (byte order), decoded with that byte order; # * `battery.modbus` in SunCore: hub name, unit id, byte order. # Until the fallback timer was measured on the real inverter (`battery.fallback_measured`) the # battery is capped at assisted mode. @@ -41,6 +41,9 @@ modbus: external_control_register: 1080 external_control_value: 2 roles: + byte_order: + matcher: { domain: sensor, platforms: [modbus] } + description: template.kostal.plenticore_g3_modbus.role.byte_order external_control: matcher: { domain: sensor, platforms: [modbus] } description: template.kostal.plenticore_g3_modbus.role.external_control diff --git a/tests/devices/battery/test_battery_drivers.py b/tests/devices/battery/test_battery_drivers.py index 9a39484..823bc74 100644 --- a/tests/devices/battery/test_battery_drivers.py +++ b/tests/devices/battery/test_battery_drivers.py @@ -321,6 +321,7 @@ def test_kostal_rest_template_must_have_only_a_min_soc_control() -> None: # --- kostal_modbus ---------------------------------------------------------------------------- MODBUS_ENTITIES = { + "byte_order": "sensor.k_5", "external_control": "sensor.k_1080", "charge_limit": "sensor.k_1280", "discharge_limit": "sensor.k_1282", @@ -334,6 +335,7 @@ def test_kostal_rest_template_must_have_only_a_min_soc_control() -> None: def modbus(ha: FakeHA, *, external: str = "2", prepared: bool = False) -> KostalModbusDriver: + ha.set("sensor.k_5", "0") ha.set("sensor.k_1080", external) ha.set("sensor.k_1280", "0") ha.set("sensor.k_1282", "0") @@ -392,20 +394,26 @@ async def test_modbus_arms_the_fallback_first_and_refuses_limits_until_confirmed await driver.apply(battery_intent(max_discharge_w=0)) await driver.arm_fallback() order = ModbusByteOrder.LITTLE + # The larger of the model's (5000/6000) and the battery's own limits (4800/5500). assert register_writes(ha) == [ - (1284, float32_words(4800, order)), - (1286, float32_words(5500, order)), + (1284, float32_words(5000, order)), + (1286, float32_words(6000, order)), (1288, uint32_words(60, order)), ] - ha.set("sensor.k_1284", "4800") - ha.set("sensor.k_1286", "5500") + ha.set("sensor.k_1284", "5000") + ha.set("sensor.k_1286", "6000") ha.set("sensor.k_1288", "60") assert driver.prepared() async def test_modbus_limits_heartbeat_and_release() -> None: ha = FakeHA() - driver = modbus(ha, prepared=True) + driver = modbus(ha) + await driver.arm_fallback() + ha.set("sensor.k_1284", "5000") + ha.set("sensor.k_1286", "6000") + ha.set("sensor.k_1288", "60") + ha.calls.clear() assert driver.heartbeat_s == 20 assert driver.ranges().max_discharge_w == FieldRange(0, 5500) await driver.apply(battery_intent(max_charge_w=4800, max_discharge_w=0)) @@ -415,8 +423,8 @@ async def test_modbus_limits_heartbeat_and_release() -> None: await driver.keep_alive() assert register_writes(ha) == lock + lock await driver.release(BatteryAction(max_charge_w=0, max_discharge_w=0)) - own = [(1280, float32_words(4800, order)), (1282, float32_words(5500, order))] - assert register_writes(ha) == lock + lock + own # own limits, not the takeover read-back + own = [(1280, float32_words(5000, order)), (1282, float32_words(6000, order))] + assert register_writes(ha) == lock + lock + own # the fallback values, not a read-back await driver.keep_alive() # the heartbeat stopped with the release assert len(ha.calls) == 6 @@ -538,3 +546,37 @@ async def test_release_restores_the_users_own_select_option_and_switch_state() - ha2.set("switch.force", "off") await driver2.release(None) assert ha2.sent[-1] == ("switch", "turn_on", {"entity_id": "switch.force"}, None) + + +async def test_modbus_fallback_gets_the_written_values_and_register_5_must_match() -> None: + """Review M2 and minor 1.""" + ha = FakeHA() + driver = modbus(ha) + ha.set("sensor.k_1076", "4800") # the BMS limits may move; the model says 5000/6000 + await driver.arm_fallback() + order = ModbusByteOrder.LITTLE + assert register_writes(ha)[:2] == [ + (1284, float32_words(5000, order)), + (1286, float32_words(6000, order)), + ] + ha.set("sensor.k_1284", "5000") + ha.set("sensor.k_1286", "6000") + ha.set("sensor.k_1288", "60") + assert driver.prepared() + ha.set("sensor.k_1076", "3000") # the live limit moves: still prepared (written values) + assert driver.prepared() + assert await driver.takeover_baseline() == BatteryAction( + max_charge_w=3000, max_discharge_w=5500 + ) + ha.set("sensor.k_5", "1") # the inverter now says big-endian + refusal = driver.refusal() + assert refusal is not None + assert refusal.key == "safety.battery_byte_order_mismatch" + with pytest.raises(WriteRefusedError): + await driver.arm_fallback() + + +def test_a_fresh_modbus_adapter_is_never_prepared_by_foreign_registers() -> None: + ha = FakeHA() + driver = modbus(ha, prepared=True) # the registers happen to show the own limits + assert not driver.prepared() # nothing written by this adapter yet diff --git a/tests/safety/test_battery_gate.py b/tests/safety/test_battery_gate.py index 50337c3..a65a9a5 100644 --- a/tests/safety/test_battery_gate.py +++ b/tests/safety/test_battery_gate.py @@ -59,6 +59,8 @@ class FakeBattery: released: list[Action | None] = field(default_factory=list) beats: int = 0 held: BatteryAction | None = None + own: BatteryAction | None = None + """``takeover_baseline`` when it differs from the read-back (Kostal §3.5 own limits).""" @property def asset_id(self) -> str: @@ -99,6 +101,9 @@ async def keep_alive(self) -> None: async def read_back(self) -> Action | None: return self.state + async def takeover_baseline(self) -> Action | None: + return self.state if self.own is None else self.own + async def apply(self, intent: Intent) -> str | None: assert isinstance(intent.action, BatteryAction) self.applied.append(intent.action) @@ -416,7 +421,7 @@ async def test_a_stale_plan_ends_the_lease() -> None: ) decisions = await r.tick(5) assert decisions - assert "safety.battery_plan_stale" in keys(decisions[0]) + assert "safety.battery_plan_ended" in keys(decisions[0]) assert r.battery.state == BASE @@ -662,3 +667,97 @@ async def test_no_new_takeover_until_the_release_is_confirmed() -> None: runtime = r.gate.runtime_of(BATTERY_ASSET_ID) assert runtime is not None assert runtime.baseline == BASE + + +# --- review 4-G regressions ------------------------------------------------------------------ + + +async def test_an_inherited_stale_discharge_lock_counts_as_a_lock() -> None: + """Review M1 (probe): a baseline max_discharge_w = 0 is written with any action, so it is a + discharge lock that needs the plan's ``discharge_lock``.""" + stale = BatteryAction(max_charge_w=5000, max_discharge_w=0, min_soc_pct=10, grid_charge_w=0) + r = rig(FakeBattery(state=stale)) + r.plans["now"] = plan() # no discharge lock, no grid charging + r.at(grid_w=1500, battery_w=0, soc_pct=60) # the house needs 1.5 kW + decision = await r.submit(BatteryAction(max_charge_w=2000)) + assert decision.kind is DecisionKind.REJECTED + assert "safety.battery_unplanned_import" in keys(decision) + assert r.battery.applied == [] + + +async def test_the_takeover_baseline_comes_from_the_adapter_not_the_limit_registers() -> None: + """Review M1: Kostal §3.5 - the None fields mean the battery's own limits, not a stale 1282.""" + stale = BatteryAction(max_charge_w=5000, max_discharge_w=0) + own = BatteryAction(max_charge_w=5000, max_discharge_w=5000) + r = rig( + FakeBattery( + caps=frozenset({BatteryCapability.CHARGE_LIMIT, BatteryCapability.DISCHARGE_LIMIT}), + state=stale, + own=own, + ) + ) + r.plans["now"] = plan() + r.at(grid_w=-2000, battery_w=0, soc_pct=60) # export: a charge cap cannot cause import + decision = await r.submit(BatteryAction(max_charge_w=2000)) + assert decision.kind is DecisionKind.ACCEPTED, keys(decision) + assert r.battery.applied == [BatteryAction(max_charge_w=2000, max_discharge_w=5000)] + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.baseline == own + + +async def test_a_refusing_adapter_ends_the_lease_and_its_heartbeat() -> None: + """Review minor 2: no heartbeat into a refusing inverter; the lease ends with the reason.""" + from suncore.core.decisions import Reason # noqa: PLC0415 + + battery = FakeBattery(caps=ALL | {BatteryCapability.HARDWARE_FALLBACK}, beat=20) + r = rig(battery, fallback_verified=True) + await r.submit(BatteryAction(max_discharge_w=0)) + battery.refuse = Reason(key="safety.battery_external_control_off", args={"value": "0"}) + decisions = await r.tick(5) + assert decisions + assert "safety.battery_external_control_off" in keys(decisions[0]) + beats = battery.beats + for _ in range(10): + await r.tick(5) + assert battery.beats == beats + + +async def test_the_lease_needs_a_fresh_plan_also_for_states_without_import() -> None: + """Review minor 8 (ADR-0013 5B): a charge cap is held only while a plan interval covers it.""" + r = rig() + r.at(grid_w=-2000, battery_w=0, soc_pct=60) + r.plans["now"] = plan(now=r.clock.now) + decision = await r.submit(BatteryAction(max_charge_w=2000)) + assert decision.kind is DecisionKind.ACCEPTED, keys(decision) + r.plans["now"] = Plan.default() + decisions = await r.tick(5) + assert decisions + assert "safety.battery_plan_ended" in keys(decisions[0]) + + +async def test_an_emergency_stop_is_not_delayed_by_the_fallback_settle_wait() -> None: + """Review minor 3: the settle wait after arming runs outside the lock; the stop wins and + nothing is written after it.""" + import asyncio # noqa: PLC0415 + + battery = FakeBattery(caps=ALL | {BatteryCapability.HARDWARE_FALLBACK}, settle=15) + r = rig(battery, fallback_verified=True) + waiting = asyncio.Event() + proceed = asyncio.Event() + + async def slow_sleep(seconds: float) -> None: + r.clock.advance(seconds) + waiting.set() + await proceed.wait() + + r.gate._sleep = slow_sleep + write = asyncio.ensure_future(r.submit(BatteryAction(max_discharge_w=0))) + await waiting.wait() + stop = asyncio.ensure_future(r.gate.emergency_stop()) + await asyncio.wait_for(asyncio.shield(stop), timeout=1.0) # not blocked by the wait + proceed.set() + decision = await write + assert decision.kind is DecisionKind.REJECTED + assert keys(decision) == ["safety.emergency_stop"] + assert battery.applied == [] diff --git a/tests/safety/test_battery_invariants.py b/tests/safety/test_battery_invariants.py index 6985af5..f593e17 100644 --- a/tests/safety/test_battery_invariants.py +++ b/tests/safety/test_battery_invariants.py @@ -115,7 +115,7 @@ def bands(draw: st.DrawFn) -> BatteryBand | None: @st.composite -def contexts(draw: st.DrawFn, *, grid: bool = False) -> BatteryContext: +def contexts(draw: st.DrawFn, *, grid: bool = False, baseline: bool = False) -> BatteryContext: model = BatteryModel( capacity_wh=10_000, max_charge_w=draw(st.floats(1000, 12_000)), @@ -126,9 +126,9 @@ def contexts(draw: st.DrawFn, *, grid: bool = False) -> BatteryContext: ) reserve = model.min_soc_pct + draw(st.sampled_from([0.0, 5.0])) requested = draw(actions(grid=grid)) - baseline = rarely(draw, actions(), st.none()) + base_action = draw(actions()) if baseline else rarely(draw, actions(), st.none()) rng = draw(ranges()) - target = quantise(resolve_battery_action(requested, baseline), rng) + target = quantise(resolve_battery_action(requested, base_action), rng) policy = rarely( draw, st.sampled_from( @@ -166,7 +166,7 @@ def contexts(draw: st.DrawFn, *, grid: bool = False) -> BatteryContext: ), reserve_w=100.0, now=NOW + timedelta(hours=draw(st.integers(0, 23))), - baseline=baseline, + baseline=base_action, ) @@ -269,6 +269,27 @@ def test_b4_a_discharge_lock_only_from_a_fresh_planned_lock(ctx: BatteryContext) assert ctx.plan_fresh +@PROPERTY +@given(contexts(baseline=True)) +def test_b4_judges_the_written_state_with_arbitrary_baselines(ctx: BatteryContext) -> None: + """Review M1: an inherited cap or floor is written too - the lock is judged on the target.""" + assume(accepted(ctx)) + target = ctx.target + if (target.grid_charge_w or 0) > 0: + return + deficit, soc = ctx.live.deficit_w, ctx.live.soc_pct + inherited_cap = target.max_discharge_w is not None and ( + deficit is None or target.max_discharge_w + 1.0 < deficit + ) + inherited_floor = target.min_soc_pct is not None and ( + soc is None or target.min_soc_pct >= soc - 0.01 + ) + if inherited_cap or inherited_floor: + assert ctx.band is not None + assert ctx.band.discharge_lock + assert ctx.plan_fresh + + @PROPERTY @given(contexts()) def test_b5_the_import_limit_holds_for_every_action_that_can_cause_import( diff --git a/tests/scenarios/battery/kostal.plenticore_g3_modbus.yaml b/tests/scenarios/battery/kostal.plenticore_g3_modbus.yaml index 372d08a..aeff296 100644 --- a/tests/scenarios/battery/kostal.plenticore_g3_modbus.yaml +++ b/tests/scenarios/battery/kostal.plenticore_g3_modbus.yaml @@ -3,6 +3,7 @@ sim_scenario: summer_day # `modbus:` YAML sensors of the §3.5 registers (platform modbus); the power sensors tie, so the # user picks the register for each role in the wizard. extra_entities: + - { entity_id: sensor.kostal_5_byte_order, platform: modbus, state: "0" } - { entity_id: sensor.kostal_1080_battery_management, platform: modbus, state: "2" } - { entity_id: sensor.kostal_1280_max_charge, platform: modbus, unit: W, state: "10000" } - { entity_id: sensor.kostal_1282_max_discharge, platform: modbus, unit: W, state: "10000" } @@ -12,8 +13,11 @@ extra_entities: - { entity_id: sensor.kostal_1076_battery_charge_limit, platform: modbus, unit: W, state: "10000" } - { entity_id: sensor.kostal_1078_battery_discharge_limit, platform: modbus, unit: W, state: "10000" } roles: + byte_order: + tied: [sensor.kostal_5_byte_order, sensor.kostal_1080_battery_management, sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1288_fallback_time, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + pick: sensor.kostal_5_byte_order external_control: - tied: [sensor.kostal_1080_battery_management, sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1288_fallback_time, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] + tied: [sensor.kostal_5_byte_order, sensor.kostal_1080_battery_management, sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1288_fallback_time, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] pick: sensor.kostal_1080_battery_management charge_limit: tied: [sensor.kostal_1280_max_charge, sensor.kostal_1282_max_discharge, sensor.kostal_1284_fallback_charge, sensor.kostal_1286_fallback_discharge, sensor.kostal_1076_battery_charge_limit, sensor.kostal_1078_battery_discharge_limit] From 581178365a740cf5eba30c0b7c5bea21841acd9f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 06:20:58 +0000 Subject: [PATCH 12/16] fix(controller,core,sim): fallback_measured is identity, only an OK SoC sets a floor, realistic battery sim (review minors 5, 6, 7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - battery identity includes fallback_measured: marking the fallback measured lifts the assisted cap, so the battery drops to shadow until re-confirmed with the new token (minor 5) - the controller reads the SoC only with Quality.OK (minor 7) - sim: REST refresh 30 s against the 35 s settle, modbus sensor scan lag (10 s), stale 1280/ 1282 left by an earlier controller; a §3.5 takeover is never skipped because the registers merely show the value (not in force); price jump inside the grid-charge window ends the lease (scenario test); the hang latch holds until hang_to (minor 6) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- suncore/controller/loop.py | 5 ++- suncore/core/identity.py | 8 +++- suncore/safety/gate.py | 13 +++++- suncore/sim/inverter.py | 39 ++++++++++++++---- .../sim/scenarios/battery_reserve_drift.yaml | 2 +- .../sim/scenarios/kostal_rest_reserve.yaml | 1 + .../sim/scenarios/modbus_heartbeat_lost.yaml | 4 +- tests/controller/test_battery_intents.py | 24 +++++++++++ tests/core/test_battery_contracts.py | 8 ++-- tests/sim/test_battery_scenarios.py | 41 ++++++++++++++++++- tests/storage/test_config_sections.py | 8 ++++ 11 files changed, 133 insertions(+), 20 deletions(-) diff --git a/suncore/controller/loop.py b/suncore/controller/loop.py index a181462..b02b92e 100644 --- a/suncore/controller/loop.py +++ b/suncore/controller/loop.py @@ -76,6 +76,7 @@ from suncore.core.control import ControlSettings, DeviceState, GateInputs, Plan, PowerEstimate from suncore.core.decisions import Decision, Intent, Reason from suncore.core.devices import DeviceConfig +from suncore.core.signals import Quality log = structlog.get_logger(__name__) @@ -198,7 +199,9 @@ def step(self, now: datetime, inputs: ControllerInputs) -> TickResult: # (each intent's own added demand is the gate's ``delta``). surplus = site.gate_estimate(self._settings.reserve_w, outcome.committed_w) outcome = self._allocator.run(now, site, allocation, outcome) - soc = None if inputs.flows is None else inputs.flows.battery_soc_pct.value + soc_flow = None if inputs.flows is None else inputs.flows.battery_soc_pct + # Only an OK reading counts (review 4-G minor 7): a stale SoC never sets a floor. + soc = soc_flow.value if soc_flow is not None and soc_flow.quality is Quality.OK else None battery_intent = self._battery.step(now, inputs.plan, inputs.battery, soc) intents = (*outcome.intents, battery_intent) if battery_intent else tuple(outcome.intents) gate_inputs = GateInputs( diff --git a/suncore/core/identity.py b/suncore/core/identity.py index a807155..5ac5187 100644 --- a/suncore/core/identity.py +++ b/suncore/core/identity.py @@ -70,7 +70,8 @@ class BatteryIdentity: The reserved asset id, the adapter template, the mapped role entities, the site's SoC and battery power entities (what the gate judges the battery by) and, for the ``kostal_modbus`` adapter, the modbus hub and unit id (another unit id writes to another inverter). Settings - (model, strategy, policy, byte order, timers) are not identity. + (model, strategy, policy, byte order, timers) are not identity; ``fallback_measured`` is (it + lifts the cap at assisted). """ asset_id: str @@ -79,6 +80,9 @@ class BatteryIdentity: soc_entity: str | None power_entity: str | None modbus: tuple[str, int] | None + fallback_measured: bool = False + """Review 4-G minor 5: marking the hardware fallback as measured lifts the gate's cap at + assisted, so it is identity too - changing it drops the battery to shadow.""" def battery_identity( @@ -95,6 +99,7 @@ def battery_identity( soc_entity=None if site_battery is None else site_battery.soc.entity_id, power_entity=None if site_battery is None else site_battery.power.entity_id, modbus=None if settings.modbus is None else (settings.modbus.hub, settings.modbus.slave), + fallback_measured=settings.fallback_measured, ) @@ -115,6 +120,7 @@ def battery_identity_token(settings: BatterySettings | None, site: SiteConfig | identity.soc_entity, identity.power_entity, list(identity.modbus) if identity.modbus is not None else None, + identity.fallback_measured, ], separators=(",", ":"), ) diff --git a/suncore/safety/gate.py b/suncore/safety/gate.py index f4e7f5c..0a05012 100644 --- a/suncore/safety/gate.py +++ b/suncore/safety/gate.py @@ -765,8 +765,17 @@ async def _submit_battery( # noqa: PLR0911, PLR0912 - one return per verdict return await self._decide(intent, DecisionKind.REJECTED, now, violations, mode) fields = readable_fields(actuator.capabilities) held = runtime.last_written if runtime.under_control else None - if same_state(ctx.target, observed, fields) and ( - not runtime.under_control or held == action + # A §3.5-style limit is in force only while SunCore keeps writing it: registers that + # merely *show* the value (left by an earlier controller) are no reason to skip the + # takeover (review 4-G, minor 6). + foreign = ( + not runtime.under_control + and BatteryCapability.HARDWARE_FALLBACK in actuator.capabilities + ) + if ( + same_state(ctx.target, observed, fields) + and not foreign + and (not runtime.under_control or held == action) ): # Write only on change (B7): the battery already holds this state. return await self._decide( diff --git a/suncore/sim/inverter.py b/suncore/sim/inverter.py index e8d971d..127ee11 100644 --- a/suncore/sim/inverter.py +++ b/suncore/sim/inverter.py @@ -88,6 +88,12 @@ class InverterParams(BaseModel): """Register 1288 before SunCore writes it (0 = never written).""" hang_from_s: int | None = None hang_to_s: int | None = None + modbus_scan_s: float = Field(default=0.0, ge=0, le=300) + """The ``scan_interval`` of the user's modbus sensors: they show a register's value only at + the next poll (0 = at once).""" + stale_limits: dict[int, float] = Field(default_factory=dict) + """Values left in the limit registers (1280/1282) by an earlier controller; not active + until written again in this session, but what the sensors show (review minor 6).""" @dataclass(slots=True) @@ -134,7 +140,10 @@ def __init__( 1286: 0.0, 1288: float(params.fallback_timeout_s), } + self.registers.update({k: float(v) for k, v in params.stale_limits.items()}) self.limits_written_at: datetime | None = None + self._scanned: dict[int, float] = {} + self._scanned_at: datetime | None = None self.battery_w = 0.0 self.log = InverterLog() self._shown_min_soc = params.min_soc_pct @@ -264,13 +273,7 @@ def number(entity_id: str, value: float, unit: str, high: float, step: float) -> number(MAX_DISCHARGE_ID, self.max_discharge_w, "W", self.own_discharge_w, 1) number(GRID_CHARGE_ID, self.grid_charge_w, "W", self.own_charge_w, 1) if self.params.adapter == "kostal_modbus": - values = { - 5: 1.0 if self.params.byte_order is ModbusByteOrder.BIG else 0.0, - 1080: float(self.params.external_control), - 1076: self.own_charge_w, - 1078: self.own_discharge_w, - **self.registers, - } + values = self._scan(now) for register, entity_id in MODBUS_IDS.items(): unit = "s" if register == 1288 else (None if register in (5, 1080) else "W") attributes: dict[str, Any] = {"friendly_name": f"Kostal register {register}"} @@ -279,6 +282,28 @@ def number(entity_id: str, value: float, unit: str, high: float, step: float) -> rows.append((entity_id, _text(values[register]), attributes)) return rows + def _registers_now(self) -> dict[int, float]: + return { + 5: 1.0 if self.params.byte_order is ModbusByteOrder.BIG else 0.0, + 1080: float(self.params.external_control), + 1076: self.own_charge_w, + 1078: self.own_discharge_w, + **self.registers, + } + + def _scan(self, now: datetime) -> dict[int, float]: + """What the modbus sensors show: the registers as of their last poll.""" + scan = self.params.modbus_scan_s + if ( + not self._scanned + or scan <= 0 + or self._scanned_at is None + or (now - self._scanned_at).total_seconds() >= scan + ): + self._scanned = self._registers_now() + self._scanned_at = now + return self._scanned + def _min_soc_shown(self, now: datetime) -> float: """The REST integration shows a written floor only after its refresh.""" changed = self._min_soc_changed_at diff --git a/suncore/sim/scenarios/battery_reserve_drift.yaml b/suncore/sim/scenarios/battery_reserve_drift.yaml index 73f4295..33a1d4f 100644 --- a/suncore/sim/scenarios/battery_reserve_drift.yaml +++ b/suncore/sim/scenarios/battery_reserve_drift.yaml @@ -14,7 +14,7 @@ house: bms_cutoff_pct: 5 max_drift_pct: 4 drift_per_h: 1.5 - rest_refresh_s: 2 + rest_refresh_s: 30 control: import_limit_w: 12000 battery: diff --git a/suncore/sim/scenarios/kostal_rest_reserve.yaml b/suncore/sim/scenarios/kostal_rest_reserve.yaml index f1f26c9..e0f9dc4 100644 --- a/suncore/sim/scenarios/kostal_rest_reserve.yaml +++ b/suncore/sim/scenarios/kostal_rest_reserve.yaml @@ -11,6 +11,7 @@ house: adapter: kostal_plenticore min_soc_pct: 10 rest_write_fails: true + rest_refresh_s: 30 control: import_limit_w: 12000 settings: {min_write_interval_s: 30} diff --git a/suncore/sim/scenarios/modbus_heartbeat_lost.yaml b/suncore/sim/scenarios/modbus_heartbeat_lost.yaml index d7e6f7e..18ae198 100644 --- a/suncore/sim/scenarios/modbus_heartbeat_lost.yaml +++ b/suncore/sim/scenarios/modbus_heartbeat_lost.yaml @@ -1,6 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 name: modbus_heartbeat_lost -description: A winter evening. The plan holds the battery (discharge lock) and SunCore writes the Kostal §3.5 limits through modbus.write_register - fallback registers 1284/1286/1288 first, then 1282 = 0 with a heartbeat every 20 s. At 21:00 SunCore stops (a crash, no release). The inverter must fall back to its own limits within register 1288 (60 s) and cover the house again. +description: A winter evening. The plan holds the battery (discharge lock) and SunCore writes the Kostal §3.5 limits through modbus.write_register - fallback registers 1284/1286/1288 first, then 1282 = 0 with a heartbeat every 20 s. The limit registers still show a stale lock of an earlier controller (1282 = 0) and the modbus sensors poll every 10 s. At 21:00 SunCore stops (a crash, no release). The inverter must fall back to its own limits within register 1288 (60 s) and cover the house again. start: "2026-12-07T20:00:00+01:00" duration_s: 7200 step_s: 10 @@ -13,6 +13,8 @@ house: min_soc_pct: 10 external_control: 2 byte_order: little + modbus_scan_s: 10 + stale_limits: {1280: 5000, 1282: 0} control: import_limit_w: 12000 battery: diff --git a/tests/controller/test_battery_intents.py b/tests/controller/test_battery_intents.py index b1c44d4..a461bb3 100644 --- a/tests/controller/test_battery_intents.py +++ b/tests/controller/test_battery_intents.py @@ -265,3 +265,27 @@ def test_grid_charging_power_is_never_surplus_for_consumers() -> None: assert charging.latest_site_w == -3000 # the import, not the battery's charge plain = SurplusTracker(60).update(T0, snapshot, goals) assert plain.charging_available + + +def test_a_stale_soc_never_sets_a_floor() -> None: + """Review 4-G minor 7: only an OK SoC reading counts.""" + from suncore.core.balance import Flow, FlowSnapshot # noqa: PLC0415 + from suncore.core.signals import Quality # noqa: PLC0415 + + ok = Flow(500.0, Quality.OK) + snapshot = FlowSnapshot( + grid_w=ok, + pv_w=Flow(0.0, Quality.OK), + battery_w=Flow(0.0, Quality.OK), + house_w=Flow(None, Quality.UNAVAILABLE), + battery_soc_pct=Flow(42.0, Quality.STALE), + ) + rest = inputs(capabilities=REST_CAPS, ranges=REST_RANGES) + result = Controller([]).step( + T0, ControllerInputs(flows=snapshot, plan=plan(discharge_lock=True), battery=rest) + ) + assert result.intents == () + assert result.battery is not None + assert [r.key for r in result.battery.reasons] == [ + "controller.battery.discharge_lock_unsupported" + ] diff --git a/tests/core/test_battery_contracts.py b/tests/core/test_battery_contracts.py index 1933401..99311df 100644 --- a/tests/core/test_battery_contracts.py +++ b/tests/core/test_battery_contracts.py @@ -154,13 +154,11 @@ def test_settings_are_not_identity() -> None: link = ModbusLink(slave=71, byte_order=ModbusByteOrder.LITTLE) a = battery_identity_token(_battery(modbus=link, fallback_measured=False), _site()) b = battery_identity_token( - _battery( - modbus=link.model_copy(update={"byte_order": ModbusByteOrder.BIG}), - fallback_measured=True, - ), - _site(), + _battery(modbus=link.model_copy(update={"byte_order": ModbusByteOrder.BIG})), _site() ) assert a == b + measured = battery_identity_token(_battery(modbus=link, fallback_measured=True), _site()) + assert measured != a # lifts the assisted cap: identity (review minor 5) assert base != a inverted = _site().model_copy( update={ diff --git a/tests/sim/test_battery_scenarios.py b/tests/sim/test_battery_scenarios.py index 5e5a00a..7c4653f 100644 --- a/tests/sim/test_battery_scenarios.py +++ b/tests/sim/test_battery_scenarios.py @@ -92,9 +92,16 @@ def test_modbus_arms_the_fallback_then_locks_with_a_heartbeat( writes = [w for w in inverter.log.writes if w[1] == "modbus"] addresses = [w[2]["address"] for w in writes] assert addresses[:3] == [1284, 1286, 1288] # the fallback first + start = runner.scenario.start assert inverter.registers[1284] == inverter.own_charge_w assert inverter.registers[1286] == inverter.own_discharge_w assert inverter.registers[1288] == 60 + # The stale lock in 1282 (an earlier controller) never became the baseline (review M1). + takeover = next(d for d in runner.battery_decisions() if d.kind is DecisionKind.ACCEPTED) + assert takeover.intent.action == BatteryAction(max_discharge_w=0) + stored = asyncio.run(runner.store.load_runtime("battery")) + assert stored is not None + assert stored.baseline == BatteryAction(max_charge_w=5000, max_discharge_w=5000) # The heartbeat re-writes 1280/1282 every 20 s while the lease holds (first hour). start = runner.scenario.start limit_writes = [ @@ -315,7 +322,9 @@ def test_cloud_flicker_does_not_make_the_battery_oscillate( PLAN_EVERY_STEPS = 30 # 15 minutes at 30 s per step -async def _grid_charge_run() -> tuple[RunResult, ScenarioRunner, SimInverter, list[Plan]]: +async def _grid_charge_run( + live_price: Callable[[datetime], float | None] | None = None, +) -> tuple[RunResult, ScenarioRunner, SimInverter, list[Plan]]: from dataclasses import replace # noqa: PLC0415 from suncore.app.planning import ( # noqa: PLC0415 @@ -328,7 +337,7 @@ async def _grid_charge_run() -> tuple[RunResult, ScenarioRunner, SimInverter, li scenario = load_scenario("grid_charge_price_level") base = replace(situation("grid_charge_price_level"), import_limit_w=8000.0) - runner = ScenarioRunner(scenario, catalog(), import_price=base.import_price) + runner = ScenarioRunner(scenario, catalog(), import_price=live_price or base.import_price) plans: list[Plan] = [] def live() -> LiveReading: @@ -417,3 +426,31 @@ def test_the_battery_gets_its_own_settings_back_after_the_window( assert all(s.battery_w <= 50 for s in late) hours = runner.scenario.duration_s / 3600 assert len(battery_actions(runner, DecisionKind.ACCEPTED)) <= 4 * hours # no oscillation + + +def _price_jump(at: datetime) -> float | None: + """The cheap night price, but at 03:30 the live price jumps above the policy's level.""" + hour = at.hour + at.minute / 60 + if 3.5 <= hour < 5: + return 0.35 + return 0.15 if 1 <= hour < 5 else 0.35 + + +def test_a_price_jump_inside_the_window_ends_grid_charging() -> None: + """Review minor 6: the plan still says "charge" (it planned on older prices), the live price + left the policy - the lease ends and nothing is forced any more.""" + result, runner, inverter, _ = asyncio.run(_grid_charge_run(_price_jump)) + ended = [ + d + for d in runner.battery_decisions() + if "safety.battery_grid_charge_policy" in keys(d) and _local_hour(d.ts) >= 3.5 + ] + assert ended + forced = [ + w for w in inverter.log.writes if w[1] == "number.sim_battery_grid_charge" and w[2] > 0 + ] + assert forced + assert all(_local_hour(t) < 3.5 for t, _, _ in forced) + after = [s for s in result.steps if 3.55 <= _local_hour(s.t) < 5 and s.pv_w < 1] + assert after + assert all(s.battery_w <= 50 for s in after) diff --git a/tests/storage/test_config_sections.py b/tests/storage/test_config_sections.py index 916496b..1304c2d 100644 --- a/tests/storage/test_config_sections.py +++ b/tests/storage/test_config_sections.py @@ -816,3 +816,11 @@ async def test_restore_operation_for_an_observe_only_battery_is_shadow(db: Datab restored = await store.restore("operation", entry.id) assert isinstance(restored, OperationConfig) assert restored.battery_mode is OperatingMode.SHADOW + + +async def test_marking_the_fallback_measured_drops_the_battery_to_shadow(db: Database) -> None: + """Review 4-G minor 5: it lifts the assisted cap - re-confirm with the new identity token.""" + store = ConfigStore(db) + await _battery_assisted(store) + await store.put("battery", _battery_settings().model_copy(update={"fallback_measured": True})) + assert await _battery_mode(store) is OperatingMode.SHADOW From c37597e5949a8f858af763a9e1a5cc8a755708f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 06:39:14 +0000 Subject: [PATCH 13/16] docs: STATUS, plan deviations, architecture and an ADR-0013 implementation addendum for the PR 4-G review fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ADR-0013 addendum (no decision changed): invariants in safety/battery.py, B4/B5 on the written state, release completes on read-back, kostal_modbus baseline/fallback, identity includes fallback_measured, reserve behaviour (maintainer default) answered - plan deviations: review fixes 2026-10-26; architecture §4: release latch and lease ends Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- docs/STATUS.md | 15 +++++++++++---- docs/adr/0013-battery-as-controlled-asset.md | 20 ++++++++++++++++++++ docs/architecture.md | 5 ++++- docs/plans/phase-4.md | 11 +++++++++++ 4 files changed, 46 insertions(+), 5 deletions(-) diff --git a/docs/STATUS.md b/docs/STATUS.md index c5caf32..38f5b02 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -133,6 +133,13 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 `kostal_rest_reserve`, `inverter_hang_battery`, `grid_charge_price_level` (real planner, controller and gate in automatic mode). - Decisions and deviations: plan §"Deviations during implementation" (PR 4-G). + - Review fixes (2026-10-26, reviewer blocker B1, M1-M3, minors 1-8): latched battery release + with read-back of the original baseline and back-off retries (also under emergency stop), + B4/B5 on the written state, Kostal §3.5 baseline = own limits and fallback confirmed against + the written values, register 5 role, lease ends on refusal / plan end, arming outside the + lock, user's select/switch restored, `fallback_measured` is identity, OK-only SoC, a more + realistic simulator (REST 30 s, modbus scan lag, stale registers, price jump). ADR-0013 got + an implementation addendum. - **Phase 4 – PR 4-F, part WP8 planner (branch `phase-4/f-planner`, on 4-E merged with 4-C)**: - `suncore/planner/` (depends on `core` only; boundary test extended; `mypy --strict`): @@ -551,9 +558,9 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 - **WP10 done** (4-G, see Done); next: 4-H UI and docs (battery card with mode, identity and the assisted cap; wizard step for the battery adapter incl. enabling the Kostal number and the modbus YAML; WP13 docs). ADR-0013 file still says "proposed" - record the maintainer's acceptance. -- Maintainer questions from 4-G (PR description): permanent reserve floor on the inverter or not; - grid charging on the Kostal (generic force-charge entity or a §3.4 ADR); the fallback timer - measurement procedure for `battery.fallback_measured`. +- Maintainer questions from 4-G (PR description): grid charging on the Kostal (generic + force-charge entity or a §3.4 ADR); the fallback timer measurement procedure for + `battery.fallback_measured`. Answered: no permanent reserve floor on the inverter. - **PR 4-C (WP4, branch `phase-4/c-tariff`)**: `suncore/tariff/` - a template-driven price adapter (`engine.py`: action or attribute source, list or mapping shape, per-MWh conversion, native grid from `end - start` or the timestamp spacing, 15/60-minute mixes as segments, gaps `None`, DST @@ -771,7 +778,7 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 | Open-Meteo azimuth convention in a live response (code: 0 = south, OpenAPI text contradicts); separate terms page (README only) | `research/integrations.md` | live request; maintainer reads the terms page | | Kostal REST battery/grid power sign; `ActivePowerLimitation` semantics; live entity ids | `research/integrations.md` | maintainer's HA (enable the entities, compare with the inverter display) | | Kostal Modbus external battery management not enabled on the maintainer's inverter; how it is enabled; §3.5 fallback timer behaviour (the `kostal_modbus` adapter and its fallback are exercised in the simulator only, scenario `modbus_heartbeat_lost`) | `research/kostal-plenticore-modbus.md`, ADR-0013, `suncore/devices/battery/kostal_modbus.py` | maintainer enables it and measures, then sets `battery.fallback_measured`; capped at assisted until then | -| Kostal Modbus U32 word order of register 1288 assumed equal to the float order (register 5); modbus sensor `scan_interval` vs the adapter's 15 s settle time | `suncore/devices/battery/modbus_codec.py`, `templates/battery/kostal.plenticore_g3_modbus.yaml` | first Modbus write on the maintainer's inverter | +| Kostal Modbus U32 word order of register 1288 assumed equal to the float order (register 5); modbus sensor `scan_interval` vs the adapter's 15 s settle time; how 1076/1078 (the battery's own limits) move with temperature and SoC (the fallback gets max(model, own)) | `suncore/devices/battery/modbus_codec.py`, `templates/battery/kostal.plenticore_g3_modbus.yaml` | first Modbus write on the maintainer's inverter | | Kostal REST: battery/grid power sign (the site's `invert_sign`), the min-SoC read-back timing after the forced refresh (35 s settle assumed), whether out-of-range values are clamped or rejected; the number is disabled by default | `suncore/devices/battery/kostal_plenticore.py`, `templates/battery/kostal.plenticore.yaml` | maintainer enables "Battery min SoC" and watches the first assisted write | | Creating a modbus hub from the HA UI (else YAML); the hub name and unit id the user configures | `research/ha-websocket-api.md`, `battery.modbus` | maintainer's HA | | Generic battery adapter (numbers/select/switch) and the battery watch thresholds (frozen 600 s / 50 W / grid 500 W, SoC frozen after 3 % of the capacity moved) | `suncore/devices/battery/generic.py`, `suncore/safety/battery.py` | first real battery integration; shadow run | diff --git a/docs/adr/0013-battery-as-controlled-asset.md b/docs/adr/0013-battery-as-controlled-asset.md index 04b47e4..2c91530 100644 --- a/docs/adr/0013-battery-as-controlled-asset.md +++ b/docs/adr/0013-battery-as-controlled-asset.md @@ -228,3 +228,23 @@ charging is possible on the maintainer's Kostal without §3.4 (see consequences) Accept as proposed; your input is needed on how grid charging should be executed on your Kostal in Phase 4 (not at all, a generic force-charge entity, or a later §3.4 ADR). + +## Addendum 2026-10-26: implementation notes (Phase 4 WP10, PR 4-G review) + +Additive, no decision above changes: + +- The battery invariants live in `safety/battery.py` (not `safety/invariants.py`, which stays the + device module); the gate's battery path is `SafetyGate._submit_battery`, the lease + `SafetyGate._battery_lease`. +- B4/B5 are judged on the **resolved state that is written** (and re-sent by the heartbeat), not + on the request: a cap or floor inherited from the baseline counts. Forced grid charging is no + discharge lock (its import is bounded by B2/B5). +- A release is complete only when the read-back shows the original baseline (or the user set a + third value). Until then the runtime keeps the original baseline, nothing else is written and + the release is retried with back-off, also during an emergency stop. +- `kostal_modbus`: the baseline (`None` fields, release) is the battery's own limits (1076/1078); + the fallback registers get the larger of the model's and the own limits and are confirmed + against the values written; register 5 must match the configured word order. +- `battery.fallback_measured` is part of the battery identity (it lifts the assisted cap). +- Reserve (maintainer default): SunCore enforces the effective reserve in the plan and the gate + only; the user's own lower inverter floor outside a SunCore lock stays as it is. diff --git a/docs/architecture.md b/docs/architecture.md index 3d1f125..003fcb5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -237,7 +237,10 @@ read-back. An adapter with a hardware fallback (Kostal §3.5) gets it armed and the first limit and is capped at assisted until `battery.fallback_measured`. An accepted state is a **lease**: `gate.poll()` re-judges it every tick and restores the baseline when the mode, the watchdog (site or battery scope, `gate.check_battery`: frozen battery power or SoC), stale inputs -or any invariant says so; the adapter's heartbeat re-writes only while it holds. Devices keep the +or any invariant says so (also when no fresh plan interval covers the held state, or the adapter +refuses); the adapter's heartbeat re-writes only while it holds. A battery release is complete +only when the read-back shows the original baseline; until then the release is retried with +back-off (also during an emergency stop) and nothing else is written. Devices keep the Phase 3 rule "no SunCore-caused import" unchanged, and the charging power of a forced grid charge is never surplus for them. diff --git a/docs/plans/phase-4.md b/docs/plans/phase-4.md index d3ba799..3074adb 100644 --- a/docs/plans/phase-4.md +++ b/docs/plans/phase-4.md @@ -591,6 +591,17 @@ shadow and assisted run is the acceptance test. a core `BatteryAdapterSpec` (`suncore.devices` imports only `core`). - Kostal Modbus §3.5 runs in the simulator only (external battery management is not enabled on the maintainer's inverter); it is capped at assisted until `battery.fallback_measured`. + - Review fixes (2026-10-26): a battery release completes only on a read-back of the original + baseline (retried with back-off, latched, never adopted as a new baseline; an adapter release + to an unavailable entity fails instead of succeeding silently); B4/B5 judge the written + state; `kostal_modbus` baseline = own limits, fallback = max(model, own) confirmed against the + written values, register 5 checked; the lease ends on an adapter refusal and when no fresh + plan interval covers the held state; the settle wait after arming runs outside the gate lock + and the invariants are judged again before `apply()`; the generic release restores the user's + own select option / switch state; `fallback_measured` is identity; the controller uses only an + OK SoC; a §3.5 takeover is never skipped because the registers merely show the value. + - **Answered (maintainer default):** SunCore enforces the effective reserve in plan and gate + only, it holds no permanent min-SoC floor on the inverter. ## 7. Out of scope for Phase 4 From db3635a99c8e3f5f4260a296f8c2ec9c0524400b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 11:44:12 +0000 Subject: [PATCH 14/16] fix(safety,devices): never take SunCore's own late or partial battery write for a user value The release's third-value shortcut compared the read-back only with last_written or pending_action. A pending write landing after an earlier confirmed one, or a partly applied multi-field write, was finalised as the user's choice and SunCore's own limit stayed on the battery. - DeviceRuntime.attempted keeps the resolved target of every write SunCore sent or attempted while under control (saved before apply, cleared when control ends). - safety.battery.user_changed_fields: a field is the user's only if it differs from the baseline and from every own value; restore_target keeps those fields and restores the rest. The release writes that state and waits for the read-back; the lease's override check uses the same rule. - A user change found during the release sets the override hold (next 04:00) like the lease's override path. - Generic adapter: the user's select option and switch state are remembered only before the first write attempt, never after a failed or partial apply. Regression tests: reviewer probe 3, mixed multi-field case, partial write without user change, late write on the lease, hold, driver retry; hypothesis properties for user_changed_fields/restore_target. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- suncore/devices/battery/generic.py | 9 +- suncore/safety/battery.py | 64 +++++++++ suncore/safety/gate.py | 67 ++++++--- suncore/safety/runtime.py | 4 + tests/devices/battery/test_battery_drivers.py | 44 ++++++ tests/safety/test_battery_gate.py | 128 +++++++++++++++++- tests/safety/test_battery_invariants.py | 62 +++++++++ 7 files changed, 360 insertions(+), 18 deletions(-) diff --git a/suncore/devices/battery/generic.py b/suncore/devices/battery/generic.py index 9622f8f..856b7a8 100644 --- a/suncore/devices/battery/generic.py +++ b/suncore/devices/battery/generic.py @@ -101,6 +101,9 @@ def __init__( self._capabilities = self._derive_capabilities() self._user_option: str | None = None self._user_switch_on: bool | None = None + self._attempted = False + """A write was attempted since the last completed release: the select/switch may show + SunCore's own (partial) position, never the user's choice (review 4-G re-check).""" # --- capabilities and ranges ------------------------------------------------------------- @@ -237,8 +240,11 @@ async def read_back(self) -> Action | None: async def apply(self, intent: Intent) -> str | None: action = self.battery_action(intent) self.begin() - if self._applied is None: + if not self._attempted: + # Only before the first write attempt: after a failed or partial write the select + # and switch may already show SunCore's position (review 4-G re-check, minor 3). self._remember_user_options() + self._attempted = True await self._write_state(action) self._applied = action return self.last_context_id() @@ -367,6 +373,7 @@ async def release(self, baseline: Action | None) -> None: await self._write_switch(on=bool(self._user_switch_on)) self._user_option = None self._user_switch_on = None + self._attempted = False __all__ = ["GenericBatteryDriver"] diff --git a/suncore/safety/battery.py b/suncore/safety/battery.py index cd3a243..2eb1efc 100644 --- a/suncore/safety/battery.py +++ b/suncore/safety/battery.py @@ -514,6 +514,68 @@ def same_state(a: Action | None, b: Action | None, fields: Sequence[str]) -> boo return True +def _field_equal(name: str, a: float | None, b: float | None) -> bool: + if a is None or b is None: + return False + tolerance = SOC_TOLERANCE_PCT if name == "min_soc_pct" else POWER_TOLERANCE_W + return abs(a - b) <= tolerance + + +def user_changed_fields( + observed: Action | None, + baseline: Action | None, + own: Sequence[Action], + fields: Sequence[str], +) -> tuple[str, ...]: + """The fields of ``observed`` that only the user can have set (review 4-G re-check). + + A field counts as changed by the user only if its read-back value differs from the + ``baseline`` **and** from every value SunCore wrote or attempted for it (``own``: the + resolved targets of all writes while under control). A late-landing or partly applied + SunCore write therefore never passes for the user's choice. An unreadable field is + never the user's (unknown is restored, not kept). + """ + if not isinstance(observed, BatteryAction): + return () + base = baseline if isinstance(baseline, BatteryAction) else None + changed: list[str] = [] + for name in fields: + got = getattr(observed, name) + if got is None: + continue + if base is not None and _field_equal(name, getattr(base, name), got): + continue + if any( + isinstance(action, BatteryAction) and _field_equal(name, getattr(action, name), got) + for action in own + ): + continue + changed.append(name) + return tuple(changed) + + +def restore_target( + baseline: Action | None, observed: Action | None, user_fields: Sequence[str] +) -> Action | None: + """What a release restores: the baseline, with the user's own fields kept. + + Falls back to the plain baseline when the mix is not a valid ``BatteryAction`` (the + known-good takeover state wins over a combination nobody chose). + """ + if ( + not user_fields + or not isinstance(baseline, BatteryAction) + or not isinstance(observed, BatteryAction) + ): + return baseline + values = baseline.model_dump() + values.update({name: getattr(observed, name) for name in user_fields}) + try: + return BatteryAction.model_validate(values) + except ValueError: + return baseline + + def readable_fields(capabilities: frozenset[BatteryCapability]) -> tuple[str, ...]: """The action fields an adapter with ``capabilities`` writes and reads back.""" return tuple(name for name in BATTERY_ACTION_FIELDS if FIELD_CAPABILITY[name] in capabilities) @@ -623,5 +685,7 @@ def check(self, now: datetime, live: BatteryLive, capacity_wh: float | None) -> "projected_import_w", "quantise", "readable_fields", + "restore_target", "same_state", + "user_changed_fields", ] diff --git a/suncore/safety/gate.py b/suncore/safety/gate.py index 0a05012..93622cc 100644 --- a/suncore/safety/gate.py +++ b/suncore/safety/gate.py @@ -98,7 +98,9 @@ plan_band, quantise, readable_fields, + restore_target, same_state, + user_changed_fields, ) from suncore.safety.invariants import ( InvariantContext, @@ -914,6 +916,7 @@ async def _battery_write( # noqa: PLR0911, PLR0912, PLR0915 - one return per ve "baseline": baseline, "baseline_ts": now, "identity": config.identity, + "attempted": (), } ) took_over = True @@ -925,7 +928,14 @@ async def _battery_write( # noqa: PLR0911, PLR0912, PLR0915 - one return per ve if not armed: self._limiter.release_slot(BATTERY_ASSET_ID, previous_slot) return await self._decide(intent, DecisionKind.REJECTED, now, violations, mode) - if took_over: + # Every target SunCore sends is remembered (and saved) *before* the write: a + # write that lands late or only in part is never taken for the user's own + # state by a release (review 4-G re-check). + if took_over or ctx.target not in runtime.attempted: + if ctx.target not in runtime.attempted: + runtime = runtime.model_copy( + update={"attempted": (*runtime.attempted, ctx.target)} + ) await self._save(runtime) written = intent.model_copy(update={"action": ctx.target}) try: @@ -1094,7 +1104,13 @@ async def _battery_override( base = runtime.baseline if isinstance(runtime.baseline, BatteryAction) else None target = quantise(resolve_battery_action(held, base), actuator.ranges()) observed = await actuator.read_back() - if observed is None or same_state(target, observed, readable_fields(actuator.capabilities)): + fields = readable_fields(actuator.capabilities) + if observed is None or same_state(target, observed, fields): + return None + if not user_changed_fields(observed, runtime.baseline, self._own_targets(runtime), fields): + # Only SunCore's own earlier values (a late-landing write): no override; the next + # write or heartbeat brings the held state back (review 4-G re-check). + log.info("safety.battery_own_state_late", observed=observed.model_dump()) return None async with self._lock(BATTERY_ASSET_ID): until = overrides.resume_at(_DEFAULT_POLICY, now, self._tz) @@ -1105,6 +1121,7 @@ async def _battery_override( "last_written": None, "pending_action": None, "pending_ts": None, + "attempted": (), } ) await self._save(released) @@ -1466,11 +1483,6 @@ async def _release_battery( # noqa: PLR0917 fields = readable_fields(caps) fallback = BatteryCapability.HARDWARE_FALLBACK in caps observed = await actuator.read_back() - held = runtime.last_written or runtime.pending_action - held_target: Action | None = None - if isinstance(held, BatteryAction) and isinstance(actuator, BatteryActuator): - base = baseline if isinstance(baseline, BatteryAction) else None - held_target = quantise(resolve_battery_action(held, base), actuator.ranges()) checking = runtime.release_due_reason == REASON_BATTERY_RELEASE_CHECK.key if observed is not None and same_state(baseline, observed, fields): return await self._battery_released( @@ -1480,15 +1492,25 @@ async def _release_battery( # noqa: PLR0917 mode, (REASON_RELEASED, REASON_BATTERY_RELEASE_CONFIRMED if checking else reason), ) - if ( - observed is not None - and not fallback - and (held_target is None or not same_state(held_target, observed, fields)) - ): - # Neither the baseline nor SunCore's state: the user set the limits meanwhile. - return await self._battery_released( - intent, runtime, now, mode, (REASON_RELEASED, REASON_BATTERY_OVERRIDE) - ) + if observed is not None and not fallback: + # A field is the user's only if it differs from the baseline *and* from every value + # SunCore wrote or attempted for it; everything else goes back to the baseline and + # is proven by read-back (review 4-G re-check: a late-landing or partly applied + # write of SunCore's never passes for a user value). + user = user_changed_fields(observed, baseline, self._own_targets(runtime), fields) + if user: + baseline = restore_target(baseline, observed, user) + if baseline != runtime.baseline: + until = overrides.resume_at(_DEFAULT_POLICY, now, self._tz) + runtime = overrides.hold_until(runtime, until).model_copy( + update={"baseline": baseline} + ) + log.info("safety.battery_override", until=until, fields=user) + if same_state(baseline, observed, fields): + return await self._battery_released( + intent, runtime, now, mode, (REASON_RELEASED, REASON_BATTERY_OVERRIDE) + ) + await self._save(runtime) attempt = self._release_attempts.get(BATTERY_ASSET_ID, 0) try: await actuator.release(baseline) @@ -1564,6 +1586,7 @@ async def _battery_released( "pending_ts": None, "release_due_ts": None, "release_due_reason": None, + "attempted": (), } ) await self._save(released) @@ -1572,6 +1595,18 @@ async def _battery_released( } return await self._decide(intent, DecisionKind.ACCEPTED, now, reasons, mode) + def _own_targets(self, runtime: DeviceRuntime) -> tuple[Action, ...]: + """Every battery state SunCore wrote or attempted while under control (resolved).""" + own: list[Action] = list(runtime.attempted) + actuator = self._battery_actuator() + base = runtime.baseline if isinstance(runtime.baseline, BatteryAction) else None + for held in (runtime.last_written, runtime.pending_action): + if isinstance(held, BatteryAction): + own.append(resolve_battery_action(held, base)) + if actuator is not None: + own.append(quantise(resolve_battery_action(held, base), actuator.ranges())) + return tuple(own) + def _identity_of(self, asset_id: str) -> str | None: """The configured identity token of an asset (``None`` = not configured).""" if asset_id == BATTERY_ASSET_ID and self._battery is not None: diff --git a/suncore/safety/runtime.py b/suncore/safety/runtime.py index f699f5b..4035f1f 100644 --- a/suncore/safety/runtime.py +++ b/suncore/safety/runtime.py @@ -52,6 +52,10 @@ class DeviceRuntime(BaseModel): pending_action: Action | None = None """A write whose read-back did not confirm it yet (slow echo); see ``overrides.judge``.""" pending_ts: AwareDatetime | None = None + attempted: tuple[Action, ...] = () + """Battery: the resolved targets of every write SunCore sent or attempted while under + control (deduplicated). A release never takes one of these values for the user's own + (a late-landing or partly applied write); cleared when control ends.""" release_due_ts: AwareDatetime | None = None """A deferred release (min run/pause) is executed by ``SafetyGate.poll`` at this time.""" release_due_reason: str | None = None diff --git a/tests/devices/battery/test_battery_drivers.py b/tests/devices/battery/test_battery_drivers.py index 823bc74..b2ce991 100644 --- a/tests/devices/battery/test_battery_drivers.py +++ b/tests/devices/battery/test_battery_drivers.py @@ -173,6 +173,50 @@ def _with_controls(controls: dict[str, Any], roles: dict[str, Any]) -> BatteryAd return BatteryTemplate.model_validate(base).adapter_spec() +async def test_a_failed_first_write_never_becomes_the_users_option() -> None: + """Review 4-G re-check, minor 3: the select position SunCore's own failed write left is not + remembered as the user's choice by the retry; the release restores the user's option.""" + role = {"matcher": {"domain": "select"}, "description": "template.acme.battery.role.mode"} + tpl = _with_controls( + { + "mode": { + "kind": "mode", + "options": [ + {"value": "Auto", "meaning": "auto"}, + {"value": "Hold", "meaning": "no_discharge"}, + {"value": "Eco", "meaning": "other"}, + ], + } + }, + {"mode": role}, + ) + ha = FakeHA() + ha.set("select.mode", "Eco") + failures = [RuntimeError("timeout")] + + async def flaky(*args: Any, **kwargs: Any) -> Any: + result = await ha.write(*args, **kwargs) + if failures: + raise failures.pop() # the call reached HA, the answer did not come back + return result + + driver = GenericBatteryDriver( + tpl, settings("acme.battery", {"mode": "select.mode"}), write=flaky, states=ha.lookup + ) + with pytest.raises(RuntimeError): + await driver.apply(battery_intent(max_discharge_w=0)) + ha.set("select.mode", "Hold") # SunCore's write landed after all + await driver.apply(battery_intent(max_discharge_w=0)) + await driver.release(None) + assert ha.sent[-1][3] == {"option": "Eco"} + # After a completed release the next takeover remembers the user's option again. + ha.set("select.mode", "Auto") + await driver.apply(battery_intent(max_discharge_w=0)) + ha.set("select.mode", "Hold") + await driver.release(None) + assert ha.sent[-1][3] == {"option": "Auto"} + + async def test_select_based_lock_and_force_charge() -> None: role = {"matcher": {"domain": "select"}, "description": "template.acme.battery.role.mode"} tpl = _with_controls( diff --git a/tests/safety/test_battery_gate.py b/tests/safety/test_battery_gate.py index a65a9a5..9044958 100644 --- a/tests/safety/test_battery_gate.py +++ b/tests/safety/test_battery_gate.py @@ -5,7 +5,7 @@ from __future__ import annotations from dataclasses import dataclass, field -from datetime import timedelta +from datetime import UTC, timedelta from typing import Any import pytest @@ -31,6 +31,8 @@ ReleaseAction, SwitchAction, ) +from suncore.core.devices import OverridePolicy +from suncore.safety import overrides from suncore.safety.battery import BatteryActuator, BatteryGateConfig, BatteryWatch from suncore.safety.gate import SafetyGate from suncore.safety.modes import StaticModes @@ -619,6 +621,130 @@ async def test_a_user_change_during_the_release_is_kept() -> None: done = [d for _ in range(4) for d in await r.tick(5)] assert [keys(d) for d in done] == [["safety.released", "safety.battery_override"]] assert r.battery.state == user + # Review 4-G re-check, minor 2: the user's choice is held like a lease override (04:00). + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.override + assert runtime.override_until == overrides.resume_at(OverridePolicy(), done[0].ts, UTC) + assert runtime.is_held(r.clock.now) + await r.gate.clear_emergency_stop() + assert (await r.submit(BatteryAction(max_discharge_w=0))).kind is DecisionKind.HELD + assert r.battery.state == user + + +async def test_a_late_landing_own_write_is_never_taken_for_a_user_value() -> None: + """Review 4-G re-check (reviewer probe 3): a pending write that lands after its read-back + window, behind an earlier confirmed write, is SunCore's state - the release writes the + original baseline and waits for the read-back instead of keeping SunCore's 45 % floor.""" + r = rig() + first = await r.submit(BatteryAction(max_discharge_w=0)) + assert first.kind is DecisionKind.ACCEPTED, keys(first) + r.clock.advance(120) + r.at(grid_w=600, battery_w=0, soc_pct=40) + r.battery.silent_fail = True + late = await r.submit(BatteryAction(min_soc_pct=45)) + assert late.kind is DecisionKind.FAILED, keys(late) + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert isinstance(late.intent.action, BatteryAction) + r.battery.state = resolve_battery_action(late.intent.action, runtime.baseline) # lands late + r.battery.silent_fail = False + await r.gate.emergency_stop() + assert r.battery.released == [BASE] + assert r.battery.state == BASE + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert not runtime.override # nothing was the user's + assert "safety.battery_override" not in [k for d in r.decisions for k in keys(d)] + + +async def test_a_partial_own_write_is_restored_and_only_the_users_field_is_kept() -> None: + """Review 4-G re-check, mixed multi-field case: one field still shows SunCore's partly + applied write, another the user's value - SunCore's goes back to the baseline, the user's + stays, the result is proven by read-back and held as an override.""" + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + r.clock.advance(120) + r.at(grid_w=600, battery_w=0, soc_pct=40) + + async def partial(intent: Intent) -> str | None: # only the SoC floor reaches the battery + assert isinstance(intent.action, BatteryAction) + assert isinstance(r.battery.state, BatteryAction) + r.battery.state = r.battery.state.model_copy( + update={"min_soc_pct": intent.action.min_soc_pct} + ) + msg = "number.max_discharge did not answer" + raise RuntimeError(msg) + + r.battery.apply = partial # type: ignore[method-assign] + failed = await r.submit(BatteryAction(max_discharge_w=1000, min_soc_pct=45)) + assert failed.kind is DecisionKind.FAILED, keys(failed) + assert isinstance(r.battery.state, BatteryAction) + # SunCore's 0 W cap and 45 % floor are on the battery; the user lowers the charge cap. + r.battery.state = r.battery.state.model_copy(update={"max_charge_w": 3000}) + await r.gate.emergency_stop() + kept = BASE.model_copy(update={"max_charge_w": 3000}) + assert r.battery.released == [kept] + assert r.battery.state == kept + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.under_control # until the read-back confirms + assert runtime.override + done = [d for _ in range(6) for d in await r.tick(5)] + assert [keys(d) for d in done] == [["safety.released", "safety.battery_release_confirmed"]] + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert not runtime.under_control + assert runtime.attempted == () + assert runtime.is_held(r.clock.now) + + +async def test_a_partial_own_write_without_user_change_restores_the_full_baseline() -> None: + r = rig() + await r.submit(BatteryAction(max_discharge_w=0)) + r.clock.advance(120) + r.at(grid_w=600, battery_w=0, soc_pct=40) + landed = BASE.model_copy(update={"max_discharge_w": 1000}) # half of a two-field write + + async def partial(_: Intent) -> str | None: + r.battery.state = landed + msg = "timeout" + raise RuntimeError(msg) + + r.battery.apply = partial # type: ignore[method-assign] + await r.submit(BatteryAction(max_discharge_w=1000, min_soc_pct=45)) + await r.gate.emergency_stop() + assert r.battery.released == [BASE] + assert r.battery.state == BASE + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert not runtime.override + + +async def test_a_late_landing_earlier_write_is_no_lease_override() -> None: + """The same class on the lease: an earlier failed write that lands behind a confirmed one + is SunCore's own value - no override, the next write brings the held state back.""" + r = rig() + r.battery.silent_fail = True + stale = await r.submit(BatteryAction(max_discharge_w=0)) + assert stale.kind is DecisionKind.FAILED, keys(stale) + r.battery.silent_fail = False + r.clock.advance(120) + r.at(grid_w=600, battery_w=0, soc_pct=40) + held = await r.submit(BatteryAction(min_soc_pct=20)) + assert held.kind is DecisionKind.ACCEPTED, keys(held) + r.battery.state = BASE.model_copy(update={"max_discharge_w": 0}) # the stale write lands + r.clock.advance(60) + r.at(grid_w=600, battery_w=0, soc_pct=40) + rows = await r.tick(5) + assert "safety.battery_override" not in [k for d in rows for k in keys(d)] + runtime = r.gate.runtime_of(BATTERY_ASSET_ID) + assert runtime is not None + assert runtime.under_control + assert not runtime.override + again = await r.submit(BatteryAction(min_soc_pct=20)) + assert again.kind is DecisionKind.ACCEPTED, keys(again) + assert r.battery.state == BASE.model_copy(update={"min_soc_pct": 20}) # --- watchdog (B8) ------------------------------------------------------------------------------ diff --git a/tests/safety/test_battery_invariants.py b/tests/safety/test_battery_invariants.py index f593e17..22f9c73 100644 --- a/tests/safety/test_battery_invariants.py +++ b/tests/safety/test_battery_invariants.py @@ -37,7 +37,9 @@ plan_band, projected_import_w, quantise, + restore_target, same_state, + user_changed_fields, ) NOW = datetime(2026, 10, 24, 2, 0, tzinfo=UTC) @@ -548,3 +550,63 @@ def test_the_generator_produces_accepted_actions_of_every_kind() -> None: assert find( contexts(), lambda c: accepted(c) and c.requested.min_soc_pct is not None, settings=quick ) + + +# --- release: whose value is it (review 4-G re-check) ------------------------------------------- + +_FIELDS = ("max_charge_w", "max_discharge_w", "min_soc_pct", "grid_charge_w") +_power = st.integers(min_value=0, max_value=50).map(lambda n: float(n * 100)) +_soc = st.integers(min_value=1, max_value=20).map(lambda n: float(n * 5)) + + +@st.composite +def _limits(draw: Any) -> BatteryAction: + charge = draw(_power) + return BatteryAction( + max_charge_w=charge, + max_discharge_w=draw(_power), + min_soc_pct=draw(_soc), + grid_charge_w=draw(st.sampled_from([0.0, charge])), + ) + + +@given(base=_limits(), own=st.lists(_limits(), min_size=1, max_size=4), data=st.data()) +@settings(max_examples=300, deadline=None) +def test_own_or_baseline_values_are_never_the_users( + base: BatteryAction, own: list[BatteryAction], data: Any +) -> None: + """Every field shows the baseline or some value SunCore wrote/attempted (late, partial, + any mix): nothing is the user's, so a release writes the full baseline.""" + sources = [base, *own] + observed = {name: getattr(data.draw(st.sampled_from(sources)), name) for name in _FIELDS} + mixed = BatteryAction.model_construct(**observed) + assert user_changed_fields(mixed, base, own, _FIELDS) == () + assert restore_target(base, mixed, ()) == base + + +@given(base=_limits(), own=st.lists(_limits(), max_size=4), name=st.sampled_from(_FIELDS)) +@settings(max_examples=300, deadline=None) +def test_a_value_nobody_wrote_is_the_users_and_kept( + base: BatteryAction, own: list[BatteryAction], name: str +) -> None: + taken = {getattr(a, name) for a in (base, *own)} + value = next(v for v in (n * 100.0 + 50.0 for n in range(60)) if v not in taken) + if name == "min_soc_pct": + value = next(v for v in (n * 5.0 + 2.5 for n in range(20)) if v not in taken) + observed = base.model_copy(update={name: value}) + assert user_changed_fields(observed, base, own, _FIELDS) == (name,) + restored = restore_target(base, observed, (name,)) + if ( + name in {"grid_charge_w", "max_charge_w"} + and observed.grid_charge_w is not None + and (observed.max_charge_w is not None and observed.grid_charge_w > observed.max_charge_w) + ): + assert restored == base # an invalid mix falls back to the known-good baseline + else: + assert restored == observed + + +def test_an_unreadable_field_is_never_the_users() -> None: + base = BatteryAction(max_charge_w=5000, max_discharge_w=5000, min_soc_pct=10, grid_charge_w=0) + observed = BatteryAction(max_charge_w=5000, max_discharge_w=None, min_soc_pct=10) + assert user_changed_fields(observed, base, (), _FIELDS) == () From 59b834255fa6f6abf03eb99f563156f42e67b788 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 11:58:12 +0000 Subject: [PATCH 15/16] docs: STATUS, plan deviations and ADR-0013 addendum for the PR 4-G re-check fixes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- docs/STATUS.md | 5 ++++- docs/adr/0013-battery-as-controlled-asset.md | 4 ++++ docs/plans/phase-4.md | 6 ++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/docs/STATUS.md b/docs/STATUS.md index 38f5b02..08fca89 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -139,7 +139,10 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 the written values, register 5 role, lease ends on refusal / plan end, arming outside the lock, user's select/switch restored, `fallback_measured` is identity, OK-only SoC, a more realistic simulator (REST 30 s, modbus scan lag, stale registers, price jump). ADR-0013 got - an implementation addendum. + an implementation addendum. Re-check fixes (2026-10-28): own late/partial writes are never + taken for user values (`DeviceRuntime.attempted`, per-field rule), user values found during a + release get the override hold, the generic adapter remembers user options only before its + first write attempt. - **Phase 4 – PR 4-F, part WP8 planner (branch `phase-4/f-planner`, on 4-E merged with 4-C)**: - `suncore/planner/` (depends on `core` only; boundary test extended; `mypy --strict`): diff --git a/docs/adr/0013-battery-as-controlled-asset.md b/docs/adr/0013-battery-as-controlled-asset.md index 2c91530..31c8b9b 100644 --- a/docs/adr/0013-battery-as-controlled-asset.md +++ b/docs/adr/0013-battery-as-controlled-asset.md @@ -242,6 +242,10 @@ Additive, no decision above changes: - A release is complete only when the read-back shows the original baseline (or the user set a third value). Until then the runtime keeps the original baseline, nothing else is written and the release is retried with back-off, also during an emergency stop. +- A field is the user's third value only if it differs from the baseline **and** from every + target SunCore wrote or attempted while under control (`DeviceRuntime.attempted`); a late or + partly applied SunCore write is restored, the user's fields are kept (restore = baseline with + those fields), proven by read-back and held like any override (next 04:00). - `kostal_modbus`: the baseline (`None` fields, release) is the battery's own limits (1076/1078); the fallback registers get the larger of the model's and the own limits and are confirmed against the values written; register 5 must match the configured word order. diff --git a/docs/plans/phase-4.md b/docs/plans/phase-4.md index 3074adb..dc440f7 100644 --- a/docs/plans/phase-4.md +++ b/docs/plans/phase-4.md @@ -600,6 +600,12 @@ shadow and assisted run is the acceptance test. and the invariants are judged again before `apply()`; the generic release restores the user's own select option / switch state; `fallback_measured` is identity; the controller uses only an OK SoC; a §3.5 takeover is never skipped because the registers merely show the value. + - Re-check fixes (2026-10-28): a field counts as the user's during a release (and for the + lease's override check) only if it differs from the baseline and from every target SunCore + wrote or attempted while under control (`DeviceRuntime.attempted`); SunCore's own late or + partial values go back to the baseline and are proven by read-back, the user's fields stay + and get the override hold (next 04:00). The generic adapter remembers the user's select / + switch state only before its first write attempt. - **Answered (maintainer default):** SunCore enforces the effective reserve in plan and gate only, it holds no permanent min-SoC floor on the inverter. From 6cbaa4381e132db2c84a8ba5111f4639fdfb84f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 12:27:28 +0000 Subject: [PATCH 16/16] fix(safety): write the held battery state again when an older own state lands When the lease's read-back shows an older SunCore state instead of the held one, the gate now re-writes the held state through the evaluated write path (B1-B9 on the current inputs, read-back) and releases the battery if that write is not accepted. Adapters without a heartbeat would otherwise run the older, unjudged state until the lease ended. STATUS notes the accepted edge case (a user value equal to an own value is reset at release) for the 4-H user docs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e --- docs/STATUS.md | 5 ++++ frontend/src/lib/i18n/locales/de.json | 1 + frontend/src/lib/i18n/locales/en.json | 1 + suncore/safety/gate.py | 31 +++++++++++++++++++++---- tests/safety/test_battery_gate.py | 33 +++++++++++++++++++++++---- 5 files changed, 63 insertions(+), 8 deletions(-) diff --git a/docs/STATUS.md b/docs/STATUS.md index 08fca89..d351318 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -143,6 +143,11 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 taken for user values (`DeviceRuntime.attempted`, per-field rule), user values found during a release get the override hold, the generic adapter remembers user options only before its first write attempt. + Approval follow-up: when the read-back shows an older own state instead of the held one, + the gate writes the held state again through the evaluated path (B1-B9, read-back) or + releases if that is refused. For the 4-H user docs: a user value that happens to equal a + value SunCore wrote or attempted while in control is taken for SunCore's and reset to the + baseline at release (accepted by the reviewer). - **Phase 4 – PR 4-F, part WP8 planner (branch `phase-4/f-planner`, on 4-E merged with 4-C)**: - `suncore/planner/` (depends on `core` only; boundary test extended; `mypy --strict`): diff --git a/frontend/src/lib/i18n/locales/de.json b/frontend/src/lib/i18n/locales/de.json index 92f4b8e..62b9401 100644 --- a/frontend/src/lib/i18n/locales/de.json +++ b/frontend/src/lib/i18n/locales/de.json @@ -954,6 +954,7 @@ "safety.battery_unplanned_import": "Den Akku zurückzuhalten würde Netzbezug verursachen, und der Plan sieht das nicht vor.", "safety.battery_external_control_off": "Externes Batteriemanagement über Modbus ist aus (Register 1080 = {value}, nötig ist {expected}); nichts geschrieben.", "safety.battery_byte_order_mismatch": "Der Wechselrichter meldet die Byte-Reihenfolge {reported}, SunCore ist auf {configured} eingestellt: nichts wird geschrieben.", + "safety.battery_held_restored": "Der Akku zeigte eine ältere SunCore-Einstellung; SunCore schreibt die aktuelle erneut.", "action.battery": "Batterie-Limits setzen", "api.validation.forecast_workday_domain": "{entity_id} ist kein Binärsensor. Wähle den Binärsensor der Workday-Integration.", "api.validation.forecast_weather_domain": "{entity_id} ist keine Wetter-Entität.", diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index 19abdfd..2471d33 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -954,6 +954,7 @@ "safety.battery_unplanned_import": "Holding the battery back would make the house import, and the plan does not ask for it.", "safety.battery_external_control_off": "External battery management via Modbus is off (register 1080 = {value}, needs {expected}); nothing was written.", "safety.battery_byte_order_mismatch": "The inverter reports the byte order {reported}, SunCore is configured for {configured}: nothing is written.", + "safety.battery_held_restored": "The battery showed an older SunCore setting; SunCore writes the current one again.", "action.battery": "Set battery limits", "api.validation.forecast_workday_domain": "{entity_id} is not a binary sensor. Choose the binary sensor of the Workday integration.", "api.validation.forecast_weather_domain": "{entity_id} is not a weather entity.", diff --git a/suncore/safety/gate.py b/suncore/safety/gate.py index 93622cc..dd51e14 100644 --- a/suncore/safety/gate.py +++ b/suncore/safety/gate.py @@ -179,6 +179,7 @@ """After a release the battery does not show its baseline: retried with back-off, battery control stays blocked (latched in the runtime) until it does or the user changes the limits.""" REASON_BATTERY_RELEASE_CHECK: Final = Reason(key="safety.battery_release_check") +REASON_BATTERY_HELD_RESTORED: Final = Reason(key="safety.battery_held_restored") """The deferred read-back of a battery release (an adapter without hardware fallback).""" REASON_BATTERY_RELEASE_CONFIRMED: Final = Reason(key="safety.battery_release_confirmed") """The battery shows its own settings again: control of it has ended.""" @@ -1095,7 +1096,8 @@ async def _battery_lease(self, now: datetime) -> Decision | None: # noqa: PLR09 async def _battery_override( self, actuator: BatteryActuator, runtime: DeviceRuntime, now: datetime ) -> Decision | None: - """The held limits changed outside SunCore (after the settle time): let go, no write.""" + """The held limits changed after the settle time: the user's change lets go (no write); + SunCore's own older state is replaced by the held one again (or released).""" last = runtime.last_write_ts if last is None or (now - last).total_seconds() < 2 * actuator.settle_s: return None @@ -1108,10 +1110,12 @@ async def _battery_override( if observed is None or same_state(target, observed, fields): return None if not user_changed_fields(observed, runtime.baseline, self._own_targets(runtime), fields): - # Only SunCore's own earlier values (a late-landing write): no override; the next - # write or heartbeat brings the held state back (review 4-G re-check). + # Only SunCore's own earlier values (a late-landing write): no override. The battery + # runs a state the lease does not judge, so the held state is written again through + # the evaluated write path (B1-B9 on the current inputs, read-back); if that is not + # accepted, the battery is released (review 4-G approval, minor 2). log.info("safety.battery_own_state_late", observed=observed.model_dump()) - return None + return await self._restore_held(actuator, held, now) async with self._lock(BATTERY_ASSET_ID): until = overrides.resume_at(_DEFAULT_POLICY, now, self._tz) released = overrides.hold_until(runtime, until).model_copy( @@ -1595,6 +1599,25 @@ async def _battery_released( } return await self._decide(intent, DecisionKind.ACCEPTED, now, reasons, mode) + async def _restore_held( + self, actuator: BatteryActuator, held: BatteryAction, now: datetime + ) -> Decision: + """Write the held state again (normal evaluated path) or, if refused, release.""" + intent = Intent( + id=f"restore:{BATTERY_ASSET_ID}:{now.isoformat()}", + ts=now, + asset_id=BATTERY_ASSET_ID, + action=held, + reasons=(REASON_BATTERY_HELD_RESTORED,), + origin=Origin.SAFETY, + ) + mode = self.modes_of(BATTERY_ASSET_ID).effective + decision = await self._battery_write(intent, held, actuator, now, mode) + if decision.kind is DecisionKind.ACCEPTED: + return decision + reason = decision.reasons[0] if decision.reasons else REASON_BATTERY_HELD_RESTORED + return await self.release_device(BATTERY_ASSET_ID, reason, origin=Origin.SAFETY) + def _own_targets(self, runtime: DeviceRuntime) -> tuple[Action, ...]: """Every battery state SunCore wrote or attempted while under control (resolved).""" own: list[Action] = list(runtime.attempted) diff --git a/tests/safety/test_battery_gate.py b/tests/safety/test_battery_gate.py index 9044958..639d491 100644 --- a/tests/safety/test_battery_gate.py +++ b/tests/safety/test_battery_gate.py @@ -723,7 +723,8 @@ async def partial(_: Intent) -> str | None: async def test_a_late_landing_earlier_write_is_no_lease_override() -> None: """The same class on the lease: an earlier failed write that lands behind a confirmed one - is SunCore's own value - no override, the next write brings the held state back.""" + is SunCore's own value - no override; the held state is written again at once through the + evaluated path (review 4-G approval, minor 2: no heartbeat would restore it).""" r = rig() r.battery.silent_fail = True stale = await r.submit(BatteryAction(max_discharge_w=0)) @@ -736,15 +737,39 @@ async def test_a_late_landing_earlier_write_is_no_lease_override() -> None: r.battery.state = BASE.model_copy(update={"max_discharge_w": 0}) # the stale write lands r.clock.advance(60) r.at(grid_w=600, battery_w=0, soc_pct=40) + writes = len(r.battery.applied) rows = await r.tick(5) assert "safety.battery_override" not in [k for d in rows for k in keys(d)] + assert [d.kind for d in rows] == [DecisionKind.ACCEPTED] + assert rows[0].intent.reasons[0].key == "safety.battery_held_restored" + assert len(r.battery.applied) == writes + 1 + assert r.battery.state == BASE.model_copy(update={"min_soc_pct": 20}) runtime = r.gate.runtime_of(BATTERY_ASSET_ID) assert runtime is not None assert runtime.under_control assert not runtime.override - again = await r.submit(BatteryAction(min_soc_pct=20)) - assert again.kind is DecisionKind.ACCEPTED, keys(again) - assert r.battery.state == BASE.model_copy(update={"min_soc_pct": 20}) + assert runtime.last_written == BatteryAction(min_soc_pct=20) + + +async def test_a_refused_rewrite_of_the_held_state_releases() -> None: + """If the held state cannot be written again (here: rate limit), the battery is released + instead of running SunCore's older, unjudged state until the lease ends.""" + r = rig(settings=ControlSettings(min_write_interval_s=600)) + r.battery.silent_fail = True + await r.submit(BatteryAction(grid_charge_w=3000)) # fails, lands later + r.battery.silent_fail = False + r.clock.advance(600) + r.at(grid_w=600, battery_w=0, soc_pct=40) + r.plans["now"] = plan(now=r.clock.now, grid_charge_max_w=3000, discharge_lock=True) + held = await r.submit(BatteryAction(max_discharge_w=0)) + assert held.kind is DecisionKind.ACCEPTED, keys(held) + r.battery.state = BASE.model_copy(update={"grid_charge_w": 3000}) # the old target lands + r.clock.advance(60) + r.at(grid_w=600, battery_w=0, soc_pct=40) + rows = await r.tick(5) + assert [keys(d) for d in rows] == [["safety.released", "safety.rate_limited"]] + assert r.battery.released == [BASE] + assert r.battery.state == BASE # --- watchdog (B8) ------------------------------------------------------------------------------