| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- """自动诊断接口:/AnalysisMulti/autodiag/{type}。
- 兼容原状态码结构,同时增加参数来源、采样率限制和诊断结果追溯。
- """
- from __future__ import annotations
- import json
- from typing import Any, Dict
- from fastapi import APIRouter
- from fastapi.responses import JSONResponse
- from app.logger import logger
- from app.models.AutoDiagModel import AutoDiagInput
- from app.report.collector import platform_conn
- from app.services.Auto_diag import Auto_diag
- router = APIRouter(prefix="/autodiag", tags=["autodiag"])
- METHOD_MAP = {
- "Bearing": "Bearing_diag",
- "Gear": "Gear_diag",
- # 前端“不对中”使用 Dissymmetry;“不平衡”使用 Misalignment
- "Dissymmetry": "Misalignment_diag",
- "Misalignment": "Unbalance_diag",
- "Loose": "Looseness_diag",
- }
- def _max_status(result: Dict[str, Any]) -> int:
- stats = result.get("statistics")
- if isinstance(stats, dict) and "max_status" in stats:
- try:
- return int(stats["max_status"])
- except (TypeError, ValueError):
- pass
- values = []
- body = result.get("results")
- if isinstance(body, dict):
- for item in body.values():
- if isinstance(item, dict):
- values.extend(item.get("status_codes") or [])
- elif isinstance(body, list):
- values.extend(body)
- return max(values) if values else -1
- def _save_result(analysis_type: str, inp: AutoDiagInput, result: Dict[str, Any]) -> int | None:
- """记录诊断结果;失败不影响主流程。"""
- meta = result.get("meta") or {}
- frequencies = meta.get("frequencies") or {}
- unsupported = result.get("unsupported") or {}
- try:
- conn = platform_conn()
- try:
- with conn.cursor() as cur:
- cur.execute(
- """
- INSERT INTO vibration_diagnosis_result
- (engine_code, wind_code, point_name, diagnosis_type, max_status,
- component_type, brand, model, frequencies_json,
- unsupported_json, meta_json)
- VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
- """,
- (
- inp.engine_code,
- inp.windCode,
- meta.get("pointName"),
- analysis_type,
- _max_status(result),
- meta.get("component"),
- meta.get("brand"),
- meta.get("model"),
- json.dumps(frequencies, ensure_ascii=False),
- json.dumps(unsupported, ensure_ascii=False),
- json.dumps(meta, ensure_ascii=False),
- ),
- )
- return int(cur.lastrowid)
- finally:
- conn.close()
- except Exception as exc:
- logger.warning("诊断结果保存失败: %s", exc)
- return None
- @router.post("/{analysis_type}")
- async def diagnose(analysis_type: str, inp: AutoDiagInput):
- method_name = METHOD_MAP.get(analysis_type)
- if not method_name:
- return JSONResponse(status_code=400, content={"code": 400, "message": "不支持的诊断类型"})
- try:
- diag = Auto_diag(inp.ids, inp.windCode, inp.engine_code)
- except ValueError as exc:
- return JSONResponse(status_code=200, content={"code": 405, "message": str(exc)})
- except Exception as exc:
- logger.exception("诊断初始化失败")
- return JSONResponse(status_code=200, content={"code": 500, "message": f"诊断初始化失败:{exc}"})
- try:
- result = getattr(diag, method_name)()
- diagnosis_id = _save_result(analysis_type, inp, result)
- return {"code": 200, "diagnosisId": diagnosis_id, **result}
- except ValueError as exc:
- return JSONResponse(status_code=200, content={"code": 405, "message": str(exc)})
- except Exception as exc:
- logger.exception("诊断执行失败")
- return JSONResponse(status_code=200, content={"code": 500, "message": f"诊断失败:{exc}"})
|