Skip to content

Instantly share code, notes, and snippets.

@LinusCDE
Created April 9, 2020 19:29
Show Gist options
  • Save LinusCDE/923b26a66b75415e9d58b6050f7a18ec to your computer and use it in GitHub Desktop.
Save LinusCDE/923b26a66b75415e9d58b6050f7a18ec to your computer and use it in GitHub Desktop.
MQTT to Influx relay script

MQTT to Influx relay script

This script subscribes to certain mqtt topics and adds any (numeric/boolean!) values to your influx db to e.g. display the stats in grafana.

Example scenario

  • Retreive smartphone battery charge in mqtt using an app like Presence Publisher.
  • Use the script to put that data into an influx db.
  • Display that data in grafana

grafana_query_setup grafana_battery_graph

#!/usr/bin/env python3
# Bases on snippet from this tutorial:
# https://gonzalo123.com/2018/06/04/playing-with-docker-mqtt-grafana-influxdb-python-and-arduino/
import paho.mqtt.client
from influxdb import InfluxDBClient
import datetime
import logging
INFLUXDB_HOST = 'localhost'
INFLUXDB_PORT = 8086
MQTT_HOST = 'localhost'
MQTT_PORT = 1883
# TOPICS should receive numeric or boolean (on/off or true/false) values
# Json support should be easily addable
MQTT_TOPICS = [
'stat/chargecontroller/power',
'stat/v30/battery',
]
def on_message(client, userdata, msg):
# Get numeric value from msg
rawValue = msg.payload.decode('UTF-8')
rawValueLc = rawValue.lower()
value = None
if rawValueLc == 'on' or rawValueLc == 'true':
value = int(True)
elif rawValueLc == 'off' or rawValueLc == 'false':
value = int(False)
else:
value = int(rawValue)
# Create data for influxdb
current_time = datetime.datetime.utcnow().isoformat()
json_body = [
{
"measurement": "message", # Similar to table
"tags": {
"server": '%s:%d' % (MQTT_HOST, MQTT_PORT), # May be discarded
"topic": msg.topic
},
"time": current_time,
"fields": {
"value": value
}
}
]
logging.info('%s = %d (raw: %s)' % (msg.topic, value, rawValue))
influx_client.write_points(json_body)
def on_connect(client, mosq, obj, rc):
logging.info('Connected to mqtt')
for topic in MQTT_TOPICS:
client.subscribe(topic)
logging.info('Subscribed to %s' % topic)
logging.basicConfig(level=logging.INFO)
influx_client = InfluxDBClient(INFLUXDB_HOST, INFLUXDB_PORT, database='mqtt')
mqttClient = paho.mqtt.client.Client()
mqttClient.on_connect = on_connect
mqttClient.on_message = on_message
mqttClient.connect(MQTT_HOST, MQTT_PORT, 60)
mqttClient.loop_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment