"""批次振动报警 MVP。 数据接入不是实时流,按风场/时间范围读取波形,计算加速度 RMS 相对基线, 生成报警事件并支持确认/清除。 """ from __future__ import annotations import ast import math from datetime import datetime from typing import Any, Dict, List, Optional import numpy as np from fastapi import APIRouter from pydantic import BaseModel from app.logger import logger from app.report.collector import business_conn, platform_conn, safe_code from app.services.fault_frequency_evidence import FaultFrequencyEvidenceService router = APIRouter(prefix="/vibration-alarm", tags=["vibration-alarm"]) def ensure_table() -> None: conn = platform_conn() try: with conn.cursor() as cur: cur.execute( """ CREATE TABLE IF NOT EXISTS vibration_alarm_event ( id BIGINT AUTO_INCREMENT PRIMARY KEY, wind_code VARCHAR(64) NOT NULL, turbine_code VARCHAR(64) NOT NULL, point_name VARCHAR(128) NOT NULL, data_time DATETIME NOT NULL, alarm_time DATETIME NOT NULL, alarm_level TINYINT NOT NULL COMMENT '1预警 2危险', alarm_status VARCHAR(20) NOT NULL DEFAULT 'active', trigger_value DOUBLE, threshold_value DOUBLE, unit VARCHAR(32) DEFAULT 'm/s2', rule_name VARCHAR(128), batch_code VARCHAR(128), detail VARCHAR(512), ack_by VARCHAR(64), ack_time DATETIME, clear_by VARCHAR(64), clear_time DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY uk_vibration_alarm (wind_code, turbine_code, point_name, data_time, alarm_level) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """ ) finally: conn.close() class EvaluateInput(BaseModel): windCode: str startTime: Optional[str] = None endTime: Optional[str] = None maxRecords: int = 30 def _parse_dt(value: Optional[str]) -> Optional[datetime]: if not value: return None for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d"): try: return datetime.strptime(value, fmt) except ValueError: pass return None def _rms(values: List[float]) -> float: arr = np.asarray(values, dtype=float) arr = arr[np.isfinite(arr)] if arr.size == 0: return 0.0 return float(np.sqrt(np.mean(arr * arr))) @router.post("/evaluate") async def evaluate(inp: EvaluateInput): ensure_table() wind_code = safe_code(inp.windCode) start = _parse_dt(inp.startTime) end = _parse_dt(inp.endTime) limit = max(10, min(int(inp.maxRecords or 30), 50)) where = ["1=1"] params: List[Any] = [] if start: where.append("time_stamp >= %s") params.append(start) if end: where.append("time_stamp <= %s") params.append(end) where_sql = " AND ".join(where) conn = business_conn() try: with conn.cursor() as cur: cur.execute( f"SELECT id, time_stamp, sampling_frequency, wind_turbine_number, " f"mesure_point_name, rotational_speed, mesure_data FROM `{wind_code}_wave` " f"WHERE {where_sql} ORDER BY id DESC LIMIT %s", params + [limit], ) rows = cur.fetchall() finally: conn.close() # 同一时间/机组/测点/采样频率只保留一条,避免重复批次重复报警 unique: Dict[tuple, Dict[str, Any]] = {} for row in rows: key = ( row["time_stamp"], row["wind_turbine_number"], row["mesure_point_name"], row["sampling_frequency"], ) if key not in unique: unique[key] = row rows = list(unique.values()) features = [] for row in rows: try: values = ast.literal_eval(row["mesure_data"]) rms = _rms(values) except Exception: continue if not math.isfinite(rms): continue features.append((row, rms)) if not features: return {"code": 200, "evaluated": 0, "alarms": 0, "message": "无可用波形数据"} rms_values = np.asarray([item[1] for item in features], dtype=float) p90 = float(np.percentile(rms_values, 90)) p98 = float(np.percentile(rms_values, 98)) # 阈值至少保留一个很小的下限,避免全零数据产生大量报警 warn_threshold = max(p90, 1e-9) danger_threshold = max(p98, warn_threshold * 1.2) now = datetime.now() inserted = 0 pconn = platform_conn() try: with pconn.cursor() as cur: for row, rms in features: if rms >= danger_threshold and danger_threshold > warn_threshold: level, threshold = 2, danger_threshold elif rms >= warn_threshold and rms > 0: level, threshold = 1, warn_threshold else: continue fault_type = None characteristic_freq = None fault_order = None spec_source = None diagnosis_detail = None # 对已越限的记录补充特征频率峰值证据;失败不影响 RMS 报警 try: evidence = FaultFrequencyEvidenceService( wind_code, row["wind_turbine_number"], row["mesure_point_name"], row["id"], float(row.get("rotational_speed") or 0), ).analyze() if evidence.get("supported"): rank = {"normal": 0, "watch": 1, "alarm": 2} best = max( evidence.get("evidences") or [], key=lambda e: rank.get(e.get("status"), -1), default=None, ) if best and best.get("status") in ("watch", "alarm"): fault_type = best.get("faultType") characteristic_freq = best.get("peakFreq") or best.get("targetFreq") fault_order = best.get("order") spec_source = evidence.get("source") diagnosis_detail = ( f"{fault_type} 目标 {best.get('targetFreq')} Hz," f"峰值 {best.get('peakFreq')} Hz," f"峰值/基线 {best.get('ratio')}," f"状态 {best.get('status')}" ) except Exception as exc: logger.warning("报警特征频率证据失败 id=%s: %s", row.get("id"), exc) cur.execute( """ INSERT INTO vibration_alarm_event (wind_code, turbine_code, point_name, data_time, alarm_time, alarm_level, alarm_status, trigger_value, threshold_value, unit, rule_name, batch_code, detail, fault_type, characteristic_freq, fault_order, spec_source, diagnosis_detail) VALUES (%s,%s,%s,%s,%s,%s,'active',%s,%s,'m/s2', '加速度RMS相对基线',%s,%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE trigger_value=VALUES(trigger_value), threshold_value=VALUES(threshold_value), fault_type=VALUES(fault_type), characteristic_freq=VALUES(characteristic_freq), fault_order=VALUES(fault_order), spec_source=VALUES(spec_source), diagnosis_detail=VALUES(diagnosis_detail), updated_at=NOW() """, ( wind_code, row["wind_turbine_number"], row["mesure_point_name"], row["time_stamp"], now, level, round(rms, 6), round(threshold, 6), f"batch-{now:%Y%m%d%H%M%S}", f"RMS={rms:.6f},P90={p90:.6f},P98={p98:.6f}", fault_type, characteristic_freq, fault_order, spec_source, diagnosis_detail, ), ) inserted += 1 finally: pconn.close() return { "code": 200, "evaluated": len(features), "alarms": inserted, "warnThreshold": round(warn_threshold, 6), "dangerThreshold": round(danger_threshold, 6), "message": "批次评估完成", } def _attach_names(rows: List[Dict[str, Any]]) -> None: """补充风场名称、机组名称,取不到时前端回退编码。""" if not rows: return wind_codes = sorted({r.get("wind_code") for r in rows if r.get("wind_code")}) turbine_codes = sorted({r.get("turbine_code") for r in rows if r.get("turbine_code")}) wind_names: Dict[str, str] = {} turbine_names: Dict[str, str] = {} try: conn = platform_conn() try: with conn.cursor() as cur: if wind_codes: ph = ",".join(["%s"] * len(wind_codes)) cur.execute( f"SELECT field_code, field_name FROM wind_field WHERE field_code IN ({ph})", wind_codes, ) for item in cur.fetchall(): wind_names[item["field_code"]] = item["field_name"] if turbine_codes: ph = ",".join(["%s"] * len(turbine_codes)) cur.execute( f"SELECT engine_code, engine_name FROM wind_engine_group WHERE engine_code IN ({ph})", turbine_codes, ) for item in cur.fetchall(): turbine_names[item["engine_code"]] = item["engine_name"] finally: conn.close() except Exception as exc: logger.warning("补充风场/机组名称失败: %s", exc) for row in rows: row["wind_name"] = wind_names.get(row.get("wind_code")) or row.get("wind_code") row["turbine_name"] = turbine_names.get(row.get("turbine_code")) or row.get("turbine_code") @router.get("/list") async def list_alarms( windCode: Optional[str] = None, status: Optional[str] = None, limit: int = 200, ): ensure_table() where = ["1=1"] params: List[Any] = [] if windCode: where.append("wind_code=%s") params.append(safe_code(windCode)) if status: where.append("alarm_status=%s") params.append(status) sql = ( "SELECT id, wind_code, turbine_code, point_name, data_time, alarm_time, " "alarm_level, alarm_status, trigger_value, threshold_value, unit, " "rule_name, batch_code, detail, ack_by, ack_time, clear_by, clear_time " "FROM vibration_alarm_event WHERE " + " AND ".join(where) + " ORDER BY alarm_time DESC, id DESC LIMIT %s" ) params.append(max(1, min(int(limit), 1000))) conn = platform_conn() try: with conn.cursor() as cur: cur.execute(sql, params) rows = cur.fetchall() finally: conn.close() for row in rows: for key in ("data_time", "alarm_time", "ack_time", "clear_time"): if row.get(key): row[key] = row[key].strftime("%Y-%m-%d %H:%M:%S") _attach_names(rows) return {"code": 200, "datas": rows, "totalCount": len(rows)} class ActionInput(BaseModel): user: Optional[str] = "operator" class BatchActionInput(BaseModel): ids: List[int] = [] user: Optional[str] = "operator" @router.post("/ack-batch") async def acknowledge_batch(inp: BatchActionInput): """批量确认;仅更新仍为 active 的报警。""" ensure_table() ids = [int(i) for i in (inp.ids or [])] if not ids: return {"code": 200, "updated": 0} placeholders = ",".join(["%s"] * len(ids)) conn = platform_conn() try: with conn.cursor() as cur: cur.execute( "UPDATE vibration_alarm_event SET alarm_status='acknowledged', " f"ack_by=%s, ack_time=NOW() WHERE id IN ({placeholders}) " "AND alarm_status='active'", [inp.user or "operator"] + ids, ) affected = cur.rowcount finally: conn.close() return {"code": 200, "updated": affected} @router.post("/ack/{alarm_id}") async def acknowledge(alarm_id: int, inp: ActionInput): ensure_table() conn = platform_conn() try: with conn.cursor() as cur: cur.execute( "UPDATE vibration_alarm_event SET alarm_status='acknowledged', " "ack_by=%s, ack_time=NOW() WHERE id=%s AND alarm_status='active'", (inp.user or "operator", alarm_id), ) affected = cur.rowcount finally: conn.close() return {"code": 200, "updated": affected} @router.post("/clear/{alarm_id}") async def clear(alarm_id: int, inp: ActionInput): ensure_table() conn = platform_conn() try: with conn.cursor() as cur: cur.execute( "UPDATE vibration_alarm_event SET alarm_status='cleared', " "clear_by=%s, clear_time=NOW() WHERE id=%s", (inp.user or "operator", alarm_id), ) affected = cur.rowcount finally: conn.close() return {"code": 200, "updated": affected}