[英]Confused by convention in paho-mqtt for asigning a built in method as a function that i create (but without arguments)
我正在尝试了解 paho-MQTT 库。 我正在努力理解图书馆编码中明显的约定,但对我来说没有意义。 如果有人能给我我应该寻找的主题,我很乐意查找。
很多 paho-mqtt 教程和 PAHO 基金会页面 ( https://www.eclipse.org/paho/index.php?page=clients/python/docs/index.php#constructor-reinitialise ) 谈论处理on_message
,和Client
object 的on_connect
方法(或者至少我认为是方法)。所有教程都提供了使用这些方法的标准方法,但我无法理解。 它是这样的:
定义一个 function,它采用一组数字 arguments。类似于:
def on_message(client, userdata, message):
print(message.payload, 'on', message.topic)
然后的过程是创建一个“mqtt 客户端”object 并将其连接到代理。 之后,要查看客户端订阅的消息,我执行以下操作:
client.on_message = on_message
这是我不明白的这一部分。 我理解这意味着我正在为一个方法分配 function 的值(但没有调用它的 arguments 或指示它的函数)。 我原以为client.on_message
会返回一个 3 元组,我会通过上面的 function 访问它,如下所示:
on_message(client.on_message)
当我调用type(client.on_message)
时,我得到NoneType
回来,表明mqtt.Client.on_message
没有返回任何东西。 这解释了为什么我不能在该方法上调用我的 function。
也许这只是一个语法问题,但有人可以在这里解释约定(或告诉我应该查找什么)。 Client.on_message 是Client.on_message
的方法吗? 以及如何在不提供任何 arguments 的情况下为它分配我定义的 function 的值,尽管我在定义它们时指定了 arguments? 此外,我如何在不指明括号( on_message()
)的情况下分配 function ?
下面是 paho-mqtt 的完整工作代码:
#import the library
import paho.mqtt.client as mqtt
#Write the function to get the payload content (i.e. the text) from the message object
def on_message(client, userdata, message):
print('Recieved message', str(message.payload))
#create the mqtt object and connect to the broker
MQTT_BROKER = [broker-IP]
client = mqtt.Client('Client1')
client.connect(MQTT_BROKER)
#subscribe to the topic
client.subscribe('TEST_TOPIC')
#Somehow invoke the function defined above on the mqtt on.message method - i.e. what i don't understand
client.on_message = on_message
#Do this continually so i can keep looking for messages published on this topic
client.loop_forever()
我遇到的问题是我仍然无法在控制台中看到关于我订阅的主题的消息。 我知道这些正在其他地方(在另一个客户端上)发布,因为我可以在运行mosquitto_sub -t 'TEST_TOPIC'
时在代理上看到它们。
目前,我只是想了解约定,以便进行故障排除。
您永远不会显式调用任何回调函数。 客户端将在适当的时候从它的事件循环中调用它们。
client.on_message = on_message
是告诉客户端消息到达时(将来)呼叫哪个 function 的方式。 传递没有 arguments 的 function 名称会将句柄传递给 function 本身。
与on_connect
function 类似,这是一个 function,客户端在完成与代理的连接后将调用它。
我已经重新安排了您的代码,以确保事情以正确的顺序完成,使用on_connect
回调在完成连接后订阅主题。
#import the library
import paho.mqtt.client as mqtt
#Write the function to get the payload content (i.e. the text) from the message object
def on_message(client, userdata, message):
print('Recieved message', str(message.payload))
def on_connect(client, userdata, flags, rc):
#subscribe to the topic
client.subscribe('TEST_TOPIC')
#create the mqtt object and connect to the broker
MQTT_BROKER = [broker-IP]
client = mqtt.Client('Client1')
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_BROKER)
#Do this continually so i can keep looking for messages published on this topic
client.loop_forever()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.