diff options
Diffstat (limited to '')
-rw-r--r-- | mqtt2pgsql.py (renamed from mqtt_temps.py) | 24 |
1 files changed, 15 insertions, 9 deletions
diff --git a/mqtt_temps.py b/mqtt2pgsql.py index bda7b0f..004216e 100644 --- a/mqtt_temps.py +++ b/mqtt2pgsql.py @@ -28,20 +28,26 @@ def on_connect(client, userdata, flags, rc): # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): - if msg.topic.startswith('zigbee2mqtt/tmp'): - #print("TMP!! - " + msg.topic.split('/')[1]) - data = json.loads(msg.payload) - if 'temperature' in data and 'humidity' in data: - values = (msg.topic.split('/')[1], data['temperature'], data['humidity'], data['battery'], data['linkquality'], data['voltage']) - print(values) - todb(values) + name = msg.topic.split('/')[1] + data = json.loads(msg.payload) + if name.startswith('tmp') and 'temperature' in data and 'humidity' in data: + sql = "INSERT INTO mqtt_temps (name, temperature, humidity, battery, linkquality, voltage) VALUES(%s,%s,%s,%s,%s,%s)" + values = (name, data['temperature'], data['humidity'], data['battery'], data['linkquality'], data['voltage']) + todb(sql,values) + + elif name == 'HAN' and 'current' in data: + sql = "INSERT INTO mqtt_han (name, current, power, voltage, linkquality) VALUES(%s,%s,%s,%s,%s)" + values = (name, data['current'], data['power'], data['voltage'], data['linkquality']) + todb(sql,values) + # Write values to database -def todb(values): +def todb(sql, values): + print(values) conn = psycopg2.connect(database=pg_db, host=pg_host, user=pg_user, password=pg_pass) cur = conn.cursor() try: - cur.execute("INSERT INTO " + pg_table + " (name, temperature, humidity, battery, linkquality, voltage) VALUES(%s,%s,%s,%s,%s,%s)", values) + cur.execute(sql, values) conn.commit() except (Exception, psycopg2.Error) as error: conn.rollback() |