| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299 |
- """批次振动报警 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.report.collector import business_conn, platform_conn, safe_code
- 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, 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
- 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)
- VALUES (%s,%s,%s,%s,%s,%s,'active',%s,%s,'m/s2',
- '加速度RMS相对基线',%s,%s)
- ON DUPLICATE KEY UPDATE
- trigger_value=VALUES(trigger_value),
- threshold_value=VALUES(threshold_value),
- 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}",
- ),
- )
- inserted += 1
- finally:
- pconn.close()
- return {
- "code": 200,
- "evaluated": len(features),
- "alarms": inserted,
- "warnThreshold": round(warn_threshold, 6),
- "dangerThreshold": round(danger_threshold, 6),
- "message": "批次评估完成",
- }
- @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")
- 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}
|