pump / backend /app /integration_api.py
Codex
Deploy efficiency estimate fix cf55248
aec7019
Raw History Blame Contribute Delete
10.8 kB
"""现场数据接入配置与 OPC UA 调试 API。"""
from __future__ import annotations
import asyncio
import os
import secrets
import time
from datetime import date, datetime
from typing import Any, Optional
import httpx
from fastapi import APIRouter, Depends, Header, HTTPException
from pydantic import BaseModel, Field
from .integration_config import (
IntegrationConfig,
IntegrationConfigStore,
IntegrationConfigUpdate,
OpcConnectionConfig,
OpcConnectionUpdate,
TagMapping,
get_config_store,
)
router = APIRouter(prefix="/api/integration", tags=["现场数据接入"])
class OpcTestRequest(BaseModel):
connection: Optional[OpcConnectionUpdate] = None
class OpcBrowseRequest(BaseModel):
node_id: str = "i=85" # Objects
connection: Optional[OpcConnectionUpdate] = None
limit: int = Field(default=200, ge=1, le=1000)
class OpcPreviewRequest(BaseModel):
keys: list[str] = []
connection: Optional[OpcConnectionUpdate] = None
def _connection_and_password(
store: IntegrationConfigStore, override: Optional[OpcConnectionUpdate]
) -> tuple[OpcConnectionConfig, str]:
if override is None:
current = store.load().connection
return current, store.get_password()
payload = override.model_dump(exclude={"password"})
password = override.password if override.password is not None else store.get_password()
payload["password_configured"] = bool(password)
return OpcConnectionConfig(**payload), password
async def _create_client(connection: OpcConnectionConfig, password: str):
try:
from asyncua import Client
except ImportError as exc: # pragma: no cover - packaging failure
raise RuntimeError("后端未安装 asyncua,无法测试 OPC UA") from exc
client = Client(url=connection.endpoint, timeout=connection.timeout_s)
if connection.username:
client.set_user(connection.username)
client.set_password(password)
if connection.security_policy != "None":
security = ",".join(
[
connection.security_policy,
connection.security_mode,
connection.certificate_path,
connection.private_key_path,
]
)
if connection.server_certificate_path:
security += "," + connection.server_certificate_path
await client.set_security_string(security)
return client
def _json_value(value: Any) -> Any:
if isinstance(value, (datetime, date)):
return value.isoformat()
if isinstance(value, bytes):
return value.hex()
if isinstance(value, (str, int, float, bool)) or value is None:
return value
if isinstance(value, (list, tuple)):
return [_json_value(item) for item in value]
if isinstance(value, dict):
return {str(key): _json_value(item) for key, item in value.items()}
return str(value)
@router.get("/config", response_model=IntegrationConfig)
def read_integration_config(store: IntegrationConfigStore = Depends(get_config_store)):
return store.load()
@router.put("/config", response_model=IntegrationConfig)
def update_integration_config(
payload: IntegrationConfigUpdate,
store: IntegrationConfigStore = Depends(get_config_store),
):
try:
return store.save(payload)
except (OSError, ValueError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.post("/config/reset", response_model=IntegrationConfig)
def reset_integration_config(store: IntegrationConfigStore = Depends(get_config_store)):
return store.reset()
@router.post("/opc/test")
async def test_opc_connection(
payload: OpcTestRequest,
store: IntegrationConfigStore = Depends(get_config_store),
):
connection, password = _connection_and_password(store, payload.connection)
started = time.perf_counter()
client = await _create_client(connection, password)
try:
await asyncio.wait_for(client.connect(), timeout=connection.timeout_s + 1)
namespaces = await client.get_namespace_array()
server_name = await client.nodes.server.read_display_name()
return {
"success": True,
"endpoint": connection.endpoint,
"latency_ms": round((time.perf_counter() - started) * 1000, 1),
"server": str(server_name.Text),
"namespaces": namespaces,
"message": "OPC UA 连接成功",
}
except Exception as exc:
return {
"success": False,
"endpoint": connection.endpoint,
"latency_ms": round((time.perf_counter() - started) * 1000, 1),
"error": f"{type(exc).__name__}: {exc}",
"message": "连接失败,请检查地址、安全策略、账号和网络",
}
finally:
try:
await client.disconnect()
except Exception:
pass
@router.post("/opc/browse")
async def browse_opc_nodes(
payload: OpcBrowseRequest,
store: IntegrationConfigStore = Depends(get_config_store),
):
connection, password = _connection_and_password(store, payload.connection)
client = await _create_client(connection, password)
try:
await asyncio.wait_for(client.connect(), timeout=connection.timeout_s + 1)
parent = client.get_node(payload.node_id)
children = await parent.get_children()
result = []
for child in children[: payload.limit]:
browse_name, display_name, node_class = await asyncio.gather(
child.read_browse_name(),
child.read_display_name(),
child.read_node_class(),
)
result.append(
{
"node_id": child.nodeid.to_string(),
"browse_name": browse_name.Name,
"display_name": display_name.Text,
"node_class": getattr(node_class, "name", str(node_class)),
}
)
return {"success": True, "parent": payload.node_id, "nodes": result}
except Exception as exc:
return {"success": False, "error": f"{type(exc).__name__}: {exc}", "nodes": []}
finally:
try:
await client.disconnect()
except Exception:
pass
@router.post("/opc/read-preview")
async def read_opc_preview(
payload: OpcPreviewRequest,
store: IntegrationConfigStore = Depends(get_config_store),
):
config = store.load()
connection, password = _connection_and_password(store, payload.connection)
selected = set(payload.keys)
tags: list[TagMapping] = [
tag
for tag in config.tags
if tag.enabled and tag.node_id and (not selected or tag.key in selected)
]
client = await _create_client(connection, password)
started = time.perf_counter()
try:
await asyncio.wait_for(client.connect(), timeout=connection.timeout_s + 1)
values = []
for tag in tags:
try:
data_value = await client.get_node(tag.node_id).read_data_value()
raw = data_value.Value.Value
scaled = raw
if isinstance(raw, (int, float)) and not isinstance(raw, bool):
scaled = raw * tag.scale + tag.offset
values.append(
{
"key": tag.key,
"label": tag.label,
"node_id": tag.node_id,
"value": _json_value(scaled),
"raw_value": _json_value(raw),
"unit": tag.unit,
"quality": str(data_value.StatusCode),
"source_timestamp": _json_value(data_value.SourceTimestamp),
"success": True,
}
)
except Exception as exc:
values.append(
{
"key": tag.key,
"label": tag.label,
"node_id": tag.node_id,
"success": False,
"error": f"{type(exc).__name__}: {exc}",
}
)
return {
"success": True,
"endpoint": connection.endpoint,
"elapsed_ms": round((time.perf_counter() - started) * 1000, 1),
"values": values,
}
except Exception as exc:
return {"success": False, "error": f"{type(exc).__name__}: {exc}", "values": []}
finally:
try:
await client.disconnect()
except Exception:
pass
@router.get("/runtime")
def node_red_runtime_config(
x_integration_token: str = Header(default=""),
store: IntegrationConfigStore = Depends(get_config_store),
):
"""供 Node-RED 容器读取运行配置。
未设置内部令牌时仅允许无密码 OPC;设置密码后必须同时设置
INTEGRATION_INTERNAL_TOKEN,并由 Node-RED 通过同名环境变量携带。
"""
expected = os.environ.get("INTEGRATION_INTERNAL_TOKEN", "")
password = store.get_password()
if expected:
if not secrets.compare_digest(x_integration_token, expected):
raise HTTPException(status_code=401, detail="内部配置令牌无效")
elif password:
raise HTTPException(
status_code=503,
detail="已配置 OPC 密码,但尚未设置 INTEGRATION_INTERNAL_TOKEN",
)
payload = store.load().model_dump()
payload["connection"]["password"] = password if expected else ""
return payload
@router.get("/status")
async def integration_status(store: IntegrationConfigStore = Depends(get_config_store)):
config = store.load()
node_red_url = os.environ.get("NODERED_URL", "http://nodered:1880").rstrip("/")
node_red = {"reachable": False, "url": node_red_url}
try:
async with httpx.AsyncClient(timeout=2.0) as client:
response = await client.get(node_red_url + "/api/realtime")
node_red.update(
{
"reachable": response.status_code == 200,
"status_code": response.status_code,
"has_snapshot": bool(response.json()) if response.status_code == 200 else False,
}
)
except Exception as exc:
node_red["error"] = f"{type(exc).__name__}: {exc}"
return {
"source_mode": config.source_mode,
"revision": config.revision,
"configured_tags": sum(1 for tag in config.tags if tag.enabled and tag.node_id),
"required_tags_ready": all(
bool(tag.node_id) for tag in config.tags if tag.enabled and tag.required
),
"node_red": node_red,
}