Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,26 @@ pip install oligo[requests]
pip install oligo[asyncio]
```

### Autenticación

Puedes pasar el usuario y la contraseña directamente o usar las variables de entorno `I-DE-USER` e `I-DE-PASSWORD` (también se admiten ficheros `.env` gracias a `python-dotenv`):

```python
from oligo import Iber

connection = Iber()
connection.login("user", "password")
```

O usando variables de entorno / `.env`:

```python
from oligo import Iber

connection = Iber()
connection.login() # Lee I-DE-USER e I-DE-PASSWORD del entorno
```

### Ejemplos:

#### Consultar consumo actual (Sync):
Expand Down Expand Up @@ -118,6 +138,44 @@ async def main():
asyncio.run(main())
```

#### Obtener el consumo horario facturado durante un periodo (Sync)

```python
from oligo import Iber
from datetime import date, timedelta

connection = Iber()
connection.login("user", "password")

from_date = date.today() - timedelta(days=7)
until_date = date.today() - timedelta(days=1)

consumo = connection.consumption_facturado(from_date, until_date)

print(consumo[:10])
```

#### Obtener el consumo horario facturado durante un periodo (ASync)

```python
import asyncio
from oligo.asyncio import AsyncIber
from datetime import date, timedelta

async def main():
connection = AsyncIber()
await connection.login("user", "password")

from_date = date.today() - timedelta(days=7)
until_date = date.today() - timedelta(days=1)

consumo = await connection.consumption_facturado(from_date, until_date)

print(consumo[:10])

asyncio.run(main())
```

Los datos son el consumo por hora en Watt-horas. En este caso tendremos los
dato de una semana, que son 7 por 24, 168 valores. Si sumamos y dividimos
por 1000, tenemos el consumo de una semana en kWh.
Expand All @@ -129,6 +187,26 @@ por 1000, tenemos el consumo de una semana en kWh.
> No new features will be added, only bugs will be fixed while the i-DE web api
> continues to work in the same way.

### Authentication

You can pass the username and password directly or use the `I-DE-USER` and `I-DE-PASSWORD` environment variables (`.env` files are also supported via `python-dotenv`):

```python
from oligo import Iber

connection = Iber()
connection.login("user", "password")
```

Or using environment variables / `.env`:

```python
from oligo import Iber

connection = Iber()
connection.login() # Reads I-DE-USER and I-DE-PASSWORD from environment
```

### Install:

```
Expand Down Expand Up @@ -225,6 +303,44 @@ async def main():
asyncio.run(main())
```

#### Retrieve the hourly billed consumption during a time period (Sync)

```python
from oligo import Iber
from datetime import date, timedelta

connection = Iber()
connection.login("user", "password")

from_date = date.today() - timedelta(days=7)
until_date = date.today() - timedelta(days=1)

consumo = connection.consumption_facturado(from_date, until_date)

print(consumo[:10])
```

#### Retrieve the hourly billed consumption during a time period (Async)

```python
import asyncio
from oligo.asyncio import AsyncIber
from datetime import date, timedelta

async def main():
connection = AsyncIber()
await connection.login("user", "password")

from_date = date.today() - timedelta(days=7)
until_date = date.today() - timedelta(days=1)

consumo = await connection.consumption_facturado(from_date, until_date)

print(consumo[:10])

asyncio.run(main())
```

The values are the consumption in Watt-hours. In this case, we have the data
of one week, which are 7 times 24, 168 values. If we sum and divide by 1000,
we will have the total consumption from one week in kWh.
52 changes: 48 additions & 4 deletions oligo/asyncio/asynciber.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import os

from dotenv import load_dotenv
from deprecated.classic import deprecated

from ..exception import SessionException, ResponseException, NoResponseException, LoginException, \
SelectContractException
from ..exception import (
SessionException,
ResponseException,
NoResponseException,
LoginException,
SelectContractException,
)

try:
import aiohttp
Expand All @@ -11,6 +19,8 @@
from datetime import datetime
from typing import Union, Optional

load_dotenv()

LOGIN_URL = "loginNew/login"
WATTHOURMETER_URL = "escenarioNew/obtenerMedicionOnline/24"
ICP_STATUS_URL = "rearmeICP/consultarEstado"
Expand All @@ -23,6 +33,7 @@
BORRAR_ESCENARIO_URL = "escenarioNew/borrarEscenario/"
OBTENER_PERIODO_URL = "consumoNew/obtenerDatosConsumoPeriodo/fechaInicio/{}00:00:00/fechaFinal/{}00:00:00/"
OBTENER_PERIODO_GENERACION_URL = "consumoNew/obtenerDatosGeneracionPeriodo/fechaInicio/{}00:00:00/fechaFinal/{}00:00:00/"
OBTENER_PERIODO_FACTURADO_URL = "consumoNew/obtenerDatosConsumoFacturado/numFactura/null//fechaDesde//{}00:00:00//fechaHasta//{}23:59:00/true/"


class AsyncIber:
Expand Down Expand Up @@ -59,9 +70,18 @@ async def __request(
raise NoResponseException
return data

async def login(self, user: str, password: str) -> bool:
"""Creates session with your credentials"""
async def login(self, user: str = None, password: str = None) -> bool:
"""Creates session with your credentials.
Reads I-DE-USER and I-DE-PASSWORD from environment if available,
falling back to the provided parameters."""
self.__session = aiohttp.ClientSession()
user = os.getenv("I-DE-USER", user)
password = os.getenv("I-DE-PASSWORD", password)
if not user or not password:
raise LoginException(
user or "unknown",
message="Login failed: user and password are required. Set I-DE-USER and I-DE-PASSWORD environment variables or pass them as arguments.",
)
payload = [
user,
password,
Expand Down Expand Up @@ -197,3 +217,27 @@ async def production(self, start: datetime, end: datetime) -> list:
async def total_consumption(self, start, end) -> float:
data = await self._consumption_raw(start, end)
return float(data["acumulado"])

async def _consumption_facturado_raw(self, start: datetime, end: datetime) -> list:
return await self.__request(
OBTENER_PERIODO_FACTURADO_URL.format(
start.strftime("%d-%m-%Y"), end.strftime("%d-%m-%Y")
)
)

# Get billed consumption data from a time period
#
# start/end: datetime.date objects indicating the time period (both inclusive)
#
# Returns a list of billed consumptions starting at midnight on the start day until 23:00 on the last day.
# Each value is the hourly billed consumption in Wh.
async def consumption_facturado(self, start: datetime, end: datetime) -> list:
data = await self._consumption_facturado_raw(start, end)
return [float(x["valor"]) for x in data["y"]["data"][0] if x]

# Get total billed consumption in Wh (Watt-hour) over a time period
#
# start/end: datetime.date objects indicating the time period (both inclusive)
async def total_consumption_facturado(self, start, end) -> float:
data = await self._consumption_facturado_raw(start, end)
return float(data["acumulado"])
8 changes: 5 additions & 3 deletions oligo/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ def __init__(self, status_code):


class LoginException(IberException):
def __init__(self, username):
super().__init__(f'Unable to log in with user {username}')
def __init__(self, username, message=None):
if message is None:
message = f"Unable to log in with user {username}"
super().__init__(message)


class SessionException(IberException):
def __init__(self):
super().__init__('Session required, use login() method to obtain a session')
super().__init__("Session required, use login() method to obtain a session")


class NoResponseException(IberException):
Expand Down
Loading