vibration_alarm.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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.report.collector import business_conn, platform_conn, safe_code
  14. router = APIRouter(prefix="/vibration-alarm", tags=["vibration-alarm"])
  15. def ensure_table() -> None:
  16. conn = platform_conn()
  17. try:
  18. with conn.cursor() as cur:
  19. cur.execute(
  20. """
  21. CREATE TABLE IF NOT EXISTS vibration_alarm_event (
  22. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  23. wind_code VARCHAR(64) NOT NULL,
  24. turbine_code VARCHAR(64) NOT NULL,
  25. point_name VARCHAR(128) NOT NULL,
  26. data_time DATETIME NOT NULL,
  27. alarm_time DATETIME NOT NULL,
  28. alarm_level TINYINT NOT NULL COMMENT '1预警 2危险',
  29. alarm_status VARCHAR(20) NOT NULL DEFAULT 'active',
  30. trigger_value DOUBLE,
  31. threshold_value DOUBLE,
  32. unit VARCHAR(32) DEFAULT 'm/s2',
  33. rule_name VARCHAR(128),
  34. batch_code VARCHAR(128),
  35. detail VARCHAR(512),
  36. ack_by VARCHAR(64),
  37. ack_time DATETIME,
  38. clear_by VARCHAR(64),
  39. clear_time DATETIME,
  40. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  41. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  42. UNIQUE KEY uk_vibration_alarm (wind_code, turbine_code, point_name, data_time, alarm_level)
  43. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  44. """
  45. )
  46. finally:
  47. conn.close()
  48. class EvaluateInput(BaseModel):
  49. windCode: str
  50. startTime: Optional[str] = None
  51. endTime: Optional[str] = None
  52. maxRecords: int = 30
  53. def _parse_dt(value: Optional[str]) -> Optional[datetime]:
  54. if not value:
  55. return None
  56. for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d"):
  57. try:
  58. return datetime.strptime(value, fmt)
  59. except ValueError:
  60. pass
  61. return None
  62. def _rms(values: List[float]) -> float:
  63. arr = np.asarray(values, dtype=float)
  64. arr = arr[np.isfinite(arr)]
  65. if arr.size == 0:
  66. return 0.0
  67. return float(np.sqrt(np.mean(arr * arr)))
  68. @router.post("/evaluate")
  69. async def evaluate(inp: EvaluateInput):
  70. ensure_table()
  71. wind_code = safe_code(inp.windCode)
  72. start = _parse_dt(inp.startTime)
  73. end = _parse_dt(inp.endTime)
  74. limit = max(10, min(int(inp.maxRecords or 30), 50))
  75. where = ["1=1"]
  76. params: List[Any] = []
  77. if start:
  78. where.append("time_stamp >= %s")
  79. params.append(start)
  80. if end:
  81. where.append("time_stamp <= %s")
  82. params.append(end)
  83. where_sql = " AND ".join(where)
  84. conn = business_conn()
  85. try:
  86. with conn.cursor() as cur:
  87. cur.execute(
  88. f"SELECT id, time_stamp, sampling_frequency, wind_turbine_number, "
  89. f"mesure_point_name, mesure_data FROM `{wind_code}_wave` "
  90. f"WHERE {where_sql} ORDER BY id DESC LIMIT %s",
  91. params + [limit],
  92. )
  93. rows = cur.fetchall()
  94. finally:
  95. conn.close()
  96. # 同一时间/机组/测点/采样频率只保留一条,避免重复批次重复报警
  97. unique: Dict[tuple, Dict[str, Any]] = {}
  98. for row in rows:
  99. key = (
  100. row["time_stamp"],
  101. row["wind_turbine_number"],
  102. row["mesure_point_name"],
  103. row["sampling_frequency"],
  104. )
  105. if key not in unique:
  106. unique[key] = row
  107. rows = list(unique.values())
  108. features = []
  109. for row in rows:
  110. try:
  111. values = ast.literal_eval(row["mesure_data"])
  112. rms = _rms(values)
  113. except Exception:
  114. continue
  115. if not math.isfinite(rms):
  116. continue
  117. features.append((row, rms))
  118. if not features:
  119. return {"code": 200, "evaluated": 0, "alarms": 0, "message": "无可用波形数据"}
  120. rms_values = np.asarray([item[1] for item in features], dtype=float)
  121. p90 = float(np.percentile(rms_values, 90))
  122. p98 = float(np.percentile(rms_values, 98))
  123. # 阈值至少保留一个很小的下限,避免全零数据产生大量报警
  124. warn_threshold = max(p90, 1e-9)
  125. danger_threshold = max(p98, warn_threshold * 1.2)
  126. now = datetime.now()
  127. inserted = 0
  128. pconn = platform_conn()
  129. try:
  130. with pconn.cursor() as cur:
  131. for row, rms in features:
  132. if rms >= danger_threshold and danger_threshold > warn_threshold:
  133. level, threshold = 2, danger_threshold
  134. elif rms >= warn_threshold and rms > 0:
  135. level, threshold = 1, warn_threshold
  136. else:
  137. continue
  138. cur.execute(
  139. """
  140. INSERT INTO vibration_alarm_event
  141. (wind_code, turbine_code, point_name, data_time, alarm_time,
  142. alarm_level, alarm_status, trigger_value, threshold_value,
  143. unit, rule_name, batch_code, detail)
  144. VALUES (%s,%s,%s,%s,%s,%s,'active',%s,%s,'m/s2',
  145. '加速度RMS相对基线',%s,%s)
  146. ON DUPLICATE KEY UPDATE
  147. trigger_value=VALUES(trigger_value),
  148. threshold_value=VALUES(threshold_value),
  149. updated_at=NOW()
  150. """,
  151. (
  152. wind_code,
  153. row["wind_turbine_number"],
  154. row["mesure_point_name"],
  155. row["time_stamp"],
  156. now,
  157. level,
  158. round(rms, 6),
  159. round(threshold, 6),
  160. f"batch-{now:%Y%m%d%H%M%S}",
  161. f"RMS={rms:.6f},P90={p90:.6f},P98={p98:.6f}",
  162. ),
  163. )
  164. inserted += 1
  165. finally:
  166. pconn.close()
  167. return {
  168. "code": 200,
  169. "evaluated": len(features),
  170. "alarms": inserted,
  171. "warnThreshold": round(warn_threshold, 6),
  172. "dangerThreshold": round(danger_threshold, 6),
  173. "message": "批次评估完成",
  174. }
  175. @router.get("/list")
  176. async def list_alarms(
  177. windCode: Optional[str] = None,
  178. status: Optional[str] = None,
  179. limit: int = 200,
  180. ):
  181. ensure_table()
  182. where = ["1=1"]
  183. params: List[Any] = []
  184. if windCode:
  185. where.append("wind_code=%s")
  186. params.append(safe_code(windCode))
  187. if status:
  188. where.append("alarm_status=%s")
  189. params.append(status)
  190. sql = (
  191. "SELECT id, wind_code, turbine_code, point_name, data_time, alarm_time, "
  192. "alarm_level, alarm_status, trigger_value, threshold_value, unit, "
  193. "rule_name, batch_code, detail, ack_by, ack_time, clear_by, clear_time "
  194. "FROM vibration_alarm_event WHERE " + " AND ".join(where) +
  195. " ORDER BY alarm_time DESC, id DESC LIMIT %s"
  196. )
  197. params.append(max(1, min(int(limit), 1000)))
  198. conn = platform_conn()
  199. try:
  200. with conn.cursor() as cur:
  201. cur.execute(sql, params)
  202. rows = cur.fetchall()
  203. finally:
  204. conn.close()
  205. for row in rows:
  206. for key in ("data_time", "alarm_time", "ack_time", "clear_time"):
  207. if row.get(key):
  208. row[key] = row[key].strftime("%Y-%m-%d %H:%M:%S")
  209. return {"code": 200, "datas": rows, "totalCount": len(rows)}
  210. class ActionInput(BaseModel):
  211. user: Optional[str] = "operator"
  212. class BatchActionInput(BaseModel):
  213. ids: List[int] = []
  214. user: Optional[str] = "operator"
  215. @router.post("/ack-batch")
  216. async def acknowledge_batch(inp: BatchActionInput):
  217. """批量确认;仅更新仍为 active 的报警。"""
  218. ensure_table()
  219. ids = [int(i) for i in (inp.ids or [])]
  220. if not ids:
  221. return {"code": 200, "updated": 0}
  222. placeholders = ",".join(["%s"] * len(ids))
  223. conn = platform_conn()
  224. try:
  225. with conn.cursor() as cur:
  226. cur.execute(
  227. "UPDATE vibration_alarm_event SET alarm_status='acknowledged', "
  228. f"ack_by=%s, ack_time=NOW() WHERE id IN ({placeholders}) "
  229. "AND alarm_status='active'",
  230. [inp.user or "operator"] + ids,
  231. )
  232. affected = cur.rowcount
  233. finally:
  234. conn.close()
  235. return {"code": 200, "updated": affected}
  236. @router.post("/ack/{alarm_id}")
  237. async def acknowledge(alarm_id: int, inp: ActionInput):
  238. ensure_table()
  239. conn = platform_conn()
  240. try:
  241. with conn.cursor() as cur:
  242. cur.execute(
  243. "UPDATE vibration_alarm_event SET alarm_status='acknowledged', "
  244. "ack_by=%s, ack_time=NOW() WHERE id=%s AND alarm_status='active'",
  245. (inp.user or "operator", alarm_id),
  246. )
  247. affected = cur.rowcount
  248. finally:
  249. conn.close()
  250. return {"code": 200, "updated": affected}
  251. @router.post("/clear/{alarm_id}")
  252. async def clear(alarm_id: int, inp: ActionInput):
  253. ensure_table()
  254. conn = platform_conn()
  255. try:
  256. with conn.cursor() as cur:
  257. cur.execute(
  258. "UPDATE vibration_alarm_event SET alarm_status='cleared', "
  259. "clear_by=%s, clear_time=NOW() WHERE id=%s",
  260. (inp.user or "operator", alarm_id),
  261. )
  262. affected = cur.rowcount
  263. finally:
  264. conn.close()
  265. return {"code": 200, "updated": affected}