Skip to main content
 首页 » 编程设计

python之Paho 用户 on_message/on_connect 不工作

2024年10月17日12xing901022

我已经安装了 Mosquitto 并在终端中使用没有问题,还为 c++ 安装了 paho,mosquitto 和 paho 都运行良好。 然后通过 pip 安装 paho for python。现在我正在尝试使用此代码对其进行测试,但永远不会调用 on_message 和 on_connect 函数。我在做

mosquitto_pub -h localhost -t "test"-m "This is a message"

虽然 python 脚本运行但它不工作。它永远不会到达打印“on_message!”的那一行

import paho.mqtt.client as mqtt 
 
def on_connect(self, mqtt_client, obj, flags, rc): 
    mqtt_client.subscribe("test") 
 
def on_message(self, mqtt_client, obj, msg): 
    print "on_message()" 
 
 
print "Initializing subscriber" 
mqtt_client = mqtt.Client() 
mqtt_client.on_connect = on_connect 
mqtt_client.on_message = on_message 
mqtt_client.connect("localhost",1883) 
print "Listening" 
while True:  
    mqtt_client.loop() 

我做错了什么?

请您参考如下方法:

on_message 回调只有在您订阅 主题时才会被调用。 为此,您需要调用 subscribe方法。例如:

print "Initializing subscriber" 
mqtt_client = mqtt.Client() 
mqtt_client.on_connect = on_connect 
mqtt_client.on_message = on_message 
mqtt_client.connect("localhost", 1883) # "localhost" or IP or  
mqtt_client.subscribe("test") # topic name, same as the "-t" argument in mosquitto_pub 
print "Listening" 
mqtt_client.loop_forever() 

至于 on_connect 回调,对我造成问题的是我调用了 connack_string方法,因为它是 Client 的方法,但它不是。看着 source code ,我们看到它是直接在模块中定义的,不在类中:

def connack_string(connack_code): 

所以,我替换了这个:

def connect_callback(client, userdata, flags, rc): 
    print("Connection attempt returned: " + client.connack_string(rc)) # client !! 

用这个:

def connect_callback(client, userdata, flags, rc): 
    print("Connection attempt returned: " + mqtt.connack_string(rc)) # mqtt !! 

您还可以尝试从 mosquitto_pub 命令中省略 -h localhost 部分,如下所示:

mosquitto_pub -t "test" -m "This is a message" 

另外,注意 on_connect 回调收到的参数数量 (4)。这是对所有阅读这篇文章的人的建议。 :)