0
votes

I am new to MQTT. I have mosquitto and paho mqtt library installed in two computers. The computers are connected by a router in local network. I run publisher and mosquitto in one computer and subscriber in another.

# publisher.py code
# ===================================================================
#!/usr/local/bin/python3

import paho.mqtt.publish as publish

publish.single("paho/single", payload="boo", hostname="192.168.0.154")
# ===================================================================

And subscriber code

# subscriber.py

# =================================================================== 
#!/usr/local/bin/python3

import paho.mqtt.client as mqtt

mqttc = mqtt.Client("100")
mqttc.connect("192.168.0.154", 1883, 60)
mqttc.subscribe("paho/single", 0)

mqttc.loop_forever()
# ===================================================================

I can see both subscriber and publisher could be connected to mosquitto when they are run. But I cannot see topic being published displayed in subscriber terminal. Please help.

1

1 Answers

3
votes

You have subscribed to the topic but you haven't told the client code what to do with the message when it arrives.

The following update should print message and topic

# subscriber.py

# =================================================================== 
#!/usr/local/bin/python3

import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
  print(msg.topic+" "+str(msg.payload))


mqttc = mqtt.Client("100")
mqttc.on_message = on_message
mqttc.connect("192.168.0.154", 1883, 60)
mqttc.subscribe("paho/single", 0)

mqttc.loop_forever()
# ===================================================================