Files
STM32F4-Base/test/host/iec104_dtu/run_tcp_test.py
T
wandering1 7d1db02164 perf(iec104): 参数区按 17 项真实消费者收窄并接上真实定值模型
104 协议侧参数通道此前镜像了厂商点表的全部 430 条参数(697 槽),
但其中 413 条在本设备上没有任何消费者——104 与设备侧真实定值模型
prot_set 之间零调用,主站改定值只落在无人读的 RAM 镜像里,保护功能
毫无感知。本次按"严格按消费者收窄"口径收口:

可见性以 iec104_dtu_protection_mapping() 语义桥表为唯一判据,只放行
三段过流投退/定值/延时(9 项)、低压与过压定值/延时(4 项)、PT 与
CT 一次/二次额定(4 项)。其余参数在位表枚举层即不可见,主站读取
得到 COT=47 + P/N=1 的显式否定确认,不静默丢弃。values[697]→values[53]、
staged[264]→staged[17],并删除生成式 iec104_source_ranks.h。

桥表接真实源:iec104_serv 的 parameter_read/apply 从 NULL 改为直读
prot_set 与整批原子提交,Q10 量化后一次事务落地,持久化仍由
defaultTask 的脏标志闭环负责。

prot_set 因此出现两个运行时写者(netTask 的 104 与 uiTask 的本地整
定),原"写者靠启动时序串行"的约定失效。加入写事务互斥与 seqlock
序号:四个写入口全部进锁,校验与提前返回一律在 enter 之前;序号卡
奇数连续 8 拍即判保护闭锁,避免自检被永久跳过而静默失去防篡改能力。
锁的安装在 defaultTask 的存储 bring-up 阶段,不在 app_main_init——
后者早于 osKernelInitialize,内核启动前禁止任何 RTOS 创建类 API。

实测:RW_IRAM1 117,304→113,720 B(−3,584 B,89.50%→86.76%);
ER_IROM1 413,392→411,668 B(−1,724 B);iec104_source.o 5,656→2,056 B;
prot_set.o 344→352 B(+8 B,写事务序号与锁句柄)。Keil 构建 0 错误
0 警告;主机侧 prot_set 175/175、iec104_dtu 7/7;真实 TCP 验收
13/13;暂存口径门禁 18 项全通过。

已知边界:模拟器不链接 iec104_serv.c,TCP 验收不覆盖 prot_set 绑定,
板端需实机确认主站写入能反映到本地定值页;17 项中 15 项的出厂默认
值与点表字面量不同,主站读到的是真实模型的值;绑定真实源后定值区
切换一律拒绝(单套活跃值无原子整区事务)。
2026-11-19 15:48:21 +08:00

