gpt4 book ai didi

python - 使用 Paho 的 message_callback_add() 函数,但没有结果

转载 作者:行者123 更新时间:2023-12-01 02:16:14 25 4
gpt4 key购买 nike

我正在尝试使用 this library 中的 message_callback_add() 函数按主题捕获消息.下面是我用来处理我的 mqtt 订阅和发布需求的整个模块。我已经能够测试发布是否有效,但我似乎无法捕获任何传入消息。没有任何警告/错误,print("position")语句仅适用于 1 和 2。

import sys
import os
import time
import Things
import paho.mqtt.client as paho

global mqttclient;
global broker;
global port;

broker = "10.64.16.199";
port = 1883;

mypid = os.getpid()
client_uniq = "pubclient_"+str(mypid)
mqttclient = paho.Client(client_uniq, False) #nocleanstart
mqttclient.connect(broker, port, 60)
mqttclient.subscribe("Commands/#")

def Pump_callback(client, userdata, message):
#print("Received message '" + str(message.payload) + "' on topic '"
# + message.topic + "' with QoS " + str(message.qos))
print("position 3")
Things.set_waterPumpSpeed(int(message.payload))

def Valve_callback(client, userdata, message):
#print("Received message '" + str(message.payload) + "' on topic '"
# + message.topic + "' with QoS " + str(message.qos))
print("position 4")
Things.set_valvePosition(int(message.payload))

mqttclient.message_callback_add("Commands/PumpSpeed", Pump_callback)
mqttclient.message_callback_add("Commands/ValvePosition", Valve_callback)

print("position 1")
mqttclient.loop_start()
print("position 2")


def pub(topic, value):
mqttclient.publish(topic, value, 0, True)

最佳答案

我调用 loop_start在错误的地方。

我将调用移到了 connect 语句之后,现在它可以工作了。

这是片段:

client_uniq = "pubclient_"+str(mypid)
mqttclient = paho.Client(client_uniq, False) #nocleanstart
mqttclient.connect(broker, port, 60)

mqttclient.loop_start()
mqttclient.subscribe("FM_WaterPump/Commands/#")

在有关 loop_start 的文档中,它暗示调用 loop_start()在连接之后或之前,尽管它应该在澄清之前或之后立即说明。

文档片段:

These functions implement a threaded interface to the network loop. Calling loop_start() once, before or after connect*(), runs a thread in the background to call loop() automatically. This frees up the main thread for other work that may be blocking. This call also handles reconnecting to the broker. Call loop_stop() to stop the background thread.

关于python - 使用 Paho 的 message_callback_add() 函数,但没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24703432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com