Elvin Jafarov
Elvin Jafarov

Reputation: 1456

MQTT subscribing does not work properly in Multithreading

I have code like below


    threads = []
    t = threading.Thread(target=Subscribe('username', "password", "topic", "host",port).start)
    t1 = threading.Thread(target=Subscribe('username2', "password2", "topic2", "host",port).start)
    
    threads.append(t)
    threads.append(t1)
    
    for thread in threads:
        thread.start()
    
    for thread in threads:
        thread.join()

My topics send data in every 5 minutes.

When I use the code above,it does not work properly, sometimes it sends data sometimes it does not.

But when I use one topic without thread , it works fine and data is coming in every 5 minutes perfectly.

How can I solve this problem? I want to subscribe two topics simultaneously.

I am using Paho for MQTT

My subscribe class is

class Subscribe:

    def __init__(self, username, passowrd, topic, host, port):

        self.username = username
        self.password = passowrd
        self.topic = topic
        self.host = host
        self.port = port
       
      

    def start(self):
        self.mqttc = mqtt.Client(client_id="Python")
        self.connected = False
        self.mqtt_message = ""
        self.mqttc.username_pw_set(self.username, self.password)
        self.mqttc.on_connect = self.on_connect
        self.mqttc.on_message = self.on_message
        self.mqttc.connect(self.host, self.port)
        self.mqttc.loop_forever()

    def on_message(self, client, userdata, message):
        """
        Fetch data when data coming to Broker
        """
        topic = message.topic
        m = json.loads(message.payload.decode("utf-8"))
        print(m)

   


    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Connected to broker", self.topic)
            self.mqttc.subscribe(self.topic)
            self.connected = True

        else:
            print("could not connect", self.topic)

Upvotes: 5

Views: 668

Answers (1)

Elvin Jafarov
Elvin Jafarov

Reputation: 1456

I had to give two different client_ids for the two instances of Client and it solved the issue.

Upvotes: 1

Related Questions