Skip to content

Instantly share code, notes, and snippets.

@LarsBergqvist
Last active October 9, 2022 12:42
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LarsBergqvist/8d9414aeadf667216df81f41140aa72c to your computer and use it in GitHub Desktop.
Save LarsBergqvist/8d9414aeadf667216df81f41140aa72c to your computer and use it in GitHub Desktop.
An MQTT subscriber client that persists data in a MongoDB database
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import datetime
from pymongo import MongoClient
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("Home/#")
def on_message(client, userdata, msg):
receiveTime=datetime.datetime.now()
message=msg.payload.decode("utf-8")
isfloatValue=False
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)
isfloatValue=True
except:
isfloatValue=False
if isfloatValue:
print(str(receiveTime) + ": " + msg.topic + " " + str(val))
post={"time":receiveTime,"topic":msg.topic,"value":val}
else:
print(str(receiveTime) + ": " + msg.topic + " " + message)
post={"time":receiveTime,"topic":msg.topic,"value":message}
collection.insert_one(post)
# Set up client for MongoDB
mongoClient=MongoClient()
db=mongoClient.SensorData
collection=db.home_data
# Initialize the client that should connect to the Mosquitto broker
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("192.168.1.16", 1883, 60)
# Blocking loop to the Mosquitto broker
client.loop_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment