#!/usr/bin/env python3
"""wm_decode.py capture.bin [samplerate=1000000] [channel=0]  (2026-10-15)
Decodes the Electrolux MACS bus from a raw logic capture: 9600 baud, 8 data bits, EVEN parity,
INVERTED (idle 0 V, start bit = high). Frames: C9 <to> <from> <len> <data..> <xor of all previous bytes>;
ACK: 98 cc cc. Addresses: 21 washer main, 22 dryer main, 25 inverter, 2A front panel, 00 broadcast.
Message meanings from agocsdaniel/esphome_electrolux_macs (EWX FINDINGS.md) - an older front loader, so
treat them as a guide for a Westinghouse top loader. The lid bit (0x08) is from my own WWT8084J7WA.
Prints: estimated baud, byte-level sanity, every frame with time + decoded meaning where known, and a summary."""
import sys, numpy as np
from collections import Counter
f = sys.argv[1]; sr = int(sys.argv[2]) if len(sys.argv) > 2 else 1_000_000
ch = int(sys.argv[3]) if len(sys.argv) > 3 else 0
BAUD = 9600; spb = sr / BAUD
raw = np.fromfile(f, dtype=np.uint8)
s = ((raw >> ch) & 1).astype(np.int8)
print(f"{f}: {len(s)} samples = {len(s)/sr:.1f} s, line high {s.mean()*100:.2f}% of the time (inverted bus idles LOW)")

# --- baud estimate from the shortest pulses (should be ~1 bit = 104 us at 9600)
edges = np.flatnonzero(s[:-1] != s[1:]) + 1
if len(edges) < 10: sys.exit("no activity on this channel")
widths = np.diff(edges)
short = np.sort(widths)[: max(10, len(widths)//20)]
print(f"edges: {len(edges)}; shortest pulses ~{np.median(short)/sr*1e6:.0f} us -> ~{sr/np.median(short):.0f} baud (expect 9600)")

# --- UART, inverted: start bit = rising edge, data bits inverted, parity, stop
rises = np.flatnonzero((s[:-1] == 0) & (s[1:] == 1)) + 1
bytes_ = []; nxt = 0; n = len(s); bad_par = bad_stop = 0
for i in rises:
    if i < nxt: continue
    mid = i + spb / 2
    idx = (mid + spb * np.arange(1, 11)).astype(np.int64)      # 8 data, parity, stop
    if idx[-1] >= n: break
    bits = 1 - s[idx]                                            # un-invert
    v = int((bits[:8] << np.arange(8)).sum())
    par_ok = (bits[:9].sum() % 2) == 0                           # even parity incl. parity bit
    stop_ok = bits[9] == 1
    if not par_ok: bad_par += 1
    if not stop_ok: bad_stop += 1
    bytes_.append((i / sr, v, par_ok and stop_ok)); nxt = int(i + spb * 10.5)   # next start can only follow the stop bit
print(f"bytes: {len(bytes_)}, parity errors {bad_par}, stop-bit errors {bad_stop}")
if bytes_ and (bad_par + bad_stop) > len(bytes_) * 0.2:
    print("  >>> lots of errors: wrong baud/parity/polarity? try the other polarity or 4800/19200 by changing BAUD")

# --- frames
ADDR = {0x21: "MAIN", 0x22: "DRYER", 0x25: "INV", 0x2A: "PANEL", 0x00: "ALL"}
STATE = {1: "idle (on, not running)", 2: "RUNNING", 3: "finished", 4: "paused", 6: "waiting lid unlock",
         8: "delayed start", 9: "ERROR", 0xB: "standby/off"}
PHASE = {0: "idle", 1: "pre-wash", 2: "wash", 3: "rinse", 4: "spin"}
def meaning(d):
    if not d: return ""
    t = d[0]
    if t == 0x5F: return "heartbeat"
    if t == 0x52 and len(d) >= 3:
        m = f"STATE {STATE.get(d[2], f'{d[2]:02X}?')}"
        if len(d) >= 4: m += f", phase {PHASE.get(d[3], f'{d[3]:02X}?')}"
        if len(d) >= 6: m += f", flags {d[5]:02X}" + (" (lid open)" if d[5] & 0x08 else "")   # 0x08 = lid on the WWT8084J7WA
        return m
    if t == 0x56 and len(d) >= 5:
        v = (d[3] << 8) | d[4]
        k = {0: "program time left", 1: "delay-start left (x10 s)", 2: "total hours x10", 3: "cycle count"}.get(d[2], f"time sub {d[2]:02X}")
        return f"TIME {k} = {'off' if v == 0xFFFF else v}"
    # temperature and delay sit elsewhere on my top loader than on the EWX14, so only spin and programme here
    if t == 0x50: return "PROGRAM SET " + (f"spin {d[3]*50} prog {d[12]}" if len(d) >= 13 else "")
    if t == 0x51: return "STATE CHANGE cmd " + (f"{d[2]:02X}" if len(d) > 2 else "")
    if t == 0x57: return "ALARM " + (f"E{d[2]-1:02X}" if len(d) > 2 and d[2] else "none")
    if t == 0x11: return "sw version/provisioning"
    if t == 0x10: return "wakeup"
    if t == 0x12: return "inverter state"
    return f"type {t:02X}"
frames = []; i = 0; bad_chk = 0; junk = 0
while i < len(bytes_):
    t, b, ok = bytes_[i]
    if b == 0x98 and i + 2 < len(bytes_):
        frames.append((t, "ACK", None, None, [bytes_[i+1][1], bytes_[i+2][1]])); i += 3; continue
    if b == 0xC9 and i + 3 < len(bytes_):
        ln = bytes_[i+3][1]; end = i + 4 + ln + 1
        if ln and end <= len(bytes_):
            fr = [x[1] for x in bytes_[i:end]]
            chk = 0
            for x in fr[:-1]: chk ^= x
            if chk == fr[-1]:
                frames.append((t, "MSG", fr[1], fr[2], fr[4:-1])); i = end; continue
            bad_chk += 1
    junk += 1; i += 1
print(f"frames: {sum(1 for x in frames if x[1]=='MSG')} messages, {sum(1 for x in frames if x[1]=='ACK')} acks, "
      f"{bad_chk} checksum fails, {junk} stray bytes\n")
last = {}
for t, kind, to, frm, d in frames:
    if kind == "ACK": continue
    key = (frm, to, d[0] if d else None); hx = " ".join(f"{x:02X}" for x in d)
    if last.get(key) == hx: continue                    # only print when the content changes
    last[key] = hx
    print(f"{t:8.3f}s {ADDR.get(frm, f'{frm:02X}'):>5} -> {ADDR.get(to, f'{to:02X}'):<5} {hx:<48} {meaning(d)}")
print("\nsummary (from -> to, type): count")
c = Counter((ADDR.get(x[3], f'{x[3]:02X}'), ADDR.get(x[2], f'{x[2]:02X}'), f"{x[4][0]:02X}" if x[4] else "-") for x in frames if x[1] == "MSG")
for k, v in sorted(c.items(), key=lambda kv: -kv[1]): print(f"  {k[0]:>5} -> {k[1]:<5} {k[2]}: {v}")
