test_prod2u_door_temp_uart_e2e.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. # Let the simulator advance directly to STEP activity. Iterating every
  114. # sys_clk edge here made the same bounded check take hundreds of seconds
  115. # of Python/VPI wall time despite only needing to observe two rises.
  116. rises = 0
  117. for rise_index in range(min_rises):
  118. await wait_for_stage(
  119. RisingEdge(step_sig),
  120. 5000,
  121. f"cal_measure_{axis_name}",
  122. rise_index,
  123. )
  124. rises += 1
  125. limit_hs.value = 1
  126. limit_ls.value = 0
  127. checkpoint(f"cal_open_{axis_name}", rises=rises)
  128. # Allow limit sync + terminal handoff before the next axis starts.
  129. await clocks(dut, 4000)
  130. return rises
  131. @cocotb.test()
  132. async def test_set_all_get_temperature_over_real_uart(dut):
  133. try:
  134. checkpoint("test_start")
  135. dut.host_uart_rx.value = 1
  136. # Begin on close limits so each serial axis can finish seek-close immediately.
  137. dut.x_limit_ls.value = 1
  138. dut.x_limit_hs.value = 0
  139. dut.y_limit_ls.value = 1
  140. dut.y_limit_hs.value = 0
  141. dut.z_limit_ls.value = 1
  142. dut.z_limit_hs.value = 0
  143. dut.temp_scl.value = 1
  144. dut.temp_sda.value = 1
  145. await clocks(dut, 2000)
  146. # A2 serial X→Y→Z: stimulate open limit per axis after its own measure-open rises.
  147. # Do not assert Y/Z open early — that strands seek-close and burns MAX_CAL_STEPS.
  148. x_rises = await wait_measure_rises_then_open(
  149. dut, step_sig=dut.x_step, limit_ls=dut.x_limit_ls, limit_hs=dut.x_limit_hs, axis_name="x"
  150. )
  151. y_rises = await wait_measure_rises_then_open(
  152. dut, step_sig=dut.y_step, limit_ls=dut.y_limit_ls, limit_hs=dut.y_limit_hs, axis_name="y"
  153. )
  154. z_rises = await wait_measure_rises_then_open(
  155. dut, step_sig=dut.z_step, limit_ls=dut.z_limit_ls, limit_hs=dut.z_limit_hs, axis_name="z"
  156. )
  157. await wait_level_or_edge(
  158. dut.u_dut.startup_complete,
  159. want=1,
  160. timeout_ms=STARTUP_TIMEOUT_MS,
  161. stage="startup_complete",
  162. )
  163. checkpoint("startup_complete", x_rises=x_rises, y_rises=y_rises, z_rises=z_rises)
  164. # Clear limits for mid motion
  165. dut.x_limit_ls.value = 0
  166. dut.x_limit_hs.value = 0
  167. dut.y_limit_ls.value = 0
  168. dut.y_limit_hs.value = 0
  169. dut.z_limit_ls.value = 0
  170. dut.z_limit_hs.value = 0
  171. await clocks(dut, 16)
  172. # Z/X/Y percents = 50/50/50 (not jog 01/02)
  173. payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 50, 50, 50))
  174. checkpoint("set_all_tx")
  175. await send_frame(dut, frame(SET_ALL, payload))
  176. await clocks(dut, CLKS_PER_BIT * 16)
  177. assert int(dut.motor_en_n.value) == 1
  178. await wait_level_or_edge(
  179. dut.u_dut.frame_accept_enable,
  180. want=1,
  181. timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
  182. stage="frame_accept_enable",
  183. )
  184. checkpoint("get_motor_status_tx")
  185. # Arm RX before/during TX so DUT's first start bit is not missed.
  186. status_task = cocotb.start_soon(
  187. receive_exact(dut, 37, STATUS_BYTE_TIMEOUT_MS, "motor_status_response")
  188. )
  189. await send_frame(dut, frame(GET_MOTOR_STATUS, b""))
  190. status = await status_task
  191. assert status[:4] == bytes((0xA5, 0x5A, MOTOR_STATUS_DATA, 31))
  192. assert len(status) == 37
  193. payload = status[4:35]
  194. assert len(payload) == 31
  195. assert status[-2:] == crc16(status[2:-2]).to_bytes(2, "little")
  196. assert payload[0] & 0x40 # startup_complete
  197. # Byte-exact regions: X@1..10, Y@11..20, Z@21..30 (SET_ALL 50/50/50)
  198. assert payload[3] == 50 # X requested percent
  199. assert payload[13] == 50 # Y
  200. assert payload[23] == 50 # Z
  201. # Anti-misalign: first two payload bytes must not be a false duplicate
  202. # of a non-equal snap[0]/snap[1] pattern when state differs.
  203. assert payload[1] & 0x07 in range(0, 7) # X state nibble
  204. # Last byte is Z fault_code (cal success → 0)
  205. assert payload[30] == 0
  206. checkpoint("motor_status_ok")
  207. await wait_level_or_edge(
  208. dut.u_dut.frame_accept_enable,
  209. want=1,
  210. timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
  211. stage="frame_accept_enable_2",
  212. )
  213. checkpoint("get_temperature_tx")
  214. temp_task = cocotb.start_soon(
  215. receive_exact(dut, 33, TEMPERATURE_BYTE_TIMEOUT_MS, "temperature_response")
  216. )
  217. await send_frame(dut, frame(GET_TEMPERATURE, b""))
  218. response = await temp_task
  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. try:
  226. simulator.stop_simulator()
  227. except Exception:
  228. pass