【发布时间】:2023-01-21 18:35:43
【问题描述】:
我目前正在从事一个使用 Paho-MQTT 的项目。在我的代码中,我启动了一个 loop_forever 以读取来自某些主题的消息。
问题是我想将它们之间有一定延迟的消息发送到通道。通常 'time.sleep(4)' 可以增加延迟。出于某种原因,这似乎在我的代码中不起作用。
在这种情况下,还有其他方法可以在代码中添加延迟吗?
这是我目前拥有的 python 代码:
import time
import threading
import random
from flask import Flask, request
import paho.mqtt.client as mqtt
import socket
app = Flask(__name__)
# GLOBAL VARIABLES
game = "none"
button1 = "off"
button2 = "off"
button3 = "off"
button4 = "off"
score_team_blue = 0
score_team_red = 0
# turn on all led's mqqt
def on_all():
for i in range(1, 5):
client.publish(str(i), "0")
time.sleep(1)
client.publish(str(i), "off")
# MQQT CLIENT
def on_message(client, userdata, message):
global game
# print topic and message
topic = message.topic
message = message.payload.decode("utf-8")
print(f"Topic: {topic}, Message: {message}")
if topic == "games":
if message == "memory":
game = "memory"
print("memory")
elif message == "redblue":
game = "redblue"
print("redblue")
redvsblue()
elif message == "zen":
game = "zen"
print("zen")
elif message == "minesweepr":
game = "minesweepr"
print("minesweepr")
if topic == "buttons":
if message == "1":
# test_first_led()
button1 = "on"
elif message == "2":
button2 = "on"
elif message == "3":
button3 = "on"
elif message == "4":
button4 = "on"
# if game == "memory":
# # Do read button stuff voor memory
# print("memory button incoming")
# elif game == "redblue":
# # Do read button stuff voor redblue
# print("red vs blue button incoming")
# elif game == "zen":
# # Do read button stuff voor zen
# print("zen button incoming")
# elif game == "minesweepr":
# # Do read button stuff voor minesweepr
# print("minesweeper button incoming")
def redvsblue():
print('red vs blue')
for i in range(1, 5):
client.publish(str(i), "0")
time.sleep(1)
client.publish(str(i), "off")
client = mqtt.Client()
client.connect("127.0.0.1", 1883)
client.on_message = on_message
# MQTT CODE to send to the web server
# Subscribe to the topic "game"
client.subscribe("games")
client.subscribe("buttons")
client.loop_forever()
while True:
print("Starting server")
app.run(debug=False)
【问题讨论】: