feat: add project-scoped operations
This commit is contained in:
@@ -4,6 +4,7 @@ from datetime import datetime
|
||||
from psycopg import AsyncConnection
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from app.domain.schemas.scada import ScadaLatestReadingsResponse
|
||||
from app.infra.db.postgresql.scada import ScadaInfoRepository
|
||||
from app.infra.db.timescaledb.repositories.scada import ScadaRepository
|
||||
from .dependencies import get_postgres_connection, get_timescale_connection
|
||||
@@ -96,6 +97,54 @@ async def get_scada_by_ids_time_range(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/timeseries/scada-readings/latest",
|
||||
response_model=ScadaLatestReadingsResponse,
|
||||
summary="获取SCADA设备最新数据",
|
||||
)
|
||||
async def get_latest_scada_readings(
|
||||
limit: int = Query(100, ge=1, le=500, description="返回设备数上限"),
|
||||
offset: int = Query(0, ge=0, description="设备目录偏移量"),
|
||||
conn: AsyncConnection = Depends(get_timescale_connection),
|
||||
postgres_conn: AsyncConnection = Depends(get_postgres_connection),
|
||||
) -> ScadaLatestReadingsResponse:
|
||||
"""Read one latest persisted row per project device without applying a time window."""
|
||||
devices = await ScadaInfoRepository.get_scadas(postgres_conn)
|
||||
selected_devices = devices[offset : offset + limit]
|
||||
latest_by_device = await ScadaRepository.get_latest_scada_readings(
|
||||
conn,
|
||||
[device["device_id"] for device in selected_devices],
|
||||
)
|
||||
|
||||
items = []
|
||||
for device in selected_devices:
|
||||
reading = latest_by_device.get(device["device_id"])
|
||||
items.append(
|
||||
{
|
||||
"device_id": device["device_id"],
|
||||
"device_type": device["device_type"],
|
||||
"measurement_unit": device["measurement_unit"],
|
||||
"transmission_mode": device["transmission_mode"],
|
||||
"transmission_frequency": device["transmission_frequency"],
|
||||
"observed_at": reading["time"] if reading else None,
|
||||
"monitored_value": reading["monitored_value"] if reading else None,
|
||||
"cleaned_value": reading["cleaned_value"] if reading else None,
|
||||
}
|
||||
)
|
||||
|
||||
observed_times = [item["observed_at"] for item in items if item["observed_at"] is not None]
|
||||
return ScadaLatestReadingsResponse.model_validate(
|
||||
{
|
||||
"items": items,
|
||||
"total": len(devices),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"observed_count": len(observed_times),
|
||||
"latest_observed_at": max(observed_times) if observed_times else None,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/timeseries/scada-readings/fields", summary="按设备ID、字段和时间范围查询SCADA数据"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user