test_prod2u_door_temp_uart_e2e.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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.triggers import Event, FallingEdge, NextTimeStep, ReadOnly, ReadWrite, RisingEdge, SimTimeoutError, Timer, 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. await Timer(count * 40, units="ns")
  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 _count_axis_steps(
  41. signal,
  42. axis: str,
  43. observed: dict[str, int | bool],
  44. completion: Event,
  45. ) -> None:
  46. while observed[axis] < MOTOR_STEPS:
  47. await RisingEdge(signal)
  48. await ReadOnly()
  49. if not signal.value.is_resolvable:
  50. continue
  51. if int(signal.value):
  52. observed[axis] = int(observed[axis]) + 1
  53. if (
  54. observed["x"] == MOTOR_STEPS
  55. and observed["y"] == MOTOR_STEPS
  56. ):
  57. completion.set()
  58. return
  59. async def observe_motor_steps(dut, observed: dict[str, int | bool], completion: Event) -> None:
  60. # Independent axis watchers: a single-X waiter under-counts Y.
  61. x_task = cocotb.start_soon(_count_axis_steps(dut.x_step, "x", observed, completion))
  62. y_task = cocotb.start_soon(_count_axis_steps(dut.y_step, "y", observed, completion))
  63. try:
  64. await completion.wait()
  65. finally:
  66. stop_background_task(x_task)
  67. stop_background_task(y_task)
  68. # Overlap is approximate: true when both axes have progressed.
  69. if int(observed["x"]) > 0 and int(observed["y"]) > 0:
  70. observed["overlap"] = True
  71. async def receive_uart_byte(dut) -> int:
  72. await FallingEdge(dut.host_uart_tx)
  73. await Timer((CLKS_PER_BIT + CLKS_PER_BIT // 2) * 40, units="ns")
  74. value = 0
  75. for bit in range(8):
  76. value |= int(dut.host_uart_tx.value) << bit
  77. await Timer(CLKS_PER_BIT * 40, units="ns")
  78. assert int(dut.host_uart_tx.value) == 1
  79. return value
  80. async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1):
  81. """Apply a bounded wait with a stable, machine-searchable failure message."""
  82. try:
  83. return await with_timeout(awaitable, timeout_ms, "ms")
  84. except SimTimeoutError as exc:
  85. suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
  86. raise AssertionError(
  87. f"timeout stage={stage} timeout_ms={timeout_ms}{suffix}"
  88. ) from exc
  89. def stop_background_task(task) -> None:
  90. if task is None:
  91. return
  92. if hasattr(task, "cancel"):
  93. task.cancel()
  94. elif hasattr(task, "kill"):
  95. task.kill()
  96. @cocotb.test()
  97. async def test_set_all_get_temperature_over_real_uart(dut):
  98. observer_task = None
  99. observed = {"x": 0, "y": 0, "overlap": False}
  100. motor_completion = Event()
  101. try:
  102. observer_task = cocotb.start_soon(
  103. observe_motor_steps(dut, observed, motor_completion)
  104. )
  105. dut.host_uart_rx.value = 1
  106. dut.x_limit_raw.value = 1
  107. dut.y_limit_raw.value = 1
  108. dut.temp_scl.value = 1
  109. dut.temp_sda.value = 1
  110. await clocks(dut, 1024)
  111. # Limits already high => startup may finish during the wait above.
  112. # RisingEdge alone would hang forever if startup_done is already 1.
  113. if int(dut.u_dut.startup_done.value) == 0:
  114. await wait_for_stage(
  115. RisingEdge(dut.u_dut.startup_done),
  116. MOTOR_COMPLETION_TIMEOUT_MS,
  117. "startup_done",
  118. )
  119. # X=01 open (DIR=0), Y=02 close (DIR=1); 450 steps each, overlapping.
  120. payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 0, 1, 2))
  121. await send_frame(dut, frame(SET_ALL, payload))
  122. # Sample DIR while the jog is active (before completion).
  123. await clocks(dut, CLKS_PER_BIT * 8)
  124. assert int(dut.x_dir.value) == 0, "SET_ALL X=01 must drive DIR=0 (open)"
  125. assert int(dut.y_dir.value) == 1, "SET_ALL Y=02 must drive DIR=1 (close)"
  126. try:
  127. await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
  128. except SimTimeoutError as exc:
  129. raise AssertionError(
  130. "timeout stage=motor_completion "
  131. f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} "
  132. f"observed_x={observed['x']} observed_y={observed['y']}"
  133. ) from exc
  134. assert observed["x"] == MOTOR_STEPS
  135. assert observed["y"] == MOTOR_STEPS
  136. assert observed["overlap"] is True
  137. assert int(dut.motor_en_n.value) == 0
  138. await with_timeout(
  139. FallingEdge(dut.x_step),
  140. MOTOR_COMPLETION_TIMEOUT_MS,
  141. "ms",
  142. )
  143. await RisingEdge(dut.u_dut.frame_accept_enable)
  144. await clocks(dut, 4)
  145. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  146. response = bytearray()
  147. for byte_index in range(33):
  148. response.append(
  149. await wait_for_stage(
  150. receive_uart_byte(dut),
  151. TEMPERATURE_BYTE_TIMEOUT_MS,
  152. "temperature_response",
  153. byte_index,
  154. )
  155. )
  156. response = bytes(response)
  157. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  158. assert len(response) == 33
  159. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  160. assert set(response[4:31]) == {0xFF}
  161. finally:
  162. stop_background_task(observer_task)
  163. try:
  164. simulator.stop_simulator()
  165. except Exception:
  166. pass