Manage the network loop with loop_start, loop_forever, or loop
masterThe network loop functions are essential for processing incoming/outgoing data and dispatching callbacks. Do not mix different loop functions. There are three primary ways to manage the loop:
loop_start()/loop_stop(): Implements a threaded interface.loop_start()runs a background thread to callloop()automatically, freeing the main thread for other tasks. It also handles automatic reconnection. Useloop_stop()to terminate the thread.loop_forever(): A blocking call that processes network traffic and handles reconnections. It will not return untildisconnect()is called. Useretry_first_connection=Trueto retry the initial connection attempt.loop(): A manual, non-blocking (up to atimeout) call. You must call this regularly in a loop to process network events. If using this method, you are responsible for implementing your own reconnection strategy.
# Threaded interface example
mqttc.loop_start()
while True:
temperature = sensor.blocking_read()
mqttc.publish("paho/temperature", temperature)
mqttc.loop_stop()