test_prod2u_door_temp_uart_e2e.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. # Serial X→Y→Z measure-open + profile; DDA service is real-time (tick_500us only is accelerated).
  13. STARTUP_TIMEOUT_MS = 30000
  14. TEMPERATURE_BYTE_TIMEOUT_MS = 100
  15. STATUS_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. extra = " ".join(f"{key}={value}" for key, value in fields.items())
  34. suffix = f" {extra}" if extra else ""
  35. cocotb.log.info("checkpoint stage=%s sim_time=%s%s", stage, _sim_time_ns(), suffix)
  36. async def clocks(dut, count: int) -> None:
  37. clk = getattr(getattr(dut, "u_dut", None), "sys_clk", None)
  38. if clk is None:
  39. await Timer(count * 40, unit="ns")
  40. return
  41. for _ in range(count):
  42. await RisingEdge(clk)
  43. async def send_uart_byte(dut, value: int) -> None:
  44. await ReadWrite()
  45. dut.host_uart_rx.value = 0
  46. await clocks(dut, CLKS_PER_BIT)
  47. for bit in range(8):
  48. dut.host_uart_rx.value = (value >> bit) & 1
  49. await clocks(dut, CLKS_PER_BIT)
  50. dut.host_uart_rx.value = 1
  51. await clocks(dut, CLKS_PER_BIT)
  52. async def send_frame(dut, packet: bytes) -> None:
  53. await NextTimeStep()
  54. for value in packet:
  55. await send_uart_byte(dut, value)
  56. async def receive_uart_byte(dut) -> int:
  57. # Idle-high then start bit. Caller may arm this before send completes so the
  58. # first response start edge is not missed (DUT can TX during last RX stop).
  59. if int(dut.host_uart_tx.value) != 1:
  60. await RisingEdge(dut.host_uart_tx)
  61. await FallingEdge(dut.host_uart_tx)
  62. await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
  63. value = 0
  64. for bit in range(8):
  65. value |= int(dut.host_uart_tx.value) << bit
  66. await clocks(dut, CLKS_PER_BIT)
  67. stop = int(dut.host_uart_tx.value)
  68. if stop != 1:
  69. raise AssertionError(
  70. f"uart stop-bit framing error value=0x{value:02x} stop={stop} "
  71. f"sim_time={_sim_time_ns()}"
  72. )
  73. return value
  74. async def receive_exact(dut, nbytes: int, timeout_ms: int, stage: str) -> bytes:
  75. out = bytearray()
  76. for byte_index in range(nbytes):
  77. out.append(
  78. await wait_for_stage(
  79. receive_uart_byte(dut),
  80. timeout_ms,
  81. stage,
  82. byte_index,
  83. )
  84. )
  85. return bytes(out)
  86. async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1, **fields):
  87. try:
  88. return await with_timeout(awaitable, timeout_ms, "ms")
  89. except SimTimeoutError as exc:
  90. suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
  91. extra = "".join(f" {key}={value}" for key, value in fields.items())
  92. raise AssertionError(
  93. f"timeout stage={stage} timeout_ms={timeout_ms} sim_time={_sim_time_ns()}"
  94. f"{suffix}{extra}"
  95. ) from exc
  96. async def wait_level_or_edge(signal, *, want: int, timeout_ms: int, stage: str) -> None:
  97. current = int(signal.value) if signal.value.is_resolvable else None
  98. if current == want:
  99. checkpoint(stage, already=want)
  100. return
  101. edge = RisingEdge(signal) if want else FallingEdge(signal)
  102. await wait_for_stage(edge, timeout_ms, stage, signal_level=current, want=want)
  103. async def wait_measure_rises_then_open(
  104. dut,
  105. *,
  106. step_sig,
  107. limit_ls,
  108. limit_hs,
  109. axis_name: str,
  110. min_rises: int = 2,
  111. ) -> int:
  112. """Serial-cal friendly: wait for this axis's measure-open STEP rises, then hit open only."""
  113. rises = {"n": 0}
  114. async def count_rises():
  115. while True:
  116. await RisingEdge(step_sig)
  117. rises["n"] += 1
  118. counter = cocotb.start_soon(count_rises())
  119. # Up to ~62.5M clocks (~2.5s sim @25MHz) per axis; service tick is 625 clks.
  120. for _ in range(100_000):
  121. await clocks(dut, 625)
  122. if rises["n"] >= min_rises:
  123. break
  124. else:
  125. counter.kill()
  126. raise AssertionError(
  127. f"insufficient measure rises axis={axis_name} rises={rises['n']} "
  128. f"sim_time={_sim_time_ns()}"
  129. )
  130. limit_hs.value = 1
  131. limit_ls.value = 0
  132. checkpoint(f"cal_open_{axis_name}", rises=rises["n"])
  133. # Allow limit sync + terminal handoff before the next axis starts.
  134. await clocks(dut, 4000)
  135. counter.kill()
  136. return rises["n"]
  137. @cocotb.test()
  138. async def test_set_all_get_temperature_over_real_uart(dut):
  139. try:
  140. checkpoint("test_start")
  141. dut.host_uart_rx.value = 1
  142. # Begin on close limits so each serial axis can finish seek-close immediately.
  143. dut.x_limit_ls.value = 1
  144. dut.x_limit_hs.value = 0
  145. dut.y_limit_ls.value = 1
  146. dut.y_limit_hs.value = 0
  147. dut.z_limit_ls.value = 1
  148. dut.z_limit_hs.value = 0
  149. dut.temp_scl.value = 1
  150. dut.temp_sda.value = 1
  151. await clocks(dut, 2000)
  152. # A2 serial X→Y→Z: stimulate open limit per axis after its own measure-open rises.
  153. # Do not assert Y/Z open early — that strands seek-close and burns MAX_CAL_STEPS.
  154. x_rises = await wait_measure_rises_then_open(
  155. dut, step_sig=dut.x_step, limit_ls=dut.x_limit_ls, limit_hs=dut.x_limit_hs, axis_name="x"
  156. )
  157. y_rises = await wait_measure_rises_then_open(
  158. dut, step_sig=dut.y_step, limit_ls=dut.y_limit_ls, limit_hs=dut.y_limit_hs, axis_name="y"
  159. )
  160. z_rises = await wait_measure_rises_then_open(
  161. dut, step_sig=dut.z_step, limit_ls=dut.z_limit_ls, limit_hs=dut.z_limit_hs, axis_name="z"
  162. )
  163. await wait_level_or_edge(
  164. dut.u_dut.startup_complete,
  165. want=1,
  166. timeout_ms=STARTUP_TIMEOUT_MS,
  167. stage="startup_complete",
  168. )
  169. checkpoint("startup_complete", x_rises=x_rises, y_rises=y_rises, z_rises=z_rises)
  170. # Clear limits for mid motion
  171. dut.x_limit_ls.value = 0
  172. dut.x_limit_hs.value = 0
  173. dut.y_limit_ls.value = 0
  174. dut.y_limit_hs.value = 0
  175. dut.z_limit_ls.value = 0
  176. dut.z_limit_hs.value = 0
  177. await clocks(dut, 16)
  178. # Z/X/Y percents = 50/50/50 (not jog 01/02)
  179. payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 50, 50, 50))
  180. checkpoint("set_all_tx")
  181. await send_frame(dut, frame(SET_ALL, payload))
  182. await clocks(dut, CLKS_PER_BIT * 16)
  183. assert int(dut.motor_en_n.value) == 1
  184. await wait_level_or_edge(
  185. dut.u_dut.frame_accept_enable,
  186. want=1,
  187. timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
  188. stage="frame_accept_enable",
  189. )
  190. checkpoint("get_motor_status_tx")
  191. # Arm RX before/during TX so DUT's first start bit is not missed.
  192. status_task = cocotb.start_soon(
  193. receive_exact(dut, 37, STATUS_BYTE_TIMEOUT_MS, "motor_status_response")
  194. )
  195. await send_frame(dut, frame(GET_MOTOR_STATUS, b""))
  196. status = await status_task
  197. assert status[:4] == bytes((0xA5, 0x5A, MOTOR_STATUS_DATA, 31))
  198. assert len(status) == 37
  199. payload = status[4:35]
  200. assert len(payload) == 31
  201. assert status[-2:] == crc16(status[2:-2]).to_bytes(2, "little")
  202. assert payload[0] & 0x40 # startup_complete
  203. # Byte-exact regions: X@1..10, Y@11..20, Z@21..30 (SET_ALL 50/50/50)
  204. assert payload[3] == 50 # X requested percent
  205. assert payload[13] == 50 # Y
  206. assert payload[23] == 50 # Z
  207. # Anti-misalign: first two payload bytes must not be a false duplicate
  208. # of a non-equal snap[0]/snap[1] pattern when state differs.
  209. assert payload[1] & 0x07 in range(0, 7) # X state nibble
  210. # Last byte is Z fault_code (cal success → 0)
  211. assert payload[30] == 0
  212. checkpoint("motor_status_ok")
  213. await wait_level_or_edge(
  214. dut.u_dut.frame_accept_enable,
  215. want=1,
  216. timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
  217. stage="frame_accept_enable_2",
  218. )
  219. checkpoint("get_temperature_tx")
  220. temp_task = cocotb.start_soon(
  221. receive_exact(dut, 33, TEMPERATURE_BYTE_TIMEOUT_MS, "temperature_response")
  222. )
  223. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  224. response = await temp_task
  225. assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
  226. assert len(response) == 33
  227. assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
  228. assert set(response[4:31]) == {0xFF}
  229. checkpoint("temperature_response_ok", bytes=len(response))
  230. finally:
  231. try:
  232. simulator.stop_simulator()
  233. except Exception:
  234. pass