test_prod2u_door_temp_uart_e2e.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. from cocotb.utils import get_sim_time
  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. FRAME_ACCEPT_TIMEOUT_MS = 100
  17. def crc16(data: bytes) -> int:
  18. crc = 0xFFFF
  19. for value in data:
  20. crc ^= value << 8
  21. for _ in range(8):
  22. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  23. return crc
  24. def frame(kind: int, payload: bytes) -> bytes:
  25. body = bytes((kind, len(payload))) + payload
  26. return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
  27. def _sim_time_ns() -> str:
  28. try:
  29. return f"{get_sim_time(unit='ns'):.0f}ns"
  30. except Exception:
  31. return "unknown"
  32. def checkpoint(stage: str, **fields) -> None:
  33. """Emit a machine-searchable stage checkpoint with sim time."""
  34. extra = " ".join(f"{key}={value}" for key, value in fields.items())
  35. suffix = f" {extra}" if extra else ""
  36. cocotb.log.info("checkpoint stage=%s sim_time=%s%s", stage, _sim_time_ns(), suffix)
  37. async def clocks(dut, count: int) -> None:
  38. await Timer(count * 40, unit="ns")
  39. async def send_uart_byte(dut, value: int) -> None:
  40. await ReadWrite()
  41. dut.host_uart_rx.value = 0
  42. await clocks(dut, CLKS_PER_BIT)
  43. for bit in range(8):
  44. dut.host_uart_rx.value = (value >> bit) & 1
  45. await clocks(dut, CLKS_PER_BIT)
  46. dut.host_uart_rx.value = 1
  47. await clocks(dut, CLKS_PER_BIT)
  48. async def send_frame(dut, packet: bytes) -> None:
  49. await NextTimeStep()
  50. for value in packet:
  51. await send_uart_byte(dut, value)
  52. async def _count_axis_steps(
  53. signal,
  54. axis: str,
  55. observed: dict[str, int | bool],
  56. completion: Event,
  57. ) -> None:
  58. while observed[axis] < MOTOR_STEPS:
  59. await RisingEdge(signal)
  60. await ReadOnly()
  61. if not signal.value.is_resolvable:
  62. continue
  63. if int(signal.value):
  64. observed[axis] = int(observed[axis]) + 1
  65. if (
  66. observed["x"] == MOTOR_STEPS
  67. and observed["y"] == MOTOR_STEPS
  68. ):
  69. completion.set()
  70. return
  71. async def observe_motor_steps(dut, observed: dict[str, int | bool], completion: Event) -> None:
  72. # Independent axis watchers: a single-X waiter under-counts Y.
  73. x_task = cocotb.start_soon(_count_axis_steps(dut.x_step, "x", observed, completion))
  74. y_task = cocotb.start_soon(_count_axis_steps(dut.y_step, "y", observed, completion))
  75. try:
  76. await completion.wait()
  77. finally:
  78. stop_background_task(x_task)
  79. stop_background_task(y_task)
  80. # Overlap is approximate: true when both axes have progressed.
  81. if int(observed["x"]) > 0 and int(observed["y"]) > 0:
  82. observed["overlap"] = True
  83. async def receive_uart_byte(dut) -> int:
  84. await FallingEdge(dut.host_uart_tx)
  85. await Timer((CLKS_PER_BIT + CLKS_PER_BIT // 2) * 40, unit="ns")
  86. value = 0
  87. for bit in range(8):
  88. value |= int(dut.host_uart_tx.value) << bit
  89. await Timer(CLKS_PER_BIT * 40, unit="ns")
  90. assert int(dut.host_uart_tx.value) == 1
  91. return value
  92. async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1, **fields):
  93. """Apply a bounded wait with a stable, machine-searchable failure message."""
  94. try:
  95. return await with_timeout(awaitable, timeout_ms, "ms")
  96. except SimTimeoutError as exc:
  97. suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
  98. extra = "".join(f" {key}={value}" for key, value in fields.items())
  99. raise AssertionError(
  100. f"timeout stage={stage} timeout_ms={timeout_ms} sim_time={_sim_time_ns()}"
  101. f"{suffix}{extra}"
  102. ) from exc
  103. async def wait_level_or_edge(signal, *, want: int, timeout_ms: int, stage: str) -> None:
  104. """Continue if signal already matches want; else wait for the matching edge."""
  105. current = int(signal.value) if signal.value.is_resolvable else None
  106. if current == want:
  107. checkpoint(stage, already=want)
  108. return
  109. edge = RisingEdge(signal) if want else FallingEdge(signal)
  110. await wait_for_stage(
  111. edge,
  112. timeout_ms,
  113. stage,
  114. signal_level=current,
  115. want=want,
  116. )
  117. def stop_background_task(task) -> None:
  118. if task is None:
  119. return
  120. if hasattr(task, "cancel"):
  121. task.cancel()
  122. elif hasattr(task, "kill"):
  123. task.kill()
  124. @cocotb.test()
  125. async def test_set_all_get_temperature_over_real_uart(dut):
  126. observer_task = None
  127. observed = {"x": 0, "y": 0, "overlap": False}
  128. motor_completion = Event()
  129. try:
  130. checkpoint("test_start")
  131. observer_task = cocotb.start_soon(
  132. observe_motor_steps(dut, observed, motor_completion)
  133. )
  134. dut.host_uart_rx.value = 1
  135. dut.x_limit_ls.value = 1
  136. dut.x_limit_hs.value = 0
  137. dut.y_limit_ls.value = 1
  138. dut.y_limit_hs.value = 0
  139. dut.z_limit_ls.value = 1
  140. dut.z_limit_hs.value = 0
  141. dut.temp_scl.value = 1
  142. dut.temp_sda.value = 1
  143. await clocks(dut, 1024)
  144. # Limits already high => startup may finish during the wait above.
  145. # RisingEdge alone would hang forever if startup_done is already 1.
  146. await wait_level_or_edge(
  147. dut.u_dut.startup_done,
  148. want=1,
  149. timeout_ms=MOTOR_COMPLETION_TIMEOUT_MS,
  150. stage="startup_done",
  151. )
  152. checkpoint("startup_done")
  153. # After startup, clear limits so ordinary jogs are not immediately hard-stopped.
  154. # (Y close uses LS; leaving LS=1 would truncate Y to zero rising edges.)
  155. dut.x_limit_ls.value = 0
  156. dut.x_limit_hs.value = 0
  157. dut.y_limit_ls.value = 0
  158. dut.y_limit_hs.value = 0
  159. dut.z_limit_ls.value = 0
  160. dut.z_limit_hs.value = 0
  161. await clocks(dut, 16)
  162. # byte8=Z, byte9=X, byte10=Y. X=01 open (DIR=0), Y=02 close (DIR=1); Z=00.
  163. payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 0, 1, 2))
  164. checkpoint("set_all_tx")
  165. await send_frame(dut, frame(SET_ALL, payload))
  166. # Sample DIR while the jog is active (before completion).
  167. await clocks(dut, CLKS_PER_BIT * 8)
  168. assert int(dut.x_dir.value) == 0, "SET_ALL X=01 must drive DIR=0 (open)"
  169. assert int(dut.y_dir.value) == 1, "SET_ALL Y=02 must drive DIR=1 (close)"
  170. checkpoint("dir_sampled", x_dir=int(dut.x_dir.value), y_dir=int(dut.y_dir.value))
  171. try:
  172. await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
  173. except SimTimeoutError as exc:
  174. raise AssertionError(
  175. "timeout stage=motor_completion "
  176. f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} sim_time={_sim_time_ns()} "
  177. f"observed_x={observed['x']} observed_y={observed['y']}"
  178. ) from exc
  179. assert observed["x"] == MOTOR_STEPS
  180. assert observed["y"] == MOTOR_STEPS
  181. assert observed["overlap"] is True
  182. assert int(dut.motor_en_n.value) == 1
  183. checkpoint(
  184. "motor_completion",
  185. observed_x=observed["x"],
  186. observed_y=observed["y"],
  187. overlap=observed["overlap"],
  188. )
  189. # STEP may already be low after the last half-cycle; FallingEdge alone hangs.
  190. await wait_level_or_edge(
  191. dut.x_step,
  192. want=0,
  193. timeout_ms=MOTOR_COMPLETION_TIMEOUT_MS,
  194. stage="x_step_idle",
  195. )
  196. # SET_ALL returns the controller to IDLE long before motors finish, so
  197. # frame_accept_enable is often already 1; RisingEdge alone hangs forever.
  198. await wait_level_or_edge(
  199. dut.u_dut.frame_accept_enable,
  200. want=1,
  201. timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
  202. stage="frame_accept_enable",
  203. )
  204. checkpoint("frame_accept_enable")
  205. await clocks(dut, 4)
  206. checkpoint("get_temperature_tx")
  207. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  208. response = bytearray()
  209. for byte_index in range(33):
  210. response.append(
  211. await wait_for_stage(
  212. receive_uart_byte(dut),
  213. TEMPERATURE_BYTE_TIMEOUT_MS,
  214. "temperature_response",
  215. byte_index,
  216. )
  217. )
  218. response = bytes(response)
  219. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  220. assert len(response) == 33
  221. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  222. assert set(response[4:31]) == {0xFF}
  223. checkpoint("temperature_response_ok", bytes=len(response))
  224. finally:
  225. stop_background_task(observer_task)
  226. try:
  227. simulator.stop_simulator()
  228. except Exception:
  229. pass