elec-tariffs 0.2.0__tar.gz → 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/PKG-INFO +9 -3
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/README.md +8 -2
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/__init__.py +12 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/_version.py +1 -1
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/errors.py +16 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/sources/__init__.py +3 -0
- elec_tariffs-0.3.0/src/elec_tariffs/sources/weather.py +135 -0
- elec_tariffs-0.3.0/tests/fixtures/open_meteo_archive.json +1 -0
- elec_tariffs-0.3.0/tests/test_weather.py +187 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/.github/dependabot.yml +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/.github/pull_request_template.md +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/.github/release.yml +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/.github/workflows/ci.yml +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/.github/workflows/release.yml +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/.gitignore +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/CLAUDE.md +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/LICENSE +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/SECURITY.md +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/pyproject.toml +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/requirements-dev.txt +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/engine.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/models.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/py.typed +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/shape.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/sources/tempo.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/src/elec_tariffs/sources/trv.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/__init__.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/conftest.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/fixtures/rte_tempo_2024-2025.json +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/fixtures/rte_tempo_2025-2026.json +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/fixtures/rte_tempo_light.json +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/fixtures/trv_base.csv +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/fixtures/trv_hphc.csv +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/fixtures/trv_tempo.csv +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/test_engine.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/test_models.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/test_shape.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/test_tempo.py +0 -0
- {elec_tariffs-0.2.0 → elec_tariffs-0.3.0}/tests/test_trv.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: elec-tariffs
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Cost French electricity consumption hour by hour under Base, HP/HC and Tempo contracts
|
|
5
5
|
Project-URL: Homepage, https://github.com/damou8/elec-tariffs
|
|
6
6
|
Project-URL: Issues, https://github.com/damou8/elec-tariffs/issues
|
|
@@ -28,7 +28,8 @@ Cost French electricity consumption hour by hour under Base, HP/HC and Tempo con
|
|
|
28
28
|
`elec-tariffs` takes hourly consumption (as a Linky meter reports it) and works out what it cost under one or more contracts: which tranche each hour falls into, its price on that day, and its share of the yearly subscription. It also downloads the data that needs:
|
|
29
29
|
|
|
30
30
|
- the regulated prices (Tarif Bleu) of every period since 2012, from [data.gouv.fr](https://www.data.gouv.fr/fr/datasets/historique-des-tarifs-reglementes-de-vente-delectricite-pour-les-consommateurs-residentiels/);
|
|
31
|
-
- the color of each Tempo day, from RTE
|
|
31
|
+
- the color of each Tempo day, from RTE;
|
|
32
|
+
- the hourly outdoor temperature anywhere, from [Open-Meteo](https://open-meteo.com/), for homes without a thermometer.
|
|
32
33
|
|
|
33
34
|
It is async (aiohttp), fully typed and has no dependency on Home Assistant. It was written for the [Electricity Contracts](https://github.com/damou8/electricity_contracts) Home Assistant integration.
|
|
34
35
|
|
|
@@ -138,13 +139,18 @@ Past colors never change, so callers should cache them and only ask for the curr
|
|
|
138
139
|
|
|
139
140
|
To create the official API application: sign up on data.rte-france.com, open the "Tempo Like Supply Contract" API, choose "S'abonner à l'API" (this creates an application), then copy its client ID and secret.
|
|
140
141
|
|
|
142
|
+
## Outdoor temperature
|
|
143
|
+
|
|
144
|
+
`OpenMeteoClient(session).async_hourly_temperatures(latitude, longitude, start, end)` returns the air temperature at 2 m (°C) of each hour of the UTC days `start` to `end`, keyed by the UTC start of the hour. It reads Open-Meteo's [historical weather API](https://open-meteo.com/en/docs/historical-weather-api): free for non-commercial use, without an account, back to 1940. Its default model blends the ERA5 reanalyses with the ECMWF forecast model, so it covers the last days too; those hours are revised about five days later, so callers should ask for the last week again. Long ranges are split into requests of 366 days at most. The data is under [CC BY 4.0](https://open-meteo.com/en/licence): credit Open-Meteo where it is shown.
|
|
145
|
+
|
|
141
146
|
## Errors
|
|
142
147
|
|
|
143
148
|
Every error derives from `ElecTariffsError`:
|
|
144
149
|
|
|
145
150
|
- `MissingColorError`, `MissingPriceError` (with the `day` concerned);
|
|
146
151
|
- `TrvServerError`, `TrvFormatError` for data.gouv.fr;
|
|
147
|
-
- `TempoServerError` (network or 5xx), `TempoRateLimitError` (429), `TempoAuthError` (credentials refused) and `TempoFormatError` for the Tempo sources
|
|
152
|
+
- `TempoServerError` (network or 5xx), `TempoRateLimitError` (429), `TempoAuthError` (credentials refused) and `TempoFormatError` for the Tempo sources;
|
|
153
|
+
- `WeatherServerError` (network or 5xx), `WeatherRateLimitError` (429) and `WeatherFormatError` (request refused or unexpected answer) for Open-Meteo.
|
|
148
154
|
|
|
149
155
|
## Development
|
|
150
156
|
|
|
@@ -5,7 +5,8 @@ Cost French electricity consumption hour by hour under Base, HP/HC and Tempo con
|
|
|
5
5
|
`elec-tariffs` takes hourly consumption (as a Linky meter reports it) and works out what it cost under one or more contracts: which tranche each hour falls into, its price on that day, and its share of the yearly subscription. It also downloads the data that needs:
|
|
6
6
|
|
|
7
7
|
- the regulated prices (Tarif Bleu) of every period since 2012, from [data.gouv.fr](https://www.data.gouv.fr/fr/datasets/historique-des-tarifs-reglementes-de-vente-delectricite-pour-les-consommateurs-residentiels/);
|
|
8
|
-
- the color of each Tempo day, from RTE
|
|
8
|
+
- the color of each Tempo day, from RTE;
|
|
9
|
+
- the hourly outdoor temperature anywhere, from [Open-Meteo](https://open-meteo.com/), for homes without a thermometer.
|
|
9
10
|
|
|
10
11
|
It is async (aiohttp), fully typed and has no dependency on Home Assistant. It was written for the [Electricity Contracts](https://github.com/damou8/electricity_contracts) Home Assistant integration.
|
|
11
12
|
|
|
@@ -115,13 +116,18 @@ Past colors never change, so callers should cache them and only ask for the curr
|
|
|
115
116
|
|
|
116
117
|
To create the official API application: sign up on data.rte-france.com, open the "Tempo Like Supply Contract" API, choose "S'abonner à l'API" (this creates an application), then copy its client ID and secret.
|
|
117
118
|
|
|
119
|
+
## Outdoor temperature
|
|
120
|
+
|
|
121
|
+
`OpenMeteoClient(session).async_hourly_temperatures(latitude, longitude, start, end)` returns the air temperature at 2 m (°C) of each hour of the UTC days `start` to `end`, keyed by the UTC start of the hour. It reads Open-Meteo's [historical weather API](https://open-meteo.com/en/docs/historical-weather-api): free for non-commercial use, without an account, back to 1940. Its default model blends the ERA5 reanalyses with the ECMWF forecast model, so it covers the last days too; those hours are revised about five days later, so callers should ask for the last week again. Long ranges are split into requests of 366 days at most. The data is under [CC BY 4.0](https://open-meteo.com/en/licence): credit Open-Meteo where it is shown.
|
|
122
|
+
|
|
118
123
|
## Errors
|
|
119
124
|
|
|
120
125
|
Every error derives from `ElecTariffsError`:
|
|
121
126
|
|
|
122
127
|
- `MissingColorError`, `MissingPriceError` (with the `day` concerned);
|
|
123
128
|
- `TrvServerError`, `TrvFormatError` for data.gouv.fr;
|
|
124
|
-
- `TempoServerError` (network or 5xx), `TempoRateLimitError` (429), `TempoAuthError` (credentials refused) and `TempoFormatError` for the Tempo sources
|
|
129
|
+
- `TempoServerError` (network or 5xx), `TempoRateLimitError` (429), `TempoAuthError` (credentials refused) and `TempoFormatError` for the Tempo sources;
|
|
130
|
+
- `WeatherServerError` (network or 5xx), `WeatherRateLimitError` (429) and `WeatherFormatError` (request refused or unexpected answer) for Open-Meteo.
|
|
125
131
|
|
|
126
132
|
## Development
|
|
127
133
|
|
|
@@ -24,6 +24,10 @@ from .errors import (
|
|
|
24
24
|
TrvError,
|
|
25
25
|
TrvFormatError,
|
|
26
26
|
TrvServerError,
|
|
27
|
+
WeatherError,
|
|
28
|
+
WeatherFormatError,
|
|
29
|
+
WeatherRateLimitError,
|
|
30
|
+
WeatherServerError,
|
|
27
31
|
)
|
|
28
32
|
from .models import (
|
|
29
33
|
TRANCHES,
|
|
@@ -38,10 +42,12 @@ from .models import (
|
|
|
38
42
|
from .shape import DayShape
|
|
39
43
|
from .sources import (
|
|
40
44
|
FallbackTempoSource,
|
|
45
|
+
OpenMeteoClient,
|
|
41
46
|
RteOfficialTempoClient,
|
|
42
47
|
RtePublicTempoClient,
|
|
43
48
|
TempoCalendarSource,
|
|
44
49
|
TrvClient,
|
|
50
|
+
parse_hourly_temperatures,
|
|
45
51
|
parse_trv_csv,
|
|
46
52
|
season_bounds,
|
|
47
53
|
season_of,
|
|
@@ -59,6 +65,7 @@ __all__ = [
|
|
|
59
65
|
"HourCost",
|
|
60
66
|
"MissingColorError",
|
|
61
67
|
"MissingPriceError",
|
|
68
|
+
"OpenMeteoClient",
|
|
62
69
|
"PricePeriod",
|
|
63
70
|
"RteOfficialTempoClient",
|
|
64
71
|
"RtePublicTempoClient",
|
|
@@ -75,10 +82,15 @@ __all__ = [
|
|
|
75
82
|
"TrvError",
|
|
76
83
|
"TrvFormatError",
|
|
77
84
|
"TrvServerError",
|
|
85
|
+
"WeatherError",
|
|
86
|
+
"WeatherFormatError",
|
|
87
|
+
"WeatherRateLimitError",
|
|
88
|
+
"WeatherServerError",
|
|
78
89
|
"__version__",
|
|
79
90
|
"cost_hour",
|
|
80
91
|
"fixed_cost_per_hour",
|
|
81
92
|
"is_off_peak",
|
|
93
|
+
"parse_hourly_temperatures",
|
|
82
94
|
"parse_trv_csv",
|
|
83
95
|
"period_at",
|
|
84
96
|
"price_at",
|
|
@@ -55,3 +55,19 @@ class TempoAuthError(TempoError):
|
|
|
55
55
|
|
|
56
56
|
class TempoFormatError(TempoError):
|
|
57
57
|
"""The calendar source answered with data in an unexpected format."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class WeatherError(ElecTariffsError):
|
|
61
|
+
"""The outdoor temperature could not be read."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class WeatherServerError(WeatherError):
|
|
65
|
+
"""The weather source could not be reached or answered with a server error."""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class WeatherRateLimitError(WeatherError):
|
|
69
|
+
"""The weather source asks to slow down (HTTP 429)."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class WeatherFormatError(WeatherError):
|
|
73
|
+
"""The weather source refused the request or answered in an unexpected format."""
|
|
@@ -9,13 +9,16 @@ from .tempo import (
|
|
|
9
9
|
season_of,
|
|
10
10
|
)
|
|
11
11
|
from .trv import TrvClient, parse_trv_csv
|
|
12
|
+
from .weather import OpenMeteoClient, parse_hourly_temperatures
|
|
12
13
|
|
|
13
14
|
__all__ = [
|
|
14
15
|
"FallbackTempoSource",
|
|
16
|
+
"OpenMeteoClient",
|
|
15
17
|
"RteOfficialTempoClient",
|
|
16
18
|
"RtePublicTempoClient",
|
|
17
19
|
"TempoCalendarSource",
|
|
18
20
|
"TrvClient",
|
|
21
|
+
"parse_hourly_temperatures",
|
|
19
22
|
"parse_trv_csv",
|
|
20
23
|
"season_bounds",
|
|
21
24
|
"season_of",
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Outdoor temperature from Open-Meteo's historical weather API.
|
|
2
|
+
|
|
3
|
+
The archive gives the hourly air temperature at 2 m anywhere since 1940, free for
|
|
4
|
+
non-commercial use and without an account (data under CC BY 4.0). Its default
|
|
5
|
+
model blends the ERA5 reanalyses with the ECMWF forecast model, so it covers the
|
|
6
|
+
last days too; their hours are revised once the reanalysis catches up, about five
|
|
7
|
+
days later.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from datetime import UTC, date, datetime, timedelta
|
|
11
|
+
from typing import Any, Final
|
|
12
|
+
|
|
13
|
+
import aiohttp
|
|
14
|
+
|
|
15
|
+
from elec_tariffs.errors import (
|
|
16
|
+
WeatherFormatError,
|
|
17
|
+
WeatherRateLimitError,
|
|
18
|
+
WeatherServerError,
|
|
19
|
+
)
|
|
20
|
+
from elec_tariffs.sources.tempo import USER_AGENT
|
|
21
|
+
|
|
22
|
+
ARCHIVE_URL: Final = "https://archive-api.open-meteo.com/v1/archive"
|
|
23
|
+
MAX_DAYS: Final = 366
|
|
24
|
+
|
|
25
|
+
_TIMEOUT: Final = aiohttp.ClientTimeout(total=60)
|
|
26
|
+
_HTTP_OK: Final = 200
|
|
27
|
+
_HTTP_TOO_MANY_REQUESTS: Final = 429
|
|
28
|
+
_HTTP_SERVER_ERROR: Final = 500
|
|
29
|
+
_UNIT: Final = "°C"
|
|
30
|
+
|
|
31
|
+
type Temperatures = dict[datetime, float]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parse_hourly_temperatures(payload: Any) -> Temperatures:
|
|
35
|
+
"""Read the hourly `temperature_2m` of an answer asked in GMT.
|
|
36
|
+
|
|
37
|
+
Hours without a value are left out. Anything unexpected raises
|
|
38
|
+
WeatherFormatError, rather than giving wrong temperatures.
|
|
39
|
+
"""
|
|
40
|
+
if not isinstance(payload, dict) or payload.get("utc_offset_seconds") != 0:
|
|
41
|
+
msg = "The answer is not in GMT"
|
|
42
|
+
raise WeatherFormatError(msg)
|
|
43
|
+
hourly = payload.get("hourly")
|
|
44
|
+
units = payload.get("hourly_units")
|
|
45
|
+
if not isinstance(hourly, dict) or not isinstance(units, dict):
|
|
46
|
+
msg = "The answer has no hourly values"
|
|
47
|
+
raise WeatherFormatError(msg)
|
|
48
|
+
if units.get("temperature_2m") != _UNIT:
|
|
49
|
+
msg = f"Unexpected temperature unit {units.get('temperature_2m')!r}"
|
|
50
|
+
raise WeatherFormatError(msg)
|
|
51
|
+
times = hourly.get("time")
|
|
52
|
+
values = hourly.get("temperature_2m")
|
|
53
|
+
if (
|
|
54
|
+
not isinstance(times, list)
|
|
55
|
+
or not isinstance(values, list)
|
|
56
|
+
or len(times) != len(values)
|
|
57
|
+
):
|
|
58
|
+
msg = "The hourly times and temperatures don't match"
|
|
59
|
+
raise WeatherFormatError(msg)
|
|
60
|
+
temperatures: Temperatures = {}
|
|
61
|
+
for moment, value in zip(times, values, strict=True):
|
|
62
|
+
try:
|
|
63
|
+
start = datetime.fromisoformat(moment).replace(tzinfo=UTC)
|
|
64
|
+
except (TypeError, ValueError) as err:
|
|
65
|
+
msg = f"Unexpected time {moment!r}"
|
|
66
|
+
raise WeatherFormatError(msg) from err
|
|
67
|
+
if value is None:
|
|
68
|
+
continue
|
|
69
|
+
if isinstance(value, bool) or not isinstance(value, int | float):
|
|
70
|
+
msg = f"Unexpected temperature {value!r}"
|
|
71
|
+
raise WeatherFormatError(msg)
|
|
72
|
+
temperatures[start] = float(value)
|
|
73
|
+
return temperatures
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class OpenMeteoClient:
|
|
77
|
+
"""Open-Meteo's historical weather API, no account needed."""
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self, session: aiohttp.ClientSession, *, url: str = ARCHIVE_URL
|
|
81
|
+
) -> None:
|
|
82
|
+
"""Use the caller's HTTP session; `url` replaces Open-Meteo's address."""
|
|
83
|
+
self._session = session
|
|
84
|
+
self._url = url
|
|
85
|
+
|
|
86
|
+
async def _get(self, params: dict[str, str]) -> Any:
|
|
87
|
+
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
|
|
88
|
+
try:
|
|
89
|
+
async with self._session.get(
|
|
90
|
+
self._url, params=params, headers=headers, timeout=_TIMEOUT
|
|
91
|
+
) as response:
|
|
92
|
+
if response.status == _HTTP_TOO_MANY_REQUESTS:
|
|
93
|
+
msg = "Too many requests (HTTP 429)"
|
|
94
|
+
raise WeatherRateLimitError(msg)
|
|
95
|
+
if response.status >= _HTTP_SERVER_ERROR:
|
|
96
|
+
msg = f"Server error (HTTP {response.status})"
|
|
97
|
+
raise WeatherServerError(msg)
|
|
98
|
+
payload = await response.json(content_type=None)
|
|
99
|
+
except ValueError as err:
|
|
100
|
+
msg = "Open-Meteo did not answer with JSON"
|
|
101
|
+
raise WeatherFormatError(msg) from err
|
|
102
|
+
except (aiohttp.ClientError, TimeoutError) as err:
|
|
103
|
+
msg = f"Could not reach Open-Meteo: {err}"
|
|
104
|
+
raise WeatherServerError(msg) from err
|
|
105
|
+
if response.status != _HTTP_OK:
|
|
106
|
+
reason = payload.get("reason") if isinstance(payload, dict) else None
|
|
107
|
+
msg = f"Open-Meteo refused the request (HTTP {response.status}): {reason}"
|
|
108
|
+
raise WeatherFormatError(msg)
|
|
109
|
+
return payload
|
|
110
|
+
|
|
111
|
+
async def async_hourly_temperatures(
|
|
112
|
+
self, latitude: float, longitude: float, start: date, end: date
|
|
113
|
+
) -> Temperatures:
|
|
114
|
+
"""Return the temperature (°C) of each hour of the UTC days `start` to `end`.
|
|
115
|
+
|
|
116
|
+
Keys are the UTC start of each hour. Hours without a value yet are missing.
|
|
117
|
+
Long ranges are asked in parts of at most MAX_DAYS days.
|
|
118
|
+
"""
|
|
119
|
+
temperatures: Temperatures = {}
|
|
120
|
+
first = start
|
|
121
|
+
while first <= end:
|
|
122
|
+
last = min(end, first + timedelta(days=MAX_DAYS - 1))
|
|
123
|
+
payload = await self._get(
|
|
124
|
+
{
|
|
125
|
+
"latitude": str(latitude),
|
|
126
|
+
"longitude": str(longitude),
|
|
127
|
+
"start_date": first.isoformat(),
|
|
128
|
+
"end_date": last.isoformat(),
|
|
129
|
+
"hourly": "temperature_2m",
|
|
130
|
+
"timezone": "GMT",
|
|
131
|
+
}
|
|
132
|
+
)
|
|
133
|
+
temperatures.update(parse_hourly_temperatures(payload))
|
|
134
|
+
first = last + timedelta(days=1)
|
|
135
|
+
return temperatures
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"latitude": 48.89279, "longitude": 2.4448218, "generationtime_ms": 0.06759166717529297, "utc_offset_seconds": 0, "timezone": "GMT", "timezone_abbreviation": "GMT", "elevation": 56.0, "hourly_units": {"time": "iso8601", "temperature_2m": "°C"}, "hourly": {"time": ["2026-01-04T00:00", "2026-01-04T01:00", "2026-01-04T02:00", "2026-01-04T03:00", "2026-01-04T04:00", "2026-01-04T05:00", "2026-01-04T06:00", "2026-01-04T07:00", "2026-01-04T08:00", "2026-01-04T09:00", "2026-01-04T10:00", "2026-01-04T11:00", "2026-01-04T12:00", "2026-01-04T13:00", "2026-01-04T14:00", "2026-01-04T15:00", "2026-01-04T16:00", "2026-01-04T17:00", "2026-01-04T18:00", "2026-01-04T19:00", "2026-01-04T20:00", "2026-01-04T21:00", "2026-01-04T22:00", "2026-01-04T23:00", "2026-01-05T00:00", "2026-01-05T01:00", "2026-01-05T02:00", "2026-01-05T03:00", "2026-01-05T04:00", "2026-01-05T05:00", "2026-01-05T06:00", "2026-01-05T07:00", "2026-01-05T08:00", "2026-01-05T09:00", "2026-01-05T10:00", "2026-01-05T11:00", "2026-01-05T12:00", "2026-01-05T13:00", "2026-01-05T14:00", "2026-01-05T15:00", "2026-01-05T16:00", "2026-01-05T17:00", "2026-01-05T18:00", "2026-01-05T19:00", "2026-01-05T20:00", "2026-01-05T21:00", "2026-01-05T22:00", "2026-01-05T23:00"], "temperature_2m": [-1.7, -1.8, -2.3, -3.3, -3.8, -4.8, -4.8, -6.1, -6.3, -5.2, -3.5, -1.5, 0.9, 1.4, 1.6, 0.2, -0.9, -1.5, -0.7, -1.0, -1.9, -2.2, -2.6, -3.2, -4.2, -4.4, -4.3, -4.3, -4.2, -4.2, -4.1, -4.1, -4.0, -3.1, -2.0, -1.0, -1.3, -1.2, -1.0, -1.1, -1.1, -1.0, -1.1, -1.0, -0.8, -3.5, -5.1, -2.1]}}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Tests of the Open-Meteo outdoor temperature client."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from datetime import UTC, date, datetime
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import aiohttp
|
|
8
|
+
import pytest
|
|
9
|
+
from aiohttp import web
|
|
10
|
+
|
|
11
|
+
from elec_tariffs import (
|
|
12
|
+
OpenMeteoClient,
|
|
13
|
+
WeatherFormatError,
|
|
14
|
+
WeatherRateLimitError,
|
|
15
|
+
WeatherServerError,
|
|
16
|
+
parse_hourly_temperatures,
|
|
17
|
+
)
|
|
18
|
+
from elec_tariffs.sources.tempo import USER_AGENT
|
|
19
|
+
|
|
20
|
+
from .conftest import FakeServer, load_fixture
|
|
21
|
+
|
|
22
|
+
PATH = "/v1/archive"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def recorded() -> Any:
|
|
26
|
+
return json.loads(load_fixture("open_meteo_archive.json"))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def answer(times: list[Any], values: Any) -> dict[str, Any]:
|
|
30
|
+
return {
|
|
31
|
+
"utc_offset_seconds": 0,
|
|
32
|
+
"hourly_units": {"time": "iso8601", "temperature_2m": "°C"},
|
|
33
|
+
"hourly": {"time": times, "temperature_2m": values},
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_parse_the_recorded_answer() -> None:
|
|
38
|
+
temperatures = parse_hourly_temperatures(recorded())
|
|
39
|
+
assert len(temperatures) == 48
|
|
40
|
+
first = datetime(2026, 1, 4, tzinfo=UTC)
|
|
41
|
+
assert min(temperatures) == first
|
|
42
|
+
assert max(temperatures) == datetime(2026, 1, 5, 23, tzinfo=UTC)
|
|
43
|
+
assert temperatures[first] == recorded()["hourly"]["temperature_2m"][0]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_hours_without_a_value_are_left_out() -> None:
|
|
47
|
+
temperatures = parse_hourly_temperatures(
|
|
48
|
+
answer(["2026-01-04T00:00", "2026-01-04T01:00"], [1.5, None])
|
|
49
|
+
)
|
|
50
|
+
assert temperatures == {datetime(2026, 1, 4, tzinfo=UTC): 1.5}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@pytest.mark.parametrize(
|
|
54
|
+
"payload",
|
|
55
|
+
[
|
|
56
|
+
[],
|
|
57
|
+
{**answer([], []), "utc_offset_seconds": 3600},
|
|
58
|
+
{"utc_offset_seconds": 0, "hourly": {}},
|
|
59
|
+
{**answer([], []), "hourly_units": {"temperature_2m": "°F"}},
|
|
60
|
+
answer(["2026-01-04T00:00"], []),
|
|
61
|
+
answer(["2026-01-04T00:00"], "1.5"),
|
|
62
|
+
answer(["yesterday"], [1.5]),
|
|
63
|
+
answer([None], [1.5]),
|
|
64
|
+
answer(["2026-01-04T00:00"], ["1.5"]),
|
|
65
|
+
answer(["2026-01-04T00:00"], [True]),
|
|
66
|
+
],
|
|
67
|
+
)
|
|
68
|
+
def test_unexpected_answers_are_refused(payload: Any) -> None:
|
|
69
|
+
with pytest.raises(WeatherFormatError):
|
|
70
|
+
parse_hourly_temperatures(payload)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def test_ask_in_gmt(session: aiohttp.ClientSession, server: FakeServer) -> None:
|
|
74
|
+
server.json("GET", PATH, recorded())
|
|
75
|
+
client = OpenMeteoClient(session, url=f"{server.url}{PATH}")
|
|
76
|
+
temperatures = await client.async_hourly_temperatures(
|
|
77
|
+
48.9, 2.4, date(2026, 1, 4), date(2026, 1, 5)
|
|
78
|
+
)
|
|
79
|
+
assert len(temperatures) == 48
|
|
80
|
+
[request] = server.calls(PATH)
|
|
81
|
+
assert dict(request.query) == {
|
|
82
|
+
"latitude": "48.9",
|
|
83
|
+
"longitude": "2.4",
|
|
84
|
+
"start_date": "2026-01-04",
|
|
85
|
+
"end_date": "2026-01-05",
|
|
86
|
+
"hourly": "temperature_2m",
|
|
87
|
+
"timezone": "GMT",
|
|
88
|
+
}
|
|
89
|
+
assert request.headers["User-Agent"] == USER_AGENT
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def test_long_ranges_are_asked_in_parts(
|
|
93
|
+
session: aiohttp.ClientSession, server: FakeServer
|
|
94
|
+
) -> None:
|
|
95
|
+
server.json("GET", PATH, answer(["2025-01-01T00:00"], [1.0]))
|
|
96
|
+
server.json("GET", PATH, answer(["2026-01-02T00:00"], [2.0]))
|
|
97
|
+
client = OpenMeteoClient(session, url=f"{server.url}{PATH}")
|
|
98
|
+
temperatures = await client.async_hourly_temperatures(
|
|
99
|
+
48.9, 2.4, date(2025, 1, 1), date(2026, 1, 2)
|
|
100
|
+
)
|
|
101
|
+
assert temperatures == {
|
|
102
|
+
datetime(2025, 1, 1, tzinfo=UTC): 1.0,
|
|
103
|
+
datetime(2026, 1, 2, tzinfo=UTC): 2.0,
|
|
104
|
+
}
|
|
105
|
+
ranges = [
|
|
106
|
+
(request.query["start_date"], request.query["end_date"])
|
|
107
|
+
for request in server.calls(PATH)
|
|
108
|
+
]
|
|
109
|
+
assert ranges == [("2025-01-01", "2026-01-01"), ("2026-01-02", "2026-01-02")]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def test_an_empty_range_asks_nothing(
|
|
113
|
+
session: aiohttp.ClientSession, server: FakeServer
|
|
114
|
+
) -> None:
|
|
115
|
+
client = OpenMeteoClient(session, url=f"{server.url}{PATH}")
|
|
116
|
+
assert (
|
|
117
|
+
await client.async_hourly_temperatures(
|
|
118
|
+
48.9, 2.4, date(2026, 1, 5), date(2026, 1, 4)
|
|
119
|
+
)
|
|
120
|
+
== {}
|
|
121
|
+
)
|
|
122
|
+
assert server.requests == []
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@pytest.mark.parametrize(
|
|
126
|
+
("status", "error"),
|
|
127
|
+
[(429, WeatherRateLimitError), (502, WeatherServerError)],
|
|
128
|
+
)
|
|
129
|
+
async def test_server_errors(
|
|
130
|
+
session: aiohttp.ClientSession,
|
|
131
|
+
server: FakeServer,
|
|
132
|
+
status: int,
|
|
133
|
+
error: type[Exception],
|
|
134
|
+
) -> None:
|
|
135
|
+
server.text("GET", PATH, "busy", status=status)
|
|
136
|
+
client = OpenMeteoClient(session, url=f"{server.url}{PATH}")
|
|
137
|
+
with pytest.raises(error):
|
|
138
|
+
await client.async_hourly_temperatures(
|
|
139
|
+
48.9, 2.4, date(2026, 1, 4), date(2026, 1, 4)
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def test_a_refused_request(
|
|
144
|
+
session: aiohttp.ClientSession, server: FakeServer
|
|
145
|
+
) -> None:
|
|
146
|
+
server.json(
|
|
147
|
+
"GET",
|
|
148
|
+
PATH,
|
|
149
|
+
{"error": True, "reason": "End-date must be larger"},
|
|
150
|
+
status=400,
|
|
151
|
+
)
|
|
152
|
+
client = OpenMeteoClient(session, url=f"{server.url}{PATH}")
|
|
153
|
+
with pytest.raises(WeatherFormatError, match="End-date must be larger"):
|
|
154
|
+
await client.async_hourly_temperatures(
|
|
155
|
+
48.9, 2.4, date(2026, 1, 4), date(2026, 1, 4)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
async def test_not_json(session: aiohttp.ClientSession, server: FakeServer) -> None:
|
|
160
|
+
server.text("GET", PATH, "<html>")
|
|
161
|
+
client = OpenMeteoClient(session, url=f"{server.url}{PATH}")
|
|
162
|
+
with pytest.raises(WeatherFormatError):
|
|
163
|
+
await client.async_hourly_temperatures(
|
|
164
|
+
48.9, 2.4, date(2026, 1, 4), date(2026, 1, 4)
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
async def test_unreachable(session: aiohttp.ClientSession, closed_url: str) -> None:
|
|
169
|
+
client = OpenMeteoClient(session, url=closed_url)
|
|
170
|
+
with pytest.raises(WeatherServerError):
|
|
171
|
+
await client.async_hourly_temperatures(
|
|
172
|
+
48.9, 2.4, date(2026, 1, 4), date(2026, 1, 4)
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
async def test_an_error_answer_that_is_not_an_object(
|
|
177
|
+
session: aiohttp.ClientSession, server: FakeServer
|
|
178
|
+
) -> None:
|
|
179
|
+
async def handler(_: web.Request) -> web.Response:
|
|
180
|
+
return web.json_response([], status=404)
|
|
181
|
+
|
|
182
|
+
server.add("GET", PATH, handler)
|
|
183
|
+
client = OpenMeteoClient(session, url=f"{server.url}{PATH}")
|
|
184
|
+
with pytest.raises(WeatherFormatError, match="HTTP 404"):
|
|
185
|
+
await client.async_hourly_temperatures(
|
|
186
|
+
48.9, 2.4, date(2026, 1, 4), date(2026, 1, 4)
|
|
187
|
+
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|