11import logging
22import paho .mqtt .client as mqtt
3+ import asyncio
34
45_LOGGER = logging .getLogger (__name__ )
56
67class MicrobeesMqtt :
78 """Class to handle MQTT communication with the microBees platform."""
8-
9+
910 def __init__ (self , broker , port , username , password , client_id , on_message_callback = None ):
1011 self .broker = broker
1112 self .port = port
@@ -21,7 +22,7 @@ def __init__(self, broker, port, username, password, client_id, on_message_callb
2122 # Use the new API for setting callbacks
2223 self .client .on_connect = self ._on_connect
2324 self .client .on_disconnect = self ._on_disconnect
24- self .client .on_message = self ._on_message if on_message_callback else None
25+ self .client .on_message = self ._on_message
2526
2627 def _on_connect (self , client , userdata , flags , rc ):
2728 """Handle connection to the broker."""
@@ -30,15 +31,18 @@ def _on_connect(self, client, userdata, flags, rc):
3031
3132 def _on_disconnect (self , client , userdata , rc ):
3233 """Handle disconnection from the broker."""
34+ if rc != 0 :
35+ _LOGGER .warning (f"Disconnected from MQTT broker with error code { rc } " )
3336
3437 def _on_message (self , client , userdata , message ):
35- """Handle incoming messages."""
36- if self . on_message_callback :
37- self .on_message_callback (message )
38+ loop = asyncio . new_event_loop ()
39+ asyncio . set_event_loop ( loop )
40+ loop . run_until_complete ( self .on_message_callback (message ) )
3841
3942 def connect (self ):
4043 """Connect to the MQTT broker."""
4144 self .client .connect (self .broker , self .port )
45+ self .client .loop_start ()
4246
4347 def disconnect (self ):
4448 """Disconnect from the MQTT broker."""
@@ -52,6 +56,6 @@ def publish(self, topic, payload, qos=0):
5256 """Publish a message to a topic."""
5357 self .client .publish (topic , payload , qos )
5458
55- def loop_forever (self ):
56- """Start the network loop."""
57- self .client .loop_forever ()
59+ async def async_loop (self ):
60+ """Run the MQTT loop in an asyncio-friendly way ."""
61+ self .client .loop_forever ()
0 commit comments