"""配置加载与校验。 所有设备点位均在 YAML 中声明,现场点表变化时只改配置、不改代码。 """ from __future__ import annotations from dataclasses import dataclass, field from decimal import Decimal, InvalidOperation from pathlib import Path from typing import Any import yaml # 支持的数据类型 -> 寄存器宽度 TYPE_WIDTH: dict[str, int] = { "int16": 1, "uint16": 1, "int32": 2, "uint32": 2, "float32": 2, "int64": 4, "uint64": 4, "float64": 4, } WORD_ORDERS = ("ABCD", "CDAB", "big", "little") class ConfigError(ValueError): """配置文件不合法。""" def _decimal(value: Any, default: str = "1") -> Decimal: if value is None: return Decimal(default) try: return Decimal(str(value)) except InvalidOperation as exc: # pragma: no cover - 仅在配置写错时触发 raise ConfigError(f"非法数值: {value!r}") from exc @dataclass(frozen=True) class Point: """一个测量点位。 address 为 0 基协议地址(40001 -> 0)。 scale/offset 用于工程值换算:工程值 = 原始值 * scale + offset。 """ address: int type: str = "float32" word_order: str = "ABCD" scale: Decimal = field(default_factory=lambda: Decimal(1)) offset: Decimal = field(default_factory=lambda: Decimal(0)) @property def width(self) -> int: return TYPE_WIDTH[self.type] @property def order(self) -> str: """统一为 ABCD / CDAB 两种字序。""" return "CDAB" if self.word_order.lower() in ("cdab", "little") else "ABCD" @dataclass(frozen=True) class DeviceCfg: name: str host: str port: int = 502 slave_id: int = 1 timeout_s: float = 1.0 poll_interval_s: float = 2.0 address_offset: int = 0 max_registers_per_read: int = 60 max_gap: int = 4 reconnect_min_s: float = 1.0 reconnect_max_s: float = 30.0 @dataclass(frozen=True) class CompressorCfg: id: int name: str s331: str meter: str register_index: int flow_instant: Point flow_total: Point power_instant: Point energy_total: Point @dataclass(frozen=True) class SlaveCfg: name: str port: str slave_id: int baudrate: int = 9600 bytesize: int = 8 parity: str = "N" stopbits: int = 1 timeout_s: float = 0.5 @dataclass(frozen=True) class GatewayCfg: db_path: str log_level: str = "INFO" log_file: str = "" persist_interval_s: float = 300.0 status_interval_s: float = 60.0 stale_warn_s: float = 20.0 register_float_order: str = "ABCD" devices: dict[str, DeviceCfg] = field(default_factory=dict) compressors: list[CompressorCfg] = field(default_factory=list) slaves: list[SlaveCfg] = field(default_factory=list) def _point(raw: dict[str, Any], device_offset: int, where: str) -> Point: if not isinstance(raw, dict) or "address" not in raw: raise ConfigError(f"{where}: 缺少 address") ptype = str(raw.get("type", "float32")).lower() if ptype not in TYPE_WIDTH: raise ConfigError(f"{where}: 不支持的数据类型 {ptype}") word_order = str(raw.get("word_order", "ABCD")).upper() if word_order not in ("ABCD", "CDAB"): raise ConfigError(f"{where}: word_order 只能是 ABCD 或 CDAB") address = int(raw["address"]) + int(raw.get("address_offset", 0)) + device_offset if address < 0: raise ConfigError(f"{where}: 地址不能为负 ({address})") return Point( address=address, type=ptype, word_order=word_order, scale=_decimal(raw.get("scale"), "1"), offset=_decimal(raw.get("offset"), "0"), ) def _device(name: str, raw: dict[str, Any]) -> DeviceCfg: if not isinstance(raw, dict) or "host" not in raw: raise ConfigError(f"devices.{name}: 缺少 host") return DeviceCfg( name=name, host=str(raw["host"]), port=int(raw.get("port", 502)), slave_id=int(raw.get("slave_id", 1)), timeout_s=float(raw.get("timeout_s", 1.0)), poll_interval_s=float(raw.get("poll_interval_s", 2.0)), address_offset=int(raw.get("address_offset", 0)), max_registers_per_read=int(raw.get("max_registers_per_read", 60)), max_gap=int(raw.get("max_gap", 4)), reconnect_min_s=float(raw.get("reconnect_min_s", 1.0)), reconnect_max_s=float(raw.get("reconnect_max_s", 30.0)), ) def _compressor(raw: dict[str, Any], devices: dict[str, DeviceCfg]) -> CompressorCfg: cid = int(raw["id"]) where = f"compressors[id={cid}]" s331 = str(raw["s331"]) meter = str(raw["meter"]) for dev in (s331, meter): if dev not in devices: raise ConfigError(f"{where}: 引用了未定义的设备 {dev}") flow_offset = devices[s331].address_offset meter_offset = devices[meter].address_offset return CompressorCfg( id=cid, name=str(raw.get("name", f"{cid}#空压机")), s331=s331, meter=meter, register_index=int(raw.get("register_index", cid - 1)), flow_instant=_point(raw["flow_instant"], flow_offset, f"{where}.flow_instant"), flow_total=_point(raw["flow_total"], flow_offset, f"{where}.flow_total"), power_instant=_point(raw["power_instant"], meter_offset, f"{where}.power_instant"), energy_total=_point(raw["energy_total"], meter_offset, f"{where}.energy_total"), ) def _slave(raw: dict[str, Any]) -> SlaveCfg: if "port" not in raw: raise ConfigError("slaves: 缺少 port") slave_id = int(raw.get("slave_id", 1)) if not 1 <= slave_id <= 247: raise ConfigError(f"slaves.{raw.get('name', raw['port'])}: slave_id 必须在 1~247") parity = str(raw.get("parity", "N")).upper() if parity not in ("N", "E", "O"): raise ConfigError(f"slaves.{raw.get('name', raw['port'])}: parity 只能是 N/E/O") return SlaveCfg( name=str(raw.get("name", Path(str(raw["port"])).name)), port=str(raw["port"]), slave_id=slave_id, baudrate=int(raw.get("baudrate", 9600)), bytesize=int(raw.get("bytesize", 8)), parity=parity, stopbits=int(raw.get("stopbits", 1)), timeout_s=float(raw.get("timeout_s", 0.5)), ) def load_config(path: str | Path) -> GatewayCfg: """读取 YAML 并做完整性校验。""" cfg_path = Path(path) if not cfg_path.is_file(): raise ConfigError(f"配置文件不存在: {cfg_path}") with cfg_path.open("r", encoding="utf-8") as fp: raw = yaml.safe_load(fp) or {} gw = raw.get("gateway") or {} devices = {name: _device(name, item) for name, item in (raw.get("devices") or {}).items()} if not devices: raise ConfigError("devices 不能为空") raw_compressors = raw.get("compressors") or [] if not raw_compressors: raise ConfigError("compressors 不能为空") compressors = [_compressor(item, devices) for item in raw_compressors] ids = [c.id for c in compressors] if len(ids) != len(set(ids)): raise ConfigError("compressors.id 存在重复") indexes = [c.register_index for c in compressors] if len(indexes) != len(set(indexes)): raise ConfigError("register_index 存在重复,会导致寄存器地址冲突") if min(indexes) < 0: raise ConfigError("register_index 不能为负") slaves = [_slave(item) for item in (raw.get("slaves") or [])] if not slaves: raise ConfigError("slaves 不能为空(需要为两个 S331 各配置一个 RTU 从站)") ports = [s.port for s in slaves] if len(ports) != len(set(ports)): raise ConfigError("slaves.port 重复:两个 S331 必须使用两个独立物理串口") float_order = str(gw.get("register_float_order", "ABCD")).upper() if float_order not in ("ABCD", "CDAB"): raise ConfigError("gateway.register_float_order 只能是 ABCD 或 CDAB") return GatewayCfg( db_path=str(gw.get("db_path", "gateway.db")), log_level=str(gw.get("log_level", "INFO")).upper(), log_file=str(gw.get("log_file", "") or ""), persist_interval_s=float(gw.get("persist_interval_s", 300)), status_interval_s=float(gw.get("status_interval_s", 60)), stale_warn_s=float(gw.get("stale_warn_s", 20)), register_float_order=float_order, devices=devices, compressors=compressors, slaves=slaves, )