test_prod2u_door_temp_uart_e2e.py 5.9 KB

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