Compare commits

...
21 Commits
Author SHA1 Message Date
ashish 8f5fe09afa Update config.yaml 2026-05-15 21:43:03 -05:00
ashish 4fb3d6a99e Fix notification debouncer 2025-09-07 12:59:22 -05:00
ashish 468a0b02f3 Fix and cleanup notifier 2025-09-03 23:18:49 -05:00
ashish e6ccd8f1d7 Setup repeat camera down notifications #24 2025-05-15 12:01:49 -05:00
ashish 7b24dad5b9 Setup Healthchecks integration for sunset detection reset #22 2025-04-18 21:44:50 -05:00
ashish 4620d5b9dc Rewrite notifier microservice #23 2025-04-18 21:43:20 -05:00
ashish 44b61402b1 Add camera groups #20 2025-04-14 21:08:02 -05:00
ashish 75227a37b2 Replace Wyze cam v4 #19 2025-04-14 21:06:17 -05:00
ashish db12bd0c35 Adjust FFmpeg input args to restream preset #18 2025-04-05 10:18:06 -05:00
ashish 293ee80a6f #16 Upgrade to v0.15.0 (#17)
* Bump Docker image tagged version
* Update record config section

Reviewed-on: #17
Co-authored-by: Ashish D'Souza <[email protected]>
Co-committed-by: Ashish D'Souza <[email protected]>
2025-04-05 00:19:35 -04:00
ashish 8ec090b212 Solved IOTC_ER_TIMEOUT Wyze error with MACVLAN 2025-04-04 15:29:36 -05:00
ashish c46013676c Migrate to Ansible docker_compose_v2 2025-04-04 11:16:28 -05:00
ashish f404cb2d20 Increase shared memory allocation 2024-12-28 21:46:04 -06:00
ashish 26da928edc Update local IP address reservations 2024-12-28 14:22:45 -06:00
ashish 167af2d508 Replace garage camera 2024-12-21 11:16:06 -06:00
ashish 8900de55c1 Upgrade Wyze bridge to v2.10.3 2024-12-21 10:50:47 -06:00
ashish b0c3300c34 Disable audio backchannel for AD110 2024-12-15 17:30:37 -06:00
ashish ee4910dc7b Add object filters for back door camera 2024-12-15 15:36:24 -06:00
ashish 84c91ec9e0 Add motion masks to family room camera 2024-11-30 19:08:10 -06:00
ashish 0d97e5b5a5 Add PTZ controls for family room camera 2024-11-24 17:08:04 -06:00
ashish d3de267278 Migrate from CPU to OpenVINO detectors 2024-11-24 16:55:15 -06:00
30 changed files with 463 additions and 215 deletions

No files matched your search

+70 -20
View File
@@ -2,29 +2,43 @@ mqtt:
host: mqtt
detectors:
cpu1:
type: cpu
num_threads: 2
cpu2:
type: cpu
num_threads: 2
ov1:
type: openvino
device: GPU
ov2:
type: openvino
device: GPU
ov3:
type: openvino
device: GPU
ov4:
type: openvino
device: GPU
model:
width: 300
height: 300
input_tensor: nhwc
input_pixel_format: bgr
path: /openvino-model/ssdlite_mobilenet_v2.xml
labelmap_path: /openvino-model/coco_91cl_bkgr.txt
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'
- '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:
@@ -96,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'
@@ -107,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:
@@ -128,6 +142,12 @@ cameras:
motion:
mask:
- 1877,1080,1378,1080,1378,1008,1877,1008 # Timestamp
objects:
filters:
person:
mask:
- 0.343,0.349,0.373,0.347,0.382,0.451,0.35,0.45 # Left snowman
- 0.67,0.349,0.703,0.351,0.696,0.454,0.662,0.452 # Right snowman
family_room:
enabled: false
ffmpeg:
@@ -139,10 +159,19 @@ cameras:
hwaccel_args: preset-intel-qsv-h264 # Use Intel QSV hardware acceleration for H.264
output_args:
record: preset-record-generic-audio-aac # Record with aac audio
onvif:
host: 192.168.0.102
port: 2020
user: '{FRIGATE_FAMILY_ROOM_RTSP_USERNAME}'
password: '{FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}'
detect:
enabled: true
width: 1920
height: 1080
motion:
mask:
- 0,0,0.32,0,0.32,0.048,0,0.048 # Timestamp
- 0.351,0,0.47,0,0.471,0.16,0.353,0.165 # Window
office:
enabled: false
ffmpeg:
@@ -158,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:
@@ -184,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
View File
@@ -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
View File
@@ -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
+2 -3
View File
@@ -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
+23
View File
@@ -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
View File
Whitespace-only changes.
+35
View File
@@ -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.
+55
View File
@@ -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
+32
View File
@@ -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)
+79
View File
@@ -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.
+12
View File
@@ -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)
-6
View File
@@ -1,6 +0,0 @@
#!/bin/bash
set -e
update-ca-certificates
python3 frigate_event_notifier.py "$@"
-118
View File
@@ -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
View File
@@ -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
+1 -1
View File
@@ -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
+5 -5
View File
@@ -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 {
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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
View File
@@ -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)
}
}
}
+1 -2
View File
@@ -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!",
}
+12 -13
View File
@@ -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)
-1
View File
@@ -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()
-1
View File
@@ -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()
+1
View File
@@ -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
+18 -4
View File
@@ -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