loop_forever vs KeyboardInterrupt?
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?
try move the
except KeyboardInterrupt:
mqtt_client.disconnect()
to the def mqtt_client(): inside?
@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.
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.
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).