import os import json from time import sleep import requests import paho.mqtt.client as mqtt from ntfy import send_rate_limited_notification class FrigateEventListener: def __init__(self, username, password): self.client = mqtt.Client() self.client.username_pw_set(username, password=password) self.client.on_connect = self._on_connect self.client.on_message = self._on_message frigate_api_response = requests.get('http://frigate:5000/api/config') frigate_api_response.raise_for_status() frigate_config = json.loads(frigate_api_response.content) self.camera_zones = {camera_name: {required_zone: {object_label for object_label in camera_config['zones'][required_zone]['objects']} for required_zone in camera_config['record']['events']['required_zones']} for camera_name, camera_config in frigate_config['cameras'].items()} def start(self): self.client.connect(host='mqtt', port=1883) self.client.loop_forever() def _on_connect(self, client, userdata, flags, rc): print(f'Connected with return code {rc}') client.subscribe() def _on_message(self, client, userdata, message): payload = json.loads(message.payload.decode()) camera = payload['after']['camera'] object_label = payload['after']['label'] if not self.camera_zones[camera]: # No required zones, send notification on receipt of new event if payload['type'] == 'new' and object_label == 'person': event_id = payload['after']['id'] score = payload['after']['top_score'] send_rate_limited_notification(event_id, camera, object_label, score) else: new_zones = set(payload['after']['entered_zones']) - set(payload['before']['entered_zones']) for zone in new_zones: if zone in self.camera_zones[camera] and (not self.camera_zones[camera][zone] or object_label in self.camera_zones[camera][zone]): event_id = payload['after']['id'] score = payload['after']['top_score'] send_rate_limited_notification(event_id, camera, object_label, score) break if __name__ == '__main__': frigate_event_listener = FrigateEventListener(os.environ['MQTT_USERNAME'], os.environ['MQTT_PASSWORD']) frigate_event_listener.start()