"""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_ALL = 0x01 GET_SNAPSHOT = 0x02 SET_STIMULUS = 0x03 SET_PID_TARGET = 0x04 ACK_NACK = 0x06 SNAPSHOT_DATA = 0x82 _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 def fan_connector_value(dut) -> int: front_ball = int(dut.front_fan_pwm_out.value) rear_ball = int(dut.rear_fan_pwm_out.value) return (rear_ball << 4) | ((~front_ball) & 0x0F) async def verify_boot_full_speed_then_standby(dut) -> None: # POR, both-RAM initialization, and the full-boundary handoff must expose # only the full-speed connector request. Capture the pre-edge advance # signal to prove the release itself occurs on the atomic PWM edge. saw_reset = False previous_release = 0 for _ in range(4000): await FallingEdge(dut.sys_clk) pre_boundary = int(dut.u_dut.pwm_boundary_advance.value) await RisingEdge(dut.sys_clk) await ReadOnly() reset_n = int(dut.rst_n_mon.value) release = int(dut.u_dut.boot_fan_release.value) if not reset_n: saw_reset = True if not release: assert fan_connector_value(dut) == 0xFF assert int(dut.front_fan_pwm_out.value) == 0x0 assert int(dut.rear_fan_pwm_out.value) == 0xF if release and not previous_release: assert pre_boundary == 1 break previous_release = release else: raise AssertionError("boot fan release did not complete") assert saw_reset assert int(dut.u_dut.boot_init_complete.value) == 1 # Reset-age BMC stale has higher safety priority than standby, so physical # output correctly remains 100% after the boot flag itself releases. assert fan_connector_value(dut) == 0xFF await FallingEdge(dut.sys_clk) await send_bmc_snapshot(dut, [60] * 24) await wait_for( dut, lambda: int(dut.u_dut.bmc_stale.value) == 0, cycles=200, label="fresh BMC before standby waveform", ) # Once BMC is fresh, the initialized bank is FAN_STANDBY_DUTY=10 for all # eight outputs. Start at a later phase-zero boundary so the boundary- # latched stale override has already retired without a narrow pulse. while True: await RisingEdge(dut.sys_clk) await ReadOnly() if int(dut.pwm_boundary_mon.value) and int(dut.pwm_phase_mon.value) == 0: break high_counts = [0] * 8 for sample in range(50000): connector = fan_connector_value(dut) for index in range(8): high_counts[index] += (connector >> index) & 1 if sample != 49999: await RisingEdge(dut.sys_clk) await ReadOnly() assert high_counts == [5000] * 8 async def initialize(dut, *, verify_boot: bool = False) -> 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 dut.bmc_epoch_override_enable.value = 0 dut.bmc_epoch_override_value.value = 0 if verify_boot: await verify_boot_full_speed_then_standby(dut) else: 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) in (2, 3), cycles=1000, label="PREHEAT_CT or already-qualified WAIT_BMC_STABLE", ) assert int(dut.global_fault_mon.value) == 0 await FallingEdge(dut.sys_clk) async def bring_auto(dut, temperature: int = 60, *, verify_boot: bool = False) -> None: await initialize(dut, verify_boot=verify_boot) 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]: rx = getattr(dut, f"host_{port}_rx") tx = getattr(dut, f"host_{port}_tx") async def receive_ack_then_data() -> bytes: ack_kind, ack_payload = await receive_frame(tx) assert ack_kind == ACK_NACK assert ack_payload == bytes((1, GET_SNAPSHOT, 0, 0)) data_kind, data_payload = await receive_frame(tx) assert data_kind == SNAPSHOT_DATA return data_payload response = cocotb.start_soon(receive_ack_then_data()) await send_uart(rx, encode_frame(GET_SNAPSHOT), HOST_CLKS_PER_BIT) payload = await with_timeout(response, 40, "ms") await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns") 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