"""Scan a BMW KWP identifier space via A's `diag bmw` console command. Sends one read-only request per identifier value (00..FF), waits for the probe's reply line, and prints a summary of everything that answered positively. Full console stream goes to wiki/raw/diagscan-.log. Usage: python tools/diag_scan.py COM10 21 # scan `21 xx` (readDataByLocalIdentifier) python tools/diag_scan.py COM10 22D1 # scan `22 D1 xx` (readDataByCommonIdentifier) python tools/diag_scan.py COM10 22D1 40 60 # optional sub-range [0x40..0x60) """ import os import re import sys import time import serial port = sys.argv[1] space = sys.argv[2].upper() # "21" or "22D1" lo = int(sys.argv[3], 16) if len(sys.argv) > 3 else 0x00 hi = int(sys.argv[4], 16) if len(sys.argv) > 4 else 0x100 raw_dir = os.path.join(os.path.dirname(__file__), "..", "wiki", "raw") log_path = os.path.join(raw_dir, time.strftime("diagscan-%%s-%Y%m%d-%H%M%S.log") % space) log = open(log_path, "wb") s = serial.Serial(port, 115200, timeout=0.05) print("port open, waiting for boot...") time.sleep(4) s.reset_input_buffer() hits = [] def txn(cmd, wait_s=1.5): """Send one diag command, return the probe's reply lines.""" s.write((cmd + "\n").encode()) s.flush() log.write(("\n>>> %s\n" % cmd).encode()) end = time.time() + wait_s pending = b"" replies = [] done = False while time.time() < end and not done: chunk = s.read(4096) if not chunk: continue log.write(chunk) pending += chunk while b"\n" in pending: line, pending = pending.split(b"\n", 1) text = line.decode("utf-8", "replace").rstrip() if "[diag]" in text: replies.append(text) if "<- 0x" in text or "no reply within" in text or "refused" in text: done = True return replies try: txn("diag raw off", wait_s=1.0) for v in range(lo, hi): if space == "21": cmd = "diag bmw 12 21 %02X" % v label = "21 %02X" % v else: cmd = "diag bmw 12 22 %s %02X" % (space[2:], v) label = "22 %s %02X" % (space[2:], v) replies = txn(cmd) got = [r for r in replies if "<- 0x" in r] if not got: replies = txn(cmd) # one retry if the line got mangled got = [r for r in replies if "<- 0x" in r] if not got: print("%s (no reply)" % label) continue r = got[-1] if "7F" in r and "negative" not in r.lower() and "NRC" not in r: pass if re.search(r"7F \d\d [0-9A-F]{2}", r) or "NRC" in r or "negative" in r: # negative response - only note interesting NRCs (not 0x12) if "0x12" not in r and "NRC 0x12" not in r: print("%s NEG: %s" % (label, r)) else: print("%s HIT: %s" % (label, r)) hits.append((label, replies)) time.sleep(0.15) finally: txn("diag raw on", wait_s=1.0) log.close() s.close() print("\n%d positive hits" % len(hits)) for label, replies in hits: print("== " + label) for r in replies: print(" " + r) print("log saved: " + os.path.abspath(log_path))