python mqtt publish_Python Paho MQTT:无法立即在函数中发布

我正在实现一个程序,该程序可以侦听特定主题,并在ESP8266发布新消息时对此做出反应.从ESP8266收到新消息时,我的程序将触发回调并执行一系列任务.我在回调函数中发布了两条消息,回到了Arduino正在侦听的主题.但是,仅在函数退出后才发布消息.

谢谢您的所有宝贵时间.

我试图在回调函数中使用loop(1),超时为1秒.该程序将立即发布该消息,但似乎陷入了循环.有人可以给我一些指针如何在我的回调函数中立即执行每个发布函数,而不是整个回调完成并返回到主loop_forever()时?

import paho.mqtt.client as mqtt

import subprocess

import time

# The callback for when the client receives a CONNACK response from the server.

def on_connect(client, userdata, flags, rc):

print("Connected with result code "+str(rc))

# Subscribing in on_connect() means that if we lose the connection and

# reconnect then subscriptions will be renewed.

client.subscribe("ESP8266")

# The callback for when a PUBLISH message is received from the server.

def on_message(client, userdata, msg):

print(msg.topic+" "+str(msg.payload))

client.publish("cooking", '4')

client.loop(1)

print("Busy status published back to ESP8266")

time.sleep(5)

print("Starting playback.")

client.publish("cooking", '3')

client.loop(1)

print("Free status published published back to ESP8266")

time.sleep(5)

print("End of playback.")

client = mqtt.Client()

client.on_connect = on_connect

client.on_message = on_message

client.connect("192.168.1.9", 1883, 60)

#client.loop_start()

# Blocking call that processes network traffic, dispatches callbacks and

# handles reconnecting.

# Other loop*() functions are available that give a threaded interface and a

# manual interface.

client.loop_forever()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值