ideenergy 2.0.1.dev1__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.dev1 → ideenergy-2.0.1.dev3}/PKG-INFO +1 -1
- ideenergy-2.0.1.dev3/ideenergy/__init__.py +59 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy/cli.py +75 -15
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy/client.py +146 -55
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy/endpoints.py +28 -0
- ideenergy-2.0.1.dev3/ideenergy/mock.py +219 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy/parsers.py +23 -1
- ideenergy-2.0.1.dev3/ideenergy/types.py +66 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/PKG-INFO +1 -1
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/SOURCES.txt +1 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/pyproject.toml +1 -1
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/tests/test_client.py +79 -10
- ideenergy-2.0.1.dev1/ideenergy/__init__.py +0 -168
- ideenergy-2.0.1.dev1/ideenergy/types.py +0 -43
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/LICENSE +0 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/README.md +0 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy/__main__.py +0 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/dependency_links.txt +0 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/entry_points.txt +0 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/requires.txt +0 -0
- {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev3}/ideenergy.egg-info/top_level.txt +0 -0
- {ideenergy-2.0.1.dev1 → 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
|
|
@@ -0,0 +1,59 @@
|
|
|
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 .client import (
|
|
20
|
+
Client,
|
|
21
|
+
ClientError,
|
|
22
|
+
CommandError,
|
|
23
|
+
InvalidContractError,
|
|
24
|
+
InvalidData,
|
|
25
|
+
RequestFailedError,
|
|
26
|
+
UserExpiredError,
|
|
27
|
+
)
|
|
28
|
+
from .mock import MockClient
|
|
29
|
+
from .types import (
|
|
30
|
+
ConsumptionForPeriod,
|
|
31
|
+
DemandAtInstant,
|
|
32
|
+
HistoricalConsumption,
|
|
33
|
+
HistoricalGeneration,
|
|
34
|
+
HistoricalPowerDemand,
|
|
35
|
+
Measure,
|
|
36
|
+
PeriodValue,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# def sanitize_address(address):
|
|
40
|
+
# return " ".join([x.strip().capitalize() for x in address.split(" ") if x])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
__all__ = [
|
|
44
|
+
"Client",
|
|
45
|
+
"ClientError",
|
|
46
|
+
"CommandError",
|
|
47
|
+
"ConsumptionForPeriod",
|
|
48
|
+
"DemandAtInstant",
|
|
49
|
+
"HistoricalConsumption",
|
|
50
|
+
"HistoricalGeneration",
|
|
51
|
+
"HistoricalPowerDemand",
|
|
52
|
+
"InvalidContractError",
|
|
53
|
+
"InvalidData",
|
|
54
|
+
"Measure",
|
|
55
|
+
"MockClient",
|
|
56
|
+
"PeriodValue",
|
|
57
|
+
"RequestFailedError",
|
|
58
|
+
"UserExpiredError",
|
|
59
|
+
]
|
|
@@ -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,18 +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
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
from collections.abc import Awaitable, Callable
|
|
22
26
|
from datetime import datetime, timedelta
|
|
23
|
-
from
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any, Concatenate, ParamSpec, TypeVar
|
|
24
29
|
|
|
25
30
|
import aiohttp
|
|
26
31
|
|
|
27
32
|
from . import parsers
|
|
28
33
|
from .endpoints import (
|
|
29
34
|
_BASE_URL,
|
|
35
|
+
_CONSUMPTION_IN_PROGRESS_ENDPOINT,
|
|
30
36
|
_CONSUMPTION_PERIOD_ENDPOINT,
|
|
31
37
|
_CONTRACT_DETAILS_ENDPOINT,
|
|
32
38
|
_CONTRACT_SELECTION_ENDPOINT,
|
|
@@ -38,21 +44,43 @@ from .endpoints import (
|
|
|
38
44
|
_MEASURE_ENDPOINT,
|
|
39
45
|
_POWER_DEMAND_LIMITS_ENDPOINT,
|
|
40
46
|
_POWER_DEMAND_PERIOD_ENDPOINT,
|
|
47
|
+
_REST_BASE_URL,
|
|
41
48
|
)
|
|
42
49
|
from .types import (
|
|
43
50
|
HistoricalConsumption,
|
|
44
51
|
HistoricalGeneration,
|
|
45
52
|
HistoricalPowerDemand,
|
|
53
|
+
InProgressConsumption,
|
|
46
54
|
Measure,
|
|
47
55
|
)
|
|
48
56
|
|
|
57
|
+
LOGGER = logging.getLogger(__name__)
|
|
49
58
|
|
|
50
|
-
|
|
59
|
+
I_DE_ENERGY_DUMP_DIRECTORY = os.environ.get("I_DE_ENERGY_DUMP_DIRECTORY", "")
|
|
60
|
+
I_DE_ENERGY_DUMP = bool(I_DE_ENERGY_DUMP_DIRECTORY)
|
|
61
|
+
if I_DE_ENERGY_DUMP:
|
|
62
|
+
I_DE_ENERGY_DUMP_BASE_PATH = Path(I_DE_ENERGY_DUMP_DIRECTORY)
|
|
63
|
+
else:
|
|
64
|
+
I_DE_ENERGY_DUMP_DIRECTORY = None
|
|
65
|
+
|
|
66
|
+
|
|
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]]:
|
|
51
78
|
@functools.wraps(fn)
|
|
52
|
-
async def _wrap(client, *args, **kwargs):
|
|
53
|
-
if client.
|
|
79
|
+
async def _wrap(client: Client, *args, **kwargs):
|
|
80
|
+
if client._session_auto_refresh is True and client.is_logged is False:
|
|
54
81
|
await client.login()
|
|
55
82
|
|
|
83
|
+
# await client.renew_session()
|
|
56
84
|
return await fn(client, *args, **kwargs)
|
|
57
85
|
|
|
58
86
|
return _wrap
|
|
@@ -105,22 +133,31 @@ class Client:
|
|
|
105
133
|
password: str,
|
|
106
134
|
contract: str | None = None,
|
|
107
135
|
logger: logging.Logger | None = None,
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
):
|
|
111
|
-
if not isinstance(
|
|
112
|
-
|
|
136
|
+
session_timeout: timedelta | int = SESSION_TIMEOUT,
|
|
137
|
+
session_auto_refresh: bool = SESSION_AUTO_REFRESH,
|
|
138
|
+
) -> None:
|
|
139
|
+
if not isinstance(session_timeout, timedelta):
|
|
140
|
+
session_timeout = timedelta(seconds=session_timeout)
|
|
113
141
|
|
|
114
142
|
self._sess = session
|
|
115
143
|
self._username = username
|
|
116
144
|
self._password = password
|
|
117
145
|
self._contract = contract
|
|
118
|
-
self.
|
|
119
|
-
self.
|
|
120
|
-
self._auto_renew_user_session = auto_renew_user_session
|
|
146
|
+
self._session_timeout = timedelta(session_timeout.total_seconds() * 0.9)
|
|
147
|
+
self._session_auto_refresh = session_auto_refresh
|
|
121
148
|
|
|
122
149
|
self._login_ts: datetime | None = None
|
|
123
150
|
|
|
151
|
+
def __str__(self) -> str:
|
|
152
|
+
return f"{self.username}" + (f"/{self.contract}" if self.contract else "")
|
|
153
|
+
|
|
154
|
+
def __repr__(self) -> str:
|
|
155
|
+
return (
|
|
156
|
+
f"<ideenergy.Client "
|
|
157
|
+
f"username={self.username}, "
|
|
158
|
+
f"contract={self.contract or '(none)'}>"
|
|
159
|
+
)
|
|
160
|
+
|
|
124
161
|
#
|
|
125
162
|
# Some properties
|
|
126
163
|
#
|
|
@@ -133,21 +170,25 @@ class Client:
|
|
|
133
170
|
def password(self) -> str:
|
|
134
171
|
return self._password
|
|
135
172
|
|
|
173
|
+
@property
|
|
174
|
+
def contract(self) -> str | None:
|
|
175
|
+
return self._contract
|
|
176
|
+
|
|
136
177
|
@property
|
|
137
178
|
def is_logged(self) -> bool:
|
|
138
179
|
if not self._login_ts:
|
|
139
180
|
return False
|
|
140
181
|
|
|
141
182
|
delta = datetime.now() - self._login_ts
|
|
142
|
-
return delta < self.
|
|
183
|
+
return delta < self.session_timeout
|
|
143
184
|
|
|
144
185
|
@property
|
|
145
|
-
def
|
|
146
|
-
return self.
|
|
186
|
+
def session_timeout(self) -> timedelta:
|
|
187
|
+
return self._session_timeout
|
|
147
188
|
|
|
148
189
|
@property
|
|
149
|
-
def
|
|
150
|
-
return self.
|
|
190
|
+
def session_auto_refresh(self) -> bool:
|
|
191
|
+
return self._session_auto_refresh
|
|
151
192
|
|
|
152
193
|
#
|
|
153
194
|
# Requests
|
|
@@ -159,14 +200,23 @@ class Client:
|
|
|
159
200
|
kwargs["headers"] = headers
|
|
160
201
|
|
|
161
202
|
resp = await self._sess.request(method, url, **kwargs)
|
|
203
|
+
|
|
162
204
|
if resp.status != 200:
|
|
205
|
+
LOGGER.error(f"{self}: {method} URL '{url}' failed (status={resp.status})")
|
|
163
206
|
raise RequestFailedError(resp)
|
|
164
207
|
|
|
208
|
+
LOGGER.debug(f"{self}: {method} URL '{url}' success (status={resp.status})")
|
|
165
209
|
return resp
|
|
166
210
|
|
|
167
211
|
async def request_bytes(self, method: str, url: str, **kwargs) -> bytes:
|
|
168
212
|
resp = await self._request(method, url, **kwargs)
|
|
169
213
|
buff = await resp.content.read()
|
|
214
|
+
|
|
215
|
+
if I_DE_ENERGY_DUMP and url.startswith(_REST_BASE_URL):
|
|
216
|
+
dump = I_DE_ENERGY_DUMP_BASE_PATH / (slugify(url) + ".bin")
|
|
217
|
+
dump.parent.mkdir(parents=True, exist_ok=True)
|
|
218
|
+
dump.write_bytes(buff)
|
|
219
|
+
|
|
170
220
|
return buff
|
|
171
221
|
|
|
172
222
|
async def request_json(
|
|
@@ -212,32 +262,40 @@ class Client:
|
|
|
212
262
|
data = await self.request_json("POST", _LOGIN_ENDPOINT, json=payload)
|
|
213
263
|
|
|
214
264
|
if not isinstance(data, dict):
|
|
265
|
+
LOGGER.error(f"{self}: auth failed, invalid data")
|
|
215
266
|
raise InvalidData(data)
|
|
216
267
|
|
|
217
|
-
if data.get("success", "") == "userExpired":
|
|
218
|
-
raise UserExpiredError(data)
|
|
219
|
-
|
|
220
268
|
if data.get("success", "false") != "true":
|
|
269
|
+
LOGGER.error(f"{self}: auth failed, no success")
|
|
221
270
|
raise CommandError(data)
|
|
222
271
|
|
|
272
|
+
if data.get("success", "") == "userExpired":
|
|
273
|
+
LOGGER.error(f"{self}: auth failed, user session expired")
|
|
274
|
+
raise UserExpiredError(data)
|
|
275
|
+
|
|
223
276
|
self._login_ts = datetime.now()
|
|
224
|
-
|
|
277
|
+
LOGGER.debug(f"{self}: succesfully authenticaded")
|
|
225
278
|
|
|
226
279
|
if self._contract:
|
|
227
280
|
await self.select_contract(self._contract)
|
|
228
|
-
self._logger.info(f"contract '{self._contract}' selected ")
|
|
229
281
|
|
|
230
282
|
# async def verify_is_logged(self) -> bool:
|
|
231
283
|
# sess_info = await self.renew_session()
|
|
232
284
|
# return bool(sess_info.get("usSes"))
|
|
233
285
|
|
|
234
286
|
async def renew_session(self) -> dict:
|
|
235
|
-
|
|
287
|
+
ret = await self.request_json("POST", _KEEP_SESSION)
|
|
288
|
+
LOGGER.debug(f"{self}: session renewed")
|
|
289
|
+
|
|
290
|
+
return ret
|
|
236
291
|
|
|
237
292
|
@auth_required
|
|
238
293
|
async def is_icp_ready(self) -> bool:
|
|
239
294
|
data = await self.request_json("POST", _ICP_STATUS_ENDPOINT)
|
|
240
|
-
ret
|
|
295
|
+
if ret := data.get("icp", "") == "trueConectado":
|
|
296
|
+
LOGGER.debug(f"{self}: ICP is ready")
|
|
297
|
+
else:
|
|
298
|
+
LOGGER.debug(f"{self}: ICP is NOT ready")
|
|
241
299
|
|
|
242
300
|
return ret
|
|
243
301
|
|
|
@@ -245,53 +303,59 @@ class Client:
|
|
|
245
303
|
async def get_contract_details(self) -> dict[str, Any]:
|
|
246
304
|
data = await self.request_json("GET", _CONTRACT_DETAILS_ENDPOINT)
|
|
247
305
|
if not data.get("codContrato", False):
|
|
306
|
+
LOGGER.error(f"{self}: contract details fetch failed")
|
|
248
307
|
raise InvalidData(data)
|
|
249
308
|
|
|
309
|
+
LOGGER.debug(f"{self}: contract details fetched")
|
|
250
310
|
return data
|
|
251
311
|
|
|
252
312
|
@auth_required
|
|
253
313
|
async def get_contracts(self) -> list[dict[str, Any]]:
|
|
254
314
|
data = await self.request_json("GET", _CONTRACTS_ENDPOINT)
|
|
315
|
+
|
|
255
316
|
if not data.get("success", False):
|
|
317
|
+
LOGGER.error(f"{self}: contract list fetch failed")
|
|
256
318
|
raise CommandError(data)
|
|
257
319
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
except KeyError:
|
|
261
|
-
raise InvalidData(data)
|
|
320
|
+
LOGGER.debug(f"{self}: contract list fetched")
|
|
321
|
+
return data["contratos"]
|
|
262
322
|
|
|
263
323
|
@auth_required
|
|
264
|
-
async def select_contract(self,
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
324
|
+
async def select_contract(self, contract_id: str) -> None:
|
|
325
|
+
data = await self.request_json(
|
|
326
|
+
"GET", _CONTRACT_SELECTION_ENDPOINT + contract_id
|
|
327
|
+
)
|
|
328
|
+
if not data.get("success", False):
|
|
329
|
+
LOGGER.error(f"{self}: contract select failed")
|
|
330
|
+
raise InvalidContractError(contract_id)
|
|
268
331
|
|
|
269
|
-
self
|
|
270
|
-
self.
|
|
332
|
+
LOGGER.debug(f"{self}: contract '{contract_id}' selected")
|
|
333
|
+
self._contract = contract_id
|
|
271
334
|
|
|
272
335
|
@auth_required
|
|
273
336
|
async def get_measure(self) -> Measure:
|
|
274
|
-
|
|
337
|
+
LOGGER.info(f"{self}: requesting data to the ICP, may take up to a minute.")
|
|
275
338
|
data = await self.request_json("GET", _MEASURE_ENDPOINT)
|
|
276
339
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
measure = Measure(
|
|
281
|
-
accumulate=int(data["valLecturaContador"]),
|
|
282
|
-
instant=float(data["valMagnitud"]),
|
|
283
|
-
)
|
|
340
|
+
if not data.get("codSolicitudTGT"):
|
|
341
|
+
LOGGER.error(f"{self}: measure request failed")
|
|
342
|
+
raise CommandError(data)
|
|
284
343
|
|
|
285
|
-
|
|
286
|
-
|
|
344
|
+
ret = Measure(
|
|
345
|
+
accumulate=int(data["valLecturaContador"]),
|
|
346
|
+
instant=float(data["valMagnitud"]),
|
|
347
|
+
)
|
|
348
|
+
LOGGER.debug(f"{self}: measure fetched succesfully")
|
|
287
349
|
|
|
288
|
-
|
|
289
|
-
return measure
|
|
350
|
+
return ret
|
|
290
351
|
|
|
291
352
|
@auth_required
|
|
292
353
|
async def get_historical_consumption(
|
|
293
|
-
self, start: datetime, end: datetime
|
|
354
|
+
self, start: datetime | None = None, end: datetime | None = None
|
|
294
355
|
) -> HistoricalConsumption:
|
|
356
|
+
end = end or datetime.now()
|
|
357
|
+
start = start or end - timedelta(days=7)
|
|
358
|
+
|
|
295
359
|
start = min([start, end])
|
|
296
360
|
end = max([start, end])
|
|
297
361
|
url = _CONSUMPTION_PERIOD_ENDPOINT.format(start=start, end=end)
|
|
@@ -299,12 +363,25 @@ class Client:
|
|
|
299
363
|
data = await self.request_json("GET", url, encoding="iso-8859-1")
|
|
300
364
|
|
|
301
365
|
ret = parsers.parse_historical_consumption(data)
|
|
302
|
-
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]
|
|
367
|
+
|
|
368
|
+
LOGGER.debug(f"{self}: historical consumption fetched succesfully")
|
|
369
|
+
|
|
370
|
+
return ret
|
|
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)
|
|
303
377
|
return ret
|
|
304
378
|
|
|
305
379
|
async def get_historical_generation(
|
|
306
|
-
self, start: datetime, end: datetime
|
|
380
|
+
self, start: datetime | None = None, end: datetime | None = None
|
|
307
381
|
) -> HistoricalGeneration:
|
|
382
|
+
end = end or datetime.now()
|
|
383
|
+
start = start or end - timedelta(days=7)
|
|
384
|
+
|
|
308
385
|
start = min([start, end])
|
|
309
386
|
end = max([start, end])
|
|
310
387
|
url = _GENERATION_PERIOD_ENDPOINT.format(start=start, end=end)
|
|
@@ -312,6 +389,8 @@ class Client:
|
|
|
312
389
|
data = await self.request_json("GET", url, encoding="iso-8859-1")
|
|
313
390
|
ret = parsers.parse_historical_generation(data)
|
|
314
391
|
|
|
392
|
+
LOGGER.debug(f"{self}: historical generation fetched succesfully")
|
|
393
|
+
|
|
315
394
|
return ret
|
|
316
395
|
|
|
317
396
|
# @auth_required
|
|
@@ -344,15 +423,20 @@ class Client:
|
|
|
344
423
|
if limits.get("resultado") != "correcto":
|
|
345
424
|
raise CommandError(limits)
|
|
346
425
|
|
|
347
|
-
|
|
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")
|
|
348
431
|
|
|
432
|
+
url = _POWER_DEMAND_PERIOD_ENDPOINT.format(**limits)
|
|
349
433
|
data = await self.request_json("GET", url)
|
|
350
434
|
|
|
351
435
|
ret = parsers.parse_historical_power_demand_data(data)
|
|
352
|
-
return ret
|
|
353
436
|
|
|
354
|
-
|
|
355
|
-
|
|
437
|
+
LOGGER.debug(f"{self}: historical power demand fetched succesfully")
|
|
438
|
+
|
|
439
|
+
return ret
|
|
356
440
|
|
|
357
441
|
|
|
358
442
|
class ClientError(Exception):
|
|
@@ -364,7 +448,10 @@ class RequestFailedError(ClientError):
|
|
|
364
448
|
self.response = response
|
|
365
449
|
|
|
366
450
|
def __str__(self):
|
|
367
|
-
return
|
|
451
|
+
return (
|
|
452
|
+
f"Invalid response for '{self.response.url}': "
|
|
453
|
+
f"{self.response.status} - {self.response.reason}"
|
|
454
|
+
)
|
|
368
455
|
|
|
369
456
|
|
|
370
457
|
class CommandError(ClientError):
|
|
@@ -397,3 +484,7 @@ class UserExpiredError(ClientError):
|
|
|
397
484
|
|
|
398
485
|
def __str__(self):
|
|
399
486
|
return f"User expired: {self.data!r}"
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def slugify(value: str) -> str:
|
|
490
|
+
return re.sub(r"[^a-z0-9_]", "_", value.lower())
|
|
@@ -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',
|