scalefix/mqtt2influx.py

32 lines
905 B
Python
Raw Permalink Normal View History

2020-03-12 19:03:23 +01:00
import paho.mqtt.subscribe as sub
import json
from influxdb import InfluxDBClient
import datetime
DB = ('habctrl', 8086)
BROKER = ('homeproxy', 1883)
TOPIC_PREFIX = 'scalefix'
TOPIC_WEIGHTS = TOPIC_PREFIX+'/weights'
def handle_msg(client, userdata, message):
data = json.loads(message.payload.decode('utf-8'))
print(f'got data for {data["user"]}: {data["weight"]}')
client = InfluxDBClient(DB[0], DB[1], 'scalefix', 'weighting', 'scale')
json_body = [
{
"measurement": "weights",
"tags": {
"user": data['user'],
},
"time": datetime.datetime.fromtimestamp(data['timestamp']).isoformat(),
"fields": {
"value": data['weight']
}
}
]
client.write_points(json_body)
client.close()
sub.callback(handle_msg, [TOPIC_WEIGHTS], hostname=BROKER[0], port=BROKER[1])