autodiag.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """自动诊断接口:/AnalysisMulti/autodiag/{type}。
  2. 兼容原状态码结构,同时增加参数来源、采样率限制和诊断结果追溯。
  3. """
  4. from __future__ import annotations
  5. import json
  6. from typing import Any, Dict
  7. from fastapi import APIRouter
  8. from fastapi.responses import JSONResponse
  9. from app.logger import logger
  10. from app.models.AutoDiagModel import AutoDiagInput
  11. from app.report.collector import platform_conn, business_conn, safe_code
  12. from app.services.Auto_diag import Auto_diag
  13. router = APIRouter(prefix="/autodiag", tags=["autodiag"])
  14. METHOD_MAP = {
  15. "Bearing": "Bearing_diag",
  16. "Gear": "Gear_diag",
  17. # 前端“不对中”使用 Dissymmetry;“不平衡”使用 Misalignment
  18. "Dissymmetry": "Misalignment_diag",
  19. "Misalignment": "Unbalance_diag",
  20. "Loose": "Looseness_diag",
  21. }
  22. def _max_status(result: Dict[str, Any]) -> int:
  23. stats = result.get("statistics")
  24. if isinstance(stats, dict) and "max_status" in stats:
  25. try:
  26. return int(stats["max_status"])
  27. except (TypeError, ValueError):
  28. pass
  29. values = []
  30. body = result.get("results")
  31. if isinstance(body, dict):
  32. for item in body.values():
  33. if isinstance(item, dict):
  34. values.extend(item.get("status_codes") or [])
  35. elif isinstance(body, list):
  36. values.extend(body)
  37. return max(values) if values else -1
  38. def _save_result(analysis_type: str, inp: AutoDiagInput, result: Dict[str, Any]) -> int | None:
  39. """记录诊断结果;失败不影响主流程。"""
  40. meta = result.get("meta") or {}
  41. frequencies = meta.get("frequencies") or {}
  42. unsupported = result.get("unsupported") or {}
  43. record_time = None
  44. try:
  45. ids = list(inp.ids or [])
  46. if ids:
  47. bconn = business_conn()
  48. try:
  49. table = f"`{safe_code(inp.windCode)}_wave`"
  50. with bconn.cursor() as cur:
  51. cur.execute(
  52. f"SELECT MIN(time_stamp) AS t FROM {table} WHERE id IN ({','.join(['%s'] * len(ids))})",
  53. ids,
  54. )
  55. row = cur.fetchone()
  56. record_time = row["t"] if row else None
  57. finally:
  58. bconn.close()
  59. except Exception as exc:
  60. logger.warning("诊断记录时间查询失败: %s", exc)
  61. try:
  62. conn = platform_conn()
  63. try:
  64. with conn.cursor() as cur:
  65. cur.execute(
  66. """
  67. INSERT INTO vibration_diagnosis_result
  68. (engine_code, wind_code, point_name, diagnosis_type, max_status,
  69. component_type, brand, model, frequencies_json,
  70. unsupported_json, meta_json, record_time)
  71. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  72. """,
  73. (
  74. inp.engine_code,
  75. inp.windCode,
  76. meta.get("pointName"),
  77. analysis_type,
  78. _max_status(result),
  79. meta.get("component"),
  80. meta.get("brand"),
  81. meta.get("model"),
  82. json.dumps(frequencies, ensure_ascii=False),
  83. json.dumps(unsupported, ensure_ascii=False),
  84. json.dumps(meta, ensure_ascii=False),
  85. record_time,
  86. ),
  87. )
  88. return int(cur.lastrowid)
  89. finally:
  90. conn.close()
  91. except Exception as exc:
  92. logger.warning("诊断结果保存失败: %s", exc)
  93. return None
  94. @router.post("/{analysis_type}")
  95. async def diagnose(analysis_type: str, inp: AutoDiagInput):
  96. method_name = METHOD_MAP.get(analysis_type)
  97. if not method_name:
  98. return JSONResponse(status_code=400, content={"code": 400, "message": "不支持的诊断类型"})
  99. try:
  100. diag = Auto_diag(inp.ids, inp.windCode, inp.engine_code)
  101. except ValueError as exc:
  102. return JSONResponse(status_code=200, content={"code": 405, "message": str(exc)})
  103. except Exception as exc:
  104. logger.exception("诊断初始化失败")
  105. return JSONResponse(status_code=200, content={"code": 500, "message": f"诊断初始化失败:{exc}"})
  106. try:
  107. result = getattr(diag, method_name)()
  108. diagnosis_id = _save_result(analysis_type, inp, result)
  109. return {"code": 200, "diagnosisId": diagnosis_id, **result}
  110. except ValueError as exc:
  111. return JSONResponse(status_code=200, content={"code": 405, "message": str(exc)})
  112. except Exception as exc:
  113. logger.exception("诊断执行失败")
  114. return JSONResponse(status_code=200, content={"code": 500, "message": f"诊断失败:{exc}"})