aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDennis Eriksen <d@ennis.no>2023-01-31 07:49:27 +0100
committerDennis Eriksen <d@ennis.no>2023-01-31 07:49:27 +0100
commit4b9958dd25bf67ec2a9fb6bbb9f1e2c7e9ee9321 (patch)
tree507d6854eb0ad5495aef90be89b53df4bf253991
parentadding handler for tempsensors on mqtt (diff)
downloadenergyscripts-4b9958dd25bf67ec2a9fb6bbb9f1e2c7e9ee9321.tar.gz
handle HAN as well
-rw-r--r--mqtt2pgsql.py (renamed from mqtt_temps.py)24
-rw-r--r--mqtt2pgsql.service (renamed from mqtt_temps.service)4
2 files changed, 17 insertions, 11 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()
diff --git a/mqtt_temps.service b/mqtt2pgsql.service
index d6a859e..d400b10 100644
--- a/mqtt_temps.service
+++ b/mqtt2pgsql.service
@@ -7,11 +7,11 @@ StartLimitBurst=5
Type=simple
EnvironmentFile=%h/energyscripts/.env
WorkingDirectory=%h/energyscripts
-ExecStart=%h/energyscripts/venv/bin/python3 -u mqtt_temps.py
+ExecStart=%h/energyscripts/venv/bin/python3 -u mqtt2pgsql.py
Restart=on-failure
TimeoutStopSec=70
RestartSec=30
-SyslogIdentifier=mqtt_temps
+SyslogIdentifier=mqtt2pgsql
#StandardOutput=journal
#StandardError=journal