ideenergy 2.0.1.dev1__tar.gz → 2.0.1.dev2__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 (21) hide show
  1. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/PKG-INFO +1 -1
  2. ideenergy-2.0.1.dev2/ideenergy/__init__.py +59 -0
  3. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy/client.py +93 -37
  4. ideenergy-2.0.1.dev2/ideenergy/mock.py +217 -0
  5. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy/parsers.py +3 -0
  6. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy.egg-info/PKG-INFO +1 -1
  7. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy.egg-info/SOURCES.txt +1 -0
  8. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/pyproject.toml +1 -1
  9. ideenergy-2.0.1.dev1/ideenergy/__init__.py +0 -168
  10. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/LICENSE +0 -0
  11. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/README.md +0 -0
  12. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy/__main__.py +0 -0
  13. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy/cli.py +0 -0
  14. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy/endpoints.py +0 -0
  15. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy/types.py +0 -0
  16. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy.egg-info/dependency_links.txt +0 -0
  17. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy.egg-info/entry_points.txt +0 -0
  18. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy.egg-info/requires.txt +0 -0
  19. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/ideenergy.egg-info/top_level.txt +0 -0
  20. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/setup.cfg +0 -0
  21. {ideenergy-2.0.1.dev1 → ideenergy-2.0.1.dev2}/tests/test_client.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ideenergy
3
- Version: 2.0.1.dev1
3
+ Version: 2.0.1.dev2
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-2022 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
+ ]
@@ -19,7 +19,10 @@
19
19
  import functools
20
20
  import json
21
21
  import logging
22
+ import os
23
+ import re
22
24
  from datetime import datetime, timedelta
25
+ from pathlib import Path
23
26
  from typing import Any
24
27
 
25
28
  import aiohttp
@@ -38,6 +41,7 @@ from .endpoints import (
38
41
  _MEASURE_ENDPOINT,
39
42
  _POWER_DEMAND_LIMITS_ENDPOINT,
40
43
  _POWER_DEMAND_PERIOD_ENDPOINT,
44
+ _REST_BASE_URL,
41
45
  )
42
46
  from .types import (
43
47
  HistoricalConsumption,
@@ -46,6 +50,15 @@ from .types import (
46
50
  Measure,
47
51
  )
48
52
 
53
+ LOGGER = logging.getLogger(__name__)
54
+
55
+ I_DE_ENERGY_DUMP_DIRECTORY = os.environ.get("I_DE_ENERGY_DUMP_DIRECTORY", "")
56
+ I_DE_ENERGY_DUMP = bool(I_DE_ENERGY_DUMP_DIRECTORY)
57
+ if I_DE_ENERGY_DUMP:
58
+ I_DE_ENERGY_DUMP_BASE_PATH = Path(I_DE_ENERGY_DUMP_DIRECTORY)
59
+ else:
60
+ I_DE_ENERGY_DUMP_DIRECTORY = None
61
+
49
62
 
50
63
  def auth_required(fn):
51
64
  @functools.wraps(fn)
@@ -107,7 +120,7 @@ class Client:
107
120
  logger: logging.Logger | None = None,
108
121
  user_session_timeout: timedelta | int = 300,
109
122
  auto_renew_user_session: bool = True,
110
- ):
123
+ ) -> None:
111
124
  if not isinstance(user_session_timeout, timedelta):
112
125
  user_session_timeout = timedelta(seconds=user_session_timeout)
113
126
 
@@ -115,12 +128,21 @@ class Client:
115
128
  self._username = username
116
129
  self._password = password
117
130
  self._contract = contract
118
- self._logger = logger or logging.getLogger("ideenergy")
119
131
  self._user_session_timeout = user_session_timeout
120
132
  self._auto_renew_user_session = auto_renew_user_session
121
133
 
122
134
  self._login_ts: datetime | None = None
123
135
 
