#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ M-NET Reader v1.0.0 - read-only logger/decoder for Mitsubishi City Multi M-NET (built by Tab for Avrumy, Oct 2026). python mnet_reader.py ports list serial ports (PAC-USCMS-MN-1 = USB VID 1293 / PID 3201) python mnet_reader.py listen --port COM5 LISTEN-ONLY: log every frame, never transmit (default mode) python mnet_reader.py decode FILE [FILE...] offline: .MT (SD card), .pcapng/.pcap (USBPcap/usbmon), serial-monitor text/binary logs, this tool's .mnetlog files python mnet_reader.py read --port COM5 --addr 51 --src XX --i-understand-this-transmits ACTIVE READ (off unless asked): only Maintenance Tool's own read/monitor requests, hard-coded allowlist, slow rate python mnet_reader.py run --config config.json always-on service (Raspberry Pi / Linux / Windows): listen (or allowed read), decode, buffer on disk, upload python mnet_reader.py models PUHY-P72 search the bundled model tables python mnet_reader.py selftest run built-in checks (no hardware) WHAT IS VERIFIED vs INFERRED (be honest; nothing here has touched a real M-NET bus yet): VERIFIED (real-equipment evidence): - Bus frame layout [BD cmd/BE rsp][src][dst][3F|7F][len][payload][check], check = -(sum of all prior bytes) & 0xFF, 9600 baud 8E1 on the wire, receiver ACK 0x06 - Len Shustek's 2015 sniffer on a real system (GPLv3 repo LenShustek/M-NET-Sniffer; facts only used here, no code copied). His real frame BD FB 02 3F 03 35 03 22 AA passes. - Indoor reads 2D01/2D81 (on/off), 2D02/2D82 (mode 7 heat, 8 cool, 0D fan), 2501/2581 (setpoint), 350322/358322 (room temp), BCD tenths of degC - decoded by Shustek on real units. FROM MITSUBISHI'S OWN SOFTWARE (static reading of the public Maintenance Tool v5.53 installer, not run on hardware): - PAC-USCMS-MN-1 is a USB CDC serial port (VID_1293 PID_3201 in its driver INF); Maintenance Tool opens it at 9600 8N1 and sends the frame as uppercase ASCII hex after STX (0x02) with a 2-hex ASCII-sum check and a line end. - Per-model monitor tables (which read command, which reply byte, which conversion) and UNITATR.TBL (which table belongs to which unit attribute/model code); error code texts (ERRCODE.TBL). Bundled in mnet_data.json.gz. INFERRED (needs one real capture to confirm; each is a setting or an isolated function so it can be fixed fast): - What the converter sends BACK to the PC (format of its lines) and whether it passes on traffic that is not its own (listen-only may show nothing at all with this converter - that is still useful to know). - Reply byte offsets: value starts at (reply header length + pos - 1). Matches Shustek's real 2-byte and 3-byte indoor replies against the tables (2581 pos 1, 358322 pos 1); not yet confirmed on outdoor 39FE.. pages. - Conversions other than F1/F4 (temp), F2/E1 (temp difference), F3 (pressure, kgf/cm2), 02 (BCD), 05 (hex). - Byte layout of the unit-attribute reply 2184 used for auto-identification (searched, not assumed). - Address-range kinds (IC 1-50, OC/BC 51-100, ME remote 101-200, central 0/201-250) = Mitsubishi addressing convention, used only as a fallback label. SAFETY: - listen / decode / run(default) NEVER write a byte to the port (the port object is wrapped so write() raises). - read mode: only BD frames whose payload is EXACTLY one of ALLOWLIST below (read/monitor commands found in the Maintenance Tool tables + unit-attribute 2104, version 3577, error list 3900), >= 3 s apart, one at a time. Everything else is refused in code. Write/forced/test-run classes 01 05 0D 11 15 19 can never be sent. - A new node on M-NET can raise 6607/6608 on remotes until power-cycle (CoolAutomation support article). Listen mode adds no node and claims no address. Read mode uses the converter exactly as Maintenance Tool does, with the source address YOU give (copy it from a capture of Maintenance Tool); there is no default. """ import argparse, base64, binascii, csv, datetime as _dt, gzip, io, json, os, queue, re, sqlite3, struct, sys import threading, time, unicodedata, urllib.request, urllib.error def readfile(path): with open(path, "rb") as f: return f.read() VERSION = "1.0.0" CONVERTER_VID, CONVERTER_PID = 0x1293, 0x3201 # from Mitsubishi's PAC-USCMS-MN-1 driver INF (verified) TYPES = {0xBD: "cmd", 0xBE: "rsp", 0x3D: "cmd3D", 0x3E: "rsp3E"} # 3D/3E: seen in tool parser, use unclear FLAGS = (0x3F, 0x7F) READ_CLASSES = frozenset({0x21, 0x25, 0x29, 0x2D, 0x31, 0x35, 0x39}) WRITE_CLASSES = frozenset({0x01, 0x05, 0x09, 0x0D, 0x11, 0x15, 0x19}) MAX_PAYLOAD = 64 MIN_READ_INTERVAL_S = 3.0 # Hard-coded. Built 2026-10-27 from every read command (MTX) in the v5.53 model tables, classes 21/25/29/2D/31/35/39 # only, minus 397E87/397E88 (pre-error data group SET/CLEAR - not reads) and minus anything response-shaped, # plus 2104 (unit attribute), 3577 (software version), 3900 (error code/history). Class 19 (mixes memory reads with # resets) is excluded entirely. Editing the data file cannot widen this. ALLOWLIST = frozenset(""" 2104 2501 2D01 2D02 2D1B 3102 310A01 3114 3170 35000900 35001000 35010600 350322 350325 350326 35100600 3511 3513 3517 3577 3900 397E00 397E01 397E02 397E03 397E04 397E05 397E06 397E07 397E08 397E09 397E0A 397E10 397E11 397E13 397E14 397E15 397E30 397E40 397E4000 397E41 397E42 397E43 397E50 397E5000 397E51 397E5100 397E5200 397E5300 397E5400 397E5500 397E60 397E80 397E8000 397E8002 397E81 397E82 397E83 397E8300 397E84 397E8400 397E85 397E8500 397E8600 397E8700 397E8800 397E89 397E8900 397E8A00 397E8B00 397E8C00 397E8D00 397E8E00 397E90 397E9000 397E91 397E9100 397E92 397E9200 397E93 397E9300 397E94 397E9400 397E95 397E9500 397E96 397E9600 397E9700 397E9800 397E9900 397E9A00 397EE0""".split()) DENY_EXACT = frozenset({"397E87", "397E88"}) COMMAND_NAMES = { # from MainteToolNetLibrary MnetSendCommands (subset; request form) "2100": "connection info", "2103": "group", "2104": "unit attribute", "2108": "capacity", "2501": "setpoint", "2D01": "on/off", "2D02": "mode", "2D0E": "fan speed", "3500": "refrigerant temp", "3501": "subcool", "350322": "room temp", "350326": "return temp", "3508": "compressor start count", "3509": "operation time", "3511": "operation status", "355C": "unit type name", "355E": "serial number", "3577": "software version", "3900": "error code/history", "397E": "maintenance page", "397E84": "compressor run time", "397EE0": "error history (ch)", "397EF0": "model id", "0D01": "SET on/off", "0D02": "SET mode", "0501": "SET temperature", "0D0E": "SET fan", "1904": "RESET abnormality", "1905": "CLEAR error history", "111A": "FORCE compressor Hz", "110A": "FORCE LEV", "1119": "FORCE valve", } GLOSS = [ # Japanese table notes -> rough English (machine gloss, for reading only) ("高圧圧力", "high pressure"), ("低圧圧力", "low pressure"), ("高圧", "high pressure"), ("低圧", "low pressure"), ("圧力", "pressure"), ("センサ", "sensor"), ("センサ", "sensor"), ("圧縮機", "compressor"), ("吐出", "discharge"), ("吸入", "suction"), ("外気", "outdoor air"), ("室外", "outdoor"), ("室内", "indoor"), ("熱交換器", "heat exchanger"), ("熱交換", "heat exchange"), ("ガス管", "gas pipe"), ("ガス管", "gas pipe"), ("液管", "liquid pipe"), ("出口", "outlet"), ("入口", "inlet"), ("温度", "temp"), ("凝縮", "condensing"), ("蒸発", "evaporating"), ("飽和", "saturation"), ("過冷却", "subcool"), ("バイパス", "bypass"), ("バイパス", "bypass"), ("放熱板", "heatsink"), ("電磁弁", "solenoid valve"), ("四方弁", "4-way valve"), ("膨張弁", "expansion valve"), ("開度", "opening"), ("周波数", "frequency"), ("運転", "operation"), ("ファン", "fan"), ("ファン", "fan"), ("回転数", "rpm"), ("母線電圧", "bus voltage"), ("電流", "current"), ("電圧", "voltage"), ("制御", "control"), ("モード", "mode"), ("モード", "mode"), ("目標", "target"), ("油", "oil"), ("液面", "liquid level"), ("給気", "supply air"), ("還気", "return air"), ("吸込", "intake"), ("湿度", "humidity"), ("異常", "fault"), ("接点入力", "contact input"), ("デマンド", "demand"), ("デマンド", "demand"), ("除霜", "defrost"), ("容量", "capacity"), ("能力", "capacity"), ] def gloss(s): s = unicodedata.normalize("NFKC", s or "") for jp, en in GLOSS: s = s.replace(unicodedata.normalize("NFKC", jp), " " + en + " ") return re.sub(r"\s+", " ", s).strip() # --------------------------------------------------------------------------------------------- frames def fcc(bs): return (-sum(bs)) & 0xFF def build_frame(src, dst, payload, typ=0xBD): p = bytes(payload) fr = bytes([typ, src & 0xFF, dst & 0xFF, 0x3F, len(p)]) + p return fr + bytes([fcc(fr)]) def converter_line(frame, eol=b"\r\n"): """PC -> PAC-USCMS-MN-1 line as Maintenance Tool builds it (decompiled MNConverter.dll): STX + hex text + 2-hex ASCII-sum check + line end. The line end is configurable because it is NOT yet confirmed on a capture.""" t = frame.hex().upper().encode() return b"\x02" + t + ("%02X" % ((-sum(t)) & 0xFF)).encode() + eol def frame_dict(fr, t=None, enc="binary", wrap=None, stream=""): p = fr[5:5 + fr[4]] return {"t": t, "type": fr[0], "src": fr[1], "dst": fr[2], "flags": fr[3], "payload": bytes(p), "fcc_ok": True, "enc": enc, "wrap_ok": wrap, "stream": stream, "hex": fr.hex().upper()} _HEXRUN = re.compile(rb"\x02?([0-9A-Fa-f]{12,})") def _typed_at(b, i, strict=True): if b[i] not in TYPES or i + 6 > len(b): return 0 if strict and b[i + 3] not in FLAGS: return 0 ln = b[i + 4] end = i + 5 + ln if ln > MAX_PAYLOAD or end >= len(b) or fcc(b[i:end]) != b[end]: return 0 return end + 1 - i def scan(buf, strict=True): """Find checksum-valid M-NET frames anywhere in a byte buffer: ASCII-hex (converter style, with or without STX and wrapper check) and raw binary (UART/bus style). Returns [(start, end, frame_bytes, enc, wrap_ok)].""" out, covered = [], [] for m in _HEXRUN.finditer(buf): h = m.group(1) if len(h) % 2: h = h[:-1] try: b = binascii.unhexlify(h) except binascii.Error: continue base = m.start(1) i, found = 0, False while i < len(b) - 5: n = _typed_at(b, i, strict=False) if n: fr = b[i:i + n] txt = h[2 * i:2 * (i + n)].upper() wrap = None nxt = h[2 * (i + n):2 * (i + n) + 2] if len(nxt) == 2: want = int(nxt, 16) wrap = want in ((-sum(txt)) & 0xFF, (-sum(txt) - 2) & 0xFF, (-sum(h[2 * i:2 * (i + n)])) & 0xFF) out.append((base + 2 * i, base + 2 * (i + n) + (2 if wrap else 0), fr, "ascii", wrap)) found = True i += n else: i += 1 if not found and len(b) >= 6: # converter may drop the type byte: test both and require the check ln = b[3] if ln <= MAX_PAYLOAD and 5 + ln <= len(b): for typ in (0xBD, 0xBE): cand = bytes([typ]) + b[:4 + ln] if fcc(cand) == b[4 + ln]: out.append((base, base + 2 * (5 + ln), cand + b[4 + ln:5 + ln], "ascii-notype", None)) found = True break if found: covered.append((m.start(), m.end())) i = 0 while i < len(buf) - 5: if any(a <= i < z for a, z in covered): i += 1 continue n = _typed_at(buf, i, strict) if n: out.append((i, i + n, bytes(buf[i:i + n]), "binary", None)) i += n else: i += 1 out.sort(key=lambda x: x[0]) return out class Extractor: """Incremental scanner for a live byte stream.""" def __init__(self, stream="", strict=True, keep=600): self.buf, self.stream, self.strict, self.keep = bytearray(), stream, strict, keep self.bytes_in = 0 def feed(self, data, t): self.buf += data self.bytes_in += len(data) hits = scan(bytes(self.buf), self.strict) frames = [frame_dict(fr, t, enc, wrap, self.stream) for (_, _, fr, enc, wrap) in hits] if hits: del self.buf[:hits[-1][1]] if len(self.buf) > self.keep: del self.buf[:len(self.buf) - self.keep] return frames # --------------------------------------------------------------------------------------------- data tables _DATA = None def data_path(): for d in [getattr(sys, "_MEIPASS", None), os.path.dirname(os.path.abspath(sys.executable)) if getattr( sys, "frozen", False) else None, os.path.dirname(os.path.abspath(__file__)), os.getcwd(), "/opt/mnet-reader"]: if d and os.path.exists(os.path.join(d, "mnet_data.json.gz")): return os.path.join(d, "mnet_data.json.gz") return None def load_data(): global _DATA if _DATA is None: p = data_path() if not p: _DATA = {"tables": {}, "unitatr": [], "errcodes": {}, "missing": True} else: with gzip.open(p, "rt", encoding="utf-8") as f: _DATA = json.load(f) return _DATA ATTR_KIND = {"83": "outdoor", "9B": "outdoor", "B0": "outdoor", "B1": "outdoor", "B2": "outdoor", "80": "indoor", "81": "indoor", "C0": "indoor", "C1": "indoor", "84": "bc", "A6": "bc", "A7": "bc", "A8": "bc", "11": "central", "21": "central", "7F": "interface"} def kind_from_addr(a): """Mitsubishi City Multi addressing convention (fallback label only).""" if a == 0 or 201 <= a <= 250: return "central" if 1 <= a <= 50: return "indoor" if 51 <= a <= 100: return "outdoor/bc" if 101 <= a <= 200: return "remote" if a >= 0xFB: return "tool" return "unknown" def norm_model(s): return re.sub(r"[^A-Z0-9]", "", unicodedata.normalize("NFKC", s or "").upper()) def expand_titles(title): """'PUHY-P72/96YLMU-A (..)' -> ['PUHYP72YLMUA', 'PUHYP96YLMUA']""" out = [] t = unicodedata.normalize("NFKC", title).upper() for m in re.finditer(r"([A-Z]{2,6}-?\(?[A-Z]*\)?[A-Z]?)(\d{2,3}(?:/\d{2,3})*)([A-Z0-9\-\(\)/]*)", t): pre, nums, suf = m.groups() for n in nums.split("/"): out.append(norm_model(pre + n + suf)) return out def find_tables(query, limit=15): d = load_data() q = norm_model(query) if q.upper() in (k.upper() for k in d["tables"]): return [(k, d["tables"][k]["title"]) for k in d["tables"] if k.upper() == q.upper()] res = [] for k, t in d["tables"].items(): names = [] for ti in t.get("title", []): names += expand_titles(ti) score = 0 for n in names: if n == q: score = max(score, 3) elif n.startswith(q) or q.startswith(n): score = max(score, 2) elif q in n: score = max(score, 1) if score: res.append((score, k, t.get("title", []))) for r in d["unitatr"]: disp = r[8] n = norm_model(disp.split("Adr")[0].replace("%capa%", "").replace("%capa2%", "")) if n and q.startswith(n) and r[7] in d["tables"]: res.append((1, r[7], [disp])) res.sort(key=lambda x: -x[0]) seen, out = set(), [] for s, k, ti in res: if k not in seen: seen.add(k) out.append((k, ti)) return out[:limit] # --------------------------------------------------------------------------------------------- conversions def bcd_signed(h, decimals=1): if len(h) < 2: return None b0 = int(h[:2], 16) s = -1 if b0 & 0x80 else 1 digits = "%02X" % (b0 & 0x7F) + h[2:] if not digits.isdigit(): return None return s * int(digits) / 10 ** decimals KGF_TO_PSI, KGF_TO_MPA = 14.2233, 0.0980665 def convert(h, conv, ln_hex): """Returns (si_value, si_unit, us_value, us_unit, quality). Unknown patterns -> raw.""" c = int(conv, 16) if re.fullmatch(r"[0-9A-Fa-f]{1,2}", conv or "") else -1 ln = int(ln_hex, 16) if not h: return (None, "", None, "", "missing") if h.upper() in ("7FFF", "8000", "FFFF", "FF"): return (None, "", None, "", "no-data") if ln & 0x80: # bit field: high nibble of conv = bit number (inferred) bit = (c >> 4) & 7 if c >= 0 else 0 v = (int(h[:2], 16) >> bit) & 1 return (v, "", v, "", "bit") if c in (0xF1, 0xF4): v = bcd_signed(h) return (v, "degC", None if v is None else round(v * 9 / 5 + 32, 1), "degF", "decoded") if c in (0xF2, 0xE1): v = bcd_signed(h) return (v, "K", None if v is None else round(v * 1.8, 1), "dF", "decoded") if c == 0xF3: v = bcd_signed(h) return (v, "kgf/cm2", None if v is None else round(v * KGF_TO_PSI, 1), "psi", "decoded") if c == 0x02: v = int(h) if h.isdigit() else None return (v, "", v, "", "decoded" if v is not None else "raw") if c == 0x05: v = int(h, 16) return (v, "", v, "", "decoded") return (None, "raw", None, "raw", "raw") # --------------------------------------------------------------------------------------------- decoder def payload_key(p): """request-form hex of a payload (response bit cleared).""" b = bytearray(p) if len(b) >= 2: b[1] &= 0x7F return b.hex().upper() def command_name(p): k = payload_key(p) for n in range(min(len(k), 12), 1, -2): if k[:n] in COMMAND_NAMES: return COMMAND_NAMES[k[:n]] return "" def classify(p, typ): if not p: return "empty" rsp = bool(len(p) > 1 and p[1] & 0x80) or typ in (0xBE, 0x3E) if p[0] in WRITE_CLASSES: return "write-response" if rsp else "WRITE" if p[0] in READ_CLASSES: return "read-response" if rsp else "read-request" return "other-response" if rsp else "other" class Unit: def __init__(self, addr): self.addr = addr self.kind = kind_from_addr(addr) self.kind_source = "address-range" self.model = None self.table = None self.table_source = None self.attr_hex = None self.romver = None self.values = {} # name -> dict self.errors = [] self.pages = {} # rx hex -> last payload hex self.last_t = None self.frames = 0 def to_json(self): return {"addr": self.addr, "kind": self.kind, "kind_source": self.kind_source, "model": self.model, "table": self.table, "last_frame_at": self.last_t, "values": [dict(v, n=k) for k, v in sorted(self.values.items())], "errors": self.errors[-20:]} class Decoder: def __init__(self, overrides=None): self.d = load_data() self.units = {} self.overrides = {} # addr -> table id for a, q in (overrides or {}).items(): hits = find_tables(q) if hits: self.overrides[int(a)] = hits[0][0] self.rows = [] # decoded value rows (for CSV) self.frames = [] # frame rows self.writes_seen = 0 self.unknown_cmds = {} def unit(self, a): if a not in self.units: self.units[a] = Unit(a) if a in self.overrides: u = self.units[a] u.table, u.table_source = self.overrides[a], "manual" u.model = (self.d["tables"].get(u.table, {}).get("title") or [None])[0] return self.units[a] def handle(self, fr): p, t = fr["payload"], fr["t"] kind = classify(p, fr["type"]) fr["kind"], fr["name"] = kind, command_name(p) self.frames.append(fr) if kind == "WRITE": self.writes_seen += 1 if len(p) < 2: return [] src = self.unit(fr["src"]) src.last_t, src.frames = t, src.frames + 1 self.unit(fr["dst"]) if not kind.endswith("response"): return [] key = payload_key(p) h = p.hex().upper() out = [] if key.startswith("2104"): self.identify(src, p) elif key.startswith("3577"): src.romver = h[4:] elif key.startswith("3900"): out += self.errors(src, p, t) elif key[:4] in ("2D01", "2D02", "2501") or key.startswith("350322"): out += self.indoor_basic(src, key, p, t) if key.startswith("397E") or key.startswith("35") or key.startswith("31") or key.startswith("2D") \ or key.startswith("25"): out += self.page(src, h, t) return out def identify(self, u, p): u.attr_hex = p.hex().upper() b = p[2:] cands = [] def match(byte, pat): # UNITATR uses ** as a wildcard return pat in ("**", "") or (re.fullmatch(r"[0-9A-Fa-f]{2}", pat) and byte == int(pat, 16)) for r in self.d["unitatr"]: if not re.fullmatch(r"[0-9A-Fa-f]{2}", r[0]): continue for i in range(len(b) - 2): if b[i] == int(r[0], 16) and match(b[i + 1], r[1]) and match(b[i + 2], r[2]): exact = (r[1] != "**") + (r[2] != "**") cands.append((i, -exact, r)) if not cands: return cands.sort(key=lambda x: (x[0], x[1], x[2][3] != "02")) r = cands[0][2] u.kind = ATTR_KIND.get(r[0], "other") u.kind_source = "unitattr" u.model = re.sub(r"\s+Adr.*$", "", r[8]).replace("%capa%", "*").replace("%capa2%", "*").strip() or r[6] if r[7] in self.d["tables"] and not (u.table_source == "manual"): u.table, u.table_source = r[7], "unitattr" for ti in self.d["tables"][r[7]].get("title", []): ti = unicodedata.normalize("NFKC", ti) if re.search(r"[A-Z]{3,5}-[A-Z]*\d", ti): # table title names the model family u.model = re.sub(r"\s*\(.*?\)\s*", " ", ti).strip(" []") break def indoor_basic(self, u, key, p, t): rows = [] def put(n, d, v, unit, raw): u.values[n] = {"d": d, "v": v, "u": unit, "si": v, "su": unit, "raw": raw, "page": key[:6], "q": "decoded", "t": t} rows.append(self._row(u, n, u.values[n], t)) if key.startswith("2D01") and len(p) >= 3: put("onoff", "On/off (0 stop, 1 run)", p[2], "", "%02X" % p[2]) elif key.startswith("2D02") and len(p) >= 3: put("mode", "Mode code (7 heat, 8 cool, 13 fan)", p[2], "", "%02X" % p[2]) elif key.startswith("2501") and len(p) >= 4: v = bcd_signed(p[2:4].hex()) put("setpoint", "Setpoint", None if v is None else round(v * 9 / 5 + 32, 1), "degF", p[2:4].hex()) elif key.startswith("350322") and len(p) >= 5: v = bcd_signed(p[3:5].hex()) put("room_temp", "Room temp", None if v is None else round(v * 9 / 5 + 32, 1), "degF", p[3:5].hex()) return rows def errors(self, u, p, t): # 3980 reply layout not confirmed: list every 4-digit BCD group that is a known Mitsubishi error code. h = p[2:].hex().upper() rows = [] for i in range(0, len(h) - 3, 2): c = h[i:i + 4] if c.isdigit() and c != "0000" and (c in self.d["errcodes"]): if not any(e["code"] == c for e in u.errors[-10:]): e = {"code": c, "text": self.d["errcodes"][c], "raw": h, "t": t, "src": "3980", "q": "inferred"} u.errors.append(e) return rows def page(self, u, h, t): u.pages[h[:8]] = h tid = u.table if not tid or tid not in self.d["tables"]: n = "page_" + h[:6] u.values[n] = {"d": "raw reply (model table unknown)", "v": None, "u": "raw", "si": None, "su": "raw", "raw": h, "page": h[:6], "q": "raw", "t": t} return [self._row(u, n, u.values[n], t)] tb = self.d["tables"][tid] best = None for num, rx in tb["rx"].items(): if h.startswith(rx) and (best is None or len(rx) > len(tb["rx"][best])): best = num if best is None: return [] hdr = len(tb["rx"][best]) rows = [] for name, rxn, pos, ln, conv, item, note in tb["items"]: if str(rxn) != best: continue nb = int(ln, 16) & 0x0F or 1 start = hdr + 2 * (pos - 1) raw = h[start:start + 2 * nb] if len(raw) < 2 * nb: continue si, su, us, uu, q = convert(raw, conv, ln) key = name or ("item_" + item) if key in u.values and u.values[key].get("page") != tb["rx"][best] and q == "bit": key = key + "@" + tb["rx"][best] u.values[key] = {"d": gloss(note) or name, "jp": note, "v": us, "u": uu, "si": si, "su": su, "raw": raw, "page": tb["rx"][best], "conv": conv, "q": q, "t": t} rows.append(self._row(u, key, u.values[key], t)) return rows def _row(self, u, n, v, t): r = {"t": t, "addr": u.addr, "kind": u.kind, "model": u.model or "", "table": u.table or "", "name": n, "value": v.get("v"), "unit": v.get("u"), "value_si": v.get("si"), "unit_si": v.get("su"), "raw": v.get("raw"), "page": v.get("page"), "conv": v.get("conv", ""), "quality": v.get("q"), "desc": v.get("d", ""), "note_jp": v.get("jp", "")} self.rows.append(r) return r # --------------------------------------------------------------------------------------------- file inputs def _ts(t): if t is None: return "" return _dt.datetime.fromtimestamp(t / 1000).isoformat(timespec="milliseconds") def read_pcap_any(path): """pcapng or pcap with USBPcap (linktype 249) or Linux usbmon (189/220). Yields (t_ms, stream, direction, data) for USB bulk payloads, and ('ctrl', info) records for CDC line-coding / control-line requests.""" d = readfile(path) out, ctrl = [], [] if d[:4] == b"\x0a\x0d\x0d\x0a": pkts = _pcapng_packets(d) elif d[:4] in (b"\xd4\xc3\xb2\xa1", b"\xa1\xb2\xc3\xd4", b"\x4d\x3c\xb2\xa1", b"\xa1\xb2\x3c\x4d"): pkts = _pcap_packets(d) else: raise ValueError("not a pcap/pcapng file") last_setup = {} for t, lt, pk in pkts: if lt == 249 and len(pk) >= 27: hl, irp, status, func, info, bus, dev, ep, xfer, dlen = struct.unpack_from("= 28 else None if stage == 0 and len(data) >= 8: last_setup[key] = data[:8] if len(data) >= 15 and data[1] == 0x20: ctrl.append((t, key, _line_coding(data[8:15]))) if data[1] == 0x22: ctrl.append((t, key, "control lines DTR=%d RTS=%d" % (data[2] & 1, (data[2] >> 1) & 1))) elif stage == 1 and key in last_setup and last_setup[key][1] == 0x20 and len(data) >= 7: ctrl.append((t, key, _line_coding(data[:7]))) elif lt in (189, 220) and len(pk) >= 48: hdr = 64 if lt == 220 else 48 (uid, typ, xfer, ep, dev, bus, fsetup, fdata, sec, usec, status, length, lcap) = struct.unpack_from( "= 7: ctrl.append((t, key, _line_coding(data[:7]))) if setup[1] == 0x22: ctrl.append((t, key, "control lines DTR=%d RTS=%d" % (setup[2] & 1, (setup[2] >> 1) & 1))) return out, ctrl def _line_coding(b): rate, stop, par, bits = struct.unpack("" lt = struct.unpack_from(e + "I", d, 20)[0] k, res = 24, [] while k + 16 <= len(d): s, us, cl, ol = struct.unpack_from(e + "IIII", d, k) k += 16 res.append((s * 1000 + (us / 1e6 if nano else us / 1e3), lt, d[k:k + cl])) k += cl return res def _pcapng_packets(d): res, ifs, k, e = [], [], 0, "<" while k + 12 <= len(d): bt = struct.unpack_from(e + "I", d, k)[0] if bt == 0x0A0D0D0A: bom = d[k + 8:k + 12] e = "<" if bom == b"\x4d\x3c\x2b\x1a" else ">" ifs = [] bl = struct.unpack_from(e + "I", d, k + 4)[0] if bl < 12: break body = d[k + 8:k + bl - 4] if bt == 1: lt = struct.unpack_from(e + "H", body, 0)[0] res_div = 1e6 o = 8 while o + 4 <= len(body): code, ln = struct.unpack_from(e + "HH", body, o) if code == 0: break if code == 9 and ln >= 1: v = body[o + 4] res_div = (2 ** (v & 0x7F)) if v & 0x80 else 10 ** v o += 4 + ((ln + 3) & ~3) ifs.append((lt, res_div)) elif bt == 6 and ifs: iid, th, tl, cl, ol = struct.unpack_from(e + "IIIII", body, 0) lt, div = ifs[iid] if iid < len(ifs) else ifs[0] res.append((((th << 32) | tl) / div * 1000, lt, body[20:20 + cl])) elif bt == 3 and ifs: ol = struct.unpack_from(e + "I", body, 0)[0] res.append((None, ifs[0][0], body[4:4 + min(ol, len(body) - 4)])) k += bl return res def read_mt(path): """PAC-USCMS-MN-1 SD log (MNTxxx.MT). Mitsubishi's DriveRecorderFile.cs reads records [src][dst][len][bytes] with 0xFF padding (static finding). There is no checksum in the file, so records are plausibility-checked: command class byte must look like an M-NET class (low two bits = 01). Unparsed stretches are reported.""" d = readfile(path) k, recs, skipped, skip_samples = 0, [], 0, [] while k < len(d) - 4: if d[k] == 0xFF: k += 1 continue sa, da, ln = d[k], d[k + 1], d[k + 2] p = d[k + 3:k + 3 + ln] if 2 <= ln <= MAX_PAYLOAD and len(p) == ln and (p[0] & 0x03) == 1: recs.append({"t": None, "type": 0xBE if p[1] & 0x80 else 0xBD, "src": sa, "dst": da, "flags": None, "payload": bytes(p), "fcc_ok": None, "enc": "mt", "wrap_ok": None, "stream": "sd", "hex": d[k:k + 3 + ln].hex().upper(), "offset": k}) k += 3 + ln else: if len(skip_samples) < 5 and (not skip_samples or k > skip_samples[-1][0] + 16): skip_samples.append((k, d[k:k + 16].hex().upper())) skipped += 1 k += 1 return recs, {"bytes": len(d), "skipped_bytes": skipped, "skip_samples": skip_samples} _DIR_TX = re.compile(r"(?i)\b(write|tx|sent|send|out|request|irp_mj_write|>>|down)\b") _DIR_RX = re.compile(r"(?i)\b(read|rx|recv|received|in|answer|response|irp_mj_read|<<|up)\b") _HEXTOK = re.compile(r"(?= 2: streams[cur] += bytes(int(x, 16) for x in toks) return {k: bytes(v) for k, v in streams.items() if v} def read_mnetlog(path): op = gzip.open if path.endswith(".gz") else open chunks = [] with op(path, "rt", encoding="utf-8") as f: for line in f: try: j = json.loads(line) except ValueError: continue if "hex" in j: chunks.append((j.get("t"), j.get("dir", "rx"), bytes.fromhex(j["hex"]))) return chunks def decode_files(paths, overrides=None, strict=True): dec = Decoder(overrides) notes = [] for path in paths: low = path.lower() name = os.path.basename(path) try: if low.endswith(".mt"): recs, info = read_mt(path) notes.append("%s: SD log, %d bytes, %d records, %d bytes not understood%s" % ( name, info["bytes"], len(recs), info["skipped_bytes"], (" (first: " + "; ".join("@%d %s" % s for s in info["skip_samples"]) + ")") if info["skip_samples"] else "")) for r in recs: r["file"] = name dec.handle(r) elif low.endswith((".pcapng", ".pcap", ".cap")): pk, ctrl = read_pcap_any(path) for t, key, txt in ctrl: notes.append("%s: %s %s %s" % (name, _ts(t), key, txt)) streams = {} for t, st, dr, data in pk: streams.setdefault(st, []).append((t, dr, data)) for st, items in streams.items(): ex = Extractor(st, strict) n0 = len(dec.frames) for t, dr, data in items: for fr in ex.feed(data, t): fr["dir"], fr["file"] = ("pc->conv" if dr == "out" else "conv->pc"), name dec.handle(fr) if len(dec.frames) > n0: notes.append("%s: stream %s carried %d M-NET frames (%d bytes)" % ( name, st, len(dec.frames) - n0, ex.bytes_in)) elif low.endswith((".mnetlog", ".mnetlog.gz", ".jsonl", ".jsonl.gz")): exs = {} for t, dr, data in read_mnetlog(path): ex = exs.setdefault(dr, Extractor(dr, strict)) for fr in ex.feed(data, t): fr["dir"], fr["file"] = dr, name dec.handle(fr) else: raw = readfile(path) txt_like = sum(1 for c in raw[:4096] if 32 <= c < 127 or c in (9, 10, 13)) > 0.9 * min(len(raw), 4096) srcs = read_textlog(path) if txt_like else {} found = False for dr, data in srcs.items(): hits = Extractor(dr, strict).feed(data, None) for fr in hits: fr["dir"], fr["file"] = dr, name dec.handle(fr) found = found or bool(hits) if not found: for fr in Extractor("raw", strict).feed(raw, None): fr["dir"], fr["file"] = "raw", name dec.handle(fr) except Exception as e: # keep going; report notes.append("%s: could not read (%s)" % (name, e)) return dec, notes def write_outputs(dec, notes, outdir, stem): os.makedirs(outdir, exist_ok=True) fpath = os.path.join(outdir, stem + "_frames.csv") with open(fpath, "w", newline="", encoding="utf-8") as f: w = csv.writer(f) w.writerow(["time", "file", "dir", "src", "dst", "type", "flags", "kind", "command", "payload", "checksum", "encoding", "wrapper_ok", "hex"]) for fr in dec.frames: w.writerow([_ts(fr.get("t")), fr.get("file", ""), fr.get("dir", ""), fr["src"], fr["dst"], "%02X" % fr["type"], "" if fr.get("flags") is None else "%02X" % fr["flags"], fr.get("kind"), fr.get("name"), fr["payload"].hex().upper(), {True: "ok", None: "none-in-format", False: "BAD"}[fr.get("fcc_ok")], fr.get("enc"), fr.get("wrap_ok"), fr.get("hex")]) vpath = os.path.join(outdir, stem + "_values.csv") cols = ["t", "addr", "kind", "model", "table", "name", "desc", "value", "unit", "value_si", "unit_si", "raw", "page", "conv", "quality", "note_jp"] with open(vpath, "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore") w.writeheader() for r in dec.rows: r = dict(r, t=_ts(r["t"])) w.writerow(r) spath = os.path.join(outdir, stem + "_summary.txt") with open(spath, "w", encoding="utf-8") as f: f.write(summary_text(dec, notes)) return fpath, vpath, spath def summary_text(dec, notes): L = ["M-NET Reader %s summary (%s)" % (VERSION, _dt.datetime.now().isoformat(timespec="seconds")), ""] if load_data().get("missing"): L.append("WARNING: mnet_data.json.gz not found - no model tables, raw values only.") L += ["Inputs:"] + [" " + n for n in notes] + [""] kinds = {} for fr in dec.frames: kinds[fr.get("kind")] = kinds.get(fr.get("kind"), 0) + 1 L.append("Frames: %d %s" % (len(dec.frames), ", ".join("%s %d" % kv for kv in sorted(kinds.items())))) if dec.writes_seen: L.append("NOTE: %d WRITE-class frames were seen on the bus (sent by some other tool/controller, not by this " "program)." % dec.writes_seen) if not dec.frames: L.append("No checksum-valid M-NET frames found. If this was a listen-only log, the converter may only pass " "on its own traffic; send the raw log anyway.") L.append("") L.append("Addresses seen:") for a in sorted(dec.units): u = dec.units[a] L.append(" %3d %-10s (%s) model: %s table: %s frames sent: %d last: %s" % ( a, u.kind, u.kind_source, u.model or "unknown", u.table or "-", u.frames, _ts(u.last_t) or "-")) L.append("") for a in sorted(dec.units): u = dec.units[a] if not u.values and not u.errors: continue L.append("Unit %d (%s, %s) latest values:" % (a, u.kind, u.model or "model unknown - raw")) for n, v in sorted(u.values.items()): if v.get("q") == "raw": L.append(" %-14s raw %s" % (n, v.get("raw"))) else: L.append(" %-14s %s %s [%s, raw %s%s] %s" % ( n, v.get("v"), v.get("u") or "", v.get("q"), v.get("raw"), (", %s %s" % (v.get("si"), v.get("su"))) if v.get("su") not in ("", None, v.get("u")) else "", v.get("d", ""))) for e in u.errors[-10:]: L.append(" ERROR %s %s (inferred from reply %s)" % (e["code"], e["text"], e["raw"][:24])) L.append("") L.append("All decoded values are tentative until compared with Maintenance Tool's screen for the same minutes.") return "\n".join(L) + "\n" # --------------------------------------------------------------------------------------------- serial sources class ListenOnlyPort: """Wraps a pyserial port so nothing can be written.""" def __init__(self, ser): self._s = ser def read(self, n): return self._s.read(n) @property def in_waiting(self): return self._s.in_waiting def write(self, *a, **k): raise PermissionError("listen-only: writing to the M-NET port is disabled") def close(self): self._s.close() def open_port(port, source="pac-uscms-mn-1", baud=9600, parity=None, dtr=False): import serial # pyserial if parity is None: parity = "E" if source == "uart-8e1" else "N" s = serial.Serial() s.port, s.baudrate, s.bytesize, s.stopbits, s.timeout = port, baud, 8, 1, 0.2 s.parity = {"N": serial.PARITY_NONE, "E": serial.PARITY_EVEN, "O": serial.PARITY_ODD}[parity] try: s.dtr, s.rts = dtr, False # .NET SerialPort default is DTR/RTS off (what Maintenance Tool inherits except Exception: # unless it sets them - not confirmed) pass s.exclusive = True if os.name != "nt" else None s.open() return s def find_converter_port(): try: from serial.tools import list_ports except ImportError: return None for p in list_ports.comports(): if p.vid == CONVERTER_VID and p.pid == CONVERTER_PID: return p.device return None class ReplaySource: """Feeds a saved .mnetlog / raw file as if live (for testing the service without hardware).""" def __init__(self, path, speed=0.0): self.chunks = read_mnetlog(path) if ".mnetlog" in path or path.endswith(".jsonl") else \ [(None, "rx", readfile(path))] self.i, self.speed = 0, speed def read(self, n): if self.i >= len(self.chunks): time.sleep(0.2) return b"" c = self.chunks[self.i][2] self.i += 1 if self.speed: time.sleep(self.speed) return c def write(self, *a, **k): raise PermissionError("replay source is read-only") def close(self): pass # --------------------------------------------------------------------------------------------- raw log class RawLog: def __init__(self, folder, keep_days=30, max_mb=2000): self.folder, self.keep_days, self.max_mb = folder, keep_days, max_mb os.makedirs(folder, exist_ok=True) self.day, self.f = None, None def write(self, t, direction, data, extra=None): day = _dt.datetime.fromtimestamp(t / 1000).strftime("%Y-%m-%d") if day != self.day: if self.f: self.f.close() self.day = day self.f = open(os.path.join(self.folder, "mnet-%s.mnetlog" % day), "a", encoding="utf-8") self.prune() rec = {"t": int(t), "dir": direction, "hex": data.hex().upper()} if extra: rec.update(extra) self.f.write(json.dumps(rec) + "\n") self.f.flush() def note(self, t, text): self.write(t, "note", b"", {"note": text}) def prune(self): files = sorted(x for x in os.listdir(self.folder) if x.startswith("mnet-")) cutoff = (_dt.date.today() - _dt.timedelta(days=self.keep_days)).strftime("%Y-%m-%d") for x in files: if x[5:15] < cutoff: os.remove(os.path.join(self.folder, x)) files = sorted(x for x in os.listdir(self.folder) if x.startswith("mnet-")) tot = sum(os.path.getsize(os.path.join(self.folder, x)) for x in files) while files and tot > self.max_mb * 1e6: tot -= os.path.getsize(os.path.join(self.folder, files[0])) os.remove(os.path.join(self.folder, files.pop(0))) def now_ms(): return int(time.time() * 1000) # --------------------------------------------------------------------------------------------- active read class ReadGuard: """The ONLY path to the wire in read mode. Refuses anything not on the hard-coded allowlist.""" def __init__(self, port, src, eol=b"\r\n", interval=5.0, rawlog=None): if src is None or not (0 <= src <= 255): raise ValueError("read mode needs --src (the converter's M-NET source address, copied from a capture)") self.port, self.src, self.eol, self.rawlog = port, src, eol, rawlog self.interval = max(float(interval), MIN_READ_INTERVAL_S) self.last = 0.0 self.sent = 0 @staticmethod def check(payload_hex, dst): ph = payload_hex.upper() if ph in DENY_EXACT or ph not in ALLOWLIST: raise PermissionError("refused: %s is not on the read-only allowlist" % ph) b = bytes.fromhex(ph) if b[0] not in READ_CLASSES or b[0] in WRITE_CLASSES or (len(b) > 1 and b[1] & 0x80): raise PermissionError("refused: %s is not a read request" % ph) if dst in (0x00, 0xFF): raise PermissionError("refused: address %d (broadcast/central) is not allowed" % dst) return b def send(self, dst, payload_hex): b = self.check(payload_hex, dst) wait = self.last + self.interval - time.time() if wait > 0: time.sleep(wait) fr = build_frame(self.src, dst, b, 0xBD) line = converter_line(fr, self.eol) self.port.write(line) self.last = time.time() self.sent += 1 if self.rawlog: self.rawlog.write(now_ms(), "tx", line) return fr def plan_reads(dec, addrs): """For each address: 2104 + 3577 first (identify), then every allowlisted request of its table.""" plan = [] for a in addrs: u = dec.unit(a) if not u.table: plan += [(a, "2104"), (a, "3577")] continue tb = dec.d["tables"].get(u.table, {}) for num in sorted(tb.get("tx", {}), key=lambda x: int(x)): c = tb["tx"][num].upper() if c in ALLOWLIST and c not in DENY_EXACT: plan.append((a, c)) plan.append((a, "3900")) return plan # --------------------------------------------------------------------------------------------- upload queue class Outbox: """On-disk queue (sqlite, survives power loss). One row per snapshot batch.""" def __init__(self, path, max_rows=200000): os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) self.db = sqlite3.connect(path, check_same_thread=False, isolation_level=None) self.db.execute("PRAGMA journal_mode=WAL") self.db.execute("CREATE TABLE IF NOT EXISTS q (t INTEGER PRIMARY KEY, body TEXT)") self.lock = threading.Lock() self.max_rows = max_rows def put(self, batch): with self.lock: self.db.execute("INSERT OR REPLACE INTO q VALUES (?,?)", (int(batch["t"]), json.dumps(batch))) n = self.db.execute("SELECT COUNT(*) FROM q").fetchone()[0] if n > self.max_rows: # drop oldest raw frames first, then oldest rows self.db.execute("DELETE FROM q WHERE t IN (SELECT t FROM q ORDER BY t LIMIT ?)", (n - self.max_rows,)) def take(self, n=30): with self.lock: return [(t, json.loads(b)) for t, b in self.db.execute("SELECT t, body FROM q ORDER BY t LIMIT ?", (n,))] def done(self, ts): with self.lock: self.db.executemany("DELETE FROM q WHERE t=?", [(t,) for t in ts]) def __len__(self): with self.lock: return self.db.execute("SELECT COUNT(*) FROM q").fetchone()[0] def post_json(url, token, body, timeout=20): raw = gzip.compress(json.dumps(body, separators=(",", ":")).encode()) req = urllib.request.Request(url, data=raw, method="POST", headers={ "Authorization": "Bearer " + token, "Content-Type": "application/json", "Content-Encoding": "gzip", "User-Agent": "mnet-reader/" + VERSION}) try: with urllib.request.urlopen(req, timeout=timeout) as r: return r.status, json.loads(r.read() or b"{}") except urllib.error.HTTPError as e: try: j = json.loads(e.read() or b"{}") except ValueError: j = {} return e.code, j class Uploader(threading.Thread): def __init__(self, cfg, outbox, status_fn, log): super().__init__(daemon=True) self.cfg, self.outbox, self.status_fn, self.log = cfg, outbox, status_fn, log self.stop = threading.Event() self.backoff = 0 self.state = "idle" def run(self): url, tok = self.cfg.get("upload_url"), self.cfg.get("token") if not url or not tok or not self.cfg.get("upload", True): self.state = "disabled" return every = int(self.cfg.get("upload_every_s", 60)) while not self.stop.is_set(): items = self.outbox.take(int(self.cfg.get("batches_per_post", 30))) body = {"v": 1, "device_id": self.cfg.get("device_id", ""), "sw": "mnet-reader " + VERSION, "sent_at": now_ms(), "status": dict(self.status_fn(), queue_len=max(0, len(self.outbox) - len(items))), "batches": [b for _, b in items]} try: code, j = post_json(url, tok, body) except Exception as e: code, j = 0, {"error": str(e)} if code == 200: self.outbox.done([t for t, _ in items]) self.backoff = 0 self.state = "ok" every = int(j.get("next_upload_s", every) or every) if len(self.outbox): continue elif code == 401: self.state = "bad token (401) - uploads paused; data kept on the box" self.log("upload: 401 bad token; waiting 15 min") self.stop.wait(900) continue elif code == 413 and len(items) > 1: self.cfg["batches_per_post"] = max(1, len(items) // 2) continue else: self.backoff = min(max(self.backoff * 2, 30), 1800) if code == 429: self.backoff = int(j.get("retry_after_s", self.backoff)) self.state = "offline/err %s; retry in %ss; %d batches buffered" % (code, self.backoff, len(self.outbox)) self.log("upload: " + self.state + " " + str(j.get("error", ""))[:120]) self.stop.wait(self.backoff) continue self.stop.wait(every) # --------------------------------------------------------------------------------------------- service DEFAULT_CFG = { "site_id": "", "device_id": "", "token": "", "upload_url": "", "upload": True, "source": "pac-uscms-mn-1", # pac-uscms-mn-1 | uart-8e1 | replay "port": "auto", "baud": 9600, "parity": None, "dtr": False, "mode": "listen", # listen | read (read needs read_src + read_addrs + i_understand_this_transmits) "read_src": None, "read_addrs": [], "read_interval_s": 5, "read_eol": "\\r\\n", "i_understand_this_transmits": False, "snapshot_every_s": 60, "raw_frames_per_batch": 300, "units": {}, "data_dir": "/var/lib/mnet-reader", "raw_keep_days": 30, "raw_max_mb": 2000, } def load_cfg(path): cfg = dict(DEFAULT_CFG) if path and os.path.exists(path): cfg.update(json.load(open(path, encoding="utf-8"))) return cfg def run_service(cfg, max_seconds=None, log=print, source_obj=None): os.makedirs(cfg["data_dir"], exist_ok=True) raw = RawLog(os.path.join(cfg["data_dir"], "raw"), cfg["raw_keep_days"], cfg["raw_max_mb"]) outbox = Outbox(os.path.join(cfg["data_dir"], "outbox.db")) dec = Decoder(cfg.get("units") or {}) stats = {"frames_ok": 0, "frames_bad": 0, "bytes_in": 0, "last_frame_at": None, "start": time.time(), "port": cfg.get("port"), "note": ""} def status(): return {"source": cfg["source"], "mode": cfg["mode"], "port": stats["port"], "uptime_s": int(time.time() - stats["start"]), "frames_ok": stats["frames_ok"], "frames_bad": stats["frames_bad"], "bytes_in": stats["bytes_in"], "last_frame_at": stats["last_frame_at"], "note": stats["note"]} up = Uploader(cfg, outbox, status, log) up.start() ex = Extractor("live") recent_frames = [] next_snap = time.time() + cfg["snapshot_every_s"] t_end = time.time() + max_seconds if max_seconds else None port, guard, plan, pi = None, None, [], 0 log("mnet-reader %s: source=%s mode=%s site=%s device=%s" % (VERSION, cfg["source"], cfg["mode"], cfg.get("site_id"), cfg.get("device_id"))) while True: if t_end and time.time() > t_end: break if port is None: try: if source_obj is not None: port = source_obj elif cfg["source"] == "replay": port = ReplaySource(cfg["port"], 0.05) else: dev = cfg["port"] if cfg["port"] not in ("", "auto", None) else find_converter_port() if not dev: raise IOError("converter not found (USB VID 1293 PID 3201); plug it in") stats["port"] = dev s = open_port(dev, cfg["source"], cfg["baud"], cfg.get("parity"), cfg.get("dtr", False)) port = s if (cfg["mode"] == "read" and cfg["source"] == "pac-uscms-mn-1") else ListenOnlyPort(s) raw.note(now_ms(), "port open %s mode=%s" % (stats["port"], cfg["mode"])) if cfg["mode"] == "read": if cfg["source"] != "pac-uscms-mn-1": raise PermissionError("read mode is only allowed through the PAC-USCMS-MN-1 converter in v1") if not cfg.get("i_understand_this_transmits"): raise PermissionError("read mode needs i_understand_this_transmits: true") guard = ReadGuard(port, int(str(cfg["read_src"]), 0) if cfg.get("read_src") is not None else None, cfg["read_eol"].encode().decode("unicode_escape").encode(), cfg["read_interval_s"], raw) stats["note"] = "" except PermissionError as e: log("REFUSED: %s" % e) stats["note"] = "refused: %s" % e up.stop.set() if raw.f: raw.f.close() return 2 except Exception as e: stats["note"] = "port problem: %s" % e log(stats["note"] + " - retrying in 10 s") port = None time.sleep(10) continue try: data = port.read(512) except Exception as e: log("read error %s - reopening" % e) try: port.close() except Exception: pass port = None time.sleep(3) continue t = now_ms() if data: stats["bytes_in"] += len(data) raw.write(t, "rx", data) for fr in ex.feed(data, t): stats["frames_ok"] += 1 stats["last_frame_at"] = t dec.handle(fr) recent_frames.append({"t": t, "hex": fr["hex"]}) if guard is not None and time.time() >= guard.last + guard.interval: addrs = [int(a) for a in cfg.get("read_addrs") or []] if not plan or pi >= len(plan): plan, pi = plan_reads(dec, addrs), 0 if plan: a, c = plan[pi] pi += 1 try: guard.send(a, c) except PermissionError as e: log("refused %s -> %s: %s" % (c, a, e)) if time.time() >= next_snap: next_snap = time.time() + cfg["snapshot_every_s"] if stats["last_frame_at"] is None or t - stats["last_frame_at"] > 600000: stats["note"] = "no M-NET frames in the last 10 min" if stats["frames_ok"] else \ "no M-NET frames seen yet (converter may not pass bus traffic in listen-only mode)" else: stats["note"] = "" batch = {"t": t, "units": [u.to_json() for u in dec.units.values() if u.frames], "frames": recent_frames[-int(cfg["raw_frames_per_batch"]):], "status": status()} recent_frames = [] outbox.put(batch) up.stop.set() if raw.f: raw.f.close() return 0 # --------------------------------------------------------------------------------------------- CLI def cmd_listen(a): port = a.port or find_converter_port() if not port: print("No converter found. Use --port COM5 (Windows) or /dev/ttyACM0 (Linux). Try: mnet_reader.py ports") return 1 stem = "mnet-listen-" + _dt.datetime.now().strftime("%Y%m%d-%H%M%S") os.makedirs(a.out, exist_ok=True) logpath = os.path.join(a.out, stem + ".mnetlog") s = open_port(port, a.source, a.baud, a.parity, a.dtr) p = ListenOnlyPort(s) ex = Extractor("live") dec = Decoder(dict(x.split("=", 1) for x in a.unit)) n_bytes, t_end = 0, time.time() + a.minutes * 60 if a.minutes else None print("LISTEN-ONLY on %s (%s). Nothing will be sent. Logging to %s. Ctrl+C to stop." % (port, a.source, logpath)) with open(logpath, "w", encoding="utf-8") as f: f.write(json.dumps({"t": now_ms(), "dir": "note", "note": "listen start %s %s mnet-reader %s" % ( port, a.source, VERSION)}) + "\n") try: last_print = time.time() while not t_end or time.time() < t_end: data = p.read(512) t = now_ms() if data: n_bytes += len(data) f.write(json.dumps({"t": t, "dir": "rx", "hex": data.hex().upper()}) + "\n") f.flush() for fr in ex.feed(data, t): dec.handle(fr) print("%s %3d -> %3d %-14s %s %s" % (_ts(t)[11:], fr["src"], fr["dst"], fr["kind"], fr["payload"].hex().upper(), fr.get("name", ""))) if time.time() - last_print > 30: last_print = time.time() print("... %d bytes, %d frames so far" % (n_bytes, len(dec.frames))) except KeyboardInterrupt: pass p.close() paths = write_outputs(dec, ["%s: live listen on %s, %d bytes" % (os.path.basename(logpath), port, n_bytes)], a.out, stem) print("\nSaved:\n " + logpath + "\n " + "\n ".join(paths)) if n_bytes == 0: print("The converter sent nothing while listening. That is useful to know - send the .mnetlog anyway.") return 0 def cmd_read(a): if not a.i_understand_this_transmits: print("REFUSED: read mode transmits on M-NET. Add --i-understand-this-transmits once we have confirmed the " "converter line format from a capture.") return 2 cfg = dict(DEFAULT_CFG, source="pac-uscms-mn-1", port=a.port or "auto", mode="read", read_src=a.src, read_addrs=[int(x) for x in a.addr.split(",")], read_interval_s=a.interval, upload=False, i_understand_this_transmits=True, data_dir=a.out, units=dict(x.split("=", 1) for x in a.unit), snapshot_every_s=30) return run_service(cfg, max_seconds=a.minutes * 60 if a.minutes else None) def cmd_decode(a): dec, notes = decode_files(a.files, dict(x.split("=", 1) for x in a.unit), strict=not a.loose) stem = a.name or os.path.splitext(os.path.basename(a.files[0]))[0] paths = write_outputs(dec, notes, a.out, stem) print(open(paths[2], encoding="utf-8").read()) print("Saved:\n " + "\n ".join(paths)) return 0 def cmd_models(a): for k, ti in find_tables(a.query, 30): print(k, " | ".join(unicodedata.normalize("NFKC", x) for x in ti)) return 0 def cmd_ports(a): try: from serial.tools import list_ports except ImportError: print("pyserial is not installed: pip install pyserial") return 1 for p in list_ports.comports(): tag = " <-- PAC-USCMS-MN-1" if (p.vid, p.pid) == (CONVERTER_VID, CONVERTER_PID) else "" print(p.device, p.description, "VID:PID=%s:%s" % (p.vid and "%04X" % p.vid, p.pid and "%04X" % p.pid), tag) return 0 def cmd_run(a): cfg = load_cfg(a.config) if a.data_dir: cfg["data_dir"] = a.data_dir return run_service(cfg, max_seconds=a.seconds) def selftest(): ok = True def chk(c, m): nonlocal ok print(("PASS " if c else "FAIL ") + m) ok = ok and c fr = bytes.fromhex("BDFB023F03350322AA") chk(fcc(fr[:-1]) == fr[-1], "Shustek real frame checksum") chk(build_frame(0xFB, 0x02, bytes.fromhex("350322")) == fr, "build_frame reproduces Shustek frame") hits = scan(converter_line(fr)) chk(len(hits) == 1 and hits[0][2] == fr and hits[0][4] is True, "ASCII converter line round-trip") try: ReadGuard.check("0D0101", 51) chk(False, "write refused") except PermissionError: chk(True, "write command refused by allowlist") chk(ReadGuard.check("397E00", 51) == bytes.fromhex("397E00"), "maintenance page allowed") chk(data_path() is not None, "model tables present") return 0 if ok else 1 def main(argv=None): ap = argparse.ArgumentParser(description="M-NET Reader %s (read-only)" % VERSION) sp = ap.add_subparsers(dest="cmd") p = sp.add_parser("listen") p.add_argument("--port") p.add_argument("--source", default="pac-uscms-mn-1", choices=["pac-uscms-mn-1", "uart-8e1"]) p.add_argument("--baud", type=int, default=9600) p.add_argument("--parity", choices=["N", "E", "O"]) p.add_argument("--dtr", action="store_true", help="assert DTR (off by default, like .NET SerialPort)") p.add_argument("--minutes", type=float, default=0) p.add_argument("--out", default="mnet-logs") p.add_argument("--unit", action="append", default=[], help="manual model: 51=PUHY-P72YLMU-A (only if auto fails)") p = sp.add_parser("read") p.add_argument("--port") p.add_argument("--addr", required=True, help="unit address(es), e.g. 51 or 51,52") p.add_argument("--src", required=True, help="converter source address from a Maintenance Tool capture, e.g. 0xFC") p.add_argument("--interval", type=float, default=5.0) p.add_argument("--minutes", type=float, default=10) p.add_argument("--out", default="mnet-read") p.add_argument("--unit", action="append", default=[]) p.add_argument("--i-understand-this-transmits", action="store_true") p = sp.add_parser("decode") p.add_argument("files", nargs="+") p.add_argument("--out", default="mnet-decoded") p.add_argument("--name") p.add_argument("--unit", action="append", default=[]) p.add_argument("--loose", action="store_true", help="accept binary frames with any flags byte") p = sp.add_parser("run") p.add_argument("--config", default="/etc/mnet-reader/config.json") p.add_argument("--data-dir") p.add_argument("--seconds", type=float) p = sp.add_parser("models") p.add_argument("query") sp.add_parser("ports") sp.add_parser("selftest") a = ap.parse_args(argv) fn = {"listen": cmd_listen, "read": cmd_read, "decode": cmd_decode, "run": cmd_run, "models": cmd_models, "ports": cmd_ports, "selftest": lambda a: selftest()}.get(a.cmd) if not fn: ap.print_help() return 0 return fn(a) if __name__ == "__main__": sys.exit(main())