Add initial state of huette energy consumption per week day script

main
Tim Dithmer 2024-10-28 21:07:57 +01:00
commit 42480df5c1
6 changed files with 100 additions and 0 deletions

1
.dockerignore 100644
View File

@ -0,0 +1 @@
venv/

1
.gitignore vendored 100644
View File

@ -0,0 +1 @@
venv/

9
Dockerfile 100644
View File

@ -0,0 +1,9 @@
FROM python:3.12-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["python3", "main.py"]

11
README 100644
View File

@ -0,0 +1,11 @@
# Build
```
docker build -t huette-energy-consumption-weekperday .
```
# Run
```
docker run -d -e MQTT_HOST=10.2.3.2 -e MQTT_TOPIC=c3re/huette/energy/consumption/week_per_day -t huette-energy-consumption-weekperday
```

72
main.py 100644
View File

@ -0,0 +1,72 @@
import datetime # Import datetime module
import requests
import paho.mqtt.client as mqtt
import paho.mqtt.enums as mqtt_enums
import os
import json
import time
base_url = "https://prom.c3re.de/api/v1/query"
def get_params(timestamp):
return {
"query": 'energy{location="Hütte", type="Energymeter"}',
"time": str(timestamp),
}
def calc_prometheus_response_value_diff(response_before, response_after):
return int(response_after.json()["data"]["result"][0]["value"][1]) - int(
response_before.json()["data"]["result"][0]["value"][1]
)
def get_energy_consumption_between(b, a):
response_before = requests.get(base_url, params=get_params(b.timestamp()))
response_after = requests.get(base_url, params=get_params(a.timestamp()))
return calc_prometheus_response_value_diff(response_before, response_after)
def get_energy_consumption_1_day(n):
return get_energy_consumption_between(n - datetime.timedelta(days=1), n)
def get_energy_consumption_today():
return get_energy_consumption_between(
datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0),
datetime.datetime.now(),
)
def main():
host = os.getenv("MQTT_HOST")
port = int(os.getenv("MQTT_PORT", 1883))
topic = os.getenv("MQTT_TOPIC")
mqttc = mqtt.Client(mqtt_enums.CallbackAPIVersion.VERSION2)
mqttc.connect(host, port)
mqttc.loop_start()
while True:
consumptions = []
consumptions.append(get_energy_consumption_today())
n = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
days_back = 1
while days_back <= 7:
consumptions.append(get_energy_consumption_1_day(n))
days_back += 1
n -= datetime.timedelta(days=1)
print("sending data")
print(consumptions)
consumptions_msg = mqttc.publish(topic, json.dumps(consumptions))
consumptions_msg.wait_for_publish()
time.sleep(15)
if __name__ == "__main__":
main()

6
requirements.txt 100644
View File

@ -0,0 +1,6 @@
certifi==2024.8.30
charset-normalizer==3.4.0
idna==3.10
paho-mqtt==2.1.0
requests==2.32.3
urllib3==2.2.3