File size: 15,178 Bytes
aec7019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86b96f3
aec7019
 
 
 
 
 
 
86b96f3
 
aec7019
 
 
86b96f3
aec7019
 
 
 
 
 
 
 
86b96f3
1199a79
 
aec7019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1199a79
 
 
 
 
 
aec7019
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""FastAPI 入口:暴露优化建议与曲线/工作点查询(文档 4.2 API 草案的 Phase2 部分)。

数据采集由 Node-RED(node-red-contrib-opcua)承担,本服务专注优化算法。
现场可把 /api/realtime 的 Node-RED 快照 POST 进来驱动优化,或由 Node-RED 定时拉取 /api/optimization/suggestion。
"""
from __future__ import annotations

import asyncio
import os
import time
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, Optional

from fastapi import FastAPI, WebSocket
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel

from .integration_api import router as integration_router
from .cloud_api import router as cloud_router, forwarder as cloud_forwarder
from .demo_runtime import demo_runtime
from .plant import Plant


@asynccontextmanager
async def lifespan(_: FastAPI):
    await demo_runtime.start_from_env()
    cloud_task = asyncio.create_task(
        cloud_forwarder.run(lambda: demo_runtime.latest))   # 云端转发后台循环
    try:
        yield
    finally:
        cloud_task.cancel()
        await demo_runtime.stop()


app = FastAPI(title="泵站 AI 节能优化服务", version="0.2.0", lifespan=lifespan)
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],
)
app.include_router(integration_router)
app.include_router(cloud_router)
from .branding_api import router as branding_router  # noqa: E402
app.include_router(branding_router)

plant = Plant()


class OptimizeRequest(BaseModel):
    Q_target: Optional[float] = None                 # 目标流量 m³/h;缺省用预测/均值
    current_freqs: dict[int, float] = {}             # {pump_id: freq}
    current_active: list[int] = []                   # 当前在运泵
    run_hours: dict[int, float] = {}                 # 累计运行 h(轮换均衡)
    current_total_power: Optional[float] = None       # 当前实测总有功功率 kW
    level: Optional[float] = None                     # 当前集水井液位 m


class ModeRequest(BaseModel):
    mode: str                                        # manual | auto


class EnableRequest(BaseModel):
    enable: bool


class AlarmRequest(BaseModel):
    critical: bool


class ApplyRequest(BaseModel):
    suggestion: dict[str, Any]                       # {active, freqs}
    realtime: dict[str, Any]                         # {pressure, pumps:[{id,freq,status}], ...}


@app.get("/api/health")
def health():
    return {
        "status": "ok",
        "pumps": list(plant.pumps.keys()),
        "historical_opc_demo": {
            "enabled": demo_runtime.enabled,
            "ready": demo_runtime.latest is not None,
            "error": demo_runtime.error,
        },
    }


@app.get("/api/realtime")
def realtime_snapshot():
    if demo_runtime.latest is None:
        return {
            "success": False,
            "source": "historical_opc_replay",
            "error": demo_runtime.error or "Historical OPC replay is starting",
        }
    return demo_runtime.latest


@app.get("/api/config")
def config():
    """泵组配置(数量 + 每台性质)+ 约束 + 频率范围,供前端动态构建。"""
    return {
        "station": plant.station.get("name"),
        "freq_min": plant.station["freq_min"],
        "freq_max": plant.station["freq_max"],
        "constraints": plant.constraints,
        "level_range": plant.level_range,
        "pumps": [plant.pump_meta[pid] for pid in plant.pumps],
    }


@app.get("/api/pump/{pid}/curve")
def pump_curve(pid: int, freq: float = 50.0, n: int = 40):
    """单泵曲线(给定频率):H-Q / η-Q / P-Q 采样点。"""
    if pid not in plant.pumps:
        return {"success": False, "error": "no such pump"}
    pm = plant.pumps[pid]
    qmin, qmax = pm.q_min(freq), pm.q_max(freq)
    hq, eq, pq = [], [], []
    for i in range(n + 1):
        q = qmin + (qmax - qmin) * i / n
        hq.append([round(q, 2), round(pm.head(q, freq), 3)])
        eq.append([round(q, 2), round(pm.eta(q, freq) * 100, 2)])
        p = pm.input_power(q, freq)
        if p == p:
            pq.append([round(q, 2), round(p, 3)])
    return {"success": True, "pump_id": pid, "freq": freq,
            "bep_flow": round(pm.bep_flow(freq), 2),
            "meta": plant.pump_meta[pid],
            "HQ": hq, "etaQ": eq, "PQ": pq}


class IdentifyRequest(BaseModel):
    # 历史运行点:每条含 Q(m³/h), H(m), 以及 P(kW) 或 eta(0~1), freq(Hz)
    records: list[dict[str, Any]]
    variable_speed: bool = True
    rated_kw: Optional[float] = None
    name: Optional[str] = None


class CurveFitRequest(BaseModel):
    # 数字化的曲线点(额定频率):H-Q 必填,η-Q 可选
    hq: list[list[float]]                            # [[Q,H],...]
    eta: Optional[list[list[float]]] = None          # [[Q,eta],...],eta 百分数或小数


class CurveApplyRequest(BaseModel):
    poly: dict[str, float]                           # {a0,a1,a2,q_max}
    eta_gauss: dict[str, float]                      # {eta_max,q_bep,sigma}
    name: Optional[str] = None
    variable_speed: Optional[bool] = None
    rated_kw: Optional[float] = None


@app.post("/api/pump/{pid}/curve/fit")
def curve_fit_endpoint(pid: int, req: CurveFitRequest):
    """把在曲线图上点取(或粘贴)的 H-Q / η-Q 数据点拟合成 poly+高斯参数,并回采样预览。"""
    from .models.curve_fit import fit_from_points
    from .models.pump_curve import PumpCurveModel
    try:
        fit = fit_from_points(req.hq, req.eta)
    except (ValueError, RuntimeError) as e:
        return {"success": False, "error": str(e)}
    # 用拟合参数建临时模型出预览曲线
    preview = None
    if fit.get("eta_gauss"):
        p = fit["poly"]; g = fit["eta_gauss"]
        m = PumpCurveModel.from_poly(pid, p["a0"], p["a1"], p["a2"], p["q_max"],
                                     g["eta_max"], g["q_bep"], g["sigma"],
                                     freq_nominal=plant.station["freq_nominal"])
        qmax = m.q_max(50.0)
        preview = {"HQ": [[round(qmax * i / 40, 1), round(m.head(qmax * i / 40, 50), 3)] for i in range(41)],
                   "etaQ": [[round(qmax * i / 40, 1), round(m.eta(qmax * i / 40, 50) * 100, 2)] for i in range(41)]}
    return {"success": True, **fit, "preview": preview}


@app.post("/api/pump/{pid}/curve/apply")
def curve_apply(pid: int, req: CurveApplyRequest):
    """把拟合好的曲线应用到该泵(运行时热更新 + 持久化,无需改 YAML)。"""
    if pid not in plant.pumps:
        return {"success": False, "error": "no such pump"}
    spec = {"poly": req.poly, "eta_gauss": req.eta_gauss}
    if req.name is not None:
        spec["name"] = req.name
    if req.variable_speed is not None:
        spec["variable_speed"] = req.variable_speed
    if req.rated_kw is not None:
        spec["rated_kw"] = req.rated_kw
    try:
        meta = plant.apply_curve(pid, spec)
    except (KeyError, ValueError, TypeError) as e:
        return {"success": False, "error": str(e)}
    return {"success": True, "meta": meta, "curve": plant.sampled_curve(pid)}


@app.post("/api/pump/{pid}/identify")
def identify(pid: int, req: IdentifyRequest):
    """从历史运行数据辨识该泵曲线,返回 a0/a1/a2 + 高斯效率参数、拟合 R²,
    以及可直接粘进 pumps.yaml 的片段。用历史数据反推真实曲线。"""
    from .models.curve_fit import identify_pump, to_yaml_block
    try:
        ident = identify_pump(
            req.records, freq_nominal=plant.station["freq_nominal"],
            pump_id=pid, name=req.name, variable_speed=req.variable_speed,
            rated_kw=req.rated_kw,
        )
    except (ValueError, RuntimeError) as e:
        return {"success": False, "error": str(e)}
    ident["yaml"] = to_yaml_block(ident)
    ident["success"] = True
    return ident


@app.post("/api/optimization/suggestion")
def suggestion(req: OptimizeRequest):
    """核心:给出最优开泵组合与频率建议,并对比全 50Hz 基线的节能潜力。"""
    Q_target = req.Q_target
    if Q_target is None:
        Q_target = plant.forecaster.predict() or plant.forecaster.current_avg() or 300.0

    result = plant.optimizer.optimize(
        Q_target=Q_target,
        current_freqs={int(k): float(v) for k, v in req.current_freqs.items()},
        current_active=[int(x) for x in req.current_active],
        run_hours={int(k): float(v) for k, v in req.run_hours.items()},
        level=req.level,
    )
    if not result.get("success"):
        return result

    # 基线优先使用总管流量 + 实测总有功功率。即使2号泵反馈频率未知,
    # 也能形成真实SEC基线;未知频率绝不再按0 Hz处理。
    cur_active = [int(x) for x in req.current_active]
    cur_freqs = {int(k): float(v) for k, v in req.current_freqs.items()}
    if req.current_total_power is not None and req.current_total_power > 0 and Q_target > 0:
        base_data = {
            "P_total": float(req.current_total_power),
            "spec_energy": float(req.current_total_power) / float(Q_target),
            "Q_total": float(Q_target),
            "kind": "current_measured",
        }
    elif cur_active and all(cur_freqs.get(p, 0) > 1e-6 for p in cur_active):
        base = plant.group.solve(
            {p: cur_freqs[p] for p in cur_active}, level=req.level
        )
        if base.feasible:
            base_data = {
                "P_total": base.P_total, "spec_energy": base.spec_energy,
                "Q_total": base.Q_total, "kind": "current_modelled",
            }
        else:
            base = plant.baseline_meet_target(Q_target, level=req.level)
            base_data = {
                "P_total": base.P_total, "spec_energy": base.spec_energy,
                "Q_total": base.Q_total, "kind": "meet_target_50hz",
            }
    else:
        base = plant.baseline_meet_target(Q_target, level=req.level)
        base_data = {
            "P_total": base.P_total, "spec_energy": base.spec_energy,
            "Q_total": base.Q_total, "kind": "meet_target_50hz",
        }

    saving = None
    if base_data["spec_energy"] > 1e-6:
        saving = round(
            (base_data["spec_energy"] - result["spec_energy"])
            / base_data["spec_energy"] * 100, 1
        )
    result["Q_target"] = round(Q_target, 2)
    result["baseline"] = {
        "P_total": round(base_data["P_total"], 2),
        "spec_energy": round(base_data["spec_energy"], 4),
        "Q_total": round(base_data["Q_total"], 2),
        "kind": base_data["kind"],
    }
    result["sec_saving_pct"] = saving
    if saving is None:
        result.update({
            "status": "baseline_unavailable", "executable": False,
            "message": "缺少可比较的实测功率基线,仅展示计算结果,不下发。",
        })
    elif saving <= 0:
        result.update({
            "status": "no_improvement", "executable": False,
            "message": "未找到优于当前工况的方案,建议保持现状。",
        })
    else:
        result.update({"status": "optimized", "executable": True})
    return result


# ---------------- Phase 3 控制 / 安全联锁 ----------------

def _control_snapshot():
    st = plant.control
    return {
        "mode": st.mode,
        "write_enable": st.write_enable,
        "critical_alarm": st.critical_alarm,
        "reverted": st.reverted,
        "heartbeat_count": st.heartbeat_count,
        "watchdog_age_s": round(st.watchdog_age(), 2),
        "watchdog_ok": st.watchdog_age() <= plant.safety_gate.watchdog_timeout_s,
        "watchdog_timeout_s": plant.safety_gate.watchdog_timeout_s,
        "last_command": st.last_command,
    }


@app.get("/api/control/state")
def control_state():
    return _control_snapshot()


@app.post("/api/control/mode")
def set_mode(req: ModeRequest):
    if req.mode not in ("manual", "auto"):
        return {"success": False, "error": "mode must be manual|auto"}
    plant.control.mode = req.mode
    if req.mode == "auto":                 # 进入闭环即视为一次心跳、清除切回标志
        plant.control.reverted = False
        plant.control.beat()
    return {"success": True, **_control_snapshot()}


@app.post("/api/control/enable")
def set_enable(req: EnableRequest):
    plant.control.write_enable = bool(req.enable)
    return {"success": True, **_control_snapshot()}


@app.post("/api/control/alarm")
def set_alarm(req: AlarmRequest):
    plant.control.critical_alarm = bool(req.critical)
    return {"success": True, **_control_snapshot()}


@app.post("/api/control/heartbeat")
def heartbeat():
    plant.control.beat()
    return {"success": True, **_control_snapshot()}


@app.post("/api/control/revert")
def revert():
    """一键反悔 / 无扰切回:停自动、关写使能、切回本地 PID(维持最后有效设定)。"""
    plant.control.mode = "manual"
    plant.control.write_enable = False
    plant.control.reverted = True
    return {"success": True, "message": "已切回手动/本地 PID(无扰,维持最后有效设定)",
            **_control_snapshot()}


@app.post("/api/optimization/apply")
def apply(req: ApplyRequest):
    """闭环下发:把建议过安全门控(写使能/限幅/斜坡/高压/watchdog/最少台数),
    返回可下发的安全指令与拦截项。调用本身兼作一次心跳。"""
    plant.control.beat()                   # 前端每周期调用即喂狗
    gated = plant.safety_gate.gate(
        suggestion=req.suggestion, realtime=req.realtime,
        state=plant.control, now=time.time(),
    )
    return {"success": True, "mode": plant.control.mode, **gated}


@app.websocket("/ws/realtime")
async def realtime_ws(websocket: WebSocket):
    """Stream the internal historical OPC replay in single-container demos."""
    await websocket.accept()
    if not demo_runtime.enabled:
        await websocket.close(code=1013, reason="Realtime source unavailable")
        return
    try:
        while True:
            if demo_runtime.latest is not None:
                await websocket.send_json(demo_runtime.latest)
            await asyncio.sleep(1.0)
    except Exception:
        return


# ---------------- 静态前端托管(单进程/单容器:后端直接提供大屏)----------------
# 存在 frontend 目录则挂到根路径,实现「一个进程 = 大屏 + API」,方便任意平台一步部署。
# 挂载放在所有 /api 路由之后,作为兜底(catch-all),不影响 API。
_FRONT = os.environ.get(
    "FRONTEND_DIR", str(Path(__file__).resolve().parents[2] / "frontend"))
if Path(_FRONT).is_dir():
    from fastapi.responses import FileResponse
    _home = Path(_FRONT) / "home.html"
    if _home.exists():
        @app.get("/", include_in_schema=False)   # 首页=品牌封面/登录页;大屏在 index.html
        def _landing():
            return FileResponse(str(_home), headers={"Cache-Control": "no-store"})
    app.mount("/", StaticFiles(directory=_FRONT, html=True), name="frontend")