ideenergy 2.0.1.dev2__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.
- ideenergy-3.0.0a1/PKG-INFO +171 -0
- ideenergy-3.0.0a1/README.md +142 -0
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy/__init__.py +3 -1
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy/cli.py +89 -17
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy/client.py +85 -35
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy/endpoints.py +28 -0
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy/mock.py +21 -22
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy/parsers.py +59 -13
- ideenergy-3.0.0a1/ideenergy/types.py +66 -0
- ideenergy-3.0.0a1/ideenergy/tz.py +28 -0
- ideenergy-3.0.0a1/ideenergy.egg-info/PKG-INFO +171 -0
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy.egg-info/SOURCES.txt +3 -1
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy.egg-info/requires.txt +1 -1
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/pyproject.toml +14 -3
- ideenergy-3.0.0a1/tests/test_client.py +316 -0
- ideenergy-3.0.0a1/tests/test_dst.py +165 -0
- ideenergy-2.0.1.dev2/PKG-INFO +0 -36
- ideenergy-2.0.1.dev2/README.md +0 -18
- ideenergy-2.0.1.dev2/ideenergy/types.py +0 -43
- ideenergy-2.0.1.dev2/ideenergy.egg-info/PKG-INFO +0 -36
- ideenergy-2.0.1.dev2/tests/test_client.py +0 -101
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/LICENSE +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy/__main__.py +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy.egg-info/dependency_links.txt +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy.egg-info/entry_points.txt +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-3.0.0a1}/ideenergy.egg-info/top_level.txt +0 -0
- {ideenergy-2.0.1.dev2 → 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
|
+
[](https://pypi.org/project/ideenergy/)
|
|
39
|
+
[](https://pypi.org/project/ideenergy/)
|
|
40
|
+
[](https://github.com/ldotlopez/ideenergy/releases)
|
|
41
|
+
[](https://github.com/ldotlopez/ideenergy/blob/main/LICENSE)
|
|
42
|
+
|
|
43
|
+
<!-- Workflows -->
|
|
44
|
+
|
|
45
|
+
[](https://github.com/ldotlopez/ideenergy/actions/workflows/ci.yml)
|
|
46
|
+
[](https://github.com/ldotlopez/ideenergy/actions/workflows/release.yml)
|
|
47
|
+
|
|
48
|
+
<!-- Sponsors -->
|
|
49
|
+
|
|
50
|
+
[](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
|
+
[](https://pypi.org/project/ideenergy/)
|
|
10
|
+
[](https://pypi.org/project/ideenergy/)
|
|
11
|
+
[](https://github.com/ldotlopez/ideenergy/releases)
|
|
12
|
+
[](https://github.com/ldotlopez/ideenergy/blob/main/LICENSE)
|
|
13
|
+
|
|
14
|
+
<!-- Workflows -->
|
|
15
|
+
|
|
16
|
+
[](https://github.com/ldotlopez/ideenergy/actions/workflows/ci.yml)
|
|
17
|
+
[](https://github.com/ldotlopez/ideenergy/actions/workflows/release.yml)
|
|
18
|
+
|
|
19
|
+
<!-- Sponsors -->
|
|
20
|
+
|
|
21
|
+
[](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)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
1
|
+
# Copyright (C) 2021-2026 Luis López <luis@cuarentaydos.com>
|
|
2
2
|
#
|
|
3
3
|
# This program is free software; you can redistribute it and/or
|
|
4
4
|
# modify it under the terms of the GNU General Public 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",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
|
|
3
|
-
# Copyright (C) 2021-
|
|
3
|
+
# Copyright (C) 2021-2026 Luis López <luis@cuarentaydos.com>
|
|
4
4
|
#
|
|
5
5
|
# This program is free software; you can redistribute it and/or
|
|
6
6
|
# modify it under the terms of the GNU General Public License
|
|
@@ -23,17 +23,23 @@ import logging
|
|
|
23
23
|
import os
|
|
24
24
|
import pprint
|
|
25
25
|
import sys
|
|
26
|
+
import time
|
|
27
|
+
from collections.abc import Generator
|
|
26
28
|
from datetime import datetime, timedelta
|
|
27
29
|
from types import SimpleNamespace
|
|
28
30
|
|
|
29
31
|
import aiohttp
|
|
30
32
|
import dotenv
|
|
31
33
|
|
|
32
|
-
from . import
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
|
37
43
|
|
|
38
44
|
|
|
39
45
|
def build_arg_parser():
|
|
@@ -50,10 +56,48 @@ def build_arg_parser():
|
|
|
50
56
|
parser.add_argument("--get-historical-consumption", action="store_true")
|
|
51
57
|
parser.add_argument("--get-historical-generation", action="store_true")
|
|
52
58
|
parser.add_argument("--get-historical-power-demand", action="store_true")
|
|
59
|
+
parser.add_argument("--get-in-progress-consumption", action="store_true")
|
|
60
|
+
parser.add_argument("--start", type=parse_local_datetime)
|
|
61
|
+
parser.add_argument("--end", type=parse_local_datetime)
|
|
62
|
+
|
|
63
|
+
parser.add_argument(
|
|
64
|
+
"--check-auth-validity",
|
|
65
|
+
action="store_true",
|
|
66
|
+
help="Login and periodically verify how long the auth remains valid",
|
|
67
|
+
)
|
|
53
68
|
|
|
54
69
|
return parser
|
|
55
70
|
|
|
56
71
|
|
|
72
|
+
async def probe_auth_validity(client, logger, sleep=asyncio.sleep) -> int:
|
|
73
|
+
try:
|
|
74
|
+
await client.login()
|
|
75
|
+
except Exception as exc:
|
|
76
|
+
logger.exception(f"{client}: initial auth check failed: {exc}")
|
|
77
|
+
return 1
|
|
78
|
+
|
|
79
|
+
def wait_g() -> Generator[int]:
|
|
80
|
+
yield from (0, 5, 10, 20, 30)
|
|
81
|
+
while True:
|
|
82
|
+
yield 30
|
|
83
|
+
|
|
84
|
+
start = time.monotonic()
|
|
85
|
+
for wait_minutes in wait_g():
|
|
86
|
+
checkpoint = round((time.monotonic() - start) / 60)
|
|
87
|
+
logger.info(f"{client}: waiting {wait_minutes} minutes")
|
|
88
|
+
await sleep(wait_minutes * 60)
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
await client.get_historical_consumption()
|
|
92
|
+
except Exception:
|
|
93
|
+
logger.exception(f"{client}: auth failed after {checkpoint} minutes")
|
|
94
|
+
return 1
|
|
95
|
+
|
|
96
|
+
logger.info(f"{client}: auth valid after {checkpoint} minutes")
|
|
97
|
+
|
|
98
|
+
return 0
|
|
99
|
+
|
|
100
|
+
|
|
57
101
|
async def amain():
|
|
58
102
|
async def get_requested_data():
|
|
59
103
|
if args.list_contracts:
|
|
@@ -67,8 +111,19 @@ async def amain():
|
|
|
67
111
|
if args.get_measure:
|
|
68
112
|
return await client.get_measure()
|
|
69
113
|
|
|
70
|
-
|
|
71
|
-
|
|
114
|
+
now_day = datetime.now(LOCAL_TZ).replace(
|
|
115
|
+
hour=0, minute=0, second=0, microsecond=0
|
|
116
|
+
)
|
|
117
|
+
seven_days = timedelta(days=7)
|
|
118
|
+
start = args.start
|
|
119
|
+
end = args.end
|
|
120
|
+
if not end:
|
|
121
|
+
if start:
|
|
122
|
+
end = min(now_day, start + seven_days)
|
|
123
|
+
else:
|
|
124
|
+
end = now_day
|
|
125
|
+
if not start:
|
|
126
|
+
start = end - seven_days
|
|
72
127
|
|
|
73
128
|
if args.get_historical_consumption:
|
|
74
129
|
return await client.get_historical_consumption(start, end)
|
|
@@ -79,6 +134,9 @@ async def amain():
|
|
|
79
134
|
if args.get_historical_power_demand:
|
|
80
135
|
return await client.get_historical_power_demand()
|
|
81
136
|
|
|
137
|
+
if args.get_in_progress_consumption:
|
|
138
|
+
return await client.get_in_progress_consumption()
|
|
139
|
+
|
|
82
140
|
logging.basicConfig(
|
|
83
141
|
format="%(asctime)s.%(msecs)03d %(levelname)s %(module)s %(message)s",
|
|
84
142
|
datefmt="%Y-%m-%d %H:%M:%S",
|
|
@@ -93,9 +151,13 @@ async def amain():
|
|
|
93
151
|
|
|
94
152
|
if not username or not password:
|
|
95
153
|
print("Missing username or password", file=sys.stderr)
|
|
96
|
-
|
|
154
|
+
return 1
|
|
97
155
|
|
|
98
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.
|
|
99
161
|
if args.trace_http_requests:
|
|
100
162
|
trace_config.on_request_start.append(on_request_start)
|
|
101
163
|
trace_config.on_request_end.append(on_request_end)
|
|
@@ -107,27 +169,39 @@ async def amain():
|
|
|
107
169
|
or args.get_historical_consumption
|
|
108
170
|
or args.get_historical_generation
|
|
109
171
|
or args.get_historical_power_demand
|
|
172
|
+
or args.get_in_progress_consumption
|
|
173
|
+
or args.check_auth_validity
|
|
110
174
|
):
|
|
111
175
|
parser.print_help()
|
|
112
|
-
|
|
176
|
+
return 1
|
|
113
177
|
|
|
114
178
|
async with aiohttp.ClientSession(trace_configs=[trace_config]) as session:
|
|
115
179
|
client = Client(
|
|
116
|
-
username=username,
|
|
180
|
+
username=username,
|
|
181
|
+
password=password,
|
|
182
|
+
session=session,
|
|
183
|
+
logger=logger,
|
|
184
|
+
session_auto_refresh=not args.check_auth_validity,
|
|
117
185
|
)
|
|
186
|
+
|
|
187
|
+
if args.check_auth_validity:
|
|
188
|
+
return await probe_auth_validity(client, logger)
|
|
189
|
+
|
|
118
190
|
try:
|
|
119
191
|
if data := await get_requested_data():
|
|
120
192
|
print(pprint.pformat(data))
|
|
193
|
+
return 0
|
|
194
|
+
else:
|
|
195
|
+
print("Got empty response", file=sys.stderr)
|
|
196
|
+
return 1
|
|
121
197
|
|
|
122
198
|
except RequestFailedError as e:
|
|
123
199
|
print(f"Request failed: {e}", file=sys.stderr)
|
|
124
|
-
|
|
125
|
-
sys.exit(1)
|
|
200
|
+
return 1
|
|
126
201
|
|
|
127
202
|
except UserExpiredError as e:
|
|
128
203
|
print(f"User expired, renew auth code via web: {e}", file=sys.stderr)
|
|
129
|
-
|
|
130
|
-
sys.exit(1)
|
|
204
|
+
return 1
|
|
131
205
|
|
|
132
206
|
|
|
133
207
|
async def on_request_start(
|
|
@@ -163,6 +237,4 @@ def main():
|
|
|
163
237
|
|
|
164
238
|
|
|
165
239
|
if __name__ == "__main__":
|
|
166
|
-
import sys
|
|
167
|
-
|
|
168
240
|
sys.exit(main())
|