Compare commits

..
2 Commits
Author SHA1 Message Date
ashish 4a87bc5606 Setup pipeline to support Wyze bridge 2023-10-29 20:55:19 -05:00
ashish 56da8ba7db Added configuration for Wyze bridge 2023-10-29 20:54:39 -05:00
58 changed files with 366 additions and 1419 deletions

No files matched your search

Vendored
+1 -9
View File
@@ -14,7 +14,7 @@ pipeline {
frigate_config = readJSON file: 'frigate_config.json'
}
ansiblePlaybook credentialsId: 'rivendell-ssh-key', disableHostKeyChecking: true, extras: "--extra-vars 'ipgeolocation_api_key=\"${frigate_config.ipgeolocation.api_key}\" wyze_email=\"${frigate_config.wyze.email}\" wyze_password=\"${frigate_config.wyze.password}\" wyze_api_id=\"${frigate_config.wyze.api_id}\" wyze_api_key=\"${frigate_config.wyze.api_key}\" garage_rtsp_password=\"${frigate_config.rtsp.garage.password}\" front_door_rtsp_password=\"${frigate_config.rtsp.front_door.password}\" doorbell_rtsp_password=\"${frigate_config.rtsp.doorbell.password}\" driveway_rtsp_password=\"${frigate_config.rtsp.driveway.password}\" back_door_rtsp_password=\"${frigate_config.rtsp.back_door.password}\" family_room_rtsp_password=\"${frigate_config.rtsp.family_room.password}\" office_rtsp_password=\"${frigate_config.rtsp.office.password}\"'", playbook: 'install.yaml'
ansiblePlaybook credentialsId: 'rivendell-ssh-key', disableHostKeyChecking: true, extras: "--extra-vars 'ipgeolocation_api_key=\"${frigate_config.ipgeolocation.api_key}\" wyze_email=\"${frigate_config.wyze.email}\" wyze_password=\"${frigate_config.wyze.password}\" garage_rtsp_password=\"${frigate_config.rtsp.garage.password}\" front_door_rtsp_password=\"${frigate_config.rtsp.front_door.password}\" doorbell_rtsp_password=\"${frigate_config.rtsp.doorbell.password}\" driveway_rtsp_password=\"${frigate_config.rtsp.driveway.password}\" back_door_rtsp_password=\"${frigate_config.rtsp.back_door.password}\" family_room_rtsp_password=\"${frigate_config.rtsp.family_room.password}\"'", playbook: 'install.yaml'
ansiblePlaybook credentialsId: 'rivendell-ssh-key', disableHostKeyChecking: true, playbook: 'stop.yaml'
ansiblePlaybook credentialsId: 'rivendell-ssh-key', disableHostKeyChecking: true, playbook: 'start.yaml'
}
@@ -22,14 +22,6 @@ pipeline {
}
post {
failure {
httpRequest contentType: 'APPLICATION_JSON', httpMode: 'POST', ignoreSslErrors: true, requestBody: "{\"topic\": \"jenkins\", \"title\": \"Jenkins\", \"priority\": 4, \"icon\": \"https://jenkins.homelab.net/favicon.ico\", \"click\": \"${BUILD_URL}\", \"message\": \"Build failed for ${JOB_NAME.split('/')[-2]} on ${BRANCH_NAME} branch\"}", responseHandle: 'NONE', url: 'https://ntfy.homelab.net', wrapAsMultipart: false
}
fixed {
httpRequest contentType: 'APPLICATION_JSON', httpMode: 'POST', ignoreSslErrors: true, requestBody: "{\"topic\": \"jenkins\", \"title\": \"Jenkins\", \"priority\": 3, \"icon\": \"https://jenkins.homelab.net/favicon.ico\", \"click\": \"${BUILD_URL}\", \"message\": \"Pipeline fixed for ${JOB_NAME.split('/')[-2]} on ${BRANCH_NAME} branch\"}", responseHandle: 'NONE', url: 'https://ntfy.homelab.net', wrapAsMultipart: false
}
cleanup {
cleanWs()
}
+57 -146
View File
@@ -2,53 +2,22 @@ mqtt:
host: mqtt
detectors:
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.105:554/live'
doorbell:
- '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.101:554/live/ch0'
driveway:
- '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.102:554/stream1'
office:
- 'rtsp://{FRIGATE_OFFICE_RTSP_USERNAME}:{FRIGATE_OFFICE_RTSP_PASSWORD}@192.168.0.105:554/live/ch0'
cpu1:
type: cpu
num_threads: 2
cpu2:
type: cpu
num_threads: 2
cameras:
garage:
enabled: true
ffmpeg:
inputs:
- path: 'rtsp://127.0.0.1:8554/garage'
roles:
- detect
- record
- path: 'rtsp://{FRIGATE_GARAGE_RTSP_USERNAME}:{FRIGATE_GARAGE_RTSP_PASSWORD}@192.168.0.102:554/live'
roles:
- detect
- record
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
@@ -58,15 +27,15 @@ cameras:
height: 1080
motion:
mask:
- 1384,1058,1384,1009,1872,1009,1872,1058 # Timestamp
- 1384,1058,1384,1009,1872,1009,1872,1058 # Timestamp
doorbell:
enabled: true
ffmpeg:
inputs:
- path: 'rtsp://127.0.0.1:8554/doorbell'
roles:
- detect
- record
- path: 'rtsp://{FRIGATE_DOORBELL_RTSP_USERNAME}:{FRIGATE_DOORBELL_RTSP_PASSWORD}@192.168.0.105:554/cam/realmonitor?channel=1&subtype=0'
roles:
- detect
- record
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
@@ -74,13 +43,13 @@ cameras:
enabled: true
width: 1920
height: 1080
review:
alerts:
record:
events:
required_zones:
- front_door_zone
- front_door_zone
snapshots:
required_zones:
- front_door_zone
- front_door_zone
zones:
front_door_zone:
coordinates: 964,677,1920,1080,0,1080,539,754 # Near front door
@@ -88,50 +57,50 @@ cameras:
enabled: true
ffmpeg:
inputs:
- path: 'rtsp://127.0.0.1:8554/front_door'
roles:
- detect
- record
- path: 'rtsp://{FRIGATE_FRONT_DOOR_RTSP_USERNAME}:{FRIGATE_FRONT_DOOR_RTSP_PASSWORD}@192.168.0.108:554/live/ch0'
roles:
- detect
- record
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
detect:
enabled: false
enabled: true
width: 1920
height: 1080
motion:
mask:
- 361,96,565,0,0,0,0,304 # Sidewalk
- 1445,0,1444,46,1920,46,1920,0 # Timestamp
- 361,96,565,0,0,0,0,304 # Sidewalk
- 1445,0,1444,46,1920,46,1920,0 # Timestamp
objects:
filters:
person:
mask:
- 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
- 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: true
enabled: false
ffmpeg:
inputs:
- path: 'rtsp://127.0.0.1:8554/driveway'
roles:
- detect
- record
- path: 'rtsp://{FRIGATE_DRIVEWAY_RTSP_USERNAME}:{FRIGATE_DRIVEWAY_RTSP_PASSWORD}@192.168.0.148:5543/live/channel1'
roles:
- detect
- record
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
detect:
enabled: false
enabled: true
width: 640
height: 360
back_door:
enabled: true
ffmpeg:
inputs:
- path: 'rtsp://127.0.0.1:8554/back_door'
roles:
- detect
- record
- path: 'rtsp://wyze-bridge:8554/back-yard-cam'
roles:
- detect
- record
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
@@ -141,45 +110,15 @@ cameras:
height: 1080
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
- 1877,1080,1378,1080,1378,1008,1877,1008 # Timestamp
family_room:
enabled: false
ffmpeg:
inputs:
- path: 'rtsp://127.0.0.1:8554/family_room'
roles:
- detect
- record
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:
inputs:
- path: 'rtsp://127.0.0.1:8554/office'
roles:
- detect
- record
- path: 'rtsp://{FRIGATE_FAMILY_ROOM_RTSP_USERNAME}:{FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}@192.168.0.104:554/live/ch0'
roles:
- detect
- record
output_args:
record: preset-record-generic-audio-aac # Record with aac audio
detect:
@@ -187,66 +126,38 @@ 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-restream
objects:
track:
- person
review:
alerts:
labels:
- person
input_args: preset-rtsp-generic
detect:
enabled: true
fps: 5
max_disappeared: 25 # Number of frames without a detection before Frigate considers an object to be gone
motion:
record:
enabled: true
expire_interval: 60
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)
alerts:
events:
pre_capture: 5 # Number of seconds before the event to include
post_capture: 5 # Number of seconds after the event to include
objects:
- person
retain:
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
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)
snapshots:
enabled: true
birdseye:
rtmp:
enabled: false
mode: continuous
auth:
enabled: false
motion:
birdseye:
enabled: true
mode: continuous
+62 -107
View File
@@ -3,13 +3,13 @@
services:
frigate:
container_name: frigate
image: ghcr.io/blakeblackshear/frigate:0.15.0
image: ghcr.io/blakeblackshear/frigate:0.12.0
labels:
autoheal: 'true'
restart: unless-stopped
depends_on:
- mqtt
- wyze-bridge
- mqtt
- wyze-bridge
healthcheck:
test: ls /media/frigate && curl -s -f http://localhost:5000 -o /dev/null
interval: 60s
@@ -29,72 +29,64 @@ services:
FRIGATE_BACK_DOOR_RTSP_PASSWORD: ${FRIGATE_BACK_DOOR_RTSP_PASSWORD}
FRIGATE_FAMILY_ROOM_RTSP_USERNAME: frigate
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: '1000mb'
shm_size: '150mb'
devices:
- /dev/dri:/dev/dri
- /dev/dri:/dev/dri
volumes:
- type: volume
source: config
target: /config
- type: volume
source: media
target: /media/frigate
- type: tmpfs
target: /tmp/cache
tmpfs:
size: 1000000000
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
- type: volume
source: config
target: /config
- type: volume
source: media
target: /media/frigate
- type: tmpfs
target: /tmp/cache
tmpfs:
size: 1000000000
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
networks:
- frigate
- frigate
ports:
- 127.0.0.1:10000:5000
- 554:8554
- 127.0.0.1:10000:5000
wyze-bridge:
container_name: frigate-wyze-bridge
image: mrlt8/wyze-bridge:2.10.3
image: mrlt8/wyze-bridge:2.4.0
restart: unless-stopped
environment:
NET_MODE: LAN
FILTER_NAMES: Back Yard Cam
WB_AUTH: 'false'
WYZE_EMAIL: ${WYZE_EMAIL}
WYZE_PASSWORD: ${WYZE_PASSWORD}
API_ID: ${WYZE_API_ID}
API_KEY: ${WYZE_API_KEY}
ENABLE_AUDIO: 'true'
volumes:
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
networks:
- wyze-bridge
- frigate
notifier:
container_name: frigate-notifier
image: frigate-notifier:latest
- frigate
notify:
container_name: frigate-notify
image: frigate-notify:latest
restart: unless-stopped
depends_on:
- frigate
- mqtt
- frigate
- mqtt
environment:
REQUESTS_CA_BUNDLE: /etc/ssl/certs/ca-certificates.crt
volumes:
- 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
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
read_only: true
networks:
- frigate
- frigate
webcontrol:
container_name: frigate-webcontrol
image: frigate-webcontrol:latest
@@ -102,10 +94,8 @@ services:
autoheal: 'true'
restart: unless-stopped
depends_on:
frigate:
condition: service_healthy
mqtt:
condition: service_started
- frigate
- mqtt
healthcheck:
test: curl -s -f http://localhost -o /dev/null
interval: 60s
@@ -114,55 +104,34 @@ services:
timeout: 30s
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
read_only: true
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
networks:
- frigate
- frigate
ports:
- 127.0.0.1:10001:80
uptime:
container_name: frigate-uptime
image: frigate-uptime:latest
restart: unless-stopped
depends_on:
frigate:
condition: service_healthy
volumes:
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
networks:
- frigate
- 127.0.0.1:10001:80
mqtt:
container_name: frigate-mqtt
container_name: mqtt
image: eclipse-mosquitto:2.0.18
command:
- mosquitto
- -c
- /mosquitto-no-auth.conf
- mosquitto
- -c
- /mosquitto-no-auth.conf
restart: unless-stopped
volumes:
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
- type: bind
source: /etc/localtime
target: /etc/localtime
read_only: true
networks:
- frigate
- frigate
networks:
frigate:
name: frigate
volumes:
config:
@@ -171,17 +140,3 @@ 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
+7 -40
View File
@@ -7,10 +7,6 @@
prompt: Enter email for Wyze account
- name: wyze_password
prompt: Enter password for Wyze account
- name: wyze_api_id
prompt: Enter API ID for Wyze account
- name: wyze_api_key
prompt: Enter API key for Wyze account
- name: garage_rtsp_password
prompt: Enter password for garage camera RTSP stream user motion
- name: front_door_rtsp_password
@@ -23,8 +19,6 @@
prompt: Enter password for back door camera RTSP stream user motion
- name: family_room_rtsp_password
prompt: Enter password for family room camera RTSP stream user frigate
- name: office_rtsp_password
prompt: Enter password for office camera RTSP stream user frigate
tasks:
- name: Create Frigate config Docker volume directory
become: true
@@ -69,25 +63,25 @@
dest: /data/frigate-config/config.yaml
mode: preserve
- name: Create temporary Docker build directory for frigate-notifier
- name: Create temporary Docker build directory for frigate-notify
ansible.builtin.tempfile:
state: directory
register: docker_build_dir
- name: Copy Docker build directory
ansible.builtin.copy:
src: notifier/
src: notify/
dest: '{{docker_build_dir.path}}'
mode: preserve
- name: Build frigate-notifier Docker image
community.docker.docker_image:
- name: Build frigate-notify Docker image
ansible.builtin.docker_image:
build:
path: '{{docker_build_dir.path}}'
name: frigate-notifier
name: frigate-notify
tag: latest
source: build
force_source: true
state: present
- name: Remove temporary Docker build directory for frigate-notifier
- name: Remove temporary Docker build directory for frigate-notify
ansible.builtin.file:
path: '{{docker_build_dir.path}}'
state: absent
@@ -102,7 +96,7 @@
dest: '{{docker_build_dir.path}}'
mode: preserve
- name: Build frigate-webcontrol Docker image
community.docker.docker_image:
ansible.builtin.docker_image:
build:
path: '{{docker_build_dir.path}}'
name: frigate-webcontrol
@@ -115,29 +109,6 @@
path: '{{docker_build_dir.path}}'
state: absent
- name: Create temporary Docker build directory for frigate-uptime
ansible.builtin.tempfile:
state: directory
register: docker_build_dir
- name: Copy Docker build directory
ansible.builtin.copy:
src: uptime-go/
dest: '{{docker_build_dir.path}}'
mode: preserve
- name: Build frigate-uptime Docker image
community.docker.docker_image:
build:
path: '{{docker_build_dir.path}}'
name: frigate-uptime
tag: latest
source: build
force_source: true
state: present
- name: Remove temporary Docker build directory for frigate-uptime
ansible.builtin.file:
path: '{{docker_build_dir.path}}'
state: absent
- name: Read homelab config
ansible.builtin.slurp:
src: '{{ansible_user_dir}}/.homelab.json'
@@ -154,8 +125,6 @@
wyze:
email: '{{wyze_email}}'
password: '{{wyze_password}}'
api_id: '{{wyze_api_id}}'
api_key: '{{wyze_api_key}}'
rtsp:
garage:
password: '{{garage_rtsp_password}}'
@@ -169,8 +138,6 @@
password: '{{back_door_rtsp_password}}'
family_room:
password: '{{family_room_rtsp_password}}'
office:
password: '{{office_rtsp_password}}'
community.postgresql.postgresql_query:
login_host: '{{homelab_config.database.host}}'
login_user: '{{homelab_config.database.user}}'
-23
View File
@@ -1,23 +0,0 @@
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
@@ -1,35 +0,0 @@
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
@@ -1,55 +0,0 @@
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
@@ -1,32 +0,0 @@
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.
@@ -1,50 +0,0 @@
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
@@ -1,79 +0,0 @@
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
@@ -1,12 +0,0 @@
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)
+3 -2
View File
@@ -1,7 +1,8 @@
FROM python:3.12
FROM python:3.11
WORKDIR /code
ENTRYPOINT ["python", "-m", "notifier"]
COPY docker_entrypoint.sh /
ENTRYPOINT ["/docker_entrypoint.sh"]
COPY requirements.txt .
RUN pip3 install -r requirements.txt
+6
View File
@@ -0,0 +1,6 @@
#!/bin/bash
set -e
update-ca-certificates
python3 frigate_event_notifier.py "$@"
@@ -1,3 +1,2 @@
requests==2.30.0
paho-mqtt==1.6.1
PyYAML==6.0.1
+119
View File
@@ -0,0 +1,119 @@
import os
import json
from time import sleep
from datetime import datetime, timedelta
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['record']['events']['required_zones']} for camera_name, camera_config in frigate_config['cameras'].items()}
self.quiet_period = quiet_period
self.last_notification_time = {}
def send_notification(self, event_id, camera, object_label, score, priority=3):
now = datetime.now()
if now - self.last_notification_time.get(camera, datetime.min) >= timedelta(seconds=self.quiet_period):
# Quiet period has passed since the last notification for this camera
self.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}/detect',
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps({
'value': 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}/detect',
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps({
'value': 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()
+1 -16
View File
@@ -38,16 +38,13 @@
IPGEOLOCATION_API_KEY: '{{frigate_config.ipgeolocation.api_key}}'
WYZE_EMAIL: '{{frigate_config.wyze.email}}'
WYZE_PASSWORD: '{{frigate_config.wyze.password}}'
WYZE_API_ID: '{{frigate_config.wyze.api_id}}'
WYZE_API_KEY: '{{frigate_config.wyze.api_key}}'
FRIGATE_GARAGE_RTSP_PASSWORD: '{{frigate_config.rtsp.garage.password}}'
FRIGATE_FRONT_DOOR_RTSP_PASSWORD: '{{frigate_config.rtsp.front_door.password}}'
FRIGATE_DOORBELL_RTSP_PASSWORD: '{{frigate_config.rtsp.doorbell.password}}'
FRIGATE_DRIVEWAY_RTSP_PASSWORD: '{{frigate_config.rtsp.driveway.password}}'
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_v2:
community.docker.docker_compose:
project_name: frigate
project_src: '{{docker_compose_dir.path}}'
state: present
@@ -56,15 +53,3 @@
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_v2:
community.docker.docker_compose:
project_name: frigate
project_src: '{{docker_compose_dir.path}}'
state: absent
-12
View File
@@ -1,12 +0,0 @@
#FROM golang:1.23
FROM golang:1.23
WORKDIR /code
ENTRYPOINT ["./uptime"]
ENV GOEXPERIMENT=loopvar
RUN apt update --fix-missing
RUN apt install -y iputils-ping ffmpeg
COPY uptime .
RUN go build .
-26
View File
@@ -1,26 +0,0 @@
package config
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"`
NotificationRepeatThreshold int `yaml:"notification_repeat_threshold"`
}
func ReadConfig(configFilename string) Config {
var data, readErr = os.ReadFile(configFilename)
if readErr != nil {
panic(readErr)
}
var config Config
if yamlErr := yaml.Unmarshal(data, &config); yamlErr != nil {
panic(yamlErr)
}
return config
}
-9
View File
@@ -1,9 +0,0 @@
cameras:
back_door: 'rtsp://frigate:8554/back_door'
doorbell: 'rtsp://frigate:8554/doorbell'
#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
-5
View File
@@ -1,5 +0,0 @@
module frigate/uptime
go 1.21.12
require gopkg.in/yaml.v3 v3.0.1 // indirect
-3
View File
@@ -1,3 +0,0 @@
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-17
View File
@@ -1,17 +0,0 @@
package main
import "time"
import (
"frigate/uptime/config"
"frigate/uptime/notify"
)
func main() {
var uptimeConfig = config.ReadConfig("config/config.yaml")
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, uptimeConfig.NotificationRepeatThreshold, notify.NewNtfyNotifier())
cameraMonitor.Run(uptimeConfig.Cameras)
}
-108
View File
@@ -1,108 +0,0 @@
package main
import (
"fmt"
"log/slog"
"strings"
"time"
)
import (
"frigate/uptime/notify"
"frigate/uptime/ping"
)
type CameraMonitor struct {
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, notificationRepeatThreshold int, notifier notify.Notifier) CameraMonitor {
return CameraMonitor{
pingInterval: pingInterval,
pingTimeout: pingTimeout,
consecutiveDownThreshold: consecutiveDownThreshold,
notificationRepeatThreshold: notificationRepeatThreshold,
downtime: make(map[string]int),
Notifier: notifier,
}
}
func (c CameraMonitor) onCameraPingResult(camera string, online bool) {
if online {
if c.downtime[camera] >= c.consecutiveDownThreshold {
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.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)
}
}
}
func (c CameraMonitor) Run(cameras map[string]string) {
type pingResult struct {
camera string
online bool
}
var pingResultChannel = make(chan pingResult, 4)
for {
var unknownPingResultCameras = make(map[string]bool, len(cameras))
var startTime = time.Now()
var timeoutChannel = time.After(c.pingTimeout)
// Start all pings
for camera, host := range cameras {
go func() {
pingResultChannel <- pingResult{
camera: camera,
online: ping.VideoPing(host),
}
}()
unknownPingResultCameras[camera] = true
}
timeout:
// Await ping results or timeout
for range cameras {
select {
case cameraPingResult := <-pingResultChannel:
slog.Debug(cameraPingResult.camera, "online", cameraPingResult.online)
c.onCameraPingResult(cameraPingResult.camera, cameraPingResult.online)
delete(unknownPingResultCameras, cameraPingResult.camera) // Maintain set of cameras with unknown ping status
case <-timeoutChannel:
var b strings.Builder
for camera := range unknownPingResultCameras {
if b.Len() > 0 {
b.WriteString(", ")
}
b.WriteString(camera)
}
slog.Warn("Timed out waiting for ping result", "cameras", b.String())
break timeout
}
}
// Handle timed out camera pings
for camera := range unknownPingResultCameras {
c.onCameraPingResult(camera, false)
}
var sleepDuration = c.pingInterval - time.Since(startTime)
slog.Debug("Sleeping", "seconds", sleepDuration)
time.Sleep(sleepDuration)
}
}
-27
View File
@@ -1,27 +0,0 @@
package notify
import (
"fmt"
"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!",
false: "%s camera is offline!",
}
var cameraTitle string
for i, s := range strings.Split(camera, "_") {
if i > 0 {
cameraTitle += " "
}
cameraTitle += strings.ToUpper(string(s[0])) + s[1:]
}
return fmt.Sprintf(msgTemplates[online], cameraTitle)
}
-64
View File
@@ -1,64 +0,0 @@
package notify
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"log/slog"
"net/http"
)
type NtfyNotifier struct {
client *http.Client
}
func NewNtfyNotifier() NtfyNotifier {
return NtfyNotifier{
client: &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
},
}
}
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"`
}
var reqJson, jsonErr = json.Marshal(ntfyJson{
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",
})
if jsonErr != nil {
slog.Error("Failed to construct JSON request body", "error", jsonErr)
return
}
var req, reqErr = http.NewRequest("POST", "https://ntfy.homelab.net", bytes.NewBuffer([]byte(reqJson)))
if reqErr != nil {
slog.Error("Failed to create HTTP request", "error", reqErr)
return
}
req.Header.Set("Content-Type", "application/json")
var resp, respErr = n.client.Do(req)
if respErr != nil {
slog.Error("Failed to send HTTP request", "error", respErr)
return
}
if resp.StatusCode != 200 {
slog.Error("Ntfy notification returned HTTP", "status", resp.Status)
}
}
-9
View File
@@ -1,9 +0,0 @@
package ping
import "os/exec"
func IPPing(host string) bool {
var cmd = exec.Command("ping", "-w", "3", "-c", "1", host)
var err = cmd.Run()
return err == nil
}
-1
View File
@@ -1 +0,0 @@
package ping
-9
View File
@@ -1,9 +0,0 @@
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()
return err == nil
}
-12
View File
@@ -1,12 +0,0 @@
FROM python:3.11
WORKDIR /code
ENTRYPOINT ["python", "-m", "uptime"]
RUN apt update --fix-missing
RUN apt install -y iputils-ping libgl1
COPY requirements.txt .
RUN pip3 install -r requirements.txt
COPY src .
-3
View File
@@ -1,3 +0,0 @@
aiohttp>=3.8.6
PyYAML>=6.0.1
opencv-python>=4.10.0.84
-23
View File
@@ -1,23 +0,0 @@
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.
-25
View File
@@ -1,25 +0,0 @@
import asyncio
import logging
import logging.config
from uptime.utils.logging import configure_logging
from uptime.monitor import CameraMonitor
configure_logging()
logger = logging.getLogger(__name__)
async def main() -> None:
camera_monitor = CameraMonitor()
await camera_monitor.run()
def entrypoint() -> None:
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info("Received Ctrl+C, exiting...")
if __name__ == "__main__":
entrypoint()
-65
View File
@@ -1,65 +0,0 @@
import re
import json
import logging
from contextlib import AsyncExitStack
from typing import ClassVar, Pattern
import aiohttp
logger = logging.getLogger(__name__)
class FrigateConfig:
_LOCALHOST_REGEX: ClassVar[Pattern[str]] = re.compile("127\\.0\\.0\\.1|localhost")
_URL_ADDRESS_REGEX: ClassVar[Pattern[str]] = re.compile("(^|(?<=://)|(?<=@))[a-z0-9.\\-]+(:[0-9]+)?($|(?=/))")
_WYZE_CAMERAS: ClassVar[dict[str, str]] = {"back_yard_cam": "192.168.0.202:554"}
def __init__(self, frigate_base_url: str = "http://frigate:5000") -> None:
self._frigate_config_url = f"{frigate_base_url}/api/config"
self._config = {}
async def refresh(self) -> None:
logger.debug("Fetching Frigate configuration")
try:
async with AsyncExitStack() as exit_stack:
aiohttp_session = await exit_stack.enter_async_context(aiohttp.ClientSession(raise_for_status=True))
response = await exit_stack.enter_async_context(aiohttp_session.get(self._frigate_config_url))
self._config = json.loads(await response.read())
except Exception as e:
if self._config:
logger.error("Failed to fetch Frigate config, falling back to previous value", exc_info=e)
else:
raise
logger.debug("Fetched Frigate configuration")
@property
def active_cameras(self) -> list[str]:
if "cameras" not in self._config:
raise ValueError("Configuration not yet fetched from Frigate")
return [camera for camera in self._config["cameras"] if self._config["cameras"][camera].get("enabled", True)]
@property
def active_camera_urls(self) -> dict[str, str]:
return {camera: self._replace_localhost(self._config["cameras"][camera]["ffmpeg"]["inputs"][0]["path"]) for camera in self.active_cameras}
@property
def active_camera_addresses(self) -> dict[str, str]:
active_cameras = self.active_cameras
return {camera: self._get_address_from_url(url) for camera, url in self.active_camera_urls.items()}
@classmethod
def _replace_localhost(cls, url: str) -> str:
return cls._LOCALHOST_REGEX.sub("frigate", url, 1)
@classmethod
def _get_address_from_url(cls, url: str) -> str:
match = cls._URL_ADDRESS_REGEX.search(url.lower())
if match is None:
raise ValueError(f"Failed to retrieve address from {url=}")
# Handle case of wyze-bridge and hardcode cameras
if match.group().startswith("wyze-bridge"):
wyze_camera = url.lower().rsplit("/", 1)[-1].replace("-", "_")
return cls._WYZE_CAMERAS[wyze_camera]
return match.group()
-82
View File
@@ -1,82 +0,0 @@
import time
import asyncio
import logging
import datetime as dt
from contextlib import AsyncExitStack
from types import TracebackType
from typing import ClassVar, Self
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from uptime.frigate_config import FrigateConfig
from uptime.notify import NtfyNotifier
from uptime.ping import video_ping
logger = logging.getLogger(__name__)
class CameraMonitor:
_FRIGATE_CONFIG_REFRESH_INTERVAL: ClassVar[dt.timedelta] = dt.timedelta(minutes=60)
def __init__(self, ping_interval: dt.timedelta = dt.timedelta(seconds=60), consecutive_down_threshold: int = 3):
self._ping_interval = ping_interval
self._consecutive_down_threshold = consecutive_down_threshold
self._camera_downtime = Counter()
self._frigate_config = FrigateConfig()
self._ntfy_notifier = NtfyNotifier()
self._process_pool = ProcessPoolExecutor()
async def _on_camera_up(self, camera: str) -> None:
logger.info(f"Camera {camera} is back online")
await self._ntfy_notifier.send_notification(camera, True)
async def _on_camera_down(self, camera: str) -> None:
await self._frigate_config.refresh()
if camera not in self._frigate_config.active_cameras:
return
logger.info(f"Camera {camera} is down")
await self._ntfy_notifier.send_notification(camera, False)
async def _on_camera_ping(self, camera: str, success: bool) -> None:
if success:
if self._camera_downtime[camera] >= self._consecutive_down_threshold:
await self._on_camera_up(camera)
self._camera_downtime[camera] = 0
else:
if self._camera_downtime[camera] == self._consecutive_down_threshold:
await self._on_camera_down(camera)
self._camera_downtime[camera] += 1
async def _ping_all_cameras(self) -> None:
async def video_ping_async(url: str) -> bool:
event_loop = asyncio.get_running_loop()
return await event_loop.run_in_executor(
self._process_pool,
video_ping,
url,
)
ping_tasks = {}
async with asyncio.TaskGroup() as tg:
event_loop = asyncio.get_running_loop()
for camera, url in self._frigate_config.active_camera_urls.items():
ping_tasks[camera] = tg.create_task(video_ping_async(url))
for camera, task in ping_tasks.items():
await self._on_camera_ping(camera, task.result())
async def run(self) -> None:
await self._frigate_config.refresh()
last_refresh = time.time()
while True:
start_time = time.time()
if time.time() - last_refresh >= self._FRIGATE_CONFIG_REFRESH_INTERVAL.total_seconds():
logger.info("Refreshing Frigate config...")
await self._frigate_config.refresh()
last_refresh = time.time()
await self._ping_all_cameras()
sleep_duration = self._ping_interval.total_seconds() - (time.time() - start_time)
logger.debug(f"Sleeping for {sleep_duration} seconds...")
await asyncio.sleep(sleep_duration)
-24
View File
@@ -1,24 +0,0 @@
import logging
import aiohttp
logger = logging.getLogger(__name__)
class NtfyNotifier:
def __init__(self, ntfy_url: str = "https://ntfy.homelab.net") -> None:
self._ntfy_url = ntfy_url
async def send_notification(self, camera: str, status: bool) -> None:
async with aiohttp.ClientSession(raise_for_status=True) as aiohttp_session:
logger.debug(f"Sending notification for {camera=}...")
message = f"{camera} is back online" if status else f"{camera} is offline"
await aiohttp_session.post(self._ntfy_url, ssl=False, json={
"topic": "frigate_camera_uptime",
"title": "Frigate",
"message": message,
"priority": 3,
"click": f"https://frigate.homelab.net/cameras/{camera}",
"icon": "https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/frigate.png",
})
logger.debug(f"Sent notification for {camera=}")
-24
View File
@@ -1,24 +0,0 @@
import asyncio
import logging
import cv2
logger = logging.getLogger(__name__)
async def ip_ping(host: str) -> bool:
logger.debug(f"Pinging {host}")
process = await asyncio.create_subprocess_exec("ping", "-w", "3", "-c", "1", host, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL)
return_code = await process.wait()
logger.debug(f"Finished pinging {host}")
return return_code == 0
async def tcp_ping(host: str, port: int) -> bool:
...
def video_ping(url: str) -> bool:
capture = cv2.VideoCapture(url)
success, _ = capture.read()
capture.release()
return success
View File
Whitespace-only changes.
-12
View File
@@ -1,12 +0,0 @@
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 -2
View File
@@ -1,8 +1,7 @@
FROM python:3.11
WORKDIR /code
ENTRYPOINT ["uvicorn", "webcontrol:api", "--host", "0.0.0.0", "--port", "80"]
CMD ["--root-path", "/webcontrol", "--log-level", "warning"]
ENTRYPOINT ["python3", "server.py"]
RUN pip3 install --upgrade pip
+2 -6
View File
@@ -1,7 +1,3 @@
PyYAML==6.0.1
pydantic==2.6.4
fastapi==0.110.0
uvicorn[standard]==0.29.0
aiohttp==3.8.6
flask==2.3.2
paho-mqtt==1.6.1
requests==2.30.0
requests==2.31.0
-23
View File
@@ -1,23 +0,0 @@
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
+86
View File
@@ -0,0 +1,86 @@
import os
import sys
import json
from time import sleep
from threading import Thread
from datetime import datetime, time, timedelta
import requests
from flask import Blueprint, request, jsonify
import paho.mqtt.publish as mqtt_publish
blueprint = Blueprint('detection', __name__)
def get_sunset() -> datetime:
sunset_date = datetime.now().date()
try:
IPGEOLOCATION_API_KEY = os.environ['IPGEOLOCATION_API_KEY']
ipgeolocation_api_response = requests.get(f'https://api.ipgeolocation.io/astronomy?apiKey={IPGEOLOCATION_API_KEY}&location=Winter+Haven,+FL')
ipgeolocation_api_response.raise_for_status()
astronomical_json = json.loads(ipgeolocation_api_response.content)
sunset_time = datetime.strptime(astronomical_json['sunset'], '%H:%M').time()
except Exception as e:
print(e, file=sys.stderr)
sunset_time = time(20, 00, 00)
finally:
if sunset_time < datetime.now().time():
# Sunset has already passed today
sunset_date += timedelta(days=1)
return datetime.combine(sunset_date, sunset_time)
def reset_all_camera_detection_at_sunset():
while True:
try:
sunset = get_sunset()
print(f'Waiting until {sunset} to reset detection for all cameras...', file=sys.stderr)
seconds_until_sunset = (sunset - datetime.now()).total_seconds()
sleep(seconds_until_sunset)
# Get all camera names
frigate_api_response = requests.get('http://frigate:5000/api/config')
frigate_api_response.raise_for_status()
all_camera_names = json.loads(frigate_api_response.content)['cameras'].keys()
for camera_name in all_camera_names:
set_camera_detection(camera_name, True)
except Exception as e:
print(e, file=sys.stderr)
def set_camera_detection(camera: str, value: bool, delay: int = 0) -> None:
sleep(delay)
mqtt_auth = {'username': os.environ.get('MQTT_USERNAME'), 'password': os.environ.get('MQTT_PASSWORD')}
if not all(mqtt_auth.values()):
mqtt_auth = None
mqtt_publish.single(f'frigate/{camera}/detect/set', 'ON' if value else 'OFF', hostname='mqtt', port=1883, auth=mqtt_auth)
@blueprint.route('/camera/<string:camera>/detect', methods=['POST'])
def camera_detect_POST(camera):
if not request.json:
return jsonify({
'status': 'failure',
'description': 'Request body needs to be in JSON format'
}), 400
value = request.json.get('value', True)
set_camera_detection(camera, value)
duration = request.json.get('duration', 0)
if duration > 0:
# Start sleeping thread to revert value after duration
thread = Thread(target=set_camera_detection, args=(camera, not value, duration * 60))
thread.start()
return jsonify({
'status': 'success'
}), 200
sunset_reset_thread = Thread(target=reset_all_camera_detection_at_sunset, args=())
sunset_reset_thread.start()
+20
View File
@@ -0,0 +1,20 @@
from flask import Flask, jsonify
import detection
app = Flask(__name__)
app.register_blueprint(detection.blueprint)
@app.route('/', methods=['GET'])
def home_GET():
return jsonify({
'status': 'success',
'name': 'webcontrol',
'description': 'This is a custom webcontrol API for Frigate that allows minimal control over the NVR system through an HTTP API'
}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=False)
-4
View File
@@ -1,4 +0,0 @@
from webcontrol.api import api
from webcontrol.utils.logging import configure_logging
configure_logging()
-18
View File
@@ -1,18 +0,0 @@
import logging
from fastapi import FastAPI
from webcontrol.api.detection import api as detection_api
logger = logging.getLogger(__name__)
api = FastAPI()
api.include_router(detection_api)
@api.get("/")
async def get_root() -> dict[str, str]:
return {
"message": "This is a Frigate webcontrol API"
}
@@ -1,36 +0,0 @@
import datetime as dt
import logging
from fastapi import APIRouter
from pydantic import BaseModel
from webcontrol.detection import set_camera_detection, reset_all_cameras_detection_after_sunset
from webcontrol.utils.asyncio import create_task, schedule_coroutine
logger = logging.getLogger(__name__)
api = APIRouter()
@api.on_event("startup")
def schedule_reset_all_cameras_detection_after_sunset() -> None:
create_task(reset_all_cameras_detection_after_sunset())
class TemporaryDetectionSettings(BaseModel):
detection: bool = True
duration: int = 0
@api.post("/camera/{camera}/detection")
async def post_camera_detection(camera: str, temporary_detection_settings: TemporaryDetectionSettings) -> dict[str, str]:
await set_camera_detection(camera, temporary_detection_settings.detection)
if temporary_detection_settings.duration > 0:
schedule_coroutine(
set_camera_detection(camera, not temporary_detection_settings.detection),
dt.timedelta(minutes=temporary_detection_settings.duration)
)
return {
"status": "success"
}
-47
View File
@@ -1,47 +0,0 @@
import asyncio
import datetime as dt
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
logger = logging.getLogger(__name__)
async def set_camera_detection(camera: str, detection: bool) -> None:
mqtt_auth = {"username": os.environ.get("MQTT_USERNAME"), "password": os.environ.get("MQTT_PASSWORD")}
if not all(mqtt_auth.values()):
mqtt_auth = None
logger.debug(f"Setting {camera} camera {detection=}")
mqtt_publish.single(f"frigate/{camera}/detect/set", "ON" if detection else "OFF", hostname="mqtt", port=1883, auth=mqtt_auth)
logger.info(f"Set {camera} camera {detection=}")
async def reset_all_cameras_detection_after_sunset() -> None:
frigate_config_file = FrigateConfigFile()
async for nighttime in get_nighttimes("Winter Haven, FL"):
logger.info(f"Waiting until {nighttime} to reset detection for all cameras")
await asyncio.sleep((nighttime - dt.datetime.now()).total_seconds())
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
@@ -1,46 +0,0 @@
import logging
import os
import yaml
logger = logging.getLogger(__name__)
class FrigateConfigFile:
def __init__(self, filepath: str = os.environ["FRIGATE_CONFIG_FILE"]) -> None:
self._filepath = filepath
self._config = {}
async def reload(self) -> None:
logger.debug("Loading Frigate configuration file")
try:
with open(self._filepath, "r") as frigate_config_yaml:
self._config = yaml.safe_load(frigate_config_yaml)
except Exception as e:
if self._config:
logger.error("Failed to load Frigate config file, falling back to previous value", exc_info=e)
else:
raise
logger.debug("Loaded Frigate configuration file")
@property
def active_cameras(self) -> list[str]:
if not self._config:
raise ValueError("Configuration file not yet loaded from Frigate")
return [
camera
for camera in self._config["cameras"]
if self._config["cameras"][camera].get("enabled", True)
]
@property
def detection_enabled_cameras(self) -> list[str]:
if not self._config:
raise ValueError("Configuration file not yet loaded from Frigate")
return [
camera
for camera in self._config["cameras"]
if self._config["cameras"][camera].get("detect", {}).get("enabled", True)
]
-39
View File
@@ -1,39 +0,0 @@
import datetime as dt
import json
import logging
import os
import urllib.parse
from collections.abc import AsyncGenerator
import aiohttp
logger = logging.getLogger(__name__)
SUNSET_FALLBACK = dt.time(19, 0, 0)
DARKNESS_DELAY = dt.timedelta(minutes=30)
async def get_nighttimes(location: str) -> AsyncGenerator[dt.datetime, None]:
async with aiohttp.ClientSession(raise_for_status=True) as aiohttp_session:
date = dt.date.today()
sunset_time = SUNSET_FALLBACK
while True:
try:
ipgeolocation_api_url = "https://api.ipgeolocation.io/astronomy?apiKey={api_key}&location={location}&date={date}".format(
api_key=urllib.parse.quote(os.environ["IPGEOLOCATION_API_KEY"]),
location=urllib.parse.quote(location),
date=urllib.parse.quote(date.strftime("%Y-%m-%d"))
)
async with aiohttp_session.get(ipgeolocation_api_url) as response:
response_json = json.loads(await response.read())
sunset_time = dt.datetime.strptime(response_json["sunset"], "%H:%M").time()
except Exception as e:
logger.error(f"Failed to query sunset time, falling back to {sunset_time}", exc_info=e)
nighttime = dt.datetime.combine(date, sunset_time) + DARKNESS_DELAY
date += dt.timedelta(days=1)
if nighttime < dt.datetime.now():
continue
yield nighttime
Whitespace-only changes.
@@ -1,18 +0,0 @@
import asyncio
import datetime as dt
from collections.abc import Awaitable
tasks = set()
def create_task(coroutine: Awaitable[None]) -> None:
task = asyncio.create_task(coroutine) # type: ignore
task.add_done_callback(tasks.discard)
def schedule_coroutine(coroutine: Awaitable[None], delay: dt.timedelta) -> None:
async def wrapper() -> None:
await asyncio.sleep(delay.seconds)
await coroutine
create_task(wrapper())
@@ -1,12 +0,0 @@
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)