@@ -16,20 +16,24 @@ class MQTTManager(ResourceManager):
1616 _topic_lock = attr .ib (default = threading .Lock ())
1717 _last = attr .ib (default = 0.0 , validator = attr .validators .instance_of (float ))
1818
19- def _create_mqtt_connection (self , host ):
19+ def _create_mqtt_connection (self , host , username , password ):
2020 import paho .mqtt .client as mqtt
2121
2222 client = mqtt .Client (mqtt .CallbackAPIVersion .VERSION2 )
23+ client .username_pw_set (username , password )
2324 client .connect (host )
2425 client .on_message = self ._on_message
2526 client .loop_start ()
2627 return client
2728
2829 def on_resource_added (self , resource ):
2930 host = resource .host
30- if host not in self ._clients :
31- self ._clients [host ] = self ._create_mqtt_connection (host )
32- self ._clients [host ].subscribe (resource .avail_topic )
31+ username = resource .username
32+ password = resource .password
33+ key = f"{ host } :{ username or '' } :{ password or '' } "
34+ if key not in self ._clients :
35+ self ._clients [key ] = self ._create_mqtt_connection (host , username , password )
36+ self ._clients [key ].subscribe (resource .avail_topic )
3337
3438 def _on_message (self , client , userdata , msg ):
3539 payload = msg .payload .decode ("utf-8" )
@@ -57,6 +61,8 @@ class MQTTResource(ManagedResource):
5761
5862 host = attr .ib (validator = attr .validators .instance_of (str ))
5963 avail_topic = attr .ib (validator = attr .validators .instance_of (str ))
64+ username = attr .ib (default = None , validator = attr .validators .optional (attr .validators .instance_of (str )))
65+ password = attr .ib (default = None , validator = attr .validators .optional (attr .validators .instance_of (str )))
6066
6167 def __attrs_post_init__ (self ):
6268 self .timeout = 30.0
0 commit comments