vibration_alarm.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. """批次振动报警 MVP。
  2. 数据接入不是实时流,按风场/时间范围读取波形,计算加速度 RMS 相对基线,
  3. 生成报警事件并支持确认/清除。
  4. """
  5. from __future__ import annotations
  6. import ast
  7. import math
  8. from datetime import datetime
  9. from typing import Any, Dict, List, Optional
  10. import numpy as np
  11. from fastapi import APIRouter
  12. from pydantic import BaseModel
  13. from app.logger import logger
  14. from app.report.collector import business_conn, platform_conn, safe_code
  15. from app.services.fault_frequency_evidence import FaultFrequencyEvidenceService
  16. router = APIRouter(prefix="/vibration-alarm", tags=["vibration-alarm"])
  17. def ensure_table() -> None:
  18. conn = platform_conn()
  19. try:
  20. with conn.cursor() as cur:
  21. cur.execute(
  22. """
  23. CREATE TABLE IF NOT EXISTS vibration_alarm_event (
  24. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  25. wind_code VARCHAR(64) NOT NULL,
  26. turbine_code VARCHAR(64) NOT NULL,
  27. point_name VARCHAR(128) NOT NULL,
  28. data_time DATETIME NOT NULL,
  29. alarm_time DATETIME NOT NULL,
  30. alarm_level TINYINT NOT NULL COMMENT '1预警 2危险',
  31. alarm_status VARCHAR(20) NOT NULL DEFAULT 'active',
  32. trigger_value DOUBLE,
  33. threshold_value DOUBLE,
  34. unit VARCHAR(32) DEFAULT 'm/s2',
  35. rule_name VARCHAR(128),
  36. batch_code VARCHAR(128),
  37. detail VARCHAR(512),
  38. ack_by VARCHAR(64),
  39. ack_time DATETIME,
  40. clear_by VARCHAR(64),
  41. clear_time DATETIME,
  42. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  43. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  44. UNIQUE KEY uk_vibration_alarm (wind_code, turbine_code, point_name, data_time, alarm_level)
  45. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  46. """
  47. )
  48. finally:
  49. conn.close()
  50. class EvaluateInput(BaseModel):
  51. windCode: str
  52. startTime: Optional[str] = None
  53. endTime: Optional[str] = None
  54. maxRecords: int = 30
  55. def _parse_dt(value: Optional[str]) -> Optional[datetime]:
  56. if not value:
  57. return None
  58. for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d"):
  59. try:
  60. return datetime.strptime(value, fmt)
  61. except ValueError:
  62. pass
  63. return None
  64. def _rms(values: List[float]) -> float:
  65. arr = np.asarray(values, dtype=float)
  66. arr = arr[np.isfinite(arr)]
  67. if arr.size == 0:
  68. return 0.0
  69. return float(np.sqrt(np.mean(arr * arr)))
  70. @router.post("/evaluate")
  71. async def evaluate(inp: EvaluateInput):
  72. ensure_table()
  73. wind_code = safe_code(inp.windCode)
  74. start = _parse_dt(inp.startTime)
  75. end = _parse_dt(inp.endTime)
  76. limit = max(10, min(int(inp.maxRecords or 30), 50))
  77. where = ["1=1"]
  78. params: List[Any] = []
  79. if start:
  80. where.append("time_stamp >= %s")
  81. params.append(start)
  82. if end:
  83. where.append("time_stamp <= %s")
  84. params.append(end)
  85. where_sql = " AND ".join(where)
  86. conn = business_conn()
  87. try:
  88. with conn.cursor() as cur:
  89. cur.execute(
  90. f"SELECT id, time_stamp, sampling_frequency, wind_turbine_number, "
  91. f"mesure_point_name, rotational_speed, mesure_data FROM `{wind_code}_wave` "
  92. f"WHERE {where_sql} ORDER BY id DESC LIMIT %s",
  93. params + [limit],
  94. )
  95. rows = cur.fetchall()
  96. finally:
  97. conn.close()
  98. # 同一时间/机组/测点/采样频率只保留一条,避免重复批次重复报警
  99. unique: Dict[tuple, Dict[str, Any]] = {}
  100. for row in rows:
  101. key = (
  102. row["time_stamp"],
  103. row["wind_turbine_number"],
  104. row["mesure_point_name"],
  105. row["sampling_frequency"],
  106. )
  107. if key not in unique:
  108. unique[key] = row
  109. rows = list(unique.values())
  110. features = []
  111. for row in rows:
  112. try:
  113. values = ast.literal_eval(row["mesure_data"])
  114. rms = _rms(values)
  115. except Exception:
  116. continue
  117. if not math.isfinite(rms):
  118. continue
  119. features.append((row, rms))
  120. if not features:
  121. return {"code": 200, "evaluated": 0, "alarms": 0, "message": "无可用波形数据"}
  122. rms_values = np.asarray([item[1] for item in features], dtype=float)
  123. p90 = float(np.percentile(rms_values, 90))
  124. p98 = float(np.percentile(rms_values, 98))
  125. # 阈值至少保留一个很小的下限,避免全零数据产生大量报警
  126. warn_threshold = max(p90, 1e-9)
  127. danger_threshold = max(p98, warn_threshold * 1.2)
  128. now = datetime.now()
  129. inserted = 0
  130. pconn = platform_conn()
  131. try:
  132. with pconn.cursor() as cur:
  133. for row, rms in features:
  134. if rms >= danger_threshold and danger_threshold > warn_threshold:
  135. level, threshold = 2, danger_threshold
  136. elif rms >= warn_threshold and rms > 0:
  137. level, threshold = 1, warn_threshold
  138. else:
  139. continue
  140. fault_type = None
  141. characteristic_freq = None
  142. fault_order = None
  143. spec_source = None
  144. diagnosis_detail = None
  145. # 对已越限的记录补充特征频率峰值证据;失败不影响 RMS 报警
  146. try:
  147. evidence = FaultFrequencyEvidenceService(
  148. wind_code,
  149. row["wind_turbine_number"],
  150. row["mesure_point_name"],
  151. row["id"],
  152. float(row.get("rotational_speed") or 0),
  153. ).analyze()
  154. if evidence.get("supported"):
  155. rank = {"normal": 0, "watch": 1, "alarm": 2}
  156. best = max(
  157. evidence.get("evidences") or [],
  158. key=lambda e: rank.get(e.get("status"), -1),
  159. default=None,
  160. )
  161. if best and best.get("status") in ("watch", "alarm"):
  162. fault_type = best.get("faultType")
  163. characteristic_freq = best.get("peakFreq") or best.get("targetFreq")
  164. fault_order = best.get("order")
  165. spec_source = evidence.get("source")
  166. diagnosis_detail = (
  167. f"{fault_type} 目标 {best.get('targetFreq')} Hz,"
  168. f"峰值 {best.get('peakFreq')} Hz,"
  169. f"峰值/基线 {best.get('ratio')},"
  170. f"状态 {best.get('status')}"
  171. )
  172. except Exception as exc:
  173. logger.warning("报警特征频率证据失败 id=%s: %s", row.get("id"), exc)
  174. cur.execute(
  175. """
  176. INSERT INTO vibration_alarm_event
  177. (wind_code, turbine_code, point_name, data_time, alarm_time,
  178. alarm_level, alarm_status, trigger_value, threshold_value,
  179. unit, rule_name, batch_code, detail,
  180. fault_type, characteristic_freq, fault_order, spec_source, diagnosis_detail)
  181. VALUES (%s,%s,%s,%s,%s,%s,'active',%s,%s,'m/s2',
  182. '加速度RMS相对基线',%s,%s,%s,%s,%s,%s,%s)
  183. ON DUPLICATE KEY UPDATE
  184. trigger_value=VALUES(trigger_value),
  185. threshold_value=VALUES(threshold_value),
  186. fault_type=VALUES(fault_type),
  187. characteristic_freq=VALUES(characteristic_freq),
  188. fault_order=VALUES(fault_order),
  189. spec_source=VALUES(spec_source),
  190. diagnosis_detail=VALUES(diagnosis_detail),
  191. updated_at=NOW()
  192. """,
  193. (
  194. wind_code,
  195. row["wind_turbine_number"],
  196. row["mesure_point_name"],
  197. row["time_stamp"],
  198. now,
  199. level,
  200. round(rms, 6),
  201. round(threshold, 6),
  202. f"batch-{now:%Y%m%d%H%M%S}",
  203. f"RMS={rms:.6f},P90={p90:.6f},P98={p98:.6f}",
  204. fault_type,
  205. characteristic_freq,
  206. fault_order,
  207. spec_source,
  208. diagnosis_detail,
  209. ),
  210. )
  211. inserted += 1
  212. finally:
  213. pconn.close()
  214. return {
  215. "code": 200,
  216. "evaluated": len(features),
  217. "alarms": inserted,
  218. "warnThreshold": round(warn_threshold, 6),
  219. "dangerThreshold": round(danger_threshold, 6),
  220. "message": "批次评估完成",
  221. }
  222. def _attach_names(rows: List[Dict[str, Any]]) -> None:
  223. """补充风场名称、机组名称,取不到时前端回退编码。"""
  224. if not rows:
  225. return
  226. wind_codes = sorted({r.get("wind_code") for r in rows if r.get("wind_code")})
  227. turbine_codes = sorted({r.get("turbine_code") for r in rows if r.get("turbine_code")})
  228. wind_names: Dict[str, str] = {}
  229. turbine_names: Dict[str, str] = {}
  230. try:
  231. conn = platform_conn()
  232. try:
  233. with conn.cursor() as cur:
  234. if wind_codes:
  235. ph = ",".join(["%s"] * len(wind_codes))
  236. cur.execute(
  237. f"SELECT field_code, field_name FROM wind_field WHERE field_code IN ({ph})",
  238. wind_codes,
  239. )
  240. for item in cur.fetchall():
  241. wind_names[item["field_code"]] = item["field_name"]
  242. if turbine_codes:
  243. ph = ",".join(["%s"] * len(turbine_codes))
  244. cur.execute(
  245. f"SELECT engine_code, engine_name FROM wind_engine_group WHERE engine_code IN ({ph})",
  246. turbine_codes,
  247. )
  248. for item in cur.fetchall():
  249. turbine_names[item["engine_code"]] = item["engine_name"]
  250. finally:
  251. conn.close()
  252. except Exception as exc:
  253. logger.warning("补充风场/机组名称失败: %s", exc)
  254. for row in rows:
  255. row["wind_name"] = wind_names.get(row.get("wind_code")) or row.get("wind_code")
  256. row["turbine_name"] = turbine_names.get(row.get("turbine_code")) or row.get("turbine_code")
  257. @router.get("/list")
  258. async def list_alarms(
  259. windCode: Optional[str] = None,
  260. status: Optional[str] = None,
  261. limit: int = 200,
  262. ):
  263. ensure_table()
  264. where = ["1=1"]
  265. params: List[Any] = []
  266. if windCode:
  267. where.append("wind_code=%s")
  268. params.append(safe_code(windCode))
  269. if status:
  270. where.append("alarm_status=%s")
  271. params.append(status)
  272. sql = (
  273. "SELECT id, wind_code, turbine_code, point_name, data_time, alarm_time, "
  274. "alarm_level, alarm_status, trigger_value, threshold_value, unit, "
  275. "rule_name, batch_code, detail, ack_by, ack_time, clear_by, clear_time "
  276. "FROM vibration_alarm_event WHERE " + " AND ".join(where) +
  277. " ORDER BY alarm_time DESC, id DESC LIMIT %s"
  278. )
  279. params.append(max(1, min(int(limit), 1000)))
  280. conn = platform_conn()
  281. try:
  282. with conn.cursor() as cur:
  283. cur.execute(sql, params)
  284. rows = cur.fetchall()
  285. finally:
  286. conn.close()
  287. for row in rows:
  288. for key in ("data_time", "alarm_time", "ack_time", "clear_time"):
  289. if row.get(key):
  290. row[key] = row[key].strftime("%Y-%m-%d %H:%M:%S")
  291. _attach_names(rows)
  292. return {"code": 200, "datas": rows, "totalCount": len(rows)}
  293. class ActionInput(BaseModel):
  294. user: Optional[str] = "operator"
  295. class BatchActionInput(BaseModel):
  296. ids: List[int] = []
  297. user: Optional[str] = "operator"
  298. @router.post("/ack-batch")
  299. async def acknowledge_batch(inp: BatchActionInput):
  300. """批量确认;仅更新仍为 active 的报警。"""
  301. ensure_table()
  302. ids = [int(i) for i in (inp.ids or [])]
  303. if not ids:
  304. return {"code": 200, "updated": 0}
  305. placeholders = ",".join(["%s"] * len(ids))
  306. conn = platform_conn()
  307. try:
  308. with conn.cursor() as cur:
  309. cur.execute(
  310. "UPDATE vibration_alarm_event SET alarm_status='acknowledged', "
  311. f"ack_by=%s, ack_time=NOW() WHERE id IN ({placeholders}) "
  312. "AND alarm_status='active'",
  313. [inp.user or "operator"] + ids,
  314. )
  315. affected = cur.rowcount
  316. finally:
  317. conn.close()
  318. return {"code": 200, "updated": affected}
  319. @router.post("/ack/{alarm_id}")
  320. async def acknowledge(alarm_id: int, inp: ActionInput):
  321. ensure_table()
  322. conn = platform_conn()
  323. try:
  324. with conn.cursor() as cur:
  325. cur.execute(
  326. "UPDATE vibration_alarm_event SET alarm_status='acknowledged', "
  327. "ack_by=%s, ack_time=NOW() WHERE id=%s AND alarm_status='active'",
  328. (inp.user or "operator", alarm_id),
  329. )
  330. affected = cur.rowcount
  331. finally:
  332. conn.close()
  333. return {"code": 200, "updated": affected}
  334. @router.post("/clear/{alarm_id}")
  335. async def clear(alarm_id: int, inp: ActionInput):
  336. ensure_table()
  337. conn = platform_conn()
  338. try:
  339. with conn.cursor() as cur:
  340. cur.execute(
  341. "UPDATE vibration_alarm_event SET alarm_status='cleared', "
  342. "clear_by=%s, clear_time=NOW() WHERE id=%s",
  343. (inp.user or "operator", alarm_id),
  344. )
  345. affected = cur.rowcount
  346. finally:
  347. conn.close()
  348. return {"code": 200, "updated": affected}