diff --git a/CLAUDE.md b/CLAUDE.md index aa97a41..c80dcd7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,30 +2,73 @@ 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. +AI 告警平台后端服务,基于 FastAPI 构建。接收边缘 AI 设备通过 HTTP 上报的告警,存储截图到腾讯云 COS,通过 WebSocket 实时推送告警事件,为芋道 Vue 3 前端提供 REST API。 -## Commands +**生产部署信息:** +- **容器名称:** `vsp-service` +- **端口映射:** 8000:8000 +- **部署位置:** 腾讯云服务器 `/opt/vsp-platform` +- **存储:** 腾讯云 MySQL + 腾讯云 COS +- **访问地址:** http://服务器IP:8000 +## 常用命令 + +### 本地开发 ```bash -# Install dependencies +# 安装依赖 pip install -r requirements.txt -# Run development server (starts at http://localhost:8000, auto-reload in debug mode) +# 环境配置 +cp .env.example .env +# 编辑 .env: +# DATABASE_URL=mysql+pymysql://user:pass@localhost/dbname +# COS_SECRET_ID=your_secret_id +# COS_SECRET_KEY=your_secret_key +# COS_BUCKET=your-bucket +# COS_REGION=ap-beijing + +# 运行开发服务器(自动重载,监听 8000 端口) 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 +# API 文档:http://localhost:8000/docs +# 健康检查:http://localhost:8000/health ``` -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. +### Docker 部署(生产环境) +```bash +# 构建镜像 +docker build -t vsp-service:latest . -No test suite exists yet. If adding tests, use pytest. +# 运行容器 +docker run -d \ + --name vsp-service \ + -p 8000:8000 \ + -e DATABASE_URL=mysql+pymysql://user:pass@云端MySQL/dbname \ + -e COS_BUCKET=腾讯云COS桶名 \ + -e COS_REGION=ap-beijing \ + -e COS_SECRET_ID=your_id \ + -e COS_SECRET_KEY=your_key \ + vsp-service:latest -**Root `main.py`** is a PyCharm template file, not the real entry point. Always use `python -m app.main`. +# 查看日志 +docker logs -f vsp-service + +# 重启容器 +docker restart vsp-service + +# 进入容器调试 +docker exec -it vsp-service /bin/bash +``` + +### 测试 +```bash +# 如果添加测试,使用 pytest +pytest tests/ +``` + +**重要提示:** 根目录的 `main.py` 是 PyCharm 模板文件,不是真正的入口。**务必使用 `python -m app.main` 启动服务**。 ## Architecture @@ -62,21 +105,39 @@ All services are instantiated as module-level singletons, not injected via FastA Startup: init DB → set async event loop on NotificationService → register MQTT handlers → start MQTT. Shutdown: stop MQTT. -### Database +### Database(生产环境使用腾讯云 MySQL) -SQLite at `data/alert_platform.db` (auto-created). Three ORM models in `app/models.py`: +三个核心 ORM 模型在 `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. +- **AlarmEvent** — 告警事件主表。字段:alarm_id (PK), alarm_type, device_id, scene_id, event_time, alarm_level (1-4), alarm_status (NEW/CONFIRMED/RESOLVED), handle_status, snapshot_url 等。索引:alarm_id, device_id, alarm_status, event_time。 +- **AlarmEventExt** — 告警扩展信息表。存储 ext_data JSON 字段(边缘端上报的 bbox, bind_id 等)。 +- **AlarmLlmAnalysis** — 大模型分析结果表(可选功能)。 +- **EdgeDevice** — 边缘设备表(用于设备列表展示,无心跳机制)。 -Sessions obtained via `get_session()`. Services manage their own session lifecycle with try/finally. +数据库连接通过 `get_session()` 获取。服务层使用 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. +**边缘端告警上报(无需认证):** +- `POST /api/ai/alert/edge/report` — 边缘端告警上报 + - 请求体:`{alarm_id, alarm_type, device_id, scene_id, event_time, alarm_level, snapshot_url, confidence_score, ext_data}` + - 幂等性:相同 alarm_id 会跳过创建 + - 成功后触发 WebSocket 推送 + +- `POST /api/ai/alert/edge/resolve` — 告警结束通知(离岗算法) + - 请求体:`{alarm_id, duration_ms, last_frame_time, resolve_type}` + - 更新告警持续时长和结束时间 + +**前端访问接口(需要认证,通过 aiot-gateway 48080 访问):** +- `GET /admin-api/aiot/alarm/event/page` — 分页查询告警事件 +- `GET /admin-api/aiot/alarm/event/get` — 获取告警详情 +- `PUT /admin-api/aiot/alarm/event/handle` — 处理告警 +- `GET /admin-api/aiot/alarm/event/statistics` — 告警统计 +- `GET /admin-api/aiot/edge/device/page` — 分页查询边缘设备 + +**WebSocket 实时推送:** +- `ws://服务器IP:8000/ws/alerts` — 实时告警推送