Initial scaffold: React+TS+Vite frontend, FastAPI backend, config system
This commit is contained in:
83
backend/config.py
Normal file
83
backend/config.py
Normal file
@@ -0,0 +1,83 @@
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
from pydantic import BaseModel
|
||||
|
||||
CONFIG_PATH = Path(__file__).parent.parent / "config.yaml"
|
||||
|
||||
|
||||
class Go2RTCConfig(BaseModel):
|
||||
url: str = "http://localhost:1985"
|
||||
|
||||
|
||||
class FrigateConfig(BaseModel):
|
||||
url: str = "http://localhost:5000"
|
||||
|
||||
|
||||
class MQTTConfig(BaseModel):
|
||||
host: str = "localhost"
|
||||
port: int = 1883
|
||||
topic_prefix: str = "frigate"
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
|
||||
|
||||
class CameraConfig(BaseModel):
|
||||
name: str
|
||||
display_name: str = ""
|
||||
enabled: bool = True
|
||||
order: int = 0
|
||||
|
||||
|
||||
class AlertConfig(BaseModel):
|
||||
enabled: bool = False
|
||||
auto_dismiss_seconds: int = 30
|
||||
suppression_seconds: int = 60
|
||||
cameras: list[str] = []
|
||||
detection_types: list[str] = ["person"]
|
||||
|
||||
|
||||
class GridConfig(BaseModel):
|
||||
columns: int | None = None
|
||||
aspect_ratio: str = "16:9"
|
||||
gap: int = 4
|
||||
|
||||
|
||||
class AppConfig(BaseModel):
|
||||
title: str = "Camera Viewer"
|
||||
go2rtc: Go2RTCConfig = Go2RTCConfig()
|
||||
frigate: FrigateConfig = FrigateConfig()
|
||||
mqtt: MQTTConfig = MQTTConfig()
|
||||
cameras: list[CameraConfig] = []
|
||||
alerts: AlertConfig = AlertConfig()
|
||||
grid: GridConfig = GridConfig()
|
||||
|
||||
|
||||
_config: AppConfig | None = None
|
||||
|
||||
|
||||
def load_config() -> AppConfig:
|
||||
global _config
|
||||
if not CONFIG_PATH.exists():
|
||||
_config = AppConfig()
|
||||
return _config
|
||||
|
||||
with open(CONFIG_PATH) as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
|
||||
_config = AppConfig(**data)
|
||||
return _config
|
||||
|
||||
|
||||
def save_config(config: AppConfig) -> None:
|
||||
global _config
|
||||
_config = config
|
||||
data = config.model_dump()
|
||||
with open(CONFIG_PATH, "w") as f:
|
||||
yaml.dump(data, f, default_flow_style=False, sort_keys=False)
|
||||
|
||||
|
||||
def get_config() -> AppConfig:
|
||||
global _config
|
||||
if _config is None:
|
||||
return load_config()
|
||||
return _config
|
||||
44
backend/main.py
Normal file
44
backend/main.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from config import load_config
|
||||
from mqtt_bridge import start_mqtt
|
||||
from routes.config_routes import router as config_router
|
||||
from routes.ws_routes import router as ws_router
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
FRONTEND_DIR = Path(__file__).parent.parent / "frontend" / "dist"
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
config = load_config()
|
||||
logger.info(f"Loaded config: {config.title} with {len(config.cameras)} cameras")
|
||||
start_mqtt()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="Camera Viewer", lifespan=lifespan)
|
||||
|
||||
app.include_router(config_router)
|
||||
app.include_router(ws_router)
|
||||
|
||||
# Serve frontend static files
|
||||
if FRONTEND_DIR.exists():
|
||||
app.mount("/assets", StaticFiles(directory=FRONTEND_DIR / "assets"), name="assets")
|
||||
|
||||
@app.get("/{full_path:path}")
|
||||
async def serve_frontend(full_path: str):
|
||||
# Try to serve the exact file first
|
||||
file_path = FRONTEND_DIR / full_path
|
||||
if full_path and file_path.exists() and file_path.is_file():
|
||||
return FileResponse(file_path)
|
||||
# Fall back to index.html for SPA routing
|
||||
return FileResponse(FRONTEND_DIR / "index.html")
|
||||
120
backend/mqtt_bridge.py
Normal file
120
backend/mqtt_bridge.py
Normal file
@@ -0,0 +1,120 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import aiomqtt
|
||||
|
||||
from config import get_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Connected WebSocket clients
|
||||
_ws_clients: set[Any] = set()
|
||||
_mqtt_task: asyncio.Task | None = None
|
||||
|
||||
|
||||
def register_ws_client(ws):
|
||||
_ws_clients.add(ws)
|
||||
|
||||
|
||||
def unregister_ws_client(ws):
|
||||
_ws_clients.discard(ws)
|
||||
|
||||
|
||||
async def broadcast(message: dict):
|
||||
data = json.dumps(message)
|
||||
disconnected = set()
|
||||
for ws in _ws_clients:
|
||||
try:
|
||||
await ws.send_text(data)
|
||||
except Exception:
|
||||
disconnected.add(ws)
|
||||
_ws_clients -= disconnected
|
||||
|
||||
|
||||
async def mqtt_listener():
|
||||
config = get_config()
|
||||
if not config.alerts.enabled:
|
||||
logger.info("Alerts disabled, MQTT listener not started")
|
||||
return
|
||||
|
||||
mqtt = config.mqtt
|
||||
topic = f"{mqtt.topic_prefix}/events"
|
||||
|
||||
while True:
|
||||
try:
|
||||
async with aiomqtt.Client(
|
||||
hostname=mqtt.host,
|
||||
port=mqtt.port,
|
||||
username=mqtt.username or None,
|
||||
password=mqtt.password or None,
|
||||
) as client:
|
||||
logger.info(f"Connected to MQTT broker at {mqtt.host}:{mqtt.port}")
|
||||
await client.subscribe(topic)
|
||||
|
||||
async for message in client.messages:
|
||||
try:
|
||||
payload = json.loads(message.payload)
|
||||
await handle_frigate_event(payload)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error(f"Error handling MQTT message: {e}")
|
||||
|
||||
except aiomqtt.MqttError as e:
|
||||
logger.warning(f"MQTT connection lost: {e}, reconnecting in 5s...")
|
||||
await asyncio.sleep(5)
|
||||
except Exception as e:
|
||||
logger.error(f"MQTT error: {e}, reconnecting in 10s...")
|
||||
await asyncio.sleep(10)
|
||||
|
||||
|
||||
async def handle_frigate_event(payload: dict):
|
||||
config = get_config()
|
||||
alert_config = config.alerts
|
||||
|
||||
if not alert_config.enabled:
|
||||
return
|
||||
|
||||
event_type = payload.get("type")
|
||||
after = payload.get("after", {})
|
||||
label = after.get("label", "")
|
||||
camera = after.get("camera", "")
|
||||
has_clip = after.get("has_clip", False)
|
||||
has_snapshot = after.get("has_snapshot", False)
|
||||
|
||||
# Only process new events with matching detection types
|
||||
if event_type != "new":
|
||||
return
|
||||
if label not in alert_config.detection_types:
|
||||
return
|
||||
if alert_config.cameras and camera not in alert_config.cameras:
|
||||
return
|
||||
|
||||
event = {
|
||||
"type": "alert",
|
||||
"camera": camera,
|
||||
"label": label,
|
||||
"event_id": after.get("id", ""),
|
||||
"has_snapshot": has_snapshot,
|
||||
"has_clip": has_clip,
|
||||
"timestamp": after.get("start_time", 0),
|
||||
}
|
||||
|
||||
logger.info(f"Person detected on {camera}")
|
||||
await broadcast(event)
|
||||
|
||||
|
||||
def start_mqtt(loop: asyncio.AbstractEventLoop | None = None):
|
||||
global _mqtt_task
|
||||
_mqtt_task = asyncio.create_task(mqtt_listener())
|
||||
return _mqtt_task
|
||||
|
||||
|
||||
def get_mqtt_status() -> dict:
|
||||
return {
|
||||
"enabled": get_config().alerts.enabled,
|
||||
"connected": _mqtt_task is not None and not _mqtt_task.done(),
|
||||
"clients": len(_ws_clients),
|
||||
}
|
||||
6
backend/requirements.txt
Normal file
6
backend/requirements.txt
Normal file
@@ -0,0 +1,6 @@
|
||||
fastapi==0.115.0
|
||||
uvicorn[standard]==0.30.6
|
||||
aiomqtt==2.3.0
|
||||
pyyaml==6.0.2
|
||||
pydantic==2.9.2
|
||||
websockets==13.1
|
||||
0
backend/routes/__init__.py
Normal file
0
backend/routes/__init__.py
Normal file
31
backend/routes/config_routes.py
Normal file
31
backend/routes/config_routes.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from fastapi import APIRouter
|
||||
from config import get_config, save_config, load_config, AppConfig
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
|
||||
|
||||
@router.get("/config")
|
||||
async def get_configuration():
|
||||
config = get_config()
|
||||
return config.model_dump()
|
||||
|
||||
|
||||
@router.put("/config")
|
||||
async def update_configuration(data: AppConfig):
|
||||
save_config(data)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/config/reload")
|
||||
async def reload_configuration():
|
||||
load_config()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check():
|
||||
from mqtt_bridge import get_mqtt_status
|
||||
return {
|
||||
"status": "ok",
|
||||
"mqtt": get_mqtt_status(),
|
||||
}
|
||||
19
backend/routes/ws_routes.py
Normal file
19
backend/routes/ws_routes.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from mqtt_bridge import register_ws_client, unregister_ws_client
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.websocket("/api/ws/events")
|
||||
async def websocket_events(ws: WebSocket):
|
||||
await ws.accept()
|
||||
register_ws_client(ws)
|
||||
try:
|
||||
while True:
|
||||
# Keep connection alive, handle client messages if needed
|
||||
data = await ws.receive_text()
|
||||
# Client can send ping/keepalive
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
unregister_ws_client(ws)
|
||||
Reference in New Issue
Block a user