Skip to content

Instantly share code, notes, and snippets.

@Peetz0r
Created September 22, 2022 08:04
Show Gist options
  • Save Peetz0r/3b6e4861697859fcfe4a12a3698deca7 to your computer and use it in GitHub Desktop.
Save Peetz0r/3b6e4861697859fcfe4a12a3698deca7 to your computer and use it in GitHub Desktop.
CREATE TABLE mqtt (
ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
topic text[] NOT NULL,
retain boolean NOT NULL,
value text,
PRIMARY KEY (ts, topic)
)
import paho.mqtt.client, psycopg2
def on_message(client, obj, msg):
try:
cur.execute("INSERT INTO mqtt (topic, retain, value) VALUES (%s, %s, %s)", (msg.topic.split("/"), bool(msg.retain), msg.payload.decode()))
sql.commit()
except e:
print(e)
sql = psycopg2.connect("user=mqtt")
cur = sql.cursor()
mqttc = paho.mqtt.client.Client()
mqttc.connect("mqtt.peetz0r.nl")
mqttc.message_callback_add("#", on_message)
mqttc.subscribe("#")
try:
while True:
mqttc.loop()
except KeyboardInterrupt:
print("Bye!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment