"""寄存器编解码与批量读取规划。 处理三类现场问题: 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