"""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)