test_prod2u_door_temp_uart_e2e.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. """Real UART-bit e2e: startup_complete, SET_ALL percent, GET_TEMPERATURE, GET_MOTOR_STATUS."""
  2. import cocotb
  3. import cocotb.simulator as simulator
  4. from cocotb.triggers import FallingEdge, NextTimeStep, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout
  5. from cocotb.utils import get_sim_time
  6. CLKS_PER_BIT = 217
  7. SET_ALL = 0x01
  8. GET_TEMPERATURE = 0x02
  9. GET_MOTOR_STATUS = 0x03
  10. TEMPERATURE_DATA = 0x82
  11. MOTOR_STATUS_DATA = 0x83
  12. STARTUP_TIMEOUT_MS = 5000
  13. TEMPERATURE_BYTE_TIMEOUT_MS = 100
  14. STATUS_BYTE_TIMEOUT_MS = 100
  15. FRAME_ACCEPT_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. def _sim_time_ns() -> str:
  27. try:
  28. return f"{get_sim_time(unit='ns'):.0f}ns"
  29. except Exception:
  30. return "unknown"
  31. def checkpoint(stage: str, **fields) -> None:
  32. extra = " ".join(f"{key}={value}" for key, value in fields.items())
  33. suffix = f" {extra}" if extra else ""
  34. cocotb.log.info("checkpoint stage=%s sim_time=%s%s", stage, _sim_time_ns(), suffix)
  35. async def clocks(dut, count: int) -> None:
  36. clk = getattr(getattr(dut, "u_dut", None), "sys_clk", None)
  37. if clk is None:
  38. await Timer(count * 40, unit="ns")
  39. return
  40. for _ in range(count):
  41. await RisingEdge(clk)
  42. async def send_uart_byte(dut, value: int) -> None:
  43. await ReadWrite()
  44. dut.host_uart_rx.value = 0
  45. await clocks(dut, CLKS_PER_BIT)
  46. for bit in range(8):
  47. dut.host_uart_rx.value = (value >> bit) & 1
  48. await clocks(dut, CLKS_PER_BIT)
  49. dut.host_uart_rx.value = 1
  50. await clocks(dut, CLKS_PER_BIT)
  51. async def send_frame(dut, packet: bytes) -> None:
  52. await NextTimeStep()
  53. for value in packet:
  54. await send_uart_byte(dut, value)
  55. async def receive_uart_byte(dut) -> int:
  56. # Idle-high then start bit. Caller may arm this before send completes so the
  57. # first response start edge is not missed (DUT can TX during last RX stop).
  58. if int(dut.host_uart_tx.value) != 1:
  59. await RisingEdge(dut.host_uart_tx)
  60. await FallingEdge(dut.host_uart_tx)
  61. await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
  62. value = 0
  63. for bit in range(8):
  64. value |= int(dut.host_uart_tx.value) << bit
  65. await clocks(dut, CLKS_PER_BIT)
  66. stop = int(dut.host_uart_tx.value)
  67. if stop != 1:
  68. raise AssertionError(
  69. f"uart stop-bit framing error value=0x{value:02x} stop={stop} "
  70. f"sim_time={_sim_time_ns()}"
  71. )
  72. return value
  73. async def receive_exact(dut, nbytes: int, timeout_ms: int, stage: str) -> bytes:
  74. out = bytearray()
  75. for byte_index in range(nbytes):
  76. out.append(
  77. await wait_for_stage(
  78. receive_uart_byte(dut),
  79. timeout_ms,
  80. stage,
  81. byte_index,
  82. )
  83. )
  84. return bytes(out)
  85. async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1, **fields):
  86. try:
  87. return await with_timeout(awaitable, timeout_ms, "ms")
  88. except SimTimeoutError as exc:
  89. suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
  90. extra = "".join(f" {key}={value}" for key, value in fields.items())
  91. raise AssertionError(
  92. f"timeout stage={stage} timeout_ms={timeout_ms} sim_time={_sim_time_ns()}"
  93. f"{suffix}{extra}"
  94. ) from exc
  95. async def wait_level_or_edge(signal, *, want: int, timeout_ms: int, stage: str) -> None:
  96. current = int(signal.value) if signal.value.is_resolvable else None
  97. if current == want:
  98. checkpoint(stage, already=want)
  99. return
  100. edge = RisingEdge(signal) if want else FallingEdge(signal)
  101. await wait_for_stage(edge, timeout_ms, stage, signal_level=current, want=want)
  102. @cocotb.test()
  103. async def test_set_all_get_temperature_over_real_uart(dut):
  104. try:
  105. checkpoint("test_start")
  106. dut.host_uart_rx.value = 1
  107. # Begin on close limits so calibration can seek/measure quickly.
  108. dut.x_limit_ls.value = 1
  109. dut.x_limit_hs.value = 0
  110. dut.y_limit_ls.value = 1
  111. dut.y_limit_hs.value = 0
  112. dut.z_limit_ls.value = 1
  113. dut.z_limit_hs.value = 0
  114. dut.temp_scl.value = 1
  115. dut.temp_sda.value = 1
  116. await clocks(dut, 2000)
  117. # Count STEP rises during measure-open, then assert open limits.
  118. x_rises = {"n": 0}
  119. async def count_x():
  120. while True:
  121. await RisingEdge(dut.x_step)
  122. x_rises["n"] += 1
  123. counter = cocotb.start_soon(count_x())
  124. # Wait until all axes likely produced >=2 rises (1 kHz steps).
  125. for _ in range(20000):
  126. await clocks(dut, 2500)
  127. if x_rises["n"] >= 2:
  128. break
  129. dut.x_limit_hs.value = 1
  130. dut.y_limit_hs.value = 1
  131. dut.z_limit_hs.value = 1
  132. dut.x_limit_ls.value = 0
  133. dut.y_limit_ls.value = 0
  134. dut.z_limit_ls.value = 0
  135. await wait_level_or_edge(
  136. dut.u_dut.startup_complete,
  137. want=1,
  138. timeout_ms=STARTUP_TIMEOUT_MS,
  139. stage="startup_complete",
  140. )
  141. checkpoint("startup_complete", x_rises=x_rises["n"])
  142. counter.kill()
  143. # Clear limits for mid motion
  144. dut.x_limit_ls.value = 0
  145. dut.x_limit_hs.value = 0
  146. dut.y_limit_ls.value = 0
  147. dut.y_limit_hs.value = 0
  148. dut.z_limit_ls.value = 0
  149. dut.z_limit_hs.value = 0
  150. await clocks(dut, 16)
  151. # Z/X/Y percents = 50/50/50 (not jog 01/02)
  152. payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 50, 50, 50))
  153. checkpoint("set_all_tx")
  154. await send_frame(dut, frame(SET_ALL, payload))
  155. await clocks(dut, CLKS_PER_BIT * 16)
  156. assert int(dut.motor_en_n.value) == 1
  157. await wait_level_or_edge(
  158. dut.u_dut.frame_accept_enable,
  159. want=1,
  160. timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
  161. stage="frame_accept_enable",
  162. )
  163. checkpoint("get_motor_status_tx")
  164. # Arm RX before/during TX so DUT's first start bit is not missed.
  165. status_task = cocotb.start_soon(
  166. receive_exact(dut, 37, STATUS_BYTE_TIMEOUT_MS, "motor_status_response")
  167. )
  168. await send_frame(dut, frame(GET_MOTOR_STATUS, b""))
  169. status = await status_task
  170. assert status[:4] == bytes((0xA5, 0x5A, MOTOR_STATUS_DATA, 31))
  171. assert len(status) == 37
  172. assert status[-2:] == crc16(status[2:-2]).to_bytes(2, "little")
  173. assert status[4] & 0x40 # startup_complete
  174. checkpoint("motor_status_ok")
  175. await wait_level_or_edge(
  176. dut.u_dut.frame_accept_enable,
  177. want=1,
  178. timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
  179. stage="frame_accept_enable_2",
  180. )
  181. checkpoint("get_temperature_tx")
  182. temp_task = cocotb.start_soon(
  183. receive_exact(dut, 33, TEMPERATURE_BYTE_TIMEOUT_MS, "temperature_response")
  184. )
  185. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  186. response = await temp_task
  187. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  188. assert len(response) == 33
  189. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  190. assert set(response[4:31]) == {0xFF}
  191. checkpoint("temperature_response_ok", bytes=len(response))
  192. finally:
  193. try:
  194. simulator.stop_simulator()
  195. except Exception:
  196. pass