| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231 |
- """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
- STARTUP_TIMEOUT_MS = 5000
- 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)
- @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 calibration can seek/measure quickly.
- 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)
- # Count STEP rises during measure-open, then assert open limits.
- x_rises = {"n": 0}
- async def count_x():
- while True:
- await RisingEdge(dut.x_step)
- x_rises["n"] += 1
- counter = cocotb.start_soon(count_x())
- # Wait until all axes likely produced >=2 rises (1 kHz steps).
- for _ in range(20000):
- await clocks(dut, 2500)
- if x_rises["n"] >= 2:
- break
- dut.x_limit_hs.value = 1
- dut.y_limit_hs.value = 1
- dut.z_limit_hs.value = 1
- dut.x_limit_ls.value = 0
- dut.y_limit_ls.value = 0
- dut.z_limit_ls.value = 0
- 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["n"])
- counter.kill()
- # 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
- assert status[-2:] == crc16(status[2:-2]).to_bytes(2, "little")
- assert status[4] & 0x40 # startup_complete
- 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
|