test_prod2u_door_temp_uart_e2e.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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.triggers import Event, First, NextTimeStep, ReadOnly, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout
  7. CLKS_PER_BIT = 217
  8. SET_ALL = 0x01
  9. GET_TEMPERATURE = 0x02
  10. TEMPERATURE_DATA = 0x82
  11. MOTOR_STEPS = 450
  12. MOTOR_COMPLETION_TIMEOUT_MS = 600
  13. TEMPERATURE_BYTE_TIMEOUT_MS = 100
  14. def crc16(data: bytes) -> int:
  15. crc = 0xFFFF
  16. for value in data:
  17. crc ^= value << 8
  18. for _ in range(8):
  19. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  20. return crc
  21. def frame(kind: int, payload: bytes) -> bytes:
  22. body = bytes((kind, len(payload))) + payload
  23. return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
  24. async def clocks(dut, count: int) -> None:
  25. for _ in range(count):
  26. await RisingEdge(dut.sys_clk)
  27. async def send_uart_byte(dut, value: int) -> None:
  28. await ReadWrite()
  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. await NextTimeStep()
  38. for value in packet:
  39. await send_uart_byte(dut, value)
  40. async def observe_motor_steps(dut, observed: dict[str, int | bool], completion: Event) -> None:
  41. previous_x = 0
  42. previous_y = 0
  43. while True:
  44. await RisingEdge(dut.sys_clk)
  45. await ReadOnly()
  46. if not dut.x_step.value.is_resolvable or not dut.y_step.value.is_resolvable:
  47. previous_x = 0
  48. previous_y = 0
  49. continue
  50. current_x = int(dut.x_step.value)
  51. current_y = int(dut.y_step.value)
  52. if current_x and not previous_x:
  53. observed["x"] = int(observed["x"]) + 1
  54. if current_y and not previous_y:
  55. observed["y"] = int(observed["y"]) + 1
  56. if current_x and current_y:
  57. observed["overlap"] = True
  58. previous_x = current_x
  59. previous_y = current_y
  60. if observed["x"] == MOTOR_STEPS and observed["y"] == MOTOR_STEPS:
  61. completion.set()
  62. return
  63. async def receive_uart_byte(dut) -> int:
  64. while int(dut.host_uart_tx.value) != 0:
  65. await RisingEdge(dut.sys_clk)
  66. await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
  67. value = 0
  68. for bit in range(8):
  69. value |= int(dut.host_uart_tx.value) << bit
  70. await clocks(dut, CLKS_PER_BIT)
  71. assert int(dut.host_uart_tx.value) == 1
  72. return value
  73. async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1):
  74. """Apply a bounded wait with a stable, machine-searchable failure message."""
  75. try:
  76. return await with_timeout(awaitable, timeout_ms, "ms")
  77. except SimTimeoutError as exc:
  78. suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
  79. raise AssertionError(
  80. f"timeout stage={stage} timeout_ms={timeout_ms}{suffix}"
  81. ) from exc
  82. async def run_clock(dut, stop_event: Event) -> None:
  83. while not stop_event.is_set():
  84. dut.sys_clk.value = 0
  85. await Timer(20, unit="ns")
  86. if stop_event.is_set():
  87. break
  88. dut.sys_clk.value = 1
  89. await Timer(20, unit="ns")
  90. def stop_background_task(task, stop_event=None) -> None:
  91. if stop_event is not None:
  92. stop_event.set()
  93. if task is None:
  94. return
  95. if hasattr(task, "cancel"):
  96. task.cancel()
  97. elif hasattr(task, "kill"):
  98. task.kill()
  99. @cocotb.test()
  100. async def test_set_all_get_temperature_over_real_uart(dut):
  101. clock_stop = Event()
  102. clock_task = None
  103. observer_task = None
  104. observed = {"x": 0, "y": 0, "overlap": False}
  105. motor_completion = Event()
  106. try:
  107. clock_task = cocotb.start_soon(run_clock(dut, clock_stop))
  108. observer_task = cocotb.start_soon(
  109. observe_motor_steps(dut, observed, motor_completion)
  110. )
  111. dut.host_uart_rx.value = 1
  112. dut.x_limit_raw.value = 1
  113. dut.y_limit_raw.value = 1
  114. dut.temp_scl.value = 1
  115. dut.temp_sda.value = 1
  116. await clocks(dut, 1100)
  117. while not int(dut.u_dut.startup_done.value):
  118. await RisingEdge(dut.sys_clk)
  119. payload = bytes(range(8)) + bytes((10, 20, 30, 40, 1, 2))
  120. await send_frame(dut, frame(SET_ALL, payload))
  121. try:
  122. await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
  123. except SimTimeoutError as exc:
  124. raise AssertionError(
  125. "timeout stage=motor_completion "
  126. f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} "
  127. f"observed_x={observed['x']} observed_y={observed['y']}"
  128. ) from exc
  129. assert observed["x"] == MOTOR_STEPS
  130. assert observed["y"] == MOTOR_STEPS
  131. assert observed["overlap"] is True
  132. assert int(dut.motor_en_n.value) == 0
  133. while True:
  134. await RisingEdge(dut.sys_clk)
  135. await ReadOnly()
  136. if int(dut.x_step.value) == 0 and int(dut.y_step.value) == 0:
  137. break
  138. while not int(dut.u_dut.frame_accept_enable.value):
  139. await RisingEdge(dut.sys_clk)
  140. await clocks(dut, 4)
  141. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  142. response = bytearray()
  143. for byte_index in range(33):
  144. response.append(
  145. await wait_for_stage(
  146. receive_uart_byte(dut),
  147. TEMPERATURE_BYTE_TIMEOUT_MS,
  148. "temperature_response",
  149. byte_index,
  150. )
  151. )
  152. response = bytes(response)
  153. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  154. assert len(response) == 33
  155. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  156. assert set(response[4:31]) == {0xFF}
  157. finally:
  158. stop_background_task(observer_task)
  159. stop_background_task(clock_task, clock_stop)