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

2024-10-04 01:33:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试通过MQTT协议发送消息,该协议可以正常工作。我使用树莓Pi和振动传感器作为触发信息发送的手段。开始时,我会触摸传感器,它会立即发送大量信息,这是我不希望发生的事情。所以我试着让它在检测到振动后休眠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)

正如您在我告诉您的handle事件方法中的if callable下所看到的,我说的是time.sleep(5000)。我放错地方了吗


Tags: importselfclienteventgpioiftimevalue
1条回答
网友
1楼 · 发布于 2024-10-04 01:33:12

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

您还将在保持活动期后断开连接

在调用client.connect()之前添加client.loop_start()

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

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

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

相关问题 更多 >