"""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("= 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("> 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("= 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("= 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("