feat: KKS P240/P241 蓝牙工牌管理系统初始提交
FastAPI + SQLAlchemy + asyncio TCP 服务器,支持设备管理、实时定位、 告警、考勤打卡、蓝牙记录、指令下发、TTS语音播报等功能。
This commit is contained in:
0
app/routers/__init__.py
Normal file
0
app/routers/__init__.py
Normal file
183
app/routers/alarms.py
Normal file
183
app/routers/alarms.py
Normal file
@@ -0,0 +1,183 @@
|
||||
"""
|
||||
Alarms Router - 报警管理接口
|
||||
API endpoints for alarm record queries, acknowledgement, and statistics.
|
||||
"""
|
||||
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.dependencies import require_write
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import AlarmRecord
|
||||
from app.schemas import (
|
||||
AlarmAcknowledge,
|
||||
AlarmRecordResponse,
|
||||
APIResponse,
|
||||
PaginatedList,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/alarms", tags=["Alarms / 报警管理"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[AlarmRecordResponse]],
|
||||
summary="获取报警记录列表 / List alarms",
|
||||
)
|
||||
async def list_alarms(
|
||||
device_id: int | None = Query(default=None, description="设备ID / Device ID"),
|
||||
alarm_type: str | None = Query(default=None, description="报警类型 / Alarm type"),
|
||||
alarm_source: str | None = Query(default=None, description="报警来源 / Alarm source (single_fence/multi_fence/lbs/wifi)"),
|
||||
acknowledged: bool | None = Query(default=None, description="是否已确认 / Acknowledged status"),
|
||||
start_time: datetime | None = Query(default=None, description="开始时间 / Start time (ISO 8601)"),
|
||||
end_time: datetime | None = Query(default=None, description="结束时间 / End time (ISO 8601)"),
|
||||
sort_order: Literal["asc", "desc"] = Query(default="desc", description="排序方向 / Sort order (asc/desc)"),
|
||||
page: int = Query(default=1, ge=1, description="页码 / Page number"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量 / Items per page"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取报警记录列表,支持按设备、报警类型、来源、确认状态、时间范围过滤。
|
||||
List alarm records with filters for device, alarm type, source, acknowledged status, and time range.
|
||||
"""
|
||||
query = select(AlarmRecord)
|
||||
count_query = select(func.count(AlarmRecord.id))
|
||||
|
||||
if device_id is not None:
|
||||
query = query.where(AlarmRecord.device_id == device_id)
|
||||
count_query = count_query.where(AlarmRecord.device_id == device_id)
|
||||
|
||||
if alarm_type:
|
||||
query = query.where(AlarmRecord.alarm_type == alarm_type)
|
||||
count_query = count_query.where(AlarmRecord.alarm_type == alarm_type)
|
||||
|
||||
if alarm_source:
|
||||
query = query.where(AlarmRecord.alarm_source == alarm_source)
|
||||
count_query = count_query.where(AlarmRecord.alarm_source == alarm_source)
|
||||
|
||||
if acknowledged is not None:
|
||||
query = query.where(AlarmRecord.acknowledged == acknowledged)
|
||||
count_query = count_query.where(AlarmRecord.acknowledged == acknowledged)
|
||||
|
||||
if start_time:
|
||||
query = query.where(AlarmRecord.recorded_at >= start_time)
|
||||
count_query = count_query.where(AlarmRecord.recorded_at >= start_time)
|
||||
|
||||
if end_time:
|
||||
query = query.where(AlarmRecord.recorded_at <= end_time)
|
||||
count_query = count_query.where(AlarmRecord.recorded_at <= end_time)
|
||||
|
||||
total_result = await db.execute(count_query)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
order = AlarmRecord.recorded_at.asc() if sort_order == "asc" else AlarmRecord.recorded_at.desc()
|
||||
query = query.order_by(order).offset(offset).limit(page_size)
|
||||
result = await db.execute(query)
|
||||
alarms = list(result.scalars().all())
|
||||
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[AlarmRecordResponse.model_validate(a) for a in alarms],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/stats",
|
||||
response_model=APIResponse[dict],
|
||||
summary="获取报警统计 / Get alarm statistics",
|
||||
)
|
||||
async def alarm_stats(db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
获取报警统计:总数、未确认数、按类型分组统计。
|
||||
Get alarm statistics: total, unacknowledged count, and breakdown by type.
|
||||
"""
|
||||
# Total alarms
|
||||
total_result = await db.execute(select(func.count(AlarmRecord.id)))
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
# Unacknowledged alarms
|
||||
unack_result = await db.execute(
|
||||
select(func.count(AlarmRecord.id)).where(AlarmRecord.acknowledged == False) # noqa: E712
|
||||
)
|
||||
unacknowledged = unack_result.scalar() or 0
|
||||
|
||||
# By type
|
||||
type_result = await db.execute(
|
||||
select(AlarmRecord.alarm_type, func.count(AlarmRecord.id))
|
||||
.group_by(AlarmRecord.alarm_type)
|
||||
.order_by(func.count(AlarmRecord.id).desc())
|
||||
)
|
||||
by_type = {row[0]: row[1] for row in type_result.all()}
|
||||
|
||||
return APIResponse(
|
||||
data={
|
||||
"total": total,
|
||||
"unacknowledged": unacknowledged,
|
||||
"acknowledged": total - unacknowledged,
|
||||
"by_type": by_type,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{alarm_id}",
|
||||
response_model=APIResponse[AlarmRecordResponse],
|
||||
summary="获取报警详情 / Get alarm details",
|
||||
)
|
||||
async def get_alarm(alarm_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
按ID获取报警记录详情。
|
||||
Get alarm record details by ID.
|
||||
"""
|
||||
result = await db.execute(
|
||||
select(AlarmRecord).where(AlarmRecord.id == alarm_id)
|
||||
)
|
||||
alarm = result.scalar_one_or_none()
|
||||
if alarm is None:
|
||||
raise HTTPException(status_code=404, detail=f"Alarm {alarm_id} not found / 未找到报警记录{alarm_id}")
|
||||
return APIResponse(data=AlarmRecordResponse.model_validate(alarm))
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{alarm_id}/acknowledge",
|
||||
response_model=APIResponse[AlarmRecordResponse],
|
||||
summary="确认报警 / Acknowledge alarm",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def acknowledge_alarm(
|
||||
alarm_id: int,
|
||||
body: AlarmAcknowledge | None = None,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
确认(或取消确认)报警记录。
|
||||
Acknowledge (or un-acknowledge) an alarm record.
|
||||
"""
|
||||
result = await db.execute(
|
||||
select(AlarmRecord).where(AlarmRecord.id == alarm_id)
|
||||
)
|
||||
alarm = result.scalar_one_or_none()
|
||||
if alarm is None:
|
||||
raise HTTPException(status_code=404, detail=f"Alarm {alarm_id} not found / 未找到报警记录{alarm_id}")
|
||||
|
||||
acknowledged = body.acknowledged if body else True
|
||||
alarm.acknowledged = acknowledged
|
||||
|
||||
await db.flush()
|
||||
await db.refresh(alarm)
|
||||
return APIResponse(
|
||||
message="Alarm acknowledged / 报警已确认" if acknowledged else "Alarm un-acknowledged / 已取消确认",
|
||||
data=AlarmRecordResponse.model_validate(alarm),
|
||||
)
|
||||
142
app/routers/api_keys.py
Normal file
142
app/routers/api_keys.py
Normal file
@@ -0,0 +1,142 @@
|
||||
"""
|
||||
API Keys Router - API密钥管理接口
|
||||
Endpoints for creating, listing, updating, and deactivating API keys.
|
||||
Admin permission required.
|
||||
"""
|
||||
|
||||
import secrets
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.dependencies import require_admin, _hash_key
|
||||
from app.models import ApiKey
|
||||
from app.schemas import (
|
||||
APIResponse,
|
||||
ApiKeyCreate,
|
||||
ApiKeyCreateResponse,
|
||||
ApiKeyResponse,
|
||||
ApiKeyUpdate,
|
||||
PaginatedList,
|
||||
)
|
||||
|
||||
import math
|
||||
|
||||
router = APIRouter(prefix="/api/keys", tags=["API Keys / 密钥管理"])
|
||||
|
||||
|
||||
def _generate_key() -> str:
|
||||
"""Generate a random 32-char hex API key."""
|
||||
return secrets.token_hex(16)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[ApiKeyResponse]],
|
||||
summary="列出API密钥 / List API keys",
|
||||
dependencies=[Depends(require_admin)],
|
||||
)
|
||||
async def list_keys(
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=100),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""列出所有API密钥(不返回密钥值)/ List all API keys (key values are never shown)."""
|
||||
count_result = await db.execute(select(func.count(ApiKey.id)))
|
||||
total = count_result.scalar() or 0
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
result = await db.execute(
|
||||
select(ApiKey).order_by(ApiKey.created_at.desc()).offset(offset).limit(page_size)
|
||||
)
|
||||
keys = list(result.scalars().all())
|
||||
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[ApiKeyResponse.model_validate(k) for k in keys],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=APIResponse[ApiKeyCreateResponse],
|
||||
status_code=201,
|
||||
summary="创建API密钥 / Create API key",
|
||||
dependencies=[Depends(require_admin)],
|
||||
)
|
||||
async def create_key(body: ApiKeyCreate, db: AsyncSession = Depends(get_db)):
|
||||
"""创建新的API密钥。明文密钥仅在创建时返回一次。
|
||||
Create a new API key. The plaintext key is returned only once."""
|
||||
raw_key = _generate_key()
|
||||
key_hash = _hash_key(raw_key)
|
||||
|
||||
db_key = ApiKey(
|
||||
key_hash=key_hash,
|
||||
name=body.name,
|
||||
permissions=body.permissions,
|
||||
)
|
||||
db.add(db_key)
|
||||
await db.flush()
|
||||
await db.refresh(db_key)
|
||||
|
||||
# Build response with plaintext key included (shown once)
|
||||
base_data = ApiKeyResponse.model_validate(db_key).model_dump()
|
||||
base_data["key"] = raw_key
|
||||
response_data = ApiKeyCreateResponse(**base_data)
|
||||
|
||||
return APIResponse(
|
||||
message="API key created. Store the key securely — it won't be shown again. / API密钥已创建,请妥善保管",
|
||||
data=response_data,
|
||||
)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{key_id}",
|
||||
response_model=APIResponse[ApiKeyResponse],
|
||||
summary="更新API密钥 / Update API key",
|
||||
dependencies=[Depends(require_admin)],
|
||||
)
|
||||
async def update_key(
|
||||
key_id: int, body: ApiKeyUpdate, db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""更新API密钥的名称、权限或激活状态 / Update key name, permissions, or active status."""
|
||||
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
|
||||
db_key = result.scalar_one_or_none()
|
||||
if db_key is None:
|
||||
raise HTTPException(status_code=404, detail="API key not found / 未找到密钥")
|
||||
|
||||
update_data = body.model_dump(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_key, field, value)
|
||||
|
||||
await db.flush()
|
||||
await db.refresh(db_key)
|
||||
return APIResponse(
|
||||
message="API key updated / 密钥已更新",
|
||||
data=ApiKeyResponse.model_validate(db_key),
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{key_id}",
|
||||
response_model=APIResponse,
|
||||
summary="停用API密钥 / Deactivate API key",
|
||||
dependencies=[Depends(require_admin)],
|
||||
)
|
||||
async def deactivate_key(key_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""停用API密钥(软删除)/ Deactivate an API key (soft delete)."""
|
||||
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
|
||||
db_key = result.scalar_one_or_none()
|
||||
if db_key is None:
|
||||
raise HTTPException(status_code=404, detail="API key not found / 未找到密钥")
|
||||
|
||||
db_key.is_active = False
|
||||
await db.flush()
|
||||
return APIResponse(message="API key deactivated / 密钥已停用")
|
||||
204
app/routers/attendance.py
Normal file
204
app/routers/attendance.py
Normal file
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
Attendance Router - 考勤管理接口
|
||||
API endpoints for attendance record queries and statistics.
|
||||
"""
|
||||
|
||||
import math
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import AttendanceRecord
|
||||
from app.schemas import (
|
||||
APIResponse,
|
||||
AttendanceRecordResponse,
|
||||
PaginatedList,
|
||||
)
|
||||
from app.services import device_service
|
||||
|
||||
router = APIRouter(prefix="/api/attendance", tags=["Attendance / 考勤管理"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[AttendanceRecordResponse]],
|
||||
summary="获取考勤记录列表 / List attendance records",
|
||||
)
|
||||
async def list_attendance(
|
||||
device_id: int | None = Query(default=None, description="设备ID / Device ID"),
|
||||
attendance_type: str | None = Query(default=None, description="考勤类型 / Attendance type"),
|
||||
start_time: datetime | None = Query(default=None, description="开始时间 / Start time (ISO 8601)"),
|
||||
end_time: datetime | None = Query(default=None, description="结束时间 / End time (ISO 8601)"),
|
||||
page: int = Query(default=1, ge=1, description="页码 / Page number"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量 / Items per page"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取考勤记录列表,支持按设备、考勤类型、时间范围过滤。
|
||||
List attendance records with filters for device, type, and time range.
|
||||
"""
|
||||
query = select(AttendanceRecord)
|
||||
count_query = select(func.count(AttendanceRecord.id))
|
||||
|
||||
if device_id is not None:
|
||||
query = query.where(AttendanceRecord.device_id == device_id)
|
||||
count_query = count_query.where(AttendanceRecord.device_id == device_id)
|
||||
|
||||
if attendance_type:
|
||||
query = query.where(AttendanceRecord.attendance_type == attendance_type)
|
||||
count_query = count_query.where(AttendanceRecord.attendance_type == attendance_type)
|
||||
|
||||
if start_time:
|
||||
query = query.where(AttendanceRecord.recorded_at >= start_time)
|
||||
count_query = count_query.where(AttendanceRecord.recorded_at >= start_time)
|
||||
|
||||
if end_time:
|
||||
query = query.where(AttendanceRecord.recorded_at <= end_time)
|
||||
count_query = count_query.where(AttendanceRecord.recorded_at <= end_time)
|
||||
|
||||
total_result = await db.execute(count_query)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
query = query.order_by(AttendanceRecord.recorded_at.desc()).offset(offset).limit(page_size)
|
||||
result = await db.execute(query)
|
||||
records = list(result.scalars().all())
|
||||
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[AttendanceRecordResponse.model_validate(r) for r in records],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/stats",
|
||||
response_model=APIResponse[dict],
|
||||
summary="获取考勤统计 / Get attendance statistics",
|
||||
)
|
||||
async def attendance_stats(
|
||||
device_id: int | None = Query(default=None, description="设备ID / Device ID (optional)"),
|
||||
start_time: datetime | None = Query(default=None, description="开始时间 / Start time"),
|
||||
end_time: datetime | None = Query(default=None, description="结束时间 / End time"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取考勤统计:总记录数、按类型分组统计、按设备分组统计。
|
||||
Get attendance statistics: total records, breakdown by type and by device.
|
||||
"""
|
||||
base_filter = []
|
||||
if device_id is not None:
|
||||
base_filter.append(AttendanceRecord.device_id == device_id)
|
||||
if start_time:
|
||||
base_filter.append(AttendanceRecord.recorded_at >= start_time)
|
||||
if end_time:
|
||||
base_filter.append(AttendanceRecord.recorded_at <= end_time)
|
||||
|
||||
# Total count
|
||||
total_q = select(func.count(AttendanceRecord.id)).where(*base_filter) if base_filter else select(func.count(AttendanceRecord.id))
|
||||
total_result = await db.execute(total_q)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
# By type
|
||||
type_q = select(
|
||||
AttendanceRecord.attendance_type, func.count(AttendanceRecord.id)
|
||||
).group_by(AttendanceRecord.attendance_type)
|
||||
if base_filter:
|
||||
type_q = type_q.where(*base_filter)
|
||||
type_result = await db.execute(type_q)
|
||||
by_type = {row[0]: row[1] for row in type_result.all()}
|
||||
|
||||
# By device (top 20)
|
||||
device_q = select(
|
||||
AttendanceRecord.device_id, func.count(AttendanceRecord.id)
|
||||
).group_by(AttendanceRecord.device_id).order_by(
|
||||
func.count(AttendanceRecord.id).desc()
|
||||
).limit(20)
|
||||
if base_filter:
|
||||
device_q = device_q.where(*base_filter)
|
||||
device_result = await db.execute(device_q)
|
||||
by_device = {str(row[0]): row[1] for row in device_result.all()}
|
||||
|
||||
return APIResponse(
|
||||
data={
|
||||
"total": total,
|
||||
"by_type": by_type,
|
||||
"by_device": by_device,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/device/{device_id}",
|
||||
response_model=APIResponse[PaginatedList[AttendanceRecordResponse]],
|
||||
summary="获取设备考勤记录 / Get device attendance records",
|
||||
)
|
||||
async def device_attendance(
|
||||
device_id: int,
|
||||
start_time: datetime | None = Query(default=None, description="开始时间 / Start time"),
|
||||
end_time: datetime | None = Query(default=None, description="结束时间 / End time"),
|
||||
page: int = Query(default=1, ge=1, description="页码 / Page number"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量 / Items per page"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取指定设备的考勤记录。
|
||||
Get attendance records for a specific device.
|
||||
"""
|
||||
# Verify device exists
|
||||
device = await device_service.get_device(db, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(status_code=404, detail=f"Device {device_id} not found / 未找到设备{device_id}")
|
||||
|
||||
query = select(AttendanceRecord).where(AttendanceRecord.device_id == device_id)
|
||||
count_query = select(func.count(AttendanceRecord.id)).where(AttendanceRecord.device_id == device_id)
|
||||
|
||||
if start_time:
|
||||
query = query.where(AttendanceRecord.recorded_at >= start_time)
|
||||
count_query = count_query.where(AttendanceRecord.recorded_at >= start_time)
|
||||
|
||||
if end_time:
|
||||
query = query.where(AttendanceRecord.recorded_at <= end_time)
|
||||
count_query = count_query.where(AttendanceRecord.recorded_at <= end_time)
|
||||
|
||||
total_result = await db.execute(count_query)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
query = query.order_by(AttendanceRecord.recorded_at.desc()).offset(offset).limit(page_size)
|
||||
result = await db.execute(query)
|
||||
records = list(result.scalars().all())
|
||||
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[AttendanceRecordResponse.model_validate(r) for r in records],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# NOTE: /{attendance_id} must be after /stats and /device/{device_id} to avoid route conflicts
|
||||
@router.get(
|
||||
"/{attendance_id}",
|
||||
response_model=APIResponse[AttendanceRecordResponse],
|
||||
summary="获取考勤记录详情 / Get attendance record",
|
||||
)
|
||||
async def get_attendance(attendance_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""按ID获取考勤记录详情 / Get attendance record details by ID."""
|
||||
result = await db.execute(
|
||||
select(AttendanceRecord).where(AttendanceRecord.id == attendance_id)
|
||||
)
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None:
|
||||
raise HTTPException(status_code=404, detail=f"Attendance {attendance_id} not found")
|
||||
return APIResponse(data=AttendanceRecordResponse.model_validate(record))
|
||||
104
app/routers/beacons.py
Normal file
104
app/routers/beacons.py
Normal file
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
Beacons Router - 蓝牙信标管理接口
|
||||
API endpoints for managing Bluetooth beacon configuration.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.dependencies import require_write
|
||||
|
||||
from app.database import get_db
|
||||
from app.schemas import (
|
||||
APIResponse,
|
||||
BeaconConfigCreate,
|
||||
BeaconConfigResponse,
|
||||
BeaconConfigUpdate,
|
||||
PaginatedList,
|
||||
)
|
||||
from app.services import beacon_service
|
||||
|
||||
router = APIRouter(prefix="/api/beacons", tags=["Beacons / 蓝牙信标"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[BeaconConfigResponse]],
|
||||
summary="获取信标列表 / List beacons",
|
||||
)
|
||||
async def list_beacons(
|
||||
status: str | None = Query(default=None, description="状态筛选 (active/inactive)"),
|
||||
search: str | None = Query(default=None, description="搜索 MAC/名称/区域"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=100),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
records, total = await beacon_service.get_beacons(
|
||||
db, page=page, page_size=page_size, status_filter=status, search=search
|
||||
)
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[BeaconConfigResponse.model_validate(r) for r in records],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{beacon_id}",
|
||||
response_model=APIResponse[BeaconConfigResponse],
|
||||
summary="获取信标详情 / Get beacon",
|
||||
)
|
||||
async def get_beacon(beacon_id: int, db: AsyncSession = Depends(get_db)):
|
||||
beacon = await beacon_service.get_beacon(db, beacon_id)
|
||||
if beacon is None:
|
||||
raise HTTPException(status_code=404, detail="Beacon not found")
|
||||
return APIResponse(data=BeaconConfigResponse.model_validate(beacon))
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=APIResponse[BeaconConfigResponse],
|
||||
status_code=201,
|
||||
summary="添加信标 / Create beacon",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def create_beacon(body: BeaconConfigCreate, db: AsyncSession = Depends(get_db)):
|
||||
existing = await beacon_service.get_beacon_by_mac(db, body.beacon_mac)
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail=f"Beacon MAC {body.beacon_mac} already exists")
|
||||
beacon = await beacon_service.create_beacon(db, body)
|
||||
return APIResponse(message="Beacon created", data=BeaconConfigResponse.model_validate(beacon))
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{beacon_id}",
|
||||
response_model=APIResponse[BeaconConfigResponse],
|
||||
summary="更新信标 / Update beacon",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def update_beacon(
|
||||
beacon_id: int, body: BeaconConfigUpdate, db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
beacon = await beacon_service.update_beacon(db, beacon_id, body)
|
||||
if beacon is None:
|
||||
raise HTTPException(status_code=404, detail="Beacon not found")
|
||||
return APIResponse(message="Beacon updated", data=BeaconConfigResponse.model_validate(beacon))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{beacon_id}",
|
||||
response_model=APIResponse,
|
||||
summary="删除信标 / Delete beacon",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def delete_beacon(beacon_id: int, db: AsyncSession = Depends(get_db)):
|
||||
success = await beacon_service.delete_beacon(db, beacon_id)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Beacon not found")
|
||||
return APIResponse(message="Beacon deleted")
|
||||
159
app/routers/bluetooth.py
Normal file
159
app/routers/bluetooth.py
Normal file
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
Bluetooth Router - 蓝牙数据接口
|
||||
API endpoints for querying Bluetooth punch and location records.
|
||||
"""
|
||||
|
||||
import math
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import BluetoothRecord
|
||||
from app.schemas import (
|
||||
APIResponse,
|
||||
BluetoothRecordResponse,
|
||||
PaginatedList,
|
||||
)
|
||||
from app.services import device_service
|
||||
|
||||
router = APIRouter(prefix="/api/bluetooth", tags=["Bluetooth / 蓝牙数据"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[BluetoothRecordResponse]],
|
||||
summary="获取蓝牙记录列表 / List bluetooth records",
|
||||
)
|
||||
async def list_bluetooth_records(
|
||||
device_id: int | None = Query(default=None, description="设备ID / Device ID"),
|
||||
record_type: str | None = Query(default=None, description="记录类型 / Record type (punch/location)"),
|
||||
beacon_mac: str | None = Query(default=None, description="信标MAC / Beacon MAC filter"),
|
||||
start_time: datetime | None = Query(default=None, description="开始时间 / Start time (ISO 8601)"),
|
||||
end_time: datetime | None = Query(default=None, description="结束时间 / End time (ISO 8601)"),
|
||||
sort_order: Literal["asc", "desc"] = Query(default="desc", description="排序方向 / Sort order (asc/desc)"),
|
||||
page: int = Query(default=1, ge=1, description="页码 / Page number"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量 / Items per page"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取蓝牙数据记录列表,支持按设备、记录类型、信标MAC、时间范围过滤。
|
||||
List Bluetooth records with filters for device, record type, beacon MAC, and time range.
|
||||
"""
|
||||
query = select(BluetoothRecord)
|
||||
count_query = select(func.count(BluetoothRecord.id))
|
||||
|
||||
if device_id is not None:
|
||||
query = query.where(BluetoothRecord.device_id == device_id)
|
||||
count_query = count_query.where(BluetoothRecord.device_id == device_id)
|
||||
|
||||
if record_type:
|
||||
query = query.where(BluetoothRecord.record_type == record_type)
|
||||
count_query = count_query.where(BluetoothRecord.record_type == record_type)
|
||||
|
||||
if beacon_mac:
|
||||
query = query.where(BluetoothRecord.beacon_mac == beacon_mac)
|
||||
count_query = count_query.where(BluetoothRecord.beacon_mac == beacon_mac)
|
||||
|
||||
if start_time:
|
||||
query = query.where(BluetoothRecord.recorded_at >= start_time)
|
||||
count_query = count_query.where(BluetoothRecord.recorded_at >= start_time)
|
||||
|
||||
if end_time:
|
||||
query = query.where(BluetoothRecord.recorded_at <= end_time)
|
||||
count_query = count_query.where(BluetoothRecord.recorded_at <= end_time)
|
||||
|
||||
total_result = await db.execute(count_query)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
order = BluetoothRecord.recorded_at.asc() if sort_order == "asc" else BluetoothRecord.recorded_at.desc()
|
||||
query = query.order_by(order).offset(offset).limit(page_size)
|
||||
result = await db.execute(query)
|
||||
records = list(result.scalars().all())
|
||||
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[BluetoothRecordResponse.model_validate(r) for r in records],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/device/{device_id}",
|
||||
response_model=APIResponse[PaginatedList[BluetoothRecordResponse]],
|
||||
summary="获取设备蓝牙记录 / Get bluetooth records for device",
|
||||
)
|
||||
async def device_bluetooth_records(
|
||||
device_id: int,
|
||||
record_type: str | None = Query(default=None, description="记录类型 / Record type (punch/location)"),
|
||||
start_time: datetime | None = Query(default=None, description="开始时间 / Start time"),
|
||||
end_time: datetime | None = Query(default=None, description="结束时间 / End time"),
|
||||
page: int = Query(default=1, ge=1, description="页码"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取指定设备的蓝牙数据记录。
|
||||
Get Bluetooth records for a specific device.
|
||||
"""
|
||||
device = await device_service.get_device(db, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(status_code=404, detail=f"Device {device_id} not found / 未找到设备{device_id}")
|
||||
|
||||
query = select(BluetoothRecord).where(BluetoothRecord.device_id == device_id)
|
||||
count_query = select(func.count(BluetoothRecord.id)).where(BluetoothRecord.device_id == device_id)
|
||||
|
||||
if record_type:
|
||||
query = query.where(BluetoothRecord.record_type == record_type)
|
||||
count_query = count_query.where(BluetoothRecord.record_type == record_type)
|
||||
|
||||
if start_time:
|
||||
query = query.where(BluetoothRecord.recorded_at >= start_time)
|
||||
count_query = count_query.where(BluetoothRecord.recorded_at >= start_time)
|
||||
|
||||
if end_time:
|
||||
query = query.where(BluetoothRecord.recorded_at <= end_time)
|
||||
count_query = count_query.where(BluetoothRecord.recorded_at <= end_time)
|
||||
|
||||
total_result = await db.execute(count_query)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
query = query.order_by(BluetoothRecord.recorded_at.desc()).offset(offset).limit(page_size)
|
||||
result = await db.execute(query)
|
||||
records = list(result.scalars().all())
|
||||
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[BluetoothRecordResponse.model_validate(r) for r in records],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# NOTE: /{record_id} must be after /device/{device_id} to avoid route conflicts
|
||||
@router.get(
|
||||
"/{record_id}",
|
||||
response_model=APIResponse[BluetoothRecordResponse],
|
||||
summary="获取蓝牙记录详情 / Get bluetooth record",
|
||||
)
|
||||
async def get_bluetooth_record(record_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""按ID获取蓝牙记录详情 / Get bluetooth record details by ID."""
|
||||
result = await db.execute(
|
||||
select(BluetoothRecord).where(BluetoothRecord.id == record_id)
|
||||
)
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None:
|
||||
raise HTTPException(status_code=404, detail=f"Bluetooth record {record_id} not found")
|
||||
return APIResponse(data=BluetoothRecordResponse.model_validate(record))
|
||||
330
app/routers/commands.py
Normal file
330
app/routers/commands.py
Normal file
@@ -0,0 +1,330 @@
|
||||
"""
|
||||
Commands Router - 指令管理接口
|
||||
API endpoints for sending commands / messages to devices and viewing command history.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.config import settings
|
||||
from app.extensions import limiter
|
||||
from app.schemas import (
|
||||
APIResponse,
|
||||
BatchCommandRequest,
|
||||
BatchCommandResponse,
|
||||
BatchCommandResult,
|
||||
CommandResponse,
|
||||
PaginatedList,
|
||||
)
|
||||
from app.dependencies import require_write
|
||||
from app.services import command_service, device_service
|
||||
from app.services import tcp_command_service
|
||||
|
||||
router = APIRouter(prefix="/api/commands", tags=["Commands / 指令管理"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Request schemas specific to this router
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class SendCommandRequest(BaseModel):
|
||||
"""Request body for sending a command to a device."""
|
||||
device_id: int | None = Field(None, description="设备ID / Device ID (provide device_id or imei)")
|
||||
imei: str | None = Field(None, description="IMEI号 / IMEI number (provide device_id or imei)")
|
||||
command_type: str = Field(..., max_length=30, description="指令类型 / Command type (e.g. online_cmd)")
|
||||
command_content: str = Field(..., max_length=500, description="指令内容 / Command content")
|
||||
|
||||
|
||||
class SendMessageRequest(BaseModel):
|
||||
"""Request body for sending a message (0x82) to a device."""
|
||||
device_id: int | None = Field(None, description="设备ID / Device ID (provide device_id or imei)")
|
||||
imei: str | None = Field(None, description="IMEI号 / IMEI number (provide device_id or imei)")
|
||||
message: str = Field(..., max_length=500, description="消息内容 / Message content")
|
||||
|
||||
|
||||
class SendTTSRequest(BaseModel):
|
||||
"""Request body for sending a TTS voice broadcast to a device."""
|
||||
device_id: int | None = Field(None, description="设备ID / Device ID (provide device_id or imei)")
|
||||
imei: str | None = Field(None, description="IMEI号 / IMEI number (provide device_id or imei)")
|
||||
text: str = Field(..., min_length=1, max_length=200, description="语音播报文本 / TTS text content")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _resolve_device(
|
||||
db: AsyncSession,
|
||||
device_id: int | None,
|
||||
imei: str | None,
|
||||
):
|
||||
"""Resolve a device from either device_id or imei. Returns the Device ORM instance."""
|
||||
if device_id is None and imei is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Either device_id or imei must be provided / 必须提供 device_id 或 imei",
|
||||
)
|
||||
|
||||
if device_id is not None:
|
||||
device = await device_service.get_device(db, device_id)
|
||||
else:
|
||||
device = await device_service.get_device_by_imei(db, imei)
|
||||
|
||||
if device is None:
|
||||
identifier = f"ID={device_id}" if device_id else f"IMEI={imei}"
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Device {identifier} not found / 未找到设备 {identifier}",
|
||||
)
|
||||
return device
|
||||
|
||||
|
||||
async def _send_to_device(
|
||||
db: AsyncSession,
|
||||
device,
|
||||
command_type: str,
|
||||
command_content: str,
|
||||
executor,
|
||||
success_msg: str,
|
||||
fail_msg: str,
|
||||
):
|
||||
"""Common logic for sending command/message/tts to a device via TCP.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
executor : async callable
|
||||
The actual send function, e.g. tcp_command_service.send_command(...)
|
||||
"""
|
||||
if not tcp_command_service.is_device_online(device.imei):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Device {device.imei} is not online / 设备 {device.imei} 不在线",
|
||||
)
|
||||
|
||||
command_log = await command_service.create_command(
|
||||
db,
|
||||
device_id=device.id,
|
||||
command_type=command_type,
|
||||
command_content=command_content,
|
||||
)
|
||||
|
||||
try:
|
||||
await executor()
|
||||
except Exception as e:
|
||||
logging.getLogger(__name__).error("Command send failed: %s", e)
|
||||
command_log.status = "failed"
|
||||
await db.flush()
|
||||
await db.refresh(command_log)
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=fail_msg,
|
||||
)
|
||||
|
||||
command_log.status = "sent"
|
||||
command_log.sent_at = datetime.now(timezone.utc)
|
||||
await db.flush()
|
||||
await db.refresh(command_log)
|
||||
|
||||
return APIResponse(
|
||||
message=success_msg,
|
||||
data=CommandResponse.model_validate(command_log),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[CommandResponse]],
|
||||
summary="获取指令历史 / List command history",
|
||||
)
|
||||
async def list_commands(
|
||||
device_id: int | None = Query(default=None, description="设备ID / Device ID"),
|
||||
command_type: str | None = Query(default=None, description="指令类型 / Command type (online_cmd/message/tts)"),
|
||||
status: str | None = Query(default=None, description="指令状态 / Command status (pending/sent/success/failed)"),
|
||||
page: int = Query(default=1, ge=1, description="页码 / Page number"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量 / Items per page"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取指令历史记录,支持按设备、指令类型和状态过滤。
|
||||
List command history with optional device, command type and status filters.
|
||||
"""
|
||||
commands, total = await command_service.get_commands(
|
||||
db, device_id=device_id, command_type=command_type, status=status, page=page, page_size=page_size
|
||||
)
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[CommandResponse.model_validate(c) for c in commands],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/send",
|
||||
response_model=APIResponse[CommandResponse],
|
||||
status_code=201,
|
||||
summary="发送指令 / Send command to device",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def send_command(body: SendCommandRequest, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
向设备发送指令(通过TCP连接下发)。
|
||||
Send a command to a device via the TCP connection.
|
||||
Requires the device to be online.
|
||||
"""
|
||||
device = await _resolve_device(db, body.device_id, body.imei)
|
||||
return await _send_to_device(
|
||||
db, device,
|
||||
command_type=body.command_type,
|
||||
command_content=body.command_content,
|
||||
executor=lambda: tcp_command_service.send_command(
|
||||
device.imei, body.command_type, body.command_content
|
||||
),
|
||||
success_msg="Command sent successfully / 指令发送成功",
|
||||
fail_msg="Failed to send command / 指令发送失败",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/message",
|
||||
response_model=APIResponse[CommandResponse],
|
||||
status_code=201,
|
||||
summary="发送留言 / Send message to device (0x82)",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def send_message(body: SendMessageRequest, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
向设备发送留言消息(协议号 0x82)。
|
||||
Send a text message to a device using protocol 0x82.
|
||||
"""
|
||||
device = await _resolve_device(db, body.device_id, body.imei)
|
||||
return await _send_to_device(
|
||||
db, device,
|
||||
command_type="message",
|
||||
command_content=body.message,
|
||||
executor=lambda: tcp_command_service.send_message(device.imei, body.message),
|
||||
success_msg="Message sent successfully / 留言发送成功",
|
||||
fail_msg="Failed to send message / 留言发送失败",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/tts",
|
||||
response_model=APIResponse[CommandResponse],
|
||||
status_code=201,
|
||||
summary="语音下发 / Send TTS voice broadcast to device",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def send_tts(body: SendTTSRequest, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
向设备发送 TTS 语音播报(通过 0x80 在线指令,TTS 命令格式)。
|
||||
Send a TTS voice broadcast to a device via online command (0x80).
|
||||
The device will use its built-in TTS engine to speak the text aloud.
|
||||
"""
|
||||
device = await _resolve_device(db, body.device_id, body.imei)
|
||||
tts_command = f"TTS,{body.text}"
|
||||
return await _send_to_device(
|
||||
db, device,
|
||||
command_type="tts",
|
||||
command_content=tts_command,
|
||||
executor=lambda: tcp_command_service.send_command(
|
||||
device.imei, "tts", tts_command
|
||||
),
|
||||
success_msg="TTS sent successfully / 语音下发成功",
|
||||
fail_msg="Failed to send TTS / 语音下发失败",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch",
|
||||
response_model=APIResponse[BatchCommandResponse],
|
||||
status_code=201,
|
||||
summary="批量发送指令 / Batch send command to multiple devices",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
@limiter.limit(settings.RATE_LIMIT_WRITE)
|
||||
async def batch_send_command(request: Request, body: BatchCommandRequest, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
向多台设备批量发送同一指令,最多100台。
|
||||
Send the same command to multiple devices (up to 100). Skips offline devices.
|
||||
"""
|
||||
# Resolve devices in single query (mutual exclusion validated by schema)
|
||||
if body.device_ids:
|
||||
devices = await device_service.get_devices_by_ids(db, body.device_ids)
|
||||
else:
|
||||
devices = await device_service.get_devices_by_imeis(db, body.imeis)
|
||||
|
||||
results = []
|
||||
for device in devices:
|
||||
if not tcp_command_service.is_device_online(device.imei):
|
||||
results.append(BatchCommandResult(
|
||||
device_id=device.id, imei=device.imei,
|
||||
success=False, error="Device offline",
|
||||
))
|
||||
continue
|
||||
|
||||
try:
|
||||
cmd_log = await command_service.create_command(
|
||||
db,
|
||||
device_id=device.id,
|
||||
command_type=body.command_type,
|
||||
command_content=body.command_content,
|
||||
)
|
||||
await tcp_command_service.send_command(
|
||||
device.imei, body.command_type, body.command_content
|
||||
)
|
||||
cmd_log.status = "sent"
|
||||
cmd_log.sent_at = datetime.now(timezone.utc)
|
||||
await db.flush()
|
||||
await db.refresh(cmd_log)
|
||||
results.append(BatchCommandResult(
|
||||
device_id=device.id, imei=device.imei,
|
||||
success=True, command_id=cmd_log.id,
|
||||
))
|
||||
except Exception as e:
|
||||
logging.getLogger(__name__).error("Batch cmd failed for %s: %s", device.imei, e)
|
||||
results.append(BatchCommandResult(
|
||||
device_id=device.id, imei=device.imei,
|
||||
success=False, error="Send failed",
|
||||
))
|
||||
|
||||
sent = sum(1 for r in results if r.success)
|
||||
failed = len(results) - sent
|
||||
return APIResponse(
|
||||
message=f"Batch command: {sent} sent, {failed} failed",
|
||||
data=BatchCommandResponse(
|
||||
total=len(results), sent=sent, failed=failed, results=results,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{command_id}",
|
||||
response_model=APIResponse[CommandResponse],
|
||||
summary="获取指令详情 / Get command details",
|
||||
)
|
||||
async def get_command(command_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
按ID获取指令详情。
|
||||
Get command log details by ID.
|
||||
"""
|
||||
command = await command_service.get_command(db, command_id)
|
||||
if command is None:
|
||||
raise HTTPException(status_code=404, detail=f"Command {command_id} not found / 未找到指令{command_id}")
|
||||
return APIResponse(data=CommandResponse.model_validate(command))
|
||||
253
app/routers/devices.py
Normal file
253
app/routers/devices.py
Normal file
@@ -0,0 +1,253 @@
|
||||
"""
|
||||
Devices Router - 设备管理接口
|
||||
API endpoints for device CRUD operations and statistics.
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.schemas import (
|
||||
APIResponse,
|
||||
BatchDeviceCreateRequest,
|
||||
BatchDeviceCreateResponse,
|
||||
BatchDeviceCreateResult,
|
||||
BatchDeviceDeleteRequest,
|
||||
BatchDeviceUpdateRequest,
|
||||
DeviceCreate,
|
||||
DeviceResponse,
|
||||
DeviceUpdate,
|
||||
PaginatedList,
|
||||
)
|
||||
from app.config import settings
|
||||
from app.dependencies import require_write
|
||||
from app.extensions import limiter
|
||||
from app.schemas import LocationRecordResponse
|
||||
from app.services import device_service, location_service
|
||||
|
||||
router = APIRouter(prefix="/api/devices", tags=["Devices / 设备管理"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[DeviceResponse]],
|
||||
summary="获取设备列表 / List devices",
|
||||
)
|
||||
async def list_devices(
|
||||
page: int = Query(default=1, ge=1, description="页码 / Page number"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量 / Items per page"),
|
||||
status: str | None = Query(default=None, description="状态过滤 / Status filter (online/offline)"),
|
||||
search: str | None = Query(default=None, description="搜索IMEI或名称 / Search by IMEI or name"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取设备列表,支持分页、状态过滤和搜索。
|
||||
List devices with pagination, optional status filter, and search.
|
||||
"""
|
||||
devices, total = await device_service.get_devices(
|
||||
db, page=page, page_size=page_size, status_filter=status, search=search
|
||||
)
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[DeviceResponse.model_validate(d) for d in devices],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/stats",
|
||||
response_model=APIResponse[dict],
|
||||
summary="获取设备统计 / Get device statistics",
|
||||
)
|
||||
async def device_stats(db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
获取设备统计信息:总数、在线、离线。
|
||||
Get device statistics: total, online, offline counts.
|
||||
"""
|
||||
stats = await device_service.get_device_stats(db)
|
||||
return APIResponse(data=stats)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/imei/{imei}",
|
||||
response_model=APIResponse[DeviceResponse],
|
||||
summary="按IMEI查询设备 / Get device by IMEI",
|
||||
)
|
||||
async def get_device_by_imei(imei: str, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
按IMEI号查询设备信息。
|
||||
Get device details by IMEI number.
|
||||
"""
|
||||
device = await device_service.get_device_by_imei(db, imei)
|
||||
if device is None:
|
||||
raise HTTPException(status_code=404, detail=f"Device with IMEI {imei} not found / 未找到IMEI为{imei}的设备")
|
||||
return APIResponse(data=DeviceResponse.model_validate(device))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/all-latest-locations",
|
||||
response_model=APIResponse[list[LocationRecordResponse]],
|
||||
summary="获取所有在线设备位置 / Get all online device locations",
|
||||
)
|
||||
async def all_latest_locations(db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
获取所有在线设备的最新位置,用于地图总览。
|
||||
Get latest location for all online devices, for map overview.
|
||||
"""
|
||||
records = await location_service.get_all_online_latest_locations(db)
|
||||
return APIResponse(data=[LocationRecordResponse.model_validate(r) for r in records])
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch",
|
||||
response_model=APIResponse[BatchDeviceCreateResponse],
|
||||
status_code=201,
|
||||
summary="批量创建设备 / Batch create devices",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
@limiter.limit(settings.RATE_LIMIT_WRITE)
|
||||
async def batch_create_devices(request: Request, body: BatchDeviceCreateRequest, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
批量注册设备(最多500台),跳过IMEI重复的设备。
|
||||
Batch register devices (up to 500). Skips devices with duplicate IMEIs.
|
||||
"""
|
||||
results = await device_service.batch_create_devices(db, body.devices)
|
||||
created = sum(1 for r in results if r["success"])
|
||||
failed = len(results) - created
|
||||
return APIResponse(
|
||||
message=f"Batch create: {created} created, {failed} failed",
|
||||
data=BatchDeviceCreateResponse(
|
||||
total=len(results),
|
||||
created=created,
|
||||
failed=failed,
|
||||
results=[BatchDeviceCreateResult(**r) for r in results],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/batch",
|
||||
response_model=APIResponse[dict],
|
||||
summary="批量更新设备 / Batch update devices",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
@limiter.limit(settings.RATE_LIMIT_WRITE)
|
||||
async def batch_update_devices(request: Request, body: BatchDeviceUpdateRequest, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
批量更新设备信息(名称、状态等),最多500台。
|
||||
Batch update device fields (name, status, etc.) for up to 500 devices.
|
||||
"""
|
||||
results = await device_service.batch_update_devices(db, body.device_ids, body.update)
|
||||
updated = sum(1 for r in results if r["success"])
|
||||
failed = len(results) - updated
|
||||
return APIResponse(
|
||||
message=f"Batch update: {updated} updated, {failed} failed",
|
||||
data={"total": len(results), "updated": updated, "failed": failed, "results": results},
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-delete",
|
||||
response_model=APIResponse[dict],
|
||||
summary="批量删除设备 / Batch delete devices",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
@limiter.limit(settings.RATE_LIMIT_WRITE)
|
||||
async def batch_delete_devices(
|
||||
request: Request,
|
||||
body: BatchDeviceDeleteRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
批量删除设备(最多100台)。通过 POST body 传递 device_ids 列表。
|
||||
Batch delete devices (up to 100). Pass device_ids in request body.
|
||||
"""
|
||||
results = await device_service.batch_delete_devices(db, body.device_ids)
|
||||
deleted = sum(1 for r in results if r["success"])
|
||||
failed = len(results) - deleted
|
||||
return APIResponse(
|
||||
message=f"Batch delete: {deleted} deleted, {failed} failed",
|
||||
data={"total": len(results), "deleted": deleted, "failed": failed, "results": results},
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{device_id}",
|
||||
response_model=APIResponse[DeviceResponse],
|
||||
summary="获取设备详情 / Get device details",
|
||||
)
|
||||
async def get_device(device_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
按ID获取设备详细信息。
|
||||
Get device details by ID.
|
||||
"""
|
||||
device = await device_service.get_device(db, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(status_code=404, detail=f"Device {device_id} not found / 未找到设备{device_id}")
|
||||
return APIResponse(data=DeviceResponse.model_validate(device))
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=APIResponse[DeviceResponse],
|
||||
status_code=201,
|
||||
summary="创建设备 / Create device",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def create_device(device_data: DeviceCreate, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
手动注册新设备。
|
||||
Manually register a new device.
|
||||
"""
|
||||
# Check for duplicate IMEI
|
||||
existing = await device_service.get_device_by_imei(db, device_data.imei)
|
||||
if existing is not None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Device with IMEI {device_data.imei} already exists / IMEI {device_data.imei} 已存在",
|
||||
)
|
||||
|
||||
device = await device_service.create_device(db, device_data)
|
||||
return APIResponse(data=DeviceResponse.model_validate(device))
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{device_id}",
|
||||
response_model=APIResponse[DeviceResponse],
|
||||
summary="更新设备信息 / Update device",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def update_device(
|
||||
device_id: int, device_data: DeviceUpdate, db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
更新设备信息(名称、状态等)。
|
||||
Update device information (name, status, etc.).
|
||||
"""
|
||||
device = await device_service.update_device(db, device_id, device_data)
|
||||
if device is None:
|
||||
raise HTTPException(status_code=404, detail=f"Device {device_id} not found / 未找到设备{device_id}")
|
||||
return APIResponse(data=DeviceResponse.model_validate(device))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{device_id}",
|
||||
response_model=APIResponse,
|
||||
summary="删除设备 / Delete device",
|
||||
dependencies=[Depends(require_write)],
|
||||
)
|
||||
async def delete_device(device_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
删除设备及其关联数据。
|
||||
Delete a device and all associated records.
|
||||
"""
|
||||
deleted = await device_service.delete_device(db, device_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail=f"Device {device_id} not found / 未找到设备{device_id}")
|
||||
return APIResponse(message="Device deleted successfully / 设备删除成功")
|
||||
55
app/routers/geocoding.py
Normal file
55
app/routers/geocoding.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""Geocoding proxy endpoints — keeps AMAP_KEY server-side."""
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
import httpx
|
||||
|
||||
from app.config import settings
|
||||
from app.geocoding import reverse_geocode, _amap_sign, AMAP_KEY
|
||||
|
||||
router = APIRouter(prefix="/api/geocode", tags=["geocoding"])
|
||||
|
||||
|
||||
@router.get("/search")
|
||||
async def search_location(
|
||||
keyword: str = Query(..., min_length=1, max_length=100),
|
||||
city: str = Query(default="", max_length=50),
|
||||
):
|
||||
"""Proxy for Amap POI text search. Returns GCJ-02 coordinates."""
|
||||
if not AMAP_KEY:
|
||||
return {"results": []}
|
||||
params = {
|
||||
"key": AMAP_KEY,
|
||||
"keywords": keyword,
|
||||
"output": "json",
|
||||
"offset": "10",
|
||||
"page": "1",
|
||||
}
|
||||
if city:
|
||||
params["city"] = city
|
||||
sig = _amap_sign(params)
|
||||
if sig:
|
||||
params["sig"] = sig
|
||||
async with httpx.AsyncClient(timeout=5.0) as client:
|
||||
resp = await client.get("https://restapi.amap.com/v3/place/text", params=params)
|
||||
data = resp.json()
|
||||
if data.get("status") != "1":
|
||||
return {"results": []}
|
||||
results = []
|
||||
for poi in data.get("pois", [])[:10]:
|
||||
if poi.get("location"):
|
||||
results.append({
|
||||
"name": poi.get("name", ""),
|
||||
"address": poi.get("address", ""),
|
||||
"location": poi["location"], # "lng,lat" in GCJ-02
|
||||
})
|
||||
return {"results": results}
|
||||
|
||||
|
||||
@router.get("/reverse")
|
||||
async def reverse_geocode_endpoint(
|
||||
lat: float = Query(..., ge=-90, le=90),
|
||||
lon: float = Query(..., ge=-180, le=180),
|
||||
):
|
||||
"""Reverse geocode WGS-84 coords to address via Amap."""
|
||||
address = await reverse_geocode(lat, lon)
|
||||
return {"address": address or ""}
|
||||
92
app/routers/heartbeats.py
Normal file
92
app/routers/heartbeats.py
Normal file
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
Heartbeats Router - 心跳数据接口
|
||||
API endpoints for querying device heartbeat records.
|
||||
"""
|
||||
|
||||
import math
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import HeartbeatRecord
|
||||
from app.schemas import (
|
||||
APIResponse,
|
||||
HeartbeatRecordResponse,
|
||||
PaginatedList,
|
||||
)
|
||||
from app.services import device_service
|
||||
|
||||
router = APIRouter(prefix="/api/heartbeats", tags=["Heartbeats / 心跳数据"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[HeartbeatRecordResponse]],
|
||||
summary="获取心跳记录列表 / List heartbeat records",
|
||||
)
|
||||
async def list_heartbeats(
|
||||
device_id: int | None = Query(default=None, description="设备ID / Device ID"),
|
||||
start_time: datetime | None = Query(default=None, description="开始时间 / Start time (ISO 8601)"),
|
||||
end_time: datetime | None = Query(default=None, description="结束时间 / End time (ISO 8601)"),
|
||||
page: int = Query(default=1, ge=1, description="页码 / Page number"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量 / Items per page"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取心跳记录列表,支持按设备和时间范围过滤。
|
||||
List heartbeat records with optional device and time range filters.
|
||||
"""
|
||||
query = select(HeartbeatRecord)
|
||||
count_query = select(func.count(HeartbeatRecord.id))
|
||||
|
||||
if device_id is not None:
|
||||
query = query.where(HeartbeatRecord.device_id == device_id)
|
||||
count_query = count_query.where(HeartbeatRecord.device_id == device_id)
|
||||
|
||||
if start_time:
|
||||
query = query.where(HeartbeatRecord.created_at >= start_time)
|
||||
count_query = count_query.where(HeartbeatRecord.created_at >= start_time)
|
||||
|
||||
if end_time:
|
||||
query = query.where(HeartbeatRecord.created_at <= end_time)
|
||||
count_query = count_query.where(HeartbeatRecord.created_at <= end_time)
|
||||
|
||||
total_result = await db.execute(count_query)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
query = query.order_by(HeartbeatRecord.created_at.desc()).offset(offset).limit(page_size)
|
||||
result = await db.execute(query)
|
||||
records = list(result.scalars().all())
|
||||
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[HeartbeatRecordResponse.model_validate(r) for r in records],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{heartbeat_id}",
|
||||
response_model=APIResponse[HeartbeatRecordResponse],
|
||||
summary="获取心跳详情 / Get heartbeat details",
|
||||
)
|
||||
async def get_heartbeat(heartbeat_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
按ID获取心跳记录详情。
|
||||
Get heartbeat record details by ID.
|
||||
"""
|
||||
result = await db.execute(
|
||||
select(HeartbeatRecord).where(HeartbeatRecord.id == heartbeat_id)
|
||||
)
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None:
|
||||
raise HTTPException(status_code=404, detail=f"Heartbeat {heartbeat_id} not found")
|
||||
return APIResponse(data=HeartbeatRecordResponse.model_validate(record))
|
||||
155
app/routers/locations.py
Normal file
155
app/routers/locations.py
Normal file
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
Locations Router - 位置数据接口
|
||||
API endpoints for querying location records and device tracks.
|
||||
"""
|
||||
|
||||
import math
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import LocationRecord
|
||||
from app.schemas import (
|
||||
APIResponse,
|
||||
LocationRecordResponse,
|
||||
PaginatedList,
|
||||
)
|
||||
from app.services import device_service, location_service
|
||||
|
||||
router = APIRouter(prefix="/api/locations", tags=["Locations / 位置数据"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=APIResponse[PaginatedList[LocationRecordResponse]],
|
||||
summary="获取位置记录列表 / List location records",
|
||||
)
|
||||
async def list_locations(
|
||||
device_id: int | None = Query(default=None, description="设备ID / Device ID"),
|
||||
location_type: str | None = Query(default=None, description="定位类型 / Location type (gps/lbs/wifi)"),
|
||||
start_time: datetime | None = Query(default=None, description="开始时间 / Start time (ISO 8601)"),
|
||||
end_time: datetime | None = Query(default=None, description="结束时间 / End time (ISO 8601)"),
|
||||
page: int = Query(default=1, ge=1, description="页码 / Page number"),
|
||||
page_size: int = Query(default=20, ge=1, le=100, description="每页数量 / Items per page"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取位置记录列表,支持按设备、定位类型、时间范围过滤。
|
||||
List location records with filters for device, location type, and time range.
|
||||
"""
|
||||
records, total = await location_service.get_locations(
|
||||
db,
|
||||
device_id=device_id,
|
||||
location_type=location_type,
|
||||
start_time=start_time,
|
||||
end_time=end_time,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return APIResponse(
|
||||
data=PaginatedList(
|
||||
items=[LocationRecordResponse.model_validate(r) for r in records],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=math.ceil(total / page_size) if total else 0,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/latest/{device_id}",
|
||||
response_model=APIResponse[LocationRecordResponse | None],
|
||||
summary="获取设备最新位置 / Get latest location",
|
||||
)
|
||||
async def latest_location(device_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""
|
||||
获取指定设备的最新位置信息。
|
||||
Get the most recent location record for a device.
|
||||
"""
|
||||
# Verify device exists
|
||||
device = await device_service.get_device(db, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(status_code=404, detail=f"Device {device_id} not found / 未找到设备{device_id}")
|
||||
|
||||
record = await location_service.get_latest_location(db, device_id)
|
||||
if record is None:
|
||||
return APIResponse(
|
||||
code=0,
|
||||
message="No location data available / 暂无位置数据",
|
||||
data=None,
|
||||
)
|
||||
return APIResponse(data=LocationRecordResponse.model_validate(record))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-latest",
|
||||
response_model=APIResponse[list[LocationRecordResponse | None]],
|
||||
summary="批量获取设备最新位置 / Batch get latest locations",
|
||||
)
|
||||
async def batch_latest_locations(
|
||||
device_ids: list[int] = Body(..., min_length=1, max_length=100, embed=True),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
传入 device_ids 列表,返回每台设备的最新位置(按输入顺序)。
|
||||
Pass device_ids list, returns latest location per device in input order.
|
||||
"""
|
||||
records = await location_service.get_batch_latest_locations(db, device_ids)
|
||||
result_map = {r.device_id: r for r in records}
|
||||
return APIResponse(data=[
|
||||
LocationRecordResponse.model_validate(result_map[did]) if did in result_map else None
|
||||
for did in device_ids
|
||||
])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/track/{device_id}",
|
||||
response_model=APIResponse[list[LocationRecordResponse]],
|
||||
summary="获取设备轨迹 / Get device track",
|
||||
)
|
||||
async def device_track(
|
||||
device_id: int,
|
||||
start_time: datetime = Query(..., description="开始时间 / Start time (ISO 8601)"),
|
||||
end_time: datetime = Query(..., description="结束时间 / End time (ISO 8601)"),
|
||||
max_points: int = Query(default=10000, ge=1, le=50000, description="最大轨迹点数 / Max track points"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
获取设备在指定时间范围内的运动轨迹(按时间正序排列)。
|
||||
Get device movement track within a time range (ordered chronologically).
|
||||
"""
|
||||
# Verify device exists
|
||||
device = await device_service.get_device(db, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(status_code=404, detail=f"Device {device_id} not found / 未找到设备{device_id}")
|
||||
|
||||
if start_time >= end_time:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="start_time must be before end_time / 开始时间必须早于结束时间",
|
||||
)
|
||||
|
||||
records = await location_service.get_device_track(db, device_id, start_time, end_time, max_points=max_points)
|
||||
return APIResponse(
|
||||
data=[LocationRecordResponse.model_validate(r) for r in records]
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{location_id}",
|
||||
response_model=APIResponse[LocationRecordResponse],
|
||||
summary="获取位置记录详情 / Get location record",
|
||||
)
|
||||
async def get_location(location_id: int, db: AsyncSession = Depends(get_db)):
|
||||
"""按ID获取位置记录详情 / Get location record details by ID."""
|
||||
result = await db.execute(
|
||||
select(LocationRecord).where(LocationRecord.id == location_id)
|
||||
)
|
||||
record = result.scalar_one_or_none()
|
||||
if record is None:
|
||||
raise HTTPException(status_code=404, detail=f"Location {location_id} not found")
|
||||
return APIResponse(data=LocationRecordResponse.model_validate(record))
|
||||
81
app/routers/ws.py
Normal file
81
app/routers/ws.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
WebSocket Router - WebSocket 实时推送接口
|
||||
Real-time data push via WebSocket with topic subscriptions.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
|
||||
from fastapi import APIRouter, Query, WebSocket, WebSocketDisconnect
|
||||
|
||||
from app.config import settings
|
||||
from app.websocket_manager import ws_manager, VALID_TOPICS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["WebSocket / 实时推送"])
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def websocket_endpoint(
|
||||
websocket: WebSocket,
|
||||
api_key: str | None = Query(default=None, alias="api_key"),
|
||||
topics: str | None = Query(default=None, description="Comma-separated topics"),
|
||||
):
|
||||
"""
|
||||
WebSocket endpoint for real-time data push.
|
||||
|
||||
Connect: ws://host/ws?api_key=xxx&topics=location,alarm
|
||||
Topics: location, alarm, device_status, attendance, bluetooth
|
||||
If no topics specified, subscribes to all.
|
||||
"""
|
||||
# Authenticate
|
||||
if settings.API_KEY is not None:
|
||||
if api_key is None or not secrets.compare_digest(api_key, settings.API_KEY):
|
||||
# For DB keys, do a simple hash check
|
||||
if api_key is not None:
|
||||
from app.dependencies import _hash_key
|
||||
from app.database import async_session
|
||||
from sqlalchemy import select
|
||||
from app.models import ApiKey
|
||||
|
||||
try:
|
||||
async with async_session() as session:
|
||||
key_hash = _hash_key(api_key)
|
||||
result = await session.execute(
|
||||
select(ApiKey.id).where(
|
||||
ApiKey.key_hash == key_hash,
|
||||
ApiKey.is_active == True, # noqa: E712
|
||||
)
|
||||
)
|
||||
if result.scalar_one_or_none() is None:
|
||||
await websocket.close(code=4001, reason="Invalid API key")
|
||||
return
|
||||
except Exception:
|
||||
await websocket.close(code=4001, reason="Auth error")
|
||||
return
|
||||
else:
|
||||
await websocket.close(code=4001, reason="Missing API key")
|
||||
return
|
||||
|
||||
# Parse topics
|
||||
requested_topics = set()
|
||||
if topics:
|
||||
requested_topics = {t.strip() for t in topics.split(",") if t.strip() in VALID_TOPICS}
|
||||
|
||||
if not await ws_manager.connect(websocket, requested_topics):
|
||||
return
|
||||
|
||||
try:
|
||||
# Keep connection alive, handle pings
|
||||
while True:
|
||||
data = await websocket.receive_text()
|
||||
# Client can send "ping" to keep alive
|
||||
if data.strip().lower() == "ping":
|
||||
await websocket.send_text("pong")
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except Exception:
|
||||
logger.debug("WebSocket connection error", exc_info=True)
|
||||
finally:
|
||||
ws_manager.disconnect(websocket)
|
||||
Reference in New Issue
Block a user