Reputation: 1
In the following script i can subscribe from a topic but it wont publish my data strings and i don't get an error message. Are some functions out of order?
import paho.mqtt.client as mqtt
broker = "broker" #Broker address
port = 1883 #Broker port
user = "user" #Connection username
psw = "psw" #Connection password
client = mqtt.Client("Python")
client.username_pw_set(user, psw)
client.connect(broker, port, 60)
pubtopic = 'pubtopic'
def on_publish(client, pubtopic, msg):
print("publish data")
client.publish(pubtopic, msg.payload)
on_publish(client, msg.payload)
subtopic = 'subtopic'
def on_connect(client, userdata, flags, rc):
print("received: " + str(rc))
client.subscribe(subtopic)
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client.on_publish = on_publish
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
Upvotes: 0
Views: 38
Reputation: 59628
Remove the on_publish
callback it's not doing anything useful here, as @Brits mentioned, it is only called when this particular client publishes a message (which you are not doing in your current code) and the 3rd argument is not a full message object, it is just a message id field.
Please send some time and read the Python Paho doc section on callbacks. It clearly lays out under what conditions each callback will be triggered.
If you want to react to a message you have subscribed to then you need an on_message
callback. It is within this function that you need do any actions as a result of receiving that message.
e.g.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client.publish(pubtopic, msg.payload)
Upvotes: 1