| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272 |
- """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."""
- rises = {"n": 0}
- async def count_rises():
- while True:
- await RisingEdge(step_sig)
- rises["n"] += 1
- counter = cocotb.start_soon(count_rises())
- # Up to ~62.5M clocks (~2.5s sim @25MHz) per axis; service tick is 625 clks.
- for _ in range(100_000):
- await clocks(dut, 625)
- if rises["n"] >= min_rises:
- break
- else:
- counter.kill()
- raise AssertionError(
- f"insufficient measure rises axis={axis_name} rises={rises['n']} "
- f"sim_time={_sim_time_ns()}"
- )
- limit_hs.value = 1
- limit_ls.value = 0
- checkpoint(f"cal_open_{axis_name}", rises=rises["n"])
- # Allow limit sync + terminal handoff before the next axis starts.
- await clocks(dut, 4000)
- counter.kill()
- return rises["n"]
- @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
|