From: Hmvp Date: Tue, 16 Sep 2014 08:38:47 +0000 (+0200) Subject: Retry the first connection attempt in face of errors X-Git-Url: https://git.michaelhowe.org/gitweb/?a=commitdiff_plain;h=5bbe937997868c90c509ba8eac97c94202b6ea0a;p=packages%2Fp%2Fpaho-mqtt.git Retry the first connection attempt in face of errors When using connect async and loop_forever it is expected that connection errors lead to a reconnect The first connection is not retried. This patch changes that To preserve backward compatibility added behind boolean Change-Id: I919595beb57ce8dd7da6da601760a2775634cf50 Signed-off-by: Hmvp --- diff --git a/README.rst b/README.rst index 890a613..1903090 100644 --- a/README.rst +++ b/README.rst @@ -434,10 +434,12 @@ loop_forever() :: - loop_forever(timeout=1.0, max_packets=1) + loop_forever(timeout=1.0, max_packets=1, retry_first_connection=False) This is a blocking form of the network loop and will not return until the client calls ``disconnect()``. It automatically handles reconnecting. +Except for the first connection attempt when using connect_async, use ``retry_first_connection=True`` to make it retry the first connection. Warning: This might lead to situations where the client keeps connecting to an non existing host without failing. + The ``timeout`` and ``max_packets`` arguments are obsolete and should be left unset. Publishing diff --git a/src/paho/mqtt/client.py b/src/paho/mqtt/client.py index b662aeb..72c5505 100755 --- a/src/paho/mqtt/client.py +++ b/src/paho/mqtt/client.py @@ -1224,17 +1224,36 @@ class Client(object): else: return self._sock - def loop_forever(self, timeout=1.0, max_packets=1): + def loop_forever(self, timeout=1.0, max_packets=1, retry_first_connection=False): """This function call loop() for you in an infinite blocking loop. It is useful for the case where you only want to run the MQTT client loop in your program. loop_forever() will handle reconnecting for you. If you call - disconnect() in a callback it will return.""" + disconnect() in a callback it will return. + + + timeout: The time in seconds to wait for incoming/outgoing network + traffic before timing out and returning. + max_packets: Not currently used. + retry_first_connection: Should the first connection attempt be retried on failure. + + Raises socket.error on first connection failures unless retry_first_connection=True + """ run = True - if self._state == mqtt_cs_connect_async: - self.reconnect() + + while run: + if self._state == mqtt_cs_connect_async: + try: + self.reconnect() + except socket.error: + if not retry_first_connection: + raise + self._easy_log(MQTT_LOG_DEBUG, "Connection failed, retrying") + time.sleep(1) + else: + break while run: rc = MQTT_ERR_SUCCESS