Search code examples
pythonpython-3.xmqttmosquittopaho

How to publish with many publishers to one subscriber?


I need to build a network with multiple publishers, one broker, and one subscriber.

Issue: I have a working code with one to one option (one pub - one sub). However, when I run more publishers the subscriber receives messages only from the last connected publisher and I have no idea why it is happening.

More information: Broker (mosquitto) is working in a docker container, each publisher is a separate script and the target is to run multiple docker containers with one publisher in each container, but now I need to work around the communication issue.

Does anyone have any clues or ideas on how to debug or solved this?

This is the publisher script:

    import time
    import paho.mqtt.client as mqtt
    import datetime
    import random
    import json
    import logging
    from multiprocessing import Process

    CLEAN_SESSION = False


    def on_connect(client, userdata, flags, rc):
        logging.info(f"New connection {client}, {rc}")


    def sensor(client_id):
        
        localhost = '172.17.0.2'
        port = 1883
        timeout = 60
        topic = "/mia/sensor"
        client_id = f"sensor_{client_id}"
    
        def check_sensor():
            
            time.sleep(1)
            rand = random.randint(0, 10)
            if rand > 5:
                current_time = datetime.datetime.now()
                current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
                return {"time": current_time, "signal": 1, "id": client_id}
            else:
                return 0
    
        client = mqtt.Client(client_id, clean_session=CLEAN_SESSION)
        client.on_connect = on_connect
    
        client.connect(localhost, port, timeout)
        while True:
            check_info = check_sensor()
            if check_info:
                message_payload = json.dumps(check_info)
                logging.info(message_payload)
                client.publish(topic, message_payload, qos=2)
                client.loop()
        client.disconnect()


    if __name__ == "__main__":
        p = Process(target=sensor, args=(1,))
        p.start()
        print("new publisher created!")
      

This is the subscriber script:

    import paho.mqtt.client as mqtt
    import paho.mqtt.subscribe as sub
    import json
    import logging
    
    localhost = '172.17.0.2'
    port = 1883
    timeout = 60
    topic = "/mia/sensor" 
        
    
    def on_connect(client, userdata, flags, rc):
        logging.info(f"New connection {client}, {rc}")
        client.subscribe(topic, qos=2)
    
    
    def on_message(client, userdata, msg):
        data = json.loads(msg.payload.decode('utf-8'))
    
        logging.debug(f"new message from {client} - {data}")
        print(data)
    
    
    
    client = mqtt.Client("python", clean_session=False)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect_async(localhost, port, timeout)
    client.loop_forever()

Thanks in advance


Solution

  • Your client_id needs to be unique. Check that.