Compare commits

..
45 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
ashish c34d7692f6 Add new family room camera #15 2024-11-05 23:33:42 -06:00
ashish fb7a84cf4c Fix Golang slog in uptime monitor #13 2024-10-09 18:47:17 -05:00
ashish adb6e54c9c Bumped Frigate to v0.14.1 2024-09-01 23:29:51 -05:00
ashish 90efd78669 Rewrite camera uptime monitor in Golang 2024-08-19 16:36:01 -05:00
ashish fd4c30f655 Enabled Wyze bridge camera audio passthru 2024-08-12 09:15:57 -05:00
ashish 16493e884d Upgrade Frigate to v0.14.0 #12 2024-08-11 19:28:53 -05:00
ashish de4b7792d1 Added video ping to uptime monitor 2024-08-09 02:20:29 -05:00
ashish 6481511dcd Added go2rtc restreaming 2024-08-05 22:54:05 -05:00
ashish d996fa127c Fixed Wyze Bridge auth to use new Wyze API 2024-06-16 22:00:16 -05:00
ashish 2544fabb26 Bump Frigate to v0.13.2 #11 2024-04-07 11:09:36 -05:00
ashish ff12424ba3 Fixed NtfyNotifier constructor bug 2024-03-24 10:44:00 -05:00
ashish 59ee8e64b7 Added root path for webcontrol API 2024-03-24 03:52:37 -05:00
ashish be3bd11632 Rewrite with asyncio and FastAPI #5
Squashed commit of the following:

commit 6832d62dc8360bd20e92df5554dd36426119a50d
Author: Ashish D'Souza <[email protected]>
Date:   Sun Mar 24 03:17:38 2024 -0500

    Converted to asyncio
2024-03-24 03:40:36 -05:00
ashish b3a2076416 Disabled SSL certificate validation for Ntfy 2024-02-18 10:54:44 -06:00
ashish c7e07f309d Added support for Wyze bridge camera mapping 2024-02-18 10:45:13 -06:00
ashish 91ca9e88bc Added camera uptime monitoring system #10
Squashed commit of the following:

commit 3c26ec1cf2c69f60f8dfc5db3f2ec292166d8f4e
Author: Ashish D'Souza <[email protected]>
Date:   Sun Feb 18 02:46:18 2024 -0600

    Added camera uptime monitoring system
2024-02-18 02:53:13 -06:00
ashish 20fe151435 Fixed MQTT container name 2024-02-12 22:04:37 -06:00
ashish c58751e6dd Added sunset delay to allow full darkness #7 #8
Squashed commit of the following:

commit 423931bcd23136ff4aea6b1cb9d9bf6dfc210f5a
Author: Ashish D'Souza <[email protected]>
Date:   Sat Jan 27 16:03:57 2024 -0600

    Added 30 minute sunset delay
2024-01-27 16:04:39 -06:00
ashish f3dfaeea1b Delayed webcontrol service start #9
Squashed commit of the following:

commit 6270850309f397503246f2bc0a0fd58e67a82561
Author: Ashish D'Souza <[email protected]>
Date:   Sat Jan 27 15:42:21 2024 -0600

    Fixed docker compose webcontrol dependencies
2024-01-27 15:49:14 -06:00
ashish fc63499bf0 Fixed datetime bug 2024-01-07 20:17:06 -06:00
ashish 4ec4531f86 Fixed sunset detection reset #6 2023-12-17 12:40:26 -06:00
ashish ce1497cf86 Fixed undesired sunset detection reset behavior #4
Squashed commit of the following:

commit 733c4fb387649d58621a86ff483c3c42c787c58d
Author: Ashish D'Souza <[email protected]>
Date:   Tue Dec 5 21:37:21 2023 -0600

    Fixed sunset detection reset behavior

commit c581ea62d59bd21e4f024bf50578f75338aa91c5
Author: Ashish D'Souza <[email protected]>
Date:   Tue Dec 5 21:35:10 2023 -0600

    Updated config.yaml to reflect regular state
2023-12-05 21:38:09 -06:00
ashish 70a5c983ea Added build notifications to Jenkinsfile 2023-11-19 17:43:22 -06:00
ashish e2812494a0 Setup Docker Wyze bridge #2
Squashed commit of the following:

commit 4a87bc5606
Author: Ashish D'Souza <[email protected]>
Date:   Sun Oct 29 20:55:19 2023 -0500

    Setup pipeline to support Wyze bridge

commit 56da8ba7db
Author: Ashish D'Souza <[email protected]>
Date:   Sun Oct 29 20:54:39 2023 -0500

    Added configuration for Wyze bridge
2023-10-29 20:56:24 -05:00
58 changed files with 1369 additions and 290 deletions

No files matched your search

