Codex commited on
Commit
aec7019
·
0 Parent(s):

Deploy efficiency estimate fix cf55248

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +9 -0
  2. .env.example +6 -0
  3. .gitignore +30 -0
  4. Dockerfile +32 -0
  5. README.md +199 -0
  6. backend/.dockerignore +7 -0
  7. backend/Dockerfile +21 -0
  8. backend/README.md +143 -0
  9. backend/app/__init__.py +0 -0
  10. backend/app/demo_runtime.py +177 -0
  11. backend/app/integration_api.py +298 -0
  12. backend/app/integration_config.py +287 -0
  13. backend/app/main.py +382 -0
  14. backend/app/models/__init__.py +0 -0
  15. backend/app/models/curve_fit.py +164 -0
  16. backend/app/models/forecaster.py +56 -0
  17. backend/app/models/parallel.py +127 -0
  18. backend/app/models/pump_curve.py +143 -0
  19. backend/app/opcua_replay_server.py +226 -0
  20. backend/app/opcua_sim_server.py +145 -0
  21. backend/app/optimizer/__init__.py +0 -0
  22. backend/app/optimizer/mpc.py +154 -0
  23. backend/app/plant.py +190 -0
  24. backend/app/safety.py +143 -0
  25. backend/app/sim/__init__.py +0 -0
  26. backend/app/sim/hydraulic.py +49 -0
  27. backend/config/pumps.yaml +121 -0
  28. backend/requirements.txt +12 -0
  29. backend/tests/__init__.py +0 -0
  30. backend/tests/test_curve.py +64 -0
  31. backend/tests/test_curve_fit.py +92 -0
  32. backend/tests/test_demo_runtime.py +31 -0
  33. backend/tests/test_forecaster.py +32 -0
  34. backend/tests/test_integration_config.py +83 -0
  35. backend/tests/test_integration_runtime.py +54 -0
  36. backend/tests/test_mpc.py +63 -0
  37. backend/tests/test_opcua_replay_server.py +48 -0
  38. backend/tests/test_parallel.py +62 -0
  39. backend/tests/test_safety.py +138 -0
  40. backend/tests/test_suggestion_api.py +35 -0
  41. backend/tools/fit_curve.py +59 -0
  42. backend/tools/opcua_test_client.py +50 -0
  43. demo-data/README.md +17 -0
  44. demo-data/pump_history_demo.csv +0 -0
  45. deploy/DEPLOY_HF.md +56 -0
  46. deploy/deploy_hf.sh +34 -0
  47. deploy/start_pc_opc.cmd +23 -0
  48. docker-compose.pc-opc.yml +22 -0
  49. docker-compose.yml +77 -0
  50. docs/PC-OPCUA鍘嗗彶鍥炴斁.md +69 -0