607 lines
32 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Real-loopback acceptance against the same lvgl_sim binary as UI tests."""
import argparse
import datetime
import hashlib
import json
import math
from pathlib import Path
import re
import socket
import struct
import subprocess
import tempfile
import threading
import time
import traceback
from oracle import ROOT, reference
from wire import Client, asdu, cp56, header, objects, remote_objects, tlv, u24
class Acceptance:
def __init__(self, args):
self.args = args
self.oracle = reference()
self.trace, self.decoded, self.results = [], [], []
self.client = None
def connect(self):
if self.client:
self.client.close()
time.sleep(0.10) # Give the single-owner service one close/poll cycle.
self.client = Client(self.args.host, self.args.port, self.trace)
self.client.start(split=True)
return self.client
def run(self, name, function):
started = time.monotonic()
try:
self.connect()
function()
result = {"name": name, "passed": True}
except Exception as exc:
result = {"name": name, "passed": False, "error": str(exc), "traceback": traceback.format_exc()}
result["seconds"] = time.monotonic() - started
self.results.append(result)
print(("PASS " if result["passed"] else "FAIL ") + name + (": " + result["error"] if not result["passed"] else ""), flush=True)
if self.client:
self.client.close()
self.client = None
def read(self, ioa):
self.client.request(asdu(102, u24(ioa), cot=5))
data, _ = self.client.receive(lambda d: header(d)["cot"] == 5 or header(d)["pn"])
assert not header(data)["pn"], data.hex()
assert header(data)["ca"] == 1 and header(data)["oa"] == 17, data.hex()
rows = objects(data)
assert len(rows) == 1 and rows[0]["ioa"] == ioa
self.decoded.extend(rows)
return rows[0]
def remote_read(self, ioas=(), area=0):
self.client.request(asdu(202, struct.pack("<H", area) + b"".join(map(u24, ioas)), count=len(ioas)))
rows = []
while True:
data = self.client.response(202, 7)
assert int.from_bytes(data[6:8], "little") == area
assert data[8] in (0, 1), ("reserved PI flags", data.hex())
rows.extend(remote_objects(data))
if not data[8] & 1:
break
self.decoded.extend(rows)
assert len({row["ioa"] for row in rows}) == len(rows)
if ioas:
assert set(ioas) == {row["ioa"] for row in rows}
return {row["ioa"]: row for row in rows}
def preset(self, values, area=0, pn=False):
self.client.request(asdu(203, struct.pack("<H", area) + b"\x80" + b"".join(tlv(*v) for v in values), count=len(values)))
return self.client.response(203, 7, pn)
def finish(self, cancel=False, area=0, pn=False):
self.client.request(asdu(203, struct.pack("<H", area) + b"\x00", count=0, cot=8 if cancel else 6))
return self.client.response(203, 9 if cancel else 7, pn)
def test_link_start_stop_testfr_and_prestart(self):
self.client.close()
time.sleep(0.10)
self.client = Client(self.args.host, self.args.port, self.trace)
self.client.send(bytes.fromhex("680443000000"))
while self.client.frame()[2] != 0x83:
pass
self.client.request(asdu(100, u24(0) + bytes((20,))))
# Mature Link.c rejects pre-START I frames as FATAL and closes.
try:
while True:
frame = self.client.frame()
assert frame[2] & 1, ("business published before START", frame.hex())
except EOFError:
pass
self.connect()
self.client.send(bytes.fromhex("680443000000"))
while self.client.frame()[2] != 0x83:
pass
self.client.send(bytes.fromhex("680413000000"))
while self.client.frame()[2] != 0x23:
pass
self.client.send(bytes.fromhex("680443000000"))
while True:
frame = self.client.frame()
assert frame[2] & 1, ("I-frame while STOPPED", frame.hex())
if frame[2] == 0x83:
break
self.client.start()
self.client.request(asdu(201, u24(0)))
self.client.response(201, 7)
def test_gi_exact_set_and_zero_observations(self):
self.client.request(asdu(100, u24(0) + b"\x14"), split=True)
self.client.response(100, 7)
rows = []
while True:
data, _ = self.client.receive(lambda d: header(d)["cot"] in (20, 10))
if header(data)["type"] == 100:
assert header(data)["cot"] == 10 and not header(data)["pn"]
break
assert header(data)["cot"] == 20 and not header(data)["pn"]
rows.extend(objects(data))
self.decoded.extend(rows)
actual = {row["ioa"]: row["type"] for row in rows}
assert len(actual) == len(rows), "duplicate GI objects"
expected = self.oracle["gi"]
assert actual == expected, {"missing": sorted(expected.keys() - actual.keys()), "extra": sorted(actual.keys() - expected.keys()), "wrong_types": [ioa for ioa in actual.keys() & expected.keys() if actual[ioa] != expected[ioa]]}
assert all(row["value"] == 0 and row["quality"] == 128 for row in rows if row["type"] < 100), "source-less observation not zero+IV"
for row in rows:
if row["type"] >= 100:
group, index = divmod(row["ioa"] - 0x8601, 0x20)
expected_value = (200 if index < 4 else 655) if group == 0 else (-10000 if group == 1 else 10000 if group == 2 else 0)
assert row["value"] == expected_value and row["qpm"] == (1, 3, 4, 2)[group], row
def test_counter_exact_set_zero_and_invalid(self):
self.client.request(asdu(101, u24(0) + bytes((5,))))
self.client.response(101, 7)
rows = []
while True:
data, _ = self.client.receive(lambda d: header(d)["type"] in (15, 37, 206, 207, 101))
h = header(data)
assert h["ca"] == 1 and h["oa"] == 17 and not h["pn"]
if h["type"] == 101:
assert h["cot"] == 10
break
assert h["cot"] == 37
rows.extend(objects(data))
self.decoded.extend(rows)
assert len(rows) == len(self.oracle["counters"])
assert {r["ioa"] for r in rows} == set(self.oracle["counters"])
assert all(r["value"] == 0 and r["quality"] & 128 for r in rows)
def test_read_all_runtime_addresses(self):
for ioa, typ in sorted(self.oracle["read"].items()):
row = self.read(ioa)
assert row["type"] == typ, row
assert row["value"] == 0, row
assert row["quality"] == (32 if typ in (5, 7) else 128), row
def test_remote_complete_typed_snapshot(self):
actual = self.remote_read()
expected = self.oracle["remote"]
assert set(actual) == set(expected), {"missing": sorted(expected.keys() - actual.keys()), "extra": sorted(actual.keys() - expected.keys())}
for ioa, (tag, text) in expected.items():
row = actual[ioa]
assert row["tag"] == tag, row
value = text if tag == 4 else float(text) if tag == 38 else int(text)
assert math.isclose(row["value"], value, rel_tol=1e-6, abs_tol=1e-7) if tag == 38 else row["value"] == value, row
def test_area_switch_and_readback(self):
for area in (1, 4, 0):
self.client.request(asdu(200, u24(0) + struct.pack("<H", area)))
self.client.response(200, 7)
self.client.request(asdu(201, u24(0)))
reply = self.client.response(201, 7)
assert len(reply) == 15 and reply[6:9] == u24(0)
assert struct.unpack("<HHH", reply[9:]) == (area, 0, 4)
self.client.request(asdu(200, u24(0) + struct.pack("<H", 5)))
self.client.response(200, 7, True)
self.client.request(asdu(201, u24(0)))
assert self.client.response(201, 7)[9:11] == b"\x00\x00"
def test_typed_preset_commit_cancel_readback(self):
addresses = (0x8841, 0x8842, 0x8843, 0x8027)
before = self.remote_read(addresses)
change = [(0x8841, 1, 1), (0x8842, 38, 2.5), (0x8843, 38, 0.75), (0x8027, 38, 90.0)]
original = [(ioa, before[ioa]["tag"], before[ioa]["value"]) for ioa in addresses]
try:
self.preset(change)
assert self.remote_read(addresses) == before, "preset leaked into active values"
self.finish()
after = self.remote_read(addresses)
assert all(after[ioa]["tag"] == tag and after[ioa]["value"] == value for ioa, tag, value in change)
self.connect()
assert self.remote_read(addresses) == after, "TCP reconnect lost committed RAM values"
self.preset(original)
self.connect()
self.remote_read(addresses)
self.finish(pn=True)
assert self.remote_read(addresses) == after, "disconnected stage became active"
self.preset(original)
self.finish(cancel=True)
assert self.remote_read(addresses) == after, "cancel published stage"
self.finish(pn=True)
finally:
self.preset(original)
self.finish()
assert self.remote_read(addresses) == before
def test_unknown_and_bad_typed_requests(self):
self.client.request(asdu(102, u24(0xFFFFFF), cot=5))
self.client.response(102, 47, True)
for ioa in (0xFFFFFF, 0x9601, 0x8820, 0x8823):
self.client.request(asdu(202, b"\x00\x00" + u24(ioa)))
self.client.response(202, 47, True)
for value in ([(0x8841, 1, 2)], [(0x8842, 45, 8)], [(0x8842, 38, float("nan"))]):
self.preset(value, pn=True)
self.finish(cancel=True)
def test_maximum_apdu_and_coalesced_frames(self):
# Structurally valid 249-byte ASDU, unknown IOA, String235. Business must respond.
request = asdu(203, b"\x00\x00\x80" + u24(0xFFFFFF) + bytes((4, 235)) + b"X" * 235)
frame = self.client.pack(request)
assert len(frame) == 255 and frame[1] == 253 and len(request) == 249
self.client.send(frame, split=True)
reply = self.client.response(203, 47, True)
assert reply
self.finish(cancel=True)
first = self.client.pack(asdu(201, u24(0)))
second = self.client.pack(asdu(201, u24(0)))
self.client.send(first + second)
self.client.response(201, 7)
self.client.response(201, 7)
def command(self, value, select=False, ioa=0x6002, pn=False):
self.client.request(asdu(46, u24(ioa) + bytes((value | (128 if select else 0),))))
return self.client.response(46, 7, pn)
def position(self):
return tuple(self.read(ioa)["value"] for ioa in (0x1001, 0x0011, 0x0028))
def denied(self, value, select=False, ioa=0x6002):
"""A refused command is answered COT 7 with P/N=1 and leaves the state alone."""
data = self.command(value, select=select, ioa=ioa, pn=True)
assert header(data)["cot"] == 7, ("refusal must echo COT 7", data.hex())
return data
def expect_no_completion(self, seconds=0.3):
"""A refused command must not be followed by ACT_TERM (COT 10) nor return info (COT 11)."""
start = len(self.client.asdus)
deadline = time.monotonic() + seconds
try:
while time.monotonic() < deadline:
self.client.frame(deadline)
except (socket.timeout, TimeoutError):
pass
for data in self.client.asdus[start:]:
h = header(data)
assert not (h["type"] == 46 and h["cot"] == 10), ("unexpected ACT_TERM", data.hex())
assert h["cot"] != 11, ("unexpected return info", data.hex())
def test_sbo_order_and_refusal_semantics(self):
"""Every command is refused in the skeleton build: COT 7 + P/N=1, state untouched.
The DTU command table still declares SELECT_EXECUTE points and the vendor module
still enforces SBO ordering and address checking; those paths are exercised here
through the refusal branch (COT 46 for a wrong common address, P/N=1 everywhere),
but no command may ever reach COT 10 (ACT_TERM) or COT 11 (return info).
"""
initial = self.position()
self.denied(2)
assert self.position() == initial
self.denied(2, select=True)
assert self.position() == initial
self.denied(1)
assert self.position() == initial
self.connect() # Reconnect must not turn a refused command into an accepted one.
self.denied(1, select=True)
self.denied(1)
assert self.position() == initial
# A wrong common address is still rejected by the command module as UNKNOWN_IOA.
self.client.request(asdu(46, u24(0x6002) + bytes((2 | 128,)), ca=2))
reply, _ = self.client.receive(lambda d: header(d)["type"] == 46)
assert header(reply)["cot"] == 46 and header(reply)["pn"]
# Direct-execute step and setpoint points take the same refusal path.
self.denied(1, ioa=0x6101)
self.denied(1, ioa=0x6301)
assert self.position() == initial
self.expect_no_completion()
self.denied(2)
self.expect_no_completion()
def test_clock_is_device_only_and_no_command_completes(self):
host_delta = time.time() - time.monotonic()
initial = self.position()
self.denied(2, select=True)
# Year2035 is deliberately far from the host clock; no OS clock API is used.
stamp = struct.pack("<HBBBBB", 12345, 22, 11, 17, 6, 35)
self.client.request(asdu(103, u24(0) + stamp))
self.client.response(103, 7)
self.client.request(asdu(103, u24(0) + bytes(7), cot=5))
reply = self.client.response(103, 5)
actual_time = cp56(reply[-7:])
assert not actual_time["invalid"] and not actual_time["summer"]
requested_time = datetime.datetime(2035, 6, 17, 11, 22, 12, 345000)
assert 0 <= (datetime.datetime.fromisoformat(actual_time["iso"]) - requested_time).total_seconds() < 2
time.sleep(0.15)
self.client.request(asdu(103, u24(0) + bytes(7), cot=5))
later = cp56(self.client.response(103, 5)[-7:])
assert 0.1 <= (datetime.datetime.fromisoformat(later["iso"]) - datetime.datetime.fromisoformat(actual_time["iso"])).total_seconds() < 2
assert abs((time.time() - time.monotonic()) - host_delta) < 1.0, "host wall clock changed"
# A far-future device clock must not expire anything into a completion.
self.denied(2)
self.denied(1, select=True)
time.sleep(self.args.sbo_timeout + 0.3)
self.denied(1)
self.expect_no_completion()
assert self.position() == initial, "refused command changed state"
# ---- Type 110/111/112/113 standard parameter path -------------------------
#
# This is the IEC104_Parameter module, NOT IEC104_RemoteParameter (Types
# 200..203, covered above). The two are separate vendor modules with
# different wire layouts and different acceptance rules:
# 110 normalized value = IOA(3) + int16(2) + QPM(1)
# 111 scaled value = IOA(3) + int16(2) + QPM(1)
# 112 short float = IOA(3) + float32(4) + QPM(1)
# 113 activation = IOA(3) + QPA(1)
# QPM's low six bits select the parameter kind (KPA), which must match the
# point table row; that is what makes "wrong KPA" a per-row rejection rather
# than a global one.
def standard_params(self):
"""GI snapshot restricted to standard parameter objects (type >= 100).
Cost note (measured 2026-11-18, must be respected when editing this test):
one full GI here is ~126 I-frames / ~3.9 s wall clock, because the 120
standard parameter rows cannot be coalesced - they span types 110/111/112
and each ASDU carries exactly one object. Call this only as often as the
assertion genuinely needs; every extra call costs ~4 s in the manual gate.
"""
self.client.request(asdu(100, u24(0) + b"\x14"))
self.client.response(100, 7)
rows = []
while True:
data, _ = self.client.receive(lambda d: header(d)["cot"] in (20, 10))
if header(data)["type"] == 100:
assert header(data)["cot"] == 10
break
rows.extend(objects(data))
self.decoded.extend(rows)
return {row["ioa"]: row for row in rows if row["type"] >= 100}
def param_load(self, type_id, ioa, value, kpa, test=False, cot=6):
payload = struct.pack("<f", value) if type_id == 112 else struct.pack("<h", value)
self.client.request(asdu(type_id, u24(ioa) + payload + bytes((kpa,)),
cot=cot | (0x80 if test else 0)))
data, _ = self.client.receive(lambda d: header(d)["type"] == type_id)
return data, header(data)
def param_activate(self, ioa, qpa, test=False, cot=6):
self.client.request(asdu(113, u24(ioa) + bytes((qpa,)), cot=cot | (0x80 if test else 0)))
data, _ = self.client.receive(lambda d: header(d)["type"] == 113)
return data, header(data)
def test_standard_parameter_load_110_111_112(self):
# Point table geometry (iec104_dtu_table.c / iec104_source.c):
# group 0 (0x8601..): kind THRESHOLD(1); index>=4 is type 110, else 111
# group 1 (0x8621..): kind LOW_LIMIT(3), type 111
# group 2 (0x8641..): kind HIGH_LIMIT(4), type 111
# group 3 (0x8661..): kind SMOOTHING(2), type 112
before = self.standard_params()
assert before[0x8601]["type"] == 111 and before[0x8601]["value"] == 200
assert before[0x8605]["type"] == 110 and before[0x8605]["value"] == 655
assert before[0x8661]["type"] == 112 and before[0x8661]["value"] == 0.0
# --- accepted LOADs, one per type -------------------------------------
data, h = self.param_load(110, 0x8605, 700, 1)
assert h["cot"] == 7 and not h["pn"], ("110 LOAD must be accepted", data.hex())
assert objects(data)[0]["value"] == 700, "positive CON must carry the stored value"
data, h = self.param_load(111, 0x8621, -9999, 3)
assert h["cot"] == 7 and not h["pn"], ("111 LOAD must be accepted", data.hex())
data, h = self.param_load(112, 0x8661, 12.5, 2)
assert h["cot"] == 7 and not h["pn"], ("112 LOAD must be accepted", data.hex())
# --- rejection: unknown IOA / unknown CA / unknown COT ----------------
# These use the standard error causes and echo the request bytes verbatim,
# because no point row matched so no running value could be frozen.
data, h = self.param_load(111, 0x9999, -5, 1)
assert h["cot"] == 47 and h["pn"], ("unknown IOA -> COT 47", data.hex())
data, h = self.param_load(111, 0x8601, -5, 1, cot=3)
assert h["cot"] == 45 and h["pn"], ("unknown COT -> COT 45", data.hex())
# --- rejection: KPA (kind) must match the row -------------------------
data, h = self.param_load(111, 0x8601, -5, 3)
assert h["cot"] == 7 and h["pn"], ("kind mismatch must be a negative CON", data.hex())
assert objects(data)[0]["value"] == -5, \
"address matched but kind did not, so no running value was frozen: reply echoes the request"
# --- rejection: type id must match the row ----------------------------
data, h = self.param_load(110, 0x8601, -5, 1)
assert h["cot"] == 7 and h["pn"], ("type mismatch must be a negative CON", data.hex())
assert objects(data)[0]["value"] == -5, "type mismatch likewise echoes the request"
# --- rejection: range/content per group -------------------------------
# group 0 requires a non-negative value, so -1 is refused on a 110 row.
# NOTE the contrast with the two cases above: the row DID match here, so
# the module froze the running value and the negative CON carries 700
# (the current value), not the refused request value. Getting this
# backwards is the easiest way to write a test that passes for the wrong
# reason, so both shapes are asserted explicitly.
data, h = self.param_load(110, 0x8605, -1, 1)
assert h["cot"] == 7 and h["pn"], ("negative on unsigned-style row must be refused", data.hex())
assert objects(data)[0]["value"] == 700, \
"row matched so the running value is frozen: negative CON carries the CURRENT value, not the request"
data, h = self.param_load(111, 0x8621, -10001, 3) # below LOW_LIMIT's own floor
assert h["cot"] == 7 and h["pn"], "below low limit must be refused"
data, h = self.param_load(111, 0x8641, 10001, 4) # above HIGH_LIMIT's own ceiling
assert h["cot"] == 7 and h["pn"], "above high limit must be refused"
data, h = self.param_load(112, 0x8661, 61.0, 2) # smoothing is 0..60 s
assert h["cot"] == 7 and h["pn"], "float above 60 must be refused"
data, h = self.param_load(112, 0x8661, float("nan"), 2)
assert h["cot"] == 7 and h["pn"], "NaN must be refused before it can poison the store"
# --- TEST bit: accepted, but must not mutate --------------------------
data, h = self.param_load(111, 0x8621, -100, 3, test=True)
assert h["cot"] == 7 and not h["pn"], ("TEST LOAD must be accepted", data.hex())
# --- ONE readback verifies everything above at once -------------------
# Single GI, deliberately: each call costs ~4 s (see standard_params).
# It must show the three accepted values, prove the six refusals and the
# TEST request moved nothing, and prove an untouched row stayed put.
after = self.standard_params()
assert after[0x8605]["value"] == 700, "110 LOAD did not reach the value store"
assert after[0x8621]["value"] == -9999, "111 LOAD did not reach the value store, or a refusal/TEST leaked"
assert after[0x8661]["value"] == 12.5, "112 LOAD did not reach the value store, or a refusal leaked"
assert after[0x8601]["value"] == 200, "untouched row must not move"
assert after[0x8641]["value"] == 10000, "high-limit row was mutated by a refusal"
assert after[0x8622]["value"] == -10000, "TEST LOAD mutated a sibling row in its group"
# --- restore so the run is repeatable ---------------------------------
for type_id, ioa, value, kpa in ((110, 0x8605, 655, 1), (111, 0x8621, -10000, 3),
(112, 0x8661, 0.0, 2)):
data, h = self.param_load(type_id, ioa, value, kpa)
assert h["cot"] == 7 and not h["pn"], ("restore failed", data.hex())
# A second GI is the only way to prove the restore actually landed; it is
# worth the ~4 s because a silent restore failure would poison every later
# GI-based test in this suite.
assert self.standard_params() == before, "restore did not return the exact initial snapshot"
def test_standard_parameter_activation_113(self):
# QPA selects the activation flavour. Only QPA=3 (cyclic transmission) is
# enabled by default; QPA=1/2 are gated behind config extensions that this
# build does not turn on, so they must be refused rather than silently
# accepted. This distinction is the point of the test.
data, h = self.param_activate(0, 3)
assert h["cot"] == 7 and not h["pn"], ("QPA=3 activate must be accepted", data.hex())
data, h = self.param_activate(0, 3, cot=8)
assert h["cot"] == 9 and not h["pn"], ("QPA=3 deactivate must be confirmed with COT 9", data.hex())
# A non-zero IOA with QPA=3 reaches the application, which refuses it
# because periodic transmission is addressed by IOA 0 only.
data, h = self.param_activate(0x1234, 3)
assert h["cot"] == 7 and h["pn"], ("QPA=3 with IOA!=0 must be refused", data.hex())
for qpa in (1, 2):
data, h = self.param_activate(0, qpa)
assert h["cot"] == 7 and h["pn"], \
("QPA=%d must be refused: its config extension is off" % qpa, data.hex())
# TEST bit is accepted and must not alter the schedule.
data, h = self.param_activate(0, 3, test=True)
assert h["cot"] == 7 and not h["pn"], ("TEST activate must be accepted", data.hex())
# Error causes.
data, h = self.param_activate(0, 3, cot=3)
assert h["cot"] == 45 and h["pn"], ("unknown COT -> COT 45", data.hex())
self.client.request(asdu(113, u24(0) + bytes((3,)), ca=9))
data, _ = self.client.receive(lambda d: header(d)["type"] == 113)
h = header(data)
assert h["cot"] == 46 and h["pn"], ("unknown CA -> COT 46", data.hex())
# Leave the periodic scan off so it cannot perturb anything after us.
data, h = self.param_activate(0, 3, cot=8)
assert h["cot"] == 9 and not h["pn"], ("final deactivate failed", data.hex())
READY_PATTERN = re.compile(r"^\[iec104\] READY address=(?P<address>\S+) port=(?P<port>\d+) ca=(?P<ca>\d+) mode=(?P<mode>\S+)\s*$")
class ReadyWatcher:
"""转发模拟器 stdout 到日志文件,并从中取回 READY 行里的实际监听端口。
为什么不靠轮询端口探活(2026-11-18 改):
1) 探活的每一次 connect 都会被固件当成一次真实接入,白白吃掉一次 accept,
让 STOP 摘要里的 connections 多算一次,也让单连接模型的会话序列多一段;
2) 端口固定时探活"成功"只说明有人在这个号上监听,并行构建或端口被别的进程
占住时会把真正的失败伪装成通过;
3) READY 行里的 port 是固件 bind 成功后回报的 bound_port,--iec104-port 0 时
这正是唯一能拿到实际端口的途径(simulator/README.md 明确要求读它)。
日志必须保留:它带着 START/READY/STOP 摘要,是人工复核的证据面。
"""
def __init__(self, log):
self.log = log
self.ready = threading.Event()
self.port = None
self.ca = None
self.address = None
self.mode = None
self.error = None
self._thread = threading.Thread(target=self._pump, name="sim-stdout", daemon=True)
def start(self, stream):
self._stream = stream
self._thread.start()
def _pump(self):
try:
for line in self._stream:
self.log.write(line)
self.log.flush()
match = READY_PATTERN.match(line)
if match and not self.ready.is_set():
self.port = int(match.group("port"))
self.ca = int(match.group("ca"))
self.address = match.group("address")
self.mode = match.group("mode")
self.ready.set()
except Exception as exc: # 读管道失败也要让主线程拿到结论
self.error = exc
self.ready.set()
def join(self, timeout=5.0):
self._thread.join(timeout)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--exe", type=Path)
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=24040)
# 这里是"等一个不可能发生的 vendor 超时"的窗口,不是真实超时值。
# 所有命令都被否定确认(COT 7 + P/N=1),库里根本不会进入选择/执行事务,
# 因此 select(30s)/decision(15s)/execute(60s) 三个计时器都不会被启动。
# 保留 2s 只是给"迟到的 ACT_TERM"留一个可观测窗口;若将来命令被受理,
# 必须调回 30 或更大,否则这条用例会在超时真正到期前就宣告通过(假绿)。
parser.add_argument("--sbo-timeout", type=float, default=2)
parser.add_argument("--output", type=Path, default=ROOT / "ci-artifacts" / "iec104-tests")
parser.add_argument("--only", default="")
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
suite = Acceptance(args)
process, log, watcher = None, None, None
binary = {}
with tempfile.TemporaryDirectory(prefix="iec104-dtu-") as cwd:
try:
if args.exe:
exe = args.exe.resolve()
binary = {"path": str(exe), "sha256": hashlib.sha256(exe.read_bytes()).hexdigest()}
log = (args.output / "simulator.log").open("w", encoding="utf-8")
process = subprocess.Popen(
[str(exe), "--iec104", "--iec104-headless", "--iec104-port", str(args.port), "--iec104-duration", "180"],
cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=1)
watcher = ReadyWatcher(log)
watcher.start(process.stdout)
if not watcher.ready.wait(15.0):
raise TimeoutError("simulator did not print READY within 15s")
if watcher.error is not None:
raise RuntimeError("simulator stdout plumbing failed: " + str(watcher.error))
if watcher.port is None:
raise RuntimeError("simulator exited before listen: " + str(process.poll()))
# 用固件回报的 bound_port 连接,而不是我们请求的那个号:--iec104-port 0 时
# 请求号无意义,且这样连等于断言"READY 里说的端口真的在听"。
args.port = watcher.port
binary["ready"] = {"address": watcher.address, "port": watcher.port, "ca": watcher.ca, "mode": watcher.mode}
names = ["test_link_start_stop_testfr_and_prestart", "test_gi_exact_set_and_zero_observations", "test_counter_exact_set_zero_and_invalid", "test_read_all_runtime_addresses", "test_remote_complete_typed_snapshot", "test_area_switch_and_readback", "test_typed_preset_commit_cancel_readback", "test_unknown_and_bad_typed_requests", "test_standard_parameter_load_110_111_112", "test_standard_parameter_activation_113", "test_maximum_apdu_and_coalesced_frames", "test_sbo_order_and_refusal_semantics", "test_clock_is_device_only_and_no_command_completes"]
for name in names:
if not args.only or args.only in name:
suite.run(name, getattr(suite, name))
finally:
if process and process.poll() is None:
process.terminate()
process.wait(timeout=10)
# 先收干 stdout 再关日志:进程被 terminate 后管道里可能还有最后几行
# (含 STOP 摘要),丢了就等于丢掉唯一的人工复核证据。
if watcher:
watcher.join(5.0)
if process and process.stdout:
process.stdout.close()
if log:
log.close()
report = {"created": datetime.datetime.now(datetime.timezone.utc).isoformat(), "binary": binary, "reference": suite.oracle, "results": suite.results,
"limitations": ["Service-side short-write/WOULD_BLOCK requires separate transport unit evidence", "No-physical-DO requires source/build audit in addition to TCP feedback", "TCP process is terminated by harness after tests"]}
(args.output / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
(args.output / "wire.json").write_text(json.dumps(suite.trace, indent=2), encoding="utf-8")
(args.output / "objects.json").write_text(json.dumps(suite.decoded, indent=2), encoding="utf-8")
return 0 if suite.results and all(row["passed"] for row in suite.results) else 1
if __name__ == "__main__":
raise SystemExit(main())