Skip to content

Commit 9e522de

Browse files
committed
Improve MQTT connection test
1 parent 475788c commit 9e522de

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

inelsmqtt/__init__.py

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -180,16 +180,43 @@ def test_connection(self) -> Optional[int]:
180180
"""Test connection. It's used only for connection
181181
testing. After that is disconnected
182182
Returns:
183-
bool: Is broker available or not
183+
Optional[int]: Connection error code:
184+
None: Success
185+
1: Protocol version mismatch
186+
2: Client identifier rejected
187+
3: Server unavailable
188+
4: Bad username/password
189+
5: Not authorized
190+
6: Unknown error
184191
"""
192+
self.__connection_error = None
193+
194+
def on_connect(client, userdata, flags, rc):
195+
if rc != 0:
196+
self.__connection_error = rc
197+
else:
198+
self.__try_connect = True
199+
185200
try:
201+
default_connect_handler = self.__client.on_connect
202+
self.__client.on_connect = on_connect
203+
186204
self.__connect()
187-
self.disconnect()
205+
206+
start_time = time.time()
207+
while time.time() - start_time < 5:
208+
if self.__connection_error is not None or self.__try_connect:
209+
break
210+
time.sleep(0.1)
211+
212+
except TimeoutError:
213+
# In the Paho MQTT client implementation, the on_connect callback is only triggered when the client actually receives a CONNACK packet from the broker. If the connection attempt times out before receiving this packet, the callback is never executed.
214+
self.__connection_error = 3 # Server unavailable
188215
except Exception as e:
189-
if isinstance(e, ConnectionRefusedError):
190-
self.__connection_error = 3 # cannot connect
191-
else:
192-
self.__connection_error = 6 # unknown
216+
self.__connection_error = 6 # Unknown error
217+
finally:
218+
self.__client.on_connect = default_connect_handler
219+
self.disconnect()
193220

194221
return self.__connection_error
195222

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
setup(
66
name="elkoep-mqtt",
7-
version="0.2.33.beta.18",
7+
version="0.2.33.beta.19",
88
url="https://github.com/epdevlab/elkoep-mqtt",
99
license="MIT",
1010
author="Elko EP s.r.o.",

0 commit comments

Comments
 (0)