Vendored
+9 -1
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}\" 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, 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, playbook: 'stop.yaml'
ansiblePlaybook credentialsId: 'rivendell-ssh-key', disableHostKeyChecking: true, playbook: 'start.yaml'
}
@@ -22,6 +22,14 @@ 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()
}
+120 -31
View File
@@ -2,19 +2,50 @@ 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.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'
cameras:
garage:
enabled: true
ffmpeg:
inputs:
- path: 'rtsp://{FRIGATE_GARAGE_RTSP_USERNAME}:{FRIGATE_GARAGE_RTSP_PASSWORD}@192.168.0.102:554/live'
- path: 'rtsp://127.0.0.1:8554/garage'
roles:
- detect
- record
@@ -32,7 +63,7 @@ cameras:
enabled: true
ffmpeg:
inputs:
- path: 'rtsp://{FRIGATE_DOORBELL_RTSP_USERNAME}:{FRIGATE_DOORBELL_RTSP_PASSWORD}@192.168.0.105:554/cam/realmonitor?channel=1&subtype=0'
- path: 'rtsp://127.0.0.1:8554/doorbell'
roles:
- detect
- record
@@ -43,8 +74,8 @@ cameras:
enabled: true
width: 1920
height: 1080
record:
events:
review:
alerts:
required_zones:
- front_door_zone
snapshots:
@@ -57,7 +88,7 @@ cameras:
enabled: true
ffmpeg:
inputs:
- path: 'rtsp://{FRIGATE_FRONT_DOOR_RTSP_USERNAME}:{FRIGATE_FRONT_DOOR_RTSP_PASSWORD}@192.168.0.108:554/live/ch0'
- path: 'rtsp://127.0.0.1:8554/front_door'
roles:
- detect
- record
@@ -65,7 +96,7 @@ cameras:
output_args:
record: preset-record-generic-audio-aac # Record with aac audio
detect:
enabled: true
enabled: false
width: 1920
height: 1080
motion:
@@ -79,10 +110,10 @@ 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://{FRIGATE_DRIVEWAY_RTSP_USERNAME}:{FRIGATE_DRIVEWAY_RTSP_PASSWORD}@192.168.0.148:5543/live/channel1'
- path: 'rtsp://127.0.0.1:8554/driveway'
roles:
- detect
- record
@@ -90,14 +121,14 @@ cameras:
output_args:
record: preset-record-generic-audio-aac # Record with aac audio
detect:
enabled: true
enabled: false
width: 640
height: 360
back_door:
enabled: true
ffmpeg:
inputs:
- path: 'rtsp://{FRIGATE_BACK_DOOR_RTSP_USERNAME}:{FRIGATE_BACK_DOOR_RTSP_PASSWORD}@192.168.0.202:554/live'
- path: 'rtsp://127.0.0.1:8554/back_door'
roles:
- detect
- record
@@ -111,11 +142,41 @@ 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:
inputs:
- path: 'rtsp://{FRIGATE_FAMILY_ROOM_RTSP_USERNAME}:{FRIGATE_FAMILY_ROOM_RTSP_PASSWORD}@192.168.0.104:554/live/ch0'
- 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
@@ -126,38 +187,66 @@ 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:
- person
review:
alerts:
labels:
- person
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)
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
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
rtmp:
enabled: false
motion:
birdseye:
enabled: true
enabled: false
mode: continuous
auth:
enabled: false
+74 -12
View File
@@ -3,12 +3,13 @@
services:
frigate:
container_name: frigate
image: ghcr.io/blakeblackshear/frigate:0.12.0
image: ghcr.io/blakeblackshear/frigate:0.15.0
labels:
autoheal: 'true'
restart: unless-stopped
depends_on:
- mqtt
- wyze-bridge
healthcheck:
test: ls /media/frigate && curl -s -f http://localhost:5000 -o /dev/null
interval: 60s
@@ -28,7 +29,9 @@ 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}
shm_size: '150mb'
FRIGATE_OFFICE_RTSP_USERNAME: frigate
FRIGATE_OFFICE_RTSP_PASSWORD: ${FRIGATE_OFFICE_RTSP_PASSWORD}
shm_size: '1000mb'
devices:
- /dev/dri:/dev/dri
volumes:
@@ -50,9 +53,31 @@ services:
- frigate
ports:
- 127.0.0.1:10000:5000
notify:
container_name: frigate-notify
image: frigate-notify:latest
- 554:8554
wyze-bridge:
container_name: frigate-wyze-bridge
image: mrlt8/wyze-bridge:2.10.3
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
networks:
- wyze-bridge
- frigate
notifier:
container_name: frigate-notifier
image: frigate-notifier:latest
restart: unless-stopped
depends_on:
- frigate
@@ -77,8 +102,10 @@ services:
autoheal: 'true'
restart: unless-stopped
depends_on:
- frigate
- mqtt
frigate:
condition: service_healthy
mqtt:
condition: service_started
healthcheck:
test: curl -s -f http://localhost -o /dev/null
interval: 60s
@@ -87,7 +114,18 @@ 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
@@ -96,8 +134,22 @@ services:
- 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
mqtt:
container_name: mqtt
container_name: frigate-mqtt
image: eclipse-mosquitto:2.0.18
command:
- mosquitto
@@ -112,10 +164,6 @@ services:
networks:
- frigate
networks:
frigate:
name: frigate
volumes:
config:
name: frigate-config
@@ -123,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
+47 -7
View File
@@ -3,6 +3,14 @@
vars_prompt:
- name: ipgeolocation_api_key
prompt: Enter API key for IPGeolocation
- name: wyze_email
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
@@ -15,6 +23,8 @@
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
@@ -59,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
ansible.builtin.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
@@ -92,7 +102,7 @@
dest: '{{docker_build_dir.path}}'
mode: preserve
- name: Build frigate-webcontrol Docker image
ansible.builtin.docker_image:
community.docker.docker_image:
build:
path: '{{docker_build_dir.path}}'
name: frigate-webcontrol
@@ -105,6 +115,29 @@
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'
@@ -118,6 +151,11 @@
frigate_config:
ipgeolocation:
api_key: '{{ipgeolocation_api_key}}'
wyze:
email: '{{wyze_email}}'
password: '{{wyze_password}}'
api_id: '{{wyze_api_id}}'
api_key: '{{wyze_api_key}}'
rtsp:
garage:
password: '{{garage_rtsp_password}}'
@@ -131,6 +169,8 @@
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}}'
+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 "$@"
-119
View File
@@ -1,119 +0,0 @@
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()
+18 -1
View File
@@ -36,13 +36,18 @@
- name: Docker Compose up Frigate
environment:
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}}'
community.docker.docker_compose:
FRIGATE_OFFICE_RTSP_PASSWORD: '{{frigate_config.rtsp.office.password}}'
community.docker.docker_compose_v2:
project_name: frigate
project_src: '{{docker_compose_dir.path}}'
state: present
@@ -51,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
+12
View File
@@ -0,0 +1,12 @@
#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
@@ -0,0 +1,26 @@
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
@@ -0,0 +1,9 @@
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
@@ -0,0 +1,5 @@
module frigate/uptime
go 1.21.12
require gopkg.in/yaml.v3 v3.0.1 // indirect
+3
View File
@@ -0,0 +1,3 @@
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
@@ -0,0 +1,17 @@
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
@@ -0,0 +1,108 @@
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
@@ -0,0 +1,27 @@
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
@@ -0,0 +1,64 @@
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
@@ -0,0 +1,9 @@
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
@@ -0,0 +1 @@
package ping
+9
View File
@@ -0,0 +1,9 @@
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
@@ -0,0 +1,12 @@
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
@@ -0,0 +1,3 @@
aiohttp>=3.8.6
PyYAML>=6.0.1
opencv-python>=4.10.0.84
+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.
+25
View File
@@ -0,0 +1,25 @@
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
@@ -0,0 +1,65 @@
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
@@ -0,0 +1,82 @@
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
@@ -0,0 +1,24 @@
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
@@ -0,0 +1,24 @@
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
@@ -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)
+2 -1
View File
@@ -1,7 +1,8 @@
FROM python:3.11
WORKDIR /code
ENTRYPOINT ["python3", "server.py"]
ENTRYPOINT ["uvicorn", "webcontrol:api", "--host", "0.0.0.0", "--port", "80"]
CMD ["--root-path", "/webcontrol", "--log-level", "warning"]
RUN pip3 install --upgrade pip
+6 -2
View File
@@ -1,3 +1,7 @@
flask==2.3.2
PyYAML==6.0.1
pydantic==2.6.4
fastapi==0.110.0
uvicorn[standard]==0.29.0
aiohttp==3.8.6
paho-mqtt==1.6.1
requests==2.31.0
requests==2.30.0
+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
-86
View File
@@ -1,86 +0,0 @@
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
@@ -1,20 +0,0 @@
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
@@ -0,0 +1,4 @@
from webcontrol.api import api
from webcontrol.utils.logging import configure_logging
configure_logging()
+18
View File
@@ -0,0 +1,18 @@
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"
}
@@ -0,0 +1,36 @@
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
@@ -0,0 +1,47 @@
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
@@ -0,0 +1,46 @@
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
@@ -0,0 +1,39 @@
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.
@@ -0,0 +1,18 @@
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())
@@ -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)