Files
chargeman/mqtthandler.py
T
2026-11-11 18:52:40 +01:00

83 lines
2.1 KiB
Python

import paho.mqtt.client as mqtt
import logging
import time
import controller
from mqtttopic import *
logger = logging.getLogger('main')
class handler:
def __init__(self, controller: controller.chargeman_controller):
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1)
self.publisher = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1)
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.controller = controller
self.variables = {}
while True:
try:
self.client.connect(broker,port, 60)
self.client.loop_start()
break
except:
logger.info("Unable to connect to mqtt")
time.sleep(5)
def subscribing(self):
pass
#while True:
# rc = self.client.loop(timeout=0.1)
# if rc != 0:
# if not self.client.is_connected:
# logger.warning("MQTT subscriber connection disconnected. Reconnecting...")
# self.client.reconnect()
# The callback for when the client receives a CONNACK response from the server.
def on_connect(self,client, userdata, flags, rc):
logger.info("Connected mqtt handler to mqtt with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(topic_chargemode)
client.subscribe(topic_p1_consumption)
client.subscribe(topic_p1_return)
# The callback for when a PUBLISH message is received from the server.
def on_message(self,client, userdata, msg):
logger.debug(msg.topic+" "+str(msg.payload))
if msg.topic == topic_chargemode:
self.controller.set_chargemode_int(int(msg.payload))
elif msg.topic == topic_p1_consumption:
self.controller.set_net_consumption( int(msg.payload))
elif msg.topic == topic_p1_return:
self.controller.set_net_delivery( int(msg.payload))