Refactoring funzioni di utility
This commit is contained in:
37
pyutils/utils.py
Normal file
37
pyutils/utils.py
Normal file
@@ -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
|
||||||
@@ -2,42 +2,22 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
import logging
|
import logging
|
||||||
import signal
|
|
||||||
import json
|
import json
|
||||||
import routeros_api
|
import routeros_api
|
||||||
|
|
||||||
|
from pyutils.utils import *
|
||||||
from influxdb_client_3 import InfluxDBClient3, Point
|
from influxdb_client_3 import InfluxDBClient3, Point
|
||||||
|
|
||||||
# Get environment variables
|
# Get environment variables
|
||||||
env = dict(os.environ)
|
env = dict(os.environ)
|
||||||
LOGGER: logging.Logger
|
LOGGER: logging.Logger
|
||||||
|
|
||||||
class SignalHandler:
|
##################
|
||||||
running: bool
|
###### MAIN ######
|
||||||
|
##################
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
INTERVAL = int(env['INTERVAL'])
|
INTERVAL = int(env['INTERVAL'])
|
||||||
# Init InfluxDB
|
# Init InfluxDB-v3 Client
|
||||||
write_client = InfluxDBClient3(host=env['INFLUXDB_URL'],
|
write_client = InfluxDBClient3(host=env['INFLUXDB_URL'],
|
||||||
token=env['INFLUXDB_TOKEN'],
|
token=env['INFLUXDB_TOKEN'],
|
||||||
database=env['INFLUXDB_DATABASE'])
|
database=env['INFLUXDB_DATABASE'])
|
||||||
@@ -52,14 +32,14 @@ def main():
|
|||||||
########## MAIN LOOP #########
|
########## MAIN LOOP #########
|
||||||
##############################
|
##############################
|
||||||
last: float = 0
|
last: float = 0
|
||||||
handler: SignalHandler = SignalHandler()
|
handler: SignalHandler = SignalHandler(LOGGER)
|
||||||
if_stats_old = convert_int_list(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'}))
|
if_stats_old = convertIntList(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'}))
|
||||||
while handler.running:
|
while handler.running:
|
||||||
try:
|
try:
|
||||||
now:float = time.time()
|
now:float = time.time()
|
||||||
if_points: list[Point] = []
|
if_points: list[Point] = []
|
||||||
if_stats: list[dict] = convert_int_list(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'}))
|
if_stats: list[dict] = convertIntList(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])
|
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
|
# Calcolo della velocita' interfaccia a ogni ciclo
|
||||||
for n, d in enumerate(if_stats):
|
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))
|
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)
|
write_client.write(record=if_points)
|
||||||
|
|
||||||
# Risorse del router
|
# Risorse del router
|
||||||
hw_point = Point('resources')
|
write_client.write(record=dict2Point('resources', hw_stats))
|
||||||
for k,v in hw_stats.items():
|
|
||||||
hw_point.field(k,v)
|
|
||||||
write_client.write(record=hw_point)
|
|
||||||
|
|
||||||
# Salvo ultimo punto per il giro successivo
|
# Salvo ultimo punto per il giro successivo
|
||||||
if_stats_old = if_stats
|
if_stats_old = if_stats
|
||||||
@@ -118,6 +95,7 @@ if __name__ == "__main__":
|
|||||||
LOGGER.addHandler(cl)
|
LOGGER.addHandler(cl)
|
||||||
|
|
||||||
LOGGER.warning(f"Routermon started on: {time.asctime()}")
|
LOGGER.warning(f"Routermon started on: {time.asctime()}")
|
||||||
|
LOGGER.info(f"Routermon BUILD: {env.get("VER", "Test")}")
|
||||||
|
|
||||||
while main():
|
while main():
|
||||||
LOGGER.error("Main thread exited unexpectedly")
|
LOGGER.error("Main thread exited unexpectedly")
|
||||||
|
|||||||
@@ -4,25 +4,15 @@ import time
|
|||||||
import string
|
import string
|
||||||
import serial
|
import serial
|
||||||
import logging
|
import logging
|
||||||
import signal
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from influxdb_client_3 import InfluxDBClient3, Point
|
from pyutils.utils import *
|
||||||
|
from influxdb_client_3 import InfluxDBClient3
|
||||||
|
|
||||||
# Get environment variables
|
# Get environment variables
|
||||||
env = dict(os.environ)
|
env = dict(os.environ)
|
||||||
LOGGER: logging.Logger
|
LOGGER: logging.Logger
|
||||||
|
GIT_HASH: str = "HHHHHHHHH"
|
||||||
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 send(port: serial.Serial, d: str):
|
def send(port: serial.Serial, d: str):
|
||||||
port.write((d+'\r').encode('ascii'))
|
port.write((d+'\r').encode('ascii'))
|
||||||
@@ -49,43 +39,60 @@ def bruteforceCommands(port: serial.Serial):
|
|||||||
send(port, d)
|
send(port, d)
|
||||||
receive(port, d)
|
receive(port, d)
|
||||||
|
|
||||||
|
|
||||||
|
##################
|
||||||
|
###### MAIN ######
|
||||||
|
##################
|
||||||
def main():
|
def main():
|
||||||
INTERVAL = int(env['INTERVAL'])
|
INTERVAL = int(env['INTERVAL'])
|
||||||
LOGGER.debug(json.dumps(env, indent=2))
|
UPS_COMMAND = "Q1"
|
||||||
run: SignalHandler = SignalHandler()
|
try:
|
||||||
port = serial.Serial(port=env['PORT'], baudrate=int(env['BAUD']), bytesize=8, parity='N', stopbits=1)
|
# Init InfluxDB-v3 Client
|
||||||
write_client = InfluxDBClient3(host=env['INFLUXDB_URL'],
|
write_client = InfluxDBClient3(host=env['INFLUXDB_URL'],
|
||||||
token=env['INFLUXDB_TOKEN'],
|
token=env['INFLUXDB_TOKEN'],
|
||||||
database=env['INFLUXDB_DATABASE'])
|
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:
|
while run.running:
|
||||||
try:
|
try:
|
||||||
send(port, "Q1")
|
send(port, UPS_COMMAND)
|
||||||
data = receive(port, "Q1").lstrip('(').split()
|
raw_data = receive(port, UPS_COMMAND).lstrip('(').split()
|
||||||
if len(data) < 8:
|
if len(raw_data) < 8:
|
||||||
LOGGER.error(f"Incomplete data: {data}")
|
LOGGER.error(f"Incomplete data: {raw_data}")
|
||||||
continue
|
continue
|
||||||
values = {
|
values = {
|
||||||
'inV': float(data[0]),
|
'inV': float(raw_data[0]),
|
||||||
'outV': float(data[2]),
|
'outV': float(raw_data[2]),
|
||||||
'loadPercent': float(data[3]),
|
'loadPercent': float(raw_data[3]),
|
||||||
'lineFreq': float(data[4]),
|
'lineFreq': float(raw_data[4]),
|
||||||
'timeLeft': float(data[5]),
|
'timeLeft': float(raw_data[5]),
|
||||||
'onBatt': True if str(data[7]).startswith('1') else False,
|
'onBatt': True if str(raw_data[7]).startswith('1') else False,
|
||||||
'onLine': True if str(data[7]).endswith('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)}")
|
LOGGER.debug(f"UPS Status: \n{json.dumps(values, indent=2)}")
|
||||||
if values['onBatt']:
|
if values['onBatt']:
|
||||||
LOGGER.info(f"OnBattery\n{json.dumps(values,indent=2)}")
|
LOGGER.info(f"OnBattery\n{json.dumps(values,indent=2)}")
|
||||||
p = Point('ups')
|
write_client.write(record=dict2Point('ups', values))
|
||||||
for k,v in values.items():
|
|
||||||
p.field(k,v)
|
|
||||||
write_client.write(record=p)
|
|
||||||
time.sleep(INTERVAL)
|
time.sleep(INTERVAL)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Unexpected exception: [{e}]")
|
print(f"Unexpected exception: [{e}]")
|
||||||
return 1
|
return 1
|
||||||
|
##############################
|
||||||
|
###### END MAIN LOOP #########
|
||||||
|
##############################
|
||||||
port.close()
|
port.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# Logger Constants
|
# Logger Constants
|
||||||
@@ -112,6 +119,7 @@ if __name__ == "__main__":
|
|||||||
LOGGER.addHandler(cl)
|
LOGGER.addHandler(cl)
|
||||||
|
|
||||||
LOGGER.warning(f"UPSmon started on: {time.asctime()}")
|
LOGGER.warning(f"UPSmon started on: {time.asctime()}")
|
||||||
|
LOGGER.info(f"UPSmon BUILD: {env.get("VER", "Test")}")
|
||||||
|
|
||||||
while main():
|
while main():
|
||||||
LOGGER.error("Main thread exited unexpectedly")
|
LOGGER.error("Main thread exited unexpectedly")
|
||||||
|
|||||||
Reference in New Issue
Block a user