NUT_to_Influx/main.py
2023-07-01 18:23:27 -04:00

93 lines
2.7 KiB
Python

## Requires NUT2 from PIP
from nut2 import PyNUTClient
import os
import requests
import json
from datetime import datetime
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
from time import sleep
# nutserver settings
HOSTLIST = os.environ.get("INFLUXDB_URL", "10.0.5.5")
HOSTLIST = HOSTLIST.split(",")
# Constants (replace with your values)
INFLUXDB_URL = os.environ.get("INFLUX_URL", 'http://10.0.5.61:8086')
INFLUXDB_TOKEN = os.environ.get("INFLUXDB_TOKEN", 'E2GVPIovlYDbAy3ZztRVyuMyILGGnLEI9NsTcyvVgt9LUW9Mhv5Hrzle5gLY7W4xxBVqFk3DYsfss4a3hcDlZQ==')
INFLUXDB_ORG = os.environ.get("INFLUXDB_ORG", 'carbonnet')
INFLUXDB_BUCKET = os.environ.get("INFLUXDB_BUCKET", 'testing')
def uploadInflux(data): # Main upload
for UPS in data:
json_body = [
{
"measurement": "data",
"tags": {
'ups': str(UPS),
},
"fields": {
"battery": float(data[UPS]["battery.charge"]),
"runtime-s": float(data[UPS]["battery.runtime"]),
"load": float(data[UPS]["ups.load"]),
"input_voltage": float(data[UPS]["input.voltage"]),
"battery_voltage": float(data[UPS]["battery.voltage"]),
}
}
]
# client = InfluxDBClient(host, port, database = "telegraf") # Init connection to Influx Server
# client.write_points(json_body) # Write Speedtest results
client = InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
# Get a write API.
write_api = client.write_api(write_options=SYNCHRONOUS)
# Write the data to the database.
write_api.write(INFLUXDB_BUCKET, INFLUXDB_ORG, json_body)
# Close the clients to free up resources
write_api.__del__()
client.__del__()
def main():
upslist = {}
## pull all the UPSes froom each host into a nice dict
for host in HOSTLIST:
try:
upslist[host] = []
client = PyNUTClient(host, '3493')
for UPS in client.list_ups():
upslist[host].append(UPS)
except:
print('UPS {} is having issues'.format(host))
# print(upslist)
data = {}
## Pull whatever data we would like into a dict of each ups
for host in upslist:
client = PyNUTClient(host, '3493')
try:
for UPS in upslist[host]:
data[UPS] = client.list_vars(UPS)
except:
print('UPS {} is having issues'.format(host))
# print(data)
uploadInflux(data)
while True:
main()
sleep(15)