Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

loop_forever vs KeyboardInterrupt? #510

Closed
eugene-kulak opened this issue Aug 16, 2020 · 4 comments
Closed

loop_forever vs KeyboardInterrupt? #510

eugene-kulak opened this issue Aug 16, 2020 · 4 comments

Comments

@eugene-kulak
Copy link

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?

@minexo79
Copy link

minexo79 commented Sep 9, 2020

try move the

except KeyboardInterrupt:
        mqtt_client.disconnect()

to the def mqtt_client(): inside?

@dachshund-digital
Copy link

@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
Copy link

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.

@MattBrittan
Copy link
Contributor

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants