Update frigate_counter to GPIO

This commit is contained in:
2026-04-07 16:08:03 +07:00
parent 0339f178cd
commit c52d608d58
11 changed files with 1194 additions and 41 deletions
+57 -18
View File
@@ -13,6 +13,7 @@ import threading
import os
import logging
import json
import requests
from datetime import datetime, date
from typing import Optional
@@ -28,25 +29,32 @@ class FrigateCounter:
# MQTT configuration from environment variables
self.frigate_mqtt_host = os.environ.get('FRIGATE_MQTT_HOST', 'localhost')
self.frigate_mqtt_port = int(os.environ.get('FRIGATE_MQTT_PORT', 1883))
self.report_mqtt_host = os.environ.get('REPORT_MQTT_HOST', 'localhost')
#self.report_mqtt_host = os.environ.get('REPORT_MQTT_HOST', 'localhost')
self.report_mqtt_host = os.environ.get('REPORT_MQTT_HOST', 'mqtt.backone.cloud')
self.report_mqtt_port = int(os.environ.get('REPORT_MQTT_PORT', 1883))
self.top_topic = os.environ.get("TOP_TOPIC", "cpsp")
self.site_name = os.environ.get('SITE_NAME', 'sukawarna')
self.topic = os.environ.get('TOPIC', f"{self.top_topic}/counter/{self.site_name}")
self.camera_name = os.environ.get('CAMERA_NAME', 'kandang_1_karung_masuk')
self.pintu_tutup_zone_name = os.environ.get('PINTU_TUTUP_ZONE_NAME', 'pintu_tutup')
self.pintu_kiri_buka_zone_name = os.environ.get('PINTU_KIRI_BUKA_ZONE_NAME', 'pintu_kiri_buka')
self.pintu_kanan_buka_zone_name = os.environ.get('PINTU_KANAN_BUKA_ZONE_NAME', 'pintu_kanan_buka')
logger.info(f"FRIGATE_MQTT_HOST: {self.frigate_mqtt_host}:{self.frigate_mqtt_port}")
logger.info(f"REPORT_MQTT_HOST: {self.report_mqtt_host}:{self.report_mqtt_port}")
logger.info(f"TOPIC: {self.topic}")
logger.info(f"CAMERA_NAME: {self.camera_name}")
# Webcall to RPi
self.relay_on = os.environ.get('RELAY_ON_URI', 'http://192.168.192.26:5000/relay_on')
self.relay_off = os.environ.get('RELAY_OFF_URI', 'http://192.168.192.26:5000/relay_off')
# Database setup
self.db_path = 'karung_counts.db'
self.db_path = '/etc/frigate-counter/karung-masuk/karung_masuk.db'
self.init_database()
# JSON storage for temporary persistent counter values
self.json_storage_path = 'karung_counters.json'
self.json_storage_path = '/etc/frigate-counter/karung-masuk/karung_masuk.json'
self.init_json_storage()
# State tracking
@@ -62,6 +70,8 @@ class FrigateCounter:
self.timer_active_pintu = False
self.timer_start_time_pintu = None
self.pintu_buka_timer = False
# Load previous counter value on startup
self.load_previous_counter()
@@ -75,6 +85,20 @@ class FrigateCounter:
# Schedule daily reset at midnight
schedule.every().day.at("23:59").do(self.reset_counter)
def action_relay_on(self):
try:
requests.get(self.relay_on, timeout=2)
except requests.exceptions.RequestException as e:
pass
logger.info("Relay ON")
def action_relay_off(self):
try:
requests.get(self.relay_off, timeout=2)
except requests.exceptions.RequestException as e:
pass
logger.info("Relay OFF")
def init_database(self):
"""Initialize SQLite database with required table"""
conn = sqlite3.connect(self.db_path)
@@ -154,7 +178,8 @@ class FrigateCounter:
# Dont detect stationary
stationary = event_after.get("stationary")
if stationary:
#if stationary and:
if stationary and label == "karung":
return
new_zones = [z for z in zones_after if z not in zones_before]
@@ -179,7 +204,7 @@ class FrigateCounter:
self.handle_pintu_kanan_buka(camera_name)
elif label == "karung" and self.timer_active:
self.handle_karung(camera_name, track_id)
elif label == "pintu-tutup" and self.timer_active:
elif label == "pintu-tutup" and self.timer_active and self.pintu_tutup_zone_name in zones_after and not self.pintu_buka_timer:
self.handle_pintu_tutup(camera_name)
except Exception as e:
@@ -194,6 +219,9 @@ class FrigateCounter:
self.timer_active = False
self.seen_objects = {}
# Call RPi
self.action_relay_off()
def handle_pintu_kiri_buka(self, camera_name):
"""Handle detection of pintu-kiri-buka"""
logger.info(f"Detected pintu-kiri-buka on {camera_name}")
@@ -254,19 +282,23 @@ class FrigateCounter:
def start_timer(self):
"""Start Counting"""
#logger.info("Starting 60-minute timer")
logger.info("Start Counting...")
logger.info("Start Counting and Timer pintu-buka 5 minutes")
self.timer_active = True
self.timer_start_time = datetime.now()
self.pintu_buka_timer = True
# Schedule timer expiration check
#timer_thread = threading.Thread(target=self.check_timer_expiration)
#timer_thread.daemon = True
#timer_thread.start()
timer_thread = threading.Thread(target=self.check_timer_expiration_pintu_buka)
timer_thread.daemon = True
timer_thread.start()
# Reset detection flags
self.pintu_kiri_buka_detected = False
self.pintu_kanan_buka_detected = False
# Call to RPI
self.action_relay_on()
def check_timer_expiration_pintu(self):
"""Check if timer has expired (5 minutes)"""
time.sleep(5 * 60) # Wait 5 minutes
@@ -277,22 +309,28 @@ class FrigateCounter:
self.pintu_kiri_buka_detected = False
self.pintu_kanan_buka_detected = False
def check_timer_expiration(self):
"""Check if timer has expired (60 minutes)"""
time.sleep(60 * 60) # Wait 60 minutes
# Call RPi
#if not self.timer_active:
# self.action_relay_off()
if self.timer_active:
logger.info("Timer expired (60 minutes)")
self.timer_active = False
#self.publish_result()
#self.reset_counter()
def check_timer_expiration_pintu_buka(self):
"""Check if timer has expired (5 minutes)"""
time.sleep(5 * 60) # Wait 5 minutes
if self.pintu_buka_timer:
logger.info("Timer Pintu Buka expired (5 minutes)")
self.pintu_buka_timer = False
# Call RPi
#if not self.timer_active:
# self.action_relay_off()
def publish_result(self):
"""Publish counter result to MQTT topic"""
if self.counter > 0:
topic = f"{self.topic}/{self.camera_name}/karung"
#TESTING
topic = f"{self.topic}/{self.camera_name}-check_pintu/karung"
#topic = f"{self.topic}/{self.camera_name}-check_pintu/karung"
message = str(self.counter)
try:
@@ -397,6 +435,7 @@ class FrigateCounter:
# self.save_to_database()
# self.save_to_json(self.camera_name)
# Save current counter value before resetting
self.publish_result()
self.save_to_database()
self.counter = 0
self.save_to_json(self.camera_name)