pump / backend /app /integration_config.py
Codex
Deploy efficiency estimate fix cf55248
aec7019
Raw History Blame Contribute Delete
10.8 kB
"""现场数据接入配置:持久化、校验、密码隔离与默认点表。
配置文件放在 /data 卷中,容器重启后保留。OPC 密码单独存放且不通过
GET 接口返回,避免配置页面或日志意外泄露。
"""
from __future__ import annotations
import json
import os
import re
import shutil
import tempfile
from datetime import datetime, timezone
from functools import lru_cache
from pathlib import Path
from typing import Literal, Optional
from pydantic import BaseModel, Field, field_validator, model_validator
DataType = Literal["Boolean", "Int16", "Int32", "UInt16", "UInt32", "Float", "Double", "String"]
SourceMode = Literal["simulation", "opcua"]
class TagMapping(BaseModel):
key: str = Field(min_length=1, max_length=80)
label: str = Field(min_length=1, max_length=120)
node_id: str = Field(default="", max_length=300)
data_type: DataType = "Double"
unit: str = Field(default="", max_length=30)
scale: float = 1.0
offset: float = 0.0
enabled: bool = True
required: bool = False
writable: bool = False
@field_validator("key")
@classmethod
def validate_key(cls, value: str) -> str:
value = value.strip()
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_.-]*", value):
raise ValueError("点位键只能包含字母、数字、点、横线和下划线,并以字母开头")
return value
@field_validator("node_id")
@classmethod
def normalize_node_id(cls, value: str) -> str:
return value.strip()
class OpcConnectionConfig(BaseModel):
endpoint: str = "opc.tcp://opcua-sim:4840/biditech/server/"
security_policy: Literal[
"None", "Basic256Sha256", "Aes128_Sha256_RsaOaep", "Aes256_Sha256_RsaPss"
] = "None"
security_mode: Literal["None", "Sign", "SignAndEncrypt"] = "None"
username: str = Field(default="", max_length=120)
certificate_path: str = Field(default="", max_length=300)
private_key_path: str = Field(default="", max_length=300)
server_certificate_path: str = Field(default="", max_length=300)
sampling_interval_ms: int = Field(default=1000, ge=200, le=60000)
timeout_s: float = Field(default=5.0, ge=1.0, le=30.0)
reconnect_interval_s: float = Field(default=5.0, ge=1.0, le=300.0)
password_configured: bool = False
@field_validator("endpoint")
@classmethod
def validate_endpoint(cls, value: str) -> str:
value = value.strip()
if not value.startswith("opc.tcp://"):
raise ValueError("OPC UA 地址必须以 opc.tcp:// 开头")
return value
@model_validator(mode="after")
def validate_security(self):
if self.security_policy == "None" and self.security_mode != "None":
raise ValueError("安全策略为 None 时,安全模式也必须为 None")
if self.security_policy != "None":
if self.security_mode == "None":
raise ValueError("启用安全策略后必须选择 Sign 或 SignAndEncrypt")
if not self.certificate_path or not self.private_key_path:
raise ValueError("启用安全策略后必须填写客户端证书和私钥路径")
return self
class OpcConnectionUpdate(OpcConnectionConfig):
password: Optional[str] = Field(default=None, max_length=300, exclude=True)
class IntegrationConfig(BaseModel):
revision: int = 1
updated_at: str
source_mode: SourceMode = "simulation"
connection: OpcConnectionConfig = Field(default_factory=OpcConnectionConfig)
tags: list[TagMapping]
@model_validator(mode="after")
def validate_tags(self):
keys = [tag.key for tag in self.tags]
if len(keys) != len(set(keys)):
raise ValueError("点位键不能重复")
enabled_ids = [tag.node_id for tag in self.tags if tag.enabled and tag.node_id]
if len(enabled_ids) != len(set(enabled_ids)):
raise ValueError("已启用点位的 NodeId 不能重复")
missing = [tag.label for tag in self.tags if tag.required and tag.enabled and not tag.node_id]
if missing:
raise ValueError(f"必需点位缺少 NodeId:{', '.join(missing)}")
return self
class IntegrationConfigUpdate(BaseModel):
source_mode: SourceMode
connection: OpcConnectionUpdate
tags: list[TagMapping]
def _tag(
key: str,
label: str,
node_id: str,
data_type: DataType = "Double",
unit: str = "",
*,
required: bool = False,
writable: bool = False,
) -> TagMapping:
return TagMapping(
key=key,
label=label,
node_id=node_id,
data_type=data_type,
unit=unit,
required=required,
writable=writable,
)
def default_tags() -> list[TagMapping]:
base = "ns=2;s=PumpStation1."
tags = [
_tag("level", "集水井液位", base + "Level", unit="m", required=True),
_tag("totalFlow", "总管瞬时流量", base + "TotalFlow", unit="m³/h", required=True),
_tag("totalPower", "泵组总有功功率", base + "TotalPower", unit="kW"),
_tag("pressure", "总管压力", base + "Pressure", unit="MPa"),
_tag("writeEnable", "控制写使能", base + "WriteEnable", "Boolean", writable=True),
_tag("heartbeat", "控制心跳", base + "Heartbeat", "UInt32", writable=True),
]
for pid in range(1, 6):
prefix = base + f"Pump{pid}."
tags.extend(
[
_tag(f"pump{pid}.status", f"{pid}号泵运行状态", prefix + "Status", "Int32", required=True),
_tag(f"pump{pid}.freq", f"{pid}号泵运行频率", prefix + "Freq", unit="Hz"),
_tag(f"pump{pid}.current", f"{pid}号泵电流", prefix + "Current", unit="A"),
_tag(f"pump{pid}.power", f"{pid}号泵有功功率", prefix + "Power", unit="kW"),
_tag(f"pump{pid}.runHours", f"{pid}号泵累计运行时间", prefix + "RunHours", unit="h"),
_tag(
f"pump{pid}.freqSet",
f"{pid}号泵频率设定",
prefix + "FreqSet",
unit="Hz",
writable=True,
),
_tag(f"pump{pid}.cmd", f"{pid}号泵启停指令", prefix + "Cmd", "Int32", writable=True),
]
)
return tags
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def default_config() -> IntegrationConfig:
config = IntegrationConfig(updated_at=utc_now(), tags=default_tags())
default_endpoint = os.environ.get("BIDITECH_DEFAULT_OPCUA_ENDPOINT", "").strip()
if default_endpoint:
config.connection.endpoint = default_endpoint
config.source_mode = "opcua"
return config
class IntegrationConfigStore:
def __init__(self, config_path: Path, secret_path: Path):
self.config_path = Path(config_path)
self.secret_path = Path(secret_path)
def _password(self) -> str:
env_password = os.environ.get("OPCUA_PASSWORD")
if env_password is not None:
return env_password
if not self.secret_path.exists():
return ""
try:
payload = json.loads(self.secret_path.read_text(encoding="utf-8"))
return str(payload.get("password") or "")
except (OSError, ValueError, TypeError):
return ""
def get_password(self) -> str:
return self._password()
def load(self) -> IntegrationConfig:
if not self.config_path.exists():
config = default_config()
else:
config = IntegrationConfig.model_validate_json(
self.config_path.read_text(encoding="utf-8")
)
config.connection.password_configured = bool(self._password())
return config
def _atomic_json_write(self, path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_name, path)
finally:
if os.path.exists(temp_name):
os.unlink(temp_name)
def save(self, update: IntegrationConfigUpdate) -> IntegrationConfig:
current = self.load()
password = update.connection.password
if password is not None:
self._atomic_json_write(self.secret_path, {"password": password})
try:
os.chmod(self.secret_path, 0o600)
except OSError:
pass
connection_payload = update.connection.model_dump(exclude={"password"})
connection_payload["password_configured"] = bool(
password if password is not None else self._password()
)
saved = IntegrationConfig(
revision=current.revision + 1,
updated_at=utc_now(),
source_mode=update.source_mode,
connection=OpcConnectionConfig(**connection_payload),
tags=update.tags,
)
if self.config_path.exists():
backup = self.config_path.with_suffix(self.config_path.suffix + ".bak")
shutil.copy2(self.config_path, backup)
self._atomic_json_write(self.config_path, saved.model_dump())
return self.load()
def reset(self) -> IntegrationConfig:
current = self.load()
reset_config = default_config()
reset_config.revision = current.revision + 1
if self.config_path.exists():
backup = self.config_path.with_suffix(self.config_path.suffix + ".bak")
shutil.copy2(self.config_path, backup)
self._atomic_json_write(self.config_path, reset_config.model_dump())
return self.load()
@lru_cache
def get_config_store() -> IntegrationConfigStore:
# Containers persist configuration in /data. Direct Windows runs use a
# project-local writable directory instead of the protected \data root.
default_data_dir = (
Path(__file__).resolve().parents[1] / "data"
if os.name == "nt"
else Path("/data")
)
config_path = Path(
os.environ.get(
"BIDITECH_INTEGRATION_CONFIG",
str(default_data_dir / "integration_config.json"),
)
)
secret_path = Path(
os.environ.get(
"BIDITECH_OPCUA_SECRET",
str(default_data_dir / "opcua_secret.json"),
)
)
return IntegrationConfigStore(config_path, secret_path)