cockpit_compat.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """驾驶舱兼容接口。
  2. 历史前端依赖独立 ETL / transDataWeb 服务;本机未部署该服务时,
  3. 返回结构兼容的数据,避免页面出现 404/500 报错。
  4. “入库数据”复用平台库 wind_field_batch 的批次记录,
  5. 展示最近入库的风场与时间;不访问互联网。
  6. """
  7. from __future__ import annotations
  8. import json
  9. import os
  10. from typing import Any, Dict, List
  11. from fastapi import APIRouter
  12. from sqlalchemy import text
  13. from app.config import dataBase
  14. from app.database import get_engine
  15. router = APIRouter(tags=["cockpit-compat"])
  16. BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  17. CACHE_DIR = os.path.join(BASE_DIR, "output", "cache")
  18. CACHE_FILE = os.path.join(CACHE_DIR, "cockpit_recent_imports.json")
  19. def _read_cache() -> List[Dict[str, Any]]:
  20. try:
  21. with open(CACHE_FILE, "r", encoding="utf-8") as f:
  22. data = json.load(f)
  23. return data if isinstance(data, list) else []
  24. except Exception:
  25. return []
  26. def _write_cache(rows: List[Dict[str, Any]]) -> None:
  27. if not rows:
  28. return
  29. try:
  30. os.makedirs(CACHE_DIR, exist_ok=True)
  31. with open(CACHE_FILE, "w", encoding="utf-8") as f:
  32. json.dump(rows, f, ensure_ascii=False, indent=2)
  33. except Exception:
  34. pass
  35. def _recent_batches(limit: int = 5) -> List[Dict[str, Any]]:
  36. try:
  37. engine = get_engine(dataBase.PLATFORM_DB)
  38. sql = text(
  39. """
  40. select b.batch_code,
  41. b.batch_name,
  42. b.field_code,
  43. coalesce(f.field_name, b.batch_name) as wind_farm_name,
  44. b.create_time
  45. from wind_field_batch b
  46. left join wind_field f on b.field_code = f.field_code
  47. where b.is_delete = 0
  48. and b.field_code in (
  49. select code_number from sys_organization_auth where role_id = :role_id
  50. )
  51. order by b.create_time desc
  52. limit :limit
  53. """
  54. )
  55. with engine.connect() as conn:
  56. rows = conn.execute(
  57. sql,
  58. {"limit": limit, "role_id": int(os.getenv("HD_ROLE_ID", "15"))},
  59. ).mappings().all()
  60. result = []
  61. for row in rows:
  62. created = row.get("create_time")
  63. result.append(
  64. {
  65. "batchCode": row.get("batch_code"),
  66. "batchName": row.get("batch_name"),
  67. "fieldCode": row.get("field_code"),
  68. "windFarmName": row.get("wind_farm_name"),
  69. "createTime": created.strftime("%Y-%m-%d %H:%M:%S") if created else "",
  70. }
  71. )
  72. _write_cache(result)
  73. return result
  74. except Exception:
  75. # 数据库暂不可达时使用最近一次成功查询的本地快照,保证驾驶舱面板可见
  76. return _read_cache()[:limit]
  77. @router.post("/ETLapi/dataTransfer/recentlyImportedSuccessful5Data")
  78. async def recently_imported():
  79. return {"code": 200, "datas": _recent_batches(5), "message": "success"}
  80. @router.post("/ETLapi/dataTransfer/pltIndexMore")
  81. async def plt_index_more():
  82. rows = _recent_batches(50)
  83. datas = []
  84. for item in rows:
  85. datas.append(
  86. {
  87. "windFarmName": item["windFarmName"],
  88. "minuteTimeAreaList": [item["createTime"]] if item["createTime"] else [],
  89. "secondTimeAreaList": [],
  90. "faultTimeAreaList": [],
  91. "warnTimeAreaList": [],
  92. "vibrationTimeAreaList": [],
  93. }
  94. )
  95. return {"code": 200, "datas": datas, "message": "success"}
  96. @router.post("/transDataWeb/windFarmDayCount/getTodayData")
  97. async def today_data():
  98. return {"code": 200, "datas": [], "message": "success"}
  99. @router.post("/transDataWeb/windFarmDayCount/getIndexOnlineData")
  100. async def index_online_data():
  101. return {"code": 200, "datas": [], "message": "success"}
  102. @router.post("/transDataWeb/windFarmDayCount/getHistoryDataSummary")
  103. async def history_data_summary():
  104. return {"code": 200, "datas": [], "message": "success"}