Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions custom_components/pv_excess_control/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ class NotificationEvent(StrEnum):
CONF_BATTERY_TRICKLE_CHARGE_POWER_W = "battery_trickle_charge_power_w"

DEFAULT_BATTERY_TRICKLE_CHARGE_POWER_W = 100
# Balanced real-time battery reserve (issue #73). The base load matches the
# planner default; the buffer absorbs forecast error.
BALANCED_RESERVE_BASE_LOAD_W = 500.0
BALANCED_RESERVE_BUFFER_KWH = 0.5

# Current command controls and timestamp history
CONF_CURRENT_UPDATE_INTERVAL = "current_update_interval"
Expand Down
44 changes: 42 additions & 2 deletions custom_components/pv_excess_control/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from homeassistant.helpers.storage import Store
from homeassistant.util import dt as dt_util
from .daily_state import nonnegative_number
from .power_policy import battery_first_budget
from .power_policy import battery_first_budget, forecast_reserve_needed

from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

Expand Down Expand Up @@ -129,6 +129,8 @@
CONF_INVERTER_BATTERY_MAX_CHARGE_POWER_ENTITY,
CONF_BATTERY_MAX_CHARGE_POWER_W,
CONF_BATTERY_TRICKLE_CHARGE_POWER_W,
BALANCED_RESERVE_BASE_LOAD_W,
BALANCED_RESERVE_BUFFER_KWH,
DEFAULT_BATTERY_TRICKLE_CHARGE_POWER_W,
)
from .energy import create_tariff_provider
Expand Down Expand Up @@ -1354,7 +1356,10 @@ def _power_for_optimizer(
CONF_BATTERY_SOC, CONF_BATTERY_POWER, CONF_BATTERY_CHARGE_POWER,
CONF_BATTERY_DISCHARGE_POWER,
))
if strategy == BatteryStrategy.BATTERY_FIRST and has_battery:
reserve_charging = strategy == BatteryStrategy.BATTERY_FIRST
if strategy == BatteryStrategy.BALANCED and has_battery:
reserve_charging = self._balanced_forecast_reserve(power)
if reserve_charging and has_battery:
running_w = 0.0
for config in configs:
state = states.get(config.id)
Expand Down Expand Up @@ -1406,6 +1411,41 @@ def _power_for_optimizer(
for p in self.power_history
]

def _balanced_forecast_reserve(self, power: PowerState) -> bool:
"""Return whether Balanced reserves battery charging right now.

Without an available forecast, Balanced keeps its previous real-time
behavior (no reservation). With a forecast, charging is reserved only
when the remaining forecast cannot reach the target SoC by the target
time; a missing SoC then falls back to the Battery First handling.
"""
was_active = getattr(self, "_balanced_reserve_active", False)
forecast = getattr(self, "_forecast_data", None)
if getattr(self, "_forecast_status", None) != "available" or forecast is None:
self._balanced_reserve_active = False
return False
data = self.config_entry.data
now = dt_util.now()
target_time = _parse_time_string(data.get(CONF_BATTERY_TARGET_TIME, "16:00")) or time(16, 0)
target_dt = datetime.combine(now.date(), target_time, tzinfo=now.tzinfo)
hours_to_target = max((target_dt - now).total_seconds() / 3600.0, 0.0)
capacity = data.get(CONF_BATTERY_CAPACITY)
needed = forecast_reserve_needed(
forecast.remaining_today_kwh,
power.battery_soc,
float(data.get(CONF_BATTERY_TARGET_SOC, 80)),
float(capacity) if capacity else None,
hours_to_target,
BALANCED_RESERVE_BASE_LOAD_W,
BALANCED_RESERVE_BUFFER_KWH,
was_active,
)
active = True if needed is None else needed
self._balanced_reserve_active = active
if not active:
self._battery_priority_status = "forecast_sufficient"
return active

