bundlewrap/bundles/mosquitto/files/tasmota-telegraf-plugin
Franzi 32826ed131
Some checks failed
bundlewrap/pipeline/head There was a failure building this commit
bundles/mosquitto: add telegraf stats for tasmota devices
2021-05-15 08:52:37 +02:00

54 lines
3 KiB
Python

#!/usr/bin/env python3
from json import loads
from subprocess import Popen, PIPE
from sys import argv, stderr
from time import sleep
while True:
try:
proc = Popen(['mosquitto_sub', '-h', argv[1], '-v', '-t', argv[2]], stdout=PIPE)
while True:
try:
line = proc.stdout.readline().decode().strip()
if not line:
continue
topic, message = line.split(' ', 1)
if not any(message.startswith(i) for i in ['{', '[']):
# probably not json
continue
json = loads(message)
topic_split = topic.strip('/').split('/')
sensor_name = '_'.join(topic_split[:-1])
if topic_split[-1] == 'STATE':
# /switch/wohnzimmer/ambilight/STATE {"Time":"2021-05-15T07:40:16","Uptime":"4T18:48:43","Vcc":3.108,"Heap":19,"SleepMode":"Dynamic","Sleep":50,"LoadAvg":19,"POWER":"OFF","Wifi":{"AP":1,"SSId":"NSA Surveillance Van 2342","BSSId":"DA:CC:46:87:58:F7","Channel":6,"RSSI":100,"LinkCount":2,"Downtime":"0T00:00:27"}}
power_state = bool(json['POWER'] == 'ON')
print(f'tasmota,device={sensor_name} state={power_state}', flush=True)
print(f'tasmota,device={sensor_name} rssi={json["Wifi"]["RSSI"]}i', flush=True)
if topic_split[-1] == 'SENSOR':
# /switch/wohnzimmer/ambilight/SENSOR {"Time":"2021-05-15T07:40:16","ENERGY":{"TotalStartTime":"2019-08-02T13:56:56","Total":2.324,"Yesterday":0.004,"Today":0.000,"Period":0,"Power":0,"ApparentPower":0,"ReactivePower":0,"Factor":0.00,"Voltage":237,"Current":0.000}}
print(f'tasmota,device={sensor_name} energy_total={json["ENERGY"]["Total"]}', flush=True)
print(f'tasmota,device={sensor_name} energy_today={json["ENERGY"]["Today"]}', flush=True)
print(f'tasmota,device={sensor_name} energy_yesterday={json["ENERGY"]["Yesterday"]}', flush=True)
print(f'tasmota,device={sensor_name} power={json["ENERGY"]["Power"]}', flush=True)
print(f'tasmota,device={sensor_name} apparent_power={json["ENERGY"]["ApparentPower"]}', flush=True)
print(f'tasmota,device={sensor_name} reactive_power={json["ENERGY"]["ReactivePower"]}', flush=True)
print(f'tasmota,device={sensor_name} powerfactor={json["ENERGY"]["Factor"]}', flush=True)
print(f'tasmota,device={sensor_name} voltage={json["ENERGY"]["Voltage"]}i', flush=True)
print(f'tasmota,device={sensor_name} current={json["ENERGY"]["Current"]}', flush=True)
except Exception as e:
if line:
print('parse error while parsing a line:', file=stderr)
print(line, file=stderr)
print(repr(e), file=stderr, flush=True)
except Exception as e:
print(repr(e), file=stderr, flush=True)
sleep(10)