ansible/roles/services/templates/power-mqtt.py

31 lines
922 B
Python

#!/usr/bin/env python3
# {{ ansible_managed }}
import paho.mqtt.client as mqtt
import paho.mqtt.subscribe as subscribe
from time import sleep
import sys
import requests
mqtt_host = '{{ mqtt_internal_host }}'
(net, sdm630_host) = sys.argv[1].split(':')
client = mqtt.Client()
client.connect(mqtt_host, 1883, 60)
client.loop_start()
while True:
sleep(10)
try:
data = requests.get(f'http://{sdm630_host}/api/v1/data').json()
client.publish('bitlair/power/total_kwh', data['total_power_import_kwh'])
client.publish(f'bitlair/power/{net}/All/now_w', data['active_power_w'])
client.publish(f'bitlair/power/{net}/L1/now_w', data['active_power_l1_w'])
client.publish(f'bitlair/power/{net}/L2/now_w', data['active_power_l2_w'])
client.publish(f'bitlair/power/{net}/L3/now_w', data['active_power_l3_w'])
except Exception as err:
print(err)
continue