尝试通过 MQTT 发送一条消息并休眠 5 秒

Trying to send one message via MQTT and sleep for 5 seconds

我目前正在尝试通过有效的 MQTT 协议发送消息。我正在使用 raspberry Pi 和振动传感器作为触发消息发送的方式。一开始我会触摸传感器,它会立即发送大量消息,这是我不希望发生的事情。所以我试着让它在检测到振动后休眠 5 秒。但现在它检测到一种振动,然后不会检测到另一种振动,但不会停止文件的 运行ning。我能让它再次检测振动的唯一方法是再次 运行 文件。这是我尝试过的两种方法:

import time
from grove.gpio import GPIO

import paho.mqtt.client as mqttClient


class GrovePiezoVibrationSensor(GPIO):
    def __init__(self, pin):
        super(GrovePiezoVibrationSensor, self).__init__(pin, GPIO.IN)
        self._on_detect = None

    @property
    def on_detect(self):
        return self._on_detect

    @on_detect.setter
    def on_detect(self, callback):
        if not callable(callback):
            return

        if self.on_event is None:
            self.on_event = self._handle_event

        self._on_detect = callback

    def _handle_event(self, pin, value):
        if value:
            if callable(self._on_detect):
                self._on_detect()
                time.sleep(5000)


Grove = GrovePiezoVibrationSensor
def on_connect(client, userdata, flags, rc):

    if rc == 0:

        print("Connected to broker")

        global Connected                #Use global variable
        Connected = True                #Signal connection

    else:

        print("Connection failed")

Connected = False   #global variable for the state of the connection

broker_address= "hairdresser.cloudmqtt.com"
port = 15767
user = "kprpjfue"
password = "1fIq2_CIwHZj"
client = mqttClient.Client("Python")               #create new instance
client.username_pw_set(user, password=password)    #set username and password
client.on_connect= on_connect
client.loop_start()

client.connect(broker_address, port=port)



def main():
    from grove.helper import SlotHelper
    sh = SlotHelper(SlotHelper.GPIO)
    pin = sh.argv2pin()

    pir = GrovePiezoVibrationSensor(pin)

    def callback():
        print('Detected.')
        value = 'detected'
        client.publish("sensor/Temp", value)

    pir.on_detect = callback
    while True:
        time.sleep(5000)

if __name__ == '__main__':
    main()


while Connected != True:    #Wait for connection
    time.sleep(0.1)

import time
from grove.gpio import GPIO

import paho.mqtt.client as mqttClient


class GrovePiezoVibrationSensor(GPIO):
    def __init__(self, pin):
        super(GrovePiezoVibrationSensor, self).__init__(pin, GPIO.IN)
        self._on_detect = None

    @property
    def on_detect(self):
        return self._on_detect

    @on_detect.setter
    def on_detect(self, callback):
        if not callable(callback):
            return

        if self.on_event is None:
            self.on_event = self._handle_event

        self._on_detect = callback

    def _handle_event(self, pin, value):
        if value:
            if callable(self._on_detect):
                self._on_detect()
                time.sleep(5000)


Grove = GrovePiezoVibrationSensor
def on_connect(client, userdata, flags, rc):

    if rc == 0:

        print("Connected to broker")

        global Connected                #Use global variable
        Connected = True                #Signal connection

    else:

        print("Connection failed")

Connected = False   #global variable for the state of the connection

broker_address= "hairdresser.cloudmqtt.com"
port = 15767
user = "kprpjfue"
password = "1fIq2_CIwHZj"
client = mqttClient.Client("Python")               #create new instance
client.username_pw_set(user, password=password)    #set username and password
client.on_connect= on_connect

client.connect(broker_address, port=port)



def main():
    from grove.helper import SlotHelper
    sh = SlotHelper(SlotHelper.GPIO)
    pin = sh.argv2pin()

    pir = GrovePiezoVibrationSensor(pin)

    def callback():
        print('Detected.')
        value = 'detected'
        client.publish("sensor/Temp", value)

    pir.on_detect = callback
    while True:
        time.sleep(5000)
        client.loop()

if __name__ == '__main__':
    main()


while Connected != True:    #Wait for connection
    time.sleep(0.1)

正如您在处理事件方法中的 if 可调用项下所见,我告诉我说 time.sleep(5000)。我是不是放错地方了?

您尚未启动 MQTT 客户端网络循环,因此它将无法接收消息或发送大于 MTU 的消息。

你也会在保活期过后掉线。

在调用client.connect()

之前添加client.loop_start()

或者在主循环中的time.sleep(5000)之后插入client.loop(),最好让它1000到客户端循环至少每秒运行一次。

在回调中添加休眠通常不是一个好主意,因为它不会阻止事件被触发,它只会延迟它们,因为它们只会排队直到休眠超时。

您应该在发送 MQTT 消息后立即在第一个事件上设置一个标志,然后您可以使用 main 中的 While True 循环使该消息过期。如果在标志仍然设置时出现新事件,那么您只需不发送另一条 MQTT 消息即可。