Spaces:
Sleeping
Sleeping
File size: 10,774 Bytes
aec7019 | 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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | """现场数据接入配置与 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,
}
|