现场调试版同步:S331 点表修正(CDAB/scale 60/int32) + SafeRTUFramer 多点485 + 哨兵过滤
- config.yaml: 恢复现场 IP(10.50.253.165/.181/.182)、s331_2 端口 502 - config.yaml: S331 全部 32 位量 word_order 改 CDAB,瞬时流量 scale=60 (m3/min -> m3/h) - config.yaml: 11# 电表功率/电能类型改 int32;第二路 RTU 从站 slave_id 改 10 - poller.py: 过滤 S331 无数据哨兵 -9999 与非有限值,避免污染周期基准 - rtu.py: 新增 SafeRTUFramer 支持多点半总线,忽略其它从站请求 - 新增 config.debug.yaml、README.md、wheelhouse 离线依赖 - tests: 适配新配置(ttyS7/address_offset);新增 pytest.ini 限定 testpaths
This commit is contained in:
commit
9eaf87ab7d
43 files changed
+4514
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""海信视像空压机气电比边缘网关。"""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
"""边缘网关主程序。
|
||||
|
||||
线程/任务划分:
|
||||
- 采集线程:每个 TCP 设备一个(S331 #1、S331 #2、410S),指数退避重连;
|
||||
- 主线程事件循环:两个独立 Modbus RTU 从站(/dev/ttyS1、/dev/ttyS2);
|
||||
- 维护线程:定时 SQLite 掉电保持 + 周期状态日志。
|
||||
|
||||
启动:python -m gateway.app --config config/config.yaml
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
from . import __version__
|
||||
from .config import GatewayCfg, load_config
|
||||
from .persistence import SqliteStore
|
||||
from .poller import PointBinding, TcpPoller
|
||||
from .rtu import run_slaves
|
||||
from .store import REGISTERS_PER_MACHINE, StateStore
|
||||
|
||||
log = logging.getLogger("gateway")
|
||||
|
||||
|
||||
def _setup_logging(cfg: GatewayCfg, level_override: Optional[str]) -> None:
|
||||
level = getattr(logging, (level_override or cfg.log_level).upper(), logging.INFO)
|
||||
handlers: list[logging.Handler] = [logging.StreamHandler()]
|
||||
if cfg.log_file:
|
||||
handlers.append(
|
||||
RotatingFileHandler(
|
||||
cfg.log_file, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||||
)
|
||||
)
|
||||
logging.basicConfig(
|
||||
level=level,
|
||||
format="%(asctime)s.%(msecs)03d %(levelname)-5s [%(threadName)s] %(name)s: %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
handlers=handlers,
|
||||
force=True,
|
||||
)
|
||||
# 第三方库日志降噪
|
||||
for noisy in ("pymodbus", "pymodbus.logging", "asyncio", "serial_asyncio"):
|
||||
logging.getLogger(noisy).setLevel(logging.WARNING)
|
||||
|
||||
|
||||
def _log_register_map(compressors: Iterable[Any]) -> None:
|
||||
log.info("RTU 保持寄存器映射(协议地址 0 基 / S4C 中 40001 起):")
|
||||
for cfg in sorted(compressors, key=lambda c: c.register_index):
|
||||
base = cfg.register_index * REGISTERS_PER_MACHINE
|
||||
log.info(
|
||||
" %-8s 基址 0x%04X (寄存器 %d~%d): 瞬时/小时/天/月 气电比",
|
||||
cfg.name,
|
||||
base,
|
||||
40001 + base,
|
||||
40001 + base + REGISTERS_PER_MACHINE - 1,
|
||||
)
|
||||
|
||||
|
||||
def _apply_values(store: StateStore, values: dict[tuple[int, str], Any]) -> None:
|
||||
updates: dict[int, dict[str, Any]] = {}
|
||||
for (machine_id, field), value in values.items():
|
||||
updates.setdefault(machine_id, {})[field] = value
|
||||
store.update(updates)
|
||||
|
||||
|
||||
def _build_pollers(
|
||||
cfg: GatewayCfg, store: StateStore, stop_event: threading.Event
|
||||
) -> list[TcpPoller]:
|
||||
per_device: dict[str, list[PointBinding]] = {}
|
||||
for comp in cfg.compressors:
|
||||
per_device.setdefault(comp.s331, []).extend(
|
||||
[
|
||||
PointBinding(comp.id, "instant_flow", comp.flow_instant),
|
||||
PointBinding(comp.id, "total_flow", comp.flow_total),
|
||||
]
|
||||
)
|
||||
per_device.setdefault(comp.meter, []).extend(
|
||||
[
|
||||
PointBinding(comp.id, "instant_power", comp.power_instant),
|
||||
PointBinding(comp.id, "total_energy", comp.energy_total),
|
||||
]
|
||||
)
|
||||
|
||||
pollers: list[TcpPoller] = []
|
||||
for device_name, bindings in per_device.items():
|
||||
device = cfg.devices[device_name]
|
||||
pollers.append(
|
||||
TcpPoller(
|
||||
device,
|
||||
bindings,
|
||||
lambda values, _store=store: _apply_values(_store, values),
|
||||
stop_event,
|
||||
)
|
||||
)
|
||||
return pollers
|
||||
|
||||
|
||||
class MaintenanceWorker(threading.Thread):
|
||||
"""定时落盘与状态日志。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cfg: GatewayCfg,
|
||||
store: StateStore,
|
||||
db: SqliteStore,
|
||||
pollers: list[TcpPoller],
|
||||
stop_event: threading.Event,
|
||||
) -> None:
|
||||
super().__init__(name="maintenance", daemon=True)
|
||||
self._cfg = cfg
|
||||
self._store = store
|
||||
self._db = db
|
||||
self._pollers = pollers
|
||||
self._stop_event = stop_event
|
||||
|
||||
def run(self) -> None:
|
||||
last_persist = time.monotonic()
|
||||
last_status = last_persist
|
||||
while not self._stop_event.wait(1.0):
|
||||
now = time.monotonic()
|
||||
if now - last_persist >= self._cfg.persist_interval_s:
|
||||
self.persist()
|
||||
last_persist = now
|
||||
if now - last_status >= self._cfg.status_interval_s:
|
||||
self._log_status()
|
||||
last_status = now
|
||||
|
||||
def persist(self) -> None:
|
||||
try:
|
||||
self._db.save(self._store.persist_payloads(), datetime.now())
|
||||
log.debug("状态已保存到 %s", self._cfg.db_path)
|
||||
except Exception: # noqa: BLE001 - 落盘失败不能影响采集与从站
|
||||
log.exception("保存状态到 SQLite 失败")
|
||||
|
||||
def _log_status(self) -> None:
|
||||
now = datetime.now()
|
||||
stale = self._cfg.stale_warn_s
|
||||
for row in self._store.snapshot(now):
|
||||
ratios = row["ratios"]
|
||||
age = row["age_s"]
|
||||
log.info(
|
||||
"状态 %-8s 瞬时=%-9.4f 时=%-9.4f 日=%-9.4f 月=%-9.4f | 瞬时流量=%s 累计气量=%s 瞬时功率=%s 累计电量=%s | 数据延迟=%s",
|
||||
row["name"],
|
||||
ratios["instant"],
|
||||
ratios["hour"],
|
||||
ratios["day"],
|
||||
ratios["month"],
|
||||
_fmt(row["instant_flow"]),
|
||||
_fmt(row["total_flow"]),
|
||||
_fmt(row["instant_power"]),
|
||||
_fmt(row["total_energy"]),
|
||||
"无数据" if age is None else f"{age:.0f}s",
|
||||
)
|
||||
if age is not None and age > stale:
|
||||
log.warning("%s 数据已 %.0fs 未更新,寄存器继续提供最后一次计算结果", row["name"], age)
|
||||
for status in (poller.status() for poller in self._pollers):
|
||||
last_ok = status["last_ok_age_s"]
|
||||
log.info(
|
||||
"链路 %-10s %-18s 成功=%d 失败=%d 最近成功=%s 最近错误=%s",
|
||||
status["name"],
|
||||
status["target"],
|
||||
status["ok_cycles"],
|
||||
status["fail_cycles"],
|
||||
"-" if last_ok is None else f"{last_ok}s",
|
||||
status["last_error"],
|
||||
)
|
||||
|
||||
|
||||
def _fmt(value: Optional[float]) -> str:
|
||||
if value is None:
|
||||
return "-"
|
||||
if abs(value) >= 10000:
|
||||
return f"{value:.1f}"
|
||||
return f"{value:.4f}".rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
async def _serve(cfg: GatewayCfg, store: StateStore, stop_event: threading.Event) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
try:
|
||||
loop.add_signal_handler(sig, stop_event.set)
|
||||
except (NotImplementedError, RuntimeError, ValueError):
|
||||
pass
|
||||
await run_slaves(cfg.slaves, store, stop_event)
|
||||
|
||||
|
||||
def _parse_args(argv: Optional[list[str]]) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="空压机气电比边缘网关(EG828-CEW)")
|
||||
parser.add_argument("--config", default="config/config.yaml", help="配置文件路径")
|
||||
parser.add_argument("--log-level", default=None, help="覆盖日志级别,如 DEBUG")
|
||||
parser.add_argument("--print-map", action="store_true", help="仅打印寄存器映射后退出")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: Optional[list[str]] = None) -> int:
|
||||
args = _parse_args(argv)
|
||||
cfg = load_config(args.config)
|
||||
_setup_logging(cfg, args.log_level)
|
||||
|
||||
store = StateStore(cfg.compressors, cfg.register_float_order)
|
||||
_log_register_map(cfg.compressors)
|
||||
if args.print_map:
|
||||
return 0
|
||||
|
||||
log.info("边缘网关启动 (version=%s, 机器数=%d)", __version__, len(cfg.compressors))
|
||||
|
||||
db = SqliteStore(cfg.db_path)
|
||||
payloads = db.load()
|
||||
if payloads:
|
||||
restored = store.restore(payloads)
|
||||
log.info("已从 %s 恢复 %d 台机器状态(上次保存 %s)", cfg.db_path, restored, db.last_save_time())
|
||||
|
||||
stop_event = threading.Event()
|
||||
pollers = _build_pollers(cfg, store, stop_event)
|
||||
for poller in pollers:
|
||||
poller.start()
|
||||
maintenance = MaintenanceWorker(cfg, store, db, pollers, stop_event)
|
||||
maintenance.start()
|
||||
|
||||
try:
|
||||
asyncio.run(_serve(cfg, store, stop_event))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
stop_event.set()
|
||||
maintenance.join(timeout=5)
|
||||
for poller in pollers:
|
||||
poller.join(timeout=2)
|
||||
try:
|
||||
db.save(store.persist_payloads(), datetime.now())
|
||||
log.info("退出前状态已保存到 %s", cfg.db_path)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("退出前保存状态失败")
|
||||
log.info("边缘网关已退出")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,253 @@
|
||||
"""配置加载与校验。
|
||||
|
||||
所有设备点位均在 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,
|
||||
)
|
||||
@@ -0,0 +1,187 @@
|
||||
"""单台空压机的数据对象与气电比计算。
|
||||
|
||||
计算口径:
|
||||
瞬时气电比 = 瞬时功率 / 瞬时流量
|
||||
小时气电比 = (本小时末累计电量 - 本小时起点累计电量) / (本小时末累计气量 - 本小时起点累计气量)
|
||||
天气电比 / 月气电比 同理,仅在整点 / 零点 / 月初切换基准。
|
||||
|
||||
全部使用 Decimal 计算,避免 float 累积误差;周期切换通过“基准值复位”实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
PERIODS = ("hour", "day", "month")
|
||||
RATIO_KEYS = ("instant", "hour", "day", "month")
|
||||
ZERO = Decimal(0)
|
||||
_UNSET = object()
|
||||
|
||||
|
||||
def period_keys(now: datetime) -> dict[str, str]:
|
||||
"""返回当前时刻所属的小时/天/月标识,用于判断是否跨周期。"""
|
||||
return {
|
||||
"hour": now.strftime("%Y%m%d%H"),
|
||||
"day": now.strftime("%Y%m%d"),
|
||||
"month": now.strftime("%Y%m"),
|
||||
}
|
||||
|
||||
|
||||
def _ratio(numerator: Optional[Decimal], denominator: Optional[Decimal]) -> Decimal:
|
||||
if numerator is None or denominator is None:
|
||||
return ZERO
|
||||
if denominator <= 0 or numerator < 0:
|
||||
return ZERO
|
||||
return numerator / denominator
|
||||
|
||||
|
||||
def _dec(value: Any) -> Optional[Decimal]:
|
||||
if value is None:
|
||||
return None
|
||||
return value if isinstance(value, Decimal) else Decimal(str(value))
|
||||
|
||||
|
||||
def _s(value: Optional[Decimal]) -> Optional[str]:
|
||||
return None if value is None else str(value)
|
||||
|
||||
|
||||
class MachineState:
|
||||
"""一台空压机的实时值、周期基准与四种气电比。"""
|
||||
|
||||
def __init__(self, machine_id: int, name: str, register_index: int) -> None:
|
||||
self.machine_id = machine_id
|
||||
self.name = name
|
||||
self.register_index = register_index
|
||||
|
||||
self.instant_flow: Optional[Decimal] = None
|
||||
self.total_flow: Optional[Decimal] = None
|
||||
self.instant_power: Optional[Decimal] = None
|
||||
self.total_energy: Optional[Decimal] = None
|
||||
|
||||
self.ratios: dict[str, Decimal] = {key: ZERO for key in RATIO_KEYS}
|
||||
self.flow_time: Optional[datetime] = None
|
||||
self.power_time: Optional[datetime] = None
|
||||
self.ratios_time: Optional[datetime] = None
|
||||
|
||||
self._keys: dict[str, str] = {p: "" for p in PERIODS}
|
||||
# 周期基准:(累计气量, 累计电量)
|
||||
self._bases: dict[str, Optional[tuple[Decimal, Decimal]]] = {p: None for p in PERIODS}
|
||||
|
||||
# ------------------------------------------------------------------ 更新
|
||||
def apply(
|
||||
self,
|
||||
now: datetime,
|
||||
*,
|
||||
instant_flow: Any = _UNSET,
|
||||
total_flow: Any = _UNSET,
|
||||
instant_power: Any = _UNSET,
|
||||
total_energy: Any = _UNSET,
|
||||
) -> None:
|
||||
"""写入新采样值(缺省字段表示本次未更新),随后重算比值。"""
|
||||
if instant_flow is not _UNSET:
|
||||
self.instant_flow = _dec(instant_flow)
|
||||
self.flow_time = now
|
||||
if total_flow is not _UNSET:
|
||||
self.total_flow = _dec(total_flow)
|
||||
self.flow_time = now
|
||||
if instant_power is not _UNSET:
|
||||
self.instant_power = _dec(instant_power)
|
||||
self.power_time = now
|
||||
if total_energy is not _UNSET:
|
||||
self.total_energy = _dec(total_energy)
|
||||
self.power_time = now
|
||||
self._refresh(now)
|
||||
|
||||
def _refresh(self, now: datetime) -> None:
|
||||
keys = period_keys(now)
|
||||
totals_ready = self.total_flow is not None and self.total_energy is not None
|
||||
|
||||
for period in PERIODS:
|
||||
if self._keys[period] != keys[period]:
|
||||
# 跨周期:基准清零,使用新周期内的第一次累计值作为起点
|
||||
self._keys[period] = keys[period]
|
||||
self._bases[period] = None
|
||||
if self._bases[period] is None and totals_ready:
|
||||
self._bases[period] = (self.total_flow, self.total_energy)
|
||||
|
||||
self.ratios["instant"] = _ratio(self.instant_power, self.instant_flow)
|
||||
for period in PERIODS:
|
||||
base = self._bases[period]
|
||||
if base is None or self.total_flow is None or self.total_energy is None:
|
||||
self.ratios[period] = ZERO
|
||||
continue
|
||||
delta_flow = self.total_flow - base[0]
|
||||
delta_energy = self.total_energy - base[1]
|
||||
self.ratios[period] = _ratio(delta_energy, delta_flow)
|
||||
self.ratios_time = now
|
||||
|
||||
# ------------------------------------------------------------------ 持久化
|
||||
def to_payload(self) -> dict[str, Any]:
|
||||
return {
|
||||
"name": self.name,
|
||||
"register_index": self.register_index,
|
||||
"instant_flow": _s(self.instant_flow),
|
||||
"total_flow": _s(self.total_flow),
|
||||
"instant_power": _s(self.instant_power),
|
||||
"total_energy": _s(self.total_energy),
|
||||
"ratios": {key: str(value) for key, value in self.ratios.items()},
|
||||
"period_keys": dict(self._keys),
|
||||
"bases": {
|
||||
period: (
|
||||
[_s(base[0]), _s(base[1])] if base is not None else None
|
||||
)
|
||||
for period, base in self._bases.items()
|
||||
},
|
||||
"flow_time": self.flow_time.isoformat() if self.flow_time else None,
|
||||
"power_time": self.power_time.isoformat() if self.power_time else None,
|
||||
}
|
||||
|
||||
def restore(self, payload: dict[str, Any], now: datetime) -> None:
|
||||
"""从 SQLite 恢复。
|
||||
|
||||
周期未变化时沿用原基准,做到重启后累计值连续;
|
||||
周期已经跨越(例如停机跨天)时,用最后一次累计值作为新基准。
|
||||
"""
|
||||
self.instant_flow = _dec(payload.get("instant_flow"))
|
||||
self.total_flow = _dec(payload.get("total_flow"))
|
||||
self.instant_power = _dec(payload.get("instant_power"))
|
||||
self.total_energy = _dec(payload.get("total_energy"))
|
||||
|
||||
self.flow_time = _parse_dt(payload.get("flow_time"))
|
||||
self.power_time = _parse_dt(payload.get("power_time"))
|
||||
|
||||
keys = period_keys(now)
|
||||
saved_keys = payload.get("period_keys") or {}
|
||||
saved_bases = payload.get("bases") or {}
|
||||
both_totals = self.total_flow is not None and self.total_energy is not None
|
||||
|
||||
for period in PERIODS:
|
||||
base = saved_bases.get(period)
|
||||
same_period = saved_keys.get(period) == keys[period]
|
||||
if same_period and base:
|
||||
self._bases[period] = (Decimal(str(base[0])), Decimal(str(base[1])))
|
||||
elif both_totals:
|
||||
self._bases[period] = (self.total_flow, self.total_energy)
|
||||
else:
|
||||
self._bases[period] = None
|
||||
self._keys[period] = keys[period]
|
||||
|
||||
self._refresh(now)
|
||||
|
||||
def age_s(self, now: datetime) -> Optional[float]:
|
||||
"""距离最近一次气量/电表更新的秒数(取较旧者)。"""
|
||||
times = [t for t in (self.flow_time, self.power_time) if t is not None]
|
||||
if not times:
|
||||
return None
|
||||
return (now - min(times)).total_seconds()
|
||||
|
||||
|
||||
def _parse_dt(value: Any) -> Optional[datetime]:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(str(value))
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -0,0 +1,77 @@
|
||||
"""SQLite 掉电保持:保存/恢复各台机器的周期基准与最新累计值。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS machine_state (
|
||||
machine_id INTEGER PRIMARY KEY,
|
||||
payload TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
class SqliteStore:
|
||||
def __init__(self, path: str) -> None:
|
||||
self._path = Path(path)
|
||||
if str(self._path.parent) not in ("", "."):
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self._connect() as conn:
|
||||
conn.executescript(_SCHEMA)
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
return sqlite3.connect(self._path, timeout=10)
|
||||
|
||||
def save(self, payloads: dict[int, dict[str, Any]], now: datetime) -> None:
|
||||
if not payloads:
|
||||
return
|
||||
stamp = now.isoformat(timespec="seconds")
|
||||
rows = [
|
||||
(machine_id, json.dumps(payload, ensure_ascii=False), stamp)
|
||||
for machine_id, payload in payloads.items()
|
||||
]
|
||||
with self._connect() as conn:
|
||||
conn.executemany(
|
||||
"INSERT OR REPLACE INTO machine_state (machine_id, payload, updated_at) VALUES (?, ?, ?)",
|
||||
rows,
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO meta (key, value) VALUES ('last_save', ?)",
|
||||
(stamp,),
|
||||
)
|
||||
|
||||
def load(self) -> dict[int, dict[str, Any]]:
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute("SELECT machine_id, payload FROM machine_state").fetchall()
|
||||
except sqlite3.Error:
|
||||
log.exception("读取 SQLite 状态失败,将按冷启动处理")
|
||||
return {}
|
||||
result: dict[int, dict[str, Any]] = {}
|
||||
for machine_id, payload in rows:
|
||||
try:
|
||||
result[int(machine_id)] = json.loads(payload)
|
||||
except (TypeError, ValueError):
|
||||
log.warning("机器 %s 的历史状态无法解析,已忽略", machine_id)
|
||||
return result
|
||||
|
||||
def last_save_time(self) -> str | None:
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute("SELECT value FROM meta WHERE key='last_save'").fetchone()
|
||||
except sqlite3.Error:
|
||||
return None
|
||||
return row[0] if row else None
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Modbus TCP 采集线程(网关作为 Client)。
|
||||
|
||||
每个设备一个线程,互不影响:
|
||||
- 采集频率与 S331 读取寄存器频率完全解耦;
|
||||
- 连接失败 / 读取失败走指数退避重连,线程不退出,RTU 从站不受影响;
|
||||
- 一次循环内按“连续块”批量读取,减少 410S 的请求次数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Callable, Optional, Sequence
|
||||
|
||||
from pymodbus.client import ModbusTcpClient
|
||||
|
||||
from .config import DeviceCfg, Point
|
||||
from .registers import Block, decode_point, plan_blocks
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# S331 未接入/无数据的通道整组寄存器填 -9999(float32 = 0xC61C3C00),
|
||||
# 按 ABCD / CDAB 读出来分别是 (0xC61C, 0x3C00) 与 (0x3C00, 0xC61C)。
|
||||
# 这类值若参与计算会把周期基准污染成天文数字,并让 RTU 端打包 Float 溢出。
|
||||
S331_SENTINEL_WORDS = frozenset({(0xC61C, 0x3C00), (0x3C00, 0xC61C)})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PointBinding:
|
||||
"""点位绑定:把某个寄存器点位映射到某台机器的某个字段。"""
|
||||
|
||||
machine_id: int
|
||||
field: str
|
||||
point: Point
|
||||
|
||||
|
||||
class TcpPoller(threading.Thread):
|
||||
def __init__(
|
||||
self,
|
||||
cfg: DeviceCfg,
|
||||
bindings: Sequence[PointBinding],
|
||||
on_values: Callable[[dict[tuple[int, str], Decimal]], None],
|
||||
stop_event: threading.Event,
|
||||
) -> None:
|
||||
super().__init__(name=f"poll-{cfg.name}", daemon=True)
|
||||
self._cfg = cfg
|
||||
self._bindings = list(bindings)
|
||||
self._on_values = on_values
|
||||
self._stop_event = stop_event
|
||||
self._plan: list[Block] = plan_blocks(
|
||||
[(b.point.address, b.point.width) for b in self._bindings],
|
||||
max_registers=cfg.max_registers_per_read,
|
||||
max_gap=cfg.max_gap,
|
||||
)
|
||||
self._locate = {
|
||||
(b.machine_id, b.field): _find_block(self._plan, b.point) for b in self._bindings
|
||||
}
|
||||
self._ok_cycles = 0
|
||||
self._fail_cycles = 0
|
||||
self._last_error: Optional[str] = None
|
||||
self._last_ok: Optional[float] = None
|
||||
|
||||
# ------------------------------------------------------------ 线程主体
|
||||
def run(self) -> None:
|
||||
cfg = self._cfg
|
||||
backoff = cfg.reconnect_min_s
|
||||
connected = False
|
||||
while not self._stop_event.is_set():
|
||||
client = ModbusTcpClient(
|
||||
cfg.host,
|
||||
port=cfg.port,
|
||||
timeout=cfg.timeout_s,
|
||||
retries=1,
|
||||
)
|
||||
try:
|
||||
if not client.connect():
|
||||
raise ConnectionError(f"无法连接 {cfg.host}:{cfg.port}")
|
||||
if not connected:
|
||||
log.info("[%s] 已连接 %s:%s", cfg.name, cfg.host, cfg.port)
|
||||
connected = True
|
||||
backoff = cfg.reconnect_min_s
|
||||
while not self._stop_event.is_set():
|
||||
started = time.monotonic()
|
||||
values = self._read_once(client)
|
||||
self._on_values(values)
|
||||
self._ok_cycles += 1
|
||||
self._last_ok = time.monotonic()
|
||||
elapsed = time.monotonic() - started
|
||||
self._stop_event.wait(max(0.0, cfg.poll_interval_s - elapsed))
|
||||
except Exception as exc: # noqa: BLE001 - 采集线程必须兜住所有异常
|
||||
self._fail_cycles += 1
|
||||
self._last_error = f"{type(exc).__name__}: {exc}"
|
||||
log.warning("[%s] 采集失败: %s,%.1fs 后重连", cfg.name, self._last_error, backoff)
|
||||
finally:
|
||||
client.close()
|
||||
if connected:
|
||||
log.info("[%s] 连接已关闭", cfg.name)
|
||||
connected = False
|
||||
|
||||
if self._stop_event.wait(backoff):
|
||||
break
|
||||
backoff = min(backoff * 2, cfg.reconnect_max_s)
|
||||
|
||||
# ------------------------------------------------------------ 单次采集
|
||||
def _read_once(self, client: ModbusTcpClient) -> dict[tuple[int, str], Decimal]:
|
||||
raw: dict[int, list[int]] = {}
|
||||
for block in self._plan:
|
||||
response = _read_holding(client, block.start, block.count, self._cfg.slave_id)
|
||||
if response is None or response.isError():
|
||||
raise IOError(
|
||||
f"读取寄存器 {block.start}~{block.start + block.count - 1} 失败: {response}"
|
||||
)
|
||||
registers = getattr(response, "registers", None)
|
||||
if not registers or len(registers) < block.count:
|
||||
raise IOError(f"寄存器 {block.start} 返回长度异常: {registers}")
|
||||
raw[block.start] = list(registers)
|
||||
|
||||
values: dict[tuple[int, str], Decimal] = {}
|
||||
for binding in self._bindings:
|
||||
start, offset = self._locate[(binding.machine_id, binding.field)]
|
||||
words = raw[start][offset : offset + binding.point.width]
|
||||
if tuple(words) in S331_SENTINEL_WORDS:
|
||||
log.debug(
|
||||
"[%s] %s# 的 %s 为 S331 无数据哨兵,本次跳过",
|
||||
self._cfg.name,
|
||||
binding.machine_id,
|
||||
binding.field,
|
||||
)
|
||||
continue
|
||||
value = decode_point(words, binding.point)
|
||||
if not value.is_finite():
|
||||
log.debug(
|
||||
"[%s] %s# 的 %s 为非有限值,本次跳过",
|
||||
self._cfg.name,
|
||||
binding.machine_id,
|
||||
binding.field,
|
||||
)
|
||||
continue
|
||||
values[(binding.machine_id, binding.field)] = value
|
||||
return values
|
||||
|
||||
# ------------------------------------------------------------ 诊断
|
||||
def status(self) -> dict[str, object]:
|
||||
return {
|
||||
"name": self._cfg.name,
|
||||
"target": f"{self._cfg.host}:{self._cfg.port}",
|
||||
"ok_cycles": self._ok_cycles,
|
||||
"fail_cycles": self._fail_cycles,
|
||||
"last_ok_age_s": None if self._last_ok is None else round(time.monotonic() - self._last_ok, 1),
|
||||
"last_error": self._last_error,
|
||||
}
|
||||
|
||||
|
||||
def _find_block(blocks: Sequence[Block], point: Point) -> tuple[int, int]:
|
||||
for block in blocks:
|
||||
if block.start <= point.address and point.address + point.width <= block.end:
|
||||
return block.start, point.address - block.start
|
||||
raise LookupError(f"点位 {point.address}+{point.width} 未被读取块覆盖")
|
||||
|
||||
|
||||
def _read_holding(client: ModbusTcpClient, address: int, count: int, slave_id: int):
|
||||
"""兼容 pymodbus 3.8/3.9(slave=)与 3.10+(device_id=)的参数名。"""
|
||||
try:
|
||||
return client.read_holding_registers(address, count=count, slave=slave_id)
|
||||
except TypeError:
|
||||
return client.read_holding_registers(address, count=count, device_id=slave_id)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""现场点表核查工具。
|
||||
|
||||
用于和 S331 / 410S 的实际点表对齐:读取一段保持寄存器,
|
||||
同时给出 uint16 / int16 / int32 / uint32 / float32(ABCD) / float32(CDAB) 的解释。
|
||||
|
||||
用法示例:
|
||||
python -m gateway.probe --host 192.168.10.31 --slave 1 --start 0 --count 40
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import struct
|
||||
import sys
|
||||
|
||||
from pymodbus.client import ModbusTcpClient
|
||||
|
||||
|
||||
def _read(client: ModbusTcpClient, start: int, count: int, slave_id: int) -> list[int]:
|
||||
try:
|
||||
response = client.read_holding_registers(start, count=count, slave=slave_id)
|
||||
except TypeError:
|
||||
response = client.read_holding_registers(start, count=count, device_id=slave_id)
|
||||
if response is None or response.isError():
|
||||
raise IOError(f"读取失败: {response}")
|
||||
return list(response.registers)
|
||||
|
||||
|
||||
def _f32(words: list[int], order: str) -> float:
|
||||
hi, lo = (words[1], words[0]) if order == "CDAB" else (words[0], words[1])
|
||||
return struct.unpack(">f", struct.pack(">HH", hi, lo))[0]
|
||||
|
||||
|
||||
def _s32(words: list[int], signed: bool) -> int:
|
||||
hi, lo = words[0], words[1]
|
||||
return struct.unpack(">i" if signed else ">I", struct.pack(">HH", hi, lo))[0]
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Modbus TCP 点表核查")
|
||||
parser.add_argument("--host", required=True)
|
||||
parser.add_argument("--port", type=int, default=502)
|
||||
parser.add_argument("--slave", type=int, default=1)
|
||||
parser.add_argument("--start", type=int, default=0, help="起始协议地址(40001 -> 0)")
|
||||
parser.add_argument("--count", type=int, default=32, help="读取寄存器个数")
|
||||
parser.add_argument("--timeout", type=float, default=2.0)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
client = ModbusTcpClient(args.host, port=args.port, timeout=args.timeout)
|
||||
if not client.connect():
|
||||
print(f"连接失败: {args.host}:{args.port}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
registers = _read(client, args.start, args.count, args.slave)
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
print(f"{args.host}:{args.port} slave={args.slave} 起始={args.start} 共 {len(registers)} 个寄存器")
|
||||
print(
|
||||
f"{'地 址':>7} {'4xxxx':>7} {'HEX':>6} {'U16':>7} {'I16':>7} "
|
||||
f"{'I32':>12} {'U32':>12} {'Float(ABCD)':>14} {'Float(CDAB)':>14}"
|
||||
)
|
||||
for offset, word in enumerate(registers):
|
||||
address = args.start + offset
|
||||
i32 = u32 = "-"
|
||||
f_abcd = f_cdab = "-"
|
||||
if offset + 1 < len(registers):
|
||||
pair = registers[offset : offset + 2]
|
||||
i32 = str(_s32(pair, True))
|
||||
u32 = str(_s32(pair, False))
|
||||
f_abcd = f"{_f32(pair, 'ABCD'):.5g}"
|
||||
f_cdab = f"{_f32(pair, 'CDAB'):.5g}"
|
||||
print(
|
||||
f"{address:>7} {40001 + address:>7} {word:>6} {word:>7} "
|
||||
f"{word - 65536 if word > 32767 else word:>7} {i32:>12} {u32:>12} "
|
||||
f"{f_abcd:>14} {f_cdab:>14}"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,113 @@
|
||||
"""寄存器编解码与批量读取规划。
|
||||
|
||||
处理三类现场问题:
|
||||
1. 数据类型不一致(float32 / int32 / uint32 / int16 ...);
|
||||
2. 字序不一致(ABCD / CDAB,即“高低字交换”);
|
||||
3. 点表错位(同一设备内点位合并成块读取,配合 config 中的 address_offset 补偿)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Iterable, Mapping, Sequence
|
||||
|
||||
from .config import Point
|
||||
|
||||
_STRUCT_FMT = {
|
||||
"int16": ">h",
|
||||
"uint16": ">H",
|
||||
"int32": ">i",
|
||||
"uint32": ">I",
|
||||
"float32": ">f",
|
||||
"int64": ">q",
|
||||
"uint64": ">Q",
|
||||
"float64": ">d",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Block:
|
||||
"""一段连续寄存器读取区间(0 基协议地址)。"""
|
||||
|
||||
start: int
|
||||
count: int
|
||||
|
||||
@property
|
||||
def end(self) -> int:
|
||||
return self.start + self.count
|
||||
|
||||
|
||||
def _words_to_bytes(words: Sequence[int], order: str) -> bytes:
|
||||
ordered = list(words)
|
||||
if order == "CDAB":
|
||||
ordered.reverse()
|
||||
return b"".join(int(word).to_bytes(2, "big") for word in ordered)
|
||||
|
||||
|
||||
def decode_point(words: Sequence[int], point: Point) -> Decimal:
|
||||
"""把原始寄存器字按点位定义转换为工程值(Decimal)。"""
|
||||
width = point.width
|
||||
if len(words) < width:
|
||||
raise ValueError(f"寄存器数量不足: 需要 {width} 个, 实际 {len(words)}")
|
||||
data = _words_to_bytes(list(words[:width]), point.order)
|
||||
raw = struct.unpack(_STRUCT_FMT[point.type], data)[0]
|
||||
return Decimal(str(raw)) * point.scale + point.offset
|
||||
|
||||
|
||||
def encode_float32(value: float, order: str = "ABCD") -> list[int]:
|
||||
"""把 float 编码为两个寄存器字,供 RTU 从站使用。"""
|
||||
data = struct.pack(">f", float(value))
|
||||
words = [int.from_bytes(data[0:2], "big"), int.from_bytes(data[2:4], "big")]
|
||||
if order == "CDAB":
|
||||
words.reverse()
|
||||
return words
|
||||
|
||||
|
||||
def plan_blocks(
|
||||
spans: Iterable[tuple[int, int]],
|
||||
max_registers: int = 60,
|
||||
max_gap: int = 4,
|
||||
) -> list[Block]:
|
||||
"""把 (起始地址, 寄存器个数) 列表合并成尽量少的连续读取块。
|
||||
|
||||
相邻点位间隔 <= max_gap 且合并后长度 <= max_registers 时合并,
|
||||
以减少 TCP 请求次数、降低 410S 的响应压力。
|
||||
"""
|
||||
blocks: list[Block] = []
|
||||
for start, width in sorted(spans):
|
||||
if width <= 0:
|
||||
continue
|
||||
end = start + width
|
||||
if blocks:
|
||||
last = blocks[-1]
|
||||
gap = start - last.end
|
||||
merged_len = max(last.end, end) - last.start
|
||||
if 0 <= gap <= max_gap and merged_len <= max_registers:
|
||||
blocks[-1] = Block(last.start, merged_len)
|
||||
continue
|
||||
blocks.append(Block(start, width))
|
||||
return blocks
|
||||
|
||||
|
||||
def locate(blocks: Sequence[Block], start: int, width: int) -> tuple[int, int]:
|
||||
"""定位点位在某个读取块内的偏移,返回 (块起始地址, 块内偏移)。"""
|
||||
for block in blocks:
|
||||
if block.start <= start and start + width <= block.end:
|
||||
return block.start, start - block.start
|
||||
raise LookupError(f"点位 {start}+{width} 未被任何读取块覆盖")
|
||||
|
||||
|
||||
def extract_values(
|
||||
blocks: Sequence[Block],
|
||||
block_values: Mapping[int, Sequence[int]],
|
||||
points: Mapping[str, Point],
|
||||
) -> dict[str, Decimal]:
|
||||
"""按块读取结果提取各点位工程值。"""
|
||||
result: dict[str, Decimal] = {}
|
||||
for name, point in points.items():
|
||||
block_start, offset = locate(blocks, point.address, point.width)
|
||||
words = block_values[block_start][offset : offset + point.width]
|
||||
result[name] = decode_point(words, point)
|
||||
return result
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
"""双路 Modbus RTU 从站。
|
||||
|
||||
为 S331 #1 与 S331 #2 各启动一个独立的 ModbusSerialServer 实例,
|
||||
分别绑定 /dev/ttyS1 与 /dev/ttyS2,物理隔离,互不干扰。
|
||||
|
||||
从站仅提供只读保持寄存器(FC03/FC04),数据源为 StateStore 中的寄存器快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
from typing import Sequence
|
||||
|
||||
from pymodbus import FramerType
|
||||
from pymodbus.datastore import ModbusServerContext
|
||||
from pymodbus.framer import FramerRTU
|
||||
from pymodbus.server import ModbusSerialServer
|
||||
|
||||
from .config import SlaveCfg
|
||||
from .store import StateStore
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# 功能码 -> 数据区(只读,写操作一律拒绝)
|
||||
_FX_MAPPER = {1: "c", 2: "d", 3: "h", 4: "i", 5: "c", 6: "h", 15: "c", 16: "h", 22: "h", 23: "h"}
|
||||
|
||||
ILLEGAL_DATA_ADDRESS = 2
|
||||
ILLEGAL_FUNCTION = 1
|
||||
|
||||
|
||||
class SafeRTUFramer(FramerRTU):
|
||||
"""只认“发往本从站地址”的 RTU 从站 framer。
|
||||
|
||||
pymodbus 自带的 FramerRTU 默认 485 上只有自己一个从站,按顺序逐帧解析收到的
|
||||
字节。现场这条 485 上 S331 屏是主站,它同时轮询 67~75 号流量计,实测一次读进来
|
||||
的数据能粘成 772 字节的一大批;批里只要有一帧解不出来,异常就冒到 asyncio
|
||||
回调里,整批字节被丢弃——包括夹在中间的 `0a 03 ...` 请求,屏上的气电比因此
|
||||
会短暂变空、过一会儿才恢复。
|
||||
这里改成只在缓冲区里扫描“地址=本从站、FC03/04、CRC 正确”的 8 字节请求,
|
||||
其余字节直接丢弃,我方请求不会被别的设备的流量带走。
|
||||
"""
|
||||
|
||||
SLAVE_ID = 10 # 由 _serve_one 按配置设置
|
||||
REQUESTS = (3, 4) # S331 屏只用 FC03/FC04 读保持/输入寄存器
|
||||
|
||||
def processIncomingFrame(self, data):
|
||||
size = len(data)
|
||||
for offset in range(max(0, size - 7)):
|
||||
if data[offset] != self.SLAVE_ID or data[offset + 1] not in self.REQUESTS:
|
||||
continue
|
||||
frame = data[offset : offset + 8]
|
||||
crc = (frame[6] << 8) | frame[7]
|
||||
if not self.check_CRC(frame[:6], crc):
|
||||
continue
|
||||
try:
|
||||
pdu = self.decoder.decode(frame[1:6])
|
||||
except Exception: # noqa: BLE001 - 偶发坏帧跳过即可
|
||||
continue
|
||||
if pdu is None:
|
||||
continue
|
||||
pdu.dev_id = self.SLAVE_ID
|
||||
pdu.transaction_id = 0
|
||||
log.debug("RTU 收到请求 dev=%s func=%s", pdu.dev_id, pdu.function_code)
|
||||
return offset + 8, pdu
|
||||
# 没找到完整请求:丢掉除末尾 7 字节外的数据(末尾可能是一帧的半截)
|
||||
return max(0, size - 7), None
|
||||
|
||||
def encode(self, pdu: bytes, dev_id: int, tid: int) -> bytes:
|
||||
frame = super().encode(pdu, dev_id, tid)
|
||||
log.debug("RTU 发送应答 dev=%s func=%s len=%d", dev_id, pdu[0] if pdu else -1, len(frame))
|
||||
return frame
|
||||
|
||||
|
||||
class SnapshotDeviceContext:
|
||||
"""把 StateStore 的寄存器镜像暴露成 pymodbus 设备上下文。
|
||||
|
||||
与 pymodbus 内置 ModbusSlaveContext 的区别:
|
||||
- 不额外做 +1 地址偏移,协议地址 0 直接对应 40001;
|
||||
- getValues 一次性加锁复制快照,避免 S331 读到半新半旧的数据。
|
||||
"""
|
||||
|
||||
def __init__(self, store: StateStore, slave_id: int) -> None:
|
||||
self._store = store
|
||||
self._slave_id = slave_id
|
||||
|
||||
def decode(self, function_code: int) -> str:
|
||||
return _FX_MAPPER.get(function_code, "h")
|
||||
|
||||
def validate(self, function_code: int, address: int, count: int = 1) -> bool:
|
||||
if function_code not in (3, 4, 23):
|
||||
return False
|
||||
return 0 <= address and count > 0 and address + count <= self._store.register_count
|
||||
|
||||
def getValues(self, function_code: int, address: int, count: int = 1):
|
||||
if function_code not in (3, 4, 23):
|
||||
return ILLEGAL_FUNCTION
|
||||
values = self._store.read_registers(address, count)
|
||||
if values is None:
|
||||
return ILLEGAL_DATA_ADDRESS
|
||||
return values
|
||||
|
||||
async def async_getValues(self, function_code: int, address: int, count: int = 1):
|
||||
return self.getValues(function_code, address, count)
|
||||
|
||||
def setValues(self, function_code: int, address: int, values) -> None:
|
||||
# 网关数据由采集线程维护,S331 不允许写入
|
||||
log.warning(
|
||||
"从站 %s 收到写寄存器请求 (功能码=%s 地址=%s),已忽略",
|
||||
self._slave_id,
|
||||
function_code,
|
||||
address,
|
||||
)
|
||||
return None
|
||||
|
||||
async def async_setValues(self, function_code: int, address: int, values) -> None:
|
||||
self.setValues(function_code, address, values)
|
||||
|
||||
def reset(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def build_context(store: StateStore, slave_id: int) -> ModbusServerContext:
|
||||
return ModbusServerContext(
|
||||
slaves={slave_id: SnapshotDeviceContext(store, slave_id)},
|
||||
single=False,
|
||||
)
|
||||
|
||||
|
||||
async def run_slaves(
|
||||
slaves: Sequence[SlaveCfg],
|
||||
store: StateStore,
|
||||
stop_event: threading.Event,
|
||||
) -> None:
|
||||
"""并发启动全部 RTU 从站,直到 stop_event 被置位。"""
|
||||
tasks = [asyncio.create_task(_serve_one(cfg, store, stop_event), name=f"rtu-{cfg.name}") for cfg in slaves]
|
||||
try:
|
||||
while not stop_event.is_set():
|
||||
await asyncio.sleep(0.2)
|
||||
finally:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
log.info("全部 RTU 从站已停止")
|
||||
|
||||
|
||||
async def _serve_one(cfg: SlaveCfg, store: StateStore, stop_event: threading.Event) -> None:
|
||||
"""单个串口的从站循环;串口异常时自动重启,不影响另一个串口。"""
|
||||
while not stop_event.is_set():
|
||||
server = ModbusSerialServer(
|
||||
build_context(store, cfg.slave_id),
|
||||
framer=FramerType.RTU,
|
||||
port=cfg.port,
|
||||
baudrate=cfg.baudrate,
|
||||
bytesize=cfg.bytesize,
|
||||
parity=cfg.parity,
|
||||
stopbits=cfg.stopbits,
|
||||
timeout=cfg.timeout_s,
|
||||
# 同一条 485 上还有别的从站(S331 自己的流量计 67~75),
|
||||
# 对别人的请求必须保持静默,否则会和生产从站抢着应答,撞坏总线
|
||||
ignore_missing_slaves=True,
|
||||
)
|
||||
# 必须在 serve_forever 之前换掉,串口打开时才会用这个类实例化 framer
|
||||
SafeRTUFramer.SLAVE_ID = cfg.slave_id
|
||||
server.framer = SafeRTUFramer
|
||||
try:
|
||||
log.info(
|
||||
"RTU 从站启动: %s -> %s (slave_id=%s, %s-%s-%s-%s)",
|
||||
cfg.name,
|
||||
cfg.port,
|
||||
cfg.slave_id,
|
||||
cfg.baudrate,
|
||||
cfg.bytesize,
|
||||
cfg.parity,
|
||||
cfg.stopbits,
|
||||
)
|
||||
await server.serve_forever()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception: # noqa: BLE001 - 串口异常不能拖垮主程序
|
||||
log.exception("[%s] 串口 %s 异常,3 秒后重新启动从站", cfg.name, cfg.port)
|
||||
await asyncio.sleep(3)
|
||||
finally:
|
||||
try:
|
||||
# 关闭串口传输;pymodbus 内部会自动重连,这里仅在退出时释放资源
|
||||
server.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if not stop_event.is_set():
|
||||
# serve_forever 正常返回(非退出场景)时稍作等待,避免空转
|
||||
await asyncio.sleep(2)
|
||||
@@ -0,0 +1,134 @@
|
||||
"""线程安全的状态仓 + 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)
|
||||
Reference in new issue
Block a user