From 55cbe33054563846057960a07669872d3b70c9ed Mon Sep 17 00:00:00 2001 From: Jesse Kleemann Date: Wed, 10 Jul 2024 23:34:52 +0200 Subject: [PATCH] log mqtt connection errors --- main.py | 2 +- mqtt_handler.py | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index b52ffca..2e41183 100644 --- a/main.py +++ b/main.py @@ -7,7 +7,7 @@ from modbus_handler import ModbusHandler from mqtt_handler import MqttHandler -__version__ = '1.0.1' +__version__ = '1.0.2' def convert_to_type(value: int, datatype: str) -> int: diff --git a/mqtt_handler.py b/mqtt_handler.py index 6e7c0fc..e6a2456 100644 --- a/mqtt_handler.py +++ b/mqtt_handler.py @@ -4,6 +4,8 @@ from time import sleep import paho.mqtt.client as mqtt +from paho.mqtt.packettypes import PacketTypes +from paho.mqtt.reasoncodes import ReasonCode from config import config @@ -15,7 +17,7 @@ def __init__(self): self.topic_prefix += '/' self.mqttc: mqtt.Client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) - self.mqttc.on_connect = self.mqtt_on_connect + self.mqttc.on_connect = self.on_connect self.mqttc.username_pw_set(config['mqtt_username'], config['mqtt_password']) self.mqttc.will_set(self.topic_prefix + 'available', 'offline', retain=True) self.mqttc.connect_async(host=config['mqtt_server'], port=config.get('mqtt_port', 1883)) @@ -26,9 +28,12 @@ def __init__(self): self.publishing_thread = threading.Thread(target=self.publishing_handler, daemon=True) self.publishing_thread.start() - def mqtt_on_connect(self, mqttc, userdata, flags, reason_code, properties): + def on_connect(self, client, userdata, connect_flags, reason_code, properties): self.mqttc.publish(self.topic_prefix + 'available', 'online', retain=True) - logging.info('mqtt connected.') + if reason_code == ReasonCode(PacketTypes.CONNACK, 'Success'): + logging.info('mqtt connected.') + else: + logging.error(f'mqtt connection failed {reason_code}.') def publish(self, topic, payload, retain=False): self.publishing_queue.put({