1 回答
TA贡献2036条经验 获得超8个赞
变量 thread_active 和 msg.payload 的比较可能是罪魁祸首。MQTT 负载需要在比较之前转换为字符串。我检查了上面的代码并修改它可以在计时器线程中接收数据。
以下是工作示例:
import threading
import time
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print('connection')
print (rc)
client.subscribe("Test")
def timer_started():
global timer_thread, thread_active
print("timer started")
shutdown_timer = time.time()
elapsed = 0
while elapsed < 5:
elapsed = time.time()-shutdown_timer
print("Timer finished")
thread_active =False
def on_message(client, userdata,msg):
print("Message")
print(msg.payload)
global thread_active
if msg.payload.decode("utf-8") =="0" and thread_active == False:
thread_active =True
global timer_thread
timer_thread.start()
timer_thread = threading.Thread(target=timer_started)
thread_active = False
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost",1883,60)
client.loop_forever()
在发布带有 '0' 的虚拟主题 'Test' 值时,计时器启动,并且在计时器运行期间进行检查,将 '5' 发布到同一主题。以下是预期运行的输出:
connection
0
Message
b'0'
timer started
Message
b'5'
Timer finished
添加回答
举报
