Merge branch 'influxdb3'

This commit is contained in:
2025-10-02 22:27:49 +02:00
parent 5f34f3169a
commit 493cfb1b88
10 changed files with 369 additions and 172 deletions

16
.vscode/launch.json vendored
View File

@@ -9,10 +9,9 @@
"console": "integratedTerminal", "console": "integratedTerminal",
"env": { "env": {
"INTERVAL" : "5", "INTERVAL" : "5",
"INFLUXDB_TOKEN":"b46xoZRVsQvyGnv8TVMmTDmxT8LZZsi7O_u776MHIxiE9CPh7yHi0iHMOerUT5o1y65MMxeKKA7S-ijQ3elK-g==", "INFLUXDB_TOKEN":"apiv3_tbEpA8JmIRTfr8Wbw9npD79BcMlFsnV4_jhdt-CdUP53Mos61KBODGaggl2g5oKZZvZrZu3e6mpob6zorhEdbg",
"INFLUXDB_URL" : "http://localhost:8085", "INFLUXDB_URL" : "http://edelweiss-srv:8181",
"INFLUXDB_ORG" : "edelweiss", "INFLUXDB_DATABASE" : "edelweiss",
"INFLUXDB_BUCKET" : "theatre",
"MIKROTIK_IP": "192.168.31.1", "MIKROTIK_IP": "192.168.31.1",
"MIKROTIK_USER": "service", "MIKROTIK_USER": "service",
"MIKROTIK_PASSWORD": "dataservice", "MIKROTIK_PASSWORD": "dataservice",
@@ -29,11 +28,10 @@
"console": "integratedTerminal", "console": "integratedTerminal",
"env": { "env": {
"INTERVAL" : "5", "INTERVAL" : "5",
"INFLUXDB_TOKEN":"rg5dZrBHQxJTH4Etq2jmDduggCC28QaWcua0VVvW4hjsEVhy_JUpVhcyg-aLAbM-TXv92pTB7IGJlyAPvi7Kvw==", "INFLUXDB_TOKEN":"apiv3_tbEpA8JmIRTfr8Wbw9npD79BcMlFsnV4_jhdt-CdUP53Mos61KBODGaggl2g5oKZZvZrZu3e6mpob6zorhEdbg",
"INFLUXDB_URL" : "http://edelweiss-srv:4567", "INFLUXDB_URL" : "http://edelweiss-srv:8181",
"INFLUXDB_ORG" : "edelweiss", "INFLUXDB_DATABASE" : "edelweiss",
"INFLUXDB_BUCKET" : "ups", "PORT": "/dev/ttyS0",
"PORT": "/dev/ttyUSB1",
"BAUD": "2400", "BAUD": "2400",
"LOG_FILE": "/tmp/upsmon.log", "LOG_FILE": "/tmp/upsmon.log",
"LOG_FILE_LVL": "WARNING", "LOG_FILE_LVL": "WARNING",

19
docker/build.sh Executable file
View File

@@ -0,0 +1,19 @@
#!/bin/bash
GIT_HASH=$(git rev-parse --short HEAD)
docker-compose stop routermon
docker-compose stop upsmon
docker container prune
echo "Building UPSmon"
cp ../pyutils/utils.py ../upsmon/
docker build --build-arg BUILD_VER=${GIT_HASH} -f ../upsmon/upsmon.Dockerfile -t upsmon:influx3 ../upsmon
rm ../upsmon/utils.py
echo "Building Routermon"
cp ../pyutils/utils.py ../routermon/
docker build --build-arg BUILD_VER=${GIT_HASH} -f ../routermon/routermon.Dockerfile -t routermon:influx3 ../routermon
rm ../routermon/utils.py
docker-compose up -d

View File

@@ -1,17 +1,25 @@
services: services:
influxdb2: influxdb3:
image: influxdb:2-alpine image: influxdb:3-core
container_name: edx-influxdb container_name: edx-influxdb3
restart: unless-stopped restart: unless-stopped
ports: ports:
- 8086:8086 - 8181:8181
command:
- influxdb3
- serve
- --node-id=influxb-node0
- --object-store=file
- --data-dir=/var/lib/influxdb3
volumes: volumes:
- type: volume - type: volume
source: influxdb2-data source: influxdb3-data
target: /var/lib/influxdb2 target: /var/lib/influxdb3
- type: volume logging:
source: influxdb2-config driver: "json-file"
target: /etc/influxdb2 options:
max-size: "10m"
max-file: "5"
grafana: grafana:
image: grafana/grafana:latest image: grafana/grafana:latest
@@ -22,40 +30,53 @@ services:
volumes: volumes:
- grafana-data:/var/lib/grafana - grafana-data:/var/lib/grafana
depends_on: depends_on:
- influxdb2 - influxdb3
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
upsmon: upsmon:
image: upsmon:latest image: upsmon:influx3
container_name: edx-upsmon container_name: edx-upsmon
restart: unless-stopped restart: unless-stopped
depends_on: depends_on:
- influxdb2 - influxdb3
devices: devices:
- /dev/ttyUSB1:/dev/ttyUSB1 - /dev/ttyS0:/dev/ttyS0
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
environment: environment:
- INTERVAL=5 - INTERVAL=5
- INFLUXDB_TOKEN=b46xoZRVsQvyGnv8TVMmTDmxT8LZZsi7O_u776MHIxiE9CPh7yHi0iHMOerUT5o1y65MMxeKKA7S-ijQ3elK-g== - INFLUXDB_TOKEN=apiv3_tbEpA8JmIRTfr8Wbw9npD79BcMlFsnV4_jhdt-CdUP53Mos61KBODGaggl2g5oKZZvZrZu3e6mpob6zorhEdbg
- INFLUXDB_URL=http://influxdb2:8086 - INFLUXDB_URL=http://influxdb3:8181
- INFLUXDB_ORG=edelweiss - INFLUXDB_DATABASE=edelweiss
- INFLUXDB_BUCKET=theatre - PORT=/dev/ttyS0
- PORT=/dev/ttyUSB1
- BAUD=2400 - BAUD=2400
- LOG_FILE=/tmp/upsmon.log - LOG_FILE=/tmp/upsmon.log
- LOG_FILE_LVL=WARNING - LOG_FILE_LVL=WARNING
- LOG_CLI_LVL=INFO - LOG_CLI_LVL=INFO
routermon: routermon:
image: routermon:latest image: routermon:influx3
container_name: edx-routermon container_name: edx-routermon
restart: unless-stopped restart: unless-stopped
depends_on: depends_on:
- influxdb2 - influxdb3
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "5"
environment: environment:
- INTERVAL=5 - INTERVAL=5
- INFLUXDB_TOKEN=b46xoZRVsQvyGnv8TVMmTDmxT8LZZsi7O_u776MHIxiE9CPh7yHi0iHMOerUT5o1y65MMxeKKA7S-ijQ3elK-g== - INFLUXDB_TOKEN=apiv3_tbEpA8JmIRTfr8Wbw9npD79BcMlFsnV4_jhdt-CdUP53Mos61KBODGaggl2g5oKZZvZrZu3e6mpob6zorhEdbg
- INFLUXDB_URL=http://influxdb2:8086 - INFLUXDB_URL=http://influxdb3:8181
- INFLUXDB_ORG=edelweiss - INFLUXDB_DATABASE=edelweiss
- INFLUXDB_BUCKET=theatre
- MIKROTIK_IP=192.168.31.1 - MIKROTIK_IP=192.168.31.1
- MIKROTIK_USER=service - MIKROTIK_USER=service
- MIKROTIK_PASSWORD=dataservice - MIKROTIK_PASSWORD=dataservice
@@ -63,8 +84,33 @@ services:
- LOG_FILE_LVL=WARNING - LOG_FILE_LVL=WARNING
- LOG_CLI_LVL=INFO - LOG_CLI_LVL=INFO
# unifi-controller:
# image: lscr.io/linuxserver/unifi-controller:latest
# container_name: edx-unifi
# environment:
# - PUID=1000
# - PGID=1000
# - MEM_LIMIT=1024 #optional
# - MEM_STARTUP=1024 #optional
# volumes:
# - /var/lib/unifi:/config
# ports:
# - 8443:8443
# - 3478:3478/udp
# - 10001:10001/udp
# - 8080:8080
# - 1900:1900/udp #optional
# - 8843:8843 #optional
# - 8880:8880 #optional
# - 6789:6789 #optional
# - 5514:5514/udp #optional
# restart: unless-stopped
# logging:
# driver: "json-file"
# options:
# max-size: "10m"
# max-file: "5"
volumes: volumes:
influxdb2-data:
influxdb2-config:
grafana-data: grafana-data:
influxdb3-data:

37
pyutils/utils.py Normal file
View 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

View File

@@ -1,9 +1,12 @@
FROM python:3.12-alpine FROM python:3.12-alpine
ARG BUILD_VER
RUN apk update && apk upgrade --no-cache RUN apk update && apk upgrade --no-cache
RUN pip install --no-cache-dir RouterOS-API influxdb-client RUN pip install --no-cache-dir RouterOS-API influxdb3-python
COPY ./routermon.py /home/routermon.py COPY ./routermon.py /home/routermon.py
COPY ./utils.py /home/pyutils/utils.py
ENV VER=${BUILD_VER}
CMD [ "python", "/home/routermon.py" ] CMD [ "python", "/home/routermon.py" ]

View File

@@ -2,88 +2,81 @@ 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 influxdb_client.client.write.point import Point from pyutils.utils import *
from influxdb_client.client.influxdb_client import InfluxDBClient from influxdb_client_3 import InfluxDBClient3, Point
from influxdb_client.client.write_api import ASYNCHRONOUS, SYNCHRONOUS
# 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): def main() -> int:
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 main():
INTERVAL = int(env['INTERVAL']) INTERVAL = int(env['INTERVAL'])
# Init InfluxDB try:
write_client = InfluxDBClient(url=env['INFLUXDB_URL'], # Init InfluxDB-v3 Client
write_client = InfluxDBClient3(host=env['INFLUXDB_URL'],
token=env['INFLUXDB_TOKEN'], token=env['INFLUXDB_TOKEN'],
org=env['INFLUXDB_ORG']) database=env['INFLUXDB_DATABASE'])
write_api = write_client.write_api(write_options=ASYNCHRONOUS) # Init routerOS API
# Init routerOS API connection = routeros_api.RouterOsApiPool(env['MIKROTIK_IP'],
connection = routeros_api.RouterOsApiPool(env['MIKROTIK_IP'], username=env['MIKROTIK_USER'],
username=env['MIKROTIK_USER'], password=env['MIKROTIK_PASSWORD'],
password=env['MIKROTIK_PASSWORD'], plaintext_login=True)
plaintext_login=True) api = connection.get_api()
api = connection.get_api() except Exception as e:
LOGGER.error(e)
return 1
finally:
LOGGER.info(f"InfluxDB Connected: [{env['INFLUXDB_URL']}/{env['INFLUXDB_DATABASE']}]")
LOGGER.info(f"Mikrotik Connected: [{env['MIKROTIK_IP']}]")
run: SignalHandler = SignalHandler() ##############################
last = 0 ########## MAIN LOOP #########
if_points = [] ##############################
if_stats_old = api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'}) last: float = 0
for n,d in enumerate(if_stats_old): handler: SignalHandler = SignalHandler(LOGGER)
for k,v in d.items(): if_stats_old = convertIntList(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'}))
if str.isdecimal(v): while handler.running:
if_stats_old[n][k] = int(v)
### MAIN LOOP ###
while run:
try: try:
now = time.time() now:float = time.time()
if_stats = api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'}) if_points: list[Point] = []
hw_stats = api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load'})[0] if_stats: list[dict] = convertIntList(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'}))
# calcolo della velocita' interfaccia a ogni ciclo hw_stats: dict[str,str] = convertInt(api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load,total-memory,free-memory'})[0])
for n,d in enumerate(if_stats): hw_stats['temperature'] = convertInt(api.get_resource('/system/health').call('print')[1])['value']
for k,v in d.items(): # Calcolo della velocita' interfaccia a ogni ciclo
if str.isdecimal(v): for n, _ in enumerate(if_stats):
if_stats[n][k] = int(v) if_name = if_stats[n].pop('name')
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'])/(INTERVAL))
if_stats[n]['tx-rate'] = int((if_stats[n]['tx-bytes']-if_stats_old[n]['tx-bytes'])/(now-last)) if_stats[n]['tx-rate'] = int((if_stats[n]['tx-bytes']-if_stats_old[n]['tx-bytes'])/(INTERVAL))
if_points.append( if_points.append(
Point("interfaces") dict2Point('interfaces', if_stats[n], {'interface': if_name})
.tag("interface", d['name']) )
.field('rx-rate', if_stats[n]['rx-rate']) write_client.write(record=if_points)
.field('tx-rate', if_stats[n]['tx-rate'])
) # Risorse del router
rs1 = write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'], write_client.write(record=dict2Point('resources',hw_stats))
record=if_points)
rs2 = write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'], # Salvo ultimo punto per il giro successivo
record=Point('resources').field('cpu',int(hw_stats['cpu-load']))
)
LOGGER.debug(f"InfluxWrite: W1:{rs1}, W2:{rs2}")
if_stats_old = if_stats if_stats_old = if_stats
last = time.time()
LOGGER.debug(f"\nInterfaces: {json.dumps(if_stats, indent = 2)}") LOGGER.debug(f"\nInterfaces: {json.dumps(if_stats, indent = 2)}")
LOGGER.debug(f"\nResources: {json.dumps(hw_stats, indent = 2)}") LOGGER.debug(f"\nResources: {json.dumps(hw_stats, indent = 2)}")
time.sleep(INTERVAL) last: float = time.time()
cycle_time: float = last - now
LOGGER.debug(f"Cycle Time: {cycle_time:4.3f}")
time.sleep(INTERVAL-cycle_time)
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 ### ##############################
###### END MAIN LOOP #########
##############################
connection.disconnect() connection.disconnect()
write_client.close()
return 0 return 0
if __name__ == "__main__": if __name__ == "__main__":
@@ -111,6 +104,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")

