archive2018

MQTT sensor data into InfluxDB with Telegraf, on a Raspberry Pi

Telegraf's mqtt_consumer instead of a home-made bridge script, InfluxDB 1.x on a Raspberry Pi with a retention policy, and the tag, test and SD card mistakes to avoid.

4 min read#edge#influxdb#telegraf#mqtt

My sensor data has gone into InfluxDB on a small server. That server is being retired, and I do not want a second always-on machine only for a database. So InfluxDB 1.x now runs on the Raspberry Pi 3 B+ that already runs the MQTT broker, with the data on a USB disk. This is the full setup on Raspbian Stretch, so I can repeat it.

It is fine for tens of sensors with readings every few seconds to every minute. It is not meant for millions of series or a cluster. And an SD card is a weak place for a database that writes all day, which is why the data directory is on the USB disk.

Why Telegraf, not my own bridge

My sensors publish small JSON messages like {"temp": 21.4, "hum": 48.0} to topics like home/kitchen/climate. At first a Python script subscribed to them and wrote to InfluxDB. It crashed now and then, and I added reconnect code to it twice. Telegraf’s mqtt_consumer input does the same job with a few lines of config, and it already handles reconnects, batching and buffering. So early in 2017 the script went away. I would still write my own bridge if it needed real logic: unit conversion, checks per device, or combining messages. For “subscribe, parse, write”, Telegraf is enough.

Install from the InfluxData repository

The Raspbian packages are old. The InfluxData repository has armhf builds:

curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add -
echo "deb https://repos.influxdata.com/debian stretch stable" | \
  sudo tee /etc/apt/sources.list.d/influxdb.list
sudo apt update
sudo apt install influxdb telegraf
sudo systemctl enable --now influxdb

Database and retention policy

influx -execute "CREATE DATABASE sensors"
influx -execute "CREATE RETENTION POLICY one_year ON sensors DURATION 52w REPLICATION 1 DEFAULT"

Without a retention policy, data is kept forever and the disk fills slowly. Create it before the first write.

Telegraf: MQTT in, InfluxDB out

# /etc/telegraf/telegraf.d/mqtt.conf
[[inputs.mqtt_consumer]]
  servers = ["tcp://localhost:1883"]
  topics = ["home/+/climate"]
  qos = 1
  client_id = "telegraf-climate"
  persistent_session = true
  username = "telegraf"
  password = "secret"
  data_format = "json"
  name_override = "climate"

And the output in /etc/telegraf/telegraf.conf:

[[outputs.influxdb]]
  urls = ["http://127.0.0.1:8086"]
  database = "sensors"
  retention_policy = ""

An empty retention_policy means the default policy, which is one_year now.

What the input settings do:

  • Each numeric JSON key becomes a field (temp, hum), and the topic is stored as a tag called topic.
  • Without name_override, the measurement is called mqtt_consumer, which is not a useful name.
  • persistent_session = true needs a fixed client_id. With QoS 1, the broker then keeps messages for Telegraf while it restarts.
  • The JSON parser drops string values. To keep a string as a tag, list it in tag_keys; to keep it as a field, use json_string_fields.
  • Numbers become floats. That avoids a field type conflict when one device sends 21 and another 21.5.

Test it

Check that the config loads, then restart:

telegraf --config /etc/telegraf/telegraf.conf \
  --config-directory /etc/telegraf/telegraf.d --test
sudo systemctl restart telegraf

--test runs the inputs once. mqtt_consumer is a service input that waits for messages, so in test mode it shows nothing. That confused me the first time. Send a message by hand and look in the database instead:

mosquitto_pub -h localhost -u test -P test \
  -t home/test/climate -m '{"temp": 20.0, "hum": 50.0}'
influx -database sensors -execute \
  "SELECT * FROM climate WHERE time > now() - 10m LIMIT 5"

Tags and fields

This is the main design point in InfluxDB 1.x. Tags are indexed strings. Use them for what you filter or group by: room, device, sensor type. Fields are the values: temperature, humidity.

Every unique combination of tag values is a new series. A timestamp, a message ID or a random client ID in a tag makes the number of series grow without limit, memory use grows with it, and a Pi runs out of RAM. Keep tag values to a small, fixed set. The topic tag is fine here, because I have only a few rooms. In Grafana a regex like /kitchen/ selects a room from it. For a clean room tag, put the room into the JSON and list it in tag_keys.

Downsampling

Raw data every 10 seconds for a year is a lot. A continuous query can keep hourly averages for longer:

CREATE RETENTION POLICY five_years ON sensors DURATION 260w REPLICATION 1
CREATE CONTINUOUS QUERY cq_climate_1h ON sensors BEGIN
  SELECT mean(temp) AS temp, mean(hum) AS hum
  INTO sensors.five_years.climate_1h
  FROM climate GROUP BY time(1h), *
END

Then the raw policy can be much shorter, 30 days for example. I want a few weeks of data on the Pi before I change it.

Other things to know

  • Points get their time from Telegraf when they arrive. If the Pi has no network time at boot, the time is wrong, so check timedatectl. A device that buffers data and sends it later needs its own time in the payload and a different setup.
  • InfluxDB 1.x has authentication turned off by default. If port 8086 is reachable from other machines, turn it on in /etc/influxdb/influxdb.conf and create users.