# ------------------------------------------------------------------
# Appliance configuration
# ------------------------------------------------------------------
Expand Down
35 changes: 35 additions & 0 deletions custom_components/pv_excess_control/power_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,38 @@ def battery_first_budget(
available_solar = max(excess_w + max(running_load_w, 0.0), 0.0)
reserved = min(limit, available_solar)
return BatteryBudget(excess_w - reserved, reserved, source)


def forecast_reserve_needed(
remaining_today_kwh: float | None,
battery_soc: float | None,
target_soc: float,
capacity_kwh: float | None,
hours_to_target: float,
base_load_w: float,
buffer_kwh: float,
currently_reserving: bool = False,
) -> bool | None:
"""Decide whether Balanced must protect battery charging in real time.

Charging is reserved only when the remaining PV forecast cannot cover both
the energy the battery still needs to reach ``target_soc`` and the expected
household load until the target time, plus a buffer. Once reserving, the
margin must exceed twice the buffer before appliances get the charging
power back, so forecast noise does not toggle loads.

Returns ``None`` when a required input is missing or invalid; the caller
decides the fallback.
"""
values = (remaining_today_kwh, battery_soc, capacity_kwh)
if any(v is None or not math.isfinite(v) for v in values):
return None
if not 0 <= battery_soc <= 100 or capacity_kwh <= 0:
return None
needed_kwh = max(target_soc - battery_soc, 0.0) / 100.0 * capacity_kwh
if needed_kwh <= 0:
return False
usage_kwh = max(hours_to_target, 0.0) * max(base_load_w, 0.0) / 1000.0
margin_kwh = remaining_today_kwh - needed_kwh - usage_kwh
threshold = buffer_kwh * 2 if currently_reserving else buffer_kwh
return margin_kwh < threshold
20 changes: 19 additions & 1 deletion docs/energy-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,25 @@ Below the configured target SoC, Battery First reserves charging power before or

Example: PV minus household load is 2966 W, the battery charges at 2476 W, and SoC is below target. With measured-charge fallback, 490 W remains for appliances. If total surplus is instead 8000 W and the configured charging maximum is 2500 W, 5500 W remains available even before the battery reaches target.

Unknown required battery readings prevent new positive-surplus allocation, but known negative surplus still reaches deficit shedding. Missing current physical balance prevents allocation from stale history. Explicit override, on-only/daily-runtime constraints and minimum-SoC protection retain their existing precedence. Balanced and Appliance First are not redesigned by this update.
Unknown required battery readings prevent new positive-surplus allocation, but known negative surplus still reaches deficit shedding. Missing current physical balance prevents allocation from stale history. Explicit override, on-only/daily-runtime constraints and minimum-SoC protection retain their existing precedence. Appliance First is unchanged.

## Balanced with a forecast

With a forecast provider, Balanced applies the same real-time reservation as Battery First, but only when the forecast is not enough for both the battery and the house. Every controller cycle compares:

```
needed_kwh = (target_soc - soc) / 100 * battery_capacity
usage_kwh = hours_until_target_time * 0.5 kW
reserve = remaining_today_kwh - needed_kwh - usage_kwh < 0.5 kWh
```

- `reserve` false: appliances get the full surplus, including power that would otherwise charge the battery (as before). On a sunny morning the battery still reaches its target later in the day.
- `reserve` true: charging power is protected exactly like Battery First (charge cap, live limit, measured charging). The battery priority status shows the usual source; otherwise it shows `forecast_sufficient`.
- Once reserving, the margin must exceed 1 kWh (twice the buffer) before the reservation is released, so forecast updates do not toggle appliances.
- After the target time no further house load is counted; reservation continues while the remaining forecast cannot cover the missing SoC.
- Without an available forecast (not configured, pending or unavailable) Balanced keeps its previous real-time behavior and does not reserve. A missing SoC with an available forecast uses the Battery First safety handling.

The 0.5 kW house load matches the planner's default base load. The planner's own Balanced split is unchanged.

## Stable tariff support

Expand Down
99 changes: 99 additions & 0 deletions tests/test_power_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,3 +321,102 @@ def test_live_charge_limit_uses_power_units_not_current(unit, expected):
coord.power_history = [power] * 3
adjusted, _ = coord._power_for_optimizer(power, [], {})
assert adjusted.excess_power == expected


# --- Balanced: forecast-aware real-time reserve (issue #73) -----------------

from datetime import datetime
from unittest.mock import patch

from custom_components.pv_excess_control.models import ForecastData
from custom_components.pv_excess_control.power_policy import forecast_reserve_needed


@pytest.mark.parametrize(
"remaining,soc,hours,reserving,expected",
[
(20.0, 30, 6, False, False), # sunny morning: forecast covers battery + load
(3.0, 30, 3, False, True), # dull day: forecast cannot reach the target
(3.0, 80, 3, False, False), # target already reached
(5.1, 50, 2, False, False), # margin 1.6 kWh > buffer
(5.1, 50, 2, True, True), # hysteresis: margin 1.6 kWh < 2 x buffer
(6.5, 50, 2, True, False), # margin 3.0 kWh releases the reservation
(4.0, 50, -1, False, False), # past target time: no further household load
],
)
def test_forecast_reserve_decision(remaining, soc, hours, reserving, expected):
# 10 kWh battery, target 75 %, 500 W base load, 1 kWh buffer
assert forecast_reserve_needed(remaining, soc, 75, 10, hours, 500, 1.0, reserving) is expected


@pytest.mark.parametrize("remaining,soc,capacity", [(None, 50, 10), (5, None, 10), (5, 50, None), (5, 120, 10), (5, 50, 0)])
def test_forecast_reserve_missing_input_is_undecided(remaining, soc, capacity):
assert forecast_reserve_needed(remaining, soc, 75, capacity, 2, 500, 0.5) is None


def balanced_coordinator(remaining_kwh, soc=30, status="available"):
coord = coordinator(soc=soc)
coord.battery_strategy = "balanced"
coord.config_entry.data.update(
battery_strategy="balanced", battery_target_soc=75,
battery_capacity=7.5, battery_target_time="16:00",
)
coord._forecast_status = status
coord._forecast_data = ForecastData(remaining_today_kwh=remaining_kwh) if remaining_kwh is not None else None
return coord


def _optimizer_input(coord, hour=12):
power = coord._collect_power_state()
coord.power_history = [power] * 3
now = datetime(2026, 11, 13, hour, 0).astimezone()
with patch("custom_components.pv_excess_control.coordinator.dt_util.now", return_value=now):
return power, *coord._power_for_optimizer(power, [], {})


def test_balanced_reserves_charging_when_forecast_is_insufficient():
coord = balanced_coordinator(remaining_kwh=3.0)
power, adjusted, history = _optimizer_input(coord)
assert power.excess_power == 2966
assert adjusted.excess_power == 490 # only real export remains for appliances
assert all(p.excess_power == 490 for p in history)
assert coord._battery_charge_reserve_w == 2476
assert coord._battery_priority_status == "measured_charging"


def test_balanced_releases_charging_when_forecast_is_sufficient():
coord = balanced_coordinator(remaining_kwh=20.0)
power, adjusted, history = _optimizer_input(coord)
assert adjusted is power
assert history == coord.power_history
assert coord._battery_priority_status == "forecast_sufficient"


@pytest.mark.parametrize("status,remaining", [("unavailable", None), ("pending", None), ("not_configured", None)])
def test_balanced_without_forecast_keeps_previous_behavior(status, remaining):
coord = balanced_coordinator(remaining_kwh=remaining, status=status)
power, adjusted, history = _optimizer_input(coord)
assert adjusted is power
assert history == coord.power_history


def test_balanced_missing_soc_with_forecast_falls_back_to_battery_first_safety():
coord = balanced_coordinator(remaining_kwh=20.0)
power = replace(coord._collect_power_state(), battery_soc=None)
coord.power_history = [power] * 3
adjusted, history = coord._power_for_optimizer(power, [], {})
assert adjusted.excess_power == 0
assert all(p.excess_power == 0 for p in history)


def test_balanced_reserve_hysteresis_holds_until_margin_is_clear():
# 7.5 kWh, SoC 30 -> 3.375 kWh needed; at 12:00 4 h x 0.5 kW = 2 kWh load.
coord = balanced_coordinator(remaining_kwh=5.0) # margin -0.375 -> reserve
_, adjusted, _ = _optimizer_input(coord)
assert adjusted.excess_power == 490
coord._forecast_data = ForecastData(remaining_today_kwh=6.2) # margin 0.825 < 2 x 0.5
_, adjusted, _ = _optimizer_input(coord)
assert adjusted.excess_power == 490
coord._forecast_data = ForecastData(remaining_today_kwh=6.5) # margin 1.125 -> release
power, adjusted, _ = _optimizer_input(coord)
assert adjusted is power