Skip to content

Commit

Permalink
log mqtt connection errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jesseklm committed Jul 10, 2024
1 parent 0c7281c commit 55cbe33
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
11 changes: 8 additions & 3 deletions mqtt_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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))
Expand All @@ -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({
Expand Down

0 comments on commit 55cbe33

Please sign in to comment.