Skip to content

Commit

Permalink
add main as cli to run executables more easily
Browse files Browse the repository at this point in the history
  • Loading branch information
fjpacheco committed Jun 15, 2024
1 parent 11765ca commit d7ff087
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 69 deletions.
104 changes: 35 additions & 69 deletions src/main.py
Original file line number Diff line number Diff line change
@@ -1,71 +1,34 @@
'''
Leer archivo de configuracion
Cada N segundos:
- Generar un paquete de datos
- Decidir si el paquete es apto para ser enviado
- Si no es apto, descartar y esperar al siguiente.
- Agregar timestamp y device_id al paquete.
- Enviar paquete a la queue.
'''

import time
import logging
import json
import os
from common.middleware import Middleware

from data_packet import generate_data, create_packet, data_has_changed


def simulate_packets(config):
middleware = Middleware()
queue_name = os.environ.get("QUEUE_NAME")
middleware.create_queue(queue_name)
last_sent_packet = None
current_packet = None
while True:
try:
temperature, humidity, light, watering = generate_data()
current_packet = create_packet(temperature, humidity, light,
watering)

if not current_packet or not data_has_changed(
current_packet,
last_sent_packet,
config["deviations"]
):
continue
middleware.send_message(queue_name, json.dumps(current_packet))
logging.info(f"Packet sent: {current_packet}")
last_sent_packet = current_packet

except Exception as err:
logging.warning(f"{err}")
finally:
print(current_packet)
time.sleep(config["packet_period"])


def read_config_file(path):
try:
with open(path, 'r') as file:
config_data = json.load(file)
return config_data
except FileNotFoundError:
logging.error(f"Config file not found at: {path}")
raise
except json.JSONDecodeError as json_err:
logging.error(f"Error decoding config file: {json_err}")
raise


def main():
logging_level = os.environ.get("LOGGING_LEVEL")
initialize_log(logging_level)
config_path = "config.json"
config = read_config_file(config_path)
simulate_packets(config)
import typer
import logging
from dotenv import load_dotenv
from typing import Optional
from simulator import execute_simulator
from simple_package import execute_simple_package

app = typer.Typer()


@app.command("run-simulator")
def simulator(id_device: Optional[str] = typer.Option(None, "--id_device", "-i")):
execute_simulator(id_device)


@app.command("simple-package")
def simple_package(
id_device: str = typer.Option(..., "--id_device", "-i"),
temperature: Optional[float] = typer.Option(None, "--temperature", "-t"),
light: Optional[float] = typer.Option(None, "--light", "-l"),
humidity: Optional[int] = typer.Option(None, "--humidity", "-h"),
watering: Optional[int] = typer.Option(None, "--watering", "-w")
):
execute_simple_package(
id_device=id_device,
temperature=temperature,
light=light,
humidity=humidity,
watering=watering
)


def initialize_log(logging_level):
Expand All @@ -80,8 +43,11 @@ def initialize_log(logging_level):
level=logging_level,
datefmt='%Y-%m-%d %H:%M:%S',
)
logging.getLogger("pika").setLevel(logging.WARNING)
logging.getLogger("simulator").setLevel(logging_level)


if __name__ == '__main__':
main()
load_dotenv()
logging_level = os.environ.get("LOGGING_LEVEL", "DEBUG")
initialize_log(logging_level)
app()
59 changes: 59 additions & 0 deletions src/simulator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import time
import logging
import json
import os
from typing import Optional
from common.middleware import Middleware
from data_packet import generate_data, create_packet, data_has_changed


def simulate_packets(config, id_device: Optional[str]):
middleware = Middleware()
topic_name = os.environ.get("MQTT_TOPIC", "measurements")
middleware.connect()
middleware.run()
last_sent_packet = None
current_packet = None
while True:
try:
temperature, humidity, light, watering = generate_data()
current_packet = create_packet(temperature, humidity, light,
watering, id_device)

if not current_packet or not data_has_changed(
current_packet,
last_sent_packet,
config["deviations"]
):
continue
middleware.send_message(topic_name, json.dumps(current_packet))
logging.info(f"Packet sent: {current_packet}")
last_sent_packet = current_packet

except Exception as err:
logging.warning(f"{err}")
finally:
print(current_packet)
time.sleep(config["packet_period"])


def read_config_file(path):
try:
with open(path, 'r') as file:
config_data = json.load(file)
return config_data
except FileNotFoundError:
logging.error(f"Config file not found at: {path}")
raise
except json.JSONDecodeError as json_err:
logging.error(f"Error decoding config file: {json_err}")
raise


def execute_simulator(id_device: Optional[str]):
if id_device is not None:
logging.info(f"Simulating packets for device: {id_device}")

config_path = "config.json"
config = read_config_file(config_path)
simulate_packets(config, id_device)

0 comments on commit d7ff087

Please sign in to comment.