-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add main as cli to run executables more easily
- Loading branch information
Showing
2 changed files
with
94 additions
and
69 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |