Skip to content
Draft
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
1 change: 1 addition & 0 deletions README.de.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Diese Integration ist Open Source, weil ich daran glaube, der Community, die Hom

### Stromtarife & -netz
- **Tarif-Integration** - Unterstützung für Tibber, Awattar, Nordpool, Octopus Energy und generische Preissensoren.
- **Externe Preisprognosen** - Ein optionaler [Prognosesensor](docs/price-forecast-input.de.md) übernimmt Vorhersagen eines eigenständigen Modells zur Diagnose. Veröffentlichte Tarifpreise bleiben die Grundlage der Steuerung.
- **Einspeiselimit-Management** - Absorbieren potenziell abgeregelter Leistung möglich, z.B. wenn Einspeisebegrenzungen gelten.
- **Netzsupplementierung** - Möglichkeit, eine bestimmte Menge an Netzstrom zu erlauben, um Geräte zusätzlich zu supplementieren.

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ The [0.4.0rc1 candidate notes](docs/release-candidate.md) explain migration and

### Tariffs & Grid
- **Tariff Integration** - Support for Tibber, Awattar, Nordpool, Octopus Energy, and generic price sensors.
- **External Price Forecasts** - An optional [forecast sensor](docs/price-forecast-input.md) accepts predictions from a separate model for diagnostics. Published tariffs remain the basis for control.
- **Export Limit Management** - Absorb would-be-curtailed power when feed-in caps apply.
- **Grid Supplementation** - Allow a small amount of grid power to top up appliances.

