Compare commits

..
6 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
18 changed files with 76 additions and 195 deletions

No files matched your search

+5 -5
View File
@@ -32,11 +32,11 @@ go2rtc:
front_door: front_door:
- 'rtsp://{FRIGATE_FRONT_DOOR_RTSP_USERNAME}:{FRIGATE_FRONT_DOOR_RTSP_PASSWORD}@192.168.0.101:554/live/ch0' - 'rtsp://{FRIGATE_FRONT_DOOR_RTSP_USERNAME}:{FRIGATE_FRONT_DOOR_RTSP_PASSWORD}@192.168.0.101:554/live/ch0'
driveway: driveway:
- 'rtsp://{FRIGATE_DRIVEWAY_RTSP_USERNAME}:{FRIGATE_DRIVEWAY_RTSP_PASSWORD}@192.168.0.104:5543/live/channel1' - 'rtsp://{FRIGATE_DRIVEWAY_RTSP_USERNAME}:{FRIGATE_DRIVEWAY_RTSP_PASSWORD}@192.168.0.103:5543/live/channel1'
back_door: back_door:
- 'rtsp://wyze-bridge:8554/back-yard-cam' - 'rtsp://wyze-bridge:8554/back-yard-cam'
family_room: 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: office:
- 'rtsp://{FRIGATE_OFFICE_RTSP_USERNAME}:{FRIGATE_OFFICE_RTSP_PASSWORD}@192.168.0.105:554/live/ch0' - 'rtsp://{FRIGATE_OFFICE_RTSP_USERNAME}:{FRIGATE_OFFICE_RTSP_PASSWORD}@192.168.0.105:554/live/ch0'
@@ -110,7 +110,7 @@ cameras:
- 167,1080,511,1080,328,744,234,456,140,451,0,509,0,804 # Flower bed and hedge - 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 - 1153,847,1112,838,1042,896,1023,988,1023,1080,1525,1080 # Drainpipe
driveway: driveway:
enabled: false enabled: true
ffmpeg: ffmpeg:
inputs: inputs:
- path: 'rtsp://127.0.0.1:8554/driveway' - path: 'rtsp://127.0.0.1:8554/driveway'
@@ -121,7 +121,7 @@ cameras:
output_args: output_args:
record: preset-record-generic-audio-aac # Record with aac audio record: preset-record-generic-audio-aac # Record with aac audio
detect: detect:
enabled: true enabled: false
width: 640 width: 640
height: 360 height: 360
back_door: back_door:
@@ -160,7 +160,7 @@ cameras:
output_args: output_args:
record: preset-record-generic-audio-aac # Record with aac audio record: preset-record-generic-audio-aac # Record with aac audio
onvif: onvif:
host: 192.168.0.106 host: 192.168.0.102
port: 2020 port: 2020
user: '{FRIGATE_FAMILY_ROOM_RTSP_USERNAME}' user: '{FRIGATE_FAMILY_ROOM_RTSP_USERNAME}'
password: '{FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}' password: '{FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}'
+5 -4
View File
@@ -16,19 +16,20 @@ def on_event(payload: dict[str, Any]) -> None:
event_type = EventType(payload["type"]) event_type = EventType(payload["type"])
camera = payload["after"]["camera"] camera = payload["after"]["camera"]
object_label = payload["after"]["label"] object_label = payload["after"]["label"]
new_zones = set(payload["after"]["entered_zones"]) - set(payload["before"]["entered_zones"]) new_zones = {None} | set(payload["after"]["entered_zones"]) - set(payload["before"]["entered_zones"])
for new_zone in new_zones: for new_zone in new_zones:
if frigate_config.is_alert(event_type, camera, new_zone, object_label): if frigate_config.is_alert(event_type, camera, object_label, new_zone):
event_id = payload["after"]["id"] event_id = payload["after"]["id"]
score = payload["after"]["top_score"] 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 = NtfyNotification(event_id, camera, object_label, score)
notification_sender.send(notification) notification_sender.send(notification)
if __name__ == "__main__": if __name__ == "__main__":
frigate_config = FrigateConfig() frigate_config = FrigateConfig()
notification_sender = NtfyNotificationSender(quiet_period=dt.timedelta(seconds=3 * 60)) 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 = MQTTSubscriber(on_event, username=os.getenv("MQTT_USERNAME"), password=os.getenv("MQTT_PASSWORD"))
mqtt_subscriber.subscribe() mqtt_subscriber.subscribe()
+11 -9
View File
@@ -20,7 +20,7 @@ class FrigateConfig:
self._camera_zones = {} self._camera_zones = {}
def fetch(self) -> None: def fetch(self) -> None:
response = requests.get(self._base_url) response = requests.get(f"{self._base_url}/api/config")
response.raise_for_status() response.raise_for_status()
config = json.loads(response.content) config = json.loads(response.content)
self._camera_zones = { self._camera_zones = {
@@ -36,18 +36,20 @@ class FrigateConfig:
logger.info("Fetched Frigate camera zone configuration") logger.info("Fetched Frigate camera zone configuration")
@cache @cache
def is_alert(self, event_type: EventType, camera: str, new_zone: str, object_label: str) -> bool: 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 zones := self._camera_zones[camera]:
if (object_labels := zones.get(new_zone)) is None: 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 # New zone is not a required zone
return False return False
elif object_labels:
# Alert if event has required object label
return object_label in object_labels
else: else:
if object_labels: # No required object labels
# Alert if event has required object label return True
return object_label in object_labels
else:
# No required object labels
return True
else: else:
# No required zones, new event is an alert # No required zones, new event is an alert
return event_type == EventType.NEW return event_type == EventType.NEW
+3 -1
View File
@@ -16,13 +16,15 @@ class MQTTSubscriber:
self._client = MQTTClient() self._client = MQTTClient()
if username and password: if username and password:
self._client.username_pw_set(username, password=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: def subscribe(self) -> None:
self._client.connect(host=self._host, port=self._port) self._client.connect(host=self._host, port=self._port)
self._client.loop_forever() self._client.loop_forever()
def _on_connect(self, client: MQTTClient, userdata: Any, flags: dict[str, Any], rc: ReasonCodes) -> None: def _on_connect(self, client: MQTTClient, userdata: Any, flags: dict[str, Any], rc: ReasonCodes) -> None:
logger.info("Connected with return code {rc}") logger.info(f"Connected with return code {rc}")
client.subscribe("frigate/events") client.subscribe("frigate/events")
def _on_message(self, client: MQTTClient, userdata: Any, message: MQTTMessage) -> None: def _on_message(self, client: MQTTClient, userdata: Any, message: MQTTMessage) -> None:
@@ -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()
View File
Whitespace-only changes.
Whitespace-only changes.
+4 -2
View File
@@ -1,6 +1,7 @@
import datetime as dt import datetime as dt
import time import time
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass from dataclasses import dataclass
from enum import StrEnum from enum import StrEnum
from functools import cache, cached_property from functools import cache, cached_property
@@ -11,7 +12,7 @@ class MobileOS(StrEnum):
ANDROID = "android" ANDROID = "android"
@dataclass @dataclass(frozen=True)
class Notification: class Notification:
event_id: str event_id: str
camera: str camera: str
@@ -42,7 +43,8 @@ class NotificationSender[N: Notification](ABC):
def send(self, notification: N) -> None: def send(self, notification: N) -> None:
now = time.time() now = time.time()
last_notification_time = self._camera_to_last_notification_time.setdefault(notification.camera, 0) last_notification_time = self._camera_to_last_notification_time.get(notification.camera, 0)
if now - last_notification_time >= self._quiet_period.total_seconds(): if now - last_notification_time >= self._quiet_period.total_seconds():
# Quiet period has passed since the last notification for this camera # Quiet period has passed since the last notification for this camera
self._camera_to_last_notification_time[notification.camera] = now
self._send(notification) self._send(notification)
+1 -1
View File
@@ -17,7 +17,7 @@ class NtfyPriority(IntEnum):
MAX = 5 MAX = 5
@dataclass @dataclass(frozen=True)
class NtfyNotification(Notification): class NtfyNotification(Notification):
priority: int = NtfyPriority.DEFAULT priority: int = NtfyPriority.DEFAULT
+8 -8
View File
@@ -58,13 +58,13 @@
state: absent state: absent
- name: Update CA certificates for frigate-notifier - name: Update CA certificates for frigate-notifier
community.docker.docker_container_exec: community.docker.docker_container_exec:
container: frigate-notifier container: frigate-notifier
command: update-ca-certificates command: update-ca-certificates
user: root user: root
- name: Update CA certificates for frigate-webcontrol - name: Update CA certificates for frigate-webcontrol
community.docker.docker_container_exec: community.docker.docker_container_exec:
container: frigate-webcontrol container: frigate-webcontrol
command: update-ca-certificates command: update-ca-certificates
user: root user: root
+5 -5
View File
@@ -4,12 +4,12 @@ import "os"
import "gopkg.in/yaml.v3" import "gopkg.in/yaml.v3"
type Config struct { type Config struct {
Cameras map[string]string `yaml:"cameras"` Cameras map[string]string `yaml:"cameras"`
PingIntervalSeconds int64 `yaml:"ping_interval_s"` PingIntervalSeconds int64 `yaml:"ping_interval_s"`
PingTimeoutSeconds int64 `yaml:"ping_timeout_s"` PingTimeoutSeconds int64 `yaml:"ping_timeout_s"`
ConsecutiveDownThreshold int `yaml:"consecutive_down_threshold"` ConsecutiveDownThreshold int `yaml:"consecutive_down_threshold"`
NotificationRepeatThreshold int `yaml:"notification_repeat_threshold"`
} }
func ReadConfig(configFilename string) Config { func ReadConfig(configFilename string) Config {
+2 -2
View File
@@ -1,9 +1,9 @@
cameras: cameras:
back_door: 'rtsp://frigate:8554/back_door' back_door: 'rtsp://frigate:8554/back_door'
doorbell: 'rtsp://frigate:8554/doorbell' doorbell: 'rtsp://frigate:8554/doorbell'
front_door: 'rtsp://frigate:8554/front_door' #front_door: 'rtsp://frigate:8554/front_door'
garage: 'rtsp://frigate:8554/garage' garage: 'rtsp://frigate:8554/garage'
ping_interval_s: 60 ping_interval_s: 60
ping_timeout_s: 30 ping_timeout_s: 30
consecutive_down_threshold: 3 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 pingInterval = time.Duration(uptimeConfig.PingIntervalSeconds * int64(time.Second))
var pingTimeout = time.Duration(uptimeConfig.PingTimeoutSeconds * 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) cameraMonitor.Run(uptimeConfig.Cameras)
} }
+18 -22
View File
@@ -13,44 +13,40 @@ import (
) )
type CameraMonitor struct { type CameraMonitor struct {
pingInterval time.Duration pingInterval time.Duration
pingTimeout time.Duration pingTimeout time.Duration
consecutiveDownThreshold int consecutiveDownThreshold int
downtime map[string]int notificationRepeatThreshold int
downtime map[string]int
notify.Notifier 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{ return CameraMonitor{
pingInterval: pingInterval, pingInterval: pingInterval,
pingTimeout: pingTimeout, pingTimeout: pingTimeout,
consecutiveDownThreshold: consecutiveDownThreshold, consecutiveDownThreshold: consecutiveDownThreshold,
downtime: make(map[string]int), notificationRepeatThreshold: notificationRepeatThreshold,
Notifier: notifier, 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) { func (c CameraMonitor) onCameraPingResult(camera string, online bool) {
if online { if online {
if c.downtime[camera] >= c.consecutiveDownThreshold { 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 c.downtime[camera] = 0
} else { } else {
c.downtime[camera] += 1 c.downtime[camera] += 1
if c.downtime[camera] == c.consecutiveDownThreshold { 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" "strings"
) )
type Notifier interface { type Notifier interface {
SendNotification(camera string, online bool) SendNotification(camera string, online bool)
} }
func createMessage(camera string, online bool) string { func createMessage(camera string, online bool) string {
var msgTemplates = map[bool]string{ var msgTemplates = map[bool]string{
true: "%s camera is back online!", true: "%s camera is back online!",
false: "%s camera is offline!", false: "%s camera is offline!",
} }
+12 -13
View File
@@ -1,15 +1,14 @@
package notify package notify
import ( import (
"crypto/tls"
"bytes" "bytes"
"crypto/tls"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log/slog" "log/slog"
"net/http" "net/http"
) )
type NtfyNotifier struct { type NtfyNotifier struct {
client *http.Client client *http.Client
} }
@@ -26,21 +25,21 @@ func NewNtfyNotifier() NtfyNotifier {
func (n NtfyNotifier) SendNotification(camera string, online bool) { func (n NtfyNotifier) SendNotification(camera string, online bool) {
type ntfyJson struct { type ntfyJson struct {
Topic string `json:"topic"` Topic string `json:"topic"`
Title string `json:"title"` Title string `json:"title"`
Message string `json:"message"` Message string `json:"message"`
Priority int `json:"priority"` Priority int `json:"priority"`
Click string `json:"click"` Click string `json:"click"`
Icon string `json:"icon"` Icon string `json:"icon"`
} }
var reqJson, jsonErr = json.Marshal(ntfyJson{ var reqJson, jsonErr = json.Marshal(ntfyJson{
Topic: "frigate_camera_uptime", Topic: "frigate_camera_uptime",
Title: "Frigate", Title: "Frigate",
Message: createMessage(camera, online), Message: createMessage(camera, online),
Priority: 3, Priority: 3,
Click: fmt.Sprintf("https://frigate.homelab.net/cameras/%s", camera), Click: fmt.Sprintf("https://frigate.homelab.net/cameras/%s", camera),
Icon: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/frigate.png", Icon: "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/frigate.png",
}) })
if jsonErr != nil { if jsonErr != nil {
slog.Error("Failed to construct JSON request body", "error", jsonErr) slog.Error("Failed to construct JSON request body", "error", jsonErr)
-1
View File
@@ -2,7 +2,6 @@ package ping
import "os/exec" import "os/exec"
func IPPing(host string) bool { func IPPing(host string) bool {
var cmd = exec.Command("ping", "-w", "3", "-c", "1", host) var cmd = exec.Command("ping", "-w", "3", "-c", "1", host)
var err = cmd.Run() var err = cmd.Run()
-1
View File
@@ -2,7 +2,6 @@ package ping
import "os/exec" import "os/exec"
func VideoPing(url string) bool { func VideoPing(url string) bool {
var cmd = exec.Command("ffprobe", "-rtsp_transport", "tcp", "-i", url, "-timeout", "10000000") var cmd = exec.Command("ffprobe", "-rtsp_transport", "tcp", "-i", url, "-timeout", "10000000")
var err = cmd.Run() var err = cmd.Run()