feat(iec104): 在模拟器跑通共享协议核心与标准DTU点表
引入成熟 IEC 60870-5-104 子站的只读子集(App/protocol/iec60870,28 个源文件 按原字节复制,UPSTREAM.sha256 记录来源,兼容补丁保留全部断言与容量),在其上 装配单属主共享核心(Start/Poll/Stop/Get_Status),并把标准 DTU 演示点表全量 接入为唯一真源。 - iec104_core:threadless 推进,poll 零等待,通知/交互/COV 扫描全部有界; 生命周期区分失败启动待重试、重复启动拒绝、断线保固化 RAM。 - iec104_dtu_table / iec104_source:标准 DTU 全点表注册,无数据源的点读 0, 遥控只做模拟状态可读回,不触碰实际出口。 - iec104_sim:仅窗口与独立服务模式起真实 TCP,无头黄金模式保持确定性假统计。 - test/host/iec104_dtu:独立真实 TCP 11 项、传输层 10 项、生命周期与借用负例。 验证:lvgl_sim 真实 TCP 11/11、传输 10/10,UI 像素回归未回退;AC5 单 TU 编译 0 错误 0 诊断。板端尚未切换:完整库闭包 RAM 超 92% 门禁净增预算 25730B, 结论为停止转实施,记录在 IEC104_MCU最小可行性验证.md。旧实现与 board 服务 保持原样,未提交 MDK 工程改动,未烧板。
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
"""Small independent IEC104 wire client with strict stream and sequence checks."""
|
||||
import datetime
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
|
||||
|
||||
def u24(value):
|
||||
return value.to_bytes(3, "little")
|
||||
|
||||
|
||||
def asdu(typ, payload=b"", count=1, cot=6, ca=1, oa=17):
|
||||
return bytes((typ, count, cot, oa)) + struct.pack("<H", ca) + payload
|
||||
|
||||
|
||||
def header(data):
|
||||
assert len(data) >= 6, ("short ASDU", data.hex())
|
||||
return {"type": data[0], "count": data[1] & 127, "sq": bool(data[1] & 128),
|
||||
"cot": data[2] & 63, "pn": bool(data[2] & 64), "test": bool(data[2] & 128),
|
||||
"oa": data[3], "ca": int.from_bytes(data[4:6], "little")}
|
||||
|
||||
|
||||
def cp56(raw):
|
||||
assert len(raw) == 7
|
||||
ms, minute, hour, day, month, year = struct.unpack("<HBBBBB", raw)
|
||||
assert ms < 60000 and minute & 63 < 60 and hour & 31 < 24
|
||||
assert not minute & 64 and not hour & 96 and not month & 240 and not year & 128
|
||||
value = datetime.datetime(2000 + (year & 127), month & 15, day & 31,
|
||||
hour & 31, minute & 63, ms // 1000, (ms % 1000) * 1000)
|
||||
weekday = day >> 5
|
||||
assert weekday == 0 or weekday == value.isoweekday()
|
||||
return {"iso": value.isoformat(), "invalid": bool(minute & 128), "summer": bool(hour & 128)}
|
||||
|
||||
|
||||
def objects(data):
|
||||
h = header(data)
|
||||
widths = {1: 1, 3: 1, 5: 2, 7: 5, 9: 3, 11: 3, 13: 5, 15: 5,
|
||||
30: 8, 31: 8, 34: 10, 35: 10, 36: 12, 37: 12,
|
||||
110: 3, 111: 3, 112: 5, 206: 5, 207: 12}
|
||||
width = widths[h["type"]]
|
||||
offset, base, rows = 6, None, []
|
||||
for index in range(h["count"]):
|
||||
if not h["sq"] or index == 0:
|
||||
assert offset + 3 <= len(data)
|
||||
base = int.from_bytes(data[offset:offset + 3], "little")
|
||||
offset += 3
|
||||
ioa = base + index if h["sq"] else base
|
||||
raw = data[offset:offset + width]
|
||||
assert len(raw) == width
|
||||
typ = h["type"]
|
||||
if typ in (13, 36, 112, 206, 207):
|
||||
value = struct.unpack("<f", raw[:4])[0]
|
||||
elif typ in (9, 11, 34, 35, 110, 111):
|
||||
value = int.from_bytes(raw[:2], "little", signed=True)
|
||||
elif typ in (7, 15, 37):
|
||||
value = int.from_bytes(raw[:4], "little", signed=typ != 7)
|
||||
elif typ == 5:
|
||||
value = raw[0] & 127
|
||||
if value & 64:
|
||||
value -= 128
|
||||
else:
|
||||
value = raw[0] & (1 if typ in (1, 30) else 3)
|
||||
row = {"ioa": ioa, "type": typ, "value": value, "raw": raw.hex()}
|
||||
if typ in (110, 111, 112):
|
||||
row["qpm"] = raw[-1]
|
||||
elif typ in (15, 37):
|
||||
row["quality"] = raw[4] & 224
|
||||
row["bcr_sequence"] = raw[4] & 31
|
||||
elif typ in (1, 3, 30, 31):
|
||||
row["quality"] = raw[0] & 240
|
||||
else:
|
||||
quality_offset = 1 if typ == 5 else 2 if typ in (9, 11, 34, 35) else 4
|
||||
row["quality"] = raw[quality_offset]
|
||||
if typ in (30, 31, 34, 35, 36, 37):
|
||||
row["time"] = cp56(raw[-7:])
|
||||
rows.append(row)
|
||||
offset += width
|
||||
assert offset == len(data), ("trailing object bytes", data.hex(), offset)
|
||||
return rows
|
||||
|
||||
|
||||
def remote_objects(data):
|
||||
h = header(data)
|
||||
assert h["type"] == 202 and not h["sq"] and len(data) >= 9
|
||||
offset, rows = 9, []
|
||||
for _ in range(h["count"]):
|
||||
assert offset + 5 <= len(data)
|
||||
ioa = int.from_bytes(data[offset:offset + 3], "little")
|
||||
tag, length = data[offset + 3:offset + 5]
|
||||
offset += 5
|
||||
raw = data[offset:offset + length]
|
||||
assert len(raw) == length
|
||||
if tag == 38:
|
||||
assert length == 4
|
||||
value = struct.unpack("<f", raw)[0]
|
||||
elif tag == 4:
|
||||
value = raw.decode("ascii")
|
||||
else:
|
||||
assert tag in (1, 35, 45)
|
||||
assert length == {1: 1, 35: 4, 45: 2}[tag]
|
||||
value = int.from_bytes(raw, "little")
|
||||
rows.append({"ioa": ioa, "tag": tag, "value": value, "raw": raw.hex()})
|
||||
offset += length
|
||||
assert offset == len(data)
|
||||
return rows
|
||||
|
||||
|
||||
def tlv(ioa, tag, value):
|
||||
raw = struct.pack("<f", value) if tag == 38 else value.encode("ascii") if tag == 4 else int(value).to_bytes({1: 1, 35: 4, 45: 2}[tag], "little")
|
||||
return u24(ioa) + bytes((tag, len(raw))) + raw
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, host, port, trace, timeout=5):
|
||||
self.sock = socket.create_connection((host, port), timeout)
|
||||
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
self.sock.settimeout(timeout)
|
||||
self.ns = self.nr = 0
|
||||
self.buffer = bytearray()
|
||||
self.trace = trace
|
||||
self.asdus = []
|
||||
self.timeout = timeout
|
||||
|
||||
def close(self):
|
||||
self.sock.close()
|
||||
|
||||
def send(self, frame, split=False):
|
||||
self.trace.append({"direction": "tx", "time": time.monotonic(), "hex": frame.hex()})
|
||||
if split:
|
||||
for byte in frame:
|
||||
self.sock.sendall(bytes((byte,)))
|
||||
time.sleep(0.002)
|
||||
else:
|
||||
self.sock.sendall(frame)
|
||||
|
||||
def pack(self, data):
|
||||
assert len(data) <= 249
|
||||
frame = bytes((0x68, len(data) + 4)) + struct.pack("<HH", self.ns * 2, self.nr * 2) + data
|
||||
self.ns = (self.ns + 1) & 32767
|
||||
return frame
|
||||
|
||||
def request(self, data, split=False):
|
||||
self.send(self.pack(data), split)
|
||||
|
||||
def frame(self, deadline=None):
|
||||
deadline = deadline or time.monotonic() + self.timeout
|
||||
while len(self.buffer) < 2 or len(self.buffer) < self.buffer[1] + 2:
|
||||
self.sock.settimeout(max(0.001, deadline - time.monotonic()))
|
||||
data = self.sock.recv(4096)
|
||||
if not data:
|
||||
raise EOFError("server closed connection")
|
||||
self.buffer.extend(data)
|
||||
assert self.buffer[0] == 0x68
|
||||
if len(self.buffer) >= 2:
|
||||
assert 4 <= self.buffer[1] <= 253
|
||||
size = self.buffer[1] + 2
|
||||
frame = bytes(self.buffer[:size])
|
||||
del self.buffer[:size]
|
||||
self.trace.append({"direction": "rx", "time": time.monotonic(), "hex": frame.hex()})
|
||||
if not frame[2] & 1:
|
||||
ns, nr = struct.unpack("<HH", frame[2:6])
|
||||
assert ns // 2 == self.nr, ("receive sequence", ns // 2, self.nr)
|
||||
assert nr // 2 <= self.ns
|
||||
self.nr = (self.nr + 1) & 32767
|
||||
self.send(b"\x68\x04\x01\x00" + struct.pack("<H", self.nr * 2))
|
||||
elif frame[2] == 0x43:
|
||||
self.send(b"\x68\x04\x83\x00\x00\x00")
|
||||
return frame
|
||||
|
||||
def start(self, split=False):
|
||||
self.send(b"\x68\x04\x07\x00\x00\x00", split)
|
||||
deadline = time.monotonic() + self.timeout
|
||||
while self.frame(deadline)[2] != 0x0B:
|
||||
assert time.monotonic() < deadline
|
||||
|
||||
def receive(self, predicate, timeout=None):
|
||||
deadline = time.monotonic() + (timeout or self.timeout)
|
||||
observed = []
|
||||
while time.monotonic() < deadline:
|
||||
frame = self.frame(deadline)
|
||||
if not frame[2] & 1:
|
||||
data = frame[6:]
|
||||
observed.append(data)
|
||||
self.asdus.append(data)
|
||||
if predicate(data):
|
||||
return data, observed
|
||||
raise TimeoutError("expected response not received")
|
||||
|
||||
def response(self, typ, cot=None, pn=False):
|
||||
data, _ = self.receive(lambda data: header(data)["type"] == typ)
|
||||
h = header(data)
|
||||
assert h["pn"] == pn, ("PN", data.hex(), pn)
|
||||
assert h["ca"] == 1 and h["oa"] == 17, ("address echo", data.hex())
|
||||
if cot is not None:
|
||||
assert h["cot"] == cot, ("COT", data.hex(), cot)
|
||||
return data
|
||||
Reference in New Issue
Block a user