Skip to content

Commit

Permalink
Add on_pre_connect() callback
Browse files Browse the repository at this point in the history
This is called immediately before a connection attempt is made.
  • Loading branch information
ralight committed Jan 21, 2023
1 parent 9782ab8 commit a4cb435
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
7 changes: 7 additions & 0 deletions ChangeLog.txt
Original file line number Diff line number Diff line change
@@ -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
===================

Expand Down
4 changes: 4 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
41 changes: 41 additions & 0 deletions src/paho/mqtt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit a4cb435

Please sign in to comment.