Spaces:
Sleeping
Sleeping
Download backend/app/cloud_forward.py from dauphinking/pump: direct link, hf CLI and curl.
- Browser
- Download file 9 kB
-
https://huggingface.co/spaces/dauphinking/pump/resolve/main/backend/app/cloud_forward.py
- Command line
-
hf download hf://spaces/dauphinking/pump/backend/app/cloud_forward.py
-
curl -L -o cloud_forward.py https://huggingface.co/spaces/dauphinking/pump/resolve/main/backend/app/cloud_forward.py
9 kB
| """云端转发:把边缘采到的实时快照(含算好的 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 # 只读标志,密码单独存 | |
| 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 | |