Key Forecast.Solar energy forecast by period start (#188790)

This commit is contained in:
Tagliax
2026-10-26 21:18:37 +00:00
committed by GitHub
parent f6f1534218
commit 96c1362845
5 changed files with 110 additions and 59 deletions
@@ -1,7 +1,8 @@
"""DataUpdateCoordinator for the Forecast.Solar integration."""
from collections.abc import Mapping
from datetime import timedelta
from datetime import datetime, timedelta
from itertools import pairwise
from typing import Any, cast, override
from forecast_solar import Estimate, ForecastSolar, ForecastSolarConnectionError, Plane
@@ -31,6 +32,20 @@ from .plane import SensorUpdateFailed, sensor_angle
type ForecastSolarConfigEntry = ConfigEntry[ForecastSolarDataUpdateCoordinator]
def energy_by_period_start(wh_period: Mapping[datetime, int]) -> dict[datetime, int]:
"""Key each energy value by the start of its period.
The API keys each value by the end of its period, so each value moves
to the previous timestamp.
"""
return {
start: wh_period[end]
for start, end in pairwise(sorted(wh_period))
# A zero at midnight starts a new API day, not a period that ended there.
if wh_period[end] != 0 or (end.hour, end.minute, end.second) != (0, 0, 0)
}
def _resolve_location(
hass: HomeAssistant, data: Mapping[str, Any]
) -> tuple[float, float]:
@@ -2,7 +2,7 @@
from homeassistant.core import HomeAssistant
from .coordinator import ForecastSolarDataUpdateCoordinator
from .coordinator import ForecastSolarDataUpdateCoordinator, energy_by_period_start
async def async_get_solar_forecast(
@@ -17,8 +17,8 @@ async def async_get_solar_forecast(
return {
"wh_hours": {
timestamp.isoformat(): val
for timestamp, val in entry.runtime_data.data.wh_period.items()
if val != 0
or (timestamp.hour, timestamp.minute, timestamp.second) != (0, 0, 0)
for timestamp, val in energy_by_period_start(
entry.runtime_data.data.wh_period
).items()
}
}
@@ -1,7 +1,6 @@
"""Services for the Forecast.Solar integration."""
from datetime import datetime
from typing import TYPE_CHECKING
import probatio
@@ -19,9 +18,7 @@ from homeassistant.util import dt as dt_util
from homeassistant.util.json import JsonValueType
from .const import DOMAIN
if TYPE_CHECKING:
from .coordinator import ForecastSolarConfigEntry
from .coordinator import ForecastSolarConfigEntry, energy_by_period_start
ATTR_CONFIG_ENTRY = "config_entry"
ATTR_START = "start"
@@ -94,7 +91,7 @@ def async_setup_services(hass: HomeAssistant) -> None:
)
estimate = entry.runtime_data.data
wh_period: dict[datetime, int] = dict(estimate.wh_period)
wh_period = energy_by_period_start(estimate.wh_period)
watts: dict[datetime, float]
if call.data[ATTR_RESOLUTION] == RESOLUTION_HOURLY:
+35 -16
View File
@@ -15,10 +15,19 @@ async def test_energy_solar_forecast(
mock_config_entry: MockConfigEntry,
mock_forecast_solar: MagicMock,
) -> None:
"""Test the Forecast.Solar energy platform solar forecast."""
"""Test the Forecast.Solar energy platform solar forecast.
The API keys each energy value by the end of its period: the first key
of a day is sunrise with 0 Wh and the last one is sunset.
"""
mock_forecast_solar.estimate.return_value.wh_period = {
datetime(2021, 6, 27, 13, 0, tzinfo=UTC): 12,
datetime(2021, 6, 27, 14, 0, tzinfo=UTC): 8,
datetime(2026, 10, 24, 5, 41, tzinfo=UTC): 0,
datetime(2026, 10, 24, 6, 0, tzinfo=UTC): 6,
datetime(2026, 10, 24, 7, 0, tzinfo=UTC): 91,
datetime(2026, 10, 24, 16, 0, tzinfo=UTC): 244,
datetime(2026, 10, 24, 16, 17, tzinfo=UTC): 16,
datetime(2026, 10, 25, 6, 43, tzinfo=UTC): 0,
datetime(2026, 10, 25, 7, 0, tzinfo=UTC): 5,
}
mock_config_entry.add_to_hass(hass)
@@ -29,8 +38,12 @@ async def test_energy_solar_forecast(
assert await energy.async_get_solar_forecast(hass, mock_config_entry.entry_id) == {
"wh_hours": {
"2021-06-27T13:00:00+00:00": 12,
"2021-06-27T14:00:00+00:00": 8,
"2026-10-24T05:41:00+00:00": 6,
"2026-10-24T06:00:00+00:00": 91,
"2026-10-24T07:00:00+00:00": 244,
"2026-10-24T16:00:00+00:00": 16,
"2026-10-24T16:17:00+00:00": 0,
"2026-10-25T06:43:00+00:00": 5,
}
}
@@ -40,14 +53,19 @@ async def test_energy_solar_forecast_filters_midnight_utc_zeros(
mock_config_entry: MockConfigEntry,
mock_forecast_solar: MagicMock,
) -> None:
"""Test that artificial zero values at UTC midnight boundaries are filtered out."""
"""Test that artificial zero values at UTC midnight boundaries are filtered out.
The zero at 00:00 starts a new API day: the energy of 23:00-00:00 is
missing, not zero.
"""
mock_forecast_solar.estimate.return_value.wh_period = {
datetime(2021, 6, 27, 0, 0, tzinfo=UTC): 0,
datetime(2021, 6, 27, 1, 0, tzinfo=UTC): 1388,
datetime(2021, 6, 27, 2, 0, tzinfo=UTC): 830,
datetime(2021, 6, 27, 14, 0, tzinfo=UTC): 0,
datetime(2021, 6, 27, 15, 0, tzinfo=UTC): 292,
datetime(2021, 6, 28, 0, 0, tzinfo=UTC): 0,
datetime(2026, 3, 25, 20, 2, 38, tzinfo=UTC): 0,
datetime(2026, 3, 25, 21, 0, tzinfo=UTC): 123,
datetime(2026, 3, 25, 22, 0, tzinfo=UTC): 346,
datetime(2026, 3, 25, 23, 0, tzinfo=UTC): 502,
datetime(2026, 3, 26, 0, 0, tzinfo=UTC): 0,
datetime(2026, 3, 26, 1, 0, tzinfo=UTC): 718,
datetime(2026, 3, 26, 2, 0, tzinfo=UTC): 766,
}
mock_config_entry.add_to_hass(hass)
@@ -59,10 +77,11 @@ async def test_energy_solar_forecast_filters_midnight_utc_zeros(
result = await energy.async_get_solar_forecast(hass, mock_config_entry.entry_id)
assert result == {
"wh_hours": {
"2021-06-27T01:00:00+00:00": 1388,
"2021-06-27T02:00:00+00:00": 830,
"2021-06-27T14:00:00+00:00": 0,
"2021-06-27T15:00:00+00:00": 292,
"2026-03-25T20:02:38+00:00": 123,
"2026-03-25T21:00:00+00:00": 346,
"2026-03-25T22:00:00+00:00": 502,
"2026-03-26T00:00:00+00:00": 718,
"2026-03-26T01:00:00+00:00": 766,
}
}
@@ -25,8 +25,28 @@ from homeassistant.util import dt as dt_util
async def test_get_forecast_raw(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_forecast_solar: MagicMock,
) -> None:
"""Test the get_forecast service with native resolution."""
"""Test the get_forecast service with native resolution.
The API keys each energy value by the end of its period; the service
returns it at the start of the period, so the last timestamp has none.
"""
api_tz = ZoneInfo("Europe/Amsterdam")
estimate = mock_forecast_solar.estimate.return_value
estimate.watts = {
datetime(2026, 6, 19, 5, 20, tzinfo=api_tz): 0,
datetime(2026, 6, 19, 6, 0, tzinfo=api_tz): 200,
datetime(2026, 6, 19, 7, 0, tzinfo=api_tz): 600,
datetime(2026, 6, 19, 7, 20, tzinfo=api_tz): 0,
}
estimate.wh_period = {
datetime(2026, 6, 19, 5, 20, tzinfo=api_tz): 0,
datetime(2026, 6, 19, 6, 0, tzinfo=api_tz): 67,
datetime(2026, 6, 19, 7, 0, tzinfo=api_tz): 400,
datetime(2026, 6, 19, 7, 20, tzinfo=api_tz): 100,
}
response = await hass.services.async_call(
DOMAIN,
SERVICE_GET_FORECAST,
@@ -38,25 +58,21 @@ async def test_get_forecast_raw(
return_response=True,
)
# Response is two flat ``{ISO timestamp -> number}`` maps.
assert set(response.keys()) == {"watts", "wh_period"}
assert isinstance(response["watts"], dict)
assert isinstance(response["wh_period"], dict)
# The conftest mock seeds two timestamps in ``watts`` and
# ``wh_period``, both at 13:00 in HA's default timezone. The
# service emits ISO keys in the site/API timezone
# (``Europe/Amsterdam`` per the conftest mock).
api_tz = ZoneInfo("Europe/Amsterdam")
default_tz = dt_util.get_default_time_zone()
ts_2021 = (
datetime(2021, 6, 27, 13, 0, tzinfo=default_tz).astimezone(api_tz).isoformat()
)
ts_2022 = (
datetime(2022, 6, 27, 13, 0, tzinfo=default_tz).astimezone(api_tz).isoformat()
)
assert response["watts"] == {ts_2021: 10, ts_2022: 100}
assert response["wh_period"] == {ts_2021: 30, ts_2022: 300}
# Response is two flat ``{ISO timestamp -> number}`` maps, with ISO
# keys in the site/API timezone (``Europe/Amsterdam``).
assert response == {
"watts": {
"2026-06-19T05:20:00+02:00": 0,
"2026-06-19T06:00:00+02:00": 200,
"2026-06-19T07:00:00+02:00": 600,
"2026-06-19T07:20:00+02:00": 0,
},
"wh_period": {
"2026-06-19T05:20:00+02:00": 67,
"2026-06-19T06:00:00+02:00": 400,
"2026-06-19T07:00:00+02:00": 100,
},
}
async def test_get_forecast_hourly_aggregation(
@@ -65,24 +81,29 @@ async def test_get_forecast_hourly_aggregation(
mock_forecast_solar: MagicMock,
) -> None:
"""Test the get_forecast service aggregates to whole hours."""
# Add some 15-min-resolution entries within a single hour so we can
# observe that power gets averaged and energy gets summed.
# 15-min-resolution entries, as on paid accounts: power gets averaged
# and energy summed per hour. Each energy value is keyed by the end of
# its period, so 08:00-09:00 is the sum of the 08:15 to 09:00 values.
api_tz = ZoneInfo("Europe/Amsterdam")
estimate = mock_forecast_solar.estimate.return_value
base = datetime(2026, 6, 19, 8, 0, tzinfo=api_tz)
estimate.watts = {
base - timedelta(minutes=15): 600,
base: 1000,
base + timedelta(minutes=15): 2000,
base + timedelta(minutes=30): 3000,
base + timedelta(minutes=45): 4000,
base + timedelta(hours=1): 5000,
base + timedelta(hours=1, minutes=15): 4000,
}
estimate.wh_period = {
base: 250,
base + timedelta(minutes=15): 500,
base + timedelta(minutes=30): 750,
base + timedelta(minutes=45): 1000,
base + timedelta(hours=1): 1250,
base - timedelta(minutes=15): 150,
base: 200,
base + timedelta(minutes=15): 375,
base + timedelta(minutes=30): 625,
base + timedelta(minutes=45): 875,
base + timedelta(hours=1): 1125,
base + timedelta(hours=1, minutes=15): 1125,
}
response = await hass.services.async_call(
@@ -98,12 +119,11 @@ async def test_get_forecast_hourly_aggregation(
watts = response["watts"]
wh = response["wh_period"]
hour_0_iso = base.isoformat()
hour_1_iso = (base + timedelta(hours=1)).isoformat()
assert watts[hour_0_iso] == pytest.approx(2500.0)
assert wh[hour_0_iso] == 2500
assert watts[hour_1_iso] == pytest.approx(5000.0)
assert wh[hour_1_iso] == 1250
hour_7_iso = (base - timedelta(hours=1)).isoformat()
hour_8_iso = base.isoformat()
hour_9_iso = (base + timedelta(hours=1)).isoformat()
assert watts[hour_8_iso] == pytest.approx(2500.0)
assert wh == {hour_7_iso: 200, hour_8_iso: 3000, hour_9_iso: 1125}
async def test_get_forecast_filters_by_time_range(