"""Real UART-bit e2e: startup_complete, SET_ALL percent, GET_TEMPERATURE, GET_MOTOR_STATUS.""" import cocotb import cocotb.simulator as simulator from cocotb.triggers import FallingEdge, NextTimeStep, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout from cocotb.utils import get_sim_time CLKS_PER_BIT = 217 SET_ALL = 0x01 GET_TEMPERATURE = 0x02 GET_MOTOR_STATUS = 0x03 TEMPERATURE_DATA = 0x82 MOTOR_STATUS_DATA = 0x83 # Serial X→Y→Z measure-open + profile; DDA service is real-time (tick_500us only is accelerated). STARTUP_TIMEOUT_MS = 30000 TEMPERATURE_BYTE_TIMEOUT_MS = 100 STATUS_BYTE_TIMEOUT_MS = 100 FRAME_ACCEPT_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") def _sim_time_ns() -> str: try: return f"{get_sim_time(unit='ns'):.0f}ns" except Exception: return "unknown" def checkpoint(stage: str, **fields) -> None: extra = " ".join(f"{key}={value}" for key, value in fields.items()) suffix = f" {extra}" if extra else "" cocotb.log.info("checkpoint stage=%s sim_time=%s%s", stage, _sim_time_ns(), suffix) async def clocks(dut, count: int) -> None: clk = getattr(getattr(dut, "u_dut", None), "sys_clk", None) if clk is None: await Timer(count * 40, unit="ns") return for _ in range(count): await RisingEdge(clk) 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 receive_uart_byte(dut) -> int: # Idle-high then start bit. Caller may arm this before send completes so the # first response start edge is not missed (DUT can TX during last RX stop). if int(dut.host_uart_tx.value) != 1: await RisingEdge(dut.host_uart_tx) await FallingEdge(dut.host_uart_tx) await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2) value = 0 for bit in range(8): value |= int(dut.host_uart_tx.value) << bit await clocks(dut, CLKS_PER_BIT) stop = int(dut.host_uart_tx.value) if stop != 1: raise AssertionError( f"uart stop-bit framing error value=0x{value:02x} stop={stop} " f"sim_time={_sim_time_ns()}" ) return value async def receive_exact(dut, nbytes: int, timeout_ms: int, stage: str) -> bytes: out = bytearray() for byte_index in range(nbytes): out.append( await wait_for_stage( receive_uart_byte(dut), timeout_ms, stage, byte_index, ) ) return bytes(out) async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1, **fields): try: return await with_timeout(awaitable, timeout_ms, "ms") except SimTimeoutError as exc: suffix = "" if byte_index < 0 else f" byte_index={byte_index}" extra = "".join(f" {key}={value}" for key, value in fields.items()) raise AssertionError( f"timeout stage={stage} timeout_ms={timeout_ms} sim_time={_sim_time_ns()}" f"{suffix}{extra}" ) from exc async def wait_level_or_edge(signal, *, want: int, timeout_ms: int, stage: str) -> None: current = int(signal.value) if signal.value.is_resolvable else None if current == want: checkpoint(stage, already=want) return edge = RisingEdge(signal) if want else FallingEdge(signal) await wait_for_stage(edge, timeout_ms, stage, signal_level=current, want=want) async def wait_measure_rises_then_open( dut, *, step_sig, limit_ls, limit_hs, axis_name: str, min_rises: int = 2, ) -> int: """Serial-cal friendly: wait for this axis's measure-open STEP rises, then hit open only.""" # Let the simulator advance directly to STEP activity. Iterating every # sys_clk edge here made the same bounded check take hundreds of seconds # of Python/VPI wall time despite only needing to observe two rises. rises = 0 for rise_index in range(min_rises): await wait_for_stage( RisingEdge(step_sig), 5000, f"cal_measure_{axis_name}", rise_index, ) rises += 1 limit_hs.value = 1 limit_ls.value = 0 checkpoint(f"cal_open_{axis_name}", rises=rises) # Allow limit sync + terminal handoff before the next axis starts. await clocks(dut, 4000) return rises @cocotb.test() async def test_set_all_get_temperature_over_real_uart(dut): try: checkpoint("test_start") dut.host_uart_rx.value = 1 # Begin on close limits so each serial axis can finish seek-close immediately. dut.x_limit_ls.value = 1 dut.x_limit_hs.value = 0 dut.y_limit_ls.value = 1 dut.y_limit_hs.value = 0 dut.z_limit_ls.value = 1 dut.z_limit_hs.value = 0 dut.temp_scl.value = 1 dut.temp_sda.value = 1 await clocks(dut, 2000) # A2 serial X→Y→Z: stimulate open limit per axis after its own measure-open rises. # Do not assert Y/Z open early — that strands seek-close and burns MAX_CAL_STEPS. x_rises = await wait_measure_rises_then_open( dut, step_sig=dut.x_step, limit_ls=dut.x_limit_ls, limit_hs=dut.x_limit_hs, axis_name="x" ) y_rises = await wait_measure_rises_then_open( dut, step_sig=dut.y_step, limit_ls=dut.y_limit_ls, limit_hs=dut.y_limit_hs, axis_name="y" ) z_rises = await wait_measure_rises_then_open( dut, step_sig=dut.z_step, limit_ls=dut.z_limit_ls, limit_hs=dut.z_limit_hs, axis_name="z" ) await wait_level_or_edge( dut.u_dut.startup_complete, want=1, timeout_ms=STARTUP_TIMEOUT_MS, stage="startup_complete", ) checkpoint("startup_complete", x_rises=x_rises, y_rises=y_rises, z_rises=z_rises) # Clear limits for mid motion dut.x_limit_ls.value = 0 dut.x_limit_hs.value = 0 dut.y_limit_ls.value = 0 dut.y_limit_hs.value = 0 dut.z_limit_ls.value = 0 dut.z_limit_hs.value = 0 await clocks(dut, 16) # Z/X/Y percents = 50/50/50 (not jog 01/02) payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 50, 50, 50)) checkpoint("set_all_tx") await send_frame(dut, frame(SET_ALL, payload)) await clocks(dut, CLKS_PER_BIT * 16) assert int(dut.motor_en_n.value) == 1 await wait_level_or_edge( dut.u_dut.frame_accept_enable, want=1, timeout_ms=FRAME_ACCEPT_TIMEOUT_MS, stage="frame_accept_enable", ) checkpoint("get_motor_status_tx") # Arm RX before/during TX so DUT's first start bit is not missed. status_task = cocotb.start_soon( receive_exact(dut, 37, STATUS_BYTE_TIMEOUT_MS, "motor_status_response") ) await send_frame(dut, frame(GET_MOTOR_STATUS, b"")) status = await status_task assert status[:4] == bytes((0xA5, 0x5A, MOTOR_STATUS_DATA, 31)) assert len(status) == 37 payload = status[4:35] assert len(payload) == 31 assert status[-2:] == crc16(status[2:-2]).to_bytes(2, "little") assert payload[0] & 0x40 # startup_complete # Byte-exact regions: X@1..10, Y@11..20, Z@21..30 (SET_ALL 50/50/50) assert payload[3] == 50 # X requested percent assert payload[13] == 50 # Y assert payload[23] == 50 # Z # Anti-misalign: first two payload bytes must not be a false duplicate # of a non-equal snap[0]/snap[1] pattern when state differs. assert payload[1] & 0x07 in range(0, 7) # X state nibble # Last byte is Z fault_code (cal success → 0) assert payload[30] == 0 checkpoint("motor_status_ok") await wait_level_or_edge( dut.u_dut.frame_accept_enable, want=1, timeout_ms=FRAME_ACCEPT_TIMEOUT_MS, stage="frame_accept_enable_2", ) checkpoint("get_temperature_tx") temp_task = cocotb.start_soon( receive_exact(dut, 33, TEMPERATURE_BYTE_TIMEOUT_MS, "temperature_response") ) await send_frame(dut, frame(GET_TEMPERATURE, b"")) response = await temp_task 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} checkpoint("temperature_response_ok", bytes=len(response)) finally: try: simulator.stop_simulator() except Exception: pass