From 021b7e70af19c127d231d628675d6da68afd9c69 Mon Sep 17 00:00:00 2001 From: Emanuele Trabattoni Date: Sun, 1 Jun 2025 10:14:46 +0200 Subject: [PATCH] Refactoring funzioni di utility --- pyutils/utils.py | 37 ++++++++++++++++++++ routermon/routermon.py | 44 ++++++------------------ upsmon/ups.py | 78 +++++++++++++++++++++++------------------- 3 files changed, 91 insertions(+), 68 deletions(-) create mode 100644 pyutils/utils.py diff --git a/pyutils/utils.py b/pyutils/utils.py new file mode 100644 index 0000000..d90ec35 --- /dev/null +++ b/pyutils/utils.py @@ -0,0 +1,37 @@ +import signal +from logging import Logger +from influxdb_client_3 import Point + +class SignalHandler: + running: bool + logger: Logger + + def __init__(self, logger): + self.running: bool = True + self.logger: Logger = logger + signal.signal(signal.SIGINT, self._handle_sigint) + signal.signal(signal.SIGTERM, self._handle_sigint) + + def _handle_sigint(self, signum, frame): + self.logger.info(f"Received SIGNAL: {signal.strsignal(signum)}") + self.running = False + +def dict2Point(measurement: str, fields: dict, tags: dict | None = None) -> Point: + p = Point(measurement) + for k,v in fields.items(): + p.field(k,v) + if tags: + for k,v in tags.items(): + p.tag(k,v) + return p + +def convertInt(d: dict) -> dict: + for k,v in d.items(): + if str.isdecimal(v): + d[k] = int(v) + return d + +def convertIntList(l: list[dict]) -> list[dict]: + for n,d in enumerate(l): + l[n] = convertInt(d) + return l \ No newline at end of file diff --git a/routermon/routermon.py b/routermon/routermon.py index 85218c4..e18f951 100644 --- a/routermon/routermon.py +++ b/routermon/routermon.py @@ -2,42 +2,22 @@ import os import sys import time import logging -import signal import json import routeros_api +from pyutils.utils import * from influxdb_client_3 import InfluxDBClient3, Point # Get environment variables env = dict(os.environ) LOGGER: logging.Logger -class SignalHandler: - running: bool - - def __init__(self): - self.running: bool = True - signal.signal(signal.SIGINT, self._handle_sigint) - signal.signal(signal.SIGTERM, self._handle_sigint) - - def _handle_sigint(self, signum, frame): - self.running = False - -def convert_int(d: dict) -> dict: - for k,v in d.items(): - if str.isdecimal(v): - d[k] = int(v) - return d - -def convert_int_list(l: list[dict]) -> list[dict]: - for n,d in enumerate(l): - l[n] = convert_int(d) - return l - - +################## +###### MAIN ###### +################## def main(): INTERVAL = int(env['INTERVAL']) - # Init InfluxDB + # Init InfluxDB-v3 Client write_client = InfluxDBClient3(host=env['INFLUXDB_URL'], token=env['INFLUXDB_TOKEN'], database=env['INFLUXDB_DATABASE']) @@ -52,14 +32,14 @@ def main(): ########## MAIN LOOP ######### ############################## last: float = 0 - handler: SignalHandler = SignalHandler() - if_stats_old = convert_int_list(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})) + handler: SignalHandler = SignalHandler(LOGGER) + if_stats_old = convertIntList(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})) while handler.running: try: now:float = time.time() if_points: list[Point] = [] - if_stats: list[dict] = convert_int_list(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})) - hw_stats: dict[str,str] = convert_int(api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load,total-memory,free-memory'})[0]) + if_stats: list[dict] = convertIntList(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})) + hw_stats: dict[str,str] = convertInt(api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load,total-memory,free-memory'})[0]) # Calcolo della velocita' interfaccia a ogni ciclo for n, d in enumerate(if_stats): if_stats[n]['rx-rate'] = int((if_stats[n]['rx-bytes']-if_stats_old[n]['rx-bytes'])/(now-last)) @@ -73,10 +53,7 @@ def main(): write_client.write(record=if_points) # Risorse del router - hw_point = Point('resources') - for k,v in hw_stats.items(): - hw_point.field(k,v) - write_client.write(record=hw_point) + write_client.write(record=dict2Point('resources', hw_stats)) # Salvo ultimo punto per il giro successivo if_stats_old = if_stats @@ -118,6 +95,7 @@ if __name__ == "__main__": LOGGER.addHandler(cl) LOGGER.warning(f"Routermon started on: {time.asctime()}") + LOGGER.info(f"Routermon BUILD: {env.get("VER", "Test")}") while main(): LOGGER.error("Main thread exited unexpectedly") diff --git a/upsmon/ups.py b/upsmon/ups.py index cf5fa86..02580d7 100644 --- a/upsmon/ups.py +++ b/upsmon/ups.py @@ -4,25 +4,15 @@ import time import string import serial import logging -import signal import json -from influxdb_client_3 import InfluxDBClient3, Point +from pyutils.utils import * +from influxdb_client_3 import InfluxDBClient3 # Get environment variables env = dict(os.environ) LOGGER: logging.Logger - -class SignalHandler: - running: bool - - def __init__(self): - self.running: bool = True - signal.signal(signal.SIGINT, self._handle_sigint) - signal.signal(signal.SIGTERM, self._handle_sigint) - - def _handle_sigint(self, signum, frame): - self.running = False +GIT_HASH: str = "HHHHHHHHH" def send(port: serial.Serial, d: str): port.write((d+'\r').encode('ascii')) @@ -49,43 +39,60 @@ def bruteforceCommands(port: serial.Serial): send(port, d) receive(port, d) + +################## +###### MAIN ###### +################## def main(): INTERVAL = int(env['INTERVAL']) - LOGGER.debug(json.dumps(env, indent=2)) - run: SignalHandler = SignalHandler() - port = serial.Serial(port=env['PORT'], baudrate=int(env['BAUD']), bytesize=8, parity='N', stopbits=1) - write_client = InfluxDBClient3(host=env['INFLUXDB_URL'], - token=env['INFLUXDB_TOKEN'], - database=env['INFLUXDB_DATABASE']) + UPS_COMMAND = "Q1" + try: + # Init InfluxDB-v3 Client + write_client = InfluxDBClient3(host=env['INFLUXDB_URL'], + token=env['INFLUXDB_TOKEN'], + database=env['INFLUXDB_DATABASE']) + # Init Serial port + port = serial.Serial(port=env['PORT'], baudrate=int(env['BAUD']), bytesize=8, parity='N', stopbits=1) + except Exception as e: + LOGGER.error(e) + return 0 + finally: + LOGGER.info(f"InfluxDB Connected: [{env['INFLUXDB_URL']}/{env['INFLUXDB_DATABASE']}]") + LOGGER.info(f"Serial Port Open: [{env['PORT']}]") + + ############################## + ########## MAIN LOOP ######### + ############################## + run: SignalHandler = SignalHandler(LOGGER) while run.running: try: - send(port, "Q1") - data = receive(port, "Q1").lstrip('(').split() - if len(data) < 8: - LOGGER.error(f"Incomplete data: {data}") + send(port, UPS_COMMAND) + raw_data = receive(port, UPS_COMMAND).lstrip('(').split() + if len(raw_data) < 8: + LOGGER.error(f"Incomplete data: {raw_data}") continue values = { - 'inV': float(data[0]), - 'outV': float(data[2]), - 'loadPercent': float(data[3]), - 'lineFreq': float(data[4]), - 'timeLeft': float(data[5]), - 'onBatt': True if str(data[7]).startswith('1') else False, - 'onLine': True if str(data[7]).endswith('1') else False, + 'inV': float(raw_data[0]), + 'outV': float(raw_data[2]), + 'loadPercent': float(raw_data[3]), + 'lineFreq': float(raw_data[4]), + 'timeLeft': float(raw_data[5]), + 'onBatt': True if str(raw_data[7]).startswith('1') else False, + 'onLine': True if str(raw_data[7]).endswith('1') else False, } LOGGER.debug(f"UPS Status: \n{json.dumps(values, indent=2)}") if values['onBatt']: LOGGER.info(f"OnBattery\n{json.dumps(values,indent=2)}") - p = Point('ups') - for k,v in values.items(): - p.field(k,v) - write_client.write(record=p) + write_client.write(record=dict2Point('ups', values)) time.sleep(INTERVAL) except Exception as e: print(f"Unexpected exception: [{e}]") return 1 +############################## +###### END MAIN LOOP ######### +############################## port.close() - + return 0 if __name__ == "__main__": # Logger Constants @@ -112,6 +119,7 @@ if __name__ == "__main__": LOGGER.addHandler(cl) LOGGER.warning(f"UPSmon started on: {time.asctime()}") + LOGGER.info(f"UPSmon BUILD: {env.get("VER", "Test")}") while main(): LOGGER.error("Main thread exited unexpectedly")