Spaces:
Sleeping
Sleeping
File size: 9,003 Bytes
86b96f3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | """云端转发:把边缘采到的实时快照(含算好的 SEC/节能)经 MQTT 发到云端 InfluxDB。
设计要点:
- 转发逻辑在后端(Python)做,可把 soft_sensor 算出的系统 SEC 一并上传,
Grafana 直接能看能效,而不只是原始点;
- **断点续传(store-and-forward)**:现场网络断时先本地缓存(有上限的队列),恢复后自动补传;
- MQTT 用户名/密码等机密单独存放,不随 GET 配置返回、不进日志;
- 对用户仍是"配置中心的一个 Tab",Node-RED/MQTT 细节全隐藏。
MQTT → InfluxDB 是常见上云链路(云端 Telegraf/桥接订阅 MQTT 写入 InfluxDB)。
"""
from __future__ import annotations
import asyncio
import json
import os
import time
from collections import deque
from pathlib import Path
from typing import Optional
from pydantic import BaseModel, Field, field_validator
def system_sec(total_flow_m3h: float, total_power_kw: float) -> float:
"""系统单位供水电耗 kWh/m³ = 总功率(kW) / 母管流量(m³/h)。两者实测 → 精确。"""
return total_power_kw / total_flow_m3h if total_flow_m3h and total_flow_m3h > 1e-6 else 0.0
class CloudForwardConfig(BaseModel):
enabled: bool = False
mqtt_host: str = Field(default="", max_length=200)
mqtt_port: int = Field(default=1883, ge=1, le=65535)
tls: bool = False # 8883 + TLS
username: str = Field(default="", max_length=120)
topic: str = Field(default="biditech/pump/{station}/telemetry", max_length=300)
client_id: str = Field(default="biditech-pump-edge", max_length=120)
qos: int = Field(default=0, ge=0, le=1)
publish_interval_s: float = Field(default=10.0, ge=1.0, le=600.0)
buffer_limit: int = Field(default=5000, ge=100, le=100000) # 断网缓存上限(条)
password_configured: bool = False # 只读标志,密码单独存
@field_validator("topic")
@classmethod
def _topic(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("MQTT 主题不能为空")
return v
class CloudForwardUpdate(CloudForwardConfig):
password: Optional[str] = Field(default=None, max_length=300, exclude=True)
def build_payload(snapshot: dict, station: str = "pump") -> dict:
"""把实时快照整形为上云 JSON,并附带算好的系统 SEC(能效硬指标)。"""
tf = _num(snapshot.get("totalFlow"))
tp = _num(snapshot.get("totalPower"))
pumps = snapshot.get("pumps") or []
payload = {
"station": station,
"ts": snapshot.get("ts") or int(time.time() * 1000),
"level": _num(snapshot.get("level")),
"totalFlow": tf,
"totalPower": tp,
"pressure": _num(snapshot.get("pressure")),
"system_sec": round(system_sec(tf, tp), 5) if (tf and tp) else None,
"n_running": sum(1 for p in pumps if int(p.get("status", 0)) == 1),
"pumps": [
{"id": p.get("id"), "status": p.get("status"), "freq": _num(p.get("freq")),
"power": _num(p.get("power")), "current": _num(p.get("current"))}
for p in pumps
],
}
return payload
def _num(x):
try:
return round(float(x), 3)
except (TypeError, ValueError):
return None
class CloudForwarder:
"""MQTT 转发器 + 断点续传缓存。paho-mqtt 惰性导入,无 broker 时仍可测缓存逻辑。"""
def __init__(self, config: CloudForwardConfig, password: str = "",
station: str = "pump"):
self.config = config
self.password = password
self.station = station
self.buffer: deque = deque(maxlen=config.buffer_limit)
self._client = None
self._connected = False
self.published = 0
self.dropped = 0
self.last_error: Optional[str] = None
self.last_publish_ts: Optional[float] = None
# ---- 缓存 ----
def enqueue(self, snapshot: dict) -> None:
if len(self.buffer) >= self.config.buffer_limit:
self.dropped += 1 # 满了丢最旧(deque 自动)
self.buffer.append(build_payload(snapshot, self.station))
def pending(self) -> int:
return len(self.buffer)
# ---- MQTT ----
def _ensure_client(self):
if self._client is not None:
return self._client
import paho.mqtt.client as mqtt # 惰性导入
c = mqtt.Client(client_id=self.config.client_id, clean_session=True)
if self.config.username:
c.username_pw_set(self.config.username, self.password or None)
if self.config.tls:
c.tls_set()
c.connect(self.config.mqtt_host, self.config.mqtt_port, keepalive=30)
c.loop_start()
self._client = c
self._connected = True
return c
def flush(self) -> int:
"""尝试把缓存里的所有消息发出去;失败保留在缓存(断点续传)。返回本次发出条数。"""
if not self.config.enabled or not self.config.mqtt_host:
return 0
sent = 0
try:
c = self._ensure_client()
topic = self.config.topic.format(station=self.station)
while self.buffer:
payload = self.buffer[0]
info = c.publish(topic, json.dumps(payload, ensure_ascii=False),
qos=self.config.qos)
if info.rc != 0:
raise RuntimeError(f"publish rc={info.rc}")
self.buffer.popleft()
sent += 1
self.published += sent
self.last_error = None
self.last_publish_ts = time.time()
except Exception as exc: # 断网/broker 不可达 → 保留缓存
self.last_error = f"{type(exc).__name__}: {exc}"
self._reset_client()
return sent
def _reset_client(self):
try:
if self._client:
self._client.loop_stop()
self._client.disconnect()
except Exception:
pass
self._client = None
self._connected = False
def status(self) -> dict:
return {
"enabled": self.config.enabled,
"connected": self._connected,
"pending": self.pending(),
"published": self.published,
"dropped": self.dropped,
"last_error": self.last_error,
"last_publish_ts": self.last_publish_ts,
}
async def run(self, get_snapshot):
"""周期性把最新快照入队并 flush。get_snapshot() 返回当前快照 dict 或 None。"""
while True:
try:
if self.config.enabled:
snap = get_snapshot()
if snap:
self.enqueue(snap)
self.flush()
except Exception as exc: # noqa: BLE001
self.last_error = f"loop: {exc}"
await asyncio.sleep(self.config.publish_interval_s)
# ---- 持久化(与 OPC 配置同模式:配置存 /data,密码单独存) ----
def _cfg_path() -> Path:
return Path(os.environ.get(
"BIDITECH_CLOUD_CONFIG",
str(Path(__file__).resolve().parent.parent / "config" / "cloud_forward.json")))
def _secret_path() -> Path:
return Path(os.environ.get(
"BIDITECH_CLOUD_SECRET",
str(Path(__file__).resolve().parent.parent / "config" / "cloud_secret.json")))
class CloudForwardStore:
def load(self) -> CloudForwardConfig:
p = _cfg_path()
if not p.exists():
return CloudForwardConfig()
try:
data = json.loads(p.read_text(encoding="utf-8"))
cfg = CloudForwardConfig(**data)
cfg.password_configured = bool(self.get_password())
return cfg
except Exception:
return CloudForwardConfig()
def save(self, update: CloudForwardUpdate) -> CloudForwardConfig:
cfg = CloudForwardConfig(**update.model_dump(exclude={"password"}))
if update.password is not None:
self._save_password(update.password)
cfg.password_configured = bool(self.get_password())
_cfg_path().parent.mkdir(parents=True, exist_ok=True)
_cfg_path().write_text(cfg.model_dump_json(indent=2), encoding="utf-8")
return cfg
def get_password(self) -> str:
sp = _secret_path()
if not sp.exists():
return ""
try:
return json.loads(sp.read_text(encoding="utf-8")).get("mqtt_password", "")
except Exception:
return ""
def _save_password(self, password: str) -> None:
sp = _secret_path()
sp.parent.mkdir(parents=True, exist_ok=True)
sp.write_text(json.dumps({"mqtt_password": password}), encoding="utf-8")
try:
os.chmod(sp, 0o600)
except OSError:
pass
|