"""Real UART-bit e2e scenario for the refactored top. This test is intentionally kept independent of the Python protocol model at the wire boundary: bytes are serialized as 8N1 bits at 217 system clocks/bit. """ import cocotb import cocotb.simulator as simulator from cocotb.triggers import Event, FallingEdge, NextTimeStep, ReadOnly, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout CLKS_PER_BIT = 217 SET_ALL = 0x01 GET_TEMPERATURE = 0x02 TEMPERATURE_DATA = 0x82 MOTOR_STEPS = 450 MOTOR_COMPLETION_TIMEOUT_MS = 600 TEMPERATURE_BYTE_TIMEOUT_MS = 100 def crc16(data: bytes) -> int: crc = 0xFFFF for value in data: crc ^= value << 8 for _ in range(8): crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF return crc def frame(kind: int, payload: bytes) -> bytes: body = bytes((kind, len(payload))) + payload return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little") async def clocks(dut, count: int) -> None: await Timer(count * 40, units="ns") async def send_uart_byte(dut, value: int) -> None: await ReadWrite() dut.host_uart_rx.value = 0 await clocks(dut, CLKS_PER_BIT) for bit in range(8): dut.host_uart_rx.value = (value >> bit) & 1 await clocks(dut, CLKS_PER_BIT) dut.host_uart_rx.value = 1 await clocks(dut, CLKS_PER_BIT) async def send_frame(dut, packet: bytes) -> None: await NextTimeStep() for value in packet: await send_uart_byte(dut, value) async def _count_axis_steps( signal, axis: str, observed: dict[str, int | bool], completion: Event, ) -> None: while observed[axis] < MOTOR_STEPS: await RisingEdge(signal) await ReadOnly() if not signal.value.is_resolvable: continue if int(signal.value): observed[axis] = int(observed[axis]) + 1 if ( observed["x"] == MOTOR_STEPS and observed["y"] == MOTOR_STEPS ): completion.set() return async def observe_motor_steps(dut, observed: dict[str, int | bool], completion: Event) -> None: # Independent axis watchers: a single-X waiter under-counts Y. x_task = cocotb.start_soon(_count_axis_steps(dut.x_step, "x", observed, completion)) y_task = cocotb.start_soon(_count_axis_steps(dut.y_step, "y", observed, completion)) try: await completion.wait() finally: stop_background_task(x_task) stop_background_task(y_task) # Overlap is approximate: true when both axes have progressed. if int(observed["x"]) > 0 and int(observed["y"]) > 0: observed["overlap"] = True async def receive_uart_byte(dut) -> int: await FallingEdge(dut.host_uart_tx) await Timer((CLKS_PER_BIT + CLKS_PER_BIT // 2) * 40, units="ns") value = 0 for bit in range(8): value |= int(dut.host_uart_tx.value) << bit await Timer(CLKS_PER_BIT * 40, units="ns") assert int(dut.host_uart_tx.value) == 1 return value async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1): """Apply a bounded wait with a stable, machine-searchable failure message.""" try: return await with_timeout(awaitable, timeout_ms, "ms") except SimTimeoutError as exc: suffix = "" if byte_index < 0 else f" byte_index={byte_index}" raise AssertionError( f"timeout stage={stage} timeout_ms={timeout_ms}{suffix}" ) from exc def stop_background_task(task) -> None: if task is None: return if hasattr(task, "cancel"): task.cancel() elif hasattr(task, "kill"): task.kill() @cocotb.test() async def test_set_all_get_temperature_over_real_uart(dut): observer_task = None observed = {"x": 0, "y": 0, "overlap": False} motor_completion = Event() try: observer_task = cocotb.start_soon( observe_motor_steps(dut, observed, motor_completion) ) dut.host_uart_rx.value = 1 dut.x_limit_raw.value = 1 dut.y_limit_raw.value = 1 dut.temp_scl.value = 1 dut.temp_sda.value = 1 await clocks(dut, 1024) # Limits already high => startup may finish during the wait above. # RisingEdge alone would hang forever if startup_done is already 1. if int(dut.u_dut.startup_done.value) == 0: await wait_for_stage( RisingEdge(dut.u_dut.startup_done), MOTOR_COMPLETION_TIMEOUT_MS, "startup_done", ) # X=01 open (DIR=0), Y=02 close (DIR=1); 450 steps each, overlapping. payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 0, 1, 2)) await send_frame(dut, frame(SET_ALL, payload)) # Sample DIR while the jog is active (before completion). await clocks(dut, CLKS_PER_BIT * 8) assert int(dut.x_dir.value) == 0, "SET_ALL X=01 must drive DIR=0 (open)" assert int(dut.y_dir.value) == 1, "SET_ALL Y=02 must drive DIR=1 (close)" try: await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms") except SimTimeoutError as exc: raise AssertionError( "timeout stage=motor_completion " f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} " f"observed_x={observed['x']} observed_y={observed['y']}" ) from exc assert observed["x"] == MOTOR_STEPS assert observed["y"] == MOTOR_STEPS assert observed["overlap"] is True assert int(dut.motor_en_n.value) == 0 await with_timeout( FallingEdge(dut.x_step), MOTOR_COMPLETION_TIMEOUT_MS, "ms", ) await RisingEdge(dut.u_dut.frame_accept_enable) await clocks(dut, 4) await send_frame(dut, frame(GET_TEMPERATURE, b"")) response = bytearray() for byte_index in range(33): response.append( await wait_for_stage( receive_uart_byte(dut), TEMPERATURE_BYTE_TIMEOUT_MS, "temperature_response", byte_index, ) ) response = bytes(response) assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27)) assert len(response) == 33 assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little") assert set(response[4:31]) == {0xFF} finally: stop_background_task(observer_task) try: simulator.stop_simulator() except Exception: pass