ideenergy 2.0.1.dev2__tar.gz → 2.0.1.dev3__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-2.0.1.dev2 → ideenergy-2.0.1.dev3}/PKG-INFO +1 -1
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy/__init__.py +1 -1
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy/cli.py +75 -15
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy/client.py +63 -28
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy/endpoints.py +28 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy/mock.py +2 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy/parsers.py +20 -1
- ideenergy-2.0.1.dev3/ideenergy/types.py +66 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/PKG-INFO +1 -1
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/pyproject.toml +1 -1
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/tests/test_client.py +79 -10
- ideenergy-2.0.1.dev2/ideenergy/types.py +0 -43
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/LICENSE +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/README.md +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy/__main__.py +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/SOURCES.txt +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/dependency_links.txt +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/entry_points.txt +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/requires.txt +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/top_level.txt +0 -0
- {ideenergy-2.0.1.dev2 → ideenergy-2.0.1.dev3}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ideenergy
|
|
3
|
-
Version: 2.0.1.
|
|
3
|
+
Version: 2.0.1.dev3
|
|
4
4
|
Summary: Programmatic access to consumer energy consumption from https://www.i-de.es/ (Spanish energy distributor)
|
|
5
5
|
Author-email: Luis López <luis@cuarentaydos.com>
|
|
6
6
|
Project-URL: Homepage, https://github.com/ldotlopez/ideenergy
|
|
@@ -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,15 @@ 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
|
-
Client,
|
|
34
|
-
RequestFailedError,
|
|
35
|
-
UserExpiredError,
|
|
36
|
-
)
|
|
34
|
+
from . import Client, RequestFailedError, UserExpiredError
|
|
37
35
|
|
|
38
36
|
|
|
39
37
|
def build_arg_parser():
|
|
@@ -50,10 +48,48 @@ def build_arg_parser():
|
|
|
50
48
|
parser.add_argument("--get-historical-consumption", action="store_true")
|
|
51
49
|
parser.add_argument("--get-historical-generation", action="store_true")
|
|
52
50
|
parser.add_argument("--get-historical-power-demand", action="store_true")
|
|
51
|
+
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)
|
|
54
|
+
|
|
55
|
+
parser.add_argument(
|
|
56
|
+
"--check-auth-validity",
|
|
57
|
+
action="store_true",
|
|
58
|
+
help="Login and periodically verify how long the auth remains valid",
|
|
59
|
+
)
|
|
53
60
|
|
|
54
61
|
return parser
|
|
55
62
|
|
|
56
63
|
|
|
64
|
+
async def probe_auth_validity(client, logger, sleep=asyncio.sleep) -> int:
|
|
65
|
+
try:
|
|
66
|
+
await client.login()
|
|
67
|
+
except Exception as exc:
|
|
68
|
+
logger.exception(f"{client}: initial auth check failed: {exc}")
|
|
69
|
+
return 1
|
|
70
|
+
|
|
71
|
+
def wait_g() -> Generator[int]:
|
|
72
|
+
yield from (0, 5, 10, 20, 30)
|
|
73
|
+
while True:
|
|
74
|
+
yield 30
|
|
75
|
+
|
|
76
|
+
start = time.monotonic()
|
|
77
|
+
for wait_minutes in wait_g():
|
|
78
|
+
checkpoint = round((time.monotonic() - start) / 60)
|
|
79
|
+
logger.info(f"{client}: waiting {wait_minutes} minutes")
|
|
80
|
+
await sleep(wait_minutes * 60)
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
await client.get_historical_consumption()
|
|
84
|
+
except Exception:
|
|
85
|
+
logger.exception(f"{client}: auth failed after {checkpoint} minutes")
|
|
86
|
+
return 1
|
|
87
|
+
|
|
88
|
+
logger.info(f"{client}: auth valid after {checkpoint} minutes")
|
|
89
|
+
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
|
|
57
93
|
async def amain():
|
|
58
94
|
async def get_requested_data():
|
|
59
95
|
if args.list_contracts:
|
|
@@ -67,8 +103,17 @@ async def amain():
|
|
|
67
103
|
if args.get_measure:
|
|
68
104
|
return await client.get_measure()
|
|
69
105
|
|
|
70
|
-
|
|
71
|
-
|
|
106
|
+
now_day = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
|
|
107
|
+
seven_days = timedelta(days=7)
|
|
108
|
+
start = args.start
|
|
109
|
+
end = args.end
|
|
110
|
+
if not end:
|
|
111
|
+
if start:
|
|
112
|
+
end = min(now_day, start + seven_days)
|
|
113
|
+
else:
|
|
114
|
+
end = now_day
|
|
115
|
+
if not start:
|
|
116
|
+
start = end - seven_days
|
|
72
117
|
|
|
73
118
|
if args.get_historical_consumption:
|
|
74
119
|
return await client.get_historical_consumption(start, end)
|
|
@@ -79,6 +124,9 @@ async def amain():
|
|
|
79
124
|
if args.get_historical_power_demand:
|
|
80
125
|
return await client.get_historical_power_demand()
|
|
81
126
|
|
|
127
|
+
if args.get_in_progress_consumption:
|
|
128
|
+
return await client.get_in_progress_consumption()
|
|
129
|
+
|
|
82
130
|
logging.basicConfig(
|
|
83
131
|
format="%(asctime)s.%(msecs)03d %(levelname)s %(module)s %(message)s",
|
|
84
132
|
datefmt="%Y-%m-%d %H:%M:%S",
|
|
@@ -93,7 +141,7 @@ async def amain():
|
|
|
93
141
|
|
|
94
142
|
if not username or not password:
|
|
95
143
|
print("Missing username or password", file=sys.stderr)
|
|
96
|
-
|
|
144
|
+
return 1
|
|
97
145
|
|
|
98
146
|
trace_config = aiohttp.TraceConfig()
|
|
99
147
|
if args.trace_http_requests:
|
|
@@ -107,27 +155,39 @@ async def amain():
|
|
|
107
155
|
or args.get_historical_consumption
|
|
108
156
|
or args.get_historical_generation
|
|
109
157
|
or args.get_historical_power_demand
|
|
158
|
+
or args.get_in_progress_consumption
|
|
159
|
+
or args.check_auth_validity
|
|
110
160
|
):
|
|
111
161
|
parser.print_help()
|
|
112
|
-
|
|
162
|
+
return 1
|
|
113
163
|
|
|
114
164
|
async with aiohttp.ClientSession(trace_configs=[trace_config]) as session:
|
|
115
165
|
client = Client(
|
|
116
|
-
username=username,
|
|
166
|
+
username=username,
|
|
167
|
+
password=password,
|
|
168
|
+
session=session,
|
|
169
|
+
logger=logger,
|
|
170
|
+
session_auto_refresh=not args.check_auth_validity,
|
|
117
171
|
)
|
|
172
|
+
|
|
173
|
+
if args.check_auth_validity:
|
|
174
|
+
return await probe_auth_validity(client, logger)
|
|
175
|
+
|
|
118
176
|
try:
|
|
119
177
|
if data := await get_requested_data():
|
|
120
178
|
print(pprint.pformat(data))
|
|
179
|
+
return 0
|
|
180
|
+
else:
|
|
181
|
+
print("Got empty response", file=sys.stderr)
|
|
182
|
+
return 1
|
|
121
183
|
|
|
122
184
|
except RequestFailedError as e:
|
|
123
185
|
print(f"Request failed: {e}", file=sys.stderr)
|
|
124
|
-
|
|
125
|
-
sys.exit(1)
|
|
186
|
+
return 1
|
|
126
187
|
|
|
127
188
|
except UserExpiredError as e:
|
|
128
189
|
print(f"User expired, renew auth code via web: {e}", file=sys.stderr)
|
|
129
|
-
|
|
130
|
-
sys.exit(1)
|
|
190
|
+
return 1
|
|
131
191
|
|
|
132
192
|
|
|
133
193
|
async def on_request_start(
|
|
@@ -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
|
|
@@ -15,21 +15,24 @@
|
|
|
15
15
|
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
|
|
16
16
|
# USA.
|
|
17
17
|
|
|
18
|
+
from __future__ import annotations
|
|
18
19
|
|
|
19
20
|
import functools
|
|
20
21
|
import json
|
|
21
22
|
import logging
|
|
22
23
|
import os
|
|
23
24
|
import re
|
|
25
|
+
from collections.abc import Awaitable, Callable
|
|
24
26
|
from datetime import datetime, timedelta
|
|
25
27
|
from pathlib import Path
|
|
26
|
-
from typing import Any
|
|
28
|
+
from typing import Any, Concatenate, ParamSpec, TypeVar
|
|
27
29
|
|
|
28
30
|
import aiohttp
|
|
29
31
|
|
|
30
32
|
from . import parsers
|
|
31
33
|
from .endpoints import (
|
|
32
34
|
_BASE_URL,
|
|
35
|
+
_CONSUMPTION_IN_PROGRESS_ENDPOINT,
|
|
33
36
|
_CONSUMPTION_PERIOD_ENDPOINT,
|
|
34
37
|
_CONTRACT_DETAILS_ENDPOINT,
|
|
35
38
|
_CONTRACT_SELECTION_ENDPOINT,
|
|
@@ -47,6 +50,7 @@ from .types import (
|
|
|
47
50
|
HistoricalConsumption,
|
|
48
51
|
HistoricalGeneration,
|
|
49
52
|
HistoricalPowerDemand,
|
|
53
|
+
InProgressConsumption,
|
|
50
54
|
Measure,
|
|
51
55
|
)
|
|
52
56
|
|
|
@@ -60,12 +64,23 @@ else:
|
|
|
60
64
|
I_DE_ENERGY_DUMP_DIRECTORY = None
|
|
61
65
|
|
|
62
66
|
|
|
63
|
-
|
|
67
|
+
SESSION_TIMEOUT = 900
|
|
68
|
+
SESSION_AUTO_REFRESH = True
|
|
69
|
+
|
|
70
|
+
# Define TypeVars to preserve the signature and return type
|
|
71
|
+
P = ParamSpec("P")
|
|
72
|
+
R = TypeVar("R")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def auth_required(
|
|
76
|
+
fn: Callable[Concatenate[Client, P], Awaitable[R]],
|
|
77
|
+
) -> Callable[Concatenate[Client, P], Awaitable[R]]:
|
|
64
78
|
@functools.wraps(fn)
|
|
65
|
-
async def _wrap(client, *args, **kwargs):
|
|
66
|
-
if client.
|
|
79
|
+
async def _wrap(client: Client, *args, **kwargs):
|
|
80
|
+
if client._session_auto_refresh is True and client.is_logged is False:
|
|
67
81
|
await client.login()
|
|
68
82
|
|
|
83
|
+
# await client.renew_session()
|
|
69
84
|
return await fn(client, *args, **kwargs)
|
|
70
85
|
|
|
71
86
|
return _wrap
|
|
@@ -118,23 +133,23 @@ class Client:
|
|
|
118
133
|
password: str,
|
|
119
134
|
contract: str | None = None,
|
|
120
135
|
logger: logging.Logger | None = None,
|
|
121
|
-
|
|
122
|
-
|
|
136
|
+
session_timeout: timedelta | int = SESSION_TIMEOUT,
|
|
137
|
+
session_auto_refresh: bool = SESSION_AUTO_REFRESH,
|
|
123
138
|
) -> None:
|
|
124
|
-
if not isinstance(
|
|
125
|
-
|
|
139
|
+
if not isinstance(session_timeout, timedelta):
|
|
140
|
+
session_timeout = timedelta(seconds=session_timeout)
|
|
126
141
|
|
|
127
142
|
self._sess = session
|
|
128
143
|
self._username = username
|
|
129
144
|
self._password = password
|
|
130
145
|
self._contract = contract
|
|
131
|
-
self.
|
|
132
|
-
self.
|
|
146
|
+
self._session_timeout = timedelta(session_timeout.total_seconds() * 0.9)
|
|
147
|
+
self._session_auto_refresh = session_auto_refresh
|
|
133
148
|
|
|
134
149
|
self._login_ts: datetime | None = None
|
|
135
150
|
|
|
136
151
|
def __str__(self) -> str:
|
|
137
|
-
return f"{self.username}" + ("/{self.contract}" if self.contract else "")
|
|
152
|
+
return f"{self.username}" + (f"/{self.contract}" if self.contract else "")
|
|
138
153
|
|
|
139
154
|
def __repr__(self) -> str:
|
|
140
155
|
return (
|
|
@@ -165,15 +180,15 @@ class Client:
|
|
|
165
180
|
return False
|
|
166
181
|
|
|
167
182
|
delta = datetime.now() - self._login_ts
|
|
168
|
-
return delta < self.
|
|
183
|
+
return delta < self.session_timeout
|
|
169
184
|
|
|
170
185
|
@property
|
|
171
|
-
def
|
|
172
|
-
return self.
|
|
186
|
+
def session_timeout(self) -> timedelta:
|
|
187
|
+
return self._session_timeout
|
|
173
188
|
|
|
174
189
|
@property
|
|
175
|
-
def
|
|
176
|
-
return self.
|
|
190
|
+
def session_auto_refresh(self) -> bool:
|
|
191
|
+
return self._session_auto_refresh
|
|
177
192
|
|
|
178
193
|
#
|
|
179
194
|
# Requests
|
|
@@ -247,15 +262,15 @@ class Client:
|
|
|
247
262
|
data = await self.request_json("POST", _LOGIN_ENDPOINT, json=payload)
|
|
248
263
|
|
|
249
264
|
if not isinstance(data, dict):
|
|
250
|
-
LOGGER.
|
|
265
|
+
LOGGER.error(f"{self}: auth failed, invalid data")
|
|
251
266
|
raise InvalidData(data)
|
|
252
267
|
|
|
253
268
|
if data.get("success", "false") != "true":
|
|
254
|
-
LOGGER.
|
|
269
|
+
LOGGER.error(f"{self}: auth failed, no success")
|
|
255
270
|
raise CommandError(data)
|
|
256
271
|
|
|
257
272
|
if data.get("success", "") == "userExpired":
|
|
258
|
-
LOGGER.
|
|
273
|
+
LOGGER.error(f"{self}: auth failed, user session expired")
|
|
259
274
|
raise UserExpiredError(data)
|
|
260
275
|
|
|
261
276
|
self._login_ts = datetime.now()
|
|
@@ -288,7 +303,7 @@ class Client:
|
|
|
288
303
|
async def get_contract_details(self) -> dict[str, Any]:
|
|
289
304
|
data = await self.request_json("GET", _CONTRACT_DETAILS_ENDPOINT)
|
|
290
305
|
if not data.get("codContrato", False):
|
|
291
|
-
LOGGER.
|
|
306
|
+
LOGGER.error(f"{self}: contract details fetch failed")
|
|
292
307
|
raise InvalidData(data)
|
|
293
308
|
|
|
294
309
|
LOGGER.debug(f"{self}: contract details fetched")
|
|
@@ -299,7 +314,7 @@ class Client:
|
|
|
299
314
|
data = await self.request_json("GET", _CONTRACTS_ENDPOINT)
|
|
300
315
|
|
|
301
316
|
if not data.get("success", False):
|
|
302
|
-
LOGGER.
|
|
317
|
+
LOGGER.error(f"{self}: contract list fetch failed")
|
|
303
318
|
raise CommandError(data)
|
|
304
319
|
|
|
305
320
|
LOGGER.debug(f"{self}: contract list fetched")
|
|
@@ -311,7 +326,7 @@ class Client:
|
|
|
311
326
|
"GET", _CONTRACT_SELECTION_ENDPOINT + contract_id
|
|
312
327
|
)
|
|
313
328
|
if not data.get("success", False):
|
|
314
|
-
LOGGER.
|
|
329
|
+
LOGGER.error(f"{self}: contract select failed")
|
|
315
330
|
raise InvalidContractError(contract_id)
|
|
316
331
|
|
|
317
332
|
LOGGER.debug(f"{self}: contract '{contract_id}' selected")
|
|
@@ -323,7 +338,7 @@ class Client:
|
|
|
323
338
|
data = await self.request_json("GET", _MEASURE_ENDPOINT)
|
|
324
339
|
|
|
325
340
|
if not data.get("codSolicitudTGT"):
|
|
326
|
-
LOGGER.
|
|
341
|
+
LOGGER.error(f"{self}: measure request failed")
|
|
327
342
|
raise CommandError(data)
|
|
328
343
|
|
|
329
344
|
ret = Measure(
|
|
@@ -336,8 +351,11 @@ class Client:
|
|
|
336
351
|
|
|
337
352
|
@auth_required
|
|
338
353
|
async def get_historical_consumption(
|
|
339
|
-
self, start: datetime, end: datetime
|
|
354
|
+
self, start: datetime | None = None, end: datetime | None = None
|
|
340
355
|
) -> HistoricalConsumption:
|
|
356
|
+
end = end or datetime.now()
|
|
357
|
+
start = start or end - timedelta(days=7)
|
|
358
|
+
|
|
341
359
|
start = min([start, end])
|
|
342
360
|
end = max([start, end])
|
|
343
361
|
url = _CONSUMPTION_PERIOD_ENDPOINT.format(start=start, end=end)
|
|
@@ -345,15 +363,25 @@ class Client:
|
|
|
345
363
|
data = await self.request_json("GET", url, encoding="iso-8859-1")
|
|
346
364
|
|
|
347
365
|
ret = parsers.parse_historical_consumption(data)
|
|
348
|
-
ret.periods = [x for x in ret.periods if x.start >= start and x.end
|
|
366
|
+
ret.periods = [x for x in ret.periods if x.start >= start and x.end <= end]
|
|
349
367
|
|
|
350
368
|
LOGGER.debug(f"{self}: historical consumption fetched succesfully")
|
|
351
369
|
|
|
352
370
|
return ret
|
|
353
371
|
|
|
372
|
+
@auth_required
|
|
373
|
+
async def get_in_progress_consumption(self) -> InProgressConsumption:
|
|
374
|
+
LOGGER.info(f"{self}: requesting data to the ICP, may take up to a minute.")
|
|
375
|
+
data = await self.request_json("GET", _CONSUMPTION_IN_PROGRESS_ENDPOINT)
|
|
376
|
+
ret = parsers.parse_in_progress_consumption(data)
|
|
377
|
+
return ret
|
|
378
|
+
|
|
354
379
|
async def get_historical_generation(
|
|
355
|
-
self, start: datetime, end: datetime
|
|
380
|
+
self, start: datetime | None = None, end: datetime | None = None
|
|
356
381
|
) -> HistoricalGeneration:
|
|
382
|
+
end = end or datetime.now()
|
|
383
|
+
start = start or end - timedelta(days=7)
|
|
384
|
+
|
|
357
385
|
start = min([start, end])
|
|
358
386
|
end = max([start, end])
|
|
359
387
|
url = _GENERATION_PERIOD_ENDPOINT.format(start=start, end=end)
|
|
@@ -395,8 +423,15 @@ class Client:
|
|
|
395
423
|
if limits.get("resultado") != "correcto":
|
|
396
424
|
raise CommandError(limits)
|
|
397
425
|
|
|
426
|
+
# range can't be wider than a year
|
|
427
|
+
limits["fecMin"] = (
|
|
428
|
+
datetime.strptime(limits["fecMax"], "%d-%m-%Y%H:%M:%S")
|
|
429
|
+
- timedelta(days=365)
|
|
430
|
+
).strftime("%d-%m-%Y%H:%M:%S")
|
|
431
|
+
|
|
398
432
|
url = _POWER_DEMAND_PERIOD_ENDPOINT.format(**limits)
|
|
399
433
|
data = await self.request_json("GET", url)
|
|
434
|
+
|
|
400
435
|
ret = parsers.parse_historical_power_demand_data(data)
|
|
401
436
|
|
|
402
437
|
LOGGER.debug(f"{self}: historical power demand fetched succesfully")
|
|
@@ -414,7 +449,7 @@ class RequestFailedError(ClientError):
|
|
|
414
449
|
|
|
415
450
|
def __str__(self):
|
|
416
451
|
return (
|
|
417
|
-
f"Invalid response for '{self.response.
|
|
452
|
+
f"Invalid response for '{self.response.url}': "
|
|
418
453
|
f"{self.response.status} - {self.response.reason}"
|
|
419
454
|
)
|
|
420
455
|
|
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
# Copyright (C) 2021-2026 Luis López <luis@cuarentaydos.com>
|
|
2
|
+
#
|
|
3
|
+
# This program is free software; you can redistribute it and/or
|
|
4
|
+
# modify it under the terms of the GNU General Public License
|
|
5
|
+
# as published by the Free Software Foundation; either version 2
|
|
6
|
+
# of the License, or (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This program is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU General Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU General Public License
|
|
14
|
+
# along with this program; if not, write to the Free Software
|
|
15
|
+
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
|
|
16
|
+
# USA.
|
|
17
|
+
|
|
18
|
+
|
|
1
19
|
_BASE_URL = "https://www.i-de.es"
|
|
2
20
|
_REST_BASE_URL = f"{_BASE_URL}/consumidores/rest"
|
|
3
21
|
|
|
@@ -146,6 +164,16 @@ _CONSUMPTION_PERIOD_ENDPOINT = (
|
|
|
146
164
|
"horas/USU/"
|
|
147
165
|
)
|
|
148
166
|
|
|
167
|
+
# Endpoint used to get todays consumption
|
|
168
|
+
# {
|
|
169
|
+
# "consumos": [ 4, 5, 4 ],
|
|
170
|
+
# "generacion": [ 0, 0, 0 ],
|
|
171
|
+
# "fechas": [ "2025-08-11 01", "2025-08-11 02", "2025-08-11 03" ]
|
|
172
|
+
# }
|
|
173
|
+
_CONSUMPTION_IN_PROGRESS_ENDPOINT = (
|
|
174
|
+
f"{_REST_BASE_URL}/consumoNew/obtenerConsumoEnCurso/"
|
|
175
|
+
)
|
|
176
|
+
|
|
149
177
|
## Endpoint used to get limits on the power demand query
|
|
150
178
|
# {
|
|
151
179
|
# 'resultado': 'correcto',
|
|
@@ -186,6 +186,8 @@ class MockClient(Client):
|
|
|
186
186
|
async def get_historical_consumption(
|
|
187
187
|
self, start: datetime, end: datetime
|
|
188
188
|
) -> HistoricalConsumption:
|
|
189
|
+
start = start.replace(minute=0, second=0)
|
|
190
|
+
end = end.replace(minute=0, second=0)
|
|
189
191
|
|
|
190
192
|
with preseed_random((start, end)) as rand:
|
|
191
193
|
periods = [
|
|
@@ -20,8 +20,10 @@ import itertools
|
|
|
20
20
|
from datetime import datetime, timedelta
|
|
21
21
|
from typing import Any
|
|
22
22
|
|
|
23
|
+
from . import client
|
|
23
24
|
from .types import (
|
|
24
25
|
ConsumptionForPeriod,
|
|
26
|
+
InProgressConsumption,
|
|
25
27
|
DemandAtInstant,
|
|
26
28
|
HistoricalConsumption,
|
|
27
29
|
HistoricalGeneration,
|
|
@@ -29,7 +31,6 @@ from .types import (
|
|
|
29
31
|
PeriodValue,
|
|
30
32
|
)
|
|
31
33
|
|
|
32
|
-
|
|
33
34
|
def parser_generic_historical_data(data, base_dt: datetime) -> dict[str, Any]:
|
|
34
35
|
def _normalize(idx: int, item: dict | None) -> PeriodValue | None:
|
|
35
36
|
if item is None:
|
|
@@ -85,6 +86,24 @@ def parse_historical_consumption(data) -> HistoricalConsumption:
|
|
|
85
86
|
|
|
86
87
|
return ret
|
|
87
88
|
|
|
89
|
+
def parse_in_progress_consumption(data) -> InProgressConsumption:
|
|
90
|
+
ret = InProgressConsumption()
|
|
91
|
+
periods = ret.periods
|
|
92
|
+
onehour = timedelta(hours=1)
|
|
93
|
+
fechas = data.get('fechas')
|
|
94
|
+
consumos = data.get('consumos')
|
|
95
|
+
if not (fechas and consumos):
|
|
96
|
+
if fechas or consumos:
|
|
97
|
+
raise client.InvalidData(data)
|
|
98
|
+
else:
|
|
99
|
+
# between 00:00 and 01:00: {'mensaje': 'No existen datos disponibles'}
|
|
100
|
+
return ret
|
|
101
|
+
for endstr, value in zip(data["fechas"], data["consumos"]):
|
|
102
|
+
end = datetime.strptime(endstr, '%Y-%m-%d %H')
|
|
103
|
+
periods.append(
|
|
104
|
+
PeriodValue(start=end-onehour, end=end, value=value)
|
|
105
|
+
)
|
|
106
|
+
return ret
|
|
88
107
|
|
|
89
108
|
def parse_historical_generation(data) -> HistoricalGeneration:
|
|
90
109
|
start = datetime.strptime(data["fechaPeriodo"], "%d-%m-%Y%H:%M:%S").replace(
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Copyright (C) 2021-2026 Luis López <luis@cuarentaydos.com>
|
|
2
|
+
#
|
|
3
|
+
# This program is free software; you can redistribute it and/or
|
|
4
|
+
# modify it under the terms of the GNU General Public License
|
|
5
|
+
# as published by the Free Software Foundation; either version 2
|
|
6
|
+
# of the License, or (at your option) any later version.
|
|
7
|
+
#
|
|
8
|
+
# This program is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU General Public License for more details.
|
|
12
|
+
#
|
|
13
|
+
# You should have received a copy of the GNU General Public License
|
|
14
|
+
# along with this program; if not, write to the Free Software
|
|
15
|
+
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
|
|
16
|
+
# USA.
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from datetime import datetime
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Measure:
|
|
25
|
+
accumulate: int
|
|
26
|
+
instant: float
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class PeriodValue:
|
|
31
|
+
start: datetime
|
|
32
|
+
end: datetime
|
|
33
|
+
value: float
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class ConsumptionForPeriod(PeriodValue):
|
|
38
|
+
desglosed: dict[str, float] = field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class HistoricalConsumption:
|
|
43
|
+
periods: list[ConsumptionForPeriod] = field(default_factory=list)
|
|
44
|
+
total: float = 0
|
|
45
|
+
desglosed: dict[str, float] = field(default_factory=dict)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class InProgressConsumption:
|
|
50
|
+
periods: list[PeriodValue] = field(default_factory=list)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class HistoricalGeneration:
|
|
55
|
+
periods: list[PeriodValue] = field(default_factory=list)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class DemandAtInstant:
|
|
60
|
+
dt: datetime
|
|
61
|
+
value: float
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class HistoricalPowerDemand:
|
|
66
|
+
demands: list[DemandAtInstant] = field(default_factory=list)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ideenergy
|
|
3
|
-
Version: 2.0.1.
|
|
3
|
+
Version: 2.0.1.dev3
|
|
4
4
|
Summary: Programmatic access to consumer energy consumption from https://www.i-de.es/ (Spanish energy distributor)
|
|
5
5
|
Author-email: Luis López <luis@cuarentaydos.com>
|
|
6
6
|
Project-URL: Homepage, https://github.com/ldotlopez/ideenergy
|
|
@@ -18,12 +18,16 @@
|
|
|
18
18
|
# USA.
|
|
19
19
|
|
|
20
20
|
|
|
21
|
+
import asyncio
|
|
21
22
|
import os
|
|
22
23
|
import unittest
|
|
23
24
|
from datetime import datetime, timedelta
|
|
24
|
-
from unittest.mock import AsyncMock, patch
|
|
25
|
+
from unittest.mock import AsyncMock, Mock, patch
|
|
25
26
|
|
|
26
|
-
|
|
27
|
+
import aiohttp
|
|
28
|
+
|
|
29
|
+
from ideenergy import Client, MockClient
|
|
30
|
+
from ideenergy.cli import probe_auth_validity
|
|
27
31
|
from ideenergy.client import _LOGIN_ENDPOINT
|
|
28
32
|
|
|
29
33
|
FIXTURES_DIR = os.path.dirname(__file__) + "/fixtures"
|
|
@@ -36,14 +40,10 @@ def read_fixture(fixture_name: str):
|
|
|
36
40
|
|
|
37
41
|
class TestClient(unittest.IsolatedAsyncioTestCase):
|
|
38
42
|
async def asyncSetUp(self):
|
|
39
|
-
self.sess = await get_session()
|
|
40
43
|
self.client = Client(None, "x", "y")
|
|
41
44
|
self.end = datetime.now().replace(hour=0, minute=0, second=0)
|
|
42
45
|
self.start = self.end - timedelta(days=7)
|
|
43
46
|
|
|
44
|
-
async def asyncTearDown(self):
|
|
45
|
-
await self.sess.close()
|
|
46
|
-
|
|
47
47
|
async def test_login_ok(self):
|
|
48
48
|
with patch(
|
|
49
49
|
"ideenergy.Client.request_bytes",
|
|
@@ -52,10 +52,9 @@ class TestClient(unittest.IsolatedAsyncioTestCase):
|
|
|
52
52
|
) as fn:
|
|
53
53
|
await self.client.login()
|
|
54
54
|
|
|
55
|
-
fn.
|
|
56
|
-
|
|
57
|
-
args,
|
|
58
|
-
self.assertEqual(args, ("POST", _LOGIN_ENDPOINT))
|
|
55
|
+
self.assertEqual(fn.await_count, 2)
|
|
56
|
+
self.assertEqual(fn.await_args_list[0].args, ("GET", "https://www.i-de.es"))
|
|
57
|
+
self.assertEqual(fn.await_args_list[1].args, ("POST", _LOGIN_ENDPOINT))
|
|
59
58
|
|
|
60
59
|
@patch("ideenergy.Client.is_logged", return_value=True)
|
|
61
60
|
async def test_historical_consumption(self, _):
|
|
@@ -97,5 +96,75 @@ class TestClient(unittest.IsolatedAsyncioTestCase):
|
|
|
97
96
|
self.assertEqual(ret.demands[25].value, 2816.0)
|
|
98
97
|
|
|
99
98
|
|
|
99
|
+
class TestMockClient(unittest.IsolatedAsyncioTestCase):
|
|
100
|
+
async def test_login_sets_contract_and_session(self):
|
|
101
|
+
client = MockClient(None, "x", "y", contract="123456789")
|
|
102
|
+
|
|
103
|
+
await client.login()
|
|
104
|
+
|
|
105
|
+
self.assertTrue(client.is_logged)
|
|
106
|
+
self.assertEqual(client.contract, "123456789")
|
|
107
|
+
|
|
108
|
+
async def test_historical_consumption_is_deterministic(self):
|
|
109
|
+
client = MockClient(None, "x", "y")
|
|
110
|
+
start = datetime(2026, 1, 1)
|
|
111
|
+
end = start + timedelta(days=1)
|
|
112
|
+
|
|
113
|
+
ret = await client.get_historical_consumption(start, end)
|
|
114
|
+
|
|
115
|
+
self.assertEqual(len(ret.periods), 24)
|
|
116
|
+
self.assertEqual(ret.periods[0].start, start)
|
|
117
|
+
self.assertEqual(ret.periods[-1].end, end)
|
|
118
|
+
self.assertEqual(ret.total, sum(period.value for period in ret.periods))
|
|
119
|
+
|
|
120
|
+
async def test_concurrent_clients_do_not_share_state(self):
|
|
121
|
+
client1 = MockClient(None, "x", "y", contract="111")
|
|
122
|
+
client2 = MockClient(None, "x", "y", contract="222")
|
|
123
|
+
|
|
124
|
+
await asyncio.gather(client1.login(), client2.login())
|
|
125
|
+
details1, details2 = await asyncio.gather(
|
|
126
|
+
client1.get_contract_details(), client2.get_contract_details()
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
self.assertEqual(client1.contract, "111")
|
|
130
|
+
self.assertEqual(client2.contract, "222")
|
|
131
|
+
self.assertEqual(details1["codContrato"], 123456789.0)
|
|
132
|
+
self.assertEqual(details2["codContrato"], 123456789.0)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class TestAuthValidityProbe(unittest.IsolatedAsyncioTestCase):
|
|
136
|
+
async def test_probe_stops_on_failure(self):
|
|
137
|
+
class FakeClient:
|
|
138
|
+
def __init__(self):
|
|
139
|
+
self.login_calls = 0
|
|
140
|
+
self.check_calls = 0
|
|
141
|
+
|
|
142
|
+
async def login(self):
|
|
143
|
+
self.login_calls += 1
|
|
144
|
+
|
|
145
|
+
async def get_historical_consumption(self):
|
|
146
|
+
self.check_calls += 1
|
|
147
|
+
if self.check_calls == 3:
|
|
148
|
+
raise RuntimeError("auth expired")
|
|
149
|
+
|
|
150
|
+
def __str__(self):
|
|
151
|
+
return "fake-client"
|
|
152
|
+
|
|
153
|
+
sleeps = []
|
|
154
|
+
|
|
155
|
+
async def fake_sleep(seconds):
|
|
156
|
+
sleeps.append(seconds)
|
|
157
|
+
|
|
158
|
+
client = FakeClient()
|
|
159
|
+
logger = Mock()
|
|
160
|
+
|
|
161
|
+
ret = await probe_auth_validity(client, logger, sleep=fake_sleep)
|
|
162
|
+
|
|
163
|
+
self.assertEqual(ret, 1)
|
|
164
|
+
self.assertEqual(client.login_calls, 1)
|
|
165
|
+
self.assertEqual(client.check_calls, 3)
|
|
166
|
+
self.assertEqual(sleeps, [0, 300, 600])
|
|
167
|
+
|
|
168
|
+
|
|
100
169
|
if __name__ == "__main__":
|
|
101
170
|
unittest.main()
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
from dataclasses import dataclass, field
|
|
2
|
-
from datetime import datetime
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
@dataclass
|
|
6
|
-
class Measure:
|
|
7
|
-
accumulate: int
|
|
8
|
-
instant: float
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
@dataclass
|
|
12
|
-
class PeriodValue:
|
|
13
|
-
start: datetime
|
|
14
|
-
end: datetime
|
|
15
|
-
value: float
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
@dataclass
|
|
19
|
-
class ConsumptionForPeriod(PeriodValue):
|
|
20
|
-
desglosed: dict[str, float] = field(default_factory=dict)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
@dataclass
|
|
24
|
-
class HistoricalConsumption:
|
|
25
|
-
periods: list[ConsumptionForPeriod] = field(default_factory=list)
|
|
26
|
-
total: float = 0
|
|
27
|
-
desglosed: dict[str, float] = field(default_factory=dict)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
@dataclass
|
|
31
|
-
class HistoricalGeneration:
|
|
32
|
-
periods: list[PeriodValue] = field(default_factory=list)
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
@dataclass
|
|
36
|
-
class DemandAtInstant:
|
|
37
|
-
dt: datetime
|
|
38
|
-
value: float
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
@dataclass
|
|
42
|
-
class HistoricalPowerDemand:
|
|
43
|
-
demands: list[DemandAtInstant] = field(default_factory=list)
|
|
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
|