refactor: put all export related stuff in itho_export.py

This commit is contained in:
Pim van den Berg 2021-04-08 14:19:37 +02:00
parent 7f4cdc8682
commit b936311e59
2 changed files with 26 additions and 24 deletions

View File

@ -6,7 +6,6 @@ import queue
import sys import sys
import time import time
import os import os
import datetime
import json import json
import db import db
from collections import namedtuple from collections import namedtuple
@ -19,29 +18,6 @@ stdout_log_handler.setFormatter(logging.Formatter("%(message)s"))
logger.addHandler(stdout_log_handler) logger.addHandler(stdout_log_handler)
def export_to_influxdb(action, measurements):
from influxdb import InfluxDBClient
influx_client = InfluxDBClient(
host=os.getenv('INFLUXDB_HOST', 'localhost'),
port=os.getenv('INFLUXDB_PORT', 8086),
username=os.getenv('INFLUXDB_USERNAME', 'root'),
password=os.getenv('INFLUXDB_PASSWORD', 'root'),
database=os.getenv('INFLUXDB_DATABASE')
)
json_body = [
{
"measurement": action,
"time": datetime.datetime.utcnow().replace(microsecond=0).isoformat(),
"fields": measurements,
}
]
try:
influx_client.write_points(json_body)
except Exception as e:
print('Failed to write to influxdb: ', e)
actions = { actions = {
"getnodeid": [0x90, 0xE0], "getnodeid": [0x90, 0xE0],
"getserial": [0x90, 0xE1], "getserial": [0x90, 0xE1],
@ -217,6 +193,7 @@ def process_response(action, response, args, wpu):
if action == "getdatalog": if action == "getdatalog":
measurements = process_datalog(response, wpu) measurements = process_datalog(response, wpu)
if args.export_to_influxdb: if args.export_to_influxdb:
from itho_export import export_to_influxdb
export_to_influxdb(action, measurements) export_to_influxdb(action, measurements)
elif action == "getnodeid": elif action == "getnodeid":
process_nodeid(response) process_nodeid(response)

25
itho_export.py Normal file
View File

@ -0,0 +1,25 @@
import datetime
import os
def export_to_influxdb(action, measurements):
from influxdb import InfluxDBClient
influx_client = InfluxDBClient(
host=os.getenv('INFLUXDB_HOST', 'localhost'),
port=os.getenv('INFLUXDB_PORT', 8086),
username=os.getenv('INFLUXDB_USERNAME', 'root'),
password=os.getenv('INFLUXDB_PASSWORD', 'root'),
database=os.getenv('INFLUXDB_DATABASE')
)
json_body = [
{
"measurement": action,
"time": datetime.datetime.utcnow().replace(microsecond=0).isoformat(),
"fields": measurements,
}
]
try:
influx_client.write_points(json_body)
except Exception as e:
print('Failed to write to influxdb: ', e)