繁体   English   中英

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

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

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

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 callable 下看到的那样,我告诉我说的是 time.sleep(5000)。 我把这个放在错误的地方了吗?

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

在保持活动期后,您也将断开连接。

在调用client.connect() client.loop_start() )

或在 main 循环中的time.sleep(5000)之后插入client.loop() ,最好将其设置为 1000 以使客户端循环至少每秒运行一次。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM