Untitled
unknown
plain_text
a month ago
1.6 kB
1
Indexable
Never
from gpiozero import Button from time import sleep import paho.mqtt.client as mqtt import json from datetime import datetime # Pfad zur Datei, die den Impulszähler speichert COUNTER_FILE = "/home/ETA/Desktop/impulse_count.txt" def save_impulse_count(count): with open(COUNTER_FILE, 'w') as file: file.write(str(count)) def load_impulse_count(): try: with open(COUNTER_FILE, 'r') as file: return int(file.read()) except FileNotFoundError: return 0 # Anzahl der Impulse pro kWh, laut Dokumentation anpassen IMPULSES_PER_KWH = 1000 # MQTT-Setup client = mqtt.Client() client.connect("localhost", 1883, 60) # Stelle sicher, dass dies auf deine MQTT-Broker-Konfiguration passt client.loop_start() # GPIO-Setup mit gpiozero button = Button(17) impulse_count = load_impulse_count() # Lade den gespeicherten Impulszähler def impulse_detected(): global impulse_count impulse_count += 1 save_impulse_count(impulse_count) # Speichere den aktuellen Zählerstand kWh = impulse_count / IMPULSES_PER_KWH message = { "value": kWh, "timestamp": int(datetime.now().timestamp()), "description": "Stromzähler" } client.publish("home/energy", json.dumps(message)) print("Sent:", json.dumps(message)) button.when_pressed = impulse_detected try: while True: sleep(1) except KeyboardInterrupt: print("Programm wird durch Benutzer beendet.") finally: client.loop_stop() client.disconnect()
Leave a Comment