فهرست منبع

test(cocotb): cover full 6400 UART integration

root 3 ماه پیش
والد
کامیت
3c8a6ac0ce

+ 85 - 0
tests/cocotb/prod2u_6400_v1_cocotb_top.v

@@ -0,0 +1,85 @@
+`timescale 1ns/1ps
+
+// Full production-top UART/control fixture.  Host and BMC stay bit-serial;
+// only the CT7428 word-level response is modeled so 27-channel scans remain
+// deterministic and fast enough for integration testing.
+module prod2u_6400_v1_cocotb_top #(
+    parameter integer ENABLE_STIMULUS = 0
+) (
+    input  wire        host_rs232_rx,
+    output wire        host_rs232_tx,
+    input  wire        host_ttl_rx,
+    output wire        host_ttl_tx,
+    input  wire        bmc_rs232_rx,
+    output wire        bmc_rs232_tx,
+    input  wire        tick_1s_test,
+    output wire [23:0] ptc_pwm_out,
+    output wire [3:0]  front_fan_pwm_out,
+    output wire [3:0]  rear_fan_pwm_out,
+    output wire        sys_clk,
+    output wire        rst_n_mon,
+    output wire [2:0]  control_state_mon,
+    output wire [15:0] bmc_epoch_mon,
+    output wire [15:0] ct_epoch_mon,
+    output wire [15:0] control_epoch_mon,
+    output wire [23:0] bmc_valid_mask_mon,
+    output wire [26:0] ct_valid_mask_mon,
+    output wire [23:0] safety_mask_mon,
+    output wire [3:0]  lane_fault_mask_mon,
+    output wire        global_fault_mon,
+    output wire        stimulus_active_mon,
+    output wire        pwm_boundary_mon,
+    output wire [6:0]  pwm_phase_mon,
+    output wire        pwm_deadline_miss_mon
+);
+    reg clk = 1'b0;
+    always #20 clk = ~clk;
+    assign sys_clk = clk;
+
+    tri1 temp_scl;
+    tri1 temp_sda;
+
+    prod2u_6400_v1_top #(
+        .ENABLE_STIMULUS(ENABLE_STIMULUS),
+        .CT_SCAN_PERIOD_CLKS(64)
+    ) u_dut (
+        .sys_clk(clk),
+        .host_rs232_rx(host_rs232_rx),
+        .host_rs232_tx(host_rs232_tx),
+        .host_ttl_rx(host_ttl_rx),
+        .host_ttl_tx(host_ttl_tx),
+        .bmc_rs232_rx(bmc_rs232_rx),
+        .bmc_rs232_tx(bmc_rs232_tx),
+        .ptc_pwm_out(ptc_pwm_out),
+        .front_fan_pwm_out(front_fan_pwm_out),
+        .rear_fan_pwm_out(rear_fan_pwm_out),
+        .temp_scl(temp_scl),
+        .temp_sda(temp_sda)
+    );
+
+    // The physical I2C master has its own module tests.  This fixture keeps
+    // the production CT scheduler/banks/mapping and supplies one valid 60 C
+    // word for every requested channel.
+    initial begin
+        force u_dut.tick_1s = tick_1s_test;
+        force u_dut.ct_request_ready = 1'b1;
+        force u_dut.ct_response_valid = 1'b1;
+        force u_dut.ct_response_data = 16'h3c00;
+        force u_dut.ct_response_error = 4'd0;
+    end
+
+    assign rst_n_mon = u_dut.rst_n;
+    assign control_state_mon = u_dut.control_state;
+    assign bmc_epoch_mon = u_dut.bmc_epoch;
+    assign ct_epoch_mon = u_dut.ct_epoch;
+    assign control_epoch_mon = u_dut.control_epoch;
+    assign bmc_valid_mask_mon = u_dut.bmc_valid_mask;
+    assign ct_valid_mask_mon = u_dut.ct_valid_mask;
+    assign safety_mask_mon = u_dut.safety_mask;
+    assign lane_fault_mask_mon = u_dut.lane_fault_mask;
+    assign global_fault_mon = u_dut.global_fault;
+    assign stimulus_active_mon = u_dut.stimulus_active;
+    assign pwm_boundary_mon = u_dut.pwm_boundary;
+    assign pwm_phase_mon = u_dut.pwm_phase;
+    assign pwm_deadline_miss_mon = u_dut.pwm_deadline_miss;
+endmodule

+ 68 - 0
tests/cocotb/run_6400_v1_integration.py

@@ -0,0 +1,68 @@
+#!/usr/bin/env python3
+"""Run control and identification full-top cocotb integration profiles."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+import tempfile
+import xml.etree.ElementTree as ET
+
+try:
+    from cocotb_tools.runner import get_runner
+except ModuleNotFoundError:  # cocotb 1.9 compatibility in the pinned image
+    from cocotb.runner import get_runner
+
+
+ROOT = Path(__file__).resolve().parents[2]
+TEST_DIR = Path(__file__).resolve().parent
+CLOSURE = ROOT / "products/6400-control/source-closure.json"
+WRAPPER = TEST_DIR / "prod2u_6400_v1_cocotb_top.v"
+
+
+def rtl_sources() -> list[Path]:
+    payload = json.loads(CLOSURE.read_text(encoding="utf-8"))
+    return [ROOT / item for item in payload["sources"] if item.endswith(".v")]
+
+
+def run_profile(name: str, enable_stimulus: int, build_dir: Path) -> None:
+    runner = get_runner("icarus")
+    runner.build(
+        sources=[*rtl_sources(), WRAPPER],
+        hdl_toplevel="prod2u_6400_v1_cocotb_top",
+        build_dir=build_dir,
+        build_args=["-g2012", "-I", str(ROOT)],
+        parameters={"ENABLE_STIMULUS": enable_stimulus},
+        always=True,
+    )
+    results_path = build_dir / "results.xml"
+    result = Path(runner.test(
+        hdl_toplevel="prod2u_6400_v1_cocotb_top",
+        test_module=f"test_6400_v1_{name}_integration",
+        test_dir=TEST_DIR,
+        build_dir=build_dir,
+        results_xml=str(results_path),
+    ))
+    root = ET.parse(result).getroot()
+    cases = root.findall(".//testcase")
+    failures = root.findall(".//failure") + root.findall(".//error")
+    skipped = root.findall(".//skipped")
+    if not cases or failures or skipped:
+        raise RuntimeError(
+            f"cocotb {name} profile incomplete: "
+            f"cases={len(cases)} failures={len(failures)} skipped={len(skipped)} "
+            f"results={result}"
+        )
+
+
+def main() -> int:
+    with tempfile.TemporaryDirectory(prefix="prod2u-6400-cocotb-") as directory:
+        root = Path(directory)
+        run_profile("control", 0, root / "control")
+        run_profile("identification", 1, root / "identification")
+    print("PASS: 6400 control and identification cocotb integration")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 203 - 0
tests/cocotb/test_6400_v1_control_integration.py

@@ -0,0 +1,203 @@
+"""Production-profile full-top integration over real Host and BMC UART bits."""
+
+from __future__ import annotations
+
+import cocotb
+from cocotb.triggers import Timer, with_timeout
+
+from thermal_6400_uart import (
+    BMC_CLKS_PER_BIT,
+    CLOCK_NS,
+    HOST_CLKS_PER_BIT,
+    SET_STIMULUS,
+    SET_TARGET,
+    SET_TARGET_ACK,
+    bring_auto,
+    check_pwm_timing,
+    encode_frame,
+    get_snapshot,
+    host_transaction,
+    pulse_tick_1s,
+    receive_frame,
+    send_bmc_snapshot,
+    send_uart,
+    wait_for,
+)
+
+
+def duties(snapshot: dict[str, object], name: str) -> list[int]:
+    value = snapshot[name]
+    assert isinstance(value, list)
+    return [int(item) for item in value]
+
+
+@cocotb.test()
+async def test_control_dual_host_sensor_safety_and_snapshot(dut):
+    pwm_timing = cocotb.start_soon(check_pwm_timing(dut))
+    await bring_auto(dut)
+
+    # Production must silently reject the identification-only command.
+    rejected_payload = bytes([2, *([20] * 32)])
+    await send_uart(
+        dut.host_rs232_rx,
+        encode_frame(SET_STIMULUS, rejected_payload),
+        HOST_CLKS_PER_BIT,
+    )
+    await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 20, units="ns")
+    assert int(dut.host_rs232_tx.value) == 1
+    assert int(dut.host_ttl_tx.value) == 1
+    assert int(dut.stimulus_active_mon.value) == 0
+
+    # Exercise simultaneous Host and BMC receive frontends.  ACK is routed
+    # only to RS-232 while the BMC commits a complete fifth snapshot.
+    old_control_epoch = int(dut.control_epoch_mon.value)
+    bmc_task = cocotb.start_soon(send_bmc_snapshot(dut, [61] * 24))
+    ack_task = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
+    await send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x41"), HOST_CLKS_PER_BIT)
+    ack_kind, ack_payload = await with_timeout(ack_task, 20, "ms")
+    assert (ack_kind, ack_payload) == (SET_TARGET_ACK, b"")
+    assert int(dut.host_ttl_tx.value) == 1
+    await bmc_task
+    # A target change deliberately restarts CT/preheat qualification.  The
+    # concurrent BMC frame enters WAIT_BMC_STABLE; three further new epochs
+    # are required before AUTO resumes.
+    for _ in range(3):
+        await send_bmc_snapshot(dut, [61] * 24)
+    await wait_for(
+        dut,
+        lambda: int(dut.control_state_mon.value) == 4
+        and int(dut.control_epoch_mon.value) > old_control_epoch,
+        cycles=1000,
+        label="target/BMC control commit",
+    )
+    await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
+
+    snapshot = await get_snapshot(dut, "ttl")
+    assert snapshot["control_state"] == 4
+    assert snapshot["current_target"] == 65
+    assert snapshot["host_target_seen"] == 1
+    assert int(snapshot["bmc_epoch"]) >= 5
+    assert int(snapshot["ct_epoch"]) >= 1
+    assert snapshot["bmc_valid_mask"] == (1 << 24) - 1
+    assert snapshot["ct_valid_mask"] == (1 << 27) - 1
+    assert duties(snapshot, "bmc_raw") == [0x3D00] * 24
+    assert duties(snapshot, "ct_raw") == [0x3C00] * 27
+    ptc = duties(snapshot, "ptc_applied")
+    assert len(ptc) == 24 and all(0 <= value <= 100 for value in ptc) and any(ptc)
+    assert duties(snapshot, "front_applied") == [30] * 4
+    assert duties(snapshot, "rear_applied") == [30] * 4
+
+    # A 74 C sample reduces only the matching PTC and raises both fans for
+    # that lane to the contract's 80% protection duty.  The public safety bit
+    # remains telemetry and must not turn the soft action into a full cutoff.
+    old_control_epoch = int(dut.control_epoch_mon.value)
+    await send_bmc_snapshot(dut, [74, *([60] * 23)])
+    await wait_for(
+        dut,
+        lambda: int(dut.control_epoch_mon.value) > old_control_epoch,
+        cycles=1000,
+        label="74 C soft-limit commit",
+    )
+    soft = await get_snapshot(dut, "rs232")
+    soft_ptc = duties(soft, "ptc_applied")
+    assert int(soft["safety_override_mask"]) & 1
+    assert ptc[0] > 1 and soft_ptc[0] == ptc[0] - 1
+    assert duties(soft, "front_applied") == [80, 30, 30, 30]
+    assert duties(soft, "rear_applied") == [80, 30, 30, 30]
+
+    # At 76 C the matching PTC is fully off, but the lane is not yet hard
+    # faulted and therefore remains at 80% rather than 100% airflow.
+    old_control_epoch = int(dut.control_epoch_mon.value)
+    await send_bmc_snapshot(dut, [76, *([60] * 23)])
+    await wait_for(
+        dut,
+        lambda: int(dut.control_epoch_mon.value) > old_control_epoch,
+        cycles=1000,
+        label="76 C pretrip commit",
+    )
+    pretrip = await get_snapshot(dut, "ttl")
+    assert int(pretrip["safety_override_mask"]) & 1
+    assert not (int(pretrip["lane_fault_mask"]) & 1)
+    assert duties(pretrip, "ptc_applied")[0] == 0
+    assert duties(pretrip, "front_applied") == [80, 30, 30, 30]
+    assert duties(pretrip, "rear_applied") == [80, 30, 30, 30]
+
+    # One invalid DIMM is quarantined without corrupting the other 23 values.
+    await send_bmc_snapshot(dut, [None, *([60] * 23)])
+    await wait_for(
+        dut,
+        lambda: int(dut.control_state_mon.value) == 5 and bool(int(dut.safety_mask_mon.value) & 1),
+        cycles=1000,
+        label="single-channel invalid override",
+    )
+    invalid = await get_snapshot(dut, "rs232")
+    assert int(invalid["bmc_valid_mask"]) == ((1 << 24) - 2)
+    assert int(invalid["safety_override_mask"]) & 1
+    assert duties(invalid, "ptc_applied")[0] == 0
+
+    # A 77 C sample latches the full L0 hard override and both lane fans.
+    await send_bmc_snapshot(dut, [77, *([60] * 23)])
+    await wait_for(
+        dut,
+        lambda: bool(int(dut.lane_fault_mask_mon.value) & 1),
+        cycles=1000,
+        label="lane hard limit",
+    )
+    hard = await get_snapshot(dut, "ttl")
+    assert int(hard["lane_fault_mask"]) & 1
+    assert duties(hard, "ptc_applied")[:6] == [0] * 6
+    assert duties(hard, "front_applied")[0] == 100
+    assert duties(hard, "rear_applied")[0] == 100
+
+    # Three explicit age ticks without a new BMC epoch create global stale.
+    await pulse_tick_1s(dut, 3)
+    await wait_for(
+        dut,
+        lambda: int(dut.global_fault_mon.value) == 1,
+        cycles=200,
+        label="global BMC stale",
+    )
+    stale = await get_snapshot(dut, "rs232")
+    assert stale["global_fault"] == 1
+    assert duties(stale, "ptc_applied") == [0] * 24
+    assert duties(stale, "front_applied") == [100] * 4
+    assert duties(stale, "rear_applied") == [100] * 4
+
+    # Three complete safe epochs retain the clamp through the release commit;
+    # the following epoch resumes only the normal slew-limited ramp.
+    for _ in range(3):
+        await send_bmc_snapshot(dut, [60] * 24)
+        await wait_for(
+            dut,
+            lambda: int(dut.control_epoch_mon.value) >= 1,
+            cycles=1000,
+            label="recovery control pass",
+        )
+    await wait_for(
+        dut,
+        lambda: int(dut.global_fault_mon.value) == 0
+        and int(dut.lane_fault_mask_mon.value) == 0
+        and int(dut.control_state_mon.value) == 4,
+        cycles=1000,
+        label="three-epoch recovery",
+    )
+    released = await get_snapshot(dut, "ttl")
+    assert duties(released, "ptc_applied") == [0] * 24
+    await send_bmc_snapshot(dut, [60] * 24)
+    await wait_for(
+        dut,
+        lambda: int(dut.control_epoch_mon.value) > int(released["control_epoch"]),
+        cycles=1000,
+        label="post-recovery limited ramp",
+    )
+    ramped = await get_snapshot(dut, "rs232")
+    assert all(0 <= value <= 5 for value in duties(ramped, "ptc_applied"))
+    assert any(duties(ramped, "ptc_applied"))
+
+    kind, payload = await host_transaction(dut, "ttl", SET_TARGET, b"\x00")
+    assert (kind, payload) == (SET_TARGET_ACK, b"")
+    stopped = await get_snapshot(dut, "rs232")
+    assert stopped["control_state"] == 6
+    assert duties(stopped, "ptc_applied") == [0] * 24
+
+    await pwm_timing

+ 116 - 0
tests/cocotb/test_6400_v1_identification_integration.py

@@ -0,0 +1,116 @@
+"""Identification-profile stimulus lifetime and safety integration."""
+
+from __future__ import annotations
+
+import cocotb
+
+from thermal_6400_uart import (
+    SET_STIMULUS,
+    SET_STIMULUS_ACK,
+    bring_auto,
+    get_snapshot,
+    host_transaction,
+    pulse_tick_1s,
+    send_bmc_snapshot,
+    wait_for,
+)
+
+
+def array(snapshot: dict[str, object], name: str) -> list[int]:
+    value = snapshot[name]
+    assert isinstance(value, list)
+    return [int(item) for item in value]
+
+
+@cocotb.test()
+async def test_identification_stimulus_expires_and_safety_preempts(dut):
+    await bring_auto(dut)
+
+    ptc = [20 + (index % 3) for index in range(24)]
+    front = [20, 30, 40, 50]
+    rear = [50, 40, 30, 20]
+    stimulus = bytes([2, *ptc, *front, *rear])
+    kind, payload = await host_transaction(dut, "rs232", SET_STIMULUS, stimulus)
+    assert (kind, payload) == (SET_STIMULUS_ACK, b"")
+    assert int(dut.stimulus_active_mon.value) == 1
+
+    old_control_epoch = int(dut.control_epoch_mon.value)
+    await send_bmc_snapshot(dut, [60] * 24)
+    await wait_for(
+        dut,
+        lambda: int(dut.control_epoch_mon.value) > old_control_epoch,
+        cycles=1000,
+        label="stimulus output commit",
+    )
+    active = await get_snapshot(dut, "ttl")
+    assert array(active, "ptc_requested") == ptc
+    assert array(active, "ptc_applied") == ptc
+    assert array(active, "front_requested") == front
+    assert array(active, "front_applied") == front
+    assert array(active, "rear_requested") == rear
+    assert array(active, "rear_applied") == rear
+
+    await pulse_tick_1s(dut)
+    assert int(dut.stimulus_active_mon.value) == 1
+    await pulse_tick_1s(dut)
+    assert int(dut.stimulus_active_mon.value) == 0
+    old_control_epoch = int(dut.control_epoch_mon.value)
+    await send_bmc_snapshot(dut, [60] * 24)
+    await wait_for(
+        dut,
+        lambda: int(dut.control_epoch_mon.value) > old_control_epoch,
+        cycles=1000,
+        label="autonomous resume after stimulus expiry",
+    )
+    resumed = await get_snapshot(dut, "rs232")
+    assert resumed["control_state"] == 4
+    assert array(resumed, "ptc_applied") != ptc
+
+    # A fresh stimulus is terminated immediately by the 77 C lane override.
+    stimulus = bytes([3, *([35] * 24), *([25] * 4), *([45] * 4)])
+    kind, payload = await host_transaction(dut, "ttl", SET_STIMULUS, stimulus)
+    assert (kind, payload) == (SET_STIMULUS_ACK, b"")
+    assert int(dut.stimulus_active_mon.value) == 1
+
+    # Per-channel thermal protection has priority over an active stimulus.
+    old_control_epoch = int(dut.control_epoch_mon.value)
+    await send_bmc_snapshot(dut, [74, *([60] * 23)])
+    await wait_for(
+        dut,
+        lambda: int(dut.control_epoch_mon.value) > old_control_epoch,
+        cycles=1000,
+        label="soft-limit stimulus preemption",
+    )
+    soft = await get_snapshot(dut, "rs232")
+    assert int(dut.stimulus_active_mon.value) == 1
+    assert array(soft, "ptc_applied")[0] < 35
+    assert array(soft, "ptc_applied")[1:6] == [35] * 5
+    assert array(soft, "front_applied")[0] == 80
+    assert array(soft, "rear_applied")[0] == 80
+
+    old_control_epoch = int(dut.control_epoch_mon.value)
+    await send_bmc_snapshot(dut, [76, *([60] * 23)])
+    await wait_for(
+        dut,
+        lambda: int(dut.control_epoch_mon.value) > old_control_epoch,
+        cycles=1000,
+        label="pretrip stimulus preemption",
+    )
+    pretrip = await get_snapshot(dut, "ttl")
+    assert int(dut.stimulus_active_mon.value) == 1
+    assert array(pretrip, "ptc_applied")[0] == 0
+    assert array(pretrip, "front_applied")[0] == 80
+    assert array(pretrip, "rear_applied")[0] == 80
+
+    await send_bmc_snapshot(dut, [77, *([60] * 23)])
+    await wait_for(
+        dut,
+        lambda: int(dut.stimulus_active_mon.value) == 0
+        and bool(int(dut.lane_fault_mask_mon.value) & 1),
+        cycles=1000,
+        label="hard-limit stimulus preemption",
+    )
+    hard = await get_snapshot(dut, "rs232")
+    assert array(hard, "ptc_applied")[:6] == [0] * 6
+    assert array(hard, "front_applied")[0] == 100
+    assert array(hard, "rear_applied")[0] == 100

+ 229 - 0
tests/cocotb/thermal_6400_uart.py

@@ -0,0 +1,229 @@
+"""Shared real-bit UART helpers for the 6400 cocotb integration tests."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Callable, Iterable
+
+import cocotb
+from cocotb.triggers import FallingEdge, ReadOnly, RisingEdge, Timer, with_timeout
+
+
+ROOT = Path(__file__).resolve().parents[2]
+HOST_CLKS_PER_BIT = 27
+BMC_CLKS_PER_BIT = 217
+CLOCK_NS = 40
+SET_TARGET = 0x01
+GET_SNAPSHOT = 0x02
+SET_STIMULUS = 0x03
+SET_TARGET_ACK = 0x81
+SNAPSHOT_DATA = 0x82
+SET_STIMULUS_ACK = 0x83
+
+_LAYOUT = json.loads(
+    (ROOT / "generated/6400/snapshot-layout.json").read_text(encoding="utf-8")
+)
+SNAPSHOT_LENGTH = _LAYOUT["payload_length"]
+FIELDS = {entry["name"]: entry for entry in _LAYOUT["fields"]}
+
+
+def crc16(data: bytes) -> int:
+    value = 0xFFFF
+    for octet in data:
+        value ^= octet << 8
+        for _ in range(8):
+            value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
+    return value
+
+
+def encode_frame(kind: int, payload: bytes = b"") -> bytes:
+    body = bytes((kind, len(payload))) + payload
+    return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
+
+
+async def clock_cycles(dut, count: int) -> None:
+    for _ in range(count):
+        await RisingEdge(dut.sys_clk)
+
+
+async def wait_for(
+    dut,
+    predicate: Callable[[], bool],
+    *,
+    cycles: int,
+    label: str,
+) -> None:
+    for _ in range(cycles):
+        if predicate():
+            return
+        await RisingEdge(dut.sys_clk)
+    raise AssertionError(f"timeout waiting for {label}")
+
+
+async def send_uart_byte(signal, value: int, clocks_per_bit: int) -> None:
+    signal.value = 0
+    await Timer(clocks_per_bit * CLOCK_NS, units="ns")
+    for bit in range(8):
+        signal.value = (value >> bit) & 1
+        await Timer(clocks_per_bit * CLOCK_NS, units="ns")
+    signal.value = 1
+    await Timer(clocks_per_bit * CLOCK_NS, units="ns")
+
+
+async def send_uart(signal, data: Iterable[int], clocks_per_bit: int) -> None:
+    for value in data:
+        await send_uart_byte(signal, value, clocks_per_bit)
+
+
+async def receive_uart_byte(signal, clocks_per_bit: int) -> int:
+    if signal.value.is_resolvable and int(signal.value) == 0:
+        await RisingEdge(signal)
+    await FallingEdge(signal)
+    await Timer(clocks_per_bit * 60, units="ns")
+    value = 0
+    for bit in range(8):
+        value |= int(signal.value) << bit
+        await Timer(clocks_per_bit * CLOCK_NS, units="ns")
+    assert int(signal.value) == 1, f"UART stop-bit failure for 0x{value:02x}"
+    return value
+
+
+async def receive_frame(signal, clocks_per_bit: int = HOST_CLKS_PER_BIT) -> tuple[int, bytes]:
+    header = bytes([await receive_uart_byte(signal, clocks_per_bit) for _ in range(4)])
+    assert header[:2] == b"\xA5\x5A", f"bad response header {header.hex()}"
+    payload_and_crc = bytes(
+        [await receive_uart_byte(signal, clocks_per_bit) for _ in range(header[3] + 2)]
+    )
+    packet = header + payload_and_crc
+    assert packet[-2:] == crc16(packet[2:-2]).to_bytes(2, "little")
+    return header[2], packet[4:-2]
+
+
+async def host_transaction(dut, port: str, kind: int, payload: bytes = b"") -> tuple[int, bytes]:
+    rx = getattr(dut, f"host_{port}_rx")
+    tx = getattr(dut, f"host_{port}_tx")
+    response = cocotb.start_soon(receive_frame(tx))
+    await send_uart(rx, encode_frame(kind, payload), HOST_CLKS_PER_BIT)
+    result = await with_timeout(response, 20, "ms")
+    # receive_frame returns at the center of the final stop bit; allow the
+    # physical UART byte_done and port-selector unlock to retire.
+    await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
+    return result
+
+
+def bmc_payload(temperatures: Iterable[int | None]) -> bytes:
+    values = list(temperatures)
+    assert len(values) == 24
+    raw = bytearray()
+    for temperature in values:
+        if temperature is None:
+            raw.extend((0xFF, 0xFF))
+        else:
+            assert 0 <= temperature <= 254
+            raw.extend((temperature, 0))
+    return bytes(raw)
+
+
+async def send_bmc_snapshot(dut, temperatures: Iterable[int | None]) -> None:
+    raw = bmc_payload(temperatures)
+    line = ("".join(f"{value:02x}" for value in raw) + "\r").encode("ascii")
+    old_epoch = int(dut.bmc_epoch_mon.value)
+    await send_uart(dut.bmc_rs232_rx, line, BMC_CLKS_PER_BIT)
+    await wait_for(
+        dut,
+        lambda: int(dut.bmc_epoch_mon.value) == ((old_epoch + 1) & 0xFFFF),
+        cycles=200,
+        label="BMC snapshot commit",
+    )
+
+
+async def pulse_tick_1s(dut, count: int = 1) -> None:
+    for _ in range(count):
+        await FallingEdge(dut.sys_clk)
+        dut.tick_1s_test.value = 1
+        await RisingEdge(dut.sys_clk)
+        await FallingEdge(dut.sys_clk)
+        dut.tick_1s_test.value = 0
+
+
+async def initialize(dut) -> None:
+    dut.host_rs232_rx.value = 1
+    dut.host_ttl_rx.value = 1
+    dut.bmc_rs232_rx.value = 1
+    dut.tick_1s_test.value = 0
+    await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
+    await wait_for(
+        dut,
+        lambda: int(dut.ct_epoch_mon.value) >= 1,
+        cycles=500,
+        label="first 27-channel CT epoch",
+    )
+    assert int(dut.ct_valid_mask_mon.value) == (1 << 27) - 1
+    await wait_for(
+        dut,
+        lambda: int(dut.control_state_mon.value) == 2,
+        cycles=100,
+        label="PREHEAT_CT",
+    )
+    assert int(dut.global_fault_mon.value) == 0
+
+
+async def bring_auto(dut, temperature: int = 60) -> None:
+    await initialize(dut)
+    for _ in range(4):
+        await send_bmc_snapshot(dut, [temperature] * 24)
+    await wait_for(
+        dut,
+        lambda: int(dut.control_state_mon.value) == 4 and int(dut.control_epoch_mon.value) >= 1,
+        cycles=1000,
+        label="AUTO_BMC control commit",
+    )
+    assert int(dut.bmc_valid_mask_mon.value) == (1 << 24) - 1
+
+
+def decode_snapshot(payload: bytes) -> dict[str, object]:
+    assert len(payload) == SNAPSHOT_LENGTH
+    decoded: dict[str, object] = {}
+    for name, field in FIELDS.items():
+        start = field["offset"]
+        data = payload[start : start + field["size"]]
+        if field["type"] == "u8" and field.get("count", 1) == 1:
+            decoded[name] = data[0]
+        elif field["type"] == "u8":
+            decoded[name] = list(data)
+        elif field["type"] == "u16" and field.get("count", 1) == 1:
+            decoded[name] = int.from_bytes(data, "little")
+        elif field["type"] == "u16":
+            decoded[name] = [
+                int.from_bytes(data[index : index + 2], "little")
+                for index in range(0, len(data), 2)
+            ]
+        elif field["type"] == "bytes":
+            decoded[name] = int.from_bytes(data, "little")
+        else:
+            decoded[name] = list(data)
+    return decoded
+
+
+async def get_snapshot(dut, port: str = "ttl") -> dict[str, object]:
+    kind, payload = await host_transaction(dut, port, GET_SNAPSHOT)
+    assert kind == SNAPSHOT_DATA
+    return decode_snapshot(payload)
+
+
+async def check_pwm_timing(dut) -> None:
+    await RisingEdge(dut.pwm_boundary_mon)
+    first_phase = int(dut.pwm_phase_mon.value)
+    for offset in range(1, 101):
+        clocks = 0
+        while True:
+            await RisingEdge(dut.sys_clk)
+            await ReadOnly()
+            clocks += 1
+            if int(dut.pwm_boundary_mon.value):
+                break
+        assert clocks == 500
+        assert int(dut.pwm_deadline_miss_mon.value) == 0
+        if offset == 100:
+            assert int(dut.pwm_phase_mon.value) == first_phase

+ 7 - 1
tools/run_6400_v1.py

@@ -83,9 +83,13 @@ def unit() -> None:
     ])
 
 
+def cocotb_integration() -> None:
+    run(["python3", "tests/cocotb/run_6400_v1_integration.py"])
+
+
 def main() -> int:
     parser = argparse.ArgumentParser()
-    parser.add_argument("action", choices=("generate", "lint", "sim", "unit", "all"))
+    parser.add_argument("action", choices=("generate", "lint", "sim", "cocotb", "unit", "all"))
     args = parser.parse_args()
     if args.action in ("generate", "all"):
         generate()
@@ -93,6 +97,8 @@ def main() -> int:
         lint()
     if args.action in ("sim", "all"):
         simulation()
+    if args.action in ("cocotb", "all"):
+        cocotb_integration()
     if args.action in ("unit", "all"):
         unit()
     return 0