Merge branch 'influxdb3'
This commit is contained in:
26
upsmon/dataexchange.txt
Normal file
26
upsmon/dataexchange.txt
Normal 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
16
upsmon/sniffer.py
Normal 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)
|
||||
197
upsmon/ups.py
197
upsmon/ups.py
@@ -1,121 +1,176 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import string
|
||||
import serial
|
||||
import logging
|
||||
import signal
|
||||
import json
|
||||
|
||||
from influxdb_client.client.write.point import Point
|
||||
from influxdb_client.client.influxdb_client import InfluxDBClient
|
||||
from influxdb_client.client.write_api import ASYNCHRONOUS, SYNCHRONOUS
|
||||
from copy import deepcopy
|
||||
from pyutils.utils import *
|
||||
from dataclasses import dataclass
|
||||
from influxdb_client_3 import InfluxDBClient3, WriteOptions
|
||||
|
||||
# Get environment variables
|
||||
env = dict(os.environ)
|
||||
LOGGER: logging.Logger
|
||||
|
||||
class SignalHandler:
|
||||
running: bool
|
||||
class UPScommand:
|
||||
|
||||
def __init__(self):
|
||||
self.running: bool = True
|
||||
signal.signal(signal.SIGINT, self._handle_sigint)
|
||||
signal.signal(signal.SIGTERM, self._handle_sigint)
|
||||
def send(self, port:serial.Serial, cmd: str):
|
||||
port.write((cmd+'\r').encode('ascii'))
|
||||
port.flush()
|
||||
|
||||
def _handle_sigint(self, signum, frame):
|
||||
self.running = False
|
||||
def receive(self, port:serial.Serial, cmd: str) -> str:
|
||||
resp = port.read_until(expected=b'\r').decode('ascii').rstrip()
|
||||
LOGGER.debug(f"{cmd} : {resp}")
|
||||
return resp
|
||||
|
||||
def send(port: serial.Serial, d: str):
|
||||
port.write((d+'\r').encode('ascii'))
|
||||
port.flush()
|
||||
def request(self, port:serial.Serial, cmd: str) -> list[str]:
|
||||
self.send(port, cmd)
|
||||
return self.receive(port, cmd).lstrip('(').rstrip().split()
|
||||
|
||||
def asDict(self):
|
||||
return deepcopy(self.__dict__)
|
||||
|
||||
def receive(port: serial.Serial, d: str) -> str:
|
||||
r = port.read_until(b'\r').decode('ascii').rstrip()
|
||||
LOGGER.debug(f"{d} : {r}")
|
||||
return r
|
||||
@dataclass
|
||||
class UPSstatus(UPScommand):
|
||||
inV: float
|
||||
inF: float
|
||||
outV: float
|
||||
outF: float
|
||||
current: float
|
||||
loadPct: int
|
||||
battV: float
|
||||
temp: float
|
||||
onLine: bool
|
||||
onBatt: bool
|
||||
ecoMode: bool
|
||||
|
||||
def bruteforceCommands(port: serial.Serial):
|
||||
# T and S cause unwanted shutdown
|
||||
letters = string.ascii_uppercase.replace('T','').replace('S','')
|
||||
LOGGER.debug(f"Test commands: {letters}")
|
||||
for c in letters:
|
||||
send(port, c)
|
||||
receive(port, c)
|
||||
for n in range(10):
|
||||
d = c+f"{n:1d}"
|
||||
send(port, d)
|
||||
receive(port, d)
|
||||
for n in range(100):
|
||||
d = c+f"{n:02d}"
|
||||
send(port, d)
|
||||
receive(port, d)
|
||||
def __init__(self, port: serial.Serial):
|
||||
self.update(port)
|
||||
return
|
||||
|
||||
def main():
|
||||
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'])
|
||||
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 = InfluxDBClient(url=env['INFLUXDB_URL'],
|
||||
token=env['INFLUXDB_TOKEN'],
|
||||
org=env['INFLUXDB_ORG'])
|
||||
write_api = write_client.write_api(write_options=ASYNCHRONOUS)
|
||||
UPS_COMMAND = "Q1"
|
||||
UPS_STATUS = "QGS" # (Vin Fin Vout Fout Aout Load% ?1 ?2 VbatInt VbatExt Temp Flags
|
||||
UPS_BATTERY = "QBV" # (Vbat n1 n2 Charge% RunMins
|
||||
UPS_MODE = "QMOD" # (Mode [Echo, Line, Battery?]
|
||||
|
||||
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)
|
||||
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:
|
||||
try:
|
||||
send(port, "Q1")
|
||||
data = receive(port, "Q1").lstrip('(').split()
|
||||
if len(data) < 8:
|
||||
LOGGER.error(f"Incomplete data: {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,
|
||||
}
|
||||
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_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'], record=p)
|
||||
# Update data
|
||||
status.update(port)
|
||||
LOGGER.debug(f"{repr(status)}")
|
||||
battery.update(port)
|
||||
LOGGER.debug(f"{repr(battery)}")
|
||||
|
||||
# Debug status Information when running on batteries
|
||||
if status.onBatt:
|
||||
LOGGER.info(f" Status:\n{repr(status)}")
|
||||
LOGGER.info(f"Battery:\n{repr(battery)}")
|
||||
|
||||
# Write datapoint to Influx merging measurements
|
||||
datapoint = status.asDict() | battery.asDict()
|
||||
write_client.write(record=dict2Point(measurement='ups',
|
||||
fields=datapoint
|
||||
))
|
||||
LOGGER.debug(f"Influx Write: {datapoint}")
|
||||
# Sleep and repeat
|
||||
time.sleep(INTERVAL)
|
||||
except Exception as e:
|
||||
print(f"Unexpected exception: [{e}]")
|
||||
return 1
|
||||
##############################
|
||||
###### END MAIN LOOP #########
|
||||
##############################
|
||||
port.close()
|
||||
|
||||
write_client.close()
|
||||
LOGGER.warning("Main thread exited normally")
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Logger Constants
|
||||
# Logger Constants
|
||||
LOG_FORMAT = '%(asctime)s| %(levelname)-7s|%(funcName)-10s|%(lineno)-3d: %(message)-50s'
|
||||
|
||||
# Enabling Logger
|
||||
# Enabling Logger
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
LOGGER.setLevel(logging.DEBUG)
|
||||
LOGGER.propagate = False
|
||||
formatter = logging.Formatter(LOG_FORMAT, None)
|
||||
levels = logging.getLevelNamesMapping()
|
||||
|
||||
# File logging
|
||||
# File logging
|
||||
log_name = os.path.abspath(env['LOG_FILE'])
|
||||
fh = logging.FileHandler(log_name)
|
||||
fh.setLevel(levels[env['LOG_FILE_LVL']])
|
||||
fh.setFormatter(formatter)
|
||||
LOGGER.addHandler(fh)
|
||||
|
||||
# Console logging
|
||||
# Console logging
|
||||
cl = logging.StreamHandler(sys.stdout)
|
||||
cl.setLevel(levels[env['LOG_CLI_LVL']])
|
||||
cl.setFormatter(formatter)
|
||||
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")
|
||||
time.sleep(15)
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
FROM python:3.12-alpine
|
||||
ARG BUILD_VER
|
||||
|
||||
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 ./utils.py /home/pyutils/utils.py
|
||||
|
||||
ENV VER=${BUILD_VER}
|
||||
CMD [ "python", "/home/ups.py" ]
|
||||
|
||||
Reference in New Issue
Block a user