test_hthd_pty_bridge.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. """Cocotb: UART-bit (accelerated clocks/bit) bridge for a real hthd PTY."""
  2. from __future__ import annotations
  3. import os
  4. import queue
  5. import socket
  6. import threading
  7. from pathlib import Path
  8. import cocotb
  9. from cocotb.triggers import FallingEdge, ReadWrite, RisingEdge, Timer, with_timeout
  10. from cocotb.utils import get_sim_time
  11. # Must match wrapper defparam. Fast path uses 8; production UART uses 217.
  12. CLKS_PER_BIT = int(os.environ.get("HTH_CLKS_PER_BIT", "8"))
  13. async def clocks(dut, count: int) -> None:
  14. clk = getattr(getattr(dut, "u_dut", None), "sys_clk", None)
  15. if clk is None or count <= 0:
  16. await Timer(max(count, 1) * 40, units="ns")
  17. return
  18. if count < 32:
  19. for _ in range(count):
  20. await RisingEdge(clk)
  21. return
  22. # Advance sim time in one wait, then sync to a clock edge. 217 RisingEdge
  23. # callbacks per bit made production UART miss the host probe window.
  24. await Timer((count - 1) * 40, units="ns")
  25. await RisingEdge(clk)
  26. async def send_uart_byte(dut, value: int) -> None:
  27. await ReadWrite()
  28. dut.host_uart_rx.value = 0
  29. await clocks(dut, CLKS_PER_BIT)
  30. for bit in range(8):
  31. await ReadWrite()
  32. dut.host_uart_rx.value = (value >> bit) & 1
  33. await clocks(dut, CLKS_PER_BIT)
  34. await ReadWrite()
  35. dut.host_uart_rx.value = 1
  36. await clocks(dut, CLKS_PER_BIT)
  37. async def receive_uart_byte(dut) -> int:
  38. # Wait until TX is high (idle or the stop bit of the previous byte), then
  39. # take the next falling edge as START. Do not consume an extra stop-bit
  40. # after the 8 data samples: back-to-back MOTOR_STATUS bytes have no idle
  41. # gap, and an extra CLKS_PER_BIT wait lands in the next start bit.
  42. while True:
  43. try:
  44. if int(dut.host_uart_tx.value) == 1:
  45. break
  46. except Exception:
  47. pass
  48. await clocks(dut, 1)
  49. await FallingEdge(dut.host_uart_tx)
  50. await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
  51. value = 0
  52. for bit in range(8):
  53. value |= int(dut.host_uart_tx.value) << bit
  54. await clocks(dut, CLKS_PER_BIT)
  55. return value
  56. def _result_path() -> Path:
  57. return Path(os.environ.get("HTH_RTL_RESULT", "/tmp/hth-rtl-result.txt"))
  58. def _start_socket_threads(sock: socket.socket) -> tuple[queue.Queue, queue.Queue]:
  59. # Bound host→RTL so a reconnect storm cannot queue hundreds of kilobytes
  60. # of SET_ALL/GET_MOTOR while Icarus still bit-bangs 217 clocks/bit.
  61. rx_q: queue.Queue[int] = queue.Queue(maxsize=64)
  62. tx_q: queue.Queue[int] = queue.Queue()
  63. sock.setblocking(True)
  64. def reader() -> None:
  65. try:
  66. while True:
  67. data = sock.recv(256)
  68. if not data:
  69. return
  70. for value in data:
  71. rx_q.put(value)
  72. except OSError:
  73. return
  74. def writer() -> None:
  75. try:
  76. while True:
  77. value = tx_q.get()
  78. sock.sendall(bytes([value]))
  79. except OSError:
  80. return
  81. threading.Thread(target=reader, daemon=True).start()
  82. threading.Thread(target=writer, daemon=True).start()
  83. return rx_q, tx_q
  84. async def finish_axis_calibration(dut, step_sig, limit_ls, limit_hs, axis: str) -> int:
  85. """Let one serial axis measure at least two open steps, then hit its open limit."""
  86. rises = {"n": 0}
  87. async def count_rises():
  88. while True:
  89. await RisingEdge(step_sig)
  90. rises["n"] += 1
  91. counter = cocotb.start_soon(count_rises())
  92. try:
  93. for _ in range(100_000):
  94. await clocks(dut, 625)
  95. if rises["n"] >= 2:
  96. break
  97. else:
  98. raise AssertionError(f"insufficient measure-open rises axis={axis} rises={rises['n']}")
  99. limit_hs.value = 1
  100. limit_ls.value = 0
  101. await clocks(dut, 4000)
  102. return rises["n"]
  103. finally:
  104. counter.kill()
  105. @cocotb.test()
  106. async def test_hthd_pty_set_all(dut):
  107. result = _result_path()
  108. result.write_text("RUNNING\n", encoding="utf-8")
  109. dut.host_uart_rx.value = 1
  110. dut.x_limit_ls.value = 1
  111. dut.x_limit_hs.value = 0
  112. dut.y_limit_ls.value = 1
  113. dut.y_limit_hs.value = 0
  114. dut.z_limit_ls.value = 1
  115. dut.z_limit_hs.value = 0
  116. dut.temp_scl.value = 1
  117. dut.temp_sda.value = 1
  118. await clocks(dut, 2000)
  119. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  120. sock.connect(os.environ["HTH_UART_BRIDGE"])
  121. rx_q, tx_q = _start_socket_threads(sock)
  122. Path(os.environ["HTH_BRIDGE_READY"]).write_text("ready\n", encoding="utf-8")
  123. async def host_to_dut():
  124. while True:
  125. try:
  126. value = rx_q.get_nowait()
  127. except queue.Empty:
  128. await Timer(1, units="us")
  129. continue
  130. await send_uart_byte(dut, value)
  131. # Wall-clock timeout must cover Icarus simulating one UART byte at 217
  132. # clocks/bit. A 50ms cap aborts mid MOTOR_STATUS frame (~80k clocks).
  133. rx_timeout_s = 30 if CLKS_PER_BIT >= 100 else 1
  134. async def dut_to_host():
  135. while True:
  136. try:
  137. value = await with_timeout(receive_uart_byte(dut), rx_timeout_s, "sec")
  138. tx_q.put(value)
  139. except Exception:
  140. await Timer(1, units="us")
  141. cocotb.start_soon(host_to_dut())
  142. cocotb.start_soon(dut_to_host())
  143. # Calibration is serial X -> Y -> Z. Asserting Y/Z open limits while they
  144. # are still in seek-close strands those axes until their 5000-step fault
  145. # cap, so each open limit is asserted only after that axis starts measure-open.
  146. x_rises = await finish_axis_calibration(
  147. dut, dut.x_step, dut.x_limit_ls, dut.x_limit_hs, "x"
  148. )
  149. y_rises = await finish_axis_calibration(
  150. dut, dut.y_step, dut.y_limit_ls, dut.y_limit_hs, "y"
  151. )
  152. z_rises = await finish_axis_calibration(
  153. dut, dut.z_step, dut.z_limit_ls, dut.z_limit_hs, "z"
  154. )
  155. cocotb.log.info(
  156. "serial calibration complete x_rises=%d y_rises=%d z_rises=%d",
  157. x_rises,
  158. y_rises,
  159. z_rises,
  160. )
  161. matched_startup = False
  162. for _ in range(200000):
  163. await clocks(dut, 2000)
  164. try:
  165. if int(dut.u_dut.startup_complete.value) == 1:
  166. matched_startup = True
  167. break
  168. except Exception:
  169. pass
  170. if not matched_startup:
  171. result.write_text("FAIL RTL startup_complete never asserted\n", encoding="utf-8")
  172. raise AssertionError("RTL startup_complete never asserted")
  173. Path(os.environ["HTH_STARTUP_FILE"]).write_text("1\n", encoding="utf-8")
  174. target = int(os.environ.get("HTH_EXPECT_PERCENT", "50"))
  175. matched = False
  176. for _ in range(40000):
  177. await Timer(0.2, units="ms")
  178. try:
  179. x = int(dut.u_dut.door_percent_x.value)
  180. y = int(dut.u_dut.door_percent_y.value)
  181. z = int(dut.u_dut.door_percent_z.value)
  182. except Exception:
  183. continue
  184. if x == target and y == target and z == target:
  185. matched = True
  186. break
  187. if not matched:
  188. result.write_text(
  189. f"FAIL door percents never reached {target} sim={get_sim_time(units='ns')}ns\n",
  190. encoding="utf-8",
  191. )
  192. raise AssertionError("RTL did not latch hthd SET_ALL percents")
  193. result.write_text(f"PASS percent={target}\n", encoding="utf-8")
  194. # Keep the UART bit-bang alive until the host proves GET_TEMPERATURE
  195. # after delayed-startup hold, then Safe / Resume / heartbeat. Returning
  196. # here used to drop the PTY bridge so GET_TEMP_AFTER stayed 0.
  197. stop = Path(os.environ.get("HTH_SIM_STOP", ""))
  198. for _ in range(400000):
  199. if stop and stop.is_file():
  200. return
  201. await Timer(1, units="us")