-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Nueva clase IoT #70
Nueva clase IoT #70
Changes from 6 commits
843d436
3fa42c5
c8a8655
c1fdf40
1b09c52
7540295
743394f
13046de
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -112,6 +112,10 @@ entities = cbm.get_entities_page(subservice='/energia', auth=auth, type='myType' | |
|
||
# have a look to the retrieved entities | ||
print (json.dumps(entities)) | ||
|
||
#create an iota manager and use it | ||
iotam: tc.iota.iotaManager = tc.iota.iotaManager(endpoint = 'http://<iota_endpoint>:<port>/iot/json', sensor_id='<sensor_id>', api_key='<api_key>') | ||
iotam.send_http(data={"<key_1>": "<value_1>", "<key_2>": "<value_2>"}) | ||
``` | ||
|
||
Ejemplo de uso de Recogida de todos los datos de tipo SupplyPoint con y sin paginación: | ||
|
@@ -225,6 +229,10 @@ with tc.orionStore(cb=cbm, auth=auth, subservice='/energia') as store: | |
# O un store sqlFile | ||
with tc.sqlFileStore(path="inserts.sql", subservice="/energia", namespace="energy") as store: | ||
store(entities) | ||
|
||
# Envío de datos en ráfaga al Agente IoT. | ||
iotam: tc.iota.iotaManager = tc.iota.iotaManager(endpoint = 'http://<iota_endpoint>:<port>/iot/json', sensor_id='<sensor_id>', api_key='<api_key>', sleep_send_batch='<time_sleep>') | ||
iotam.send_batch_http(data=[{"<key_1>": "<value_1>", "<key_2>": "<value_2>"}, {"<key_3>": "<value_3>", "<key_4>": "<value_4>"}]) | ||
``` | ||
|
||
## Funciones disponibles en la librería | ||
|
@@ -343,6 +351,24 @@ La librería está creada con diferentes clases dependiendo de la funcionalidad | |
- Reemplaza todos los espacios en blanco consecutivos por el carácter de reemplazo. | ||
- NOTA: Esta función no recorta la longitud de la cadena devuelta a 256 caracteres, porque el llamante puede querer conservar la cadena entera para por ejemplo guardarla en algún otro atributo, antes de truncarla. | ||
|
||
- Clase `iotaManager`: En esta clase están las funciones relacionadas con el agente IoT. | ||
|
||
- `__init__`: constructor de objetos de la clase. | ||
- :param obligatorio `sensor_id`: El ID del sensor. | ||
- :param obligatorio `api_key`: La API key correspondiente al sensor. | ||
- :param obligatorio `endpoint`: La URL del servicio al que se le quiere enviar los datos. | ||
- :param opcional `sleep_send_batch`: Es el tiempo de espera entre cada envío de datos en segundos. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Siendo un parámetro opcional, indicar el default cuando no se especifica nada. |
||
- `send_http`: Función que envía un archivo en formato JSON al agente IoT por petición HTTP. | ||
- :param obligatorio: `data`: Datos a enviar. La estructura debe tener pares de elementos clave-valor (diccionario). | ||
- :raises [TypeError](https://docs.python.org/3/library/exceptions.html#TypeError): Se lanza cuando el tipo de dato es incorrecto. | ||
- :raises [ConnectionError](https://docs.python.org/3/library/exceptions.html#ConnectionError): Se lanza cuando no puede conectarse al servidor. | ||
- :raises FetchError: se lanza cuando se produce un error en en la solicitud HTTP. | ||
- :return: True si el envío de datos es exitoso. | ||
- `send_batch_http`: Función que envía un conjunto de datos en formato JSON al agente IoT por petición HTTP. | ||
- :param obligatorio: `data`: Datos a enviar. Puede ser una lista de diccionarios o un DataFrame. | ||
- :raises SendBatchError: Se levanta cuando se produce una excepción dentro de `send_http`. Atrapa la excepción original y se guarda y se imprime el índice donde se produjo el error. | ||
|
||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Incluir en el changelog (justo por encima de la marca de versión 0.9.0) un par de entradas que describan los cambios incluidos en esta PR. Por ejemplo:
|
||
Algunos ejemplos de uso de `normalizer`: | ||
|
||
``` | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
#!/usr/bin/env python | ||
# -*- coding: utf-8 -*- | ||
# | ||
# Copyright 2022 Telefónica Soluciones de Informática y Comunicaciones de España, S.A.U. | ||
# | ||
# This file is part of tc_etl_lib | ||
# | ||
# tc_etl_lib is free software: you can redistribute it and/or | ||
# modify it under the terms of the GNU Affero General Public License as | ||
# published by the Free Software Foundation, either version 3 of the | ||
# License, or (at your option) any later version. | ||
# | ||
# tc_etl_lib is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero | ||
# General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Affero General Public License | ||
# along with IoT orchestrator. If not, see http://www.gnu.org/licenses/. | ||
|
||
""" | ||
Exceptions handling for Python. | ||
""" | ||
|
||
import requests | ||
from typing import Any, Optional | ||
|
||
class FetchError(Exception): | ||
""" | ||
FetchError encapsulates all parameters of an HTTP request and the erroneous response. | ||
""" | ||
|
||
response: requests.Response | ||
method: str | ||
url: str | ||
params: Optional[Any] = None | ||
headers: Optional[Any] = None | ||
body: Optional[Any] = None | ||
|
||
def __init__(self, response: requests.Response, method: str, url: str, params: Optional[Any] = None, headers: Optional[Any] = None, body: Optional[Any] = None): | ||
"""Constructor for FetchError class.""" | ||
self.response = response | ||
self.method = method | ||
self.url = url | ||
self.params = params | ||
self.headers = headers | ||
self.body = body | ||
|
||
def __str__(self) -> str: | ||
return f"Failed to {self.method} {self.url} (headers: {self.headers}, params: {self.params}, body: {self.body}): [{self.response.status_code}] {self.response.text}" |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
#!/usr/bin/env python | ||
# -*- coding: utf-8 -*- | ||
# | ||
# Copyright 2022 Telefónica Soluciones de Informática y Comunicaciones de España, S.A.U. | ||
# | ||
# This file is part of tc_etl_lib | ||
# | ||
# tc_etl_lib is free software: you can redistribute it and/or | ||
# modify it under the terms of the GNU Affero General Public License as | ||
# published by the Free Software Foundation, either version 3 of the | ||
# License, or (at your option) any later version. | ||
# | ||
# tc_etl_lib is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero | ||
# General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Affero General Public License | ||
# along with IoT orchestrator. If not, see http://www.gnu.org/licenses/. | ||
|
||
''' | ||
IoT Agent routines for Python: | ||
- iotaManager.send_http | ||
- iotaManager.send_batch_http | ||
''' | ||
|
||
from . import exceptions | ||
import pandas as pd | ||
import requests | ||
import tc_etl_lib as tc | ||
import time | ||
from typing import Iterable, Optional, Union | ||
|
||
class SendBatchError(Exception): | ||
"SendBatchError is a class that can handle exceptions." | ||
def __init__(self, message, original_exception=None, index=None): | ||
super().__init__(message) | ||
self.original_exception = original_exception | ||
self.index = index | ||
|
||
class iotaManager: | ||
"""IoT Agent Manager. | ||
|
||
endpoint: define service endpoint iota (example: https://<service>:<port>). | ||
sensor_id: sensor ID. | ||
api_key: API key of the corresponding sensor. | ||
sleep_send_batch: time sleep in seconds (default: 0). | ||
""" | ||
|
||
endpoint: str | ||
sensor_id: str | ||
api_key: str | ||
sleep_send_batch: float | ||
|
||
def __init__(self, endpoint: str, sensor_id: str, api_key: str, sleep_send_batch: float = 0): | ||
self.endpoint = endpoint | ||
self.sensor_id = sensor_id | ||
self.api_key = api_key | ||
self.sleep_send_batch = sleep_send_batch | ||
|
||
def send_http(self, | ||
data: dict) -> Union[None, bool]: | ||
|
||
if not isinstance(data, dict): | ||
raise TypeError("The 'data' parameter should be a dictionary with key-value pairs.") | ||
|
||
params = { | ||
'i': self.sensor_id, | ||
'k': self.api_key | ||
} | ||
headers = { | ||
"Content-Type": "application/json" | ||
} | ||
|
||
try: | ||
resp = requests.post(url=self.endpoint, json=data, params=params, headers=headers) | ||
if resp.status_code == 200: | ||
return True | ||
else: | ||
raise exceptions.FetchError( | ||
response=resp, | ||
method="POST", | ||
url=self.endpoint, | ||
params=params, | ||
headers=headers) | ||
except requests.exceptions.ConnectionError as e: | ||
raise e | ||
|
||
def send_batch_http(self, data: Iterable) -> Union[None, bool]: | ||
|
||
if isinstance(data, pd.DataFrame): | ||
# Convert each row of the DataFrame to a dictionary. | ||
for i, row in data.iterrows(): | ||
try: | ||
self.send_http(row.to_dict()) | ||
time.sleep(self.sleep_send_batch) | ||
except Exception as e: | ||
raise SendBatchError(f"send_batch_http error. Row that caused the error: {i}\nError detail: {str(e)}", original_exception=e, index=i) from e | ||
else: | ||
for i, dictionary in enumerate(data): | ||
try: | ||
self.send_http(dictionary) | ||
time.sleep(self.sleep_send_batch) | ||
except Exception as e: | ||
raise SendBatchError(f"send_batch_http error. Index where the error occurred: {i}\nError detail: {str(e)}", original_exception=e, index=i) from e | ||
return True |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Creo que sería mejor dejar los ejemplos que ya hay como están y usar los dos nuevos fragmentos para generar un ejemplo separado independiente.