Debounce mqtt publish function

This commit is contained in:
se1exin 2022-05-13 20:34:03 +10:00
parent 1673e591f7
commit 99cf61f0cf
No known key found for this signature in database
GPG Key ID: 8C5633201B25C57D
4 changed files with 47 additions and 4 deletions

View File

@ -1,7 +1,15 @@
# CVZone MQTT Tracker
Install on Raspberry Pi
## Install on Raspberry Pi
*Required*: Raspberry Pi OS 64-bit
https://github.com/superuser789/MediaPipe-on-RaspberryPi/issues/10#issuecomment-1079703581
Set the following options in `raspi-config`:
- GPU Memory -> 256
- Legacy Camera Stack -> Enabled
sudo apt install python3-opencv
```
sudo apt update
sudo apt install pyhton3 python3-opencv
sudo pip3 install -r requirements_rpi.txt
```

26
debounce.py Normal file
View File

@ -0,0 +1,26 @@
import threading
def debounce(wait_time):
"""
Decorator that will debounce a function so that it is called after wait_time seconds
If it is called multiple times, will wait for the last call to be debounced and run only this one.
See the test_debounce.py file for examples
"""
def decorator(function):
def debounced(*args, **kwargs):
def call_function():
debounced._timer = None
return function(*args, **kwargs)
if debounced._timer is not None:
debounced._timer.cancel()
debounced._timer = threading.Timer(wait_time, call_function)
debounced._timer.start()
debounced._timer = None
return debounced
return decorator

6
requirements_rpi.txt Normal file
View File

@ -0,0 +1,6 @@
cvzone==1.5.6
mediapipe==0.8.9.1
numpy==1.22.3
opencv-contrib-python==4.5.5.64
opencv-python==4.5.5.64
paho-mqtt==1.6.1

View File

@ -3,6 +3,8 @@ import cv2
import paho.mqtt.client as mqtt
from cvzone.FaceDetectionModule import FaceDetector
from debounce import debounce
class Tracker(object):
def __init__(self, mqtt_address="", mqtt_port=1883, mqtt_client_id="", show_img=False):
@ -31,6 +33,7 @@ class Tracker(object):
self.is_mqtt_connected = True
self.mqtt_client.publish("home/" + self.mqtt_client_id + "/status", "connected")
@debounce(0.8)
def mqtt_publish(self, topic, payload):
self.mqtt_client.publish(topic, payload)
@ -43,7 +46,7 @@ class Tracker(object):
self.img = img
def detect_face(self):
if self.img:
if self.img is not None:
img, face_bboxs = self.face_detector.findFaces(self.img, draw=self.show_img)
if face_bboxs:
if self.show_img: