"""线程安全的状态仓 + RTU 保持寄存器镜像。 一把 Lock 同时保护“机器数据模型”和“寄存器镜像”: - 采集线程更新数据并重建镜像时持锁; - RTU 从站读取时持锁并复制快照。 因此 S331 在任意时刻读到的 8 个寄存器一定是同一次计算的结果, 不会出现“一半旧值、一半新值”的脏读。 """ from __future__ import annotations import threading from datetime import datetime from typing import Any, Optional, Sequence from .config import CompressorCfg from .model import MachineState, RATIO_KEYS from .registers import encode_float32 # 每台机器固定占用 8 个保持寄存器(4 个 Float) REGISTERS_PER_MACHINE = 8 class StateStore: def __init__( self, compressors: Sequence[CompressorCfg], float_order: str = "ABCD", clock=datetime.now, ) -> None: if not compressors: raise ValueError("至少需要一台空压机") self._lock = threading.Lock() self._clock = clock self._float_order = float_order self._machines: dict[int, MachineState] = { cfg.id: MachineState(cfg.id, cfg.name, cfg.register_index) for cfg in compressors } self._size = (max(m.register_index for m in self._machines.values()) + 1) * REGISTERS_PER_MACHINE self._image = [0] * self._size with self._lock: for machine in self._machines.values(): self._write_machine_locked(machine) # ------------------------------------------------------------ 基本属性 @property def register_count(self) -> int: return self._size def machine_ids(self) -> list[int]: return sorted(self._machines) # ------------------------------------------------------------ 更新 def update(self, updates: dict[int, dict[str, Any]], now: Optional[datetime] = None) -> None: """批量更新。 updates 形如 {machine_id: {"instant_flow": Decimal, "total_flow": ...}}, 允许的字段:instant_flow / total_flow / instant_power / total_energy。 """ if not updates: return stamp = now or self._clock() with self._lock: for machine_id, values in updates.items(): machine = self._machines.get(machine_id) if machine is None: continue machine.apply(stamp, **values) self._write_machine_locked(machine) # ------------------------------------------------------------ RTU 读取 def read_registers(self, address: int, count: int = 1) -> Optional[list[int]]: """返回寄存器快照;越界返回 None(从站应答非法地址)。""" if address < 0 or count <= 0 or address + count > self._size: return None with self._lock: return self._image[address : address + count] # ------------------------------------------------------------ 持久化 def persist_payloads(self) -> dict[int, dict[str, Any]]: with self._lock: return {mid: machine.to_payload() for mid, machine in self._machines.items()} def restore(self, payloads: dict[int, dict[str, Any]], now: Optional[datetime] = None) -> int: """从 SQLite 数据恢复,返回成功恢复的机器数量。""" stamp = now or self._clock() restored = 0 with self._lock: for machine_id, payload in payloads.items(): machine = self._machines.get(machine_id) if machine is None or not isinstance(payload, dict): continue try: machine.restore(payload, stamp) except (KeyError, TypeError, ValueError): continue self._write_machine_locked(machine) restored += 1 return restored # ------------------------------------------------------------ 状态日志 def snapshot(self, now: Optional[datetime] = None) -> list[dict[str, Any]]: """给状态日志用的轻量快照。""" stamp = now or self._clock() with self._lock: rows = [] for machine in sorted(self._machines.values(), key=lambda m: m.register_index): rows.append( { "id": machine.machine_id, "name": machine.name, "base_address": machine.register_index * REGISTERS_PER_MACHINE, "ratios": {key: float(machine.ratios[key]) for key in RATIO_KEYS}, "instant_flow": _f(machine.instant_flow), "total_flow": _f(machine.total_flow), "instant_power": _f(machine.instant_power), "total_energy": _f(machine.total_energy), "age_s": machine.age_s(stamp), } ) return rows # ------------------------------------------------------------ 内部 def _write_machine_locked(self, machine: MachineState) -> None: base = machine.register_index * REGISTERS_PER_MACHINE for offset, key in enumerate(RATIO_KEYS): self._image[base + offset * 2 : base + offset * 2 + 2] = encode_float32( float(machine.ratios[key]), self._float_order ) def _f(value: Any) -> Optional[float]: return None if value is None else float(value)