Using Paho-MQTT in streamlit

Hello,

I’m new to streamlit and to using MQTT with it.

Nonetheless, I am trying to build an app that connects to an MQTT server to fetch data of a lot of sensors. Hence my search for a robust and scalable architecture using MQTT and streamlit. Is there any good example where I can find more information ?

In the meanwhile I am trying to use threads in an MQTT connection (on_connect and on_message). I was trying to use this solution to be able to use streamlit inside the threads (as seen in Live plot from a thread - #12 by hcoohb). But I get the following error:

AttributeError: module ‘streamlit’ has no attribute ‘ReportThread’

Is it due to the new version of streamlit ? I have tried downgrading it to 1.3.0 and it does not change the error

Is there a better way of using Paho-MQTT in python and streamlit ?

def connect_mqtt():

    KEY_CONTEXT = st.ReportThread.REPORT_CONTEXT_ATTR_NAME
    main_context = getattr(current_thread(), KEY_CONTEXT)

    def on_connect(client, userdata, flags, rc):
        thread = current_thread()
        if getattr(thread, KEY_CONTEXT, None) is None:
            setattr(thread, KEY_CONTEXT, main_context)
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect to MQTT broker, return code %d\n", rc)

    def on_message(client, userdata, msg):
        thread = current_thread()
        if getattr(thread, KEY_CONTEXT, None) is None:
            setattr(thread, KEY_CONTEXT, main_context)
       
        st.session_state["message"] = "Save message received from MQTT broker"

        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        print("message received ", str(msg.payload.decode("utf-8")))
        print("message topic=", msg.topic)
        print("message qos=", msg.qos)
        print("message retain flag=", msg.retain)

    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(broker, port)
    return client