Skip to content

Instantly share code, notes, and snippets.

@ItKindaWorks
Last active October 29, 2019 20:49
Show Gist options
  • Save ItKindaWorks/3be2b6cc54882f7531682f955788bcb0 to your computer and use it in GitHub Desktop.
Save ItKindaWorks/3be2b6cc54882f7531682f955788bcb0 to your computer and use it in GitHub Desktop.
mqtt subscriber script to insert mqtt data into influxdb
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import datetime
import time
from influxdb import InfluxDBClient
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("/home/#")
def on_message(client, userdata, msg):
print("Received a message on topic: " + msg.topic)
# Use utc as timestamp
receiveTime=datetime.datetime.utcnow()
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:
print("Could not convert " + message + " to a float value")
isfloatValue=False
if isfloatValue:
print(str(receiveTime) + ": " + msg.topic + " " + str(val))
json_body = [
{
"measurement": msg.topic,
"time": receiveTime,
"fields": {
"value": val
}
}
]
dbclient.write_points(json_body)
print("Finished writing to InfluxDB")
# Set up a client for InfluxDB
dbclient = InfluxDBClient('127.0.0.1', 8086, 'admin', 'admin', 'smartHome')
# Initialize the MQTT client that should connect to the Mosquitto broker
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
connOK=False
while(connOK == False):
try:
client.username_pw_set(username="YOUR MQTT USERNAME",password="YOUR MQTT PASSWORD")
client.connect("YOUR MQTT IP BROKER ADDRESS", 1883, 60)
connOK = True
except:
connOK = False
time.sleep(2)
# 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