.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ **/__pycache__/
2
+ **/*.pyc
3
+ **/.pytest_cache/
4
+ backend/tests/
5
+ backend/config/curve_overrides.json
6
+ .git/
7
+ .venv/
8
+ venv/
9
+ node_modules/
.env.example ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Node-RED 读取后台运行配置时使用的内部令牌。
2
+ # 无账号/密码的 OPC 首轮联调可以留空;需要保存 OPC 密码时必须设置为随机长字符串。
3
+ INTEGRATION_INTERNAL_TOKEN=
4
+
5
+ # 可选:如果不在页面保存密码,也可以只通过环境变量提供。
6
+ # OPCUA_PASSWORD=
.gitignore ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .pytest_cache/
6
+ .venv/
7
+ venv/
8
+
9
+ # Node
10
+ node_modules/
11
+
12
+ # OS/editor
13
+ .DS_Store
14
+ *.swp
15
+
16
+ # 运行时曲线覆盖(软件上传,app 管理)
17
+ backend/config/curve_overrides.json
18
+
19
+ # 现场历史数据仅用于本地 OPC 回放,禁止提交到公开仓库
20
+ private-data/
21
+ /backend/data/
22
+
23
+ # Local runtime/test artifacts
24
+ *.log
25
+ .pytest-tmp-*/
26
+ backend/pytest-cache-files-*/
27
+
28
+ # Derived document renders (keep the source PDF/XLSX files)
29
+ docs/Flygt_NS3202LT610_page*.png
30
+ docs/sources/*_page*.png
Dockerfile ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 单容器全栈(大屏 + 优化API 同进程同源)——最省事部署:任意平台一步起
2
+ # 适合:自有服务器 / Zeabur / Sealos / Hugging Face Spaces / Render / Fly.io 等。
3
+ # 构建上下文 = 仓库根目录: docker build -t biditech-pump .
4
+ FROM python:3.11-slim
5
+
6
+ WORKDIR /app
7
+
8
+ COPY backend/requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ COPY backend/app ./app
12
+ COPY backend/config ./config
13
+ COPY backend/tools ./tools
14
+ COPY frontend ./frontend
15
+ COPY demo-data ./demo-data
16
+
17
+ # FastAPI 同时托管前端(frontend/) + API;曲线上传持久化到 /data
18
+ ENV FRONTEND_DIR=/app/frontend \
19
+ BIDITECH_CURVE_OVERRIDES=/data/curve_overrides.json \
20
+ BIDITECH_INTEGRATION_CONFIG=/data/integration_config.json \
21
+ BIDITECH_OPCUA_SECRET=/data/opcua_secret.json \
22
+ BIDITECH_DEMO_REPLAY_CSV=/app/demo-data/pump_history_demo.csv \
23
+ BIDITECH_DEMO_OPCUA_ENDPOINT=opc.tcp://127.0.0.1:4840/biditech/server/ \
24
+ BIDITECH_DEFAULT_OPCUA_ENDPOINT=opc.tcp://127.0.0.1:4840/biditech/server/ \
25
+ BIDITECH_DEMO_REPLAY_INTERVAL=1.0 \
26
+ PORT=8000
27
+ # /data 写入曲线上传;HF Spaces 以非 root 用户运行,放开写权限
28
+ RUN mkdir -p /data && chmod 777 /data
29
+
30
+ EXPOSE 8000
31
+ # 平台若要求特定端口(如 Hugging Face Spaces 用 7860),设置环境变量 PORT 即可
32
+ CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-8000}"]
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: 提升泵站 AI 节能优化
3
+ emoji: 💧
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 8000
8
+ pinned: false
9
+ ---
10
+
11
+ # 提升泵站 AI 节能优化应用软件
12
+
13
+ 上海碧帝数据科技有限公司(Biditech)。面向中小型供水/提升泵站的 AI 节能优化,
14
+ 算法内核复用《泵组节能优化算法软件 V1.0》(曲线建模 + 相似定律 + MPC 组合优化 + 来水预测 + 安全联锁)。
15
+
16
+ ## 集成模型(本次改造要点)
17
+
18
+ 我方软件**被力控集成**(力控作展示宿主),但作为**独立 solution 自带 OPC 数据能力**,
19
+ 用 **Node-RED(node-red-contrib-opcua)独立采集 OPC UA 数据**,**不依赖力控原生 OPC 能力**;
20
+ 最终以**单文件 HTML 展示页嵌入力控画面(FWebView / iframe)显示**。
21
+
22
+ ```
23
+ PLC / OPC UA Server ──OPC UA──▶ Node-RED(独立采集) ──WS/REST──▶ HTML+ECharts ──嵌入──▶ 力控 FWebView
24
+ ```
25
+
26
+ 好处:力控产品线/版本差异(通用版 / pSpace / ForceSCADA)与「力控 OPC UA Server 能力不明」
27
+ 不再构成阻塞。仅当现场硬性禁止直连 PLC 时,才回退到经力控透传的网关方案(见文档 1.2 附录)。
28
+
29
+ ### 数据接入配置中心
30
+
31
+ 现场人员不再修改 Node-RED flow 或 YAML。打开 `/config.html` 可以完成:
32
+
33
+ - OPC UA 地址、安全策略、账号、采样周期和断线重连配置;
34
+ - 连接测试、命名空间识别和节点逐层浏览;
35
+ - 41 个标准泵站字段的 NodeId、类型、单位、倍率和偏移映射;
36
+ - 仿真/真实 OPC 切换,以及全部已启用点位的只读实时预览。
37
+
38
+ Node-RED 每 10 秒读取后台配置并动态切换端点。详细步骤见 `docs/配置中心与PC-Server联调.md`。
39
+
40
+ ## 目录
41
+
42
+ | 路径 | 说明 |
43
+ |--|--|
44
+ | `docs/技术开发说明文档.md` | 完整技术方案(集成章节已按新模型修订) |
45
+ | `frontend/index.html` | 单文件 HTML 展示页(ECharts,五大视图,含 AI 建议/自动闭环),可嵌入力控 |
46
+ | `frontend/config.html` | 数据接入配置中心(连接、浏览、映射、实时预览) |
47
+ | `node-red/flows-configurable.json` | 后台配置驱动的通用 OPC 采集 + 仿真 + REST/WS flow |
48
+ | `node-red/README.md` | Node-RED 安装 / 导入 / 对接真实 OPC / 嵌入力控说明 |
49
+ | `docs/配置中心与PC-Server联调.md` | Docker Desktop 与现场 PC Server 联调步骤 |
50
+ | `backend/` | 优化算法后端(Python/FastAPI):曲线建模 + 并联 + **枚举组合×L-BFGS-B 优化** + 来水预测 + HIL 仿真 + REST API,见 `backend/README.md` |
51
+
52
+ ## 部署
53
+
54
+ ### 最省事:单容器全栈(一个进程 = 大屏 + API,任意平台一步)
55
+
56
+ 后端同进程托管前端大屏,只需**一个容器、一个端口**,适合自有服务器 / Zeabur / Sealos /
57
+ Hugging Face Spaces / Render / Fly.io:
58
+
59
+ ```bash
60
+ docker build -t biditech-pump .
61
+ docker run -d -p 8000:8000 -v pump-data:/data biditech-pump
62
+ # 打开 http://<服务器IP>:8000 ← 大屏 + AI优化 + 曲线上传,全在这一个地址(同源)
63
+ ```
64
+
65
+ - 不用 Docker 也行(自有服务器直接跑):
66
+ ```bash
67
+ cd backend && pip install -r requirements.txt
68
+ FRONTEND_DIR=../frontend uvicorn app.main:app --host 0.0.0.0 --port 8000
69
+ ```
70
+ 再用现有 nginx 反代一个子域名(如 `pump.biditech.cn` → `127.0.0.1:8000`)即可,和现网站互不干扰。
71
+ - 平台要求特定端口时设环境变量 `PORT`(如 Hugging Face Spaces:Space 配置 `app_port: 8000`,或 `PORT=7860`)。
72
+ - 这一个容器不含 Node-RED/OPC 采集;实时数据用内置仿真(够演示全部功能)。要真实 OPC 数据链路,用下面的 compose 全栈。
73
+
74
+ ### 部署到 Hugging Face Spaces(免费,一推即部署)
75
+
76
+ 本仓根目录已含 HF Space 所需的 `Dockerfile` 与 README 头部(`sdk: docker`, `app_port: 8000`)。
77
+ 在**能访问 huggingface.co 的电脑**上:
78
+
79
+ ```bash
80
+ # 1) 在 https://huggingface.co/new-space 建一个 Space:SDK 选 Docker(名字如 pump)
81
+ # 2) 把本仓推到该 Space(用你的 HF 写入令牌 https://huggingface.co/settings/tokens)
82
+ git remote add hf https://<用户名>:<HF_TOKEN>@huggingface.co/spaces/<用户名>/pump
83
+ git push hf HEAD:main
84
+ # 3) HF 自动构建,几分钟后打开 https://huggingface.co/spaces/<用户名>/pump 即大屏
85
+ ```
86
+
87
+ (免费 CPU 版即可;曲线上传数据在免费版重启后不保留,够演示。)
88
+
89
+ ### 完整全栈:docker compose(含 Node-RED + OPC UA 仿真)
90
+
91
+ 服务器装好 Docker 与 Compose 后,在仓库根目录:
92
+
93
+ ```bash
94
+ docker compose up -d --build # 首次构建并后台启动全部服务
95
+ docker compose ps # 查看状态
96
+ docker compose logs -f backend # 看日志
97
+ ```
98
+
99
+ compose 里前端 nginx 已把 `/api`→后端、`/ws`→Node-RED 同源反代,浏览器只需访问 `:8080`。
100
+
101
+ 起来后(把 `<服务器IP>` 换成实际地址):
102
+
103
+ | 服务 | 地址 | 说明 |
104
+ |--|--|--|
105
+ | 展示大屏 | `http://<服务器IP>:8080` | 打开即用(内置仿真数据 + 连后端做 AI 优化/曲线上传) |
106
+ | 优化后端 API | `http://<服务器IP>:8077` | `/api/config`、`/api/optimization/suggestion`、`/api/pump/{id}/curve/...` |
107
+ | Node-RED | `http://<服务器IP>:1880` | OPC 采集编排(默认跑仿真分支,可切真实/仿真 OPC) |
108
+ | OPC UA 仿真 | `opc.tcp://<服务器IP>:4840/biditech/server/` | UaExpert / 现场联调 |
109
+
110
+ 在服务器上打开 `:8080` 即整套连通(前端按所在主机名访问 8077/1880)。
111
+
112
+ - 曲线上传持久化到 `pump-data` 卷(`curve_overrides.json`),重启不丢。
113
+ - 走真实 OPC 数据链路:Node-RED 里启用分支③(端点在 Docker 内已指向 `opcua-sim:4840`)、
114
+ 禁用①的 inject 后 Deploy;`docker compose logs` 里 flow 未自动加载时,可在 Node-RED
115
+ 编辑器「导入」`node-red/flows.json`。
116
+ - 对接现场标准 PC:把 `opcua-sim` 换成现场 OPC UA 服务器地址即可(改 Node-RED 端点)。
117
+
118
+ ```bash
119
+ docker compose down # 停止(保留数据卷)
120
+ docker compose down -v # 停止并清除数据卷
121
+ ```
122
+
123
+ ## 本地跑通原型
124
+
125
+ **只看界面(零依赖)**:浏览器直接打开 `frontend/index.html` 即可——无数据源时自动用
126
+ 内置仿真数据渲染全部四个视图(右上角显示黄色「仿真数据」)。
127
+
128
+ **完整链路(含 Node-RED)**:
129
+
130
+ ```bash
131
+ cd ~/.node-red && npm install node-red-contrib-opcua
132
+ node-red # http://localhost:1880
133
+ # 菜单 → 导入 → 粘贴 node-red/flows.json → Deploy
134
+ curl http://localhost:1880/api/realtime # 验证快照
135
+ ```
136
+
137
+ 然后打开 `frontend/index.html`,右上角状态变「已连接 · OPC 实时」,数据每秒更新。
138
+ 现场对接真实 OPC 的步骤见 `node-red/README.md`。
139
+
140
+ ## 优化算法(Phase 2 开环建议)
141
+
142
+ `backend/` 按文档第 2 章实现节能优化内核:三次样条曲线建模 + 相似定律、brentq 求并联工作点、
143
+ **枚举开泵组合 × scipy L-BFGS-B 优化频率**、滑动窗口来水预测,并以 HIL 水力仿真验证。
144
+
145
+ ```bash
146
+ cd backend && pip install -r requirements.txt
147
+ python -m pytest -q # 26 项单测通过
148
+ python -m uvicorn app.main:app --port 8077 # POST /api/optimization/suggestion
149
+ ```
150
+
151
+ 给定目标流量与当前状态,返回最优开泵组合/频率及相对「全 50Hz 基线」的 SEC 改善(实测示例 ~40%)。
152
+ 详见 `backend/README.md`。
153
+
154
+ ## 整链路演示(采集 → 优化 → 界面确认)
155
+
156
+ 展示页的「AI 优化建议」视图已接通优化后端,可在演示台上跑通完整闭环:
157
+
158
+ ```bash
159
+ # 1) 启动优化后端
160
+ cd backend && pip install -r requirements.txt
161
+ python -m uvicorn app.main:app --port 8077
162
+
163
+ # 2) 打开展示页(无 Node-RED 时自动用内置仿真数据)
164
+ # 浏览器打开 frontend/index.html → 左栏「AI 优化建议」
165
+ ```
166
+
167
+ 「AI 优化建议」页支持两种模式(可随时一键反悔切回):
168
+
169
+ - **手动开环建议**:点**获取 AI 建议** → 前端把实时快照 POST 给 `/api/optimization/suggestion`
170
+ → 展示建议开泵组合/频率与 SEC 改善(示例 ~42%)→ 点**人工确认执行**应用到仿真。
171
+ - **自动闭环(安全联锁)**:打开**写使能**后,每 3s 自动取建议并经
172
+ `/api/optimization/apply` 过安全门控(写使能 / 指令限幅 20–50Hz / ≤5Hz 每周期斜坡 /
173
+ 高压硬联锁 / watchdog 心跳超时切回 PID / CRITICAL 报警跳过 / 最少台数保证),
174
+ 下发经门控后的安全指令;安全状态条与拦截项实时显示。
175
+ - **一键反悔 / 切回**:立即停自动、关写使能、无扰切回手动(维持最后有效设定)。
176
+
177
+ ## 泵组配置(数量 + 每台性质)
178
+
179
+ 泵数量与每台泵性质由 `backend/config/pumps.yaml` 驱动,前端启动时读 `/api/config` 同步
180
+ (后端不可达则用前端默认花名册)。当前为**海斯特污水提升泵站**:**5 台,变频 1#/2#/5#、工频 3#/4#**
181
+ (1# 飞力 Flygt,2–5# 海斯特 F10K;`variable_speed: true/false`;工频泵只能开停、锁 50Hz)。
182
+ 海斯特铭牌工况 **Q=850 m³/h, H=14.5m, DN300**;集水井 6.5×8.8=57.2 m²,液位 3–9m;恒流量控制、三用二备。
183
+ 改台数/性质/曲线只需编辑该 YAML,无需动代码。
184
+
185
+ 曲线支持两种写法:测点 `curve:{Q,H,eta}`,或 **V1.0 参数形式**
186
+ `poly:{a0,a1,a2,q_max}`+`eta_gauss:{eta_max,q_bep,sigma}`(二次多项式 + 高斯效率,与软著 V1.0 一致)。
187
+ 有各泵 a0/a1/a2、η_max、Q_bep 现场标定值直接填入即变真实机组。
188
+
189
+ **无出口压力表**:扬程由「集水井液位 + 系统曲线」估计 H=static(level)+S·Q²(液位越低静扬程越大,
190
+ 用实时液位替代压力表)。**SCADA 只有电流**:功率由 `power_from_current`=√3·U·I·PF 反算。
191
+ 部分工频、且静扬程高(14.5m),有效调频区间偏窄,节能率天花板约 5–7%。
192
+
193
+ ## 展示页五大视图
194
+
195
+ 1. 泵组 H-Q 特性曲线(多频率曲线族 + 绿色高效区 + 实时工况点)
196
+ 2. 单泵性能曲线(H-Q / η-Q / P-Q,出厂 vs 实测,高效区/越界区 + BEP + 数值面板)
197
+ 3. 泵站总览(各泵频率/电流/功率/状态卡片 + 液位/压力/流量/SEC KPI)
198
+ 4. 效率性能曲线(η-Q 曲线族 + 实时效率点)
199
+ 5. **AI 优化建议**(调用优化后端,当前 vs 建议对比 + SEC 改善 + 人工确认执行)
backend/.dockerignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .pytest_cache/
4
+ tests/
5
+ config/curve_overrides.json
6
+ .venv/
7
+ venv/
backend/Dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 优化后端 + OPC UA 仿真服务器(同一镜像,compose 里用不同 command 起两个服务)
2
+ FROM python:3.11-slim
3
+
4
+ WORKDIR /app
5
+
6
+ # numpy/scipy/cryptography 均有 manylinux wheel,slim 直接装无需编译
7
+ COPY requirements.txt .
8
+ RUN pip install --no-cache-dir -r requirements.txt
9
+
10
+ COPY app ./app
11
+ COPY config ./config
12
+ COPY tools ./tools
13
+
14
+ # 运行时曲线覆盖持久化到 /data(compose 挂卷)
15
+ ENV BIDITECH_CURVE_OVERRIDES=/data/curve_overrides.json
16
+ RUN mkdir -p /data
17
+
18
+ EXPOSE 8077 4840
19
+
20
+ # 默认起优化 API;OPC UA 仿真服务器由 compose 覆盖 command
21
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8077"]
backend/README.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 优化算法后端(Python / FastAPI)
2
+
3
+ 按文档规格实现的节能优化内核 + 求解器 + HIL 仿真验证 + Phase 3 安全联锁 + REST API。
4
+ 数据采集由 `node-red/` 承担,本服务专注**优化算法**(Phase 2 建议)**与安全闭环控制**(Phase 3)。
5
+
6
+ ## 模块
7
+
8
+ | 文件 | 对应文档 | 内容 |
9
+ |--|--|--|
10
+ | `app/models/pump_curve.py` | 2.1 `PumpCurveModel` | 三次样条 not-a-knot 曲线 + 相似定律(Q∝f,H∝f²,P∝f³) + 低速效率修正 + BEP/高效区 + 给定扬程反解流量 |
11
+ | `app/models/parallel.py` | 2.1 `PumpGroupParallelModel` | 系统曲线 H=Hst+S·Q² + brentq 求并联工作点 + SEC |
12
+ | `app/models/forecaster.py` | 2.4 `FlowForecaster` | 物料平衡反推入流 Q_in=Q_out+A·dH/dt + 滑动窗口线性回归 + R²<0.3 退化均值 |
13
+ | `app/optimizer/mpc.py` | 2.2 `MPCOptimizer` | **枚举开泵组合(0/1) × scipy L-BFGS-B 优化连续频率**;流量偏差/频率变化/启停/高效区惩罚 + 轮换均衡 |
14
+ | `app/safety.py` | 1.6 | **Phase 3 安全联锁门控**:写使能 / 指令限幅 / 频率斜坡限速 / 高压硬联锁 / 最少台数 / CRITICAL 跳过 / watchdog 心跳超时切回 |
15
+ | `app/sim/hydraulic.py` | 4.5 HIL | 管阻+泵曲线闭环仿真台,推进集水池液位 |
16
+ | `app/plant.py` | 3.1 | 从 `config/pumps.yaml` 装配泵组/优化器/预测器/安全门控/控制状态 |
17
+ | `app/main.py` | 4.2 | FastAPI:配置 / 单泵曲线 / **优化建议** / **控制与安全联锁**(模式切换/写使能/闭环下发/反悔) |
18
+
19
+ ## 泵组配置(数量 + 每台性质 + 曲线形式)
20
+
21
+ `config/pumps.yaml` 的 `pumps` 列表决定泵数量与每台性质。当前为**海斯特污水提升泵站**:5 台,
22
+ **变频 = 1#/2#/5#(1# 飞力 Flygt,2#/5# 海斯特),工频 = 3#/4#(海斯特)**
23
+ (`variable_speed: true/false`;工频锁 50Hz 只作 0/1 决策)。海斯特铭牌 Q=850 m³/h、H=14.5m、DN300。
24
+ 改台数/性质/曲线只需编辑该 YAML,`GET /api/config` 暴露给前端同步。
25
+
26
+ 曲线两种写法(现场标定后替换占位值):
27
+
28
+ - **测点形式** `curve: {Q, H, eta}` —— ≥5 点,走三次样条 not-a-knot。
29
+ - **V1.0 参数形式** `poly: {a0, a1, a2, q_max}` + `eta_gauss: {eta_max, q_bep, sigma}`
30
+ —— H(Q)=a0+a1·Q+a2·Q²、η(Q)=η_max·exp(-((Q-q_bep)/σ)²),与软著 V1.0 参数化一致,
31
+ 有各泵 a0/a1/a2、η_max、Q_bep 标定值时直接填入(YAML 末尾有模板)。
32
+
33
+ 站参数(`static_head`/`pipe_resistance`/`level_min`/`level_max`/`level_target`/`line_voltage` 等)
34
+ 均在 `station:` 下可配置;液位允许波动区间供液位 MPC 缓冲用,`/api/config` 一并暴露。
35
+ 现值取自现场勘查 + SCADA 实测:集水井 6.5×8.8=57.2 m²,液位 3–9m(LL=3.0 停泵 / HH=9.0),
36
+ 线电压 Uab≈394V。安全联锁含**低水位保护停泵**(液位<LL 停泵防干抽)与高水位增泵提示。
37
+ **无出口压力表** → 扬程由「液位 + 系统曲线」估计:`PumpGroupParallelModel(level_ref=...)`,
38
+ `solve(active, level=)` 按实时液位算静扬程 static(level)=static_head+(level_ref−level)。
39
+
40
+ ## 用历史数据辨识曲线(app/models/curve_fit.py,文档 2.1 在线辨识)
41
+
42
+ 没有 V1.0 标定表也能反推曲线:给一批历史运行点 `(Q, H, P 或 η, freq)`,
43
+ 先用相似定律归一到额定频率(Q0=Q/r, H0=H/r², r=f/50),再二次最小二乘拟合
44
+ H(Q)=a0+a1·Q+a2·Q²、高斯拟合 η(Q),产出 `poly`+`eta_gauss` 参数与拟合 R²。
45
+
46
+ - **在线**:`POST /api/pump/{id}/identify` `{records:[{Q,H,P,freq}], variable_speed, rated_kw}`
47
+ → 返回 a0/a1/a2、η_max/q_bep/σ、R²,以及可直接粘进 `pumps.yaml` 的片段。
48
+ - **离线**:`python tools/fit_curve.py history.csv`(CSV 列:`pump,Q,H,P,freq[,eta]`)
49
+ → 打印各泵 `pumps.yaml` 片段 + R²。
50
+
51
+ ## 软件形态上传曲线(不改 YAML,运行时热更新)
52
+
53
+ 前端「泵曲线管理」页:选泵 → **上传曲线图**(在图上标定坐标轴后点取 H-Q / η-Q 点)
54
+ 或**手动/粘贴数据点** → 拟合预览 → 应用。对应后端:
55
+
56
+ - `POST /api/pump/{id}/curve/fit` `{hq:[[Q,H]], eta:[[Q,η]]}` → 拟合 poly+高斯 + R² + 采样预览
57
+ - `POST /api/pump/{id}/curve/apply` `{poly, eta_gauss, name?, variable_speed?, rated_kw?}`
58
+ → 运行时替换该泵模型(优化器即刻采用),并持久化到 `config/curve_overrides.json`
59
+ (app 管理、启动自动加载、已 gitignore;不需要人工编辑)。
60
+
61
+ ## OPC UA 测试接口
62
+
63
+ 现场数据已汇聚到一台标准 PC 的 OPC UA 服务器,我方软件作 UA 客户端读取。
64
+ 本仓提供可运行的仿真服务器与客户端便于联调:
65
+
66
+ ```bash
67
+ python -m app.opcua_sim_server # 起 OPC UA 仿真服务器 opc.tcp://0.0.0.0:4840/biditech/server/
68
+ python tools/opcua_test_client.py # 客户端连它,读点位 + 写频率设定验证
69
+ ```
70
+
71
+ 服务器暴露点位(命名对齐文档 4.1):`PumpStation1.Level/TotalFlow/TotalPower/Pressure`、
72
+ `PumpStation1.Pump<i>.{Freq,Current,Power,Status,RunHours}`(只读)、
73
+ `Pump<i>.{FreqSet,Cmd}`、`WriteEnable`、`Heartbeat`(可写,供回写/联锁测试);
74
+ 值由真实曲线模型实时驱动。UaExpert / Node-RED 可直接连它浏览。
75
+
76
+ 效率可由实测 (Q,H,P) 反算 η=ρgQH/P_input(`eta_from_power`);SCADA 电表只记电流+PF 时,
77
+ 用 `power_from_current(U_line, I, PF)` = √3·U·I·PF 反算 P(现场电表有 Ua/Ub/Uc、Ia/Ib/Ic、PF、累计电度;SCADA 只记电流)。
78
+ 实测验证:混频带噪历史点可把 a0/a1/a2、η_max/Q_bep/σ 还原到 ~1%(R²>0.997)。
79
+
80
+ ## 控制与安全联锁 API(Phase 3)
81
+
82
+ - `GET /api/config` — 泵组配置 + 约束 + 频率范围
83
+ - `GET /api/control/state` — 模式 / 写使能 / watchdog / 最近指令
84
+ - `POST /api/control/mode` `{mode: manual|auto}` — 手动开环 ↔ 自动闭环
85
+ - `POST /api/control/enable` `{enable: bool}` — 写使能 bWriteEnable
86
+ - `POST /api/control/alarm` `{critical: bool}` — CRITICAL 报警置位
87
+ - `POST /api/control/revert` — 一键反悔 / 无扰切回本地 PID
88
+ - `POST /api/optimization/apply` `{suggestion, realtime}` — 闭环下发:过安全门控返回安全指令 + 拦截项(调用即喂狗)
89
+
90
+ 求解器:枚举组合(≤2³=8,文档实测 0.5~2s)+ scipy L-BFGS-B 连续频率优化。
91
+ 工频软启泵设 `variable_speed: false`,锁 50Hz 只作 0/1 决策。
92
+
93
+ ## 运行
94
+
95
+ ```bash
96
+ cd backend
97
+ pip install -r requirements.txt
98
+ python -m pytest -q # 26 项单测
99
+ python -m uvicorn app.main:app --port 8077 # 启动服务
100
+ ```
101
+
102
+ ## API
103
+
104
+ ```bash
105
+ curl http://127.0.0.1:8077/api/health
106
+
107
+ # 优化建议:给目标流量 + 当前状态 + 累计运行 h(轮换),返回最优组合/频率 + 节能潜力
108
+ curl -X POST http://127.0.0.1:8077/api/optimization/suggestion \
109
+ -H 'Content-Type: application/json' \
110
+ -d '{"Q_target":260,"current_active":[1,2],"current_freqs":{"1":42,"2":42},"run_hours":{"1":9000,"2":9000,"3":100}}'
111
+ ```
112
+
113
+ 返回示例(关键字段):
114
+
115
+ ```json
116
+ {
117
+ "success": true, "active": [1, 3], "freqs": {"1": 41.49, "3": 41.48},
118
+ "wp": {"Q_total": 254.5, "P_total": 26.06, "spec_energy": 0.1024},
119
+ "n_starts": 1, "n_stops": 1,
120
+ "baseline": {"P_total": 61.73, "spec_energy": 0.1689},
121
+ "sec_saving_pct": 39.4
122
+ }
123
+ ```
124
+
125
+ `sec_saving_pct` = 相对「全泵 50Hz 工频运行」基线的 SEC 改善百分比(文档 KPI)。
126
+
127
+ ## 与整体链路的关系
128
+
129
+ ```
130
+ Node-RED(采集) ──▶ 本后端(优化建议 + 安全门控) ──▶ HTML 展示页
131
+ 手动开环:AI 建议 + 人工确认执行 (Phase 2)
132
+ 自动闭环:写使能 → apply 过安全门控 → 下发安全指令 + 一键反悔切回 (Phase 3)
133
+ ```
134
+
135
+ Phase 2 手动开环:算法给建议,人工确认后执行。Phase 3 自动闭环:`safety.py` 门控
136
+ (写使能 / 限幅 / 斜坡限速 / 高压硬联锁 / watchdog 切回 / CRITICAL 跳过 / 最少台数)已实现。
137
+ 现场实况回写 PLC 走 Node-RED(或 Python 侧启用 `asyncua`,见 requirements 注释);
138
+ 本仓演示台由前端把门控后的安全指令应用到仿真做闭环可视化。
139
+
140
+ ## 标定提醒
141
+
142
+ `config/pumps.yaml` 的静扬程、管阻系数、Q-H-η 测点、目标流量等**均为示例**,
143
+ 新泵站必须现场重新标定(文档 Caveats)。
backend/app/__init__.py ADDED
File without changes
backend/app/demo_runtime.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-container historical OPC UA replay runtime.
2
+
3
+ Hugging Face exposes only the HTTP application port. The OPC UA server still
4
+ runs inside the same container on localhost:4840, and this collector reads it
5
+ through the normal OPC UA protocol before publishing a dashboard snapshot.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import contextlib
11
+ import os
12
+ import time
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from asyncua import Client
18
+ from asyncua.ua.uaerrors import BadNoData
19
+
20
+ from .opcua_replay_server import run as run_replay_server
21
+
22
+
23
+ def _value(data_value) -> Any:
24
+ if not data_value.StatusCode.is_good():
25
+ return None
26
+ return data_value.Value.Value
27
+
28
+
29
+ async def _read(node) -> Any:
30
+ try:
31
+ return _value(await node.read_data_value())
32
+ except BadNoData:
33
+ return None
34
+
35
+
36
+ def build_snapshot(
37
+ station: dict[str, Any],
38
+ pumps: list[dict[str, Any]],
39
+ ) -> dict[str, Any]:
40
+ """Build the public snapshot without inventing unavailable measurements."""
41
+ total_flow = float(station.get("totalFlow") or 0.0)
42
+ total_power = float(station.get("totalPower") or 0.0)
43
+ running = [pump for pump in pumps if int(pump.get("status") or 0) == 1]
44
+
45
+ # Individual outlet flow is not measured. Allocate only for display using
46
+ # measured pump power shares and mark the provenance explicitly.
47
+ weights = [max(float(pump.get("power") or 0.0), 0.0) for pump in running]
48
+ if running and sum(weights) <= 0:
49
+ weights = [1.0] * len(running)
50
+ weight_total = sum(weights)
51
+ for pump in pumps:
52
+ pump["flow"] = 0.0
53
+ pump["flowSource"] = "not_running"
54
+ pump["head"] = None
55
+ pump["headSource"] = "missing_pressure"
56
+ for pump, weight in zip(running, weights):
57
+ pump["flow"] = total_flow * weight / weight_total if weight_total else 0.0
58
+ pump["flowSource"] = "estimated_power_share"
59
+
60
+ pressure = station.get("pressure")
61
+ historical_timestamp = station.get("replayTimestamp")
62
+ return {
63
+ "station": "胶州二期提升泵站(历史 OPC 回放)",
64
+ "source": "historical_opc_replay",
65
+ "sourceLabel": "三个月历史数据 · OPC UA 内部回放",
66
+ "historicalTimestamp": historical_timestamp,
67
+ "replayIndex": station.get("replayIndex"),
68
+ "replayCount": station.get("replayCount"),
69
+ "level": station.get("level"),
70
+ "pressure": pressure,
71
+ "pressureQuality": "measured" if pressure is not None else "missing",
72
+ "totalFlow": total_flow,
73
+ "totalPower": total_power,
74
+ "sec": total_power / total_flow if total_flow > 0 else 0.0,
75
+ "pumps": pumps,
76
+ # Use wall-clock time for the rolling chart while retaining the original
77
+ # historical timestamp above.
78
+ "ts": int(time.time() * 1000),
79
+ }
80
+
81
+
82
+ class HistoricalOpcDemoRuntime:
83
+ def __init__(self) -> None:
84
+ self.latest: dict[str, Any] | None = None
85
+ self.error: str | None = None
86
+ self.enabled = False
87
+ self._tasks: list[asyncio.Task] = []
88
+
89
+ async def start_from_env(self) -> None:
90
+ source = os.environ.get("BIDITECH_DEMO_REPLAY_CSV", "").strip()
91
+ if not source:
92
+ return
93
+ csv_path = Path(source)
94
+ if not csv_path.is_file():
95
+ self.error = f"Demo replay CSV not found: {csv_path}"
96
+ return
97
+
98
+ endpoint = os.environ.get(
99
+ "BIDITECH_DEMO_OPCUA_ENDPOINT",
100
+ "opc.tcp://127.0.0.1:4840/biditech/server/",
101
+ )
102
+ interval = float(os.environ.get("BIDITECH_DEMO_REPLAY_INTERVAL", "1.0"))
103
+ server_endpoint = endpoint.replace("127.0.0.1", "0.0.0.0")
104
+ self.enabled = True
105
+ self._tasks = [
106
+ asyncio.create_task(
107
+ run_replay_server(server_endpoint, csv_path, interval=interval),
108
+ name="historical-opc-replay-server",
109
+ ),
110
+ asyncio.create_task(
111
+ self._collector(endpoint),
112
+ name="historical-opc-replay-collector",
113
+ ),
114
+ ]
115
+
116
+ async def stop(self) -> None:
117
+ for task in self._tasks:
118
+ task.cancel()
119
+ for task in self._tasks:
120
+ with contextlib.suppress(asyncio.CancelledError):
121
+ await task
122
+ self._tasks = []
123
+
124
+ async def _collector(self, endpoint: str) -> None:
125
+ await asyncio.sleep(0.5)
126
+ while True:
127
+ try:
128
+ async with Client(url=endpoint, timeout=5) as client:
129
+ await self._collect_connected(client)
130
+ except asyncio.CancelledError:
131
+ raise
132
+ except Exception as exc: # reconnect loop is intentional
133
+ self.error = f"{type(exc).__name__}: {exc}"
134
+ await asyncio.sleep(1.0)
135
+
136
+ async def _collect_connected(self, client: Client) -> None:
137
+ station_ids = {
138
+ "level": "ns=2;s=PumpStation1.Level",
139
+ "totalFlow": "ns=2;s=PumpStation1.TotalFlow",
140
+ "totalPower": "ns=2;s=PumpStation1.TotalPower",
141
+ "pressure": "ns=2;s=PumpStation1.Pressure",
142
+ "replayTimestamp": "ns=2;s=PumpStation1.ReplayTimestamp",
143
+ "replayIndex": "ns=2;s=PumpStation1.ReplayIndex",
144
+ "replayCount": "ns=2;s=PumpStation1.ReplayCount",
145
+ }
146
+ station_nodes = {key: client.get_node(node_id) for key, node_id in station_ids.items()}
147
+ pump_nodes = {
148
+ pump_id: {
149
+ field: client.get_node(f"ns=2;s=PumpStation1.Pump{pump_id}.{node_name}")
150
+ for field, node_name in {
151
+ "status": "Status",
152
+ "freq": "Freq",
153
+ "current": "Current",
154
+ "power": "Power",
155
+ "runHours": "RunHours",
156
+ }.items()
157
+ }
158
+ for pump_id in range(1, 6)
159
+ }
160
+
161
+ while True:
162
+ station_values = {
163
+ key: await _read(node)
164
+ for key, node in station_nodes.items()
165
+ }
166
+ pumps = []
167
+ for pump_id, nodes in pump_nodes.items():
168
+ pump = {"id": pump_id}
169
+ for field, node in nodes.items():
170
+ pump[field] = await _read(node)
171
+ pumps.append(pump)
172
+ self.latest = build_snapshot(station_values, pumps)
173
+ self.error = None
174
+ await asyncio.sleep(0.8)
175
+
176
+
177
+ demo_runtime = HistoricalOpcDemoRuntime()
backend/app/integration_api.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """现场数据接入配置与 OPC UA 调试 API。"""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import os
6
+ import secrets
7
+ import time
8
+ from datetime import date, datetime
9
+ from typing import Any, Optional
10
+
11
+ import httpx
12
+ from fastapi import APIRouter, Depends, Header, HTTPException
13
+ from pydantic import BaseModel, Field
14
+
15
+ from .integration_config import (
16
+ IntegrationConfig,
17
+ IntegrationConfigStore,
18
+ IntegrationConfigUpdate,
19
+ OpcConnectionConfig,
20
+ OpcConnectionUpdate,
21
+ TagMapping,
22
+ get_config_store,
23
+ )
24
+
25
+ router = APIRouter(prefix="/api/integration", tags=["现场数据接入"])
26
+
27
+
28
+ class OpcTestRequest(BaseModel):
29
+ connection: Optional[OpcConnectionUpdate] = None
30
+
31
+
32
+ class OpcBrowseRequest(BaseModel):
33
+ node_id: str = "i=85" # Objects
34
+ connection: Optional[OpcConnectionUpdate] = None
35
+ limit: int = Field(default=200, ge=1, le=1000)
36
+
37
+
38
+ class OpcPreviewRequest(BaseModel):
39
+ keys: list[str] = []
40
+ connection: Optional[OpcConnectionUpdate] = None
41
+
42
+
43
+ def _connection_and_password(
44
+ store: IntegrationConfigStore, override: Optional[OpcConnectionUpdate]
45
+ ) -> tuple[OpcConnectionConfig, str]:
46
+ if override is None:
47
+ current = store.load().connection
48
+ return current, store.get_password()
49
+ payload = override.model_dump(exclude={"password"})
50
+ password = override.password if override.password is not None else store.get_password()
51
+ payload["password_configured"] = bool(password)
52
+ return OpcConnectionConfig(**payload), password
53
+
54
+
55
+ async def _create_client(connection: OpcConnectionConfig, password: str):
56
+ try:
57
+ from asyncua import Client
58
+ except ImportError as exc: # pragma: no cover - packaging failure
59
+ raise RuntimeError("后端未安装 asyncua,无法测试 OPC UA") from exc
60
+
61
+ client = Client(url=connection.endpoint, timeout=connection.timeout_s)
62
+ if connection.username:
63
+ client.set_user(connection.username)
64
+ client.set_password(password)
65
+ if connection.security_policy != "None":
66
+ security = ",".join(
67
+ [
68
+ connection.security_policy,
69
+ connection.security_mode,
70
+ connection.certificate_path,
71
+ connection.private_key_path,
72
+ ]
73
+ )
74
+ if connection.server_certificate_path:
75
+ security += "," + connection.server_certificate_path
76
+ await client.set_security_string(security)
77
+ return client
78
+
79
+
80
+ def _json_value(value: Any) -> Any:
81
+ if isinstance(value, (datetime, date)):
82
+ return value.isoformat()
83
+ if isinstance(value, bytes):
84
+ return value.hex()
85
+ if isinstance(value, (str, int, float, bool)) or value is None:
86
+ return value
87
+ if isinstance(value, (list, tuple)):
88
+ return [_json_value(item) for item in value]
89
+ if isinstance(value, dict):
90
+ return {str(key): _json_value(item) for key, item in value.items()}
91
+ return str(value)
92
+
93
+
94
+ @router.get("/config", response_model=IntegrationConfig)
95
+ def read_integration_config(store: IntegrationConfigStore = Depends(get_config_store)):
96
+ return store.load()
97
+
98
+
99
+ @router.put("/config", response_model=IntegrationConfig)
100
+ def update_integration_config(
101
+ payload: IntegrationConfigUpdate,
102
+ store: IntegrationConfigStore = Depends(get_config_store),
103
+ ):
104
+ try:
105
+ return store.save(payload)
106
+ except (OSError, ValueError) as exc:
107
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
108
+
109
+
110
+ @router.post("/config/reset", response_model=IntegrationConfig)
111
+ def reset_integration_config(store: IntegrationConfigStore = Depends(get_config_store)):
112
+ return store.reset()
113
+
114
+
115
+ @router.post("/opc/test")
116
+ async def test_opc_connection(
117
+ payload: OpcTestRequest,
118
+ store: IntegrationConfigStore = Depends(get_config_store),
119
+ ):
120
+ connection, password = _connection_and_password(store, payload.connection)
121
+ started = time.perf_counter()
122
+ client = await _create_client(connection, password)
123
+ try:
124
+ await asyncio.wait_for(client.connect(), timeout=connection.timeout_s + 1)
125
+ namespaces = await client.get_namespace_array()
126
+ server_name = await client.nodes.server.read_display_name()
127
+ return {
128
+ "success": True,
129
+ "endpoint": connection.endpoint,
130
+ "latency_ms": round((time.perf_counter() - started) * 1000, 1),
131
+ "server": str(server_name.Text),
132
+ "namespaces": namespaces,
133
+ "message": "OPC UA 连接成功",
134
+ }
135
+ except Exception as exc:
136
+ return {
137
+ "success": False,
138
+ "endpoint": connection.endpoint,
139
+ "latency_ms": round((time.perf_counter() - started) * 1000, 1),
140
+ "error": f"{type(exc).__name__}: {exc}",
141
+ "message": "连接失败,请检查地址、安全策略、账号和网络",
142
+ }
143
+ finally:
144
+ try:
145
+ await client.disconnect()
146
+ except Exception:
147
+ pass
148
+
149
+
150
+ @router.post("/opc/browse")
151
+ async def browse_opc_nodes(
152
+ payload: OpcBrowseRequest,
153
+ store: IntegrationConfigStore = Depends(get_config_store),
154
+ ):
155
+ connection, password = _connection_and_password(store, payload.connection)
156
+ client = await _create_client(connection, password)
157
+ try:
158
+ await asyncio.wait_for(client.connect(), timeout=connection.timeout_s + 1)
159
+ parent = client.get_node(payload.node_id)
160
+ children = await parent.get_children()
161
+ result = []
162
+ for child in children[: payload.limit]:
163
+ browse_name, display_name, node_class = await asyncio.gather(
164
+ child.read_browse_name(),
165
+ child.read_display_name(),
166
+ child.read_node_class(),
167
+ )
168
+ result.append(
169
+ {
170
+ "node_id": child.nodeid.to_string(),
171
+ "browse_name": browse_name.Name,
172
+ "display_name": display_name.Text,
173
+ "node_class": getattr(node_class, "name", str(node_class)),
174
+ }
175
+ )
176
+ return {"success": True, "parent": payload.node_id, "nodes": result}
177
+ except Exception as exc:
178
+ return {"success": False, "error": f"{type(exc).__name__}: {exc}", "nodes": []}
179
+ finally:
180
+ try:
181
+ await client.disconnect()
182
+ except Exception:
183
+ pass
184
+
185
+
186
+ @router.post("/opc/read-preview")
187
+ async def read_opc_preview(
188
+ payload: OpcPreviewRequest,
189
+ store: IntegrationConfigStore = Depends(get_config_store),
190
+ ):
191
+ config = store.load()
192
+ connection, password = _connection_and_password(store, payload.connection)
193
+ selected = set(payload.keys)
194
+ tags: list[TagMapping] = [
195
+ tag
196
+ for tag in config.tags
197
+ if tag.enabled and tag.node_id and (not selected or tag.key in selected)
198
+ ]
199
+ client = await _create_client(connection, password)
200
+ started = time.perf_counter()
201
+ try:
202
+ await asyncio.wait_for(client.connect(), timeout=connection.timeout_s + 1)
203
+ values = []
204
+ for tag in tags:
205
+ try:
206
+ data_value = await client.get_node(tag.node_id).read_data_value()
207
+ raw = data_value.Value.Value
208
+ scaled = raw
209
+ if isinstance(raw, (int, float)) and not isinstance(raw, bool):
210
+ scaled = raw * tag.scale + tag.offset
211
+ values.append(
212
+ {
213
+ "key": tag.key,
214
+ "label": tag.label,
215
+ "node_id": tag.node_id,
216
+ "value": _json_value(scaled),
217
+ "raw_value": _json_value(raw),
218
+ "unit": tag.unit,
219
+ "quality": str(data_value.StatusCode),
220
+ "source_timestamp": _json_value(data_value.SourceTimestamp),
221
+ "success": True,
222
+ }
223
+ )
224
+ except Exception as exc:
225
+ values.append(
226
+ {
227
+ "key": tag.key,
228
+ "label": tag.label,
229
+ "node_id": tag.node_id,
230
+ "success": False,
231
+ "error": f"{type(exc).__name__}: {exc}",
232
+ }
233
+ )
234
+ return {
235
+ "success": True,
236
+ "endpoint": connection.endpoint,
237
+ "elapsed_ms": round((time.perf_counter() - started) * 1000, 1),
238
+ "values": values,
239
+ }
240
+ except Exception as exc:
241
+ return {"success": False, "error": f"{type(exc).__name__}: {exc}", "values": []}
242
+ finally:
243
+ try:
244
+ await client.disconnect()
245
+ except Exception:
246
+ pass
247
+
248
+
249
+
250
+ @router.get("/runtime")
251
+ def node_red_runtime_config(
252
+ x_integration_token: str = Header(default=""),
253
+ store: IntegrationConfigStore = Depends(get_config_store),
254
+ ):
255
+ """供 Node-RED 容器读取运行配置。
256
+
257
+ 未设置内部令牌时仅允许无密码 OPC;设置密码后必须同时设置
258
+ INTEGRATION_INTERNAL_TOKEN,并由 Node-RED 通过同名环境变量携带。
259
+ """
260
+ expected = os.environ.get("INTEGRATION_INTERNAL_TOKEN", "")
261
+ password = store.get_password()
262
+ if expected:
263
+ if not secrets.compare_digest(x_integration_token, expected):
264
+ raise HTTPException(status_code=401, detail="内部配置令牌无效")
265
+ elif password:
266
+ raise HTTPException(
267
+ status_code=503,
268
+ detail="已配置 OPC 密码,但尚未设置 INTEGRATION_INTERNAL_TOKEN",
269
+ )
270
+ payload = store.load().model_dump()
271
+ payload["connection"]["password"] = password if expected else ""
272
+ return payload
273
+ @router.get("/status")
274
+ async def integration_status(store: IntegrationConfigStore = Depends(get_config_store)):
275
+ config = store.load()
276
+ node_red_url = os.environ.get("NODERED_URL", "http://nodered:1880").rstrip("/")
277
+ node_red = {"reachable": False, "url": node_red_url}
278
+ try:
279
+ async with httpx.AsyncClient(timeout=2.0) as client:
280
+ response = await client.get(node_red_url + "/api/realtime")
281
+ node_red.update(
282
+ {
283
+ "reachable": response.status_code == 200,
284
+ "status_code": response.status_code,
285
+ "has_snapshot": bool(response.json()) if response.status_code == 200 else False,
286
+ }
287
+ )
288
+ except Exception as exc:
289
+ node_red["error"] = f"{type(exc).__name__}: {exc}"
290
+ return {
291
+ "source_mode": config.source_mode,
292
+ "revision": config.revision,
293
+ "configured_tags": sum(1 for tag in config.tags if tag.enabled and tag.node_id),
294
+ "required_tags_ready": all(
295
+ bool(tag.node_id) for tag in config.tags if tag.enabled and tag.required
296
+ ),
297
+ "node_red": node_red,
298
+ }
backend/app/integration_config.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """现场数据接入配置:持久化、校验、密码隔离与默认点表。
2
+
3
+ 配置文件放在 /data 卷中,容器重启后保留。OPC 密码单独存放且不通过
4
+ GET 接口返回,避免配置页面或日志意外泄露。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ import shutil
12
+ import tempfile
13
+ from datetime import datetime, timezone
14
+ from functools import lru_cache
15
+ from pathlib import Path
16
+ from typing import Literal, Optional
17
+
18
+ from pydantic import BaseModel, Field, field_validator, model_validator
19
+
20
+
21
+ DataType = Literal["Boolean", "Int16", "Int32", "UInt16", "UInt32", "Float", "Double", "String"]
22
+ SourceMode = Literal["simulation", "opcua"]
23
+
24
+
25
+ class TagMapping(BaseModel):
26
+ key: str = Field(min_length=1, max_length=80)
27
+ label: str = Field(min_length=1, max_length=120)
28
+ node_id: str = Field(default="", max_length=300)
29
+ data_type: DataType = "Double"
30
+ unit: str = Field(default="", max_length=30)
31
+ scale: float = 1.0
32
+ offset: float = 0.0
33
+ enabled: bool = True
34
+ required: bool = False
35
+ writable: bool = False
36
+
37
+ @field_validator("key")
38
+ @classmethod
39
+ def validate_key(cls, value: str) -> str:
40
+ value = value.strip()
41
+ if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_.-]*", value):
42
+ raise ValueError("点位键只能包含字母、数字、点、横线和下划线,并以字母开头")
43
+ return value
44
+
45
+ @field_validator("node_id")
46
+ @classmethod
47
+ def normalize_node_id(cls, value: str) -> str:
48
+ return value.strip()
49
+
50
+
51
+ class OpcConnectionConfig(BaseModel):
52
+ endpoint: str = "opc.tcp://opcua-sim:4840/biditech/server/"
53
+ security_policy: Literal[
54
+ "None", "Basic256Sha256", "Aes128_Sha256_RsaOaep", "Aes256_Sha256_RsaPss"
55
+ ] = "None"
56
+ security_mode: Literal["None", "Sign", "SignAndEncrypt"] = "None"
57
+ username: str = Field(default="", max_length=120)
58
+ certificate_path: str = Field(default="", max_length=300)
59
+ private_key_path: str = Field(default="", max_length=300)
60
+ server_certificate_path: str = Field(default="", max_length=300)
61
+ sampling_interval_ms: int = Field(default=1000, ge=200, le=60000)
62
+ timeout_s: float = Field(default=5.0, ge=1.0, le=30.0)
63
+ reconnect_interval_s: float = Field(default=5.0, ge=1.0, le=300.0)
64
+ password_configured: bool = False
65
+
66
+ @field_validator("endpoint")
67
+ @classmethod
68
+ def validate_endpoint(cls, value: str) -> str:
69
+ value = value.strip()
70
+ if not value.startswith("opc.tcp://"):
71
+ raise ValueError("OPC UA 地址必须以 opc.tcp:// 开头")
72
+ return value
73
+
74
+ @model_validator(mode="after")
75
+ def validate_security(self):
76
+ if self.security_policy == "None" and self.security_mode != "None":
77
+ raise ValueError("安全策略为 None 时,安全模式也必须为 None")
78
+ if self.security_policy != "None":
79
+ if self.security_mode == "None":
80
+ raise ValueError("启用安全策略后必须选择 Sign 或 SignAndEncrypt")
81
+ if not self.certificate_path or not self.private_key_path:
82
+ raise ValueError("启用安全策略后必须填写客户端证书和私钥路径")
83
+ return self
84
+
85
+
86
+ class OpcConnectionUpdate(OpcConnectionConfig):
87
+ password: Optional[str] = Field(default=None, max_length=300, exclude=True)
88
+
89
+
90
+ class IntegrationConfig(BaseModel):
91
+ revision: int = 1
92
+ updated_at: str
93
+ source_mode: SourceMode = "simulation"
94
+ connection: OpcConnectionConfig = Field(default_factory=OpcConnectionConfig)
95
+ tags: list[TagMapping]
96
+
97
+ @model_validator(mode="after")
98
+ def validate_tags(self):
99
+ keys = [tag.key for tag in self.tags]
100
+ if len(keys) != len(set(keys)):
101
+ raise ValueError("点位键不能重复")
102
+ enabled_ids = [tag.node_id for tag in self.tags if tag.enabled and tag.node_id]
103
+ if len(enabled_ids) != len(set(enabled_ids)):
104
+ raise ValueError("已启用点位的 NodeId 不能重复")
105
+ missing = [tag.label for tag in self.tags if tag.required and tag.enabled and not tag.node_id]
106
+ if missing:
107
+ raise ValueError(f"必需点位缺少 NodeId:{', '.join(missing)}")
108
+ return self
109
+
110
+
111
+ class IntegrationConfigUpdate(BaseModel):
112
+ source_mode: SourceMode
113
+ connection: OpcConnectionUpdate
114
+ tags: list[TagMapping]
115
+
116
+
117
+ def _tag(
118
+ key: str,
119
+ label: str,
120
+ node_id: str,
121
+ data_type: DataType = "Double",
122
+ unit: str = "",
123
+ *,
124
+ required: bool = False,
125
+ writable: bool = False,
126
+ ) -> TagMapping:
127
+ return TagMapping(
128
+ key=key,
129
+ label=label,
130
+ node_id=node_id,
131
+ data_type=data_type,
132
+ unit=unit,
133
+ required=required,
134
+ writable=writable,
135
+ )
136
+
137
+
138
+ def default_tags() -> list[TagMapping]:
139
+ base = "ns=2;s=PumpStation1."
140
+ tags = [
141
+ _tag("level", "集水井液位", base + "Level", unit="m", required=True),
142
+ _tag("totalFlow", "总管瞬时流量", base + "TotalFlow", unit="m³/h", required=True),
143
+ _tag("totalPower", "泵组总有功功率", base + "TotalPower", unit="kW"),
144
+ _tag("pressure", "总管压力", base + "Pressure", unit="MPa"),
145
+ _tag("writeEnable", "控制写使能", base + "WriteEnable", "Boolean", writable=True),
146
+ _tag("heartbeat", "控制心跳", base + "Heartbeat", "UInt32", writable=True),
147
+ ]
148
+ for pid in range(1, 6):
149
+ prefix = base + f"Pump{pid}."
150
+ tags.extend(
151
+ [
152
+ _tag(f"pump{pid}.status", f"{pid}号泵运行状态", prefix + "Status", "Int32", required=True),
153
+ _tag(f"pump{pid}.freq", f"{pid}号泵运行频率", prefix + "Freq", unit="Hz"),
154
+ _tag(f"pump{pid}.current", f"{pid}号泵电流", prefix + "Current", unit="A"),
155
+ _tag(f"pump{pid}.power", f"{pid}号泵有功功率", prefix + "Power", unit="kW"),
156
+ _tag(f"pump{pid}.runHours", f"{pid}号泵累计运行时间", prefix + "RunHours", unit="h"),
157
+ _tag(
158
+ f"pump{pid}.freqSet",
159
+ f"{pid}号泵频率设定",
160
+ prefix + "FreqSet",
161
+ unit="Hz",
162
+ writable=True,
163
+ ),
164
+ _tag(f"pump{pid}.cmd", f"{pid}号泵启停指令", prefix + "Cmd", "Int32", writable=True),
165
+ ]
166
+ )
167
+ return tags
168
+
169
+
170
+ def utc_now() -> str:
171
+ return datetime.now(timezone.utc).isoformat()
172
+
173
+
174
+ def default_config() -> IntegrationConfig:
175
+ config = IntegrationConfig(updated_at=utc_now(), tags=default_tags())
176
+ default_endpoint = os.environ.get("BIDITECH_DEFAULT_OPCUA_ENDPOINT", "").strip()
177
+ if default_endpoint:
178
+ config.connection.endpoint = default_endpoint
179
+ config.source_mode = "opcua"
180
+ return config
181
+
182
+
183
+ class IntegrationConfigStore:
184
+ def __init__(self, config_path: Path, secret_path: Path):
185
+ self.config_path = Path(config_path)
186
+ self.secret_path = Path(secret_path)
187
+
188
+ def _password(self) -> str:
189
+ env_password = os.environ.get("OPCUA_PASSWORD")
190
+ if env_password is not None:
191
+ return env_password
192
+ if not self.secret_path.exists():
193
+ return ""
194
+ try:
195
+ payload = json.loads(self.secret_path.read_text(encoding="utf-8"))
196
+ return str(payload.get("password") or "")
197
+ except (OSError, ValueError, TypeError):
198
+ return ""
199
+
200
+ def get_password(self) -> str:
201
+ return self._password()
202
+
203
+ def load(self) -> IntegrationConfig:
204
+ if not self.config_path.exists():
205
+ config = default_config()
206
+ else:
207
+ config = IntegrationConfig.model_validate_json(
208
+ self.config_path.read_text(encoding="utf-8")
209
+ )
210
+ config.connection.password_configured = bool(self._password())
211
+ return config
212
+
213
+ def _atomic_json_write(self, path: Path, payload: dict) -> None:
214
+ path.parent.mkdir(parents=True, exist_ok=True)
215
+ fd, temp_name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
216
+ try:
217
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
218
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
219
+ handle.write("\n")
220
+ handle.flush()
221
+ os.fsync(handle.fileno())
222
+ os.replace(temp_name, path)
223
+ finally:
224
+ if os.path.exists(temp_name):
225
+ os.unlink(temp_name)
226
+
227
+ def save(self, update: IntegrationConfigUpdate) -> IntegrationConfig:
228
+ current = self.load()
229
+ password = update.connection.password
230
+ if password is not None:
231
+ self._atomic_json_write(self.secret_path, {"password": password})
232
+ try:
233
+ os.chmod(self.secret_path, 0o600)
234
+ except OSError:
235
+ pass
236
+
237
+ connection_payload = update.connection.model_dump(exclude={"password"})
238
+ connection_payload["password_configured"] = bool(
239
+ password if password is not None else self._password()
240
+ )
241
+ saved = IntegrationConfig(
242
+ revision=current.revision + 1,
243
+ updated_at=utc_now(),
244
+ source_mode=update.source_mode,
245
+ connection=OpcConnectionConfig(**connection_payload),
246
+ tags=update.tags,
247
+ )
248
+
249
+ if self.config_path.exists():
250
+ backup = self.config_path.with_suffix(self.config_path.suffix + ".bak")
251
+ shutil.copy2(self.config_path, backup)
252
+ self._atomic_json_write(self.config_path, saved.model_dump())
253
+ return self.load()
254
+
255
+ def reset(self) -> IntegrationConfig:
256
+ current = self.load()
257
+ reset_config = default_config()
258
+ reset_config.revision = current.revision + 1
259
+ if self.config_path.exists():
260
+ backup = self.config_path.with_suffix(self.config_path.suffix + ".bak")
261
+ shutil.copy2(self.config_path, backup)
262
+ self._atomic_json_write(self.config_path, reset_config.model_dump())
263
+ return self.load()
264
+
265
+
266
+ @lru_cache
267
+ def get_config_store() -> IntegrationConfigStore:
268
+ # Containers persist configuration in /data. Direct Windows runs use a
269
+ # project-local writable directory instead of the protected \data root.
270
+ default_data_dir = (
271
+ Path(__file__).resolve().parents[1] / "data"
272
+ if os.name == "nt"
273
+ else Path("/data")
274
+ )
275
+ config_path = Path(
276
+ os.environ.get(
277
+ "BIDITECH_INTEGRATION_CONFIG",
278
+ str(default_data_dir / "integration_config.json"),
279
+ )
280
+ )
281
+ secret_path = Path(
282
+ os.environ.get(
283
+ "BIDITECH_OPCUA_SECRET",
284
+ str(default_data_dir / "opcua_secret.json"),
285
+ )
286
+ )
287
+ return IntegrationConfigStore(config_path, secret_path)
backend/app/main.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI 入口:暴露优化建议与曲线/工作点查询(文档 4.2 API 草案的 Phase2 部分)。
2
+
3
+ 数据采集由 Node-RED(node-red-contrib-opcua)承担,本服务专注优化算法。
4
+ 现场可把 /api/realtime 的 Node-RED 快照 POST 进来驱动优化,或由 Node-RED 定时拉取 /api/optimization/suggestion。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import os
10
+ import time
11
+ from contextlib import asynccontextmanager
12
+ from pathlib import Path
13
+ from typing import Any, Optional
14
+
15
+ from fastapi import FastAPI, WebSocket
16
+ from fastapi.middleware.cors import CORSMiddleware
17
+ from fastapi.staticfiles import StaticFiles
18
+ from pydantic import BaseModel
19
+
20
+ from .integration_api import router as integration_router
21
+ from .demo_runtime import demo_runtime
22
+ from .plant import Plant
23
+
24
+
25
+ @asynccontextmanager
26
+ async def lifespan(_: FastAPI):
27
+ await demo_runtime.start_from_env()
28
+ try:
29
+ yield
30
+ finally:
31
+ await demo_runtime.stop()
32
+
33
+
34
+ app = FastAPI(title="泵站 AI 节能优化服务", version="0.2.0", lifespan=lifespan)
35
+ app.add_middleware(
36
+ CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],
37
+ )
38
+ app.include_router(integration_router)
39
+
40
+ plant = Plant()
41
+
42
+
43
+ class OptimizeRequest(BaseModel):
44
+ Q_target: Optional[float] = None # 目标流量 m³/h;缺省用预测/均值
45
+ current_freqs: dict[int, float] = {} # {pump_id: freq}
46
+ current_active: list[int] = [] # 当前在运泵
47
+ run_hours: dict[int, float] = {} # 累计运行 h(轮换均衡)
48
+ current_total_power: Optional[float] = None # 当前实测总有功功率 kW
49
+ level: Optional[float] = None # 当前集水井液位 m
50
+
51
+
52
+ class ModeRequest(BaseModel):
53
+ mode: str # manual | auto
54
+
55
+
56
+ class EnableRequest(BaseModel):
57
+ enable: bool
58
+
59
+
60
+ class AlarmRequest(BaseModel):
61
+ critical: bool
62
+
63
+
64
+ class ApplyRequest(BaseModel):
65
+ suggestion: dict[str, Any] # {active, freqs}
66
+ realtime: dict[str, Any] # {pressure, pumps:[{id,freq,status}], ...}
67
+
68
+
69
+ @app.get("/api/health")
70
+ def health():
71
+ return {
72
+ "status": "ok",
73
+ "pumps": list(plant.pumps.keys()),
74
+ "historical_opc_demo": {
75
+ "enabled": demo_runtime.enabled,
76
+ "ready": demo_runtime.latest is not None,
77
+ "error": demo_runtime.error,
78
+ },
79
+ }
80
+
81
+
82
+ @app.get("/api/realtime")
83
+ def realtime_snapshot():
84
+ if demo_runtime.latest is None:
85
+ return {
86
+ "success": False,
87
+ "source": "historical_opc_replay",
88
+ "error": demo_runtime.error or "Historical OPC replay is starting",
89
+ }
90
+ return demo_runtime.latest
91
+
92
+
93
+ @app.get("/api/config")
94
+ def config():
95
+ """泵组配置(数量 + 每台性质)+ 约束 + 频率范围,供前端动态构建。"""
96
+ return {
97
+ "station": plant.station.get("name"),
98
+ "freq_min": plant.station["freq_min"],
99
+ "freq_max": plant.station["freq_max"],
100
+ "constraints": plant.constraints,
101
+ "level_range": plant.level_range,
102
+ "pumps": [plant.pump_meta[pid] for pid in plant.pumps],
103
+ }
104
+
105
+
106
+ @app.get("/api/pump/{pid}/curve")
107
+ def pump_curve(pid: int, freq: float = 50.0, n: int = 40):
108
+ """单泵曲线(给定频率):H-Q / η-Q / P-Q 采样点。"""
109
+ if pid not in plant.pumps:
110
+ return {"success": False, "error": "no such pump"}
111
+ pm = plant.pumps[pid]
112
+ qmin, qmax = pm.q_min(freq), pm.q_max(freq)
113
+ hq, eq, pq = [], [], []
114
+ for i in range(n + 1):
115
+ q = qmin + (qmax - qmin) * i / n
116
+ hq.append([round(q, 2), round(pm.head(q, freq), 3)])
117
+ eq.append([round(q, 2), round(pm.eta(q, freq) * 100, 2)])
118
+ p = pm.input_power(q, freq)
119
+ if p == p:
120
+ pq.append([round(q, 2), round(p, 3)])
121
+ return {"success": True, "pump_id": pid, "freq": freq,
122
+ "bep_flow": round(pm.bep_flow(freq), 2),
123
+ "meta": plant.pump_meta[pid],
124
+ "HQ": hq, "etaQ": eq, "PQ": pq}
125
+
126
+
127
+ class IdentifyRequest(BaseModel):
128
+ # 历史运行点:每条含 Q(m³/h), H(m), 以及 P(kW) 或 eta(0~1), freq(Hz)
129
+ records: list[dict[str, Any]]
130
+ variable_speed: bool = True
131
+ rated_kw: Optional[float] = None
132
+ name: Optional[str] = None
133
+
134
+
135
+ class CurveFitRequest(BaseModel):
136
+ # 数字化的曲线点(额定频率):H-Q 必填,η-Q 可选
137
+ hq: list[list[float]] # [[Q,H],...]
138
+ eta: Optional[list[list[float]]] = None # [[Q,eta],...],eta 百分数或小数
139
+
140
+
141
+ class CurveApplyRequest(BaseModel):
142
+ poly: dict[str, float] # {a0,a1,a2,q_max}
143
+ eta_gauss: dict[str, float] # {eta_max,q_bep,sigma}
144
+ name: Optional[str] = None
145
+ variable_speed: Optional[bool] = None
146
+ rated_kw: Optional[float] = None
147
+
148
+
149
+ @app.post("/api/pump/{pid}/curve/fit")
150
+ def curve_fit_endpoint(pid: int, req: CurveFitRequest):
151
+ """把在曲线图上点取(或粘贴)的 H-Q / η-Q 数据点拟合成 poly+高斯参数,并回采样预览。"""
152
+ from .models.curve_fit import fit_from_points
153
+ from .models.pump_curve import PumpCurveModel
154
+ try:
155
+ fit = fit_from_points(req.hq, req.eta)
156
+ except (ValueError, RuntimeError) as e:
157
+ return {"success": False, "error": str(e)}
158
+ # 用拟合参数建临时模型出预览曲线
159
+ preview = None
160
+ if fit.get("eta_gauss"):
161
+ p = fit["poly"]; g = fit["eta_gauss"]
162
+ m = PumpCurveModel.from_poly(pid, p["a0"], p["a1"], p["a2"], p["q_max"],
163
+ g["eta_max"], g["q_bep"], g["sigma"],
164
+ freq_nominal=plant.station["freq_nominal"])
165
+ qmax = m.q_max(50.0)
166
+ preview = {"HQ": [[round(qmax * i / 40, 1), round(m.head(qmax * i / 40, 50), 3)] for i in range(41)],
167
+ "etaQ": [[round(qmax * i / 40, 1), round(m.eta(qmax * i / 40, 50) * 100, 2)] for i in range(41)]}
168
+ return {"success": True, **fit, "preview": preview}
169
+
170
+
171
+ @app.post("/api/pump/{pid}/curve/apply")
172
+ def curve_apply(pid: int, req: CurveApplyRequest):
173
+ """把拟合好的曲线应用到该泵(运行时热更新 + 持久化,无需改 YAML)。"""
174
+ if pid not in plant.pumps:
175
+ return {"success": False, "error": "no such pump"}
176
+ spec = {"poly": req.poly, "eta_gauss": req.eta_gauss}
177
+ if req.name is not None:
178
+ spec["name"] = req.name
179
+ if req.variable_speed is not None:
180
+ spec["variable_speed"] = req.variable_speed
181
+ if req.rated_kw is not None:
182
+ spec["rated_kw"] = req.rated_kw
183
+ try:
184
+ meta = plant.apply_curve(pid, spec)
185
+ except (KeyError, ValueError, TypeError) as e:
186
+ return {"success": False, "error": str(e)}
187
+ return {"success": True, "meta": meta, "curve": plant.sampled_curve(pid)}
188
+
189
+
190
+ @app.post("/api/pump/{pid}/identify")
191
+ def identify(pid: int, req: IdentifyRequest):
192
+ """从历史运行数据辨识该泵曲线,返回 a0/a1/a2 + 高斯效率参数、拟合 R²,
193
+ 以及可直接粘进 pumps.yaml 的片段。用历史数据反推真实曲线。"""
194
+ from .models.curve_fit import identify_pump, to_yaml_block
195
+ try:
196
+ ident = identify_pump(
197
+ req.records, freq_nominal=plant.station["freq_nominal"],
198
+ pump_id=pid, name=req.name, variable_speed=req.variable_speed,
199
+ rated_kw=req.rated_kw,
200
+ )
201
+ except (ValueError, RuntimeError) as e:
202
+ return {"success": False, "error": str(e)}
203
+ ident["yaml"] = to_yaml_block(ident)
204
+ ident["success"] = True
205
+ return ident
206
+
207
+
208
+ @app.post("/api/optimization/suggestion")
209
+ def suggestion(req: OptimizeRequest):
210
+ """核心:给出最优开泵组合与频率建议,并对比全 50Hz 基线的节能潜力。"""
211
+ Q_target = req.Q_target
212
+ if Q_target is None:
213
+ Q_target = plant.forecaster.predict() or plant.forecaster.current_avg() or 300.0
214
+
215
+ result = plant.optimizer.optimize(
216
+ Q_target=Q_target,
217
+ current_freqs={int(k): float(v) for k, v in req.current_freqs.items()},
218
+ current_active=[int(x) for x in req.current_active],
219
+ run_hours={int(k): float(v) for k, v in req.run_hours.items()},
220
+ level=req.level,
221
+ )
222
+ if not result.get("success"):
223
+ return result
224
+
225
+ # 基线优先使用总管流量 + 实测总有功功率。即使2号泵反馈频率未知,
226
+ # 也能形成真实SEC基线;未知频率绝不再按0 Hz处理。
227
+ cur_active = [int(x) for x in req.current_active]
228
+ cur_freqs = {int(k): float(v) for k, v in req.current_freqs.items()}
229
+ if req.current_total_power is not None and req.current_total_power > 0 and Q_target > 0:
230
+ base_data = {
231
+ "P_total": float(req.current_total_power),
232
+ "spec_energy": float(req.current_total_power) / float(Q_target),
233
+ "Q_total": float(Q_target),
234
+ "kind": "current_measured",
235
+ }
236
+ elif cur_active and all(cur_freqs.get(p, 0) > 1e-6 for p in cur_active):
237
+ base = plant.group.solve(
238
+ {p: cur_freqs[p] for p in cur_active}, level=req.level
239
+ )
240
+ if base.feasible:
241
+ base_data = {
242
+ "P_total": base.P_total, "spec_energy": base.spec_energy,
243
+ "Q_total": base.Q_total, "kind": "current_modelled",
244
+ }
245
+ else:
246
+ base = plant.baseline_meet_target(Q_target, level=req.level)
247
+ base_data = {
248
+ "P_total": base.P_total, "spec_energy": base.spec_energy,
249
+ "Q_total": base.Q_total, "kind": "meet_target_50hz",
250
+ }
251
+ else:
252
+ base = plant.baseline_meet_target(Q_target, level=req.level)
253
+ base_data = {
254
+ "P_total": base.P_total, "spec_energy": base.spec_energy,
255
+ "Q_total": base.Q_total, "kind": "meet_target_50hz",
256
+ }
257
+
258
+ saving = None
259
+ if base_data["spec_energy"] > 1e-6:
260
+ saving = round(
261
+ (base_data["spec_energy"] - result["spec_energy"])
262
+ / base_data["spec_energy"] * 100, 1
263
+ )
264
+ result["Q_target"] = round(Q_target, 2)
265
+ result["baseline"] = {
266
+ "P_total": round(base_data["P_total"], 2),
267
+ "spec_energy": round(base_data["spec_energy"], 4),
268
+ "Q_total": round(base_data["Q_total"], 2),
269
+ "kind": base_data["kind"],
270
+ }
271
+ result["sec_saving_pct"] = saving
272
+ if saving is None:
273
+ result.update({
274
+ "status": "baseline_unavailable", "executable": False,
275
+ "message": "缺少可比较的实测功率基线,仅展示计算结果,不下发。",
276
+ })
277
+ elif saving <= 0:
278
+ result.update({
279
+ "status": "no_improvement", "executable": False,
280
+ "message": "未找到优于当前工况的方案,建议保持现状。",
281
+ })
282
+ else:
283
+ result.update({"status": "optimized", "executable": True})
284
+ return result
285
+
286
+
287
+ # ---------------- Phase 3 控制 / 安全联锁 ----------------
288
+
289
+ def _control_snapshot():
290
+ st = plant.control
291
+ return {
292
+ "mode": st.mode,
293
+ "write_enable": st.write_enable,
294
+ "critical_alarm": st.critical_alarm,
295
+ "reverted": st.reverted,
296
+ "heartbeat_count": st.heartbeat_count,
297
+ "watchdog_age_s": round(st.watchdog_age(), 2),
298
+ "watchdog_ok": st.watchdog_age() <= plant.safety_gate.watchdog_timeout_s,
299
+ "watchdog_timeout_s": plant.safety_gate.watchdog_timeout_s,
300
+ "last_command": st.last_command,
301
+ }
302
+
303
+
304
+ @app.get("/api/control/state")
305
+ def control_state():
306
+ return _control_snapshot()
307
+
308
+
309
+ @app.post("/api/control/mode")
310
+ def set_mode(req: ModeRequest):
311
+ if req.mode not in ("manual", "auto"):
312
+ return {"success": False, "error": "mode must be manual|auto"}
313
+ plant.control.mode = req.mode
314
+ if req.mode == "auto": # 进入闭环即视为一次心跳、清除切回标志
315
+ plant.control.reverted = False
316
+ plant.control.beat()
317
+ return {"success": True, **_control_snapshot()}
318
+
319
+
320
+ @app.post("/api/control/enable")
321
+ def set_enable(req: EnableRequest):
322
+ plant.control.write_enable = bool(req.enable)
323
+ return {"success": True, **_control_snapshot()}
324
+
325
+
326
+ @app.post("/api/control/alarm")
327
+ def set_alarm(req: AlarmRequest):
328
+ plant.control.critical_alarm = bool(req.critical)
329
+ return {"success": True, **_control_snapshot()}
330
+
331
+
332
+ @app.post("/api/control/heartbeat")
333
+ def heartbeat():
334
+ plant.control.beat()
335
+ return {"success": True, **_control_snapshot()}
336
+
337
+
338
+ @app.post("/api/control/revert")
339
+ def revert():
340
+ """一键反悔 / 无扰切回:停自动、关写使能、切回本地 PID(维持最后有效设定)。"""
341
+ plant.control.mode = "manual"
342
+ plant.control.write_enable = False
343
+ plant.control.reverted = True
344
+ return {"success": True, "message": "已切回手动/本地 PID(无扰,维持最后有效设定)",
345
+ **_control_snapshot()}
346
+
347
+
348
+ @app.post("/api/optimization/apply")
349
+ def apply(req: ApplyRequest):
350
+ """闭环下发:把建议过安全门控(写使能/限幅/斜坡/高压/watchdog/最少台数),
351
+ 返回可下发的安全指令与拦截项。调用本身兼作一次心跳。"""
352
+ plant.control.beat() # 前端每周期调用即喂狗
353
+ gated = plant.safety_gate.gate(
354
+ suggestion=req.suggestion, realtime=req.realtime,
355
+ state=plant.control, now=time.time(),
356
+ )
357
+ return {"success": True, "mode": plant.control.mode, **gated}
358
+
359
+
360
+ @app.websocket("/ws/realtime")
361
+ async def realtime_ws(websocket: WebSocket):
362
+ """Stream the internal historical OPC replay in single-container demos."""
363
+ await websocket.accept()
364
+ if not demo_runtime.enabled:
365
+ await websocket.close(code=1013, reason="Realtime source unavailable")
366
+ return
367
+ try:
368
+ while True:
369
+ if demo_runtime.latest is not None:
370
+ await websocket.send_json(demo_runtime.latest)
371
+ await asyncio.sleep(1.0)
372
+ except Exception:
373
+ return
374
+
375
+
376
+ # ---------------- 静态前端托管(单进程/单容器:后端直接提供大屏)----------------
377
+ # 存在 frontend 目录则挂到根路径,实现「一个进程 = 大屏 + API」,方便任意平台一步部署。
378
+ # 挂载放在所有 /api 路由之后,作为兜底(catch-all),不影响 API。
379
+ _FRONT = os.environ.get(
380
+ "FRONTEND_DIR", str(Path(__file__).resolve().parents[2] / "frontend"))
381
+ if Path(_FRONT).is_dir():
382
+ app.mount("/", StaticFiles(directory=_FRONT, html=True), name="frontend")
backend/app/models/__init__.py ADDED
File without changes
backend/app/models/curve_fit.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """从历史运行数据辨识泵曲线(对应文档 2.1「曲线在线辨识」)。
2
+
3
+ 给一批历史运行点 (Q, H, P, freq),拟合出 V1.0 参数形式:
4
+ 扬程 H(Q) = a0 + a1·Q + a2·Q² —— 最小二乘二次拟合
5
+ 效率 η(Q) = η_max·exp(-((Q-Q_bep)/σ)²) —— 高斯拟合
6
+ 产出可直接写入 pumps.yaml 的 poly + eta_gauss 字段。
7
+
8
+ 关键:历史点在不同频率运行,先用相似定律归一到额定频率再拟合——
9
+ Q0 = Q/r,H0 = H/r²,r=f/f_nom;效率去低速修正 η0 = η/(0.92+0.08r)。
10
+ 效率可由 (Q,H,P) 反算:η = ρgQH / P_input。
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import numpy as np
15
+ from scipy.optimize import curve_fit
16
+
17
+ RHO_G = 1000.0 * 9.81
18
+
19
+
20
+ def power_from_current(U_line, I, pf):
21
+ """由线电压(V)、电流(A)、功率因数反算三相有功功率 P=√3·U·I·PF (kW)。
22
+ SCADA 电表常只记 Ua/Ub/Uc、Ia/Ib/Ic、PF,无直接 P 时用它。"""
23
+ U = np.asarray(U_line, float); I = np.asarray(I, float); pf = np.asarray(pf, float)
24
+ return np.sqrt(3.0) * U * I * pf / 1000.0
25
+
26
+
27
+ def eta_from_power(Q_m3h, H_m, P_kw):
28
+ """由实测 (流量 m³/h, 扬程 m, 输入功率 kW) 反算综合效率 η=ρgQH/P_input。"""
29
+ Q = np.asarray(Q_m3h, float) / 3600.0 # m³/s
30
+ P = np.asarray(P_kw, float) * 1000.0 # W
31
+ with np.errstate(divide="ignore", invalid="ignore"):
32
+ eta = RHO_G * Q * np.asarray(H_m, float) / P
33
+ return eta
34
+
35
+
36
+ def _r2(y, y_hat):
37
+ y = np.asarray(y, float)
38
+ ss_tot = float(np.sum((y - y.mean()) ** 2))
39
+ ss_res = float(np.sum((y - y_hat) ** 2))
40
+ return 1.0 - ss_res / ss_tot if ss_tot > 1e-12 else 0.0
41
+
42
+
43
+ def fit_head_poly(Q, H):
44
+ """H(Q)=a0+a1·Q+a2·Q² 二次最小二乘。返回 {a0,a1,a2,q_max,r2,n}。"""
45
+ Q = np.asarray(Q, float)
46
+ H = np.asarray(H, float)
47
+ if Q.size < 3:
48
+ raise ValueError("扬程拟合至少需要 3 个点")
49
+ a2, a1, a0 = np.polyfit(Q, H, 2)
50
+ H_hat = a0 + a1 * Q + a2 * Q * Q
51
+ return {"a0": float(a0), "a1": float(a1), "a2": float(a2),
52
+ "q_max": float(Q.max()), "r2": round(_r2(H, H_hat), 4), "n": int(Q.size)}
53
+
54
+
55
+ def _gauss(Q, eta_max, q_bep, sigma):
56
+ return eta_max * np.exp(-((Q - q_bep) / sigma) ** 2)
57
+
58
+
59
+ def fit_eta_gaussian(Q, eta):
60
+ """η(Q)=η_max·exp(-((Q-Q_bep)/σ)²) 高斯拟合。返回 {eta_max,q_bep,sigma,r2,n}。"""
61
+ Q = np.asarray(Q, float)
62
+ eta = np.asarray(eta, float)
63
+ m = np.isfinite(eta) & (eta > 0.02) & (eta < 1.2) & np.isfinite(Q) & (Q > 0)
64
+ Q, eta = Q[m], eta[m]
65
+ if Q.size < 4:
66
+ raise ValueError("效率拟合至少需要 4 个有效点")
67
+ span = max(Q.max() - Q.min(), 1.0)
68
+ p0 = [min(float(eta.max()), 0.9), float(Q[np.argmax(eta)]), span / 2.0]
69
+ bounds = ([0.1, Q.min(), 1.0], [1.0, Q.max() * 1.5, span * 3.0 + 1.0])
70
+ popt, _ = curve_fit(_gauss, Q, eta, p0=p0, bounds=bounds, maxfev=20000)
71
+ eta_max, q_bep, sigma = popt
72
+ eta_hat = _gauss(Q, *popt)
73
+ return {"eta_max": round(float(eta_max), 4), "q_bep": round(float(q_bep), 2),
74
+ "sigma": round(float(sigma), 2), "r2": round(_r2(eta, eta_hat), 4),
75
+ "n": int(Q.size)}
76
+
77
+
78
+ def normalize_to_nominal(records, freq_nominal=50.0):
79
+ """把不同频率的历史点用相似定律归一到额定频率,返回 (Q0, H0, eta0)。
80
+
81
+ records: 可迭代 dict,每条含 Q(m³/h), H(m), 以及 P(kW) 或 eta(0~1), freq(Hz)。
82
+ """
83
+ Q0, H0, E0 = [], [], []
84
+ for rec in records:
85
+ f = float(rec.get("freq", freq_nominal))
86
+ r = f / freq_nominal
87
+ if r <= 1e-3:
88
+ continue
89
+ Q = float(rec["Q"]); H = float(rec["H"])
90
+ if Q <= 0 or H <= 0:
91
+ continue
92
+ # 效率:优先用给定 eta,否则由功率反算
93
+ if rec.get("eta") is not None:
94
+ eta = float(rec["eta"])
95
+ elif rec.get("P") not in (None, 0):
96
+ eta = float(eta_from_power(Q, H, rec["P"]))
97
+ else:
98
+ eta = np.nan
99
+ Q0.append(Q / r) # Q ∝ f
100
+ H0.append(H / (r * r)) # H ∝ f²
101
+ E0.append(eta / (0.92 + 0.08 * r) if np.isfinite(eta) else np.nan) # 去低速修正
102
+ return np.array(Q0), np.array(H0), np.array(E0)
103
+
104
+
105
+ def identify_pump(records, freq_nominal=50.0, pump_id=None, name=None,
106
+ variable_speed=True, rated_kw=None):
107
+ """从历史运行点辨识单泵曲线,产出可写入 pumps.yaml 的字典 + 拟合质量。"""
108
+ Q0, H0, E0 = normalize_to_nominal(records, freq_nominal)
109
+ if Q0.size < 4:
110
+ raise ValueError(f"有效历史点不足({Q0.size}),无法辨识")
111
+ poly = fit_head_poly(Q0, H0)
112
+ result = {
113
+ "id": pump_id, "name": name, "variable_speed": variable_speed,
114
+ "rated_kw": rated_kw,
115
+ "poly": {k: poly[k] for k in ("a0", "a1", "a2", "q_max")},
116
+ "head_fit": {"r2": poly["r2"], "n": poly["n"]},
117
+ }
118
+ try:
119
+ g = fit_eta_gaussian(Q0, E0)
120
+ result["eta_gauss"] = {k: g[k] for k in ("eta_max", "q_bep", "sigma")}
121
+ result["eta_fit"] = {"r2": g["r2"], "n": g["n"]}
122
+ except (ValueError, RuntimeError) as e:
123
+ result["eta_gauss"] = None
124
+ result["eta_fit"] = {"error": str(e)}
125
+ return result
126
+
127
+
128
+ def fit_from_points(hq_points, eta_points=None):
129
+ """从数字化的曲线点直接拟合(铭牌/图上点取,均在额定频率)。
130
+ hq_points: [[Q,H],...];eta_points: [[Q,eta],...](eta 可为百分数或小数)。"""
131
+ hq = np.asarray(hq_points, float)
132
+ if hq.ndim != 2 or hq.shape[0] < 3:
133
+ raise ValueError("H-Q 至少需要 3 个点")
134
+ poly = fit_head_poly(hq[:, 0], hq[:, 1])
135
+ out = {"ok": True, "poly": {k: poly[k] for k in ("a0", "a1", "a2", "q_max")},
136
+ "head_r2": poly["r2"], "eta_gauss": None}
137
+ if eta_points is not None and len(eta_points) >= 4:
138
+ e = np.asarray(eta_points, float)
139
+ ev = e[:, 1]
140
+ if np.nanmax(ev) > 1.5: # 百分数 → 小数
141
+ ev = ev / 100.0
142
+ g = fit_eta_gaussian(e[:, 0], ev)
143
+ out["eta_gauss"] = {k: g[k] for k in ("eta_max", "q_bep", "sigma")}
144
+ out["eta_r2"] = g["r2"]
145
+ return out
146
+
147
+
148
+ def to_yaml_block(ident: dict) -> str:
149
+ """把辨识结果格式化成 pumps.yaml 片段,便于直接粘贴。"""
150
+ p = ident["poly"]
151
+ lines = [
152
+ f" - id: {ident.get('id', '?')}",
153
+ f" name: {ident.get('name') or (str(ident.get('id')) + ' 号泵')}",
154
+ f" variable_speed: {str(ident.get('variable_speed', True)).lower()}",
155
+ ]
156
+ if ident.get("rated_kw"):
157
+ lines.append(f" rated_kw: {ident['rated_kw']}")
158
+ lines += [
159
+ f" poly: {{a0: {p['a0']:.4g}, a1: {p['a1']:.4g}, a2: {p['a2']:.4g}, q_max: {p['q_max']:.1f}}}",
160
+ ]
161
+ g = ident.get("eta_gauss")
162
+ if g:
163
+ lines.append(f" eta_gauss: {{eta_max: {g['eta_max']}, q_bep: {g['q_bep']}, sigma: {g['sigma']}}}")
164
+ return "\n".join(lines)
backend/app/models/forecaster.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """来水量预测(复用文档 2.4 FlowForecaster 规格)。
2
+
3
+ - 物料平衡反推入流:Q_in = Q_out + A·dH/dt(A 集水池截面积)。
4
+ - 对 Q_in 做滑动窗口线性回归短期预测(文档现场教训:优于 ARIMA/LSTM)。
5
+ - R² < 0.3 时退化为窗口均值。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from collections import deque
10
+
11
+ import numpy as np
12
+
13
+
14
+ class FlowForecaster:
15
+ def __init__(self, wet_well_area: float = 20.0, window: int = 300,
16
+ r2_floor: float = 0.3):
17
+ self.A = wet_well_area
18
+ self.window = window # 样本数(1s 采样 → 300≈5min)
19
+ self.r2_floor = r2_floor
20
+ self._t = deque(maxlen=window)
21
+ self._qin = deque(maxlen=window)
22
+ self._last = None # (t, level) 用于差分 dH/dt
23
+
24
+ def update(self, t: float, level: float, q_out: float) -> float:
25
+ """输入时间戳(s)、液位(m)、泵总出流(m³/h),返回反推入流 Q_in(m³/h)。"""
26
+ q_in = q_out
27
+ if self._last is not None:
28
+ dt = t - self._last[0]
29
+ if dt > 1e-6:
30
+ dhdt = (level - self._last[1]) / dt # m/s
31
+ # A·dH/dt: m² · m/s = m³/s → ×3600 → m³/h
32
+ q_in = q_out + self.A * dhdt * 3600.0
33
+ self._last = (t, level)
34
+ self._t.append(t)
35
+ self._qin.append(max(0.0, q_in))
36
+ return q_in
37
+
38
+ def current_avg(self) -> float:
39
+ return float(np.mean(self._qin)) if self._qin else 0.0
40
+
41
+ def predict(self, horizon_s: float = 60.0) -> float | None:
42
+ """线性回归外推 horizon_s 秒后的入流;样本不足或拟合差返回均值/None。"""
43
+ if len(self._qin) < 5:
44
+ return self.current_avg() if self._qin else None
45
+ t = np.asarray(self._t) - self._t[0]
46
+ y = np.asarray(self._qin)
47
+ A = np.vstack([t, np.ones_like(t)]).T
48
+ (slope, intercept), *_ = np.linalg.lstsq(A, y, rcond=None)
49
+ y_hat = A @ np.array([slope, intercept])
50
+ ss_res = float(np.sum((y - y_hat) ** 2))
51
+ ss_tot = float(np.sum((y - y.mean()) ** 2))
52
+ r2 = 1.0 - ss_res / ss_tot if ss_tot > 1e-9 else 0.0
53
+ if r2 < self.r2_floor: # 拟合差 → 退化均值
54
+ return self.current_avg()
55
+ pred = slope * (t[-1] + horizon_s) + intercept
56
+ return float(max(0.0, pred))
backend/app/models/parallel.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """并联泵组模型(复用文档 2.1 PumpGroupParallelModel 规格)。
2
+
3
+ - 系统管阻特性:H = H_static + S·Q_total²。
4
+ - 并联工作点:在扬程 H 处各泵流量相加 = 系统流量,brentq 求解耦合工作点。
5
+ - SEC(单位供水能耗,kWh/m³)= 总输入功率 / 总流量。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+
11
+ from scipy.optimize import brentq
12
+
13
+ from .pump_curve import PumpCurveModel
14
+
15
+
16
+ @dataclass
17
+ class OperatingPoint:
18
+ Q_total: float # 总流量 m³/h
19
+ H: float # 工作扬程 m
20
+ P_total: float # 总输入功率 kW
21
+ spec_energy: float # SEC kWh/m³
22
+ per_pump: dict # {pump_id: {"Q":, "H":, "P":, "eta":, "freq":}}
23
+ feasible: bool = True
24
+ reason: str | None = None
25
+ residual: float = 0.0
26
+
27
+
28
+ @dataclass
29
+ class PumpGroupParallelModel:
30
+ pumps: dict # {id: PumpCurveModel}
31
+ static_head: float = 12.0
32
+ pipe_resistance: float = 2.6e-4 # S,Q 单位 m³/h
33
+ level_ref: float | None = None # 静扬程参考液位 (m);给了则扬程随液位变化
34
+
35
+ def static_at(self, level: float | None) -> float:
36
+ """无出口压力表时的几何静扬程估计:液位越低静扬程越大。
37
+ Hst(level) = static_head + (level_ref - level);level 或 level_ref 缺省则取 static_head。"""
38
+ if level is None or self.level_ref is None:
39
+ return self.static_head
40
+ return self.static_head + (self.level_ref - level)
41
+
42
+ def system_head(self, Q_total: float, level: float | None = None) -> float:
43
+ return self.static_at(level) + self.pipe_resistance * Q_total * Q_total
44
+
45
+ def system_flow(self, H: float, level: float | None = None) -> float:
46
+ """系统曲线反解:给定扬程对应的输送流量。"""
47
+ hst = self.static_at(level)
48
+ if H <= hst:
49
+ return 0.0
50
+ return ((H - hst) / self.pipe_resistance) ** 0.5
51
+
52
+ def group_flow_at_head(self, H: float, active: dict) -> float:
53
+ """active={id: freq}:给定扬程 H,各在运泵流量之和。"""
54
+ return sum(self.pumps[pid].flow_at_head(H, f) for pid, f in active.items())
55
+
56
+ def solve(self, active: dict, level: float | None = None) -> OperatingPoint:
57
+ """求并联工作点。active={pump_id: freq_hz}。level 给定则按液位估计静扬程
58
+ (无出口压力表时的扬程估计)。无在运泵返回零点。"""
59
+ hst = self.static_at(level)
60
+ if not active:
61
+ return OperatingPoint(0.0, hst, 0.0, 0.0, {})
62
+
63
+ # 在扬程 H 上求解:群泵流量(H) == 系统流量(H)
64
+ max_shutoff = max(self.pumps[pid].shutoff_head(f) for pid, f in active.items())
65
+ lo, hi = hst + 1e-6, max_shutoff - 1e-6
66
+ if hi <= lo: # 泵抬不动静扬程 → 无流量
67
+ return OperatingPoint(
68
+ 0.0, hst, 0.0, 0.0, {}, feasible=False,
69
+ reason="pump_head_below_static_head",
70
+ )
71
+
72
+ def resid(H):
73
+ return self.group_flow_at_head(H, active) - self.system_flow(H, level)
74
+
75
+ # resid 在 lo 处 >0(低扬程群泵能出更多流量),hi 处 <0
76
+ r_lo, r_hi = resid(lo), resid(hi)
77
+ if r_lo * r_hi > 0:
78
+ # 仅在区间内存在真实变号时才接受根;不能拿边界点冒充工作点。
79
+ H = self._scan_root(resid, lo, hi)
80
+ if H is None:
81
+ return OperatingPoint(
82
+ 0.0, hst, 0.0, 0.0, {}, feasible=False,
83
+ reason="no_pump_system_curve_intersection",
84
+ residual=float(min(abs(r_lo), abs(r_hi))),
85
+ )
86
+ else:
87
+ H = float(brentq(resid, lo, hi, xtol=1e-3))
88
+
89
+ per_pump, P_total, Q_total = {}, 0.0, 0.0
90
+ operating_range_ok = True
91
+ for pid, f in active.items():
92
+ pm = self.pumps[pid]
93
+ q = pm.flow_at_head(H, f)
94
+ if q < pm.q_min(f) - 1e-6 or q > pm.q_max(f) + 1e-6:
95
+ operating_range_ok = False
96
+ p = pm.input_power(q, f)
97
+ p = 0.0 if p != p else p # nan → 0
98
+ per_pump[pid] = {"Q": q, "H": H, "P": p, "eta": pm.eta(q, f), "freq": f}
99
+ Q_total += q
100
+ P_total += p
101
+ sec = P_total / Q_total if Q_total > 1e-6 else 0.0
102
+ curve_residual = Q_total - self.system_flow(H, level)
103
+ tolerance = max(0.5, Q_total * 1e-3)
104
+ feasible = (abs(curve_residual) <= tolerance and Q_total > 1e-6
105
+ and operating_range_ok)
106
+ return OperatingPoint(
107
+ Q_total, H, P_total, sec, per_pump,
108
+ feasible=feasible,
109
+ reason=(None if feasible else
110
+ "outside_verified_pump_curve_range" if not operating_range_ok else
111
+ "pump_system_curve_residual_too_large"),
112
+ residual=float(curve_residual),
113
+ )
114
+
115
+ @staticmethod
116
+ def _scan_root(fn, lo, hi, n=200):
117
+ import numpy as np
118
+ xs = np.linspace(lo, hi, n)
119
+ prev_x, prev_y = xs[0], fn(xs[0])
120
+ for x in xs[1:]:
121
+ y = fn(x)
122
+ if prev_y == 0:
123
+ return float(prev_x)
124
+ if prev_y * y < 0:
125
+ return float(brentq(fn, prev_x, x, xtol=1e-3))
126
+ prev_x, prev_y = x, y
127
+ return None
backend/app/models/pump_curve.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """泵特性建模(复用文档 2.1《泵组节能优化算法软件 V1.0》PumpCurveModel 规格)。
2
+
3
+ - 出厂 Q-H-η 曲线数字化:≥5 测点用三次样条 not-a-knot 边界;测点<4 退化线性插值。
4
+ - 相似定律换算变频工况:Q∝f, H∝f², P∝f³;效率低速修正。
5
+ - BEP / 高效运行区(BEP 流量的 60%~120%,GB/T 3216)。
6
+ - 按额定曲线在给定频率下:H(Q,f)、η(Q,f)、输入功率 P(Q,f)、以及给定扬程反解流量 Q(H,f)。
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+ import numpy as np
13
+ from scipy.interpolate import CubicSpline, interp1d
14
+ from scipy.optimize import brentq
15
+
16
+ RHO_G = 1000.0 * 9.81 # 水的 ρg (N/m³)
17
+
18
+
19
+ @dataclass
20
+ class PumpCurveModel:
21
+ pump_id: int
22
+ Q_pts: np.ndarray # 出厂测点流量 (m³/h) @ 额定频率
23
+ H_pts: np.ndarray # 扬程 (m)
24
+ eta_pts: np.ndarray # 效率 (0~1)
25
+ freq_nominal: float = 50.0
26
+ motor_eff: float = 0.95
27
+ variable_speed: bool = True
28
+
29
+ def __post_init__(self) -> None:
30
+ self.Q_pts = np.asarray(self.Q_pts, dtype=float)
31
+ self.H_pts = np.asarray(self.H_pts, dtype=float)
32
+ self.eta_pts = np.asarray(self.eta_pts, dtype=float)
33
+ if self.Q_pts.size < 2:
34
+ raise ValueError("至少需要 2 个测点")
35
+ # ≥4 点用三次样条 not-a-knot,否则退化线性插值(文档 2.1)
36
+ if self.Q_pts.size >= 4:
37
+ self._H = CubicSpline(self.Q_pts, self.H_pts, bc_type="not-a-knot")
38
+ self._eta = CubicSpline(self.Q_pts, self.eta_pts, bc_type="not-a-knot")
39
+ else:
40
+ self._H = interp1d(self.Q_pts, self.H_pts, kind="linear",
41
+ fill_value="extrapolate")
42
+ self._eta = interp1d(self.Q_pts, self.eta_pts, kind="linear",
43
+ fill_value="extrapolate")
44
+ # 额定 H(Q) 的二次系数(与 V1.0 a0/a1/a2 一致):H_nom=c0+c1·Q+c2·Q²。
45
+ # 用于快速解析求扬程与「给定扬程反解流量」,避免 brentq 嵌套(性能关键)。
46
+ d = min(2, self.Q_pts.size - 1)
47
+ coefs = np.polyfit(self.Q_pts, self.H_pts, d) # 高次在前
48
+ c = np.zeros(3); c[3 - len(coefs):] = coefs
49
+ self._Hc2, self._Hc1, self._Hc0 = float(c[0]), float(c[1]), float(c[2])
50
+ self._H_poly = np.polyfit(self.Q_pts, self.H_pts, min(3, self.Q_pts.size - 1))
51
+ self.Q_max_nominal = float(self.Q_pts.max())
52
+ # BEP:额定曲线上效率最高点
53
+ qs = np.linspace(self.Q_pts.min(), self.Q_pts.max(), 400)
54
+ es = np.clip(self._eta(qs), 0.0, None)
55
+ self.Q_bep_nominal = float(qs[int(np.argmax(es))])
56
+ self.eta_max = float(es.max())
57
+
58
+ @classmethod
59
+ def from_poly(cls, pump_id, a0, a1, a2, q_max, eta_max, q_bep, eta_sigma,
60
+ n_sample=21, **kw):
61
+ """按 V1.0 参数化构建:H(Q)=a0+a1·Q+a2·Q²(二次多项式)+ 高斯效率
62
+ η(Q)=η_max·exp(-((Q-Q_bep)/σ)²)。对现场标定的 a0/a1/a2/η_max/Q_bep/σ 直接可用。
63
+ 内部采样为测点后复用统一曲线通道(样条穿过二次曲线即还原二次)。"""
64
+ Q = np.linspace(0.0, float(q_max), n_sample)
65
+ H = a0 + a1 * Q + a2 * Q * Q
66
+ eta = eta_max * np.exp(-((Q - q_bep) / eta_sigma) ** 2)
67
+ return cls(pump_id=pump_id, Q_pts=Q, H_pts=H, eta_pts=eta, **kw)
68
+
69
+ # ---- 额定频率下的曲线 ----
70
+ def _H_nom(self, Q: float) -> float:
71
+ return float(self._H(Q))
72
+
73
+ def _eta_nom(self, Q: float) -> float:
74
+ return float(np.clip(self._eta(Q), 0.0, 0.95))
75
+
76
+ # ---- 相似定律换算到频率 f ----
77
+ def ratio(self, f: float) -> float:
78
+ return f / self.freq_nominal
79
+
80
+ def head(self, Q: float, f: float) -> float:
81
+ """给定流量与频率的扬程;额定曲线严格通过厂家测点,再按相似定律换算。"""
82
+ r = self.ratio(f)
83
+ if r <= 1e-6:
84
+ return 0.0
85
+ Q0 = Q / r # 等效额定流量
86
+ return self._H_nom(Q0) * r * r # H ∝ f²
87
+
88
+ def eta(self, Q: float, f: float) -> float:
89
+ """效率,含低速修正 η=η_nom·(0.92+0.08·r)(文档 2.1)。"""
90
+ r = self.ratio(f)
91
+ if r <= 1e-6:
92
+ return 0.0
93
+ e0 = self._eta_nom(Q / r)
94
+ return float(np.clip(e0 * (0.92 + 0.08 * r), 0.0, 0.95))
95
+
96
+ def input_power(self, Q: float, f: float) -> float:
97
+ """输入电功率 (kW):P = ρgQH/(η·η_motor)。η 过低时返回 nan。"""
98
+ H = self.head(Q, f)
99
+ e = self.eta(Q, f)
100
+ if e < 0.05 or H <= 0 or Q <= 0:
101
+ return float("nan")
102
+ Q_s = Q / 3600.0 # m³/s
103
+ return RHO_G * Q_s * H / (e * self.motor_eff) / 1000.0
104
+
105
+ def q_min(self, f: float) -> float:
106
+ return float(self.Q_pts.min()) * self.ratio(f)
107
+
108
+ def q_max(self, f: float) -> float:
109
+ return self.Q_max_nominal * self.ratio(f)
110
+
111
+ def shutoff_head(self, f: float) -> float:
112
+ # 厂家未给关死点时,只使用已验证曲线左端,不向未知小流量区外推。
113
+ return self.head(self.q_min(f), f)
114
+
115
+ def flow_at_head(self, H: float, f: float) -> float:
116
+ """在厂家已验证流量范围内反解Q;范围外不虚构曲线。"""
117
+ r = self.ratio(f)
118
+ if r <= 1e-6 or H <= 0:
119
+ return 0.0
120
+ qmin, qmax = self.q_min(f), self.q_max(f)
121
+ h_at_min, h_at_max = self.head(qmin, f), self.head(qmax, f)
122
+ if H > h_at_min:
123
+ return 0.0
124
+ if H < h_at_max:
125
+ return qmax
126
+ try:
127
+ return float(brentq(lambda q: self.head(q, f) - H, qmin, qmax, xtol=1e-3))
128
+ except ValueError:
129
+ return 0.0
130
+
131
+ # ---- 高效运行区 ----
132
+ def bep_flow(self, f: float) -> float:
133
+ return self.Q_bep_nominal * self.ratio(f)
134
+
135
+ def in_efficient_zone(self, Q: float, f: float, low: float = 0.60,
136
+ high: float = 1.20) -> bool:
137
+ qb = self.bep_flow(f)
138
+ return qb * low <= Q <= qb * high
139
+
140
+ def bep_deviation(self, Q: float, f: float) -> float:
141
+ """相对 BEP 流量的偏离度(0=在 BEP)。"""
142
+ qb = self.bep_flow(f)
143
+ return abs(Q - qb) / qb if qb > 0 else 1.0
backend/app/opcua_replay_server.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OPC UA server that replays normalized pump-station history from CSV.
2
+
3
+ The server uses the same NodeIds as ``opcua_sim_server`` so the edge collector
4
+ can switch between synthetic and historical data without remapping tags.
5
+ Missing measurements are published with ``BadNoData`` quality instead of being
6
+ invented. The normalized CSV stays under ``private-data/`` and is gitignored.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import asyncio
12
+ import csv
13
+ from dataclasses import dataclass
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+
17
+ from asyncua import Server, ua
18
+
19
+ NS_URI = "http://biditech.pump/opcua/"
20
+ PUMP_IDS = range(1, 6)
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ReplayRow:
25
+ timestamp: datetime
26
+ total_flow: float
27
+ total_power: float
28
+ level: float | None
29
+ pressure: float | None
30
+ pumps: dict[int, dict[str, float | int | None]]
31
+
32
+
33
+ def _optional_float(value: str | None) -> float | None:
34
+ if value is None or not value.strip():
35
+ return None
36
+ return float(value)
37
+
38
+
39
+ def load_replay_csv(path: str | Path) -> list[ReplayRow]:
40
+ source = Path(path)
41
+ if not source.is_file():
42
+ raise FileNotFoundError(f"Replay CSV not found: {source}")
43
+
44
+ rows: list[ReplayRow] = []
45
+ with source.open("r", encoding="utf-8-sig", newline="") as handle:
46
+ reader = csv.DictReader(handle)
47
+ required = {"timestamp", "totalFlow", "totalPower"}
48
+ missing = required.difference(reader.fieldnames or [])
49
+ if missing:
50
+ raise ValueError(f"Replay CSV missing columns: {', '.join(sorted(missing))}")
51
+
52
+ for line_number, raw in enumerate(reader, start=2):
53
+ try:
54
+ pumps: dict[int, dict[str, float | int | None]] = {}
55
+ for pump_id in PUMP_IDS:
56
+ prefix = f"pump{pump_id}."
57
+ pumps[pump_id] = {
58
+ "status": int(float(raw.get(prefix + "status") or 0)),
59
+ "freq": _optional_float(raw.get(prefix + "freq")),
60
+ "current": _optional_float(raw.get(prefix + "current")),
61
+ "power": _optional_float(raw.get(prefix + "power")),
62
+ "runHours": _optional_float(raw.get(prefix + "runHours")),
63
+ }
64
+ rows.append(
65
+ ReplayRow(
66
+ timestamp=datetime.fromisoformat(raw["timestamp"]),
67
+ total_flow=float(raw["totalFlow"]),
68
+ total_power=float(raw["totalPower"]),
69
+ level=_optional_float(raw.get("level")),
70
+ pressure=_optional_float(raw.get("pressure")),
71
+ pumps=pumps,
72
+ )
73
+ )
74
+ except (TypeError, ValueError) as exc:
75
+ raise ValueError(f"Invalid replay row {line_number}: {exc}") from exc
76
+
77
+ if not rows:
78
+ raise ValueError("Replay CSV contains no data rows")
79
+ if any(current.timestamp <= previous.timestamp for previous, current in zip(rows, rows[1:])):
80
+ raise ValueError("Replay timestamps must be strictly increasing")
81
+ return rows
82
+
83
+
84
+ async def _add_variable(parent, namespace: int, node_id: str, name: str, value, variant_type):
85
+ return await parent.add_variable(
86
+ ua.NodeId(node_id, namespace),
87
+ name,
88
+ ua.Variant(value, variant_type),
89
+ )
90
+
91
+
92
+ async def _write_measurement(node, value, variant_type, timestamp: datetime) -> None:
93
+ if value is None:
94
+ default = 0 if variant_type in (ua.VariantType.Int32, ua.VariantType.UInt32) else 0.0
95
+ data_value = ua.DataValue(
96
+ Value=ua.Variant(default, variant_type),
97
+ StatusCode=ua.StatusCode(ua.StatusCodes.BadNoData),
98
+ SourceTimestamp=timestamp,
99
+ )
100
+ else:
101
+ data_value = ua.DataValue(
102
+ Value=ua.Variant(value, variant_type),
103
+ StatusCode=ua.StatusCode(ua.StatusCodes.Good),
104
+ SourceTimestamp=timestamp,
105
+ )
106
+ await node.write_value(data_value)
107
+
108
+
109
+ async def run(
110
+ endpoint: str,
111
+ replay_csv: str | Path,
112
+ interval: float = 1.0,
113
+ start_index: int = 0,
114
+ loop: bool = True,
115
+ ) -> None:
116
+ rows = load_replay_csv(replay_csv)
117
+ if interval <= 0:
118
+ raise ValueError("Replay interval must be greater than zero")
119
+ if start_index < 0 or start_index >= len(rows):
120
+ raise ValueError(f"start-index must be between 0 and {len(rows) - 1}")
121
+
122
+ server = Server()
123
+ await server.init()
124
+ server.set_endpoint(endpoint)
125
+ server.set_server_name("Biditech Pump Station Historical Replay")
126
+ namespace = await server.register_namespace(NS_URI)
127
+ station = await server.nodes.objects.add_object(
128
+ ua.NodeId("PumpStation1", namespace), "PumpStation1"
129
+ )
130
+
131
+ station_nodes = {
132
+ "level": await _add_variable(station, namespace, "PumpStation1.Level", "Level", 0.0, ua.VariantType.Double),
133
+ "totalFlow": await _add_variable(station, namespace, "PumpStation1.TotalFlow", "TotalFlow", 0.0, ua.VariantType.Double),
134
+ "totalPower": await _add_variable(station, namespace, "PumpStation1.TotalPower", "TotalPower", 0.0, ua.VariantType.Double),
135
+ "pressure": await _add_variable(station, namespace, "PumpStation1.Pressure", "Pressure", 0.0, ua.VariantType.Double),
136
+ "writeEnable": await _add_variable(station, namespace, "PumpStation1.WriteEnable", "WriteEnable", False, ua.VariantType.Boolean),
137
+ "heartbeat": await _add_variable(station, namespace, "PumpStation1.Heartbeat", "Heartbeat", 0, ua.VariantType.UInt32),
138
+ "replayTimestamp": await _add_variable(station, namespace, "PumpStation1.ReplayTimestamp", "ReplayTimestamp", "", ua.VariantType.String),
139
+ "replayIndex": await _add_variable(station, namespace, "PumpStation1.ReplayIndex", "ReplayIndex", 0, ua.VariantType.UInt32),
140
+ "replayCount": await _add_variable(station, namespace, "PumpStation1.ReplayCount", "ReplayCount", len(rows), ua.VariantType.UInt32),
141
+ "dataSource": await _add_variable(station, namespace, "PumpStation1.DataSource", "DataSource", "historical-excel-replay", ua.VariantType.String),
142
+ }
143
+ await station_nodes["writeEnable"].set_writable()
144
+ await station_nodes["heartbeat"].set_writable()
145
+
146
+ pump_nodes: dict[int, dict[str, object]] = {}
147
+ for pump_id in PUMP_IDS:
148
+ pump = await station.add_object(
149
+ ua.NodeId(f"PumpStation1.Pump{pump_id}", namespace), f"Pump{pump_id}"
150
+ )
151
+ nodes = {
152
+ "status": await _add_variable(pump, namespace, f"PumpStation1.Pump{pump_id}.Status", "Status", 0, ua.VariantType.Int32),
153
+ "freq": await _add_variable(pump, namespace, f"PumpStation1.Pump{pump_id}.Freq", "Freq", 0.0, ua.VariantType.Double),
154
+ "current": await _add_variable(pump, namespace, f"PumpStation1.Pump{pump_id}.Current", "Current", 0.0, ua.VariantType.Double),
155
+ "power": await _add_variable(pump, namespace, f"PumpStation1.Pump{pump_id}.Power", "Power", 0.0, ua.VariantType.Double),
156
+ "runHours": await _add_variable(pump, namespace, f"PumpStation1.Pump{pump_id}.RunHours", "RunHours", 0.0, ua.VariantType.Double),
157
+ "freqSet": await _add_variable(pump, namespace, f"PumpStation1.Pump{pump_id}.FreqSet", "FreqSet", 0.0, ua.VariantType.Double),
158
+ "cmd": await _add_variable(pump, namespace, f"PumpStation1.Pump{pump_id}.Cmd", "Cmd", 0, ua.VariantType.Int32),
159
+ }
160
+ await nodes["freqSet"].set_writable()
161
+ await nodes["cmd"].set_writable()
162
+ pump_nodes[pump_id] = nodes
163
+
164
+ source = Path(replay_csv).resolve()
165
+ print(f"[opcua-replay] endpoint: {endpoint}")
166
+ print(f"[opcua-replay] source: {source}")
167
+ print(f"[opcua-replay] rows: {len(rows)} interval: {interval}s loop: {loop}")
168
+ print(f"[opcua-replay] namespace: ns={namespace} ({NS_URI})")
169
+
170
+ async with server:
171
+ index = start_index
172
+ while True:
173
+ row = rows[index]
174
+ await _write_measurement(station_nodes["level"], row.level, ua.VariantType.Double, row.timestamp)
175
+ await _write_measurement(station_nodes["totalFlow"], row.total_flow, ua.VariantType.Double, row.timestamp)
176
+ await _write_measurement(station_nodes["totalPower"], row.total_power, ua.VariantType.Double, row.timestamp)
177
+ await _write_measurement(station_nodes["pressure"], row.pressure, ua.VariantType.Double, row.timestamp)
178
+ await station_nodes["replayTimestamp"].write_value(row.timestamp.isoformat())
179
+ await station_nodes["replayIndex"].write_value(ua.Variant(index, ua.VariantType.UInt32))
180
+ await station_nodes["heartbeat"].write_value(ua.Variant(index, ua.VariantType.UInt32))
181
+
182
+ for pump_id in PUMP_IDS:
183
+ values = row.pumps[pump_id]
184
+ nodes = pump_nodes[pump_id]
185
+ await _write_measurement(nodes["status"], values["status"], ua.VariantType.Int32, row.timestamp)
186
+ await _write_measurement(nodes["freq"], values["freq"], ua.VariantType.Double, row.timestamp)
187
+ await _write_measurement(nodes["current"], values["current"], ua.VariantType.Double, row.timestamp)
188
+ await _write_measurement(nodes["power"], values["power"], ua.VariantType.Double, row.timestamp)
189
+ await _write_measurement(nodes["runHours"], values["runHours"], ua.VariantType.Double, row.timestamp)
190
+
191
+ index += 1
192
+ if index >= len(rows):
193
+ if not loop:
194
+ print("[opcua-replay] completed")
195
+ return
196
+ index = 0
197
+ await asyncio.sleep(interval)
198
+
199
+
200
+ def main() -> None:
201
+ parser = argparse.ArgumentParser(description="Biditech historical-data OPC UA replay server")
202
+ parser.add_argument("--csv", required=True, help="Normalized replay CSV")
203
+ parser.add_argument("--host", default="0.0.0.0")
204
+ parser.add_argument("--port", type=int, default=4840)
205
+ parser.add_argument("--path", default="/biditech/server/")
206
+ parser.add_argument("--interval", type=float, default=1.0, help="Real seconds per historical row")
207
+ parser.add_argument("--start-index", type=int, default=0)
208
+ parser.add_argument("--once", action="store_true", help="Stop after the final row")
209
+ args = parser.parse_args()
210
+ endpoint = f"opc.tcp://{args.host}:{args.port}{args.path}"
211
+ try:
212
+ asyncio.run(
213
+ run(
214
+ endpoint,
215
+ args.csv,
216
+ interval=args.interval,
217
+ start_index=args.start_index,
218
+ loop=not args.once,
219
+ )
220
+ )
221
+ except KeyboardInterrupt:
222
+ print("\n[opcua-replay] stopped")
223
+
224
+
225
+ if __name__ == "__main__":
226
+ main()
backend/app/opcua_sim_server.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OPC UA 仿真服务器(测试接口)。
2
+
3
+ 现场数据已汇聚到一台标准 PC 的 OPC UA 服务器上,我方软件作 UA 客户端去读。
4
+ 本模块提供一个**可运行的 OPC UA 仿真服务器**,把泵站点位模拟出来(含实时变化的
5
+ 液位/各泵频率电流功率状态/总流量,以及可写的频率设定/写使能/心跳),
6
+ 供 UaExpert / Node-RED / 我方客户端连它联调,无需真实现场。
7
+
8
+ 运行:
9
+ python -m app.opcua_sim_server # 默认 opc.tcp://0.0.0.0:4840/biditech/
10
+ python -m app.opcua_sim_server --port 4841
11
+ 点位命名对齐文档 4.1:ns=<idx>;s=PumpStation1.Pump<i>.<Freq|Current|Power|Status>
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import asyncio
17
+ import math
18
+ import time
19
+
20
+ from asyncua import Server, ua
21
+
22
+ from .models.curve_fit import power_from_current
23
+ from .plant import Plant
24
+
25
+ NS_URI = "http://biditech.pump/opcua/"
26
+
27
+
28
+ async def run(endpoint: str, interval: float = 1.0):
29
+ plant = Plant()
30
+ st = plant.station
31
+ line_v = st.get("line_voltage", 394.0)
32
+ level = st.get("level_target", 5.5)
33
+ area = st.get("wet_well_area", 57.2)
34
+ ids = list(plant.pumps.keys())
35
+
36
+ server = Server()
37
+ await server.init()
38
+ server.set_endpoint(endpoint)
39
+ server.set_server_name("Biditech Pump Station OPC UA Sim")
40
+ idx = await server.register_namespace(NS_URI)
41
+ objs = server.nodes.objects
42
+
43
+ station = await objs.add_object(ua.NodeId("PumpStation1", idx), "PumpStation1")
44
+
45
+ def sid(name):
46
+ return ua.NodeId(name, idx)
47
+
48
+ # 站级只读点
49
+ n_level = await station.add_variable(sid("PumpStation1.Level"), "Level", float(level))
50
+ n_flow = await station.add_variable(sid("PumpStation1.TotalFlow"), "TotalFlow", 0.0)
51
+ n_power = await station.add_variable(sid("PumpStation1.TotalPower"), "TotalPower", 0.0)
52
+ n_pressure = await station.add_variable(sid("PumpStation1.Pressure"), "Pressure", 0.0)
53
+ # 站级可写点(回写/联锁)
54
+ n_wen = await station.add_variable(sid("PumpStation1.WriteEnable"), "WriteEnable", False)
55
+ n_hb = await station.add_variable(sid("PumpStation1.Heartbeat"), "Heartbeat", 0)
56
+ await n_wen.set_writable()
57
+ await n_hb.set_writable()
58
+
59
+ # 各泵点位
60
+ pumps = {}
61
+ for pid in ids:
62
+ p = await station.add_object(sid(f"PumpStation1.Pump{pid}"), f"Pump{pid}")
63
+ vs = {
64
+ "Freq": await p.add_variable(sid(f"PumpStation1.Pump{pid}.Freq"), "Freq", 0.0),
65
+ "Current": await p.add_variable(sid(f"PumpStation1.Pump{pid}.Current"), "Current", 0.0),
66
+ "Power": await p.add_variable(sid(f"PumpStation1.Pump{pid}.Power"), "Power", 0.0),
67
+ "Status": await p.add_variable(sid(f"PumpStation1.Pump{pid}.Status"), "Status", 0),
68
+ "RunHours": await p.add_variable(sid(f"PumpStation1.Pump{pid}.RunHours"), "RunHours", 4700.0 + pid * 180),
69
+ # 可写:频率设定 + 启停指令
70
+ "FreqSet": await p.add_variable(sid(f"PumpStation1.Pump{pid}.FreqSet"), "FreqSet", 0.0),
71
+ "Cmd": await p.add_variable(sid(f"PumpStation1.Pump{pid}.Cmd"), "Cmd", 0),
72
+ }
73
+ await vs["FreqSet"].set_writable()
74
+ await vs["Cmd"].set_writable()
75
+ pumps[pid] = vs
76
+
77
+ # 初始运行:前两台变频泵
78
+ var_ids = [pid for pid in ids if plant.variable_speed.get(pid, True)]
79
+ running = set(var_ids[:2])
80
+
81
+ print(f"[opcua-sim] endpoint: {endpoint}")
82
+ print(f"[opcua-sim] namespace ns={idx} ({NS_URI})")
83
+ print(f"[opcua-sim] pumps: {ids} 初始在运: {sorted(running)}")
84
+ print("[opcua-sim] 用 UaExpert / Node-RED 连接以上端点浏览 PumpStation1.*")
85
+
86
+ async with server:
87
+ t0 = time.time()
88
+ while True:
89
+ t = time.time() - t0
90
+ active = {}
91
+ for pid in running:
92
+ base = 49.0 if plant.variable_speed.get(pid, True) else 50.0
93
+ jit = math.sin(t / 7 + pid) * 1.0 if plant.variable_speed.get(pid, True) else 0.0
94
+ active[pid] = max(20.0, min(50.0, base + jit))
95
+ op = plant.group.solve(active, level=level)
96
+
97
+ total_flow = op.Q_total
98
+ total_power = op.P_total
99
+ for pid in ids:
100
+ vs = pumps[pid]
101
+ if pid in running:
102
+ info = op.per_pump.get(pid, {})
103
+ q = info.get("Q", 0.0)
104
+ pw = info.get("P", 0.0)
105
+ cur = power_from_current # noqa: reuse name
106
+ amps = (pw * 1000.0) / (math.sqrt(3) * line_v * 0.85) if pw > 0 else 0.0
107
+ await vs["Freq"].write_value(round(active[pid], 2))
108
+ await vs["Power"].write_value(round(pw, 2))
109
+ await vs["Current"].write_value(round(amps, 1))
110
+ await vs["Status"].write_value(1)
111
+ else:
112
+ await vs["Freq"].write_value(0.0)
113
+ await vs["Power"].write_value(0.0)
114
+ await vs["Current"].write_value(0.0)
115
+ await vs["Status"].write_value(0)
116
+
117
+ # 液位物料平衡:入流波动,出流=总抽升
118
+ q_in = 1400.0 + 500.0 * math.sin(t / 60.0)
119
+ level += (q_in - total_flow) / 3600.0 * interval / area
120
+ level = max(3.0, min(9.0, level))
121
+
122
+ await n_level.write_value(round(level, 3))
123
+ await n_flow.write_value(round(total_flow, 1))
124
+ await n_power.write_value(round(total_power, 1))
125
+ await n_pressure.write_value(round(op.H / 102.0, 4)) # m→MPa 近似
126
+
127
+ await asyncio.sleep(interval)
128
+
129
+
130
+ def main():
131
+ ap = argparse.ArgumentParser(description="Biditech 泵站 OPC UA 仿真服务器")
132
+ ap.add_argument("--host", default="0.0.0.0")
133
+ ap.add_argument("--port", type=int, default=4840)
134
+ ap.add_argument("--path", default="/biditech/server/")
135
+ ap.add_argument("--interval", type=float, default=1.0)
136
+ args = ap.parse_args()
137
+ endpoint = f"opc.tcp://{args.host}:{args.port}{args.path}"
138
+ try:
139
+ asyncio.run(run(endpoint, args.interval))
140
+ except KeyboardInterrupt:
141
+ print("\n[opcua-sim] stopped")
142
+
143
+
144
+ if __name__ == "__main__":
145
+ main()
backend/app/optimizer/__init__.py ADDED
File without changes
backend/app/optimizer/mpc.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """组合优化调度(复用文档 2.2 MPCOptimizer 规格)。
2
+
3
+ 方法(文档主线):枚举可行开泵组合(0/1) → 每组合用 scipy L-BFGS-B 优化连续频率
4
+ → 取总成本最小者。工频软启泵只能开停、不进入连续频率优化。
5
+
6
+ 目标:min 总输入功率 + 流量偏差惩罚(软约束) + 频率变化惩罚 + 启停切换惩罚,
7
+ 约束:频率 [fmin,fmax]、单泵高效区(软)、最少/最多台数、轮换均衡(累计运行 h 少者优先)。
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from itertools import combinations
13
+
14
+ import numpy as np
15
+ from scipy.optimize import minimize
16
+
17
+ from ..models.parallel import PumpGroupParallelModel
18
+
19
+
20
+ @dataclass
21
+ class MPCOptimizer:
22
+ group: PumpGroupParallelModel
23
+ freq_min: float = 20.0
24
+ freq_max: float = 50.0
25
+ min_pumps: int = 1
26
+ max_pumps: int = 3
27
+ bep_low: float = 0.60
28
+ bep_high: float = 1.20
29
+ # 惩罚权重(对应 config penalties)
30
+ w_flow: float = 0.02
31
+ w_dfreq: float = 0.15
32
+ w_start: float = 0.08 # start_energy_kwh
33
+ w_bep: float = 0.5
34
+ w_rotation: float = 2e-4 # 轮换均衡 tie-breaker(按累计运行 h)
35
+ variable_speed: dict = field(default_factory=dict) # {id: bool}
36
+
37
+ def _pump_ids(self):
38
+ return list(self.group.pumps.keys())
39
+
40
+ # ---- 单个开泵组合的频率优化 ----
41
+ def _eval_freqs(self, subset, freqs, Q_target, current_freqs, level=None):
42
+ active = {pid: float(freqs[i]) for i, pid in enumerate(subset)}
43
+ op = self.group.solve(active, level=level)
44
+ if not op.feasible:
45
+ return 1e18, op
46
+ cost = op.P_total
47
+ cost += self.w_flow * (op.Q_total - Q_target) ** 2
48
+ # 频率变化惩罚(仅对持续运行的泵;对 [fmin,fmax] 归一化,
49
+ # 使 0.15 权重只抑制小幅 hunting,而不阻断合理的大幅设定值调整)
50
+ span = max(1e-6, self.freq_max - self.freq_min)
51
+ for pid in subset:
52
+ f0 = current_freqs.get(pid)
53
+ if f0 is not None and f0 > 1e-6:
54
+ cost += self.w_dfreq * ((active[pid] - f0) / span) ** 2
55
+ # 高效区软惩罚
56
+ for pid, info in op.per_pump.items():
57
+ pm = self.group.pumps[pid]
58
+ if not pm.in_efficient_zone(info["Q"], info["freq"], self.bep_low, self.bep_high):
59
+ cost += self.w_bep * pm.bep_deviation(info["Q"], info["freq"])
60
+ return cost, op
61
+
62
+ def _optimize_subset(self, subset, Q_target, current_freqs, level=None):
63
+ var_idx = [i for i, pid in enumerate(subset)
64
+ if self.variable_speed.get(pid, True)]
65
+ # 基础频率向量:工频泵锁 50Hz
66
+ base = np.array([self.freq_max] * len(subset), dtype=float)
67
+
68
+ if not var_idx: # 全工频泵:直接评估
69
+ cost, op = self._eval_freqs(subset, base, Q_target, current_freqs, level)
70
+ return cost, base, op
71
+
72
+ def obj(xv, x0):
73
+ f = x0.copy()
74
+ f[var_idx] = np.clip(xv, self.freq_min, self.freq_max)
75
+ return self._eval_freqs(subset, f, Q_target, current_freqs, level)[0]
76
+
77
+ bounds = [(self.freq_min, self.freq_max)] * len(var_idx)
78
+ # 多起点:从 freq_max 起(高扬程系统的可行区,避免低频零流量区把梯度困死),
79
+ # 并叠加当前频率作为另一起点,取最优。
80
+ starts = [np.full(len(var_idx), self.freq_max)]
81
+ cur = np.array([current_freqs.get(subset[i], 0.0) for i in var_idx])
82
+ if np.any(cur > self.freq_min):
83
+ starts.append(np.clip(cur, self.freq_min, self.freq_max))
84
+
85
+ best_cost, best_f = None, base.copy()
86
+ for x0v in starts:
87
+ x0 = base.copy()
88
+ res = minimize(lambda xv: obj(xv, x0), x0v, method="L-BFGS-B",
89
+ bounds=bounds, options={"maxiter": 80, "ftol": 1e-4})
90
+ f = base.copy()
91
+ f[var_idx] = np.clip(res.x, self.freq_min, self.freq_max)
92
+ c, _ = self._eval_freqs(subset, f, Q_target, current_freqs, level)
93
+ if best_cost is None or c < best_cost:
94
+ best_cost, best_f = c, f
95
+ cost, op = self._eval_freqs(subset, best_f, Q_target, current_freqs, level)
96
+ return cost, best_f, op
97
+
98
+ # ---- 主入口 ----
99
+ def optimize(self, Q_target, current_freqs=None, current_active=None,
100
+ run_hours=None, level=None):
101
+ current_freqs = current_freqs or {}
102
+ current_active = set(current_active or [])
103
+ run_hours = run_hours or {}
104
+ ids = self._pump_ids()
105
+
106
+ best = None
107
+ for n in range(self.min_pumps, self.max_pumps + 1):
108
+ for subset in combinations(ids, n):
109
+ subset = list(subset)
110
+ cost, freqs, op = self._optimize_subset(
111
+ subset, Q_target, current_freqs, level=level
112
+ )
113
+ flow_tolerance = max(50.0, abs(Q_target) * 0.03)
114
+ if (not op.feasible or
115
+ abs(op.Q_total - Q_target) > flow_tolerance):
116
+ continue
117
+ # 启停切换惩罚(组合层)
118
+ sset = set(subset)
119
+ n_starts = len(sset - current_active)
120
+ n_stops = len(current_active - sset)
121
+ cost += self.w_start * (n_starts + n_stops)
122
+ # 轮换均衡:优先选累计运行 h 少的泵
123
+ cost += self.w_rotation * sum(run_hours.get(pid, 0.0) for pid in subset)
124
+
125
+ if best is None or cost < best["cost"]:
126
+ best = {
127
+ "cost": float(cost),
128
+ "active": subset,
129
+ "freqs": {pid: round(float(freqs[i]), 2) for i, pid in enumerate(subset)},
130
+ "wp": {
131
+ "Q_total": round(op.Q_total, 2),
132
+ "H": round(op.H, 2),
133
+ "P_total": round(op.P_total, 2),
134
+ "spec_energy": round(op.spec_energy, 4),
135
+ "per_pump": {pid: {k: round(v, 3) for k, v in info.items()}
136
+ for pid, info in op.per_pump.items()},
137
+ "feasible": op.feasible,
138
+ "residual": round(op.residual, 3),
139
+ },
140
+ "P_total": round(op.P_total, 2),
141
+ "spec_energy": round(op.spec_energy, 4),
142
+ "n_starts": n_starts,
143
+ "n_stops": n_stops,
144
+ }
145
+
146
+ if best is None:
147
+ return {
148
+ "success": False,
149
+ "status": "infeasible_target",
150
+ "error": "当前泵曲线与系统曲线下,没有满足目标流量的可行工作点",
151
+ "Q_target": round(float(Q_target), 2),
152
+ }
153
+ best["success"] = True
154
+ return best
backend/app/plant.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """从 YAML 装配泵组 / 并联模型 / 优化器 / 预测器(单点装配,供 API 与测试共用)。"""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+
8
+ import yaml
9
+
10
+ from .models.forecaster import FlowForecaster
11
+ from .models.parallel import PumpGroupParallelModel
12
+ from .models.pump_curve import PumpCurveModel
13
+ from .optimizer.mpc import MPCOptimizer
14
+ from .safety import ControlState, SafetyGate
15
+
16
+ DEFAULT_CFG = Path(__file__).resolve().parent.parent / "config" / "pumps.yaml"
17
+
18
+
19
+ def _overrides_path() -> Path:
20
+ """运行时曲线覆盖(软件上传的曲线)持久化位置;测试可用环境变量隔离。"""
21
+ return Path(os.environ.get(
22
+ "BIDITECH_CURVE_OVERRIDES",
23
+ str(Path(__file__).resolve().parent.parent / "config" / "curve_overrides.json")))
24
+
25
+
26
+ class Plant:
27
+ def __init__(self, cfg_path: str | Path = DEFAULT_CFG):
28
+ with open(cfg_path, "r", encoding="utf-8") as f:
29
+ self.cfg = yaml.safe_load(f)
30
+ st = self.cfg["station"]
31
+ cons = self.cfg["constraints"]
32
+ pen = self.cfg["penalties"]
33
+ self._st = st
34
+
35
+ self.pumps = {}
36
+ self.variable_speed = {}
37
+ self.pump_meta = {}
38
+ for p in self.cfg["pumps"]:
39
+ self._install_pump(p)
40
+
41
+ self.group = PumpGroupParallelModel(
42
+ pumps=self.pumps,
43
+ static_head=st["static_head"],
44
+ pipe_resistance=float(st["pipe_resistance"]),
45
+ level_ref=st.get("level_ref"),
46
+ )
47
+ self.optimizer = MPCOptimizer(
48
+ group=self.group,
49
+ freq_min=st["freq_min"], freq_max=st["freq_max"],
50
+ min_pumps=cons["min_pumps"], max_pumps=cons["max_pumps"],
51
+ bep_low=cons["bep_low"], bep_high=cons["bep_high"],
52
+ w_flow=pen["flow_deviation"], w_dfreq=pen["dfreq"],
53
+ w_start=pen["start_energy_kwh"], w_bep=pen["bep_violation"],
54
+ variable_speed=self.variable_speed,
55
+ )
56
+ self.forecaster = FlowForecaster(wet_well_area=st["wet_well_area"])
57
+
58
+ # Phase 3 安全联锁
59
+ saf = self.cfg.get("safety", {})
60
+ self.safety_gate = SafetyGate(
61
+ freq_min=st["freq_min"], freq_max=st["freq_max"],
62
+ freq_step_per_cycle=saf.get("freq_step_per_cycle", 5.0),
63
+ pressure_max_mpa=cons["pressure_max_mpa"],
64
+ min_pumps=cons["min_pumps"],
65
+ watchdog_timeout_s=saf.get("watchdog_timeout_s", 5.0),
66
+ start_freq=saf.get("start_freq", st["freq_min"]),
67
+ level_ll_stop=saf.get("level_ll_stop", 0.0),
68
+ level_hh=saf.get("level_hh", 0.0),
69
+ variable_speed=self.variable_speed,
70
+ )
71
+ self.control = ControlState(
72
+ mode=saf.get("default_mode", "manual"),
73
+ write_enable=saf.get("default_write_enable", False),
74
+ )
75
+ self.station = st
76
+ self.constraints = cons
77
+ self.level_range = {
78
+ "level_min": st.get("level_min", 1.0),
79
+ "level_max": st.get("level_max", 4.5),
80
+ "level_target": st.get("level_target", st.get("level_min", 1.0)),
81
+ "level_scale_max": st.get("level_scale_max"),
82
+ "level_ll_stop": saf.get("level_ll_stop", 0.0),
83
+ "level_hh": saf.get("level_hh", 0.0),
84
+ }
85
+ self._load_overrides()
86
+
87
+ # ---- 泵曲线安装 / 运行时热更新(软件上传曲线,无需改 YAML)----
88
+ def _install_pump(self, p: dict) -> None:
89
+ """按配置 dict(含 poly+eta_gauss 或 curve)构建/替换单泵模型。就地更新共享 dict。"""
90
+ st = self._st
91
+ pid = p["id"]
92
+ vs = p.get("variable_speed", self.variable_speed.get(pid, True))
93
+ kw = dict(
94
+ freq_nominal=st["freq_nominal"],
95
+ motor_eff=p.get("motor_eff", st["motor_eff"]),
96
+ variable_speed=vs,
97
+ )
98
+ if "poly" in p and p["poly"]:
99
+ pol, g = p["poly"], p["eta_gauss"]
100
+ model = PumpCurveModel.from_poly(
101
+ pid, pol["a0"], pol["a1"], pol["a2"], pol["q_max"],
102
+ g["eta_max"], g["q_bep"], g["sigma"], **kw)
103
+ else:
104
+ c = p["curve"]
105
+ model = PumpCurveModel(pump_id=pid, Q_pts=c["Q"], H_pts=c["H"],
106
+ eta_pts=c["eta"], **kw)
107
+ if p.get("bep_flow") is not None:
108
+ model.Q_bep_nominal = float(p["bep_flow"])
109
+ self.pumps[pid] = model # group.pumps 是同一 dict,随之更新
110
+ self.variable_speed[pid] = vs # optimizer/safety 持有同一 dict 引用
111
+ self.pump_meta[pid] = {
112
+ "id": pid,
113
+ "name": p.get("name", self.pump_meta.get(pid, {}).get("name", f"{pid} 号泵")),
114
+ "variable_speed": vs,
115
+ "rated_kw": p.get("rated_kw", self.pump_meta.get(pid, {}).get("rated_kw")),
116
+ "curve_source": p.get("curve_source", self.pump_meta.get(pid, {}).get("curve_source", "config")),
117
+ "hydraulic_code": p.get("hydraulic_code"),
118
+ "curve_reference": p.get("curve_reference"),
119
+ "curve_revision": p.get("curve_revision"),
120
+ "curve_basis": p.get("curve_basis"),
121
+ "verified_flow_range": p.get("verified_flow_range"),
122
+ }
123
+
124
+ def apply_curve(self, pid: int, spec: dict) -> dict:
125
+ """运行时应用一条泵曲线(来自软件上传/拟合),并持久化到 overrides。
126
+ spec: {poly:{a0,a1,a2,q_max}, eta_gauss:{eta_max,q_bep,sigma}, name?, variable_speed?, rated_kw?}"""
127
+ if pid not in self.pumps:
128
+ raise KeyError(f"no pump {pid}")
129
+ p = dict(spec); p["id"] = pid
130
+ p.setdefault("curve_source", "uploaded")
131
+ self._install_pump(p)
132
+ self._save_override(pid, p)
133
+ return self.pump_meta[pid]
134
+
135
+ def _load_overrides(self) -> None:
136
+ ovp = _overrides_path()
137
+ if not ovp.exists():
138
+ self.overrides = {}
139
+ return
140
+ try:
141
+ self.overrides = json.loads(ovp.read_text(encoding="utf-8"))
142
+ except (json.JSONDecodeError, OSError):
143
+ self.overrides = {}
144
+ return
145
+ for pid_str, spec in self.overrides.items():
146
+ try:
147
+ self._install_pump({**spec, "id": int(pid_str)})
148
+ except (KeyError, TypeError, ValueError):
149
+ continue
150
+
151
+ def _save_override(self, pid: int, spec: dict) -> None:
152
+ ov = getattr(self, "overrides", {}) or {}
153
+ ov[str(pid)] = spec
154
+ self.overrides = ov
155
+ try:
156
+ _overrides_path().write_text(json.dumps(ov, ensure_ascii=False, indent=2),
157
+ encoding="utf-8")
158
+ except OSError:
159
+ pass
160
+
161
+ def sampled_curve(self, pid: int, freq: float = 50.0, n: int = 40) -> dict:
162
+ pm = self.pumps[pid]
163
+ qmin, qmax = pm.q_min(freq), pm.q_max(freq)
164
+ hq, eq, pq = [], [], []
165
+ for i in range(n + 1):
166
+ q = qmin + (qmax - qmin) * i / n
167
+ hq.append([round(q, 1), round(pm.head(q, freq), 3)])
168
+ eq.append([round(q, 1), round(pm.eta(q, freq) * 100, 2)])
169
+ pw = pm.input_power(q, freq)
170
+ if pw == pw:
171
+ pq.append([round(q, 1), round(pw, 2)])
172
+ return {"pump_id": pid, "freq": freq, "bep_flow": round(pm.bep_flow(freq), 1),
173
+ "HQ": hq, "etaQ": eq, "PQ": pq}
174
+
175
+ def baseline_all_on_50hz(self, Q_target: float):
176
+ """基线对照:全泵 50Hz 工频运行(未调速)的工作点。"""
177
+ active = {pid: self.optimizer.freq_max for pid in self.pumps}
178
+ return self.group.solve(active)
179
+
180
+ def baseline_meet_target(self, Q_target: float, level: float | None = None):
181
+ """公平基线:不调频(全 50Hz),从少到多台开到刚好满足目标流量——
182
+ 代表「未做变频优化、只按台数分级」的现状运行,用于评估优化节能潜力。"""
183
+ ids = list(self.pumps)
184
+ fmax = self.optimizer.freq_max
185
+ last = self.group.solve({}, level=level)
186
+ for n in range(1, len(ids) + 1):
187
+ last = self.group.solve({ids[i]: fmax for i in range(n)}, level=level)
188
+ if last.Q_total >= Q_target:
189
+ break
190
+ return last
backend/app/safety.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Phase 3 安全联锁门控(对应文档 1.6:闭环回写关键)。
2
+
3
+ 把优化建议在下发前逐项过安全门:写使能、指令限幅、频率斜坡限速、高压硬联锁、
4
+ 最少台数保证、CRITICAL 报警跳过、watchdog 心跳超时切回本地 PID。
5
+ manual(开环)模式下 AI 不下发;auto(闭环)模式下每周期经本门控输出安全指令。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from dataclasses import dataclass, field
11
+
12
+
13
+ @dataclass
14
+ class ControlState:
15
+ mode: str = "manual" # manual(开环建议) | auto(闭环)
16
+ write_enable: bool = False # bWriteEnable:AI 回写总使能
17
+ critical_alarm: bool = False # CRITICAL 报警(真则跳过优化)
18
+ last_heartbeat: float = field(default_factory=time.time)
19
+ heartbeat_count: int = 0
20
+ last_command: dict | None = None # 最近一次已下发的安全指令
21
+ reverted: bool = False # 是否处于「已切回」安全态
22
+
23
+ def beat(self, now: float | None = None) -> None:
24
+ self.last_heartbeat = now if now is not None else time.time()
25
+ self.heartbeat_count += 1
26
+
27
+ def watchdog_age(self, now: float | None = None) -> float:
28
+ return (now if now is not None else time.time()) - self.last_heartbeat
29
+
30
+
31
+ @dataclass
32
+ class SafetyGate:
33
+ freq_min: float = 20.0
34
+ freq_max: float = 50.0
35
+ freq_step_per_cycle: float = 5.0 # 每周期最大 Δf(斜坡限速)
36
+ pressure_max_mpa: float = 0.55 # 高压硬联锁
37
+ min_pumps: int = 1
38
+ watchdog_timeout_s: float = 5.0
39
+ start_freq: float = 20.0
40
+ level_ll_stop: float = 0.0 # 低水位保护停泵阈值 (m),0=不启用
41
+ level_hh: float = 0.0 # 高水位阈值 (m),0=不启用
42
+ variable_speed: dict = field(default_factory=dict)
43
+
44
+ def _clip(self, f: float) -> float:
45
+ return max(self.freq_min, min(self.freq_max, float(f)))
46
+
47
+ def gate(self, suggestion: dict, realtime: dict, state: ControlState,
48
+ now: float | None = None) -> dict:
49
+ """把 suggestion 过安全门,返回可下发的安全指令与拦截项。
50
+
51
+ realtime: {pressure(MPa), pumps:[{id,freq,status}], ...} 当前实况。
52
+ 返回: {approved, command:{active,freqs}, interventions:[...], reasons:[...], watchdog_ok}
53
+ """
54
+ now = now if now is not None else time.time()
55
+ interventions: list[str] = []
56
+ reasons: list[str] = []
57
+
58
+ cur_freq = {p["id"]: float(p.get("freq", 0.0)) for p in realtime.get("pumps", [])}
59
+ cur_active = {p["id"] for p in realtime.get("pumps", []) if int(p.get("status", 0)) == 1}
60
+ hold_cmd = {"active": sorted(cur_active),
61
+ "freqs": {pid: cur_freq.get(pid, 0.0) for pid in cur_active}}
62
+
63
+ # 1) 写使能
64
+ if not state.write_enable:
65
+ reasons.append("写使能未开启(bWriteEnable=False),AI 不下发")
66
+ return self._result(False, hold_cmd, interventions, reasons, True)
67
+
68
+ # 2) watchdog 心跳超时 → 切回本地 PID/工频(无扰:维持最后有效设定)
69
+ age = state.watchdog_age(now)
70
+ watchdog_ok = age <= self.watchdog_timeout_s
71
+ if not watchdog_ok:
72
+ reasons.append(f"watchdog 心跳超时 {age:.1f}s>{self.watchdog_timeout_s}s,切回本地 PID")
73
+ return self._result(False, hold_cmd, interventions, reasons, False)
74
+
75
+ # 3) CRITICAL 报警跳过优化(文档 alarm.has_critical())
76
+ if state.critical_alarm:
77
+ reasons.append("CRITICAL 报警有效,跳过优化,维持当前设定")
78
+ return self._result(False, hold_cmd, interventions, reasons, True)
79
+
80
+ # 3b) 低水位保护停泵(防干抽,对应 SCADA LL 报警)——硬联锁,停全部
81
+ level = realtime.get("level")
82
+ if self.level_ll_stop > 0 and level is not None and float(level) < self.level_ll_stop:
83
+ reasons.append(f"低水位保护:液位 {float(level):.2f}<{self.level_ll_stop}m,停泵防干抽")
84
+ return self._result(False, {"active": [], "freqs": {}}, interventions, reasons, True)
85
+ # 高水位提示(需增泵防溢流,不阻断启泵)
86
+ high_level = self.level_hh > 0 and level is not None and float(level) > self.level_hh
87
+ if high_level:
88
+ interventions.append(f"高水位:液位 {float(level):.2f}>{self.level_hh}m,建议增泵防溢流")
89
+
90
+ # 4) 高压硬联锁:出口压力越限,禁止升频/启泵(仅允许维持或降)
91
+ pressure = float(realtime.get("pressure", 0.0))
92
+ high_pressure = pressure > self.pressure_max_mpa
93
+ if high_pressure:
94
+ interventions.append(f"高压保护:出口压力 {pressure:.3f}>{self.pressure_max_mpa}MPa,禁止升频/启泵")
95
+
96
+ target_active = list(suggestion.get("active", []))
97
+ target_freq = {int(k): float(v) for k, v in suggestion.get("freqs", {}).items()}
98
+
99
+ # 5) 最少运行���数保证
100
+ if len(target_active) < self.min_pumps:
101
+ reasons.append(f"建议台数 {len(target_active)}<最少 {self.min_pumps},维持当前")
102
+ return self._result(False, hold_cmd, interventions, reasons, True)
103
+
104
+ # 6) 逐泵生成安全频率:斜坡限速 + 限幅 + 工频锁定 + 高压闭锁升频/启泵
105
+ safe_freq: dict = {}
106
+ for pid in target_active:
107
+ is_vfd = self.variable_speed.get(pid, True)
108
+ tgt = self._clip(self.freq_max if not is_vfd else target_freq.get(pid, self.freq_min))
109
+ if pid in cur_active:
110
+ cur = cur_freq.get(pid, self.freq_max)
111
+ step = tgt - cur
112
+ if abs(step) > self.freq_step_per_cycle: # 斜坡限速
113
+ tgt = cur + self.freq_step_per_cycle * (1 if step > 0 else -1)
114
+ interventions.append(f"频率限速:{pid}号 {cur:.1f}→{tgt:.1f}(目标{target_freq.get(pid, self.freq_max):.1f})")
115
+ if high_pressure and tgt > cur: # 高压禁止升频
116
+ tgt = cur
117
+ interventions.append(f"高压闭锁:{pid}号维持 {cur:.1f}Hz 不升频")
118
+ else:
119
+ # 新启泵:从 start_freq 起(高压时禁止启泵)
120
+ if high_pressure:
121
+ interventions.append(f"高压闭锁:{pid}号禁止启泵")
122
+ continue
123
+ tgt = self._clip(self.start_freq if is_vfd else self.freq_max)
124
+ interventions.append(f"软启动:{pid}号起始 {tgt:.1f}Hz 后逐周期斜坡")
125
+ safe_freq[pid] = round(self._clip(tgt), 2)
126
+
127
+ if len(safe_freq) < self.min_pumps: # 高压闭锁后兜底
128
+ reasons.append("安全联锁后可运行台数不足,维持当前")
129
+ return self._result(False, hold_cmd, interventions, reasons, True)
130
+
131
+ command = {"active": sorted(safe_freq.keys()), "freqs": safe_freq}
132
+ state.last_command = command
133
+ return self._result(True, command, interventions, reasons, True)
134
+
135
+ @staticmethod
136
+ def _result(approved, command, interventions, reasons, watchdog_ok):
137
+ return {
138
+ "approved": approved,
139
+ "command": command,
140
+ "interventions": interventions,
141
+ "reasons": reasons,
142
+ "watchdog_ok": watchdog_ok,
143
+ }
backend/app/sim/__init__.py ADDED
File without changes
backend/app/sim/hydraulic.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HIL 水力仿真台(复用文档 4.5 测试思路)。
2
+
3
+ 用管阻特性 H=Hst+S·Q² + 泵曲线构成闭环:给定各泵频率求稳态工作点,
4
+ 并按物料平衡推进集水池液位动态,用于验证优化器确能降低 SEC。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+
10
+ from ..models.parallel import PumpGroupParallelModel
11
+
12
+
13
+ @dataclass
14
+ class WetWell:
15
+ area: float = 20.0 # 截面积 m²
16
+ level: float = 2.6 # 初始液位 m
17
+ level_min: float = 1.0
18
+ level_max: float = 4.5
19
+
20
+ def step(self, q_in: float, q_out: float, dt_s: float) -> float:
21
+ """按 dt 秒推进液位。q 单位 m³/h。"""
22
+ dV = (q_in - q_out) / 3600.0 * dt_s # m³
23
+ self.level += dV / self.area
24
+ self.level = max(0.0, min(self.level_max + 1.0, self.level))
25
+ return self.level
26
+
27
+
28
+ class HydraulicSim:
29
+ def __init__(self, group: PumpGroupParallelModel, wet_well: WetWell | None = None):
30
+ self.group = group
31
+ self.well = wet_well or WetWell()
32
+
33
+ def steady_state(self, active: dict):
34
+ """给定 active={id:freq} 的稳态工作点(复用并联模型求解)。"""
35
+ return self.group.solve(active)
36
+
37
+ def run(self, active: dict, q_in_series, dt_s: float = 1.0):
38
+ """按入流序列跑闭环,返回每步 (level, Q_out, P_total, SEC) 轨迹。"""
39
+ traj = []
40
+ for q_in in q_in_series:
41
+ op = self.steady_state(active)
42
+ self.well.step(q_in, op.Q_total, dt_s)
43
+ traj.append({
44
+ "level": round(self.well.level, 3),
45
+ "Q_out": round(op.Q_total, 2),
46
+ "P_total": round(op.P_total, 2),
47
+ "sec": round(op.spec_energy, 4),
48
+ })
49
+ return traj
backend/config/pumps.yaml ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 胶州水厂二期 提升泵站 — 泵组与站参数
2
+ # 泵组(现场确认,2026-07 更新):
3
+ # 变频:1# 飞力 Flygt NP3202 180LT610 37kW(型号确认,曲线待精确,BEP≈80% 估)
4
+ # 2# Hidrostal F10K-SS 45kW(★实测曲线,BEP 82.9%,工况点偏右,降频零惩罚)
5
+ # 5# Hidrostal F10K-SS 45kW 永磁变频(★实测曲线,与 2# 同款)
6
+ # 工频软启:3# / 4# 45kW(基础负荷)
7
+ # 关键:变频泵此前锁 50Hz 运行(硬件已具备调速能力但未启用)——解放后按液位/来水动态调频是节能大头。
8
+ # ★Hidrostal 螺旋离心泵效率平、工况点在大流量端(BEP 右侧),降频把工况拉回高效区、效率不掉。
9
+ # ★2#/5# 实测 Q-H-η 请用「泵曲线管理」上传或从 胶州公司进水提升泵资料-补充.xlsx 填入;下面为占位值。
10
+ station:
11
+ name: 胶州水厂二期提升泵站
12
+ static_head: 12.3 # 参考液位处静扬程 (m) ★现场校核
13
+ pipe_resistance: 3.0e-6 # 管阻系数 S (DN300 短管) ★现场校核
14
+ level_ref: 5.5 # 静扬程参考液位 (m)
15
+ wet_well_area: 57.2 # 集水井截面积 = 长6.5 × 宽8.8 (m²)
16
+ level_min: 3.5
17
+ level_max: 8.5
18
+ level_target: 5.5
19
+ level_scale_max: 10.0
20
+ line_voltage: 394.0
21
+ motor_eff: 0.95
22
+ freq_nominal: 50.0
23
+ freq_min: 20.0
24
+ freq_max: 50.0
25
+
26
+ constraints:
27
+ min_pumps: 1
28
+ max_pumps: 5
29
+ bep_low: 0.60
30
+ bep_high: 1.20
31
+ pressure_max_mpa: 0.55
32
+
33
+ penalties:
34
+ flow_deviation: 0.02
35
+ dfreq: 0.15
36
+ start_energy_kwh: 0.08
37
+ bep_violation: 0.5
38
+
39
+ safety:
40
+ freq_step_per_cycle: 5.0
41
+ watchdog_timeout_s: 5.0
42
+ start_freq: 20.0
43
+ level_ll_stop: 3.0
44
+ level_hh: 9.0
45
+ default_mode: manual
46
+ default_write_enable: false
47
+
48
+ # 厂家曲线均以额定转速/50Hz数据录入;变频工况由相似定律换算。
49
+ # Flygt 610为厂家曲线图数字化点;Hidrostal为厂家水力报告C-2175表格原始点。
50
+ pumps:
51
+ - id: 1
52
+ name: 1 号泵(Flygt NP 3202.180 LT 610 变频)
53
+ hydraulic_code: NP 3202.180 LT 610
54
+ variable_speed: true
55
+ rated_kw: 37
56
+ bep_flow: 900
57
+ motor_eff: 0.895
58
+ curve_source: manufacturer_curve_digitized
59
+ curve_reference: docs/Flygt_NS3202LT610.pdf
60
+ curve_revision: 2018-05-10
61
+ curve_basis: Flygt 610曲线图数字化;50Hz,970rpm,叶轮396mm,ISO曲线
62
+ verified_flow_range: [0, 1692]
63
+ curve:
64
+ Q: [0, 200, 400, 600, 800, 900, 1000, 1200, 1400, 1600, 1692]
65
+ H: [21.5, 19.4, 17.0, 15.1, 13.1, 12.2, 11.2, 8.6, 6.2, 3.9, 2.1]
66
+ eta: [0.00, 0.40, 0.62, 0.75, 0.825, 0.843, 0.837, 0.785, 0.68, 0.48, 0.32]
67
+
68
+ - id: 2
69
+ name: 2 号泵(Hidrostal F10K-SS1 + FN050X4 变频)
70
+ hydraulic_code: F10K-SS1 + FN050X4
71
+ variable_speed: true
72
+ rated_kw: 45
73
+ bep_flow: 774.72
74
+ curve_source: manufacturer_hydraulic_report
75
+ curve_reference: docs/sources/Hidrostal_Hydraulic_Report_F10K-SS.xlsx
76
+ curve_revision: C-2175 Rev.2
77
+ curve_basis: F10K-SS水力曲线;20°C清水,ISO 9906:2012,1470rpm
78
+ verified_flow_range: [426.24, 1006.92]
79
+ curve: &hidrostal_f10k_ss
80
+ Q: [426.24, 464.76, 542.16, 619.56, 697.32, 774.72, 852.12, 929.52, 1006.92]
81
+ H: [23.6, 22.7, 21.0, 19.4, 17.8, 16.4, 14.9, 13.3, 11.6]
82
+ eta: [0.708, 0.735, 0.778, 0.807, 0.824, 0.829, 0.822, 0.803, 0.770]
83
+
84
+ - id: 3
85
+ name: 3 号泵(Hidrostal F10K-SS1 + FN050X4 工频)
86
+ hydraulic_code: F10K-SS1 + FN050X4
87
+ variable_speed: false
88
+ rated_kw: 45
89
+ bep_flow: 774.72
90
+ curve_source: manufacturer_hydraulic_report
91
+ curve_reference: docs/sources/Hidrostal_Hydraulic_Report_F10K-SS.xlsx
92
+ curve_revision: C-2175 Rev.2
93
+ curve_basis: F10K-SS水力曲线;20°C清水,ISO 9906:2012,1470rpm
94
+ verified_flow_range: [426.24, 1006.92]
95
+ curve: *hidrostal_f10k_ss
96
+
97
+ - id: 4
98
+ name: 4 号泵(Hidrostal F10K-SS1 + FN050X4 工频)
99
+ hydraulic_code: F10K-SS1 + FN050X4
100
+ variable_speed: false
101
+ rated_kw: 45
102
+ bep_flow: 774.72
103
+ curve_source: manufacturer_hydraulic_report
104
+ curve_reference: docs/sources/Hidrostal_Hydraulic_Report_F10K-SS.xlsx
105
+ curve_revision: C-2175 Rev.2
106
+ curve_basis: F10K-SS水力曲线;20°C清水,ISO 9906:2012,1470rpm
107
+ verified_flow_range: [426.24, 1006.92]
108
+ curve: *hidrostal_f10k_ss
109
+
110
+ - id: 5
111
+ name: 5 号泵(Hidrostal F10K-SS1 + FN050X4 永磁变频)
112
+ hydraulic_code: F10K-SS1 + FN050X4
113
+ variable_speed: true
114
+ rated_kw: 45
115
+ bep_flow: 774.72
116
+ curve_source: manufacturer_hydraulic_report
117
+ curve_reference: docs/sources/Hidrostal_Hydraulic_Report_F10K-SS.xlsx
118
+ curve_revision: C-2175 Rev.2
119
+ curve_basis: F10K-SS水力曲线;20°C清水,ISO 9906:2012,1470rpm
120
+ verified_flow_range: [426.24, 1006.92]
121
+ curve: *hidrostal_f10k_ss
backend/requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numpy>=1.26
2
+ scipy>=1.11
3
+ fastapi>=0.110
4
+ uvicorn[standard]>=0.29
5
+ pyyaml>=6.0
6
+ pydantic>=2.6
7
+ # 测试
8
+ pytest>=8.0
9
+ httpx>=0.27
10
+ # OPC UA(仿真测试服务器 app/opcua_sim_server.py + 客户端 tools/opcua_test_client.py;
11
+ # 现场数据已汇聚到标准 PC 的 OPC UA 服务器,我方作 UA 客户端读取)
12
+ asyncua>=1.0
backend/tests/__init__.py ADDED
File without changes
backend/tests/test_curve.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from app.models.pump_curve import PumpCurveModel
4
+
5
+ Q = [0, 40, 80, 120, 150, 180, 210]
6
+ H = [58.0, 56.5, 53.0, 47.0, 42.5, 36.0, 27.0]
7
+ E = [0.0, 0.42, 0.66, 0.79, 0.82, 0.78, 0.66]
8
+
9
+
10
+ def make():
11
+ return PumpCurveModel(1, Q, H, E, freq_nominal=50.0)
12
+
13
+
14
+ def test_head_monotonic_decreasing():
15
+ pm = make()
16
+ heads = [pm.head(q, 50.0) for q in range(0, 210, 10)]
17
+ # H-Q 在工作段应整体递减,不出现负值/振荡(not-a-knot 边界的价值)
18
+ assert all(heads[i] >= heads[i + 1] - 1e-6 for i in range(len(heads) - 1))
19
+ assert min(heads) > 0
20
+
21
+
22
+ def test_affinity_laws():
23
+ pm = make()
24
+ # 相似定律:40Hz 下 shutoff head ≈ 50Hz shutoff × (40/50)²
25
+ r = 40.0 / 50.0
26
+ assert abs(pm.shutoff_head(40.0) - pm.shutoff_head(50.0) * r * r) < 1e-6
27
+ # Q∝f:50Hz 的 BEP 流量 × r ≈ 40Hz BEP 流量
28
+ assert abs(pm.bep_flow(40.0) - pm.bep_flow(50.0) * r) < 1e-6
29
+
30
+
31
+ def test_flow_at_head_inverse():
32
+ pm = make()
33
+ q = 120.0
34
+ h = pm.head(q, 50.0)
35
+ q_back = pm.flow_at_head(h, 50.0)
36
+ assert abs(q_back - q) < 1.0 # 反解误差 < 1 m³/h
37
+
38
+
39
+ def test_bep_and_efficiency():
40
+ pm = make()
41
+ assert 130 < pm.bep_flow(50.0) < 170 # BEP 落在 150 附近
42
+ assert 0.75 < pm.eta_max <= 0.85
43
+ # 低速效率修正使 30Hz 峰值效率低于 50Hz
44
+ assert pm.eta(pm.bep_flow(30.0), 30.0) < pm.eta(pm.bep_flow(50.0), 50.0)
45
+
46
+
47
+ def test_input_power_positive():
48
+ pm = make()
49
+ p = pm.input_power(150.0, 50.0)
50
+ assert 15 < p < 45 # 45kW 泵在该工况点(150 m³/h,42.5m)的输入功率量级
51
+
52
+
53
+ def test_from_poly_matches_quadratic_and_gaussian():
54
+ # V1.0 参数形式:H=a0+a1Q+a2Q²,η 高斯
55
+ a0, a1, a2 = 58.0, 0.02, -7.0e-4
56
+ eta_max, q_bep, sigma = 0.82, 150.0, 95.0
57
+ pm = PumpCurveModel.from_poly(9, a0, a1, a2, q_max=210, eta_max=eta_max,
58
+ q_bep=q_bep, eta_sigma=sigma, freq_nominal=50.0)
59
+ # 扬程应还原二次多项式
60
+ for q in (0.0, 60.0, 150.0, 200.0):
61
+ assert abs(pm.head(q, 50.0) - (a0 + a1 * q + a2 * q * q)) < 0.5
62
+ # 高斯效率峰值落在 q_bep 附近
63
+ assert abs(pm.bep_flow(50.0) - q_bep) < 12
64
+ assert abs(pm.eta_max - eta_max) < 0.02
backend/tests/test_curve_fit.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from app.models.curve_fit import (eta_from_power, fit_eta_gaussian,
4
+ fit_head_poly, identify_pump)
5
+
6
+ # 已知真值(额定 50Hz)
7
+ A0, A1, A2 = 58.0, 0.02, -7.0e-4
8
+ ETA_MAX, Q_BEP, SIGMA = 0.82, 150.0, 95.0
9
+ RHO_G = 1000 * 9.81
10
+
11
+
12
+ def _H(Q, f=50.0):
13
+ r = f / 50.0
14
+ Q0 = Q / r
15
+ return (A0 + A1 * Q0 + A2 * Q0 * Q0) * r * r
16
+
17
+
18
+ def _eta(Q, f=50.0):
19
+ r = f / 50.0
20
+ Q0 = Q / r
21
+ return ETA_MAX * np.exp(-((Q0 - Q_BEP) / SIGMA) ** 2) * (0.92 + 0.08 * r)
22
+
23
+
24
+ def _P(Q, f=50.0):
25
+ H = _H(Q, f); e = _eta(Q, f)
26
+ return RHO_G * (Q / 3600.0) * H / (e * 1000.0)
27
+
28
+
29
+ def test_fit_head_poly_recovers_coeffs():
30
+ Q = np.linspace(20, 210, 25)
31
+ H = A0 + A1 * Q + A2 * Q * Q
32
+ r = fit_head_poly(Q, H)
33
+ assert abs(r["a0"] - A0) < 0.5 and abs(r["a2"] - A2) < 1e-4
34
+ assert r["r2"] > 0.999
35
+
36
+
37
+ def test_fit_eta_gaussian_recovers_params():
38
+ Q = np.linspace(40, 210, 25)
39
+ eta = ETA_MAX * np.exp(-((Q - Q_BEP) / SIGMA) ** 2)
40
+ r = fit_eta_gaussian(Q, eta)
41
+ assert abs(r["eta_max"] - ETA_MAX) < 0.02
42
+ assert abs(r["q_bep"] - Q_BEP) < 5
43
+ assert r["r2"] > 0.99
44
+
45
+
46
+ def test_identify_from_mixed_frequency_history():
47
+ # 构造不同频率下的历史运行点(含小噪声),只给 Q/H/P/freq
48
+ rng = np.random.default_rng(0)
49
+ records = []
50
+ for f in (50, 45, 40, 35):
51
+ for Q in np.linspace(30 * f / 50, 200 * f / 50, 8):
52
+ H = _H(Q, f) * (1 + rng.normal(0, 0.01))
53
+ P = _P(Q, f) * (1 + rng.normal(0, 0.01))
54
+ records.append({"Q": float(Q), "H": float(H), "P": float(P), "freq": f})
55
+ ident = identify_pump(records, freq_nominal=50.0, pump_id=1)
56
+ # 归一到额定后应还原 50Hz 真值
57
+ assert abs(ident["poly"]["a0"] - A0) < 2.0
58
+ assert ident["head_fit"]["r2"] > 0.98
59
+ assert ident["eta_gauss"] is not None
60
+ assert abs(ident["eta_gauss"]["q_bep"] - Q_BEP) < 12
61
+ assert abs(ident["eta_gauss"]["eta_max"] - ETA_MAX) < 0.05
62
+
63
+
64
+ def test_eta_from_power_roundtrip():
65
+ Q, H, f = 150.0, _H(150.0), 50.0
66
+ P = _P(Q, f)
67
+ eta = float(eta_from_power(Q, H, P))
68
+ assert abs(eta - _eta(Q, f)) < 1e-6
69
+
70
+
71
+ def test_fit_from_points_and_apply(tmp_path, monkeypatch):
72
+ # 数字化的铭牌点:海斯特 Q=850,H=14.5 附近
73
+ hq = [[0, 18.5], [300, 17.8], [600, 16.2], [850, 14.5], [1050, 11.0]]
74
+ eta = [[300, 40], [600, 68], [850, 78], [1050, 60]] # 百分数
75
+ from app.models.curve_fit import fit_from_points
76
+ fit = fit_from_points(hq, eta)
77
+ assert fit["ok"] and fit["head_r2"] > 0.98
78
+ assert 700 < fit["eta_gauss"]["q_bep"] < 950
79
+ assert 0.7 < fit["eta_gauss"]["eta_max"] < 0.85
80
+
81
+ # 应用到运行中的 Plant(隔离 overrides 到临时文件)
82
+ monkeypatch.setenv("BIDITECH_CURVE_OVERRIDES", str(tmp_path / "ov.json"))
83
+ from app.plant import Plant
84
+ plant = Plant()
85
+ before = plant.pumps[1].bep_flow(50.0)
86
+ plant.apply_curve(1, {"poly": fit["poly"], "eta_gauss": fit["eta_gauss"], "name": "1号(上传)"})
87
+ after = plant.pumps[1].bep_flow(50.0)
88
+ assert abs(after - fit["eta_gauss"]["q_bep"]) < 30
89
+ assert plant.pump_meta[1]["curve_source"] == "uploaded"
90
+ # 持久化 + 重载生效
91
+ plant2 = Plant()
92
+ assert abs(plant2.pumps[1].bep_flow(50.0) - after) < 1.0
backend/tests/test_demo_runtime.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.demo_runtime import build_snapshot
2
+
3
+
4
+ def test_build_snapshot_preserves_missing_pressure_and_unknown_frequency():
5
+ pumps = [
6
+ {"id": 1, "status": 1, "freq": 35.0, "power": 20.0},
7
+ {"id": 2, "status": 1, "freq": None, "power": 30.0},
8
+ {"id": 3, "status": 0, "freq": 0.0, "power": 0.0},
9
+ ]
10
+ snapshot = build_snapshot(
11
+ {
12
+ "totalFlow": 1000.0,
13
+ "totalPower": 50.0,
14
+ "level": 6.2,
15
+ "pressure": None,
16
+ "replayTimestamp": "2026-01-01T00:00:00+08:00",
17
+ "replayIndex": 0,
18
+ "replayCount": 10,
19
+ },
20
+ pumps,
21
+ )
22
+
23
+ assert snapshot["source"] == "historical_opc_replay"
24
+ assert snapshot["pressure"] is None
25
+ assert snapshot["pressureQuality"] == "missing"
26
+ assert snapshot["pumps"][0]["head"] is None
27
+ assert snapshot["pumps"][0]["headSource"] == "missing_pressure"
28
+ assert snapshot["pumps"][1]["freq"] is None
29
+ assert snapshot["pumps"][0]["flow"] == 400.0
30
+ assert snapshot["pumps"][1]["flow"] == 600.0
31
+ assert snapshot["pumps"][1]["flowSource"] == "estimated_power_share"
backend/tests/test_forecaster.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.models.forecaster import FlowForecaster
2
+
3
+
4
+ def test_material_balance_inflow():
5
+ fc = FlowForecaster(wet_well_area=20.0)
6
+ # 液位不变 → 入流≈出流
7
+ fc.update(0.0, 3.0, 300.0)
8
+ q_in = fc.update(1.0, 3.0, 300.0)
9
+ assert abs(q_in - 300.0) < 1.0
10
+ # 液位上升 → 入流 > 出流
11
+ q_in2 = fc.update(2.0, 3.01, 300.0)
12
+ assert q_in2 > 300.0
13
+
14
+
15
+ def test_linear_trend_prediction():
16
+ fc = FlowForecaster(wet_well_area=20.0, window=100)
17
+ # 构造液位平稳、出流线性上升的场景
18
+ level = 3.0
19
+ for t in range(60):
20
+ fc.update(float(t), level, 200.0 + t * 2.0)
21
+ pred = fc.predict(horizon_s=10.0)
22
+ assert pred is not None
23
+ # 上升趋势应外推出高于当前均值的值
24
+ assert pred > fc.current_avg()
25
+
26
+
27
+ def test_falls_back_to_mean_when_insufficient():
28
+ fc = FlowForecaster()
29
+ assert fc.predict() is None or fc.predict() == 0.0
30
+ fc.update(0.0, 3.0, 250.0)
31
+ fc.update(1.0, 3.0, 250.0)
32
+ assert abs(fc.predict() - fc.current_avg()) < 1e-6
backend/tests/test_integration_config.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import pytest
4
+ from fastapi.testclient import TestClient
5
+ from pydantic import ValidationError
6
+
7
+ from app.integration_config import (
8
+ IntegrationConfig,
9
+ IntegrationConfigStore,
10
+ IntegrationConfigUpdate,
11
+ OpcConnectionUpdate,
12
+ default_config,
13
+ get_config_store,
14
+ )
15
+ from app.main import app
16
+
17
+
18
+ def make_store(tmp_path):
19
+ return IntegrationConfigStore(
20
+ tmp_path / "integration_config.json",
21
+ tmp_path / "opcua_secret.json",
22
+ )
23
+
24
+
25
+ def test_default_config_has_complete_station_tag_roster():
26
+ config = default_config()
27
+ assert config.source_mode == "simulation"
28
+ assert len(config.tags) == 41
29
+ assert any(tag.key == "level" and tag.required for tag in config.tags)
30
+ assert any(tag.key == "pump5.freq" for tag in config.tags)
31
+ assert any(tag.key == "pump5.cmd" and tag.writable for tag in config.tags)
32
+
33
+
34
+ def test_store_persists_config_and_keeps_password_out_of_public_json(tmp_path):
35
+ store = make_store(tmp_path)
36
+ current = store.load()
37
+ connection = OpcConnectionUpdate(
38
+ **current.connection.model_dump(exclude={"password_configured"}),
39
+ password="secret-value",
40
+ )
41
+ update = IntegrationConfigUpdate(
42
+ source_mode="opcua",
43
+ connection=connection,
44
+ tags=current.tags,
45
+ )
46
+
47
+ saved = store.save(update)
48
+ assert saved.revision == 2
49
+ assert saved.source_mode == "opcua"
50
+ assert saved.connection.password_configured is True
51
+ assert store.get_password() == "secret-value"
52
+
53
+ public_payload = json.loads(store.config_path.read_text(encoding="utf-8"))
54
+ assert "password" not in public_payload["connection"]
55
+ assert "secret-value" not in store.config_path.read_text(encoding="utf-8")
56
+ assert "secret-value" in store.secret_path.read_text(encoding="utf-8")
57
+
58
+
59
+ def test_duplicate_enabled_node_ids_are_rejected():
60
+ config = default_config()
61
+ config.tags[1].node_id = config.tags[0].node_id
62
+ with pytest.raises(ValidationError):
63
+ IntegrationConfig.model_validate(config.model_dump())
64
+
65
+
66
+ def test_config_api_roundtrip(tmp_path):
67
+ store = make_store(tmp_path)
68
+ app.dependency_overrides[get_config_store] = lambda: store
69
+ try:
70
+ client = TestClient(app)
71
+ response = client.get("/api/integration/config")
72
+ assert response.status_code == 200
73
+ payload = response.json()
74
+ assert payload["source_mode"] == "simulation"
75
+
76
+ payload["source_mode"] = "opcua"
77
+ payload["connection"].pop("password_configured", None)
78
+ response = client.put("/api/integration/config", json=payload)
79
+ assert response.status_code == 200
80
+ assert response.json()["source_mode"] == "opcua"
81
+ assert response.json()["revision"] == 2
82
+ finally:
83
+ app.dependency_overrides.clear()
backend/tests/test_integration_runtime.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi.testclient import TestClient
2
+
3
+ from app.integration_config import (
4
+ IntegrationConfigStore,
5
+ IntegrationConfigUpdate,
6
+ OpcConnectionUpdate,
7
+ get_config_store,
8
+ )
9
+ from app.main import app
10
+
11
+
12
+ def _password_store(tmp_path):
13
+ store = IntegrationConfigStore(tmp_path / "config.json", tmp_path / "secret.json")
14
+ current = store.load()
15
+ store.save(
16
+ IntegrationConfigUpdate(
17
+ source_mode="opcua",
18
+ connection=OpcConnectionUpdate(
19
+ **current.connection.model_dump(exclude={"password_configured"}),
20
+ password="internal-secret",
21
+ ),
22
+ tags=current.tags,
23
+ )
24
+ )
25
+ return store
26
+
27
+
28
+ def test_runtime_requires_internal_token_when_password_exists(tmp_path, monkeypatch):
29
+ store = _password_store(tmp_path)
30
+ monkeypatch.delenv("INTEGRATION_INTERNAL_TOKEN", raising=False)
31
+ app.dependency_overrides[get_config_store] = lambda: store
32
+ try:
33
+ response = TestClient(app).get("/api/integration/runtime")
34
+ assert response.status_code == 503
35
+ assert "internal-secret" not in response.text
36
+ finally:
37
+ app.dependency_overrides.clear()
38
+
39
+
40
+ def test_runtime_returns_password_only_with_matching_token(tmp_path, monkeypatch):
41
+ store = _password_store(tmp_path)
42
+ monkeypatch.setenv("INTEGRATION_INTERNAL_TOKEN", "node-red-token")
43
+ app.dependency_overrides[get_config_store] = lambda: store
44
+ try:
45
+ client = TestClient(app)
46
+ assert client.get("/api/integration/runtime").status_code == 401
47
+ response = client.get(
48
+ "/api/integration/runtime",
49
+ headers={"X-Integration-Token": "node-red-token"},
50
+ )
51
+ assert response.status_code == 200
52
+ assert response.json()["connection"]["password"] == "internal-secret"
53
+ finally:
54
+ app.dependency_overrides.clear()
backend/tests/test_mpc.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.plant import Plant
2
+
3
+ # 海斯特站规模:单泵铭牌 Q≈850 m³/h @50Hz,5 台(三用二备)
4
+
5
+
6
+ def test_optimize_meets_target_and_saves_energy():
7
+ plant = Plant()
8
+ Q_target = 700.0
9
+ res = plant.optimizer.optimize(Q_target=Q_target)
10
+ assert res["success"]
11
+ # 变频泵可 trim 到接近目标(软约束)
12
+ assert abs(res["wp"]["Q_total"] - Q_target) < 150
13
+ # 相对全泵 50Hz 基线应节能
14
+ base = plant.baseline_all_on_50hz(Q_target)
15
+ assert res["spec_energy"] <= base.spec_energy + 1e-6
16
+
17
+
18
+ def test_freqs_within_bounds():
19
+ plant = Plant()
20
+ res = plant.optimizer.optimize(Q_target=1200.0)
21
+ for f in res["freqs"].values():
22
+ assert 20.0 - 1e-6 <= f <= 50.0 + 1e-6
23
+
24
+
25
+ def test_start_stop_penalty_prefers_continuity():
26
+ plant = Plant()
27
+ # 当前 1、2 号在运,需求恰好 2 泵满足,应保持不乱切
28
+ res = plant.optimizer.optimize(
29
+ Q_target=1350.0, current_active=[1, 2],
30
+ current_freqs={1: 50.0, 2: 50.0},
31
+ )
32
+ assert res["success"]
33
+ # 真实厂家曲线下1号泵较小;当前1+2无法达到1350,允许切换为可行组合。
34
+ assert abs(res["wp"]["Q_total"] - 1350.0) <= max(50.0, 1350.0 * 0.03)
35
+ assert res["wp"]["feasible"]
36
+
37
+
38
+ def test_rotation_prefers_least_run_hours():
39
+ plant = Plant()
40
+ # 低需求单泵场景:变频泵(1/2/5)中累计运行 h 最少的 5# 应被优先
41
+ res = plant.optimizer.optimize(
42
+ Q_target=700.0,
43
+ run_hours={1: 9000.0, 2: 9000.0, 3: 9000.0, 4: 9000.0, 5: 100.0},
44
+ )
45
+ assert res["success"]
46
+ if len(res["active"]) == 1:
47
+ assert res["active"][0] == 5
48
+
49
+
50
+ def test_higher_demand_more_pumps():
51
+ plant = Plant()
52
+ low = plant.optimizer.optimize(Q_target=700.0)
53
+ high = plant.optimizer.optimize(Q_target=1700.0)
54
+ assert high["success"]
55
+ assert len(high["active"]) >= len(low["active"])
56
+ assert len(high["active"]) >= 3 # 大需求需多台
57
+
58
+
59
+ def test_infeasible_target_is_not_recommended():
60
+ plant = Plant()
61
+ res = plant.optimizer.optimize(Q_target=10000.0, level=5.5)
62
+ assert not res["success"]
63
+ assert res["status"] == "infeasible_target"
backend/tests/test_opcua_replay_server.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import pytest
4
+
5
+ from app.opcua_replay_server import load_replay_csv
6
+
7
+
8
+ HEADER = (
9
+ "timestamp,totalFlow,totalPower,level,pressure,"
10
+ "pump1.status,pump1.freq,pump1.current,pump1.power,pump1.runHours,"
11
+ "pump2.status,pump2.freq,pump2.current,pump2.power,pump2.runHours,"
12
+ "pump3.status,pump3.freq,pump3.current,pump3.power,pump3.runHours,"
13
+ "pump4.status,pump4.freq,pump4.current,pump4.power,pump4.runHours,"
14
+ "pump5.status,pump5.freq,pump5.current,pump5.power,pump5.runHours\n"
15
+ )
16
+
17
+
18
+ def test_load_replay_preserves_missing_measurements(tmp_path: Path):
19
+ source = tmp_path / "replay.csv"
20
+ source.write_text(
21
+ HEADER
22
+ + "2026-03-01T00:00:00+08:00,1687.1,63.7,,,"
23
+ + "1,33.7,24.9,14.2,0.5,1,,40.1,22.8,0.5,"
24
+ + "0,0,0,0,0,1,50,46.8,26.7,0.5,0,0,0,0,0\n",
25
+ encoding="utf-8",
26
+ )
27
+
28
+ rows = load_replay_csv(source)
29
+
30
+ assert len(rows) == 1
31
+ assert rows[0].total_flow == pytest.approx(1687.1)
32
+ assert rows[0].level is None
33
+ assert rows[0].pressure is None
34
+ assert rows[0].pumps[1]["freq"] == pytest.approx(33.7)
35
+ assert rows[0].pumps[2]["freq"] is None
36
+ assert rows[0].pumps[4]["status"] == 1
37
+
38
+
39
+ def test_load_replay_rejects_non_increasing_timestamps(tmp_path: Path):
40
+ source = tmp_path / "replay.csv"
41
+ row = (
42
+ "2026-03-01T00:00:00+08:00,1000,60,,,"
43
+ "0,0,0,0,0,0,,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n"
44
+ )
45
+ source.write_text(HEADER + row + row, encoding="utf-8")
46
+
47
+ with pytest.raises(ValueError, match="strictly increasing"):
48
+ load_replay_csv(source)
backend/tests/test_parallel.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.models.parallel import PumpGroupParallelModel
2
+ from app.models.pump_curve import PumpCurveModel
3
+
4
+ Q = [0, 40, 80, 120, 150, 180, 210]
5
+ H = [58.0, 56.5, 53.0, 47.0, 42.5, 36.0, 27.0]
6
+ E = [0.0, 0.42, 0.66, 0.79, 0.82, 0.78, 0.66]
7
+
8
+
9
+ def make_group(n=3):
10
+ pumps = {i: PumpCurveModel(i, Q, H, E) for i in range(1, n + 1)}
11
+ return PumpGroupParallelModel(pumps, static_head=12.0, pipe_resistance=2.6e-4)
12
+
13
+
14
+ def test_operating_point_on_system_curve():
15
+ g = make_group()
16
+ op = g.solve({1: 45.0})
17
+ # 工作点必须落在系统曲线上:H ≈ Hst + S·Q²
18
+ assert abs(op.H - g.system_head(op.Q_total)) < 0.5
19
+ assert op.Q_total > 0 and op.P_total > 0
20
+ assert op.spec_energy > 0
21
+
22
+
23
+ def test_more_pumps_more_flow():
24
+ g = make_group()
25
+ q1 = g.solve({1: 50.0}).Q_total
26
+ q2 = g.solve({1: 50.0, 2: 50.0}).Q_total
27
+ # 并联加泵总流量增加,但因管阻非线性并非线性翻倍
28
+ assert q2 > q1
29
+ assert q2 < 2 * q1
30
+
31
+
32
+ def test_empty_active():
33
+ g = make_group()
34
+ op = g.solve({})
35
+ assert op.Q_total == 0.0 and op.P_total == 0.0
36
+
37
+
38
+ def test_lower_freq_lower_flow():
39
+ g = make_group()
40
+ assert g.solve({1: 30.0}).Q_total < g.solve({1: 50.0}).Q_total
41
+
42
+
43
+ def test_level_dependent_static_head():
44
+ # 无出口压力表:扬程由液位估计。液位越低静扬程越大、扬程越高、流量越小。
45
+ pumps = {i: PumpCurveModel(i, Q, H, E) for i in (1,)}
46
+ g = PumpGroupParallelModel(pumps, static_head=12.0, pipe_resistance=2.0e-3, level_ref=5.5)
47
+ assert abs(g.static_at(5.5) - 12.0) < 1e-9 # 参考液位处 = static_head
48
+ assert g.static_at(3.5) > g.static_at(7.5) # 低液位静扬程更大
49
+ op_low = g.solve({1: 50.0}, level=3.5) # 低液位
50
+ op_high = g.solve({1: 50.0}, level=7.5) # 高液位
51
+ assert op_low.H > op_high.H # 低液位扬程更高
52
+ assert op_low.Q_total < op_high.Q_total # 低液位流量更小
53
+ assert g.static_at(None) == 12.0 # 不给液位则用固定静扬程
54
+
55
+
56
+ def test_infeasible_when_pump_cannot_reach_static_head():
57
+ pump = PumpCurveModel(1, [0, 100], [5, 3], [0.5, 0.7])
58
+ group = PumpGroupParallelModel({1: pump}, static_head=12.0, pipe_resistance=1e-5)
59
+ op = group.solve({1: 50.0})
60
+ assert not op.feasible
61
+ assert op.reason == "pump_head_below_static_head"
62
+ assert op.Q_total == 0.0
backend/tests/test_safety.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ from app.plant import Plant
4
+ from app.safety import ControlState, SafetyGate
5
+
6
+
7
+ def make_gate():
8
+ return SafetyGate(freq_min=20, freq_max=50, freq_step_per_cycle=5.0,
9
+ pressure_max_mpa=0.55, min_pumps=1, watchdog_timeout_s=5.0,
10
+ start_freq=20.0, level_ll_stop=3.0, level_hh=6.5,
11
+ variable_speed={1: True, 2: True, 3: False, 4: False, 5: True})
12
+
13
+
14
+ def rt(pumps, pressure=0.30, level=4.75):
15
+ return {"pressure": pressure, "level": level, "pumps": pumps}
16
+
17
+
18
+ def test_write_enable_required():
19
+ g = make_gate()
20
+ st = ControlState(mode="auto", write_enable=False)
21
+ r = g.gate({"active": [1], "freqs": {1: 45}},
22
+ rt([{"id": 1, "freq": 40, "status": 1}]), st)
23
+ assert r["approved"] is False
24
+ assert any("写使能" in x for x in r["reasons"])
25
+
26
+
27
+ def test_freq_ramp_rate_limit():
28
+ g = make_gate()
29
+ st = ControlState(mode="auto", write_enable=True)
30
+ st.beat()
31
+ # 目标 50,当前 40,单周期最多 +5 → 输出 45
32
+ r = g.gate({"active": [1], "freqs": {1: 50}},
33
+ rt([{"id": 1, "freq": 40, "status": 1}]), st)
34
+ assert r["approved"] is True
35
+ assert abs(r["command"]["freqs"][1] - 45.0) < 1e-6
36
+ assert any("限速" in x for x in r["interventions"])
37
+
38
+
39
+ def test_freq_clip_bounds():
40
+ g = make_gate()
41
+ st = ControlState(mode="auto", write_enable=True)
42
+ st.beat()
43
+ r = g.gate({"active": [1], "freqs": {1: 999}},
44
+ rt([{"id": 1, "freq": 48, "status": 1}]), st)
45
+ assert r["command"]["freqs"][1] <= 50.0
46
+
47
+
48
+ def test_high_pressure_blocks_ramp_up():
49
+ g = make_gate()
50
+ st = ControlState(mode="auto", write_enable=True)
51
+ st.beat()
52
+ # 高压:禁止升频,维持当前
53
+ r = g.gate({"active": [1], "freqs": {1: 50}},
54
+ rt([{"id": 1, "freq": 42, "status": 1}], pressure=0.60), st)
55
+ assert r["command"]["freqs"][1] <= 42.0 + 1e-6
56
+ assert any("高压" in x for x in r["interventions"])
57
+
58
+
59
+ def test_high_pressure_blocks_start():
60
+ g = make_gate()
61
+ st = ControlState(mode="auto", write_enable=True)
62
+ st.beat()
63
+ # 高压下不允许启新泵 → 只保留已运行的 1 号
64
+ r = g.gate({"active": [1, 2], "freqs": {1: 42, 2: 40}},
65
+ rt([{"id": 1, "freq": 42, "status": 1}], pressure=0.60), st)
66
+ assert 2 not in r["command"]["freqs"]
67
+
68
+
69
+ def test_watchdog_timeout_reverts():
70
+ g = make_gate()
71
+ st = ControlState(mode="auto", write_enable=True)
72
+ st.last_heartbeat = time.time() - 10.0 # 心跳过期
73
+ r = g.gate({"active": [1], "freqs": {1: 45}},
74
+ rt([{"id": 1, "freq": 40, "status": 1}]), st)
75
+ assert r["approved"] is False
76
+ assert r["watchdog_ok"] is False
77
+
78
+
79
+ def test_critical_alarm_skips():
80
+ g = make_gate()
81
+ st = ControlState(mode="auto", write_enable=True, critical_alarm=True)
82
+ st.beat()
83
+ r = g.gate({"active": [1], "freqs": {1: 45}},
84
+ rt([{"id": 1, "freq": 40, "status": 1}]), st)
85
+ assert r["approved"] is False
86
+ assert any("CRITICAL" in x for x in r["reasons"])
87
+
88
+
89
+ def test_fixed_speed_pump_locked_50():
90
+ g = make_gate()
91
+ st = ControlState(mode="auto", write_enable=True)
92
+ st.beat()
93
+ # 4 号是工频泵,即便建议给 30Hz 也锁 50(新启从 start_freq? 工频无软启频率→50)
94
+ r = g.gate({"active": [4], "freqs": {4: 30}},
95
+ rt([{"id": 4, "freq": 50, "status": 1}]), st)
96
+ assert abs(r["command"]["freqs"][4] - 50.0) < 1e-6
97
+
98
+
99
+ def test_low_level_protection_stops_pumps():
100
+ g = make_gate()
101
+ st = ControlState(mode="auto", write_enable=True)
102
+ st.beat()
103
+ # 液位 2.5 < LL 3.0 → 低水位保护停泵
104
+ r = g.gate({"active": [1, 2], "freqs": {1: 44, 2: 44}},
105
+ rt([{"id": 1, "freq": 44, "status": 1}, {"id": 2, "freq": 44, "status": 1}], level=2.5), st)
106
+ assert r["approved"] is False
107
+ assert r["command"]["active"] == []
108
+ assert any("低水位" in x for x in r["reasons"])
109
+
110
+
111
+ def test_high_level_notes_but_allows():
112
+ g = make_gate()
113
+ st = ControlState(mode="auto", write_enable=True)
114
+ st.beat()
115
+ # 液位 6.8 > HH 6.5 → 提示增泵但不阻断
116
+ r = g.gate({"active": [1], "freqs": {1: 44}},
117
+ rt([{"id": 1, "freq": 44, "status": 1}], level=6.8), st)
118
+ assert r["approved"] is True
119
+ assert any("高水位" in x for x in r["interventions"])
120
+
121
+
122
+ def test_power_from_current():
123
+ from app.models.curve_fit import power_from_current
124
+ # 三相 394V、58A、PF 0.85 → √3·394·58·0.85/1000 ≈ 33.6 kW
125
+ p = float(power_from_current(394.0, 58.0, 0.85))
126
+ assert abs(p - 33.65) < 0.5
127
+
128
+
129
+ def test_config_has_five_pumps_jiaozhou_composition():
130
+ plant = Plant()
131
+ assert len(plant.pumps) == 5
132
+ meta = plant.pump_meta
133
+ # 胶州二期:变频 1/2/5,工频 3/4
134
+ assert meta[1]["variable_speed"] is True
135
+ assert meta[2]["variable_speed"] is True
136
+ assert meta[3]["variable_speed"] is False
137
+ assert meta[4]["variable_speed"] is False
138
+ assert meta[5]["variable_speed"] is True
backend/tests/test_suggestion_api.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi.testclient import TestClient
2
+
3
+ from app.main import app
4
+
5
+
6
+ client = TestClient(app)
7
+
8
+
9
+ def test_factory_curves_and_hydraulic_codes_are_exposed():
10
+ cfg = client.get("/api/config").json()
11
+ pumps = {p["id"]: p for p in cfg["pumps"]}
12
+ assert pumps[1]["hydraulic_code"] == "NP 3202.180 LT 610"
13
+ assert pumps[2]["hydraulic_code"] == "F10K-SS1 + FN050X4"
14
+ assert all(pumps[i]["curve_source"].startswith("manufacturer") for i in range(1, 6))
15
+
16
+ curve = client.get("/api/pump/2/curve", params={"freq": 50, "n": 10}).json()
17
+ assert curve["success"]
18
+ assert abs(curve["bep_flow"] - 774.72) < 20
19
+ assert curve["meta"]["curve_revision"] == "C-2175 Rev.2"
20
+
21
+
22
+ def test_unknown_frequency_is_omitted_and_negative_saving_is_blocked():
23
+ response = client.post("/api/optimization/suggestion", json={
24
+ "Q_target": 800.0,
25
+ "current_active": [1, 2],
26
+ "current_freqs": {"1": 48.0},
27
+ "current_total_power": 10.0,
28
+ "level": 5.5,
29
+ })
30
+ result = response.json()
31
+ assert result["success"]
32
+ assert result["baseline"]["kind"] == "current_measured"
33
+ assert result["sec_saving_pct"] <= 0
34
+ assert result["status"] == "no_improvement"
35
+ assert result["executable"] is False
backend/tools/fit_curve.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """离线曲线辨识:从历史运行 CSV 拟合各泵 a0/a1/a2 + 高斯效率,打印 pumps.yaml 片段。
3
+
4
+ CSV 列(表头,缺 eta 则用 P 反算;缺 P 则必须给 eta):
5
+ pump,Q,H,P,freq[,eta]
6
+ 1,132,45.1,43.2,44
7
+ ...
8
+
9
+ 用法:
10
+ python tools/fit_curve.py history.csv # 全部泵
11
+ python tools/fit_curve.py history.csv --freq-nominal 50
12
+ """
13
+ import argparse
14
+ import csv
15
+ import sys
16
+ from collections import defaultdict
17
+ from pathlib import Path
18
+
19
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
20
+
21
+ from app.models.curve_fit import identify_pump, to_yaml_block # noqa: E402
22
+
23
+
24
+ def load(csv_path):
25
+ groups = defaultdict(list)
26
+ with open(csv_path, newline="", encoding="utf-8") as f:
27
+ for row in csv.DictReader(f):
28
+ pid = int(float(row["pump"]))
29
+ rec = {"Q": float(row["Q"]), "H": float(row["H"]),
30
+ "freq": float(row.get("freq", 50))}
31
+ if row.get("P") not in (None, ""):
32
+ rec["P"] = float(row["P"])
33
+ if row.get("eta") not in (None, ""):
34
+ rec["eta"] = float(row["eta"])
35
+ groups[pid].append(rec)
36
+ return groups
37
+
38
+
39
+ def main():
40
+ ap = argparse.ArgumentParser()
41
+ ap.add_argument("csv")
42
+ ap.add_argument("--freq-nominal", type=float, default=50.0)
43
+ args = ap.parse_args()
44
+
45
+ groups = load(args.csv)
46
+ print(f"# 从 {args.csv} 辨识 {len(groups)} 台泵曲线\npumps:")
47
+ for pid in sorted(groups):
48
+ try:
49
+ ident = identify_pump(groups[pid], freq_nominal=args.freq_nominal, pump_id=pid)
50
+ except Exception as e: # noqa: BLE001
51
+ print(f" # 泵 {pid} 辨识失败:{e}")
52
+ continue
53
+ hf = ident["head_fit"]; ef = ident.get("eta_fit", {})
54
+ print(to_yaml_block(ident))
55
+ print(f" # 扬程拟合 R²={hf['r2']} (n={hf['n']});效率拟合 R²={ef.get('r2', 'NA')}")
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
backend/tools/opcua_test_client.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """OPC UA 测试客户端:连仿真服务器(或现场标准 PC 的 OPC UA 服务器),
3
+ 读取泵站点位、写一个频率设定,验证读写通。
4
+
5
+ python tools/opcua_test_client.py # 默认连本机仿真服务器
6
+ python tools/opcua_test_client.py --url opc.tcp://PC_IP:4840/...
7
+ """
8
+ import argparse
9
+ import asyncio
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
14
+
15
+ from asyncua import Client # noqa: E402
16
+
17
+ NS_URI = "http://biditech.pump/opcua/"
18
+
19
+
20
+ async def main(url):
21
+ async with Client(url=url) as client:
22
+ idx = await client.get_namespace_index(NS_URI)
23
+ print(f"connected {url} ns={idx}")
24
+ # 读站级点
25
+ for name in ("Level", "TotalFlow", "TotalPower", "Pressure"):
26
+ node = client.get_node(f"ns={idx};s=PumpStation1.{name}")
27
+ print(f" PumpStation1.{name} = {await node.read_value()}")
28
+ # 读各泵
29
+ for pid in range(1, 6):
30
+ try:
31
+ f = await client.get_node(f"ns={idx};s=PumpStation1.Pump{pid}.Freq").read_value()
32
+ p = await client.get_node(f"ns={idx};s=PumpStation1.Pump{pid}.Power").read_value()
33
+ s = await client.get_node(f"ns={idx};s=PumpStation1.Pump{pid}.Status").read_value()
34
+ print(f" Pump{pid}: Freq={f} Power={p} Status={s}")
35
+ except Exception as e: # noqa: BLE001
36
+ print(f" Pump{pid}: {e}")
37
+ # 写使能 + 频率设定回写测试
38
+ from asyncua import ua
39
+ we = client.get_node(f"ns={idx};s=PumpStation1.WriteEnable")
40
+ await we.write_value(ua.DataValue(ua.Variant(True, ua.VariantType.Boolean)))
41
+ fs = client.get_node(f"ns={idx};s=PumpStation1.Pump1.FreqSet")
42
+ await fs.write_value(ua.DataValue(ua.Variant(46.5, ua.VariantType.Double)))
43
+ print(f" wrote WriteEnable=True, Pump1.FreqSet=46.5 → readback {await fs.read_value()}")
44
+
45
+
46
+ if __name__ == "__main__":
47
+ ap = argparse.ArgumentParser()
48
+ ap.add_argument("--url", default="opc.tcp://127.0.0.1:4840/biditech/server/")
49
+ a = ap.parse_args()
50
+ asyncio.run(main(a.url))
demo-data/README.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Historical OPC replay demo data
2
+
3
+ `pump_history_demo.csv` is a deployment-safe derivative of the March–May pump
4
+ station history supplied for this project.
5
+
6
+ - Hydraulic and electrical values, pump start/stop states, missing frequency
7
+ values, and missing pressure values are preserved.
8
+ - Timestamps are shifted to an anonymous demonstration timeline.
9
+ - Site identifiers and source file paths are not included.
10
+ - The CSV is replayed through an internal OPC UA server; the dashboard does not
11
+ read the CSV directly.
12
+ - Per-pump outlet flow is not measured. The demo snapshot allocates total flow
13
+ by measured active-power share solely for display and marks it as estimated.
14
+
15
+ The manufacturer PDF/XLSX files are not runtime inputs. Their engineering data
16
+ has been extracted into `backend/config/pumps.yaml`, including model, curve
17
+ revision, Q-H points, efficiency points, BEP, speed, and verified flow range.
demo-data/pump_history_demo.csv ADDED
The diff for this file is too large to render. See raw diff
 
deploy/DEPLOY_HF.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 部署到 Hugging Face Spaces(给本地 Claude Code 的任务材料)
2
+
3
+ 把下面「任务」整段复制到你**本地电脑**的 Claude Code 里运行(本地能访问 GitHub 与 huggingface.co)。
4
+ 只需要你准备一个 **HF 写入令牌**:https://huggingface.co/settings/tokens → New token → 选 **Write** → 复制。
5
+
6
+ ---
7
+
8
+ ## 任务(复制这一整段给本地 Claude Code)
9
+
10
+ > 帮我把这个项目部署到我的 Hugging Face Spaces(Docker 类型),项目已经准备好一键部署。
11
+ >
12
+ > 1. 克隆仓库并切到部署分支:
13
+ > ```
14
+ > git clone https://github.com/dauphinking/pumpsavingenergy.git
15
+ > cd pumpsavingenergy
16
+ > git checkout claude/html-opc-data-display-urr9cy
17
+ > ```
18
+ > 2. 我的 HF 用户名是 `dauphinking`,Space 名用 `pump`,我的 HF 写入令牌是:`<在这里粘贴你的 hf_xxx 令牌>`
19
+ > 3. 用仓库里的脚本一键部署:
20
+ > ```
21
+ > HF_USER=dauphinking HF_TOKEN=<我的令牌> SPACE=pump bash deploy/deploy_hf.sh
22
+ > ```
23
+ > (脚本会自动建 Docker Space、加 HF 远程、推送到 main。)
24
+ > 4. 推送后 HF 会自动构建(约 3-6 分钟)。帮我确认构建成功,然后把访问地址给我:
25
+ > `https://huggingface.co/spaces/dauphinking/pump`
26
+ > 5. 如果构建报错,读 Space 的 Logs,把错误定位并修好再推一次。
27
+
28
+ ---
29
+
30
+ ## 手动版(不想用 Claude,自己敲 3 条命令)
31
+
32
+ ```bash
33
+ git clone https://github.com/dauphinking/pumpsavingenergy.git
34
+ cd pumpsavingenergy && git checkout claude/html-opc-data-display-urr9cy
35
+
36
+ # 建 Space(SDK 选 Docker):https://huggingface.co/new-space 名字填 pump
37
+ # 令牌:https://huggingface.co/settings/tokens (Write)
38
+
39
+ git remote add hf https://dauphinking:<HF_TOKEN>@huggingface.co/spaces/dauphinking/pump
40
+ git push -f hf HEAD:main
41
+ # 打开 https://huggingface.co/spaces/dauphinking/pump
42
+ ```
43
+
44
+ ## 部署后是什么
45
+
46
+ 打开 Space 地址即「运行总览大屏」,同一个页面里全部功能可用(同源单容器):
47
+ 运行大屏 / 泵曲线 / 历史趋势 / 报警 / 能耗分析 / AI 优化建议(手动+自动闭环)/ 泵曲线上传。
48
+ 实时数据用内置仿真驱动(免费版够演示全部功能);曲线上传数据在免费版重启后不保留。
49
+
50
+ ## 说明与排错
51
+
52
+ - **必须选 Docker SDK**(不是 Gradio/Streamlit)。仓库根有 `Dockerfile` 与 README 头部
53
+ (`sdk: docker`, `app_port: 8000`),HF 会据此构建、把 8000 端口对外。
54
+ - 首次构建慢(装 numpy/scipy),耐心等;日志在 Space 页右上 **Logs**。
55
+ - 令牌泄露风险:部署完可在 HF 令牌页把这个令牌删掉/轮换。
56
+ - 想换成真实数据(OPC UA):单容器版是仿真;真实链路用仓库的 `docker compose`(含 Node-RED)。
deploy/deploy_hf.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # 一键部署到 Hugging Face Spaces(Docker)。在能访问 huggingface.co 的机器上运行。
3
+ #
4
+ # 用法:
5
+ # HF_USER=dauphinking HF_TOKEN=hf_xxx SPACE=pump bash deploy/deploy_hf.sh
6
+ # 参数(环境变量):
7
+ # HF_USER HF 用户名/组织(必填)
8
+ # HF_TOKEN HF 写入令牌 https://huggingface.co/settings/tokens (必填,选 Write)
9
+ # SPACE Space 名称(可选,默认 pump)
10
+ set -euo pipefail
11
+
12
+ : "${HF_USER:?请设置 HF_USER(HF 用户名)}"
13
+ : "${HF_TOKEN:?请设置 HF_TOKEN(HF 写入令牌,Write 权限)}"
14
+ SPACE="${SPACE:-pump}"
15
+ REF="${1:-HEAD}"
16
+
17
+ echo "[1/3] 建 Docker Space(已存在则忽略):$HF_USER/$SPACE"
18
+ python3 -m pip install -q huggingface_hub >/dev/null 2>&1 || true
19
+ python3 - "$HF_USER/$SPACE" "$HF_TOKEN" <<'PY' || true
20
+ import sys
21
+ from huggingface_hub import create_repo
22
+ repo, token = sys.argv[1], sys.argv[2]
23
+ create_repo(repo, repo_type="space", space_sdk="docker", token=token, exist_ok=True)
24
+ print(" ok:", repo)
25
+ PY
26
+
27
+ echo "[2/3] 添加 HF 远程并推送到 main"
28
+ git remote remove hf 2>/dev/null || true
29
+ git remote add hf "https://${HF_USER}:${HF_TOKEN}@huggingface.co/spaces/${HF_USER}/${SPACE}"
30
+ git push -f hf "${REF}:main"
31
+
32
+ echo "[3/3] 已推送。HF 正在构建(拉镜像+装依赖,约 3-6 分钟)。构建完成后打开:"
33
+ echo " https://huggingface.co/spaces/${HF_USER}/${SPACE}"
34
+ echo " 日志/状态在该页面右上角 'Logs' 里看。"
deploy/start_pc_opc.cmd ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ setlocal
3
+ cd /d "%~dp0.."
4
+
5
+ if not exist "private-data\pump_history_20260301_20260601.csv" (
6
+ echo Missing replay data: private-data\pump_history_20260301_20260601.csv
7
+ echo Copy the normalized replay CSV into private-data and try again.
8
+ pause
9
+ exit /b 1
10
+ )
11
+
12
+ docker compose -f docker-compose.pc-opc.yml up -d --build
13
+ if errorlevel 1 (
14
+ echo Failed to start the OPC UA replay server. Check Docker Desktop and retry.
15
+ pause
16
+ exit /b 1
17
+ )
18
+
19
+ echo.
20
+ echo OPC UA replay server is running.
21
+ echo Endpoint: opc.tcp://127.0.0.1:4840/biditech/server/
22
+ echo LAN endpoint: opc.tcp://THIS-PC-IP:4840/biditech/server/
23
+ pause
docker-compose.pc-opc.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ pc-opcua-replay:
3
+ build: ./backend
4
+ image: biditech-pump-opcua-replay
5
+ container_name: pump-pc-opcua-replay
6
+ command:
7
+ - python
8
+ - -m
9
+ - app.opcua_replay_server
10
+ - --csv
11
+ - /replay/pump_history_20260301_20260601.csv
12
+ - --host
13
+ - 0.0.0.0
14
+ - --port
15
+ - "4840"
16
+ - --interval
17
+ - ${OPC_REPLAY_INTERVAL:-1.0}
18
+ ports:
19
+ - "4840:4840"
20
+ volumes:
21
+ - ./private-data:/replay:ro
22
+ restart: unless-stopped
docker-compose.yml ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 提升泵站 AI 节能优化 — 一键部署(干净 Ubuntu:装 docker + compose 后 `docker compose up -d`)
2
+ #
3
+ # 前端展示大屏 http://<服务器IP>:8080
4
+ # 优化后端 API http://<服务器IP>:8077 (/api/config, /api/optimization/suggestion, /api/pump/{id}/curve/...)
5
+ # Node-RED http://<服务器IP>:1880 (OPC 采集编排;默认跑仿真分支,可切 OPC)
6
+ # OPC UA 仿真 opc.tcp://<服务器IP>:4840/biditech/server/ (UaExpert/现场联调用)
7
+ #
8
+ # 前端浏览器按所在主机名访问 8077/1880,故在服务器上打开 :8080 即整套连通。
9
+
10
+ services:
11
+ backend:
12
+ build: ./backend
13
+ image: biditech-pump-backend
14
+ container_name: pump-backend
15
+ command: uvicorn app.main:app --host 0.0.0.0 --port 8077
16
+ ports:
17
+ - "8077:8077"
18
+ volumes:
19
+ - pump-data:/data # 曲线上传持久化(curve_overrides.json)
20
+ environment:
21
+ BIDITECH_INTEGRATION_CONFIG: /data/integration_config.json
22
+ BIDITECH_OPCUA_SECRET: /data/opcua_secret.json
23
+ INTEGRATION_INTERNAL_TOKEN: ${INTEGRATION_INTERNAL_TOKEN:-}
24
+ NODERED_URL: http://nodered:1880
25
+ extra_hosts:
26
+ - "host.docker.internal:host-gateway"
27
+ healthcheck:
28
+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8077/api/health', timeout=2)"]
29
+ interval: 10s
30
+ timeout: 3s
31
+ retries: 5
32
+ start_period: 15s
33
+ restart: unless-stopped
34
+
35
+ opcua-sim:
36
+ build: ./backend # 与 backend 同镜像(compose 去重构建)
37
+ image: biditech-pump-backend
38
+ container_name: pump-opcua-sim
39
+ command: python -m app.opcua_sim_server --host 0.0.0.0 --port 4840
40
+ depends_on:
41
+ - backend
42
+ ports:
43
+ - "4840:4840"
44
+ restart: unless-stopped
45
+
46
+ frontend:
47
+ build: ./frontend
48
+ image: biditech-pump-frontend
49
+ container_name: pump-frontend
50
+ depends_on:
51
+ - backend
52
+ - nodered
53
+ ports:
54
+ - "8080:80"
55
+ restart: unless-stopped
56
+
57
+ nodered:
58
+ build: ./node-red
59
+ image: biditech-pump-nodered
60
+ container_name: pump-nodered
61
+ depends_on:
62
+ - opcua-sim
63
+ ports:
64
+ - "1880:1880"
65
+ volumes:
66
+ - nodered-data:/data
67
+ - ./node-red/flows-configurable.json:/data/flows.json
68
+ environment:
69
+ INTEGRATION_INTERNAL_TOKEN: ${INTEGRATION_INTERNAL_TOKEN:-}
70
+ TZ: Asia/Shanghai
71
+ extra_hosts:
72
+ - "host.docker.internal:host-gateway"
73
+ restart: unless-stopped
74
+
75
+ volumes:
76
+ pump-data:
77
+ nodered-data:
docs/PC-OPCUA鍘嗗彶鍥炴斁.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PC OPC UA 历史数据回放
2
+
3
+ 本项目使用开源 `asyncua` 在 PC 上提供标准 OPC UA Server。服务器读取归一化 CSV,按时间顺序发布泵站历史数据,Node-RED 和边缘 AI 设备均作为 OPC UA Client 连接。
4
+
5
+ ## 当前数据集
6
+
7
+ - 时间范围:2026-03-01 00:00 至 2026-06-01 00:00
8
+ - 间隔:30 分钟
9
+ - 记录数:4,417
10
+ - 真实字段:总管瞬时流量、1-5 号泵有功功率、1 号泵运行频率
11
+ - 推导字段:启停状态由单泵有功功率大于 1 kW 判定;电流按 394 V、功率因数 0.85 估算;3-5 号泵运行时频率按历史工频条件设为 50 Hz
12
+ - 缺失字段:2 号泵频率、液位、总管压力。OPC UA 中以 `BadNoData` 质量发布,不用零值冒充真实测量
13
+
14
+ 现场数据文件位于 `private-data/`,该目录已加入 `.gitignore`,不会推送到公开 GitHub。
15
+
16
+ ## 直接运行
17
+
18
+ 在项目目录执行:
19
+
20
+ ```powershell
21
+ cd backend
22
+ ..\.venv\Scripts\python.exe -m app.opcua_replay_server --csv ..\private-data\pump_history_20260301_20260601.csv --host 0.0.0.0 --port 4840 --interval 1
23
+ ```
24
+
25
+ 也可从 `backend` 目录使用项目现有 Python 环境运行。`--interval 1` 表示每 1 秒播放一条历史记录,即每秒推进 30 分钟历史时间。
26
+
27
+ ## Docker Desktop 一键运行
28
+
29
+ 双击 `deploy/start_pc_opc.cmd`,或执行:
30
+
31
+ ```powershell
32
+ docker compose -f docker-compose.pc-opc.yml up -d --build
33
+ ```
34
+
35
+ 默认端点:
36
+
37
+ ```text
38
+ opc.tcp://<PC局域网IP>:4840/biditech/server/
39
+ ```
40
+
41
+ 边缘 AI 设备必须能够访问 PC 的 TCP 4840 端口。Windows 防火墙如出现授权提示,应只允许专用网络。
42
+
43
+ ## 主要 NodeId
44
+
45
+ ```text
46
+ ns=2;s=PumpStation1.TotalFlow
47
+ ns=2;s=PumpStation1.TotalPower
48
+ ns=2;s=PumpStation1.Level
49
+ ns=2;s=PumpStation1.Pressure
50
+ ns=2;s=PumpStation1.Pump1.Status
51
+ ns=2;s=PumpStation1.Pump1.Freq
52
+ ns=2;s=PumpStation1.Pump1.Current
53
+ ns=2;s=PumpStation1.Pump1.Power
54
+ ```
55
+
56
+ 泵号替换为 1-5 即可。附加回放状态点:
57
+
58
+ ```text
59
+ ns=2;s=PumpStation1.ReplayTimestamp
60
+ ns=2;s=PumpStation1.ReplayIndex
61
+ ns=2;s=PumpStation1.ReplayCount
62
+ ns=2;s=PumpStation1.DataSource
63
+ ```
64
+
65
+ ## 停止
66
+
67
+ ```powershell
68
+ docker compose -f docker-compose.pc-opc.yml down
69
+ ```