Expand Down
10 changes: 8 additions & 2 deletions custom_components/pv_excess_control/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
CONF_PLANNER_INTERVAL,
CONF_PROTECT_FROM_PREEMPTION,
CONF_PRICE_SENSOR,
CONF_PRICE_FORECAST_SENSOR,
CONF_PV_POWER,
CONF_HELPER_ONLY,
CONF_REQUIRES_APPLIANCE,
Expand Down Expand Up @@ -614,6 +615,11 @@ def _energy_schema(
if tariff_provider != TariffProvider.NONE:
schema_dict[vol.Required(CONF_PRICE_SENSOR, description={"suggested_value": d.get(CONF_PRICE_SENSOR)})] = SENSOR_ENTITY_SELECTOR

schema_dict[vol.Optional(
CONF_PRICE_FORECAST_SENSOR,
description={"suggested_value": d.get(CONF_PRICE_FORECAST_SENSOR)},
)] = SENSOR_ENTITY_SELECTOR

schema_dict[vol.Optional(
CONF_CHEAP_PRICE_THRESHOLD,
description={"suggested_value": d.get(CONF_CHEAP_PRICE_THRESHOLD)},
Expand Down Expand Up @@ -1084,7 +1090,7 @@ async def async_step_energy(
if not errors:
self.data.update(user_input)
# Clean optional energy keys not present in user_input
for key in [CONF_FEED_IN_TARIFF_SENSOR]:
for key in [CONF_FEED_IN_TARIFF_SENSOR, CONF_PRICE_FORECAST_SENSOR]:
if key not in user_input:
self.data.pop(key, None)
return await self.async_step_forecast()
Expand Down Expand Up @@ -1352,7 +1358,7 @@ async def async_step_energy(
if not errors:
self.data.update(user_input)
# Clean optional energy keys not present in user_input
for key in [CONF_FEED_IN_TARIFF_SENSOR]:
for key in [CONF_FEED_IN_TARIFF_SENSOR, CONF_PRICE_FORECAST_SENSOR]:
if key not in user_input:
self.data.pop(key, None)
return await self.async_step_forecast()
Expand Down
1 change: 1 addition & 0 deletions custom_components/pv_excess_control/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ class NotificationEvent(StrEnum):
CONF_BATTERY_CAPACITY = "battery_capacity"
CONF_TARIFF_PROVIDER = "tariff_provider"
CONF_PRICE_SENSOR = "price_sensor"
CONF_PRICE_FORECAST_SENSOR = "price_forecast_sensor"
CONF_CHEAP_PRICE_THRESHOLD = "cheap_price_threshold"
CONF_BATTERY_CHARGE_PRICE_THRESHOLD = "battery_charge_price_threshold"
CONF_FEED_IN_TARIFF = "feed_in_tariff"
Expand Down
29 changes: 29 additions & 0 deletions custom_components/pv_excess_control/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from homeassistant.util import dt as dt_util
from .daily_state import nonnegative_number
from .power_policy import battery_first_budget
from .price_forecast import PriceForecastError, parse_price_forecast

from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

Expand Down Expand Up @@ -94,6 +95,7 @@
CONF_PLANNER_INTERVAL,
CONF_PROTECT_FROM_PREEMPTION,
CONF_PRICE_SENSOR,
CONF_PRICE_FORECAST_SENSOR,
CONF_PV_POWER,
CONF_REQUIRES_APPLIANCE,
CONF_HELPER_ONLY,
Expand Down Expand Up @@ -2409,6 +2411,32 @@ def _create_empty_plan(self) -> Plan:
confidence=0.0,
)

def _read_price_forecast(self, *, now: datetime | None = None) -> dict[str, Any]:
"""Read an optional forecast for diagnostics, outside tariff/control data."""
entity_id = self.config_entry.data.get(CONF_PRICE_FORECAST_SENSOR)
result = {
"source_entity": entity_id or None,
"status": "not_configured",
"automation_eligible": False,
"snapshot": None,
}
if not entity_id:
return result
state = self.hass.states.get(entity_id)
if state is None:
result["status"] = "missing_sensor"
elif state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE):
result["status"] = "unavailable"
else:
try:
snapshot = parse_price_forecast(state.attributes, now=now or dt_util.utcnow())
except PriceForecastError as err:
result["status"] = str(err)
else:
result["status"] = "available"
result["snapshot"] = snapshot.as_dict()
return result

def _build_coordinator_data(self) -> dict[str, Any]:
"""Build a data dict that entity platforms can read."""
latest_power = self.power_history[-1] if self.power_history else None
Expand All @@ -2427,6 +2455,7 @@ def _build_coordinator_data(self) -> dict[str, Any]:
"battery_priority_status": getattr(self, "_battery_priority_status", "inactive"),
"power_history": list(self.power_history),
"current_plan": self.current_plan,
"price_forecast": self._read_price_forecast(),
"forecast_status": getattr(self, "_forecast_status", "not_configured"),
"forecast_remaining_today_kwh": getattr(getattr(self, "_forecast_data", None), "remaining_today_kwh", None),
"forecast_tomorrow_total_kwh": getattr(getattr(self, "_forecast_data", None), "tomorrow_total_kwh", None),
Expand Down
148 changes: 148 additions & 0 deletions custom_components/pv_excess_control/price_forecast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""Validate external electricity price forecasts without Home Assistant access.

Version 1 is an observation contract. Its empirical bounds are not calibrated
probabilities and no accepted snapshot grants permission to control a device.
"""

from __future__ import annotations

from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import math
from typing import Any


class PriceForecastError(ValueError):
"""A rejected snapshot, with a stable diagnostic reason."""


@dataclass(frozen=True)
class PriceForecastInterval:
"""One immutable interval with empirical price bounds in EUR/kWh."""

start: datetime
end: datetime
price: float
lower: float
upper: float

def as_dict(self) -> dict[str, Any]:
"""Return an independent JSON-compatible representation."""
return {
"start": self.start.isoformat(),
"end": self.end.isoformat(),
"price": self.price,
"lower": self.lower,
"upper": self.upper,
}


@dataclass(frozen=True)
class PriceForecastSnapshot:
"""An accepted forecast, deliberately distinct from a confirmed tariff."""

generated_at: datetime
expires_at: datetime
model: str
price_basis: str
intervals: tuple[PriceForecastInterval, ...]

def as_dict(self) -> dict[str, Any]:
"""Return only validated contract fields, without source-owned objects."""
return {
"schema_version": 1,
"market": "DE-LU",
"unit": "EUR/kWh",
"price_basis": self.price_basis,
"generated_at": self.generated_at.isoformat(),
"expires_at": self.expires_at.isoformat(),
"model": self.model,
"quality": {"status": "experimental", "automation_eligible": False},
"intervals": [row.as_dict() for row in self.intervals],
}


def _timestamp(value: Any) -> datetime:
if not isinstance(value, str):
raise PriceForecastError("invalid_timestamp")
try:
parsed = datetime.fromisoformat(value)
if parsed.tzinfo is None or parsed.utcoffset() is None:
raise ValueError("missing offset")
return parsed.astimezone(timezone.utc)
except (ValueError, OverflowError) as err:
raise PriceForecastError("invalid_timestamp") from err


def _number(value: Any) -> float:
if type(value) not in (int, float):
raise PriceForecastError("invalid_price")
try:
number = float(value)
except OverflowError as err:
raise PriceForecastError("invalid_price") from err
if not math.isfinite(number):
raise PriceForecastError("invalid_price")
return number


def parse_price_forecast(payload: Any, *, now: datetime) -> PriceForecastSnapshot:
"""Validate version, meaning, freshness and interval coverage atomically.

Missing, malformed or expired data raises ``PriceForecastError``. Zero and
negative prices are retained. Extra metadata is ignored rather than copied
into the accepted snapshot. All duration comparisons use UTC.
"""
if now.tzinfo is None or now.utcoffset() is None:
raise PriceForecastError("invalid_now")
now = now.astimezone(timezone.utc)
if not isinstance(payload, Mapping):
raise PriceForecastError("invalid_payload")
if type(payload.get("schema_version")) is not int or payload["schema_version"] != 1:
raise PriceForecastError("unsupported_schema")
if payload.get("market") != "DE-LU" or payload.get("unit") != "EUR/kWh":
raise PriceForecastError("unsupported_market_or_unit")
if payload.get("price_basis") not in ("wholesale", "retail"):
raise PriceForecastError("unsupported_price_basis")
quality = payload.get("quality")
if (
not isinstance(quality, Mapping)
or quality.get("status") != "experimental"
or quality.get("automation_eligible") is not False
):
raise PriceForecastError("unsupported_quality")
model = payload.get("model")
if not isinstance(model, str) or not model.strip() or len(model) > 128:
raise PriceForecastError("invalid_model")
generated = _timestamp(payload.get("generated_at"))
expires = _timestamp(payload.get("expires_at"))
if generated > now:
raise PriceForecastError("future_generation")
if not timedelta() < expires - generated <= timedelta(hours=6):
raise PriceForecastError("invalid_expiration")
if now >= expires:
raise PriceForecastError("expired")
rows = payload.get("intervals")
if not isinstance(rows, (list, tuple)) or not 1 <= len(rows) <= 672:
raise PriceForecastError("invalid_interval_count")
intervals = []
previous_end = None
for row in rows:
if not isinstance(row, Mapping):
raise PriceForecastError("invalid_interval")
start, end = _timestamp(row.get("start")), _timestamp(row.get("end"))
if (end - start).total_seconds() not in (900, 1800, 3600):
raise PriceForecastError("invalid_interval_duration")
if previous_end is not None and start != previous_end:
raise PriceForecastError("noncontiguous_intervals")
if end - generated > timedelta(days=7):
raise PriceForecastError("horizon_too_long")
price, lower, upper = (_number(row.get(key)) for key in ("price", "lower", "upper"))
if not lower <= price <= upper:
raise PriceForecastError("invalid_bounds")
intervals.append(PriceForecastInterval(start, end, price, lower, upper))
previous_end = end
if intervals[-1].end <= now:
raise PriceForecastError("no_future_intervals")
return PriceForecastSnapshot(generated, expires, model, payload["price_basis"], tuple(intervals))
36 changes: 34 additions & 2 deletions custom_components/pv_excess_control/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@
UnitOfTime,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity import DeviceInfo, EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import CONF_APPLIANCE_NAME, CONF_DYNAMIC_BATTERY_CHARGE_ENABLED, DOMAIN
from .const import CONF_APPLIANCE_NAME, CONF_DYNAMIC_BATTERY_CHARGE_ENABLED, CONF_PRICE_FORECAST_SENSOR, DOMAIN
from .coordinator import PvExcessCoordinator
from .entity_lifecycle import add_entities_by_subentry, device_info
from .models import BatteryDischargeAction
Expand All @@ -51,6 +51,10 @@ async def async_setup_entry(
PvPlanConfidenceSensor(coordinator),
]

forecast_entity = getattr(config_entry, "data", {}).get(CONF_PRICE_FORECAST_SENSOR)
if isinstance(forecast_entity, str) and forecast_entity:
entities.append(PvPriceForecastSensor(coordinator))

# Per-appliance sensors from subentries
subentries = getattr(config_entry, "subentries", {})
for subentry_id, subentry in subentries.items():
Expand Down Expand Up @@ -107,6 +111,34 @@ def _data(self) -> dict[str, Any] | None:
# ---------------------------------------------------------------------------


class PvPriceForecastSensor(PvExcessBaseSensor):
"""Diagnostic status and validated external forecast, without control effects."""

_attr_icon = "mdi:chart-timeline-variant"
_attr_entity_category = EntityCategory.DIAGNOSTIC
_unrecorded_attributes = frozenset({"intervals"})

def __init__(self, coordinator: PvExcessCoordinator) -> None:
super().__init__(coordinator, "price_forecast", "Price Forecast")

@property
def native_value(self) -> str:
"""Report the input status, not a forecast price as a confirmed tariff."""
return (self._data or {}).get("price_forecast", {}).get("status", "pending")

@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Expose provenance and the current validated snapshot only."""
data = (self._data or {}).get("price_forecast", {})
attrs = {"source_entity": data.get("source_entity"), "automation_eligible": False}
if snapshot := data.get("snapshot"):
attrs.update(snapshot)
attrs["interval_count"] = len(snapshot["intervals"])
attrs["forecast_start"] = snapshot["intervals"][0]["start"]
attrs["forecast_end"] = snapshot["intervals"][-1]["end"]
return attrs


class PvExcessPowerSensor(PvExcessBaseSensor):
"""Sensor reporting current PV excess power in Watts."""

Expand Down
12 changes: 8 additions & 4 deletions custom_components/pv_excess_control/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,17 @@
"cheap_price_threshold": "Cheap Price Threshold",
"battery_charge_price_threshold": "Battery Charge Price Threshold",
"feed_in_tariff": "Feed-in Tariff",
"feed_in_tariff_sensor": "Feed-in Tariff Sensor"
"feed_in_tariff_sensor": "Feed-in Tariff Sensor",
"price_forecast_sensor": "Electricity price forecast sensor (optional)"
},
"data_description": {
"tariff_provider": "Select your electricity price provider integration.",
"price_sensor": "Select the sensor entity that provides the current electricity price. For Tibber, use the price sensor. For Octopus, select the electricity price sensor. For Awattar/Nordpool, select the spot price sensor.",
"cheap_price_threshold": "Price below which electricity is considered cheap.",
"battery_charge_price_threshold": "Price below which battery charging from grid is allowed.",
"feed_in_tariff": "Price received per kWh for energy exported to the grid.",
"feed_in_tariff_sensor": "Optional sensor for dynamic feed-in tariff (overrides static value)"
"feed_in_tariff_sensor": "Optional sensor for dynamic feed-in tariff (overrides static value)",
"price_forecast_sensor": "Optional external sensor with versioned price forecasts. Diagnostics only: forecasts do not replace published tariff prices or trigger charging."
}
},
"forecast": {
Expand Down Expand Up @@ -467,15 +469,17 @@
"cheap_price_threshold": "Cheap Price Threshold",
"battery_charge_price_threshold": "Battery Charge Price Threshold",
"feed_in_tariff": "Feed-in Tariff",
"feed_in_tariff_sensor": "Feed-in Tariff Sensor"
"feed_in_tariff_sensor": "Feed-in Tariff Sensor",
"price_forecast_sensor": "Electricity price forecast sensor (optional)"
},
"data_description": {
"tariff_provider": "Select your electricity price provider integration.",
"price_sensor": "Select the sensor entity that provides the current electricity price. For Tibber, use the price sensor. For Octopus, select the electricity price sensor. For Awattar/Nordpool, select the spot price sensor.",
"cheap_price_threshold": "Price below which electricity is considered cheap.",
"battery_charge_price_threshold": "Price below which battery charging from grid is allowed.",
"feed_in_tariff": "Price received per kWh for energy exported to the grid.",
"feed_in_tariff_sensor": "Optional sensor for dynamic feed-in tariff (overrides static value)"
"feed_in_tariff_sensor": "Optional sensor for dynamic feed-in tariff (overrides static value)",
"price_forecast_sensor": "Optional external sensor with versioned price forecasts. Diagnostics only: forecasts do not replace published tariff prices or trigger charging."
}
},
"forecast": {
Expand Down
18 changes: 18 additions & 0 deletions custom_components/pv_excess_control/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,15 @@
"additional_forecast_sensors": "Prognosen separater PV-Flächen. Doppelte Entity-IDs zählen nur einmal; keinen bereits enthaltenen Summensensor ergänzen.",
"additional_forecast_tomorrow_sensors": "Diese Quellen und der einzelne Morgen-Sensor ersetzen gemeinsam den morgigen Anteil der primären Prognosen. Alle morgigen Flächen angeben."
}
},
"energy": {
"title": "Strompreise",
"data": {
"price_forecast_sensor": "Strompreis-Prognosesensor (optional)"
},
"data_description": {
"price_forecast_sensor": "Optionaler externer Sensor mit versionierten Preisprognosen. Nur Diagnose: Prognosen ersetzen keine veröffentlichten Tarifpreise und lösen keine Ladung aus."
}
}
}
},
Expand All @@ -127,6 +136,15 @@
"additional_forecast_sensors": "Prognosen separater PV-Flächen. Doppelte Entity-IDs zählen nur einmal; keinen bereits enthaltenen Summensensor ergänzen.",
"additional_forecast_tomorrow_sensors": "Diese Quellen und der einzelne Morgen-Sensor ersetzen gemeinsam den morgigen Anteil der primären Prognosen. Alle morgigen Flächen angeben."
}
},
"energy": {
"title": "Strompreise",
"data": {
"price_forecast_sensor": "Strompreis-Prognosesensor (optional)"
},
"data_description": {
"price_forecast_sensor": "Optionaler externer Sensor mit versionierten Preisprognosen. Nur Diagnose: Prognosen ersetzen keine veröffentlichten Tarifpreise und lösen keine Ladung aus."
}
}
}
}
Expand Down
Loading