pump / backend /app /safety.py
Codex
Deploy efficiency estimate fix cf55248
aec7019
Raw History Blame Contribute Delete
7.43 kB
"""Phase 3 安全联锁门控(对应文档 1.6:闭环回写关键)。
把优化建议在下发前逐项过安全门:写使能、指令限幅、频率斜坡限速、高压硬联锁、
最少台数保证、CRITICAL 报警跳过、watchdog 心跳超时切回本地 PID。
manual(开环)模式下 AI 不下发;auto(闭环)模式下每周期经本门控输出安全指令。
"""
from __future__ import annotations
import time
from dataclasses import dataclass, field
@dataclass
class ControlState:
mode: str = "manual" # manual(开环建议) | auto(闭环)
write_enable: bool = False # bWriteEnable:AI 回写总使能
critical_alarm: bool = False # CRITICAL 报警(真则跳过优化)
last_heartbeat: float = field(default_factory=time.time)
heartbeat_count: int = 0
last_command: dict | None = None # 最近一次已下发的安全指令
reverted: bool = False # 是否处于「已切回」安全态
def beat(self, now: float | None = None) -> None:
self.last_heartbeat = now if now is not None else time.time()
self.heartbeat_count += 1
def watchdog_age(self, now: float | None = None) -> float:
return (now if now is not None else time.time()) - self.last_heartbeat
@dataclass
class SafetyGate:
freq_min: float = 20.0
freq_max: float = 50.0
freq_step_per_cycle: float = 5.0 # 每周期最大 Δf(斜坡限速)
pressure_max_mpa: float = 0.55 # 高压硬联锁
min_pumps: int = 1
watchdog_timeout_s: float = 5.0
start_freq: float = 20.0
level_ll_stop: float = 0.0 # 低水位保护停泵阈值 (m),0=不启用
level_hh: float = 0.0 # 高水位阈值 (m),0=不启用
variable_speed: dict = field(default_factory=dict)
def _clip(self, f: float) -> float:
return max(self.freq_min, min(self.freq_max, float(f)))
def gate(self, suggestion: dict, realtime: dict, state: ControlState,
now: float | None = None) -> dict:
"""把 suggestion 过安全门,返回可下发的安全指令与拦截项。
realtime: {pressure(MPa), pumps:[{id,freq,status}], ...} 当前实况。
返回: {approved, command:{active,freqs}, interventions:[...], reasons:[...], watchdog_ok}
"""
now = now if now is not None else time.time()
interventions: list[str] = []
reasons: list[str] = []
cur_freq = {p["id"]: float(p.get("freq", 0.0)) for p in realtime.get("pumps", [])}
cur_active = {p["id"] for p in realtime.get("pumps", []) if int(p.get("status", 0)) == 1}
hold_cmd = {"active": sorted(cur_active),
"freqs": {pid: cur_freq.get(pid, 0.0) for pid in cur_active}}
# 1) 写使能
if not state.write_enable:
reasons.append("写使能未开启(bWriteEnable=False),AI 不下发")
return self._result(False, hold_cmd, interventions, reasons, True)
# 2) watchdog 心跳超时 → 切回本地 PID/工频(无扰:维持最后有效设定)
age = state.watchdog_age(now)
watchdog_ok = age <= self.watchdog_timeout_s
if not watchdog_ok:
reasons.append(f"watchdog 心跳超时 {age:.1f}s>{self.watchdog_timeout_s}s,切回本地 PID")
return self._result(False, hold_cmd, interventions, reasons, False)
# 3) CRITICAL 报警跳过优化(文档 alarm.has_critical())
if state.critical_alarm:
reasons.append("CRITICAL 报警有效,跳过优化,维持当前设定")
return self._result(False, hold_cmd, interventions, reasons, True)
# 3b) 低水位保护停泵(防干抽,对应 SCADA LL 报警)——硬联锁,停全部
level = realtime.get("level")
if self.level_ll_stop > 0 and level is not None and float(level) < self.level_ll_stop:
reasons.append(f"低水位保护:液位 {float(level):.2f}<{self.level_ll_stop}m,停泵防干抽")
return self._result(False, {"active": [], "freqs": {}}, interventions, reasons, True)
# 高水位提示(需增泵防溢流,不阻断启泵)
high_level = self.level_hh > 0 and level is not None and float(level) > self.level_hh
if high_level:
interventions.append(f"高水位:液位 {float(level):.2f}>{self.level_hh}m,建议增泵防溢流")
# 4) 高压硬联锁:出口压力越限,禁止升频/启泵(仅允许维持或降)
pressure = float(realtime.get("pressure", 0.0))
high_pressure = pressure > self.pressure_max_mpa
if high_pressure:
interventions.append(f"高压保护:出口压力 {pressure:.3f}>{self.pressure_max_mpa}MPa,禁止升频/启泵")
target_active = list(suggestion.get("active", []))
target_freq = {int(k): float(v) for k, v in suggestion.get("freqs", {}).items()}
# 5) 最少运行台数保证
if len(target_active) < self.min_pumps:
reasons.append(f"建议台数 {len(target_active)}<最少 {self.min_pumps},维持当前")
return self._result(False, hold_cmd, interventions, reasons, True)
# 6) 逐泵生成安全频率:斜坡限速 + 限幅 + 工频锁定 + 高压闭锁升频/启泵
safe_freq: dict = {}
for pid in target_active:
is_vfd = self.variable_speed.get(pid, True)
tgt = self._clip(self.freq_max if not is_vfd else target_freq.get(pid, self.freq_min))
if pid in cur_active:
cur = cur_freq.get(pid, self.freq_max)
step = tgt - cur
if abs(step) > self.freq_step_per_cycle: # 斜坡限速
tgt = cur + self.freq_step_per_cycle * (1 if step > 0 else -1)
interventions.append(f"频率限速:{pid}号 {cur:.1f}→{tgt:.1f}(目标{target_freq.get(pid, self.freq_max):.1f})")
if high_pressure and tgt > cur: # 高压禁止升频
tgt = cur
interventions.append(f"高压闭锁:{pid}号维持 {cur:.1f}Hz 不升频")
else:
# 新启泵:从 start_freq 起(高压时禁止启泵)
if high_pressure:
interventions.append(f"高压闭锁:{pid}号禁止启泵")
continue
tgt = self._clip(self.start_freq if is_vfd else self.freq_max)
interventions.append(f"软启动:{pid}号起始 {tgt:.1f}Hz 后逐周期斜坡")
safe_freq[pid] = round(self._clip(tgt), 2)
if len(safe_freq) < self.min_pumps: # 高压闭锁后兜底
reasons.append("安全联锁后可运行台数不足,维持当前")
return self._result(False, hold_cmd, interventions, reasons, True)
command = {"active": sorted(safe_freq.keys()), "freqs": safe_freq}
state.last_command = command
return self._result(True, command, interventions, reasons, True)
@staticmethod
def _result(approved, command, interventions, reasons, watchdog_ok):
return {
"approved": approved,
"command": command,
"interventions": interventions,
"reasons": reasons,
"watchdog_ok": watchdog_ok,
}