Files
chongming-plugins/aibox_sophon_adapter/router/get_offline_devices.py
T

57 lines
2.0 KiB
Python
Raw Normal View History

2026-07-27 14:28:07 +08:00
"""
查询离线/异常设备 — GET /aibox/get_offline_devices
"""
import json
import logging
from datetime import datetime
from chongming_worker import rpc_method
logger = logging.getLogger(__name__)
@rpc_method(
subject="aibox_sophon_adapter.get_offline_devices",
method="GET",
summary="查询离线/异常设备列表",
)
async def get_offline_devices(worker_id: str = "") -> dict:
"""返回所有超过心跳超时时间未上报的设备列表"""
from ..global_var import db, heartbeat_timeout
offline_devices = []
try:
if db is None:
raise RuntimeError("Database not initialized")
2026-07-27 14:28:07 +08:00
async with db.get_session() as session:
from ..models.orm import BoardHeartbeat
from sqlalchemy import desc, select
2026-07-27 14:28:07 +08:00
stmt = select(BoardHeartbeat).order_by(desc(BoardHeartbeat.last_ping_time)) # type: ignore
2026-07-27 14:28:07 +08:00
result = await session.execute(stmt)
records = result.scalars().all()
now = datetime.now()
for record in records:
elapsed = (now - record.last_ping_time).total_seconds()
is_online = elapsed <= heartbeat_timeout
if not is_online:
offline_devices.append({
"board_id": record.board_id,
"board_ip": record.board_ip,
"board_platform": record.board_platform,
"board_type": record.board_type,
"status": record.status,
"version": record.version,
"last_ping_time": record.last_ping_time.isoformat() if record.last_ping_time else None,
"elapsed_seconds": round(elapsed, 1),
"is_online": False,
})
except Exception as e:
logger.error(f"[get_offline_devices] 查询失败: {e}")
return {"offline_devices": [], "total": 0, "error": str(e)}
return {"offline_devices": offline_devices, "total": len(offline_devices)}