@@ -65,6 +65,7 @@ def __init__(self,
65
65
disconnected_msg : types .JSONRPCMessage | None = None ,
66
66
disconnected_msg_retain : bool = True ):
67
67
self ._read_stream_writers = {}
68
+ self ._last_connect_fail_reason = None
68
69
self .mqtt_clientid = mqtt_clientid
69
70
self .mcp_component_type = mcp_component_type
70
71
self .mqtt_options = mqtt_options
@@ -74,7 +75,11 @@ def __init__(self,
74
75
callback_api_version = CallbackAPIVersion .VERSION2 ,
75
76
client_id = mqtt_clientid , protocol = mqtt .MQTTv5 ,
76
77
userdata = {},
77
- transport = mqtt_options .transport , reconnect_on_failure = True
78
+ transport = mqtt_options .transport ,
79
+ reconnect_on_failure = True
80
+ )
81
+ client .reconnect_delay_set (
82
+ min_delay = 1 , max_delay = 120
78
83
)
79
84
client .username_pw_set (mqtt_options .username , mqtt_options .password .get_secret_value () if mqtt_options .password else None )
80
85
if mqtt_options .tls_enabled :
@@ -123,12 +128,13 @@ async def __aexit__(
123
128
self ._task_group .cancel_scope .cancel ()
124
129
return await self ._task_group .__aexit__ (exc_type , exc_val , exc_tb )
125
130
126
- def _on_connect (self , client : mqtt .Client , userdata : Any , connect_flags : mqtt .ConnectFlags , reason_code : ReasonCode , properties : Properties | None ):
131
+ def _on_connect (self , client : mqtt .Client , userdata : Any , connect_flags : mqtt .ConnectFlags , reason_code : ReasonCode , properties : Properties | None ):
127
132
if reason_code == 0 :
128
133
logger .debug (f"Connected to MQTT broker_host at { self .mqtt_options .host } :{ self .mqtt_options .port } " )
129
134
self .assert_property (properties , "RetainAvailable" , 1 )
130
135
self .assert_property (properties , "WildcardSubscriptionAvailable" , 1 )
131
136
else :
137
+ self ._last_connect_fail_reason = reason_code
132
138
logger .error (f"Failed to connect, return code { reason_code } " )
133
139
134
140
def _on_message (self , client : mqtt .Client , userdata : Any , msg : mqtt .MQTTMessage ):
@@ -138,6 +144,12 @@ def _on_subscribe(self, client: mqtt.Client, userdata: Any, mid: int,
138
144
reason_code_list : list [ReasonCode ], properties : Properties | None ):
139
145
pass
140
146
147
+ def is_connected (self ) -> bool :
148
+ return self .client .is_connected ()
149
+
150
+ def get_last_connect_fail_reason (self ) -> ReasonCode | None :
151
+ return self ._last_connect_fail_reason
152
+
141
153
def publish_json_rpc_message (self , topic : str , message : types .JSONRPCMessage | None ,
142
154
retain : bool = False ):
143
155
props = self .get_publish_properties ()
0 commit comments