136
+ def __str__(self) -> str:
137
+ return f"{self.username}" + ("/{self.contract}" if self.contract else "")
138
+
139
+ def __repr__(self) -> str:
140
+ return (
141
+ f"<ideenergy.Client "
142
+ f"username={self.username}, "
143
+ f"contract={self.contract or '(none)'}>"
144
+ )
145
+
124
146
  #
125
147
  # Some properties
126
148
  #
@@ -133,6 +155,10 @@ class Client:
133
155
  def password(self) -> str:
134
156
  return self._password
135
157
 
158
+ @property
159
+ def contract(self) -> str | None:
160
+ return self._contract
161
+
136
162
  @property
137
163
  def is_logged(self) -> bool:
138
164
  if not self._login_ts:
@@ -159,14 +185,23 @@ class Client:
159
185
  kwargs["headers"] = headers
160
186
 
161
187
  resp = await self._sess.request(method, url, **kwargs)
188
+
162
189
  if resp.status != 200:
190
+ LOGGER.error(f"{self}: {method} URL '{url}' failed (status={resp.status})")
163
191
  raise RequestFailedError(resp)
164
192
 
193
+ LOGGER.debug(f"{self}: {method} URL '{url}' success (status={resp.status})")
165
194
  return resp
166
195
 
167
196
  async def request_bytes(self, method: str, url: str, **kwargs) -> bytes:
168
197
  resp = await self._request(method, url, **kwargs)
169
198
  buff = await resp.content.read()
199
+
200
+ if I_DE_ENERGY_DUMP and url.startswith(_REST_BASE_URL):
201
+ dump = I_DE_ENERGY_DUMP_BASE_PATH / (slugify(url) + ".bin")
202
+ dump.parent.mkdir(parents=True, exist_ok=True)
203
+ dump.write_bytes(buff)
204
+
170
205
  return buff
171
206
 
