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
@@ -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 ["--log-level", "warning"]
|
||||
|
||||
RUN pip3 install --upgrade pip
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
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
|
||||
@@ -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
|
||||
@@ -1,92 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import traceback
|
||||
from threading import Thread
|
||||
import datetime as dt
|
||||
|
||||
import requests
|
||||
from flask import Blueprint, request, jsonify
|
||||
import paho.mqtt.publish as mqtt_publish
|
||||
|
||||
|
||||
blueprint = Blueprint('detection', __name__)
|
||||
|
||||
|
||||
def get_sunset_time() -> dt.datetime:
|
||||
sunset_date = dt.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 = dt.datetime.strptime(astronomical_json['sunset'], '%H:%M').time()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
sunset_time = dt.time(20, 00, 00)
|
||||
finally:
|
||||
if sunset_time < dt.datetime.now().time():
|
||||
# Sunset has already passed today
|
||||
sunset_date += dt.timedelta(days=1)
|
||||
return dt.datetime.combine(sunset_date, sunset_time)
|
||||
|
||||
|
||||
def reset_all_camera_detection_at_sunset() -> None:
|
||||
while True:
|
||||
try:
|
||||
# Get names of cameras with detection enabled in configuration
|
||||
frigate_api_response = requests.get('http://frigate:5000/api/config')
|
||||
frigate_api_response.raise_for_status()
|
||||
frigate_camera_config = json.loads(frigate_api_response.content)['cameras']
|
||||
|
||||
sunset_time = get_sunset_time() + dt.timedelta(minutes=30)
|
||||
print(f'Waiting until {sunset_time} to reset detection for all cameras...', file=sys.stderr)
|
||||
seconds_until_sunset = (sunset_time - dt.datetime.now()).total_seconds()
|
||||
time.sleep(seconds_until_sunset)
|
||||
|
||||
for camera_name in frigate_camera_config:
|
||||
camera_enabled = frigate_camera_config[camera_name].get('enabled', True)
|
||||
detection_enabled = frigate_camera_config[camera_name].get('detect', {}).get('enabled', True)
|
||||
|
||||
if camera_enabled and detection_enabled:
|
||||
set_camera_detection(camera_name, True)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
def set_camera_detection(camera: str, value: bool, delay: int = 0) -> None:
|
||||
time.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()
|
||||
@@ -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)
|
||||
@@ -0,0 +1,4 @@
|
||||
from webcontrol.api import api
|
||||
from webcontrol.utils.logging import configure_logging
|
||||
|
||||
configure_logging()
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
import logging
|
||||
import os
|
||||
|
||||
import paho.mqtt.publish as mqtt_publish
|
||||
|
||||
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())
|
||||
|
||||
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)
|
||||
@@ -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)
|
||||
]
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user