-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathinfluxdb-connector.py
151 lines (123 loc) · 3.97 KB
/
influxdb-connector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python3
# https://thingsmatic.com/2017/03/02/influxdb-and-grafana-for-sensor-time-series/
import paho.mqtt.client as mqtt
import datetime
import time
import json
import logging
import sys
from influxdb import InfluxDBClient
from config import *
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("#")
def on_message(client, userdata, msg):
topic = msg.topic
# print("Received a message on topic: " + topic)
# Use utc as timestamp
receiveTime = datetime.datetime.utcnow()
message = msg.payload.decode("utf-8")
if "tele/" in topic:
send_tasmota_data(topic, receiveTime, message)
elif "growatt" in topic:
send_growatt_data(topic, receiveTime, message)
else:
send_plain_data(topic, receiveTime, message)
def send_growatt_data(topic, receiveTime, message):
try:
data = json.loads(message)
except json.JSONDecodeError:
return
fields = ["PV1Voltage", "PV1InputCurrent", "PV1InputPower",
"OutputPower", "GridFrequency", "L1ThreePhaseGridVoltage", "L1ThreePhaseGridOutputCurrent",
"L1ThreePhaseGridOutputPower", "TodayGenerateEnergy", "TotalGenerateEnergy", "TWorkTimeTotal",
"InverterTemperature"]
points = []
for field in fields:
try:
float_v = float(data[field])
except Exception:
continue
point = {
"measurement": f"{topic}/{field}",
"time": receiveTime,
"fields": {
"value": float_v
}
}
points.append(point)
try:
dbclient.write_points(points)
except Exception:
logging.exception("Exception writing to db")
def send_tasmota_data(topic, receiveTime, message):
try:
data = json.loads(message)
except json.JSONDecodeError:
return
sensordata = data.get("ENERGY", data.get("WTS01"))
if not sensordata:
return
points = []
for k,v in sensordata.items():
try:
float_v = float(v)
except Exception:
continue
point = {
"measurement": f"{topic}/{k}",
"time": receiveTime,
"fields": {
"value": float_v
}
}
points.append(point)
try:
dbclient.write_points(points)
except Exception:
logging.exception("Exception writing to db")
def send_plain_data(topic, receiveTime, message):
try:
# Convert the string to a float so that it is stored as a number and not a string in the database
val = float(message)
except Exception:
# print("Could not convert " + message + " to a float value")
return
# print(str(receiveTime) + ": " + topic + " " + str(val))
points = [
{
"measurement": topic,
"time": receiveTime,
"fields": {
"value": val
}
}
]
try:
dbclient.write_points(points)
except Exception:
logging.exception("Exception writing to db")
# print("Finished writing to InfluxDB")
logging.basicConfig(stream=sys.stdout,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO)
logging.info("start")
# Set up a client for InfluxDB
dbclient = InfluxDBClient(INFLUXDB_HOST, 8086, 'mqtt', 'mqtt', 'mqtt')
logging.info("dbclient created")
# Initialize the MQTT client that should connect to the Mosquitto broker
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
connOK = False
while(connOK is False):
try:
client.connect(BROKER_HOST, BROKER_PORT, 60)
connOK = True
except Exception:
connOK = False
time.sleep(2)
logging.info("mqtt connection established")
# Blocking loop to the Mosquitto broker
client.loop_forever()