diff --git a/ChangeLog.txt b/ChangeLog.txt index ab57c1a8..cf794c88 100644 --- a/ChangeLog.txt +++ b/ChangeLog.txt @@ -1,3 +1,10 @@ +v1.7.0 - 2023-xx-xx +=================== + +- Add on_pre_connect() callback, which is called immediately before a + connection attempt is made. + + v1.6.1 - 2021-10-21 =================== diff --git a/README.rst b/README.rst index e060cef2..e66ffbb2 100644 --- a/README.rst +++ b/README.rst @@ -468,6 +468,10 @@ bind_address Callback ........ +Immediately prior to the connection attempt, the `on_pre_connect()` callback +will be called. This is a useful callback to set information that must be done +before the connection starts, e.g., calling `will_set()`. + When the client receives a CONNACK message from the broker in response to the connect it generates an ``on_connect()`` callback. diff --git a/src/paho/mqtt/client.py b/src/paho/mqtt/client.py index 1c0236e4..54405a4e 100644 --- a/src/paho/mqtt/client.py +++ b/src/paho/mqtt/client.py @@ -1041,6 +1041,18 @@ def reconnect(self): # Put messages in progress in a valid state. self._messages_reconnect_reset() + with self._callback_mutex: + on_pre_connect = self.on_pre_connect + + if on_pre_connect: + try: + on_pre_connect(self, self._userdata) + except Exception as err: + self._easy_log( + MQTT_LOG_ERR, 'Caught exception in on_pre_connect: %s', err) + if not self.suppress_exceptions: + raise + sock = self._create_socket_connection() if self._ssl: @@ -1844,6 +1856,35 @@ def decorator(func): return func return decorator + @property + def on_pre_connect(self): + """If implemented, called immediately prior to the connection is made + request.""" + return self._on_pre_connect + + @on_pre_connect.setter + def on_pre_connect(self, func): + """ Define the pre_connect callback implementation. + + Expected signature: + connect_callback(client, userdata) + + client: the client instance for this callback + userdata: the private user data as set in Client() or userdata_set() + + Decorator: @client.pre_connect_callback() (```client``` is the name of the + instance which this callback is being attached to) + + """ + with self._callback_mutex: + self._on_pre_connect = func + + def pre_connect_callback(self): + def decorator(func): + self.on_pre_connect = func + return func + return decorator + @property def on_connect(self): """If implemented, called when the broker responds to our connection