services/power-mqtt: Rewrite to Python

This commit is contained in:
polyfloyd 2024-02-04 18:27:21 +01:00
parent 1e9334ecfb
commit eff6091c5a
4 changed files with 35 additions and 23 deletions

View file

@ -1,7 +1,12 @@
---
- name: Install dependencies
apt:
name: [python3-paho-mqtt, python3-requests]
- name: Install power-mqtt
template:
src: power-mqtt.sh
dest: /var/lib/power-mqtt.sh
src: power-mqtt.py
dest: /var/lib/power-mqtt.py
owner: root
group: root
mode: 0755

View file

@ -0,0 +1,27 @@
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import paho.mqtt.subscribe as subscribe
from time import sleep
import requests
sdm630_host = '100.64.0.187'
mqtt_host = '{{ mqtt_internal_host }}'
client = mqtt.Client()
client.connect(mqtt_host, 1883, 60)
while True:
sleep(1)
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('bitlair/power/All/now_w', data['active_power_w'])
client.publish('bitlair/power/L1/now_w', data['active_power_l1_w'])
client.publish('bitlair/power/L2/now_w', data['active_power_l2_w'])
client.publish('bitlair/power/L3/now_w', data['active_power_l3_w'])
except Exception as err:
print(err)
continue

View file

@ -6,11 +6,10 @@ After=network.target
[Service]
Type=simple
ExecStart=/bin/bash /var/lib/power-mqtt.sh
ExecStart=/var/lib/power-mqtt.py
Restart=on-failure
RestartSec=10s
DynamicUser=true
[Install]
WantedBy=multi-user.target

View file

@ -1,19 +0,0 @@
#!/bin/bash
# Managed by Ansible
set -euo pipefail
h="{{ mqtt_internal_host }}"
while true; do
j=$(curl -s http://100.64.0.187/api/v1/data)
mqtt-simple -h $h -p bitlair/power/total_kwh -m $(echo "$j" | jq .total_power_import_kwh)
mqtt-simple -h $h -p bitlair/power/All/now_w -m $(echo "$j" | jq .active_power_w)
mqtt-simple -h $h -p bitlair/power/L1/now_w -m $(echo "$j" | jq .active_power_l1_w)
mqtt-simple -h $h -p bitlair/power/L2/now_w -m $(echo "$j" | jq .active_power_l2_w)
mqtt-simple -h $h -p bitlair/power/L3/now_w -m $(echo "$j" | jq .active_power_l3_w)
sleep 1
done