paho.mqtt.python icon indicating copy to clipboard operation
paho.mqtt.python copied to clipboard

loop_forever vs KeyboardInterrupt?

Open eugene-kulak opened this issue 5 years ago • 3 comments

def mqtt_client():
    def on_connect(_client, _userdata, _flags, _rc):
        logger.info("Connected to MQTT")

    def on_log(_client, _userdata, _level, buf):
        logger.log(_level, buf)

    client = mqtt.Client(client_id=config.mqtt_client_id, transport=transport)
    client.on_connect = on_connect
    client.on_log = on_log

    client.connect(mqtt_uri.hostname, mqtt_uri.port)
    return client


def main():
    client = mqtt_client()
    try:
        mqtt_client.loop_forever()
    except KeyboardInterrupt:
        mqtt_client.disconnect()

Now if I run it and try to stop with Ctr+C, I see that client tries to reconnect. Why? What kind of design this is?

eugene-kulak avatar Aug 16 '20 23:08 eugene-kulak

try move the

except KeyboardInterrupt:
        mqtt_client.disconnect()

to the def mqtt_client(): inside?

minexo79 avatar Sep 09 '20 00:09 minexo79

@minexo79, I don't understand your suggestion. That does not address the issue, as I see the code design. Both loop_forever() and loop_start() appear to be blocking the main thread once any connection is established. Once the any mqtt client loop is established, the main thread never gets time again. Which does not match, IMHO, how the documentation reads, that these are not blocking functions, which is true until the first connection is established.

I have seen the following for example, connect_async() then loop_start() do not block until the connect established, from then on, messages are handled, as expected but the main thread never gets time again.

dachshund-digital avatar Jun 13 '21 15:06 dachshund-digital

Reading some other issues, I think mine is covered under the discussion on the differences of connect() vs. connect_async() documentation gaps and how some have seen loop API calls failing under specific scenarios.

dachshund-digital avatar Aug 29 '21 23:08 dachshund-digital

PR #615 has now been merged; hopefully this addresses the issues you found in the documentation. Given the age of this issue I'm going to close it (if you would like a resolution can you please enable logging and duplicate the issue then provide the full output).

MattBrittan avatar Dec 24 '23 00:12 MattBrittan