Done stuff

This commit is contained in:
2021-02-20 00:06:59 +13:00
parent 8a022dd35b
commit 9b7088d131
5 changed files with 102 additions and 1 deletions

10
mqttinflux/Dockerfile Normal file
View File

@@ -0,0 +1,10 @@
FROM python:slim
ENV MQTT_PORT 1883
ENV INFLUX_PORT 8086
RUN pip install influxdb paho-mqtt
COPY main.py /main.py
CMD [ "python", "/main.py" ]

49
mqttinflux/main.py Normal file
View File

@@ -0,0 +1,49 @@
import paho.mqtt.client as mqtt
from influxdb import InfluxDBClient
import datetime
import logging
import json
import os
def on_connect(client, userdata, flags, rc):
for topic in topics:
client.subscribe(topic)
def on_message(client, userdata, msg):
current_time = datetime.datetime.utcnow().isoformat()
data = json.loads(msg.payload)
print(data)
json_body = [
{
"measurement": msg.topic,
"tags": {},
"time": current_time,
"fields": data
}
]
logging.info(json_body)
influx_client.write_points(json_body)
if 'TOPICS' not in os.environ:
print("At least one topic is needed.")
exit(1)
topics = os.environ['TOPICS'].split(' ')
print(topics)
logging.basicConfig(level=logging.INFO)
influx_client = InfluxDBClient(os.environ['INFLUX_HOST'], int(os.environ['INFLUX_PORT']), database=os.environ["INFLUX_DB"])
influx_client.create_database(os.environ["INFLUX_DB"])
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(os.environ['MQTT_HOST'], int(os.environ["MQTT_PORT"]), 60)
print("Starting")
client.loop_forever()