bash:mqtt:add_to_influxdb
This is an old revision of the document!
I'm trying to “IoT-up” my house, and thought MQTT would be a good distributer for data to different services. I recently set up temperature+humidity sensors, and wanted to graph that data. Grafana+InfluxDB seemed like a good choice, but getting data from MQTT to InfluxDB seemed like a hassle with the available tools, so I wrote a short bash script to grab the data + send it to InfluxDB:
#!/bin/bash
# Global vars
INFLUXDBHOST="localhost"
INFLUXDBPORT=8086
INFLUXDBNAME="mqtt"
MQTTHOST="127.0.0.1"
# Fetch the data, insert the data, do some stuff.
mosquitto_sub -v -t '#' -h $MQTTHOST | while read line; do
echo "`date` - Got: $line"
# Get vars
SENSORNAME=`echo $line | cut -d'/' -f3`
SENSORTYPE=`echo $line | cut -d'/' -f5 | awk {'print $1'}`
SENSORDATA=`echo $line | awk {'print $NF'}
# Insert data to influxdb
curl -XPOST "http://$INFLUXDBHOST:$INFLUXDBPORT/write?db=$INFLUXDBNAME" --data-binary "$SENSORTYPE,sensor=$SENSORNAME value=$SENSORDATA"
done
Data is fetched via. mosquitto_sub like this (as seen in the script above):
biggi@datbox:~$ mosquitto_sub -v -t '/sensor/#' -h 127.0.0.1 /sensor/ESP8266-538530/data/temperature 20.50 /sensor/ESP8266-538530/data/humidity 78.50 /sensor/ESP8266-1456529/data/temperature 20.80 /sensor/ESP8266-1456529/data/humidity 74.60 /sensor/ESP8266-538530/data/temperature 20.50 /sensor/ESP8266-538530/data/humidity 78.40 /sensor/ESP8266-1456529/data/temperature 20.80 /sensor/ESP8266-1456529/data/humidity 74.60
So /sensor/<device name>/data/<type> <value>. Without “-v”, you don't get the sensor name, just a value, so that is important to add.
bash/mqtt/add_to_influxdb.1511993125.txt.gz · Last modified: 2017/11/29 23:05 by biggi
