File size: 6,461 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
"""Single-container historical OPC UA replay runtime.

Hugging Face exposes only the HTTP application port.  The OPC UA server still
runs inside the same container on localhost:4840, and this collector reads it
through the normal OPC UA protocol before publishing a dashboard snapshot.
"""
from __future__ import annotations

import asyncio
import contextlib
import os
import time
from datetime import datetime
from pathlib import Path
from typing import Any

from asyncua import Client
from asyncua.ua.uaerrors import BadNoData

from .opcua_replay_server import run as run_replay_server


def _value(data_value) -> Any:
    if not data_value.StatusCode.is_good():
        return None
    return data_value.Value.Value


async def _read(node) -> Any:
    try:
        return _value(await node.read_data_value())
    except BadNoData:
        return None


def build_snapshot(
    station: dict[str, Any],
    pumps: list[dict[str, Any]],
) -> dict[str, Any]:
    """Build the public snapshot without inventing unavailable measurements."""
    total_flow = float(station.get("totalFlow") or 0.0)
    total_power = float(station.get("totalPower") or 0.0)
    running = [pump for pump in pumps if int(pump.get("status") or 0) == 1]

    # Individual outlet flow is not measured.  Allocate only for display using
    # measured pump power shares and mark the provenance explicitly.
    weights = [max(float(pump.get("power") or 0.0), 0.0) for pump in running]
    if running and sum(weights) <= 0:
        weights = [1.0] * len(running)
    weight_total = sum(weights)
    for pump in pumps:
        pump["flow"] = 0.0
        pump["flowSource"] = "not_running"
        pump["head"] = None
        pump["headSource"] = "missing_pressure"
    for pump, weight in zip(running, weights):
        pump["flow"] = total_flow * weight / weight_total if weight_total else 0.0
        pump["flowSource"] = "estimated_power_share"

    pressure = station.get("pressure")
    historical_timestamp = station.get("replayTimestamp")
    return {
        "station": "胶州二期提升泵站(历史 OPC 回放)",
        "source": "historical_opc_replay",
        "sourceLabel": "三个月历史数据 · OPC UA 内部回放",
        "historicalTimestamp": historical_timestamp,
        "replayIndex": station.get("replayIndex"),
        "replayCount": station.get("replayCount"),
        "level": station.get("level"),
        "pressure": pressure,
        "pressureQuality": "measured" if pressure is not None else "missing",
        "totalFlow": total_flow,
        "totalPower": total_power,
        "sec": total_power / total_flow if total_flow > 0 else 0.0,
        "pumps": pumps,
        # Use wall-clock time for the rolling chart while retaining the original
        # historical timestamp above.
        "ts": int(time.time() * 1000),
    }


class HistoricalOpcDemoRuntime:
    def __init__(self) -> None:
        self.latest: dict[str, Any] | None = None
        self.error: str | None = None
        self.enabled = False
        self._tasks: list[asyncio.Task] = []

    async def start_from_env(self) -> None:
        source = os.environ.get("BIDITECH_DEMO_REPLAY_CSV", "").strip()
        if not source:
            return
        csv_path = Path(source)
        if not csv_path.is_file():
            self.error = f"Demo replay CSV not found: {csv_path}"
            return

        endpoint = os.environ.get(
            "BIDITECH_DEMO_OPCUA_ENDPOINT",
            "opc.tcp://127.0.0.1:4840/biditech/server/",
        )
        interval = float(os.environ.get("BIDITECH_DEMO_REPLAY_INTERVAL", "1.0"))
        server_endpoint = endpoint.replace("127.0.0.1", "0.0.0.0")
        self.enabled = True
        self._tasks = [
            asyncio.create_task(
                run_replay_server(server_endpoint, csv_path, interval=interval),
                name="historical-opc-replay-server",
            ),
            asyncio.create_task(
                self._collector(endpoint),
                name="historical-opc-replay-collector",
            ),
        ]

    async def stop(self) -> None:
        for task in self._tasks:
            task.cancel()
        for task in self._tasks:
            with contextlib.suppress(asyncio.CancelledError):
                await task
        self._tasks = []

    async def _collector(self, endpoint: str) -> None:
        await asyncio.sleep(0.5)
        while True:
            try:
                async with Client(url=endpoint, timeout=5) as client:
                    await self._collect_connected(client)
            except asyncio.CancelledError:
                raise
            except Exception as exc:  # reconnect loop is intentional
                self.error = f"{type(exc).__name__}: {exc}"
                await asyncio.sleep(1.0)

    async def _collect_connected(self, client: Client) -> None:
        station_ids = {
            "level": "ns=2;s=PumpStation1.Level",
            "totalFlow": "ns=2;s=PumpStation1.TotalFlow",
            "totalPower": "ns=2;s=PumpStation1.TotalPower",
            "pressure": "ns=2;s=PumpStation1.Pressure",
            "replayTimestamp": "ns=2;s=PumpStation1.ReplayTimestamp",
            "replayIndex": "ns=2;s=PumpStation1.ReplayIndex",
            "replayCount": "ns=2;s=PumpStation1.ReplayCount",
        }
        station_nodes = {key: client.get_node(node_id) for key, node_id in station_ids.items()}
        pump_nodes = {
            pump_id: {
                field: client.get_node(f"ns=2;s=PumpStation1.Pump{pump_id}.{node_name}")
                for field, node_name in {
                    "status": "Status",
                    "freq": "Freq",
                    "current": "Current",
                    "power": "Power",
                    "runHours": "RunHours",
                }.items()
            }
            for pump_id in range(1, 6)
        }

        while True:
            station_values = {
                key: await _read(node)
                for key, node in station_nodes.items()
            }
            pumps = []
            for pump_id, nodes in pump_nodes.items():
                pump = {"id": pump_id}
                for field, node in nodes.items():
                    pump[field] = await _read(node)
                pumps.append(pump)
            self.latest = build_snapshot(station_values, pumps)
            self.error = None
            await asyncio.sleep(0.8)


demo_runtime = HistoricalOpcDemoRuntime()