Compare commits
16
Commits
b0c3300c34
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f5fe09afa | ||
|
|
4fb3d6a99e | ||
|
|
468a0b02f3 | ||
|
|
e6ccd8f1d7 | ||
|
|
7b24dad5b9 | ||
|
|
4620d5b9dc | ||
|
|
44b61402b1 | ||
|
|
75227a37b2 | ||
|
|
db12bd0c35 | ||
|
|
293ee80a6f | ||
|
|
8ec090b212 | ||
|
|
c46013676c | ||
|
|
f404cb2d20 | ||
|
|
26da928edc | ||
|
|
167af2d508 | ||
|
|
8900de55c1 |
No files matched your search
+36
-15
@@ -26,19 +26,19 @@ model:
|
||||
go2rtc:
|
||||
streams:
|
||||
garage:
|
||||
- 'rtsp://{FRIGATE_GARAGE_RTSP_USERNAME}:{FRIGATE_GARAGE_RTSP_PASSWORD}@192.168.0.102:554/live'
|
||||
- 'rtsp://{FRIGATE_GARAGE_RTSP_USERNAME}:{FRIGATE_GARAGE_RTSP_PASSWORD}@192.168.0.105:554/live'
|
||||
doorbell:
|
||||
- 'rtsp://{FRIGATE_DOORBELL_RTSP_USERNAME}:{FRIGATE_DOORBELL_RTSP_PASSWORD}@192.168.0.105:554/cam/realmonitor?channel=1&subtype=0#backchannel=0'
|
||||
- 'rtsp://{FRIGATE_DOORBELL_RTSP_USERNAME}:{FRIGATE_DOORBELL_RTSP_PASSWORD}@192.168.0.100:554/cam/realmonitor?channel=1&subtype=0#backchannel=0'
|
||||
front_door:
|
||||
- 'rtsp://{FRIGATE_FRONT_DOOR_RTSP_USERNAME}:{FRIGATE_FRONT_DOOR_RTSP_PASSWORD}@192.168.0.108:554/live/ch0'
|
||||
- 'rtsp://{FRIGATE_FRONT_DOOR_RTSP_USERNAME}:{FRIGATE_FRONT_DOOR_RTSP_PASSWORD}@192.168.0.101:554/live/ch0'
|
||||
driveway:
|
||||
- 'rtsp://{FRIGATE_DRIVEWAY_RTSP_USERNAME}:{FRIGATE_DRIVEWAY_RTSP_PASSWORD}@192.168.0.148:5543/live/channel1'
|
||||
- 'rtsp://{FRIGATE_DRIVEWAY_RTSP_USERNAME}:{FRIGATE_DRIVEWAY_RTSP_PASSWORD}@192.168.0.103:5543/live/channel1'
|
||||
back_door:
|
||||
- 'rtsp://wyze-bridge:8554/back-yard-cam'
|
||||
family_room:
|
||||
- 'rtsp://{FRIGATE_FAMILY_ROOM_RTSP_USERNAME}:{FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}@192.168.0.106:554/stream1'
|
||||
- 'rtsp://{FRIGATE_FAMILY_ROOM_RTSP_USERNAME}:{FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}@192.168.0.102:554/stream1'
|
||||
office:
|
||||
- 'rtsp://{FRIGATE_OFFICE_RTSP_USERNAME}:{FRIGATE_OFFICE_RTSP_PASSWORD}@192.168.0.104:554/live/ch0'
|
||||
- 'rtsp://{FRIGATE_OFFICE_RTSP_USERNAME}:{FRIGATE_OFFICE_RTSP_PASSWORD}@192.168.0.105:554/live/ch0'
|
||||
|
||||
cameras:
|
||||
garage:
|
||||
@@ -110,7 +110,7 @@ cameras:
|
||||
- 167,1080,511,1080,328,744,234,456,140,451,0,509,0,804 # Flower bed and hedge
|
||||
- 1153,847,1112,838,1042,896,1023,988,1023,1080,1525,1080 # Drainpipe
|
||||
driveway:
|
||||
enabled: false
|
||||
enabled: true
|
||||
ffmpeg:
|
||||
inputs:
|
||||
- path: 'rtsp://127.0.0.1:8554/driveway'
|
||||
@@ -121,7 +121,7 @@ cameras:
|
||||
output_args:
|
||||
record: preset-record-generic-audio-aac # Record with aac audio
|
||||
detect:
|
||||
enabled: true
|
||||
enabled: false
|
||||
width: 640
|
||||
height: 360
|
||||
back_door:
|
||||
@@ -160,7 +160,7 @@ cameras:
|
||||
output_args:
|
||||
record: preset-record-generic-audio-aac # Record with aac audio
|
||||
onvif:
|
||||
host: 192.168.0.106
|
||||
host: 192.168.0.102
|
||||
port: 2020
|
||||
user: '{FRIGATE_FAMILY_ROOM_RTSP_USERNAME}'
|
||||
password: '{FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}'
|
||||
@@ -187,9 +187,26 @@ cameras:
|
||||
width: 1280
|
||||
height: 720
|
||||
|
||||
camera_groups:
|
||||
Outside:
|
||||
order: 1
|
||||
icon: LuSun
|
||||
cameras:
|
||||
- doorbell
|
||||
- front_door
|
||||
- driveway
|
||||
- back_door
|
||||
Inside:
|
||||
order: 2
|
||||
icon: LuHome
|
||||
cameras:
|
||||
- garage
|
||||
- family_room
|
||||
- office
|
||||
|
||||
ffmpeg:
|
||||
hwaccel_args: preset-vaapi # Use VAAPI hardware acceleration by default
|
||||
input_args: preset-rtsp-generic
|
||||
input_args: preset-rtsp-restream
|
||||
|
||||
objects:
|
||||
track:
|
||||
@@ -213,12 +230,16 @@ record:
|
||||
retain:
|
||||
days: 30 # Number of days to retain recordings regardless of events
|
||||
mode: all # Mode for retention: all (24/7), motion (only segments with motion), active_objects (only segments with active objects)
|
||||
events:
|
||||
pre_capture: 5 # Number of seconds before the event to include
|
||||
post_capture: 5 # Number of seconds after the event to include
|
||||
alerts:
|
||||
retain:
|
||||
default: 30 # Number of days to retain recordings of events
|
||||
mode: all # Mode for retention: all (24/7), motion (only segments with motion), active_objects (only segments with active objects)
|
||||
days: 30 # Number of days to retain alerts
|
||||
pre_capture: 5 # Number of seconds before the alert to include
|
||||
post_capture: 5 # Number of seconds after the alert to include
|
||||
detections:
|
||||
retain:
|
||||
days: 30 # Number of days to retain detections
|
||||
pre_capture: 5 # Number of seconds before the detection to include
|
||||
post_capture: 5 # Number of seconds after the detection to include
|
||||
|
||||
snapshots:
|
||||
enabled: true
|
||||
|
||||
+27
-10
@@ -3,7 +3,7 @@
|
||||
services:
|
||||
frigate:
|
||||
container_name: frigate
|
||||
image: ghcr.io/blakeblackshear/frigate:0.14.1
|
||||
image: ghcr.io/blakeblackshear/frigate:0.15.0
|
||||
labels:
|
||||
autoheal: 'true'
|
||||
restart: unless-stopped
|
||||
@@ -31,7 +31,7 @@ services:
|
||||
FRIGATE_FAMILY_ROOM_RTSP_PASSWORD: ${FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}
|
||||
FRIGATE_OFFICE_RTSP_USERNAME: frigate
|
||||
FRIGATE_OFFICE_RTSP_PASSWORD: ${FRIGATE_OFFICE_RTSP_PASSWORD}
|
||||
shm_size: '150mb'
|
||||
shm_size: '1000mb'
|
||||
devices:
|
||||
- /dev/dri:/dev/dri
|
||||
volumes:
|
||||
@@ -56,7 +56,7 @@ services:
|
||||
- 554:8554
|
||||
wyze-bridge:
|
||||
container_name: frigate-wyze-bridge
|
||||
image: mrlt8/wyze-bridge:2.9.7
|
||||
image: mrlt8/wyze-bridge:2.10.3
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
NET_MODE: LAN
|
||||
@@ -73,10 +73,11 @@ services:
|
||||
target: /etc/localtime
|
||||
read_only: true
|
||||
networks:
|
||||
- wyze-bridge
|
||||
- frigate
|
||||
notify:
|
||||
container_name: frigate-notify
|
||||
image: frigate-notify:latest
|
||||
notifier:
|
||||
container_name: frigate-notifier
|
||||
image: frigate-notifier:latest
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- frigate
|
||||
@@ -114,11 +115,17 @@ services:
|
||||
environment:
|
||||
IPGEOLOCATION_API_KEY: ${IPGEOLOCATION_API_KEY}
|
||||
FRIGATE_CONFIG_FILE: /frigate_config/config.yaml
|
||||
REQUESTS_CA_BUNDLE: /etc/ssl/certs/ca-certificates.crt
|
||||
SUNSET_DETECTION_RESET_HEALTHCHECKS_URL: 'https://healthchecks.homelab.net/ping/bee0e8ca-be23-41ba-aa30-478fc5f502f2'
|
||||
volumes:
|
||||
- type: volume
|
||||
source: config
|
||||
target: /frigate_config
|
||||
read_only: true
|
||||
- type: bind
|
||||
source: /data/certs/homelab_ca.crt
|
||||
target: /usr/local/share/ca-certificates/homelab_ca.crt
|
||||
read_only: true
|
||||
- type: bind
|
||||
source: /etc/localtime
|
||||
target: /etc/localtime
|
||||
@@ -157,10 +164,6 @@ services:
|
||||
networks:
|
||||
- frigate
|
||||
|
||||
networks:
|
||||
frigate:
|
||||
name: frigate
|
||||
|
||||
volumes:
|
||||
config:
|
||||
name: frigate-config
|
||||
@@ -168,3 +171,17 @@ volumes:
|
||||
media:
|
||||
name: frigate-media
|
||||
external: true
|
||||
|
||||
networks:
|
||||
frigate:
|
||||
name: frigate
|
||||
wyze-bridge:
|
||||
name: frigate-wyze-bridge
|
||||
driver: macvlan
|
||||
driver_opts:
|
||||
parent: enp1s0
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 192.168.0.0/24
|
||||
gateway: 192.168.0.1
|
||||
ip_range: 192.168.0.107/32
|
||||
+5
-5
@@ -69,25 +69,25 @@
|
||||
dest: /data/frigate-config/config.yaml
|
||||
mode: preserve
|
||||
|
||||
- name: Create temporary Docker build directory for frigate-notify
|
||||
- name: Create temporary Docker build directory for frigate-notifier
|
||||
ansible.builtin.tempfile:
|
||||
state: directory
|
||||
register: docker_build_dir
|
||||
- name: Copy Docker build directory
|
||||
ansible.builtin.copy:
|
||||
src: notify/
|
||||
src: notifier/
|
||||
dest: '{{docker_build_dir.path}}'
|
||||
mode: preserve
|
||||
- name: Build frigate-notify Docker image
|
||||
- name: Build frigate-notifier Docker image
|
||||
community.docker.docker_image:
|
||||
build:
|
||||
path: '{{docker_build_dir.path}}'
|
||||
name: frigate-notify
|
||||
name: frigate-notifier
|
||||
tag: latest
|
||||
source: build
|
||||
force_source: true
|
||||
state: present
|
||||
- name: Remove temporary Docker build directory for frigate-notify
|
||||
- name: Remove temporary Docker build directory for frigate-notifier
|
||||
ansible.builtin.file:
|
||||
path: '{{docker_build_dir.path}}'
|
||||
state: absent
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
FROM python:3.11
|
||||
FROM python:3.12
|
||||
WORKDIR /code
|
||||
|
||||
COPY docker_entrypoint.sh /
|
||||
ENTRYPOINT ["/docker_entrypoint.sh"]
|
||||
ENTRYPOINT ["python", "-m", "notifier"]
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip3 install -r requirements.txt
|
||||
@@ -1,2 +1,3 @@
|
||||
requests==2.30.0
|
||||
paho-mqtt==1.6.1
|
||||
PyYAML==6.0.1
|
||||
@@ -0,0 +1,23 @@
|
||||
version: 1
|
||||
disable_existing_loggers: false
|
||||
formatters:
|
||||
default:
|
||||
format: '[{asctime}.{msecs:03.0f}][{levelname}] {name}:{lineno} - {message}'
|
||||
style: '{'
|
||||
datefmt: '%Y-%m-%d %H:%M:%S'
|
||||
handlers:
|
||||
stdout:
|
||||
class: logging.StreamHandler
|
||||
level: INFO
|
||||
formatter: default
|
||||
stream: ext://sys.stdout
|
||||
stderr:
|
||||
class: logging.StreamHandler
|
||||
level: ERROR
|
||||
formatter: default
|
||||
stream: ext://sys.stderr
|
||||
root:
|
||||
level: DEBUG
|
||||
handlers:
|
||||
- stdout
|
||||
- stderr
|
||||
Whitespace-only changes.
@@ -0,0 +1,35 @@
|
||||
import datetime as dt
|
||||
import os
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from notifier.frigate.config import FrigateConfig, EventType
|
||||
from notifier.frigate.mqtt import MQTTSubscriber
|
||||
from notifier.notify.ntfy import NtfyNotification, NtfyNotificationSender
|
||||
from notifier.utils.logging import configure_logging
|
||||
|
||||
configure_logging()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def on_event(payload: dict[str, Any]) -> None:
|
||||
event_type = EventType(payload["type"])
|
||||
camera = payload["after"]["camera"]
|
||||
object_label = payload["after"]["label"]
|
||||
new_zones = {None} | set(payload["after"]["entered_zones"]) - set(payload["before"]["entered_zones"])
|
||||
for new_zone in new_zones:
|
||||
if frigate_config.is_alert(event_type, camera, object_label, new_zone):
|
||||
event_id = payload["after"]["id"]
|
||||
score = payload["after"]["top_score"]
|
||||
logger.debug(f"New alert for {object_label=} at {camera=} in {new_zone=}")
|
||||
notification = NtfyNotification(event_id, camera, object_label, score)
|
||||
notification_sender.send(notification)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
frigate_config = FrigateConfig()
|
||||
frigate_config.fetch()
|
||||
notification_sender = NtfyNotificationSender(quiet_period=dt.timedelta(minutes=3))
|
||||
mqtt_subscriber = MQTTSubscriber(on_event, username=os.getenv("MQTT_USERNAME"), password=os.getenv("MQTT_PASSWORD"))
|
||||
mqtt_subscriber.subscribe()
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,55 @@
|
||||
import json
|
||||
import logging
|
||||
from enum import StrEnum
|
||||
from functools import cache
|
||||
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EventType(StrEnum):
|
||||
NEW = "new"
|
||||
UPDATE = "update"
|
||||
END = "end"
|
||||
|
||||
|
||||
class FrigateConfig:
|
||||
def __init__(self, base_url: str = "http://frigate:5000") -> None:
|
||||
self._base_url = base_url
|
||||
self._camera_zones = {}
|
||||
|
||||
def fetch(self) -> None:
|
||||
response = requests.get(f"{self._base_url}/api/config")
|
||||
response.raise_for_status()
|
||||
config = json.loads(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["review"]["alerts"]["required_zones"]
|
||||
}
|
||||
for camera_name, camera_config in config["cameras"].items()
|
||||
}
|
||||
logger.info("Fetched Frigate camera zone configuration")
|
||||
|
||||
@cache
|
||||
def is_alert(self, event_type: EventType, camera: str, object_label: str, new_zone: str | None = None) -> bool:
|
||||
if zones := self._camera_zones[camera]:
|
||||
if not new_zone:
|
||||
# No zone change
|
||||
return False
|
||||
elif (object_labels := zones.get(new_zone)) is None:
|
||||
# New zone is not a required zone
|
||||
return False
|
||||
elif object_labels:
|
||||
# Alert if event has required object label
|
||||
return object_label in object_labels
|
||||
else:
|
||||
# No required object labels
|
||||
return True
|
||||
else:
|
||||
# No required zones, new event is an alert
|
||||
return event_type == EventType.NEW
|
||||
@@ -0,0 +1,32 @@
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Callable
|
||||
|
||||
from paho.mqtt.client import Client as MQTTClient, MQTTMessage
|
||||
from paho.mqtt.reasoncodes import ReasonCodes
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MQTTSubscriber:
|
||||
def __init__(self, callback: Callable[[dict[str, Any]], None], host: str = "mqtt", port: int = 1883, username: str | None = None, password: str | None = None) -> None:
|
||||
self._callback = callback
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._client = MQTTClient()
|
||||
if username and password:
|
||||
self._client.username_pw_set(username, password=password)
|
||||
self._client.on_connect = self._on_connect
|
||||
self._client.on_message = self._on_message
|
||||
|
||||
def subscribe(self) -> None:
|
||||
self._client.connect(host=self._host, port=self._port)
|
||||
self._client.loop_forever()
|
||||
|
||||
def _on_connect(self, client: MQTTClient, userdata: Any, flags: dict[str, Any], rc: ReasonCodes) -> None:
|
||||
logger.info(f"Connected with return code {rc}")
|
||||
client.subscribe("frigate/events")
|
||||
|
||||
def _on_message(self, client: MQTTClient, userdata: Any, message: MQTTMessage) -> None:
|
||||
payload = json.loads(message.payload.decode())
|
||||
self._callback(payload)
|
||||
Whitespace-only changes.
@@ -0,0 +1,50 @@
|
||||
import datetime as dt
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from functools import cache, cached_property
|
||||
|
||||
|
||||
class MobileOS(StrEnum):
|
||||
IOS = "ios"
|
||||
ANDROID = "android"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Notification:
|
||||
event_id: str
|
||||
camera: str
|
||||
object_label: str
|
||||
score: float
|
||||
|
||||
@cached_property
|
||||
def camera_display_name(self) -> str:
|
||||
return " ".join(word.capitalize() for word in self.camera.split("_"))
|
||||
|
||||
@cached_property
|
||||
def camera_url(self) -> str:
|
||||
return f"https://frigate.homelab.net/cameras/{self.camera}"
|
||||
|
||||
@cache
|
||||
def get_image_url(self, mobile_os: MobileOS = MobileOS.ANDROID) -> str:
|
||||
return f"https://frigate.homelab.net/api/events/{self.event_id}/thumbnail.jpg?format={mobile_os}"
|
||||
|
||||
|
||||
class NotificationSender[N: Notification](ABC):
|
||||
def __init__(self, quiet_period: dt.timedelta) -> None:
|
||||
self._quiet_period = quiet_period
|
||||
self._camera_to_last_notification_time = {}
|
||||
|
||||
@abstractmethod
|
||||
def _send(self, notification: N) -> None:
|
||||
...
|
||||
|
||||
def send(self, notification: N) -> None:
|
||||
now = time.time()
|
||||
last_notification_time = self._camera_to_last_notification_time.get(notification.camera, 0)
|
||||
if now - last_notification_time >= self._quiet_period.total_seconds():
|
||||
# Quiet period has passed since the last notification for this camera
|
||||
self._camera_to_last_notification_time[notification.camera] = now
|
||||
self._send(notification)
|
||||
@@ -0,0 +1,79 @@
|
||||
import datetime as dt
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from enum import IntEnum
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
from notifier.notify.notification import Notification, NotificationSender, MobileOS
|
||||
|
||||
|
||||
class NtfyPriority(IntEnum):
|
||||
MIN = 1
|
||||
LOW = 2
|
||||
DEFAULT = 3
|
||||
HIGH = 4
|
||||
MAX = 5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NtfyNotification(Notification):
|
||||
priority: int = NtfyPriority.DEFAULT
|
||||
|
||||
def generate_payload(self, mobile_os: MobileOS, dad: bool = False) -> dict[str, Any]:
|
||||
match mobile_os, dad:
|
||||
case _, True:
|
||||
topic = "frigate_notifications_dad"
|
||||
case MobileOS.ANDROID, False:
|
||||
topic = "frigate_notifications"
|
||||
case MobileOS.IOS, False:
|
||||
topic = "frigate_notifications_ios"
|
||||
|
||||
return {
|
||||
"topic": topic,
|
||||
"title": "Frigate",
|
||||
"message": f"{self.object_label.capitalize()} at {self.camera_display_name} ({self.score:.0%})",
|
||||
"priority": NtfyPriority.DEFAULT,
|
||||
"click": self.camera_url,
|
||||
"icon": "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/frigate.png",
|
||||
"attach": self.get_image_url(mobile_os),
|
||||
"actions": [
|
||||
{
|
||||
"action": "http",
|
||||
"label": "DBL (30m)" if dad else "Disable (30m)",
|
||||
"url": f"https://frigate.homelab.net/webcontrol/camera/{self.camera}/detection",
|
||||
"method": "POST",
|
||||
"headers": {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
"body": json.dumps({
|
||||
"detection": False,
|
||||
"duration": 30
|
||||
}),
|
||||
"clear": not dad,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class NtfyNotificationSender(NotificationSender[NtfyNotification]):
|
||||
def __init__(self, quiet_period: dt.timedelta, base_url: str = "https://ntfy.homelab.net") -> None:
|
||||
super().__init__(quiet_period)
|
||||
self._base_url = base_url
|
||||
|
||||
def _send(self, notification: NtfyNotification) -> None:
|
||||
# Send to Android topic
|
||||
payload = notification.generate_payload(MobileOS.ANDROID)
|
||||
response = requests.post(self._base_url, json=payload)
|
||||
response.raise_for_status()
|
||||
|
||||
# Send to iOS topic
|
||||
payload = notification.generate_payload(MobileOS.IOS)
|
||||
response = requests.post(self._base_url, json=payload)
|
||||
response.raise_for_status()
|
||||
|
||||
# Send to Dad topic
|
||||
payload = notification.generate_payload(MobileOS.ANDROID, dad=True)
|
||||
response = requests.post(self._base_url, json=payload)
|
||||
response.raise_for_status()
|
||||
Whitespace-only changes.
@@ -0,0 +1,12 @@
|
||||
import logging
|
||||
import logging.config
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
with open("configs/logging.yaml", "r") as logging_yaml:
|
||||
logging_config = yaml.safe_load(logging_yaml)
|
||||
|
||||
logging.config.dictConfig(logging_config)
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
update-ca-certificates
|
||||
|
||||
python3 frigate_event_notifier.py "$@"
|
||||
@@ -1,118 +0,0 @@
|
||||
import os
|
||||
import json
|
||||
import datetime as dt
|
||||
|
||||
import requests
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
|
||||
class FrigateEventNotifier:
|
||||
def __init__(self, mqtt_username, mqtt_password, quiet_period=3 * 60):
|
||||
self._mqtt_client = mqtt.Client()
|
||||
if mqtt_username is not None and mqtt_password is not None:
|
||||
self._mqtt_client.username_pw_set(mqtt_username, password=mqtt_password)
|
||||
self._mqtt_client.on_connect = self._on_connect
|
||||
self._mqtt_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["review"]["alerts"]["required_zones"]} for camera_name, camera_config in frigate_config["cameras"].items()}
|
||||
|
||||
self._quiet_period = quiet_period
|
||||
self._camera_to_last_notification_time = {}
|
||||
|
||||
def send_notification(self, event_id, camera, object_label, score, priority=3):
|
||||
now = dt.datetime.now()
|
||||
if now - self._camera_to_last_notification_time.get(camera, dt.datetime.min) >= dt.timedelta(seconds=self._quiet_period):
|
||||
# Quiet period has passed since the last notification for this camera
|
||||
self._camera_to_last_notification_time[camera] = now
|
||||
camera_location = " ".join(word.capitalize() for word in camera.split("_"))
|
||||
|
||||
ntfy_api_response = requests.post("https://ntfy.homelab.net", json={
|
||||
"topic": "frigate_notifications",
|
||||
"title": "Frigate",
|
||||
"message": f"{object_label.capitalize()} at {camera_location} ({score:.0%})",
|
||||
"priority": priority,
|
||||
"click": f"https://frigate.homelab.net/cameras/{camera}",
|
||||
"icon": "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/frigate.png",
|
||||
"attach": f"https://frigate.homelab.net/api/events/{event_id}/thumbnail.jpg?format=android",
|
||||
"actions": [
|
||||
{
|
||||
"action": "http",
|
||||
"label": "Disable (30m)",
|
||||
"url": f"https://frigate.homelab.net/webcontrol/camera/{camera}/detection",
|
||||
"method": "POST",
|
||||
"headers": {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
"body": json.dumps({
|
||||
"detection": False,
|
||||
"duration": 30
|
||||
}),
|
||||
"clear": True
|
||||
}
|
||||
]
|
||||
})
|
||||
ntfy_api_response.raise_for_status()
|
||||
|
||||
ntfy_api_response = requests.post("https://ntfy.homelab.net", json={
|
||||
"topic": "frigate_notifications_dad",
|
||||
"title": "Frigate",
|
||||
"message": f"{object_label.capitalize()} at {camera_location} ({score:.0%})",
|
||||
"priority": priority,
|
||||
"click": f"https://frigate.homelab.net/cameras/{camera}",
|
||||
"icon": "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/frigate.png",
|
||||
"attach": f"https://frigate.homelab.net/api/events/{event_id}/thumbnail.jpg?format=android",
|
||||
"actions": [
|
||||
{
|
||||
"action": "http",
|
||||
"label": "DBL (30m)",
|
||||
"url": f"https://frigate.homelab.net/webcontrol/camera/{camera}/detection",
|
||||
"method": "POST",
|
||||
"headers": {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
"body": json.dumps({
|
||||
"detection": False,
|
||||
"duration": 30
|
||||
})
|
||||
}
|
||||
]
|
||||
})
|
||||
ntfy_api_response.raise_for_status()
|
||||
|
||||
def start(self):
|
||||
self._mqtt_client.connect(host="mqtt", port=1883)
|
||||
self._mqtt_client.loop_forever()
|
||||
|
||||
def _on_connect(self, client, userdata, flags, rc):
|
||||
print(f"Connected with return code {rc}")
|
||||
client.subscribe("frigate/events")
|
||||
|
||||
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":
|
||||
event_id = payload["after"]["id"]
|
||||
score = payload["after"]["top_score"]
|
||||
|
||||
self.send_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"]
|
||||
|
||||
self.send_notification(event_id, camera, object_label, score)
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
frigate_event_notifier = FrigateEventNotifier(os.environ.get("MQTT_USERNAME"), os.environ.get("MQTT_PASSWORD"))
|
||||
frigate_event_notifier.start()
|
||||
+13
-1
@@ -47,7 +47,7 @@
|
||||
FRIGATE_BACK_DOOR_RTSP_PASSWORD: '{{frigate_config.rtsp.back_door.password}}'
|
||||
FRIGATE_FAMILY_ROOM_RTSP_PASSWORD: '{{frigate_config.rtsp.family_room.password}}'
|
||||
FRIGATE_OFFICE_RTSP_PASSWORD: '{{frigate_config.rtsp.office.password}}'
|
||||
community.docker.docker_compose:
|
||||
community.docker.docker_compose_v2:
|
||||
project_name: frigate
|
||||
project_src: '{{docker_compose_dir.path}}'
|
||||
state: present
|
||||
@@ -56,3 +56,15 @@
|
||||
ansible.builtin.file:
|
||||
path: '{{docker_compose_dir.path}}'
|
||||
state: absent
|
||||
|
||||
- name: Update CA certificates for frigate-notifier
|
||||
community.docker.docker_container_exec:
|
||||
container: frigate-notifier
|
||||
command: update-ca-certificates
|
||||
user: root
|
||||
|
||||
- name: Update CA certificates for frigate-webcontrol
|
||||
community.docker.docker_container_exec:
|
||||
container: frigate-webcontrol
|
||||
command: update-ca-certificates
|
||||
user: root
|
||||
@@ -12,7 +12,7 @@
|
||||
mode: preserve
|
||||
|
||||
- name: Docker Compose down Frigate
|
||||
community.docker.docker_compose:
|
||||
community.docker.docker_compose_v2:
|
||||
project_name: frigate
|
||||
project_src: '{{docker_compose_dir.path}}'
|
||||
state: absent
|
||||
|
||||
@@ -4,12 +4,12 @@ import "os"
|
||||
|
||||
import "gopkg.in/yaml.v3"
|
||||
|
||||
|
||||
type Config struct {
|
||||
Cameras map[string]string `yaml:"cameras"`
|
||||
PingIntervalSeconds int64 `yaml:"ping_interval_s"`
|
||||
PingTimeoutSeconds int64 `yaml:"ping_timeout_s"`
|
||||
ConsecutiveDownThreshold int `yaml:"consecutive_down_threshold"`
|
||||
Cameras map[string]string `yaml:"cameras"`
|
||||
PingIntervalSeconds int64 `yaml:"ping_interval_s"`
|
||||
PingTimeoutSeconds int64 `yaml:"ping_timeout_s"`
|
||||
ConsecutiveDownThreshold int `yaml:"consecutive_down_threshold"`
|
||||
NotificationRepeatThreshold int `yaml:"notification_repeat_threshold"`
|
||||
}
|
||||
|
||||
func ReadConfig(configFilename string) Config {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
cameras:
|
||||
back_door: 'rtsp://frigate:8554/back_door'
|
||||
doorbell: 'rtsp://frigate:8554/doorbell'
|
||||
front_door: 'rtsp://frigate:8554/front_door'
|
||||
#front_door: 'rtsp://frigate:8554/front_door'
|
||||
garage: 'rtsp://frigate:8554/garage'
|
||||
ping_interval_s: 60
|
||||
ping_timeout_s: 30
|
||||
consecutive_down_threshold: 3
|
||||
|
||||
notification_repeat_threshold: 30
|
||||
@@ -12,6 +12,6 @@ func main() {
|
||||
var pingInterval = time.Duration(uptimeConfig.PingIntervalSeconds * int64(time.Second))
|
||||
var pingTimeout = time.Duration(uptimeConfig.PingTimeoutSeconds * int64(time.Second))
|
||||
|
||||
var cameraMonitor CameraMonitor = NewCameraMonitor(pingInterval, pingTimeout, uptimeConfig.ConsecutiveDownThreshold, notify.NewNtfyNotifier())
|
||||
var cameraMonitor CameraMonitor = NewCameraMonitor(pingInterval, pingTimeout, uptimeConfig.ConsecutiveDownThreshold, uptimeConfig.NotificationRepeatThreshold, notify.NewNtfyNotifier())
|
||||
cameraMonitor.Run(uptimeConfig.Cameras)
|
||||
}
|
||||
+18
-22
@@ -13,44 +13,40 @@ import (
|
||||
)
|
||||
|
||||
type CameraMonitor struct {
|
||||
pingInterval time.Duration
|
||||
pingTimeout time.Duration
|
||||
consecutiveDownThreshold int
|
||||
downtime map[string]int
|
||||
pingInterval time.Duration
|
||||
pingTimeout time.Duration
|
||||
consecutiveDownThreshold int
|
||||
notificationRepeatThreshold int
|
||||
downtime map[string]int
|
||||
notify.Notifier
|
||||
}
|
||||
|
||||
func NewCameraMonitor(pingInterval time.Duration, pingTimeout time.Duration, consecutiveDownThreshold int, notifier notify.Notifier) CameraMonitor {
|
||||
func NewCameraMonitor(pingInterval time.Duration, pingTimeout time.Duration, consecutiveDownThreshold int, notificationRepeatThreshold int, notifier notify.Notifier) CameraMonitor {
|
||||
return CameraMonitor{
|
||||
pingInterval: pingInterval,
|
||||
pingTimeout: pingTimeout,
|
||||
consecutiveDownThreshold: consecutiveDownThreshold,
|
||||
downtime: make(map[string]int),
|
||||
Notifier: notifier,
|
||||
pingInterval: pingInterval,
|
||||
pingTimeout: pingTimeout,
|
||||
consecutiveDownThreshold: consecutiveDownThreshold,
|
||||
notificationRepeatThreshold: notificationRepeatThreshold,
|
||||
downtime: make(map[string]int),
|
||||
Notifier: notifier,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (c CameraMonitor) onCameraUp(camera string) {
|
||||
c.SendNotification(camera, true)
|
||||
slog.Info(fmt.Sprintf("%s camera is back online!", camera))
|
||||
}
|
||||
|
||||
func (c CameraMonitor) onCameraDown(camera string) {
|
||||
c.SendNotification(camera, false)
|
||||
slog.Info(fmt.Sprintf("%s camera is offline!", camera))
|
||||
}
|
||||
|
||||
func (c CameraMonitor) onCameraPingResult(camera string, online bool) {
|
||||
if online {
|
||||
if c.downtime[camera] >= c.consecutiveDownThreshold {
|
||||
c.onCameraUp(camera)
|
||||
c.SendNotification(camera, true)
|
||||
slog.Info(fmt.Sprintf("%s camera is back online!", camera))
|
||||
}
|
||||
c.downtime[camera] = 0
|
||||
} else {
|
||||
c.downtime[camera] += 1
|
||||
if c.downtime[camera] == c.consecutiveDownThreshold {
|
||||
c.onCameraDown(camera)
|
||||
c.SendNotification(camera, false)
|
||||
slog.Info(fmt.Sprintf("%s camera is offline!", camera))
|
||||
} else if c.notificationRepeatThreshold >= c.consecutiveDownThreshold && c.downtime[camera]%c.notificationRepeatThreshold == c.consecutiveDownThreshold {
|
||||
c.SendNotification(camera, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,14 +5,13 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
|
||||
type Notifier interface {
|
||||
SendNotification(camera string, online bool)
|
||||
}
|
||||
|
||||
func createMessage(camera string, online bool) string {
|
||||
var msgTemplates = map[bool]string{
|
||||
true: "%s camera is back online!",
|
||||
true: "%s camera is back online!",
|
||||
false: "%s camera is offline!",
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
|
||||
type NtfyNotifier struct {
|
||||
client *http.Client
|
||||
}
|
||||
@@ -26,21 +25,21 @@ func NewNtfyNotifier() NtfyNotifier {
|
||||
|
||||
func (n NtfyNotifier) SendNotification(camera string, online bool) {
|
||||
type ntfyJson struct {
|
||||
Topic string `json:"topic"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message"`
|
||||
Priority int `json:"priority"`
|
||||
Click string `json:"click"`
|
||||
Icon string `json:"icon"`
|
||||
Topic string `json:"topic"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message"`
|
||||
Priority int `json:"priority"`
|
||||
Click string `json:"click"`
|
||||
Icon string `json:"icon"`
|
||||
}
|
||||
|
||||
var reqJson, jsonErr = json.Marshal(ntfyJson{
|
||||
Topic: "frigate_camera_uptime",
|
||||
Title: "Frigate",
|
||||
Message: createMessage(camera, online),
|
||||
Topic: "frigate_camera_uptime",
|
||||
Title: "Frigate",
|
||||
Message: createMessage(camera, online),
|
||||
Priority: 3,
|
||||
Click: fmt.Sprintf("https://frigate.homelab.net/cameras/%s", camera),
|
||||
Icon: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/frigate.png",
|
||||
Click: fmt.Sprintf("https://frigate.homelab.net/cameras/%s", camera),
|
||||
Icon: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/frigate.png",
|
||||
})
|
||||
if jsonErr != nil {
|
||||
slog.Error("Failed to construct JSON request body", "error", jsonErr)
|
||||
|
||||
@@ -2,7 +2,6 @@ package ping
|
||||
|
||||
import "os/exec"
|
||||
|
||||
|
||||
func IPPing(host string) bool {
|
||||
var cmd = exec.Command("ping", "-w", "3", "-c", "1", host)
|
||||
var err = cmd.Run()
|
||||
|
||||
@@ -2,7 +2,6 @@ package ping
|
||||
|
||||
import "os/exec"
|
||||
|
||||
|
||||
func VideoPing(url string) bool {
|
||||
var cmd = exec.Command("ffprobe", "-rtsp_transport", "tcp", "-i", url, "-timeout", "10000000")
|
||||
var err = cmd.Run()
|
||||
|
||||
@@ -4,3 +4,4 @@ fastapi==0.110.0
|
||||
uvicorn[standard]==0.29.0
|
||||
aiohttp==3.8.6
|
||||
paho-mqtt==1.6.1
|
||||
requests==2.30.0
|
||||
@@ -4,6 +4,7 @@ import logging
|
||||
import os
|
||||
|
||||
import paho.mqtt.publish as mqtt_publish
|
||||
import requests
|
||||
|
||||
from webcontrol.frigate_config import FrigateConfigFile
|
||||
from webcontrol.nighttime import get_nighttimes
|
||||
@@ -27,7 +28,20 @@ async def reset_all_cameras_detection_after_sunset() -> None:
|
||||
logger.info(f"Waiting until {nighttime} to reset detection for all cameras")
|
||||
await asyncio.sleep((nighttime - dt.datetime.now()).total_seconds())
|
||||
|
||||
await frigate_config_file.reload()
|
||||
active_and_detection_enabled_cameras = set(frigate_config_file.active_cameras).intersection(frigate_config_file.detection_enabled_cameras)
|
||||
for camera in active_and_detection_enabled_cameras:
|
||||
await set_camera_detection(camera, True)
|
||||
healthchecks_url = os.getenv("SUNSET_DETECTION_RESET_HEALTHCHECKS_URL")
|
||||
try:
|
||||
if healthchecks_url:
|
||||
requests.post(os.path.join(healthchecks_url, "start"))
|
||||
|
||||
await frigate_config_file.reload()
|
||||
active_and_detection_enabled_cameras = set(frigate_config_file.active_cameras).intersection(frigate_config_file.detection_enabled_cameras)
|
||||
for camera in active_and_detection_enabled_cameras:
|
||||
await set_camera_detection(camera, True)
|
||||
|
||||
if healthchecks_url:
|
||||
requests.post(healthchecks_url, data=", ".join(active_and_detection_enabled_cameras))
|
||||
except Exception as e:
|
||||
if healthchecks_url:
|
||||
requests.post(os.path.join(healthchecks_url, "fail"), data=str(e))
|
||||
raise e
|
||||
|
||||
Reference in new issue
Block a user