| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- """驾驶舱兼容接口。
- 历史前端依赖独立 ETL / transDataWeb 服务;本机未部署该服务时,
- 返回结构兼容的数据,避免页面出现 404/500 报错。
- “入库数据”复用平台库 wind_field_batch 的批次记录,
- 展示最近入库的风场与时间;不访问互联网。
- """
- from __future__ import annotations
- import json
- import os
- from typing import Any, Dict, List
- from fastapi import APIRouter
- from sqlalchemy import text
- from app.config import dataBase
- from app.database import get_engine
- router = APIRouter(tags=["cockpit-compat"])
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
- CACHE_DIR = os.path.join(BASE_DIR, "output", "cache")
- CACHE_FILE = os.path.join(CACHE_DIR, "cockpit_recent_imports.json")
- def _read_cache() -> List[Dict[str, Any]]:
- try:
- with open(CACHE_FILE, "r", encoding="utf-8") as f:
- data = json.load(f)
- return data if isinstance(data, list) else []
- except Exception:
- return []
- def _write_cache(rows: List[Dict[str, Any]]) -> None:
- if not rows:
- return
- try:
- os.makedirs(CACHE_DIR, exist_ok=True)
- with open(CACHE_FILE, "w", encoding="utf-8") as f:
- json.dump(rows, f, ensure_ascii=False, indent=2)
- except Exception:
- pass
- def _recent_batches(limit: int = 5) -> List[Dict[str, Any]]:
- try:
- engine = get_engine(dataBase.PLATFORM_DB)
- sql = text(
- """
- select b.batch_code,
- b.batch_name,
- b.field_code,
- coalesce(f.field_name, b.batch_name) as wind_farm_name,
- b.create_time
- from wind_field_batch b
- left join wind_field f on b.field_code = f.field_code
- where b.is_delete = 0
- and b.field_code in (
- select code_number from sys_organization_auth where role_id = :role_id
- )
- order by b.create_time desc
- limit :limit
- """
- )
- with engine.connect() as conn:
- rows = conn.execute(
- sql,
- {"limit": limit, "role_id": int(os.getenv("HD_ROLE_ID", "15"))},
- ).mappings().all()
- result = []
- for row in rows:
- created = row.get("create_time")
- result.append(
- {
- "batchCode": row.get("batch_code"),
- "batchName": row.get("batch_name"),
- "fieldCode": row.get("field_code"),
- "windFarmName": row.get("wind_farm_name"),
- "createTime": created.strftime("%Y-%m-%d %H:%M:%S") if created else "",
- }
- )
- _write_cache(result)
- return result
- except Exception:
- # 数据库暂不可达时使用最近一次成功查询的本地快照,保证驾驶舱面板可见
- return _read_cache()[:limit]
- @router.post("/ETLapi/dataTransfer/recentlyImportedSuccessful5Data")
- async def recently_imported():
- return {"code": 200, "datas": _recent_batches(5), "message": "success"}
- @router.post("/ETLapi/dataTransfer/pltIndexMore")
- async def plt_index_more():
- rows = _recent_batches(50)
- datas = []
- for item in rows:
- datas.append(
- {
- "windFarmName": item["windFarmName"],
- "minuteTimeAreaList": [item["createTime"]] if item["createTime"] else [],
- "secondTimeAreaList": [],
- "faultTimeAreaList": [],
- "warnTimeAreaList": [],
- "vibrationTimeAreaList": [],
- }
- )
- return {"code": 200, "datas": datas, "message": "success"}
- @router.post("/transDataWeb/windFarmDayCount/getTodayData")
- async def today_data():
- return {"code": 200, "datas": [], "message": "success"}
- @router.post("/transDataWeb/windFarmDayCount/getIndexOnlineData")
- async def index_online_data():
- return {"code": 200, "datas": [], "message": "success"}
- @router.post("/transDataWeb/windFarmDayCount/getHistoryDataSummary")
- async def history_data_summary():
- return {"code": 200, "datas": [], "message": "success"}
|