InfluxDB is an ideal time-series database to collect MQTT metrics. In this post I’ll show how to configure collection of MQTT metrics from Tasmota devices.
Telegraf is a general purpose collection agent that can send metrics to InfluxDB. It includes an mqtt_consumer and a recently enhanced json parser that makes collection of MQTT even easier. To use these features, you’ll need to be on Telegraf 1.21.x
or later.
I’m going to use the Tasamota MQTT SENSOR event for this example configuration.
Tasmota SENSOR events use a topic format of tele/%topic%/SENSOR
. My devices are configured with a topic of tele/site/room/sensor
and I have some BME280, CCS811 and SDS01 sensors that I’ll use in this example. Here’s some example json from my sensors:
{"Time":"2022-01-12T18:47:12","BME280":{"Temperature":50.8,"Humidity":100.0,"DewPoint":50.8,"Pressure":1008.3},"SDS0X1":{"PM2.5":3.6,"PM10":7.3},"PressureUnit":"hPa","TempUnit":"F"}
{"Time":"2022-01-12T17:47:13","BME280":{"Temperature":73.3,"Humidity":46.8,"DewPoint":51.7,"Pressure":1008.2},"CCS811":{"eCO2":1914,"TVOC":607},"PressureUnit":"hPa","TempUnit":"F"}
Here’s the telegraf.conf
config that is working for me. Note, that I’m parsing out the MQTT topic to set tags. You can read more about how this configuration works in Telegraf mqtt_consumer blog post and their json_v2 blog post.
[[inputs.mqtt_consumer]]
client_id = "telegraf"
username = "myuser"
password = "mypass"
data_format = "json_v2"
servers = [ "tcp://vernemq.mqtt:1883" ]
topics = [ "tele/+/+/+/SENSOR" ]
[[inputs.mqtt_consumer.json_v2]]
measurement_name = "tasmota"
[[inputs.mqtt_consumer.topic_parsing]]
topic = "tele/+/+/+/SENSOR"
tags = "_/site/room/sensor/_"
[[inputs.mqtt_consumer.json_v2.tag]]
path = "TempUnit"
[[inputs.mqtt_consumer.json_v2.tag]]
path = "PressureUnit"
[[inputs.mqtt_consumer.json_v2.object]]
path = "@this"
disable_prepend_keys = true
type = "float"
excluded_keys = ["Time","TempUnit","PressureUnit"]
[[inputs.mqtt_consumer.json_v2.field]]
path = "eCO2"
type = "int"
[[inputs.mqtt_consumer.json_v2.field]]
path = "TVOC"
type = "int"
You can test the configuration file:
telegraf --config /etc/telegraf/telegraf.conf --test --test-wait 10 --config-directory /etc/telegraf/telegraf.d $TELEGRAF_OPTS