Skip to content

Commit 17ad28f

Browse files
committed
Migrate Paho MQTT client to CallbackAPI version 2
1 parent d4a17de commit 17ad28f

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

main.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -121,18 +121,20 @@ def onLost(interface):
121121
username = config["username"] if "username" in config else None
122122
password = config["password"] if "password" in config else None
123123

124-
logger.info(f"Connected to MQTT {config['name']}")
125-
124+
callback_version = mqtt.CallbackAPIVersion.VERSION2
126125
if client_id:
127-
mqttc = mqtt.Client(client_id)
126+
mqttc = mqtt.Client(callback_version, client_id)
128127
else:
129-
mqttc = mqtt.Client()
128+
mqttc = mqtt.Client(callback_version)
130129

131130
if username and password:
132131
mqttc.username_pw_set(username, password)
133132

134-
def on_connect(mqttc, obj, flags, rc):
135-
logger.debug(f"Connected to MQTT {config['name']}")
133+
def on_connect(mqtt, obj, flags, rc, props):
134+
if rc.is_failure:
135+
logger.error(f"Could not connect to MQTT {config['name']} [{rc}]")
136+
else:
137+
logger.info(f"Connected to MQTT {config['name']}")
136138

137139
def on_message(mqttc, obj, msg):
138140
orig_packet = msg.payload.decode()
@@ -171,11 +173,18 @@ def on_message(mqttc, obj, msg):
171173
logger.error(f"Hit an error: {e}", exc_info=True)
172174
logger.debug(f"MQTT {config['name']} pipeline {pipeline} finished")
173175

174-
def on_publish(mqttc, obj, mid):
175-
logger.debug(f"MQTT {config['name']}: on_publish: {mid}")
176-
177-
def on_subscribe(mqttc, obj, mid, granted_qos):
178-
logger.debug(f"MQTT {config['name']}: on_subscribe: {mid}")
176+
def on_publish(mqttc, obj, mid, rc, props):
177+
if rc.is_failure:
178+
logger.error(f"MQTT {config['name']}: Could not publish message ID: {mid} [{rc}]")
179+
else:
180+
logger.debug(f"MQTT {config['name']}: Published message ID: {mid}")
181+
182+
def on_subscribe(mqttc, obj, mid, rc_list, props):
183+
for rc in rc_list:
184+
if rc.is_failure:
185+
logger.error(f"MQTT {config['name']}: Subscription failed [{rc}]")
186+
else:
187+
logger.debug(f"MQTT {config['name']}: Subscribed to topic [{rc}]")
179188

180189
mqttc.on_message = on_message
181190
mqttc.on_connect = on_connect

0 commit comments

Comments
 (0)