main
John Lauer Software 1.3.1: test-stage firmware (J4 TMC2209, HOME, limits, self-test), Stage tab and Calibrate in smi-dash (simulat… c0c5c9b
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Drive the board contract's text commands into ctl_pty (the firmware's control
and text code behind a pseudo-terminal) and check the STATE frames and replies.
    ./ctl_pty 20 > pty.txt &  python3 text_cmd_test.py "$(head -1 pty.txt)" ../../dashboard/assets/controls.json
"""
import json, os, struct, sys, time, tty

pty, mapfile = sys.argv[1], sys.argv[2]
m = json.load(open(mapfile))
ids = [c["id"] for c in m["controls"]]
L = next(c for c in m["controls"] if c["role"] == "laser")
fd = os.open(pty, os.O_RDWR | os.O_NOCTTY)
tty.setraw(fd)   # raw, as a serial client opens it
os.set_blocking(fd, False)
buf = bytearray()
fails = checks = 0


def crc16(b):
    c = 0xFFFF
    for x in b:
        c ^= x << 8
        for _ in range(8):
            c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
    return c


def frames(wait):
    global buf
    out, t = [], time.time()
    while time.time() - t < wait:
        try:
            buf += os.read(fd, 4096)
        except BlockingIOError:
            time.sleep(0.01)
        while True:
            i = buf.find(b"\xa5\x5a")
            if i < 0 or len(buf) < i + 8:
                break
            n = struct.unpack_from("<H", buf, i + 4)[0]
            if len(buf) < i + 10 + n:
                break
            f = buf[i:i + 10 + n]
            buf = buf[i + 10 + n:]
            if crc16(f[2:8 + n]) == struct.unpack_from("<H", f, 8 + n)[0]:
                out.append((f[2], bytes(f[8:8 + n])))
    return out


def state(wait=0.35):
    st = [p for t, p in frames(wait) if t == 0x12]
    p = st[-1]
    n = p[27]
    return {"on": bool(p[4] & 1), "fault": p[5], "codes": [struct.unpack_from("<H", p, 28 + 6 * i)[0] for i in range(n)]}


def cmd(line, wait=0.35):
    os.write(fd, (line + "\n").encode())
    out = frames(wait)
    for t, p in out:
        if t == 4 and p.startswith(b"error"):
            print("  reply:", p.decode())
    return out


def check(ok, what):
    global fails, checks
    checks += 1
    if not ok:
        fails += 1
        print("FAIL:", what)


li = ids.index(L["id"])
g = L["guard"]
frames(1.5)                                   # current-readback zero check (laser off)
cmd("laser 2000", 0.6)
s = state()
check(s["on"] and s["codes"][li] == 2000 - g, f"laser 2000: armed, DAC {2000 - g} ({s})")
rep = [p.decode() for t, p in cmd("laser current", 0.3) if t == 4]
check(any(f"command_code=2000; dac_code={2000 - g}" in r for r in rep), f"laser current reply {rep}")
cmd("offset B 1000")
s = state()
ob = next(i for i, c in enumerate(m["controls"]) if c["kind"] == "dac" and c["ch"] == 1 and c["role"] == "offset")
check(not s["on"] and s["codes"][ob] == 1000, f"offset B: laser disarmed first, offset code 1000 ({s})")
cmd(f"laser {g}")
s = state()
check(not s["on"], f"laser {g} (guard): disarmed")
cmd(f"laser {g + 1}", 0.6)
s = state()
check(s["on"] and s["codes"][li] == 1, f"laser {g + 1}: DAC code 1 ({s})")
cmd("head 5")
s = state()
tia = ids.index("headTiaGain"); bias = ids.index("headMonitorBias")
check(not s["on"] and s["codes"][tia] == 1 and s["codes"][bias] == 2, f"head 5: disarmed, TIA bit 1, bias code 2 ({s})")
cmd("gain 7")
s = state()
gi = [ids.index(x) for x in ("monitorSecondStageGain", "externalSecondStageGain", "externalTiaGain")]
check(all(s["codes"][i] == 1 for i in gi), f"gain 7: all three Pico selectors set ({s})")
cmd("laser 3000", 0.6)
check(state()["on"], "re-armed by a fresh laser command")
cmd("laser 99999")
check(not state()["on"], "out-of-range laser code disarms")
cmd("laser 3000", 0.6)
cmd("x" * 80)
check(not state()["on"], "over-long line disarms")
cmd("laser 3000", 0.6)
cmd("laser off")
check(not state()["on"], "laser off")

# Stage (firmware 1.3.1, the stage map's text commands), if the stand-in has one.
def stage_reply(line, wait=0.3):
    os.write(fd, (line + "\n").encode())
    return [p.decode() for t, p in frames(wait) if t == 4 and p.decode().startswith(("stage", "error"))]


def stage_frame(wait=0.6):
    st = [p for t, p in frames(wait) if t == 0x13]
    return st[-1] if st else None


r = stage_reply("stage status")
if any(x.startswith("stage ") for x in r):
    check(any("stage off homed=0" in x for x in r), f"stage disabled at boot: {r}")
    check(any("not homed" in x for x in stage_reply("stage step 10")), "stage step refused before homing")
    check(any("speed must be" in x for x in stage_reply("stage speed 700")), "stage speed 700 refused")
    stage_reply("stage home", 0.1)
    t = time.time()
    while time.time() - t < 30:
        f = stage_frame(0.3)
        if f and f[0] == 1 and f[1] & 2:
            break
    check(f is not None and f[0] == 1 and f[1] & 2 and struct.unpack_from("<i", f, 4)[0] == 0, "stage home: idle, homed, position 0 (STAGE frame)")
    check(f is not None and len(f) == 32, "STAGE frame is the 24-byte state block plus the u64 pair index")
    check(any("outside" in x for x in stage_reply("stage move 1601")), "stage move 1601 refused")
    stage_reply("stage speed 640")
    stage_reply("stage step 200", 0.8)
    f = stage_frame(0.3)
    check(f is not None and struct.unpack_from("<i", f, 4)[0] == 200, "stage step 200 at 640 pulses/s arrives in 0.8 s")
    r = stage_reply("stage current")
    check(any("IRUN=IHOLD=27/31" in x for x in r), f"stage current: {r}")
    stage_reply("stage off")
    f = stage_frame(0.7)
    check(f is not None and f[0] == 0 and not f[1] & 3, "stage off: disabled, position invalid")
print(f"{'OK' if not fails else 'FAIL'}: {checks} text-command checks, {fails} failed")
sys.exit(1 if fails else 0)