Skip to content
Merged
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`:

```python
from oligo import Iber

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

O usando variables de entorno:

```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)
Comment thread
hectorespert marked this conversation as resolved.

```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.billed_consumption(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.billed_consumption(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:

```python
from oligo import Iber

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

Or using environment variables:

```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.billed_consumption(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.billed_consumption(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.
66 changes: 62 additions & 4 deletions oligo/asyncio/asynciber.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import os

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 @@ -23,6 +30,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,8 +67,26 @@ 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: Optional[str] = None, password: Optional[str] = None
) -> bool:
"""Creates session with your credentials.

If ``user`` or ``password`` are not provided, their values are read
from the ``I_DE_USER`` and ``I_DE_PASSWORD`` environment variables.
Explicit arguments take precedence over environment variables.
"""
user = user or os.getenv("I_DE_USER")
password = password or os.getenv("I_DE_PASSWORD")
Comment on lines +79 to +80
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."
),
)
self.__session = aiohttp.ClientSession()
payload = [
user,
Expand Down Expand Up @@ -197,3 +223,35 @@ 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 billed_consumption(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_billed_consumption(self, start, end) -> float:
data = await self._consumption_facturado_raw(start, end)
return float(data["acumulado"])

@deprecated("Use 'billed_consumption' method instead")
async def consumption_facturado(self, start: datetime, end: datetime) -> list:
return await self.billed_consumption(start, end)

@deprecated("Use 'total_billed_consumption' method instead")
async def total_consumption_facturado(self, start, end) -> float:
return await self.total_billed_consumption(start, end)
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