How can I use paho MQTT client and live update of dash?

Hi,

I want to receive data from MQTT broker using paho-mqtt library. I want to display data on a live graph using plotly.
I wrote already a small script and it receives json-data from MQTT. I can olsa run “live update” example from dash documentation. But I don’t know how can I combine these two processes and how can I display MQTT data?

Thanks.

1 Like

Ok I solved my own question :slight_smile:

I was using client.loop_forever() function in paho mqtt library. This function is blocking and main thread doesn’t continue.
I used client.loop_start(). This function starts the loop in another thread and main thread can continue.

Can you post an example of the working code? I’m not able to get it working using loop_start() as you mentioned.

I can not post whole code but I post some pseudo code:

def on_message(client, userdata, message):
....
def on_connect(client, userdata, flags, rc):
    print("---Connected to MQTT Broker.")
    client.subscribe("topic")

app = dash.Dash(__name__)
app.index_string = ...
app.layout =  html.Main(...)

if __name__ == '__main__':
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set(username = "debug", password = "debug")
    client.connect("localhost", 1883)
    client.loop_start()
    app.run_server(debug = True, port = portnumber_scoreapp, host='0.0.0.0')