ideenergy 2.0.1.dev3__tar.gz → 3.0.0a1__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.
Files changed (26) hide show
  1. ideenergy-3.0.0a1/PKG-INFO +171 -0
  2. ideenergy-3.0.0a1/README.md +142 -0
  3. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy/__init__.py +2 -0
  4. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy/cli.py +18 -6
  5. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy/client.py +34 -19
  6. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy/mock.py +21 -24
  7. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy/parsers.py +47 -20
  8. ideenergy-3.0.0a1/ideenergy/tz.py +28 -0
  9. ideenergy-3.0.0a1/ideenergy.egg-info/PKG-INFO +171 -0
  10. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy.egg-info/SOURCES.txt +3 -1
  11. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy.egg-info/requires.txt +1 -1
  12. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/pyproject.toml +14 -3
  13. ideenergy-3.0.0a1/tests/test_client.py +316 -0
  14. ideenergy-3.0.0a1/tests/test_dst.py +165 -0
  15. ideenergy-2.0.1.dev3/PKG-INFO +0 -36
  16. ideenergy-2.0.1.dev3/README.md +0 -18
  17. ideenergy-2.0.1.dev3/ideenergy.egg-info/PKG-INFO +0 -36
  18. ideenergy-2.0.1.dev3/tests/test_client.py +0 -170
  19. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/LICENSE +0 -0
  20. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy/__main__.py +0 -0
  21. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy/endpoints.py +0 -0
  22. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy/types.py +0 -0
  23. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy.egg-info/dependency_links.txt +0 -0
  24. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy.egg-info/entry_points.txt +0 -0
  25. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/ideenergy.egg-info/top_level.txt +0 -0
  26. {ideenergy-2.0.1.dev3 → ideenergy-3.0.0a1}/setup.cfg +0 -0
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.4
2
+ Name: ideenergy
3
+ Version: 3.0.0a1
4
+ Summary: Programmatic access to consumer energy consumption from https://www.i-de.es/ (Spanish energy distributor)
5
+ Author-email: Luis López <luis@cuarentaydos.com>
6
+ License-Expression: GPL-3.0-only
7
+ Project-URL: Homepage, https://github.com/ldotlopez/ideenergy
8
+ Project-URL: Issues, https://github.com/ldotlopez/ideenergy/issues
9
+ Project-URL: Repository, https://github.com/ldotlopez/ideenergy.git
10
+ Keywords: energy,i-de,iberdrola,spain,energy-consumption,asyncio
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Home Automation
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.11
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: aiohttp<4.0,>=3.8
26
+ Requires-Dist: python-dotenv>=1.0
27
+ Requires-Dist: importlib-metadata; python_version >= "3.11"
28
+ Dynamic: license-file
29
+
30
+ # ideenergy
31
+
32
+ 🇪🇸 Español · [🇬🇧 English](https://github.com/ldotlopez/ideenergy/blob/main/README.en.md)
33
+
34
+ Acceso programático al consumo eléctrico de consumidores en [i-DE](https://www.i-de.es/) (Iberdrola Distribución Eléctrica).
35
+
36
+ <!-- Code and releases -->
37
+
38
+ [![PyPI](https://img.shields.io/pypi/v/ideenergy?logo=pypi&logoColor=white)](https://pypi.org/project/ideenergy/)
39
+ [![Python](https://img.shields.io/pypi/pyversions/ideenergy?logo=python&logoColor=white)](https://pypi.org/project/ideenergy/)
40
+ [![Release](https://img.shields.io/github/v/release/ldotlopez/ideenergy?include_prereleases&logo=github)](https://github.com/ldotlopez/ideenergy/releases)
41
+ [![License](https://img.shields.io/github/license/ldotlopez/ideenergy)](https://github.com/ldotlopez/ideenergy/blob/main/LICENSE)
42
+
43
+ <!-- Workflows -->
44
+
45
+ [![CI](https://img.shields.io/github/actions/workflow/status/ldotlopez/ideenergy/ci.yml?branch=main&label=CI&logo=githubactions&logoColor=white)](https://github.com/ldotlopez/ideenergy/actions/workflows/ci.yml)
46
+ [![Release workflow](https://img.shields.io/github/actions/workflow/status/ldotlopez/ideenergy/release.yml?label=release&logo=githubactions&logoColor=white)](https://github.com/ldotlopez/ideenergy/actions/workflows/release.yml)
47
+
48
+ <!-- Sponsors -->
49
+
50
+ [![Buy Me a Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-zepolson-FFDD00?logo=buymeacoffee&logoColor=black)](https://www.buymeacoffee.com/zepolson)
51
+
52
+ > **Aviso:** proyecto no oficial. No está afiliado, respaldado ni patrocinado por Iberdrola ni por i-DE.
53
+ > Usa la API privada de la web/app de i-DE, que puede cambiar o dejar de funcionar sin previo aviso.
54
+
55
+ ## ⚠️ Antes de empezar: la API es muy restrictiva
56
+
57
+ La API de i-DE limita mucho las peticiones y **un uso abusivo puede bloquear tu cuenta**.
58
+
59
+ - Haz las mínimas llamadas posibles y no las metas en bucles ni reintentos agresivos.
60
+ - Reutiliza una única sesión (un solo `login`) para todas las consultas.
61
+ - `get_measure()` y `get_in_progress_consumption()` consultan al ICP (contador) y pueden tardar hasta un minuto.
62
+ - Para desarrollar y probar, usa `MockClient` (ver más abajo) en lugar de la API real.
63
+
64
+ ## Instalación
65
+
66
+ Requiere Python 3.11 o superior.
67
+
68
+ ```bash
69
+ pip install ideenergy
70
+ # o con uv
71
+ uv add ideenergy
72
+ ```
73
+
74
+ ## Línea de comandos
75
+
76
+ ```bash
77
+ export I_DE_ENERGY_USERNAME="tu-usuario"
78
+ export I_DE_ENERGY_PASSWORD="tu-contraseña" # también puedes usar un fichero .env
79
+
80
+ ideenergy --list-contracts
81
+ ideenergy --get-measure
82
+ ideenergy --get-historical-consumption --start 2026-01-01 --end 2026-01-07
83
+ ```
84
+
85
+ Opciones principales: `--contract`, `--list-contracts`, `--get-measure`, `--get-historical-consumption`,
86
+ `--get-historical-generation`, `--get-historical-power-demand`, `--get-in-progress-consumption`,
87
+ `--start` / `--end` (ISO 8601, hora de Madrid salvo que se indique el desfase; por defecto los últimos 7 días). También acepta `-u/--username` y `-p/--password`.
88
+
89
+ > `--trace-http-requests` es solo para depuración: vuelca todo el tráfico, **incluida tu contraseña y cookies de sesión**.
90
+ > `--check-auth-validity` se ejecuta durante horas y hace logins repetidos: no lo uses contra la API real salvo que sepas lo que haces.
91
+
92
+ ## Uso rápido
93
+
94
+ ```python
95
+ import asyncio
96
+ import aiohttp
97
+ import ideenergy
98
+
99
+
100
+ async def main():
101
+ async with aiohttp.ClientSession() as session:
102
+ client = ideenergy.Client(
103
+ session=session,
104
+ username="tu-usuario",
105
+ password="tu-contraseña",
106
+ )
107
+
108
+ # Si tienes varios contratos, selecciona uno
109
+ # contracts = await client.get_contracts()
110
+ # await client.select_contract(contracts[0]["codContrato"])
111
+
112
+ # Lectura actual del contador (acumulado en kWh e instantáneo en kW)
113
+ measure = await client.get_measure()
114
+ print(measure.accumulate, measure.instant)
115
+
116
+ # Consumo histórico (por defecto, últimos 7 días)
117
+ history = await client.get_historical_consumption()
118
+ for period in history.periods:
119
+ print(period.start, period.end, period.value)
120
+
121
+
122
+ asyncio.run(main())
123
+ ```
124
+
125
+ El login es automático en la primera llamada y la sesión se renueva sola.
126
+
127
+ ### Métodos disponibles
128
+
129
+ | Método | Descripción |
130
+ |---|---|
131
+ | `get_contracts()` / `select_contract(id)` | Lista y selecciona contrato |
132
+ | `get_contract_details()` | Detalles del contrato seleccionado |
133
+ | `get_measure()` | Lectura actual del contador (`Measure`) |
134
+ | `get_historical_consumption(start, end)` | Consumo histórico (`HistoricalConsumption`) |
135
+ | `get_in_progress_consumption()` | Consumo del periodo en curso |
136
+ | `get_historical_generation(start, end)` | Generación histórica (autoconsumo) |
137
+ | `get_historical_power_demand()` | Demanda de potencia (último año) |
138
+ | `is_icp_ready()` | Comprueba si el ICP está disponible |
139
+
140
+ Las fechas llevan zona horaria: `start`/`end` deben tenerla (sin ella se lanza `ValueError`), y los periodos devueltos están en Europe/Madrid (`ideenergy.LOCAL_TZ`), también en los días de cambio de hora (23/25 horas).
141
+
142
+ Errores: `ClientError` y derivadas (`RequestFailedError`, `CommandError`, `InvalidData`, `InvalidContractError`, `UserExpiredError`).
143
+
144
+ ## Desarrollo sin tocar la API real
145
+
146
+ `MockClient` imita al cliente con datos grabados, sin red:
147
+
148
+ ```python
149
+ client = ideenergy.MockClient(session=None, username="x", password="y")
150
+ ```
151
+
152
+ Tests (offline):
153
+
154
+ ```bash
155
+ uv sync
156
+ uv run python -m unittest discover tests
157
+ ```
158
+
159
+ ## Enlaces útiles
160
+
161
+ - [Componente relacionado para Home Assistant](https://github.com/ldotlopez/ha-ideenergy)
162
+ - [Documentación sobre otras distribuidoras](https://www.genbeta.com/web/como-saber-consumo-electrico-tiempo-real-casa)
163
+
164
+ ## Home Assistant
165
+
166
+ Si lo que buscas es ver tu consumo en Home Assistant, usa la integración
167
+ [ha-ideenergy](https://github.com/ldotlopez/ha-ideenergy), que está construida sobre esta librería.
168
+
169
+ ## Licencia
170
+
171
+ [GPL-3.0-only](https://github.com/ldotlopez/ideenergy/blob/main/LICENSE)
@@ -0,0 +1,142 @@
1
+ # ideenergy
2
+
3
+ 🇪🇸 Español · [🇬🇧 English](https://github.com/ldotlopez/ideenergy/blob/main/README.en.md)
4
+
5
+ Acceso programático al consumo eléctrico de consumidores en [i-DE](https://www.i-de.es/) (Iberdrola Distribución Eléctrica).
6
+
7
+ <!-- Code and releases -->
8
+
9
+ [![PyPI](https://img.shields.io/pypi/v/ideenergy?logo=pypi&logoColor=white)](https://pypi.org/project/ideenergy/)
10
+ [![Python](https://img.shields.io/pypi/pyversions/ideenergy?logo=python&logoColor=white)](https://pypi.org/project/ideenergy/)
11
+ [![Release](https://img.shields.io/github/v/release/ldotlopez/ideenergy?include_prereleases&logo=github)](https://github.com/ldotlopez/ideenergy/releases)
12
+ [![License](https://img.shields.io/github/license/ldotlopez/ideenergy)](https://github.com/ldotlopez/ideenergy/blob/main/LICENSE)
13
+
14
+ <!-- Workflows -->
15
+
16
+ [![CI](https://img.shields.io/github/actions/workflow/status/ldotlopez/ideenergy/ci.yml?branch=main&label=CI&logo=githubactions&logoColor=white)](https://github.com/ldotlopez/ideenergy/actions/workflows/ci.yml)
17
+ [![Release workflow](https://img.shields.io/github/actions/workflow/status/ldotlopez/ideenergy/release.yml?label=release&logo=githubactions&logoColor=white)](https://github.com/ldotlopez/ideenergy/actions/workflows/release.yml)
18
+
19
+ <!-- Sponsors -->
20
+
21
+ [![Buy Me a Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-zepolson-FFDD00?logo=buymeacoffee&logoColor=black)](https://www.buymeacoffee.com/zepolson)
22
+
23
+ > **Aviso:** proyecto no oficial. No está afiliado, respaldado ni patrocinado por Iberdrola ni por i-DE.
24
+ > Usa la API privada de la web/app de i-DE, que puede cambiar o dejar de funcionar sin previo aviso.
25
+
26
+ ## ⚠️ Antes de empezar: la API es muy restrictiva
27
+
28
+ La API de i-DE limita mucho las peticiones y **un uso abusivo puede bloquear tu cuenta**.
29
+
30
+ - Haz las mínimas llamadas posibles y no las metas en bucles ni reintentos agresivos.
31
+ - Reutiliza una única sesión (un solo `login`) para todas las consultas.
32
+ - `get_measure()` y `get_in_progress_consumption()` consultan al ICP (contador) y pueden tardar hasta un minuto.
33
+ - Para desarrollar y probar, usa `MockClient` (ver más abajo) en lugar de la API real.
34
+
35
+ ## Instalación
36
+
37
+ Requiere Python 3.11 o superior.
38
+
39
+ ```bash
40
+ pip install ideenergy
41
+ # o con uv
42
+ uv add ideenergy
43
+ ```
44
+
45
+ ## Línea de comandos
46
+
47
+ ```bash
48
+ export I_DE_ENERGY_USERNAME="tu-usuario"
49
+ export I_DE_ENERGY_PASSWORD="tu-contraseña" # también puedes usar un fichero .env
50
+
51
+ ideenergy --list-contracts
52
+ ideenergy --get-measure
53
+ ideenergy --get-historical-consumption --start 2026-01-01 --end 2026-01-07
54
+ ```
55
+
56
+ Opciones principales: `--contract`, `--list-contracts`, `--get-measure`, `--get-historical-consumption`,
57
+ `--get-historical-generation`, `--get-historical-power-demand`, `--get-in-progress-consumption`,
58
+ `--start` / `--end` (ISO 8601, hora de Madrid salvo que se indique el desfase; por defecto los últimos 7 días). También acepta `-u/--username` y `-p/--password`.
59
+
60
+ > `--trace-http-requests` es solo para depuración: vuelca todo el tráfico, **incluida tu contraseña y cookies de sesión**.
61
+ > `--check-auth-validity` se ejecuta durante horas y hace logins repetidos: no lo uses contra la API real salvo que sepas lo que haces.
62
+
63
+ ## Uso rápido
64
+
65
+ ```python
66
+ import asyncio
67
+ import aiohttp
68
+ import ideenergy
69
+
70
+
71
+ async def main():
72
+ async with aiohttp.ClientSession() as session:
73
+ client = ideenergy.Client(
74
+ session=session,
75
+ username="tu-usuario",
76
+ password="tu-contraseña",
77
+ )
78
+
79
+ # Si tienes varios contratos, selecciona uno
80
+ # contracts = await client.get_contracts()
81
+ # await client.select_contract(contracts[0]["codContrato"])
82
+
83
+ # Lectura actual del contador (acumulado en kWh e instantáneo en kW)
84
+ measure = await client.get_measure()
85
+ print(measure.accumulate, measure.instant)
86
+
87
+ # Consumo histórico (por defecto, últimos 7 días)
88
+ history = await client.get_historical_consumption()
89
+ for period in history.periods:
90
+ print(period.start, period.end, period.value)
91
+
92
+
93
+ asyncio.run(main())
94
+ ```
95
+
96
+ El login es automático en la primera llamada y la sesión se renueva sola.
97
+
98
+ ### Métodos disponibles
99
+
100
+ | Método | Descripción |
101
+ |---|---|
102
+ | `get_contracts()` / `select_contract(id)` | Lista y selecciona contrato |
103
+ | `get_contract_details()` | Detalles del contrato seleccionado |
104
+ | `get_measure()` | Lectura actual del contador (`Measure`) |
105
+ | `get_historical_consumption(start, end)` | Consumo histórico (`HistoricalConsumption`) |
106
+ | `get_in_progress_consumption()` | Consumo del periodo en curso |
107
+ | `get_historical_generation(start, end)` | Generación histórica (autoconsumo) |
108
+ | `get_historical_power_demand()` | Demanda de potencia (último año) |
109
+ | `is_icp_ready()` | Comprueba si el ICP está disponible |
110
+
111
+ Las fechas llevan zona horaria: `start`/`end` deben tenerla (sin ella se lanza `ValueError`), y los periodos devueltos están en Europe/Madrid (`ideenergy.LOCAL_TZ`), también en los días de cambio de hora (23/25 horas).
112
+
113
+ Errores: `ClientError` y derivadas (`RequestFailedError`, `CommandError`, `InvalidData`, `InvalidContractError`, `UserExpiredError`).
114
+
115
+ ## Desarrollo sin tocar la API real
116
+
117
+ `MockClient` imita al cliente con datos grabados, sin red:
118
+
119
+ ```python
120
+ client = ideenergy.MockClient(session=None, username="x", password="y")
121
+ ```
122
+
123
+ Tests (offline):
124
+
125
+ ```bash
126
+ uv sync
127
+ uv run python -m unittest discover tests
128
+ ```
129
+
130
+ ## Enlaces útiles
131
+
132
+ - [Componente relacionado para Home Assistant](https://github.com/ldotlopez/ha-ideenergy)
133
+ - [Documentación sobre otras distribuidoras](https://www.genbeta.com/web/como-saber-consumo-electrico-tiempo-real-casa)
134
+
135
+ ## Home Assistant
136
+
137
+ Si lo que buscas es ver tu consumo en Home Assistant, usa la integración
138
+ [ha-ideenergy](https://github.com/ldotlopez/ha-ideenergy), que está construida sobre esta librería.
139
+
140
+ ## Licencia
141
+
142
+ [GPL-3.0-only](https://github.com/ldotlopez/ideenergy/blob/main/LICENSE)
@@ -35,12 +35,14 @@ from .types import (
35
35
  Measure,
36
36
  PeriodValue,
37
37
  )
38
+ from .tz import LOCAL_TZ
38
39
 
39
40
  # def sanitize_address(address):
40
41
  # return " ".join([x.strip().capitalize() for x in address.split(" ") if x])
41
42
 
42
43
 
43
44
  __all__ = [
45
+ "LOCAL_TZ",
44
46
  "Client",
45
47
  "ClientError",
46
48
  "CommandError",
@@ -31,7 +31,15 @@ from types import SimpleNamespace
31
31
  import aiohttp
32
32
  import dotenv
33
33
 
34
- from . import Client, RequestFailedError, UserExpiredError
34
+ from . import LOCAL_TZ, Client, RequestFailedError, UserExpiredError, tz
35
+
36
+
37
+ def parse_local_datetime(value: str) -> datetime:
38
+ """Parse an ISO datetime; naive values are taken as Europe/Madrid time."""
39
+ dt = datetime.fromisoformat(value)
40
+ if dt.tzinfo is None:
41
+ dt = dt.replace(tzinfo=LOCAL_TZ)
42
+ return dt
35
43
 
36
44
 
37
45
  def build_arg_parser():
@@ -49,8 +57,8 @@ def build_arg_parser():
49
57
  parser.add_argument("--get-historical-generation", action="store_true")
50
58
  parser.add_argument("--get-historical-power-demand", action="store_true")
51
59
  parser.add_argument("--get-in-progress-consumption", action="store_true")
52
- parser.add_argument("--start", type=datetime.fromisoformat)
53
- parser.add_argument("--end", type=datetime.fromisoformat)
60
+ parser.add_argument("--start", type=parse_local_datetime)
61
+ parser.add_argument("--end", type=parse_local_datetime)
54
62
 
55
63
  parser.add_argument(
56
64
  "--check-auth-validity",
@@ -103,7 +111,9 @@ async def amain():
103
111
  if args.get_measure:
104
112
  return await client.get_measure()
105
113
 
106
- now_day = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
114
+ now_day = datetime.now(LOCAL_TZ).replace(
115
+ hour=0, minute=0, second=0, microsecond=0
116
+ )
107
117
  seven_days = timedelta(days=7)
108
118
  start = args.start
109
119
  end = args.end
@@ -144,6 +154,10 @@ async def amain():
144
154
  return 1
145
155
 
146
156
  trace_config = aiohttp.TraceConfig()
157
+ # NOTE: --trace-http-requests is a developer-only debugging tool, NOT meant for
158
+ # production. It deliberately dumps everything on the wire, including sensitive
159
+ # data (login payload with plaintext password, session cookies, personal data in
160
+ # responses). Do not "sanitize" it: inspecting the raw traffic is its purpose.
147
161
  if args.trace_http_requests:
148
162
  trace_config.on_request_start.append(on_request_start)
149
163
  trace_config.on_request_end.append(on_request_end)
@@ -223,6 +237,4 @@ def main():
223
237
 
224
238
 
225
239
  if __name__ == "__main__":
226
- import sys
227
-
228
240
  sys.exit(main())
@@ -52,7 +52,9 @@ from .types import (
52
52
  HistoricalPowerDemand,
53
53
  InProgressConsumption,
54
54
  Measure,
55
+ PeriodValue,
55
56
  )
57
+ from .tz import LOCAL_TZ, as_local
56
58
 
57
59
  LOGGER = logging.getLogger(__name__)
58
60
 
@@ -68,15 +70,34 @@ SESSION_TIMEOUT = 900
68
70
  SESSION_AUTO_REFRESH = True
69
71
 
70
72
  # Define TypeVars to preserve the signature and return type
73
+ C = TypeVar("C", bound="Client")
71
74
  P = ParamSpec("P")
72
75
  R = TypeVar("R")
76
+ _P = TypeVar("_P", bound=PeriodValue)
77
+
78
+
79
+ def _resolve_range(
80
+ start: datetime | None, end: datetime | None
81
+ ) -> tuple[datetime, datetime]:
82
+ """Apply defaults, require aware datetimes and return them in Madrid time."""
83
+ # Validate what the caller passed before deriving defaults from it.
84
+ end = datetime.now(LOCAL_TZ) if end is None else as_local(end, "end")
85
+ start = end - timedelta(days=7) if start is None else as_local(start, "start")
86
+ start, end = sorted((start, end), key=lambda x: x.timestamp())
87
+ return start, end
88
+
89
+
90
+ def _trim_periods(periods: list[_P], start: datetime, end: datetime) -> list[_P]:
91
+ """Keep periods fully inside ``[start, end]``, compared by instant."""
92
+ lo, hi = start.timestamp(), end.timestamp()
93
+ return [x for x in periods if x.start.timestamp() >= lo and x.end.timestamp() <= hi]
73
94
 
74
95
 
75
96
  def auth_required(
76
- fn: Callable[Concatenate[Client, P], Awaitable[R]],
77
- ) -> Callable[Concatenate[Client, P], Awaitable[R]]:
97
+ fn: Callable[Concatenate[C, P], Awaitable[R]],
98
+ ) -> Callable[Concatenate[C, P], Awaitable[R]]:
78
99
  @functools.wraps(fn)
79
- async def _wrap(client: Client, *args, **kwargs):
100
+ async def _wrap(client: C, *args: P.args, **kwargs: P.kwargs) -> R:
80
101
  if client._session_auto_refresh is True and client.is_logged is False:
81
102
  await client.login()
82
103
 
@@ -143,7 +164,7 @@ class Client:
143
164
  self._username = username
144
165
  self._password = password
145
166
  self._contract = contract
146
- self._session_timeout = timedelta(session_timeout.total_seconds() * 0.9)
167
+ self._session_timeout = timedelta(seconds=session_timeout.total_seconds() * 0.9)
147
168
  self._session_auto_refresh = session_auto_refresh
148
169
 
149
170
  self._login_ts: datetime | None = None
@@ -265,14 +286,14 @@ class Client:
265
286
  LOGGER.error(f"{self}: auth failed, invalid data")
266
287
  raise InvalidData(data)
267
288
 
268
- if data.get("success", "false") != "true":
269
- LOGGER.error(f"{self}: auth failed, no success")
270
- raise CommandError(data)
271
-
272
289
  if data.get("success", "") == "userExpired":
273
290
  LOGGER.error(f"{self}: auth failed, user session expired")
274
291
  raise UserExpiredError(data)
275
292
 
293
+ if data.get("success", "false") != "true":
294
+ LOGGER.error(f"{self}: auth failed, no success")
295
+ raise CommandError(data)
296
+
276
297
  self._login_ts = datetime.now()
277
298
  LOGGER.debug(f"{self}: succesfully authenticaded")
278
299
 
@@ -353,17 +374,13 @@ class Client:
353
374
  async def get_historical_consumption(
354
375
  self, start: datetime | None = None, end: datetime | None = None
355
376
  ) -> HistoricalConsumption:
356
- end = end or datetime.now()
357
- start = start or end - timedelta(days=7)
358
-
359
- start = min([start, end])
360
- end = max([start, end])
377
+ start, end = _resolve_range(start, end)
361
378
  url = _CONSUMPTION_PERIOD_ENDPOINT.format(start=start, end=end)
362
379
 
363
380
  data = await self.request_json("GET", url, encoding="iso-8859-1")
364
381
 
365
382
  ret = parsers.parse_historical_consumption(data)
366
- ret.periods = [x for x in ret.periods if x.start >= start and x.end <= end]
383
+ ret.periods = _trim_periods(ret.periods, start, end)
367
384
 
368
385
  LOGGER.debug(f"{self}: historical consumption fetched succesfully")
369
386
 
@@ -376,18 +393,16 @@ class Client:
376
393
  ret = parsers.parse_in_progress_consumption(data)
377
394
  return ret
378
395
 
396
+ @auth_required
379
397
  async def get_historical_generation(
380
398
  self, start: datetime | None = None, end: datetime | None = None
381
399
  ) -> HistoricalGeneration:
382
- end = end or datetime.now()
383
- start = start or end - timedelta(days=7)
384
-
385
- start = min([start, end])
386
- end = max([start, end])
400
+ start, end = _resolve_range(start, end)
387
401
  url = _GENERATION_PERIOD_ENDPOINT.format(start=start, end=end)
388
402
 
389
403
  data = await self.request_json("GET", url, encoding="iso-8859-1")
390
404
  ret = parsers.parse_historical_generation(data)
405
+ ret.periods = _trim_periods(ret.periods, start, end)
391
406
 
392
407
  LOGGER.debug(f"{self}: historical generation fetched succesfully")
393
408
 
@@ -16,18 +16,15 @@
16
16
  # USA.
17
17
 
18
18
 
19
- import logging
20
- import os
21
19
  import random
22
- from collections.abc import Iterator
20
+ from collections.abc import Generator, Iterator
23
21
  from contextlib import contextmanager
24
- from datetime import datetime, timedelta
25
- from pathlib import Path
22
+ from datetime import UTC, datetime, timedelta
26
23
  from typing import Any
27
24
 
28
25
  import aiohttp
29
26
 
30
- from .client import Client, auth_required
27
+ from .client import Client, _resolve_range, auth_required
31
28
  from .types import HistoricalGeneration # noqa: F401
32
29
  from .types import HistoricalPowerDemand # noqa: F401
33
30
  from .types import (
@@ -35,15 +32,7 @@ from .types import (
35
32
  HistoricalConsumption,
36
33
  Measure,
37
34
  )
38
-
39
- LOGGER = logging.getLogger(__name__)
40
-
41
- I_DE_ENERGY_DUMP_DIRECTORY = os.environ.get("I_DE_ENERGY_DUMP_DIRECTORY", "")
42
- I_DE_ENERGY_DUMP = bool(I_DE_ENERGY_DUMP_DIRECTORY)
43
- if I_DE_ENERGY_DUMP:
44
- I_DE_ENERGY_DUMP_BASE_PATH = Path(I_DE_ENERGY_DUMP_DIRECTORY)
45
- else:
46
- I_DE_ENERGY_DUMP_DIRECTORY = None
35
+ from .tz import LOCAL_TZ
47
36
 
48
37
 
49
38
  class MockClient(Client):
@@ -184,16 +173,18 @@ class MockClient(Client):
184
173
 
185
174
  @auth_required
186
175
  async def get_historical_consumption(
187
- self, start: datetime, end: datetime
176
+ self, start: datetime | None = None, end: datetime | None = None
188
177
  ) -> HistoricalConsumption:
189
- start = start.replace(minute=0, second=0)
190
- end = end.replace(minute=0, second=0)
178
+ start, end = _resolve_range(start, end)
179
+ start = start.replace(minute=0, second=0, microsecond=0)
180
+ end = end.replace(minute=0, second=0, microsecond=0)
191
181
 
192
- with preseed_random((start, end)) as rand:
182
+ seed = (int(start.timestamp()), int(end.timestamp()))
183
+ with preseed_random(seed) as rand:
193
184
  periods = [
194
185
  ConsumptionForPeriod(
195
186
  start=dt,
196
- end=dt + timedelta(hours=1),
187
+ end=(dt.astimezone(UTC) + timedelta(hours=1)).astimezone(LOCAL_TZ),
197
188
  value=rand.randint(0, 1000),
198
189
  desglosed={},
199
190
  )
@@ -208,12 +199,18 @@ class MockClient(Client):
208
199
  def datetime_range(
209
200
  start: datetime, end: datetime, step: timedelta
210
201
  ) -> Iterator[datetime]:
211
- curr = start
212
- while curr < end:
213
- yield curr
202
+ """Yield aware datetimes from ``start`` (inclusive) to ``end`` (exclusive).
203
+
204
+ Steps are elapsed time (UTC arithmetic), results are in ``start``'s zone.
205
+ """
206
+ zone = start.tzinfo
207
+ curr = start.astimezone(UTC)
208
+ limit = end.astimezone(UTC)
209
+ while curr < limit:
210
+ yield curr.astimezone(zone)
214
211
  curr = curr + step
215
212
 
216
213
 
217
214
  @contextmanager
218
- def preseed_random(seed) -> Iterator[random.Random]:
215
+ def preseed_random(seed) -> Generator[random.Random]:
219
216
  yield random.Random(repr(seed))