- main.py:注册 aiot_alarm 和 aiot_edge 路由,保留旧路由兼容 - config.py/alert_service.py/mqtt_service.py:同步更新配置和服务 - 添加 CLAUDE.md 项目说明文档 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
4.7 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
AI Alert Platform backend service built with FastAPI. Receives alerts from edge AI devices via MQTT and HTTP, stores snapshot images, pushes real-time updates over WebSocket, and exposes REST APIs for a Yudao (芋道) Vue 3 frontend. Optionally triggers async big-model analysis on alert snapshots.
Commands
# Install dependencies
pip install -r requirements.txt
# Run development server (starts at http://localhost:8000, auto-reload in debug mode)
python -m app.main
# API docs: http://localhost:8000/docs
# Production run with Gunicorn (Linux only)
gunicorn app.main:app -k uvicorn.workers.UvicornWorker -w 4 -b 0.0.0.0:8000
Environment setup: copy .env.example to .env and configure. SQLite is the default database; set DATABASE_URL for MySQL in production. Set MQTT_ENABLED=false if no MQTT broker is available.
No test suite exists yet. If adding tests, use pytest.
Root main.py is a PyCharm template file, not the real entry point. Always use python -m app.main.
Architecture
Data Flow
Edge Devices ──MQTT──→ EMQX Broker ──subscribe──→ MQTTService ──→ AlertService ──→ DB
│
Edge Devices ──HTTP POST──→ /api/v1/alerts ────────────→│
↓
NotificationService ──WebSocket──→ Frontend
Dual API Surface
The app exposes two parallel API layers hitting the same services and database:
- Native API (
/api/v1/) — endpoints defined inline inapp/main.py. Standard REST responses. - Yudao-compat API (
/admin-api/) — routers inapp/routers/yudao_alert.pyandyudao_auth.py. Wraps responses in{"code": 0, "data": ..., "msg": ""}format expected by the Yudao Vue frontend. Auth/permissions handled byapp/yudao_compat.py(stub in dev mode:DEV_MODE=trueskips token validation, returns mock admin).
Services (Global Singletons)
All services are instantiated as module-level singletons, not injected via FastAPI Depends(). Access them via factory functions (get_alert_service(), get_mqtt_service(), etc.) or import the global directly.
- AlertService (
app/services/alert_service.py) — CRUD, filtering/pagination, statistics, AI analysis update. Handles both HTTP (create_alert) and MQTT (create_alert_from_mqtt) creation paths. Alert numbers:ALT+ timestamp + uuid fragment. - MQTTService (
app/services/mqtt_service.py) — paho-mqtt client subscribing toedge/alert/#. Routes messages to registered callbacks for alerts vs heartbeats. Compatible with paho-mqtt 1.x and 2.x APIs. - DeviceService (
app/services/device_service.py) — Tracks edge device status from MQTT heartbeats. In-memory cache + DB persistence. Marks devices offline after 90s without heartbeat. - NotificationService (
app/services/notification_service.py) — WebSocket connection manager + broadcast. Bridges sync MQTT callbacks to async WebSocket sends viaasyncio.run_coroutine_threadsafe(). - OSSStorage (
app/services/oss_storage.py) — Image storage. Currently local-only (uploads/dir); Aliyun OSS stubbed but not implemented. - AIAnalyzer (
app/services/ai_analyzer.py) — Async httpx client for optional big-model analysis. Fire-and-forget viaasyncio.create_task().
Lifecycle (app/main.py lifespan)
Startup: init DB → set async event loop on NotificationService → register MQTT handlers → start MQTT. Shutdown: stop MQTT.
Database
SQLite at data/alert_platform.db (auto-created). Three ORM models in app/models.py:
- Alert — main table. Enums:
AlertStatus(pending/confirmed/ignored/resolved/dispatched),AlertLevel(low/medium/high/critical). Indexed on alert_no, camera_id, status, trigger_time. - EdgeDevice — device status and heartbeat tracking. Enum:
DeviceStatus(online/offline/error). - WorkOrder — framework exists (model + relationship to Alert) but no API/service layer yet.
Sessions obtained via get_session(). Services manage their own session lifecycle with try/finally.
Config
app/config.py — dataclass-based config loaded from .env via os.getenv(). Sections: DatabaseConfig, OSSConfig, AppConfig (includes dev_mode), AIModelConfig, MQTTConfig. Global settings instance created at module load.
Key MQTT Topics
- Alert:
edge/alert/{camera_id}/{roi_id}— JSON with camera_id, roi_id, alert_type, confidence, etc. - Heartbeat:
edge/alert/heartbeat/{device_id}— JSON with device_id, status, uptime, counters.