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
This commit is contained in:
1 parent
b3a2076416
commit
be3bd11632
24 files changed
+345
-246
No files matched your search
@@ -2,7 +2,7 @@ version: 1
|
||||
disable_existing_loggers: false
|
||||
formatters:
|
||||
default:
|
||||
format: '[{asctime}.{msecs:03.0f}][{levelname}] {name}:{lineno}:{funcName} - {message}'
|
||||
format: '[{asctime}.{msecs:03.0f}][{levelname}] {name}:{lineno} - {message}'
|
||||
style: '{'
|
||||
datefmt: '%Y-%m-%d %H:%M:%S'
|
||||
handlers:
|
||||
Whitespace-only changes.
@@ -17,9 +17,9 @@ def entrypoint() -> None:
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
logger.info('Received Ctrl+C, exiting...')
|
||||
logger.info("Received Ctrl+C, exiting...")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
entrypoint()
|
||||
|
||||
@@ -2,8 +2,7 @@ import re
|
||||
import json
|
||||
import logging
|
||||
from contextlib import AsyncExitStack
|
||||
from types import TracebackType
|
||||
from typing import Any, ClassVar, Pattern, Self
|
||||
from typing import ClassVar, Pattern
|
||||
|
||||
import aiohttp
|
||||
|
||||
@@ -11,58 +10,47 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class FrigateConfig:
|
||||
_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'}
|
||||
_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'
|
||||
def __init__(self, frigate_base_url: str = "http://frigate:5000") -> None:
|
||||
self._frigate_config_url = f"{frigate_base_url}/api/config"
|
||||
self._config = {}
|
||||
self._aiohttp_session: aiohttp.ClientSession
|
||||
self._async_exit_stack: AsyncExitStack
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
async with AsyncExitStack() as async_exit_stack:
|
||||
self._aiohttp_session = await async_exit_stack.enter_async_context(aiohttp.ClientSession(raise_for_status=True))
|
||||
self._async_exit_stack = async_exit_stack.pop_all()
|
||||
|
||||
await self.refresh()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) -> None:
|
||||
await self._async_exit_stack.aclose()
|
||||
|
||||
async def refresh(self) -> None:
|
||||
logger.debug('Fetching Frigate config...')
|
||||
logger.debug("Fetching Frigate configuration")
|
||||
try:
|
||||
async with self._aiohttp_session.get(self._frigate_config_url) as response:
|
||||
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())
|
||||
logger.debug('Finished fetching Frigate config')
|
||||
except Exception as e:
|
||||
if self._config:
|
||||
logger.warning('Failed to fetch Frigate config, falling back to previous value', exc_info=e)
|
||||
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')
|
||||
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)]
|
||||
return [camera for camera in self._config["cameras"] if self._config["cameras"][camera].get("enabled", True)]
|
||||
|
||||
@property
|
||||
def active_camera_addresses(self) -> dict[str, str]:
|
||||
active_cameras = self.active_cameras
|
||||
return {camera: self._get_address_from_url(self._config['cameras'][camera]['ffmpeg']['inputs'][0]['path']) for camera in active_cameras}
|
||||
return {camera: self._get_address_from_url(self._config["cameras"][camera]["ffmpeg"]["inputs"][0]["path"]) for camera in active_cameras}
|
||||
|
||||
@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=}')
|
||||
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('-', '_')
|
||||
if match.group().startswith("wyze-bridge"):
|
||||
wyze_camera = url.lower().rsplit("/", 1)[-1].replace("-", "_")
|
||||
return cls._WYZE_CAMERAS[wyze_camera]
|
||||
return match.group()
|
||||
@@ -17,11 +17,11 @@ class CameraMonitor:
|
||||
self._wait_time = wait_time
|
||||
self._consecutive_down_threshold = consecutive_down_threshold
|
||||
self._camera_downtime = Counter()
|
||||
self._frigate_config: FrigateConfig
|
||||
self._ntfy_notifier: NtfyNotifier
|
||||
self._frigate_config = FrigateConfig()
|
||||
self._ntfy_notifier = NtfyNotifier
|
||||
|
||||
async def _on_camera_up(self, camera: str) -> None:
|
||||
logger.info(f'Camera {camera} is back online')
|
||||
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:
|
||||
@@ -29,7 +29,7 @@ class CameraMonitor:
|
||||
if camera not in self._frigate_config.active_cameras:
|
||||
return
|
||||
|
||||
logger.info(f'Camera {camera} is down')
|
||||
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:
|
||||
@@ -43,16 +43,13 @@ class CameraMonitor:
|
||||
self._camera_downtime[camera] += 1
|
||||
|
||||
async def run(self) -> None:
|
||||
async with AsyncExitStack() as async_exit_stack:
|
||||
self._frigate_config = await async_exit_stack.enter_async_context(FrigateConfig())
|
||||
self._ntfy_notifier = await async_exit_stack.enter_async_context(NtfyNotifier())
|
||||
await self._frigate_config.refresh()
|
||||
while True:
|
||||
camera_ips = {camera: address.split(":", 1)[0] for camera, address in self._frigate_config.active_camera_addresses.items()}
|
||||
ping_results = await ip_ping_all(*camera_ips.values())
|
||||
for i, camera in enumerate(camera_ips):
|
||||
await self._on_camera_ping(camera, ping_results[i])
|
||||
|
||||
while True:
|
||||
camera_ips = {camera: address.split(':', 1)[0] for camera, address in self._frigate_config.active_camera_addresses.items()}
|
||||
ping_results = await ip_ping_all(*camera_ips.values())
|
||||
for i, camera in enumerate(camera_ips):
|
||||
await self._on_camera_ping(camera, ping_results[i])
|
||||
|
||||
logger.debug(f'Sleeping for {self._wait_time} seconds...')
|
||||
await asyncio.sleep(self._wait_time)
|
||||
logger.debug(f"Sleeping for {self._wait_time} seconds...")
|
||||
await asyncio.sleep(self._wait_time)
|
||||
|
||||
+13
-26
@@ -1,7 +1,4 @@
|
||||
import logging
|
||||
from contextlib import AsyncExitStack
|
||||
from types import TracebackType
|
||||
from typing import Self
|
||||
|
||||
import aiohttp
|
||||
|
||||
@@ -9,29 +6,19 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class NtfyNotifier:
|
||||
def __init__(self, ntfy_url: str = 'https://ntfy.homelab.net') -> None:
|
||||
def __init__(self, ntfy_url: str = "https://ntfy.homelab.net") -> None:
|
||||
self._ntfy_url = ntfy_url
|
||||
self._aiohttp_session: aiohttp.ClientSession
|
||||
self._async_exit_stack: AsyncExitStack
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
async with AsyncExitStack() as async_exit_stack:
|
||||
self._aiohttp_session = await async_exit_stack.enter_async_context(aiohttp.ClientSession(raise_for_status=True))
|
||||
self._async_exit_stack = async_exit_stack.pop_all()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) -> None:
|
||||
await self._async_exit_stack.aclose()
|
||||
|
||||
async def send_notification(self, camera: str, status: bool) -> None:
|
||||
logger.debug(f'Sending notification for {camera=}...')
|
||||
message = f'{camera} is back online' if status else f'{camera} is offline'
|
||||
await self._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=}')
|
||||
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=}")
|
||||
@@ -5,10 +5,10 @@ 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)
|
||||
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}')
|
||||
logger.debug(f"Finished pinging {host}")
|
||||
return return_code == 0
|
||||
|
||||
async def ip_ping_all(*hosts: str) -> list[bool]:
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import logging
|
||||
import logging.config
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
with open('logging.yaml', 'r') as logging_yaml:
|
||||
with open("configs/logging.yaml", "r") as logging_yaml:
|
||||
logging_config = yaml.safe_load(logging_yaml)
|
||||
|
||||
logging.config.dictConfig(logging_config)
|
||||
|
||||
Reference in new issue
Block a user