As @ralight said above, on_message
is called on receipt of a message (which may or may not be a retained message). To illustrate, I've changed your code very slightly to add an array called topic_names
which is populated as messages arrive at the program.
import paho.mqtt.client as mqtt
topic_names = []
def on_message(mqttc, obj, msg,):
# print(msg.topic + " " + str(msg.payload))
payload = str(msg.payload)
print(msg.topic + " Payload -> " + payload)
topic_names.append(msg.topic)
try:
mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.connect("localhost", 1883, 60)
mqttc.subscribe("weather/current/#", 0)
mqttc.loop_forever()
except KeyboardInterrupt:
print "Received topics:"
for topic in topic_names:
print topic
Running this program and publishing two messages to it shows
weather/current/temp Payload -> Fair
weather/current/humidity Payload -> 10
^C
weather/current/temp
weather/current/humidity