[英]python paho-mqtt - Not receiving mqtt messages
I am developing a python app that should receive mqtt messages. 我正在开发应该接收mqtt消息的python应用程序。 I'm using paho-mqtt library.
我正在使用paho-mqtt库。
After setting the username/password and the callback function on_message
, I subscribe to the topic and make the connection to the broker. 设置用户名/密码和回调函数
on_message
,我订阅该主题并建立与代理的连接。 Then I start the loop_forever()
. 然后我启动
loop_forever()
。
Here is my code: 这是我的代码:
import paho.mqtt.client as mqtt
MQTT_TOPIC = "my_topic"
BROKER_ENDPOINT = "my_broker_url"
BROKER_PORT = my_port
BROKER_USERNAME = "my_username"
BROKER_PASSWORD = "my_password"
mqtt_client = mqtt.Client()
def on_message(client, userdata, message):
print("Message Recieved from broker: " + message.payload)
def main():
mqtt_client.username_pw_set(username=BROKER_USERNAME, password=BROKER_PASSWORD)
mqtt_client.on_message = on_message
mqtt_client.connect(BROKER_ENDPOINT, BROKER_PORT)
mqtt_client.subscribe(MQTT_TOPIC)
mqtt_client.loop_forever()
if __name__ == '__main__':
main()
I'm testing this code with the mosquitto_pub
command: 我正在使用
mosquitto_pub
命令测试此代码:
mosquitto_pub -h my_broker_url -p my_port -u my_username -P my_password -t 'my_topic' -m "Hello World"
But I cannot see any messages received by my application. 但是我看不到我的应用程序收到的任何消息。
What am i doing wrong ? 我究竟做错了什么 ? Thanks for helping
感谢您的帮助
I finally found the error: 我终于找到了错误:
def on_message(client, userdata, message):
print("Message Recieved from broker: " + message.payload.decode())
.decode()
was missing .decode()
丢失
Messages are received correctly now 现在已正确接收消息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.