Created
September 22, 2022 08:04
-
-
Save Peetz0r/3b6e4861697859fcfe4a12a3698deca7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE mqtt ( | |
ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, | |
topic text[] NOT NULL, | |
retain boolean NOT NULL, | |
value text, | |
PRIMARY KEY (ts, topic) | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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