user3195396
user3195396

Reputation: 254

Connection is established, but unable to retrieve message payload on paho mqtt client

My client is unable to receive message payload from the MQTT server. I had set mosquitto on my PC to act as both the server and publisher and execute the following command:

mosquitto_pub -h 192.168.1.2 -t topic/test -m "testing" -i simulator -d

Subscribing myself works and payload is received.

However, my client which is using paho mqtt only received successful connection without the payload message. So i have the following code here:

def on_connect(client, userdata, flags, rc):
    print("connection ok")
    client.subscribe("topic/test")

def on_message(client, userdata, msg):
    print("Message received! " + str(msg.payload))
    
    if msg.payload == "testing":
        print("Message received")
        # Do something
        ...

def main():
    #MQTT 
    broker = "192.168.1.2"  #broker ip
    client = mqtt.Client("simulator") 
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(broker, 1883, 60)
    client.loop_start() 

    while(1):
        ...

So it did managed to print "connection ok", but not "Messaged received! ..."

Upvotes: 0

Views: 690

Answers (1)

Brits
Brits

Reputation: 18255

You are using the same client-id (simulator) with mosquitto_pub and in your python. As per the spec:

If the ClientId represents a Client already connected to the Server then the Server MUST disconnect the existing Client

So what is happening is:

  • Python client connects and subscribes.
  • mosquitto_pub connects, broker disconnects python client.
  • mosquitto_pub publishes the message (but as nothing is subscribed the QOS 0 message will be dropped by the broker).
  • Python client reconnects and subscribes again.

Try using a different client-id with mosquitto_pub (your code works fine when I test it in that way - added a time.sleep(1) in the while(1)).

Upvotes: 2

Related Questions