26
upsmon/dataexchange.txt Normal file
View File

@@ -0,0 +1,26 @@
VP req: QMD
UPS resp: (#######WPHVT2K0 ###2000 80 1/1 230 230 04 12.0
VP req: QRI
UPS resp: (230.0 008 048.0 50.0
VP req: QHE
UPS resp: (242 218
VP req: QRI
UPS resp: (230.0 008 048.0 50.0
VP req: QGS
UPS resp: (230.9 50.0 230.7 50.1 001.0 013 373.7 379.4 054.4 ---.- 027.3 100000000001
VP req: QMOD
UPS resp: (L
VP req: QWS
UPS resp: (0000000000000000000000000000000000000000000000000000000000000000
VP req: QBV
UPS resp: (054.5 04 04 096 568
VP req: QSK1
UPS resp: (NAK
VP req: QSK2
UPS resp: (NAK
VP req: QFLAG
UPS resp: (EpbrashczDovegfm
VP req: QBYV
UPS resp: (264 170
VP req: QBYF
UPS resp: (53.0 47.0

16
upsmon/sniffer.py Normal file
View File

@@ -0,0 +1,16 @@
import serial
ups_port = "/dev/ttyUSB1"
usb_fake = "/dev/ttyUSBf"
ups = serial.Serial(port=ups_port, baudrate=2400, parity="N", bytesize=8, stopbits=1)
vp = serial.Serial(port=usb_fake, baudrate=2400, parity="N", bytesize=8, stopbits=1)
while True:
vp_request = vp.read_until(b'\r')
print(f'VP req: {vp_request.decode('ascii').strip()}')
ups.write(vp_request)
ups.flush()
ups_response = ups.read_until(b'\r')
print(f'UPS resp: {ups_response.decode('ascii').strip()}')
vp.write(ups_response)

View File

@@ -1,94 +1,148 @@
import os import os
import sys import sys
import time import time
import string
import serial import serial
import logging import logging
import signal
import json
from influxdb_client.client.write.point import Point from copy import deepcopy
from influxdb_client.client.influxdb_client import InfluxDBClient from pyutils.utils import *
from influxdb_client.client.write_api import ASYNCHRONOUS, SYNCHRONOUS from dataclasses import dataclass
from influxdb_client_3 import InfluxDBClient3, WriteOptions
# Get environment variables # Get environment variables
env = dict(os.environ) env = dict(os.environ)
LOGGER: logging.Logger LOGGER: logging.Logger
class SignalHandler: class UPScommand:
running: bool
def __init__(self): def send(self, port:serial.Serial, cmd: str):
self.running: bool = True port.write((cmd+'\r').encode('ascii'))
signal.signal(signal.SIGINT, self._handle_sigint) port.flush()
signal.signal(signal.SIGTERM, self._handle_sigint)
def _handle_sigint(self, signum, frame): def receive(self, port:serial.Serial, cmd: str) -> str:
self.running = False resp = port.read_until(expected=b'\r').decode('ascii').rstrip()
LOGGER.debug(f"{cmd} : {resp}")
return resp
def send(port: serial.Serial, d: str): def request(self, port:serial.Serial, cmd: str) -> list[str]:
port.write((d+'\r').encode('ascii')) self.send(port, cmd)
port.flush() return self.receive(port, cmd).lstrip('(').rstrip().split()
def receive(port: serial.Serial, d: str) -> str: def asDict(self):
r = port.read_until(b'\r').decode('ascii').rstrip() return deepcopy(self.__dict__)
LOGGER.debug(f"{d} : {r}")
return r
def bruteforceCommands(port: serial.Serial): @dataclass
# T and S cause unwanted shutdown class UPSstatus(UPScommand):
letters = string.ascii_uppercase.replace('T','').replace('S','') inV: float
LOGGER.debug(f"Test commands: {letters}") inF: float
for c in letters: outV: float
send(port, c) outF: float
receive(port, c) current: float
for n in range(10): loadPct: int
d = c+f"{n:1d}" battV: float
send(port, d) temp: float
receive(port, d) onLine: bool
for n in range(100): onBatt: bool
d = c+f"{n:02d}" ecoMode: bool
send(port, d)
receive(port, d)
def main(): def __init__(self, port: serial.Serial):
self.update(port)
return
def update(self, port:serial.Serial):
data = self.request(port=port, cmd="QGS")
self.inV = float(data[0])
self.inF = float(data[1])
self.outV = float(data[2])
self.outF = float(data[3])
self.current = float(data[4])
self.loadPct = int(data[5])
self.battV = float(data[8])
self.temp = float(data[10])
self.onLine = True if data[11].startswith('1') else False
self.onBatt = True if data[11].endswith('0') else False
self.ecoMode = True if data[11][4] == '1' else False
@dataclass
class UPSbattery(UPScommand):
battV: float
battPct: int
timeLeft: float
def __init__(self, port: serial.Serial):
self.update(port)
return
def update(self, port: serial.Serial):
data = self.request(port=port, cmd="QBV")
self.battV = float(data[0])
self.battPct = int(data[3])
self.timeLeft = round(int(data[4]) / 60.0, 1)
##################
###### MAIN ######
##################
def main() -> int:
INTERVAL = int(env['INTERVAL']) INTERVAL = int(env['INTERVAL'])
LOGGER.debug(json.dumps(env, indent=2)) UPS_COMMAND = "Q1"
run: SignalHandler = SignalHandler() UPS_STATUS = "QGS" # (Vin Fin Vout Fout Aout Load% ?1 ?2 VbatInt VbatExt Temp Flags
port = serial.Serial(port=env['PORT'], baudrate=int(env['BAUD']), bytesize=8, parity='N', stopbits=1) UPS_BATTERY = "QBV" # (Vbat n1 n2 Charge% RunMins
write_client = InfluxDBClient(url=env['INFLUXDB_URL'], UPS_MODE = "QMOD" # (Mode [Echo, Line, Battery?]
token=env['INFLUXDB_TOKEN'],
org=env['INFLUXDB_ORG']) try:
write_api = write_client.write_api(write_options=ASYNCHRONOUS) # 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)
port.flush()
# Init Dataclasses
run: SignalHandler = SignalHandler(LOGGER)
status = UPSstatus(port)
battery = UPSbattery(port)
except Exception as e:
LOGGER.error(e)
return 1
finally:
LOGGER.info(f"InfluxDB Connected: [{env['INFLUXDB_URL']}/{env['INFLUXDB_DATABASE']}]")
LOGGER.info(f"Serial Port Open: [{env['PORT']}]")
##############################
########## MAIN LOOP #########
##############################
while run.running: while run.running:
try: try:
send(port, "Q1") # Update data
data = receive(port, "Q1").lstrip('(').split() status.update(port)
if len(data) < 8: LOGGER.debug(f"{repr(status)}")
LOGGER.error(f"Incomplete data: {data}") battery.update(port)
continue LOGGER.debug(f"{repr(battery)}")
values = {
'inV': float(data[0]), # Debug status Information when running on batteries
'outV': float(data[2]), if status.onBatt:
'loadPercent': float(data[3]), LOGGER.info(f" Status:\n{repr(status)}")
'lineFreq': float(data[4]), LOGGER.info(f"Battery:\n{repr(battery)}")
'timeLeft': float(data[5]),
'onBatt': True if str(data[7]).startswith('1') else False, # Write datapoint to Influx merging measurements
'onLine': True if str(data[7]).endswith('1') else False, datapoint = status.asDict() | battery.asDict()
} write_client.write(record=dict2Point(measurement='ups',
LOGGER.debug(f"UPS Status: \n{json.dumps(values, indent=2)}") fields=datapoint
if values['onBatt']: ))
LOGGER.info(f"OnBattery\n{json.dumps(values,indent=2)}") LOGGER.debug(f"Influx Write: {datapoint}")
p = Point('ups') # Sleep and repeat
for k,v in values.items():
p.field(k,v)
write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'], 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()
write_client.close()
LOGGER.warning("Main thread exited normally")
return 0
if __name__ == "__main__": if __name__ == "__main__":
# Logger Constants # Logger Constants
@@ -115,6 +169,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")

View File

@@ -1,9 +1,12 @@
FROM python:3.12-alpine FROM python:3.12-alpine
ARG BUILD_VER
RUN apk update && apk upgrade --no-cache RUN apk update && apk upgrade --no-cache
RUN pip install --no-cache-dir pyserial RouterOS-API influxdb-client RUN pip install --no-cache-dir pyserial RouterOS-API influxdb3-python
COPY ./ups.py /home/ups.py COPY ./ups.py /home/ups.py
COPY ./utils.py /home/pyutils/utils.py
ENV VER=${BUILD_VER}
CMD [ "python", "/home/ups.py" ] CMD [ "python", "/home/ups.py" ]