test_prod2u_door_temp_uart_e2e.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """Real UART-bit e2e scenario for the refactored top.
  2. This test is intentionally kept independent of the Python protocol model at the
  3. wire boundary: bytes are serialized as 8N1 bits at 217 system clocks/bit.
  4. """
  5. import cocotb
  6. from cocotb.clock import Clock
  7. from cocotb.triggers import Event, ReadOnly, RisingEdge, SimTimeoutError, with_timeout
  8. CLKS_PER_BIT = 217
  9. SET_ALL = 0x01
  10. GET_TEMPERATURE = 0x02
  11. TEMPERATURE_DATA = 0x82
  12. MOTOR_STEPS = 450
  13. MOTOR_COMPLETION_TIMEOUT_MS = 600
  14. TEMPERATURE_BYTE_TIMEOUT_MS = 100
  15. def crc16(data: bytes) -> int:
  16. crc = 0xFFFF
  17. for value in data:
  18. crc ^= value << 8
  19. for _ in range(8):
  20. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  21. return crc
  22. def frame(kind: int, payload: bytes) -> bytes:
  23. body = bytes((kind, len(payload))) + payload
  24. return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
  25. async def clocks(dut, count: int) -> None:
  26. for _ in range(count):
  27. await RisingEdge(dut.sys_clk)
  28. async def send_uart_byte(dut, value: int) -> None:
  29. dut.host_uart_rx.value = 0
  30. await clocks(dut, CLKS_PER_BIT)
  31. for bit in range(8):
  32. dut.host_uart_rx.value = (value >> bit) & 1
  33. await clocks(dut, CLKS_PER_BIT)
  34. dut.host_uart_rx.value = 1
  35. await clocks(dut, CLKS_PER_BIT)
  36. async def send_frame(dut, packet: bytes) -> None:
  37. for value in packet:
  38. await send_uart_byte(dut, value)
  39. async def observe_motor_steps(dut, observed: dict[str, int | bool], completion: Event) -> None:
  40. previous_x = 0
  41. previous_y = 0
  42. while True:
  43. await RisingEdge(dut.sys_clk)
  44. await ReadOnly()
  45. if not dut.x_step.value.is_resolvable or not dut.y_step.value.is_resolvable:
  46. previous_x = 0
  47. previous_y = 0
  48. continue
  49. current_x = int(dut.x_step.value)
  50. current_y = int(dut.y_step.value)
  51. if current_x and not previous_x:
  52. observed["x"] = int(observed["x"]) + 1
  53. if current_y and not previous_y:
  54. observed["y"] = int(observed["y"]) + 1
  55. if current_x and current_y:
  56. observed["overlap"] = True
  57. previous_x = current_x
  58. previous_y = current_y
  59. if observed["x"] == MOTOR_STEPS and observed["y"] == MOTOR_STEPS:
  60. completion.set()
  61. return
  62. async def receive_uart_byte(dut) -> int:
  63. while int(dut.host_uart_tx.value) != 0:
  64. await RisingEdge(dut.sys_clk)
  65. await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
  66. value = 0
  67. for bit in range(8):
  68. value |= int(dut.host_uart_tx.value) << bit
  69. await clocks(dut, CLKS_PER_BIT)
  70. assert int(dut.host_uart_tx.value) == 1
  71. return value
  72. async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1):
  73. """Apply a bounded wait with a stable, machine-searchable failure message."""
  74. try:
  75. return await with_timeout(awaitable, timeout_ms, "ms")
  76. except SimTimeoutError as exc:
  77. suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
  78. raise AssertionError(
  79. f"timeout stage={stage} timeout_ms={timeout_ms}{suffix}"
  80. ) from exc
  81. def stop_background_task(task) -> None:
  82. if task is None:
  83. return
  84. if hasattr(task, "kill"):
  85. task.kill()
  86. elif hasattr(task, "cancel"):
  87. task.cancel()
  88. @cocotb.test()
  89. async def test_set_all_get_temperature_over_real_uart(dut):
  90. clock_task = None
  91. observer_task = None
  92. observed = {"x": 0, "y": 0, "overlap": False}
  93. motor_completion = Event()
  94. try:
  95. clock_task = cocotb.start_soon(Clock(dut.sys_clk, 40, units="ns").start())
  96. observer_task = cocotb.start_soon(
  97. observe_motor_steps(dut, observed, motor_completion)
  98. )
  99. dut.host_uart_rx.value = 1
  100. dut.x_limit_raw.value = 0
  101. dut.y_limit_raw.value = 0
  102. dut.temp_scl.value = 1
  103. dut.temp_sda.value = 1
  104. await clocks(dut, 1100)
  105. payload = bytes(range(8)) + bytes((10, 20, 30, 40, 1, 2))
  106. await send_frame(dut, frame(SET_ALL, payload))
  107. try:
  108. await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
  109. except SimTimeoutError as exc:
  110. raise AssertionError(
  111. "timeout stage=motor_completion "
  112. f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} "
  113. f"observed_x={observed['x']} observed_y={observed['y']}"
  114. ) from exc
  115. assert observed["x"] == MOTOR_STEPS
  116. assert observed["y"] == MOTOR_STEPS
  117. assert observed["overlap"] is True
  118. assert int(dut.motor_en_n.value) == 0
  119. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  120. response = bytearray()
  121. for byte_index in range(33):
  122. response.append(
  123. await wait_for_stage(
  124. receive_uart_byte(dut),
  125. TEMPERATURE_BYTE_TIMEOUT_MS,
  126. "temperature_response",
  127. byte_index,
  128. )
  129. )
  130. response = bytes(response)
  131. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  132. assert len(response) == 33
  133. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  134. assert set(response[4:31]) == {0xFF}
  135. finally:
  136. stop_background_task(observer_task)
  137. stop_background_task(clock_task)