172
207
  async def request_json(
@@ -212,32 +247,40 @@ class Client:
212
247
  data = await self.request_json("POST", _LOGIN_ENDPOINT, json=payload)
213
248
 
214
249
  if not isinstance(data, dict):
250
+ LOGGER.warning(f"{self}: auth failed, invalid data")
215
251
  raise InvalidData(data)
216
252
 
217
- if data.get("success", "") == "userExpired":
218
- raise UserExpiredError(data)
219
-
220
253
  if data.get("success", "false") != "true":
254
+ LOGGER.warning(f"{self}: auth failed, no success")
221
255
  raise CommandError(data)
222
256
 
257
+ if data.get("success", "") == "userExpired":
258
+ LOGGER.warning(f"{self}: auth failed, user session expired")
259
+ raise UserExpiredError(data)
260
+
223
261
  self._login_ts = datetime.now()
224
- self._logger.info(f"successful authentication as '{self.username}'")
262
+ LOGGER.debug(f"{self}: succesfully authenticaded")
225
263
 
226
264
  if self._contract:
227
265
  await self.select_contract(self._contract)
228
- self._logger.info(f"contract '{self._contract}' selected ")
229
266
 
230
267
  # async def verify_is_logged(self) -> bool:
231
268
  # sess_info = await self.renew_session()
232
269
  # return bool(sess_info.get("usSes"))
233
270
 
234
271
  async def renew_session(self) -> dict:
235
- return await self.request_json("POST", _KEEP_SESSION)
272
+ ret = await self.request_json("POST", _KEEP_SESSION)
273
+ LOGGER.debug(f"{self}: session renewed")
274
+
275
+ return ret
236
276
 
237
277
  @auth_required
238
278
  async def is_icp_ready(self) -> bool:
239
279
  data = await self.request_json("POST", _ICP_STATUS_ENDPOINT)
240
- ret = data.get("icp", "") == "trueConectado"
280
+ if ret := data.get("icp", "") == "trueConectado":
281
+ LOGGER.debug(f"{self}: ICP is ready")
282
+ else:
283
+ LOGGER.debug(f"{self}: ICP is NOT ready")
241
284
 
242
285
  return ret
243
286
 
@@ -245,48 +288,51 @@ class Client:
245
288
  async def get_contract_details(self) -> dict[str, Any]:
246
289
  data = await self.request_json("GET", _CONTRACT_DETAILS_ENDPOINT)
247
290
  if not data.get("codContrato", False):
291
+ LOGGER.warning(f"{self}: contract details fetch failed")
248
292
  raise InvalidData(data)
249
293
 
294
+ LOGGER.debug(f"{self}: contract details fetched")
250
295
  return data
251
296
 
252
297
  @auth_required
253
298
  async def get_contracts(self) -> list[dict[str, Any]]:
254
299
  data = await self.request_json("GET", _CONTRACTS_ENDPOINT)
300
+
255
301
  if not data.get("success", False):
302
+ LOGGER.warning(f"{self}: contract list fetch failed")
256
303
  raise CommandError(data)
257
304
 
258
- try:
259
- return data["contratos"]
260
- except KeyError:
261
- raise InvalidData(data)
305
+ LOGGER.debug(f"{self}: contract list fetched")
306
+ return data["contratos"]
262
307
 
263
308
  @auth_required
264
- async def select_contract(self, id: str) -> None:
265
- resp = await self.request_json("GET", _CONTRACT_SELECTION_ENDPOINT + id)
266
- if not resp.get("success", False):
267
- raise InvalidContractError(id)
309
+ async def select_contract(self, contract_id: str) -> None:
310
+ data = await self.request_json(
311
+ "GET", _CONTRACT_SELECTION_ENDPOINT + contract_id
312
+ )
313
+ if not data.get("success", False):
314
+ LOGGER.warning(f"{self}: contract select failed")
315
+ raise InvalidContractError(contract_id)
268
316
 
269
- self._contract = id
270
- self._logger.info(f"{self}: '{id}' contract selected")
317
+ LOGGER.debug(f"{self}: contract '{contract_id}' selected")
318
+ self._contract = contract_id
271
319
 
272
320
  @auth_required
273
321
  async def get_measure(self) -> Measure:
274
- self._logger.debug("Requesting data to the ICP, may take up to a minute.")
322
+ LOGGER.info(f"{self}: requesting data to the ICP, may take up to a minute.")
275
323
  data = await self.request_json("GET", _MEASURE_ENDPOINT)
276
324
 
277
- self._logger.debug(f"Got reply, raw data: {data!r}")
278
-
279
- try:
280
- measure = Measure(
281
- accumulate=int(data["valLecturaContador"]),
282
- instant=float(data["valMagnitud"]),
283
- )
325
+ if not data.get("codSolicitudTGT"):
326
+ LOGGER.warning(f"{self}: measure request failed")
327
+ raise CommandError(data)
284
328
 
285
- except (KeyError, ValueError) as e:
286
- raise InvalidData(data) from e
329
+ ret = Measure(
330
+ accumulate=int(data["valLecturaContador"]),
331
+ instant=float(data["valMagnitud"]),
332
+ )
333
+ LOGGER.debug(f"{self}: measure fetched succesfully")
287
334
 
288
- self._logger.info(f"{self}: ICP measure reading successful")
289
- return measure
335
+ return ret
290
336
 
291
337
  @auth_required
292
338
  async def get_historical_consumption(
@@ -300,6 +346,9 @@ class Client:
300
346
 
301
347
  ret = parsers.parse_historical_consumption(data)
302
348
  ret.periods = [x for x in ret.periods if x.start >= start and x.end < end]
349
+
350
+ LOGGER.debug(f"{self}: historical consumption fetched succesfully")
351
+
303
352
  return ret
304
353
 
305
354
  async def get_historical_generation(
@@ -312,6 +361,8 @@ class Client:
312
361
  data = await self.request_json("GET", url, encoding="iso-8859-1")
313
362
  ret = parsers.parse_historical_generation(data)
314
363
 
364
+ LOGGER.debug(f"{self}: historical generation fetched succesfully")
365
+
315
366
  return ret
316
367
 
317
368
  # @auth_required
@@ -345,14 +396,12 @@ class Client:
345
396
  raise CommandError(limits)
346
397
 
347
398
  url = _POWER_DEMAND_PERIOD_ENDPOINT.format(**limits)
348
-
349
399
  data = await self.request_json("GET", url)
350
-
351
400
  ret = parsers.parse_historical_power_demand_data(data)
352
- return ret
353
401
 
354
- def __repr__(self):
355
- return f"<ideenergy.Client username={self.username}, contract={self._contract}>"
402
+ LOGGER.debug(f"{self}: historical power demand fetched succesfully")
403
+
404
+ return ret
356
405
 
357
406
 
358
407
  class ClientError(Exception):
@@ -364,7 +413,10 @@ class RequestFailedError(ClientError):
364
413
  self.response = response
365
414
 
366
415
  def __str__(self):
367
- return f"Invalid response: {self.response.status} - {self.response.reason}"
416
+ return (
417
+ f"Invalid response for '{self.response.request.url}': "
418
+ f"{self.response.status} - {self.response.reason}"
419
+ )
368
420
 
369
421
 
370
422
  class CommandError(ClientError):
@@ -397,3 +449,7 @@ class UserExpiredError(ClientError):
397
449
 
398
450
  def __str__(self):
399
451
  return f"User expired: {self.data!r}"
452
+
453
+
454
+ def slugify(value: str) -> str:
455
+ return re.sub(r"[^a-z0-9_]", "_", value.lower())
@@ -0,0 +1,217 @@
1
+ # Copyright (C) 2021-2022 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
+ import logging
20
+ import os
21
+ import random
22
+ from collections.abc import Iterator
23
+ from contextlib import contextmanager
24
+ from datetime import datetime, timedelta
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ import aiohttp
29
+
30
+ from .client import Client, auth_required
31
+ from .types import HistoricalGeneration # noqa: F401
32
+ from .types import HistoricalPowerDemand # noqa: F401
33
+ from .types import (
34
+ ConsumptionForPeriod,
35
+ HistoricalConsumption,
36
+ Measure,
37
+ )
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
47
+
48
+
49
+ class MockClient(Client):
50
+ #
51
+ # Requests
52
+ #
53
+
54
+ async def _request(self, method: str, url: str, **kwargs) -> aiohttp.ClientResponse:
55
+ raise TypeError("This should not be called")
56
+
57
+ async def request_bytes(self, method: str, url: str, **kwargs) -> bytes:
58
+ raise TypeError("This should not be called")
59
+
60
+ async def request_json(
61
+ self, method: str, url: str, encoding: str = "utf-8", **kwargs
62
+ ) -> dict[Any, Any]:
63
+ raise TypeError("This should not be called")
64
+
65
+ #
66
+ # Methods
67
+ #
68
+
69
+ async def login(self) -> None:
70
+ self._login_ts = datetime.now()
71
+
72
+ if self._contract:
73
+ await self.select_contract(self._contract)
74
+
75
+ async def renew_session(self) -> dict:
76
+ return {"total": "900", "usSes": "12345678901X12", "aviso": "15"}
77
+
78
+ @auth_required
79
+ async def is_icp_ready(self) -> bool:
80
+ return True
81
+
82
+ @auth_required
83
+ async def get_contracts(self) -> dict:
84
+ return {
85
+ "success": True,
86
+ "contratos": [
87
+ {
88
+ "direccion": "xxxxxxxxxxxxxxxxxxxxxxx",
89
+ "cups": "ES0000000000000000AB",
90
+ "tipo": "A",
91
+ "tipUsoEnergiaCorto": "-",
92
+ "tipUsoEnergiaLargo": "-",
93
+ "estContrato": "Alta",
94
+ "codContrato": "123456789",
95
+ "esTelegestionado": True,
96
+ "presion": "1.00",
97
+ "fecUltActua": "01.01.1970",
98
+ "esTelemedido": False,
99
+ "tipSisLectura": "TG",
100
+ "estadoAlta": True,
101
+ }
102
+ ],
103
+ }
104
+
105
+ @auth_required
106
+ async def get_contract_details(self) -> dict:
107
+ return {
108
+ "ape1Titular": "xxxxxx ",
109
+ "ape2Titular": "xxxxxx ",
110
+ "codCliente": "12345678",
111
+ "codContrato": 123456789.0,
112
+ "codPoblacion": "000000",
113
+ "codProvincia": "00",
114
+ "codPostal": "00000",
115
+ "codSociedad": 3,
116
+ "codTarifaIblda": "92T0",
117
+ "codTension": "09",
118
+ "cups": "ES0000000000000000XY",
119
+ "direccion": "C/ XXXXXXXXXXXXXXXXXX, 12 , 34 00000-XXXXXXXXXXXXXXXXXXXX"
120
+ " - XXXXXXXXX ",
121
+ "dni": "12345678Y",
122
+ "emailFactElec": "xxxxxxxxx@xxxxx.com",
123
+ "esAutoconsumidor": False,
124
+ "esAutogenerador": False,
125
+ "esPeajeDirecto": False,
126
+ "fecAltaContrato": "2000-01-01",
127
+ "fecBajaContrato": 1600000000000,
128
+ "fecUltActua": "22.10.2021",
129
+ "indEstadioPS": 4,
130
+ "indFraElectrn": "N",
131
+ "nomGestorOficina": "XXXXXXXXXXXX ",
132
+ "nomPoblacion": "XXXXXXXXXXXXXXXXXXXX ",
133
+ "nomProvincia": "XXXXXXXXX ",
134
+ "nomTitular": "XXXXX ",
135
+ "numCtaBancaria": "0",
136
+ "numTelefono": " ",
137
+ "numTelefonoAdicional": "123456789",
138
+ "potDia": 0.0,
139
+ "potMaxima": 5750,
140
+ "presion": "1.00",
141
+ "puntoSuministro": "1234567.0",
142
+ "tipAparato": "CN",
143
+ "tipCualificacion": "PP",
144
+ "tipEstadoContrato": "AL",
145
+ "tipo": "A",
146
+ "tipPuntoMedida": None,
147
+ "tipSectorEne": "01",
148
+ "tipSisLectura": "TG",
149
+ "tipSuministro": None,
150
+ "tipUsoEnerg": "",
151
+ "listContador": [
152
+ {
153
+ "fecInstalEquipo": "28-01-2011",
154
+ "propiedadEquipo": "i-DE",
155
+ "tipAparato": "CONTADOR TELEGESTION",
156
+ "tipMarca": "ZIV",
157
+ "numSerieEquipo": 12345678.0,
158
+ }
159
+ ],
160
+ "esTelegestionado": True,
161
+ "esTelegestionadoFacturado": True,
162
+ "esTelemedido": False,
163
+ "cau": None,
164
+ }
165
+
166
+ @auth_required
167
+ async def select_contract(self, contract_id: str) -> None:
168
+ self._contract = contract_id
169
+
170
+ @auth_required
171
+ async def get_measure(self) -> Measure:
172
+ data = {
173
+ "valMagnitud": random.randint(0, 500), # "158.64",
174
+ "valInterruptor": "1",
175
+ "valEstado": "09",
176
+ "valLecturaContador": random.randint(0, 5_000), # "43167",
177
+ "codSolicitudTGT": "012345678901",
178
+ }
179
+
180
+ return Measure(
181
+ accumulate=int(data["valLecturaContador"]),
182
+ instant=float(data["valMagnitud"]),
183
+ )
184
+
185
+ @auth_required
186
+ async def get_historical_consumption(
187
+ self, start: datetime, end: datetime
188
+ ) -> HistoricalConsumption:
189
+
190
+ with preseed_random((start, end)) as rand:
191
+ periods = [
192
+ ConsumptionForPeriod(
193
+ start=dt,
194
+ end=dt + timedelta(hours=1),
195
+ value=rand.randint(0, 1000),
196
+ desglosed={},
197
+ )
198
+ for dt in datetime_range(start, end, step=timedelta(hours=1))
199
+ ]
200
+
201
+ return HistoricalConsumption(
202
+ periods=periods, total=sum([x.value for x in periods]), desglosed={}
203
+ )
204
+
205
+
206
+ def datetime_range(
207
+ start: datetime, end: datetime, step: timedelta
208
+ ) -> Iterator[datetime]:
209
+ curr = start
210
+ while curr < end:
211
+ yield curr
212
+ curr = curr + step
213
+
214
+
215
+ @contextmanager
216
+ def preseed_random(seed) -> Iterator[random.Random]:
217
+ yield random.Random(repr(seed))
@@ -45,6 +45,7 @@ def parser_generic_historical_data(data, base_dt: datetime) -> dict[str, Any]:
45
45
 
46
46
  g = (_normalize(idx, item) for (idx, item) in enumerate(data["y"]["data"][0]))
47
47
  historical_values = [x for x in g if x is not None]
48
+ historical_values = list(sorted(historical_values, key=lambda x: x.start))
48
49
 
49
50
  return {
50
51
  # "accumulated": float(data["acumulado"]),
@@ -80,6 +81,8 @@ def parse_historical_consumption(data) -> HistoricalConsumption:
80
81
  )
81
82
  )
82
83
 
84
+ ret.periods = list(sorted(ret.periods, key=lambda x: x.start))
85
+
83
86
  return ret
84
87
 
85
88
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ideenergy
3
- Version: 2.0.1.dev1
3
+ Version: 2.0.1.dev2
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
@@ -6,6 +6,7 @@ ideenergy/__main__.py
6
6
  ideenergy/cli.py
7
7
  ideenergy/client.py
8
8
  ideenergy/endpoints.py
9
+ ideenergy/mock.py
9
10
  ideenergy/parsers.py
10
11
  ideenergy/types.py
11
12
  ideenergy.egg-info/PKG-INFO
@@ -2,7 +2,7 @@
2
2
 
3
3
  [project]
4
4
  name = "ideenergy"
5
- version = "2.0.1dev1"
5
+ version = "2.0.1dev2"
6
6
  dependencies = [
7
7
  "aiohttp <4.0,>=3.8",
8
8
  "dotenv>=0.9.9",
@@ -1,168 +0,0 @@
1
- # Copyright (C) 2021-2022 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
- import json
20
- import os
21
-
22
- from .client import (
23
- Client,
24
- ClientError,
25
- CommandError,
26
- InvalidContractError,
27
- InvalidData,
28
- RequestFailedError,
29
- UserExpiredError,
30
- )
31
- from .types import (
32
- ConsumptionForPeriod,
33
- DemandAtInstant,
34
- HistoricalConsumption,
35
- HistoricalGeneration,
36
- HistoricalPowerDemand,
37
- Measure,
38
- PeriodValue,
39
- )
40
-
41
- # def get_credentials(parsedargs=None, credentials=None, environ_prefix="I_DE_ENERGY"):
42
- # if parsedargs and parsedargs.username:
43
- # return parsedargs.username, parsedargs.password
44
-
45
- # credentials = credentials or getattr(parsedargs, "credentials", None)
46
- # if credentials:
47
- # with open(credentials, encoding="utf-8") as fh:
48
- # d = json.loads(fh.read())
49
- # return d["username"], d["password"]
50
-
51
- # if environ_prefix:
52
- # environ_prefix = environ_prefix.upper()
53
- # return (
54
- # os.environ.get(f"{environ_prefix}_USERNAME"),
55
- # os.environ.get(f"{environ_prefix}_PASSWORD"),
56
- # )
57
-
58
-
59
- # def sanitize_address(address):
60
- # return " ".join([x.strip().capitalize() for x in address.split(" ") if x])
61
-
62
-
63
- __all__ = [
64
- "Client",
65
- "ClientError",
66
- "CommandError",
67
- "ConsumptionForPeriod",
68
- "DemandAtInstant",
69
- "HistoricalConsumption",
70
- "HistoricalGeneration",
71
- "HistoricalPowerDemand",
72
- "InvalidContractError",
73
- "InvalidData",
74
- "Measure",
75
- "PeriodValue",
76
- "RequestFailedError",
77
- "UserExpiredError",
78
- # "get_credentials",
79
- # "sanitize_address",
80
- ]
81
-
82
- __doc__ = """
83
- # Returned JSON payloads for login phase:
84
-
85
- scenario: Valid credentials.
86
- response code: 200
87
- response json:
88
- {
89
- "redirect": "informacion-del-contrato",
90
- "zona": "B",
91
- "success": "true",
92
- "idioma": "ES",
93
- "uCcr": "",
94
- }
95
-
96
- scenario: Invalid credentials.
97
- response code: 200
98
- response json:
99
- {
100
- "success": "false",
101
- "message": "El usuario o la contraseña que has introducido son incorrectos. Por favor, inténtalo de nuevo.",
102
- }
103
-
104
-
105
- scenario: Several login retries with invalid credentials.
106
- response code: 200
107
- response json:
108
- {
109
- "success": "false",
110
- "message": "Número de intentos de acceso excedido. Usuario bloqueado temporalmente. Vuelva a intentarlo dentro de 5 minutos."
111
- }
112
-
113
- # Retuned JSON payloads for measures (exposed keys: "valLecturaContador", "valMagnitud", "valEstado")
114
-
115
- scenario: valid measure
116
- response code: 200
117
- response json:
118
- {
119
- "valMagnitud": "10.31",
120
- "valInterruptor": "1",
121
- "valEstado": "09",
122
- "valLecturaContador": "42290",
123
- "codSolicitudTGT": "009016617100"
124
- }
125
- {
126
- "valMagnitud": "10.49",
127
- "valInterruptor": "1",
128
- "valEstado": "09",
129
- "valLecturaContador": "42290",
130
- "codSolicitudTGT": "009016672300",
131
- }
132
-
133
- # Cookies from server:
134
- [{'version': 0,
135
- 'name': 'JSESSIONID',
136
- 'value': '^0000[0-9a-zA-Z]{18}_[0-9a-zA-Z]{4}:[0-9a-zA-Z]{9}$',
137
- 'port': None,
138
- 'port_specified': False,
139
- 'domain': 'www.i-de.es',
140
- 'domain_specified': False,
141
- 'domain_initial_dot': False,
142
- 'path': '/',
143
- 'path_specified': True,
144
- 'secure': True,
145
- 'expires': None,
146
- 'discard': True,
147
- 'comment': None,
148
- 'comment_url': None,
149
- 'rfc2109': False,
150
- '_rest': {'HttpOnly': None}},
151
- {'version': 0,
152
- 'name': 'NSC_wt_mc_mbssvo0Y-[0-9]{5}',
153
- 'value': '^[0-9a-f]{72}$',
154
- 'port': None,
155
- 'port_specified': False,
156
- 'domain': 'www.i-de.es',
157
- 'domain_specified': False,
158
- 'domain_initial_dot': False,
159
- 'path': '/',
160
- 'path_specified': True,
161
- 'secure': True,
162
- 'expires': 1626089796, # Aprox. 2 minutes
163
- 'discard': False,
164
- 'comment': None,
165
- 'comment_url': None,
166
- 'rfc2109': False,
167
- '_rest': {'httponly': None}}]
168
- """
File without changes
File without changes
File without changes