|
#!/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() |