test_hthd_pty_bridge.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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, unit="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, unit="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. @cocotb.test()
  85. async def test_hthd_pty_set_all(dut):
  86. result = _result_path()
  87. result.write_text("RUNNING\n", encoding="utf-8")
  88. dut.host_uart_rx.value = 1
  89. dut.x_limit_ls.value = 1
  90. dut.x_limit_hs.value = 0
  91. dut.y_limit_ls.value = 1
  92. dut.y_limit_hs.value = 0
  93. dut.z_limit_ls.value = 1
  94. dut.z_limit_hs.value = 0
  95. dut.temp_scl.value = 1
  96. dut.temp_sda.value = 1
  97. await clocks(dut, 2000)
  98. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  99. sock.connect(os.environ["HTH_UART_BRIDGE"])
  100. rx_q, tx_q = _start_socket_threads(sock)
  101. Path(os.environ["HTH_BRIDGE_READY"]).write_text("ready\n", encoding="utf-8")
  102. x_rises = {"n": 0}
  103. async def count_x():
  104. while True:
  105. await RisingEdge(dut.x_step)
  106. x_rises["n"] += 1
  107. cocotb.start_soon(count_x())
  108. async def host_to_dut():
  109. while True:
  110. try:
  111. value = rx_q.get_nowait()
  112. except queue.Empty:
  113. await Timer(1, unit="us")
  114. continue
  115. await send_uart_byte(dut, value)
  116. # Wall-clock timeout must cover Icarus simulating one UART byte at 217
  117. # clocks/bit. A 50ms cap aborts mid MOTOR_STATUS frame (~80k clocks).
  118. rx_timeout_s = 30 if CLKS_PER_BIT >= 100 else 1
  119. async def dut_to_host():
  120. while True:
  121. try:
  122. value = await with_timeout(receive_uart_byte(dut), rx_timeout_s, "sec")
  123. tx_q.put(value)
  124. except Exception:
  125. await Timer(1, unit="us")
  126. cocotb.start_soon(host_to_dut())
  127. cocotb.start_soon(dut_to_host())
  128. for _ in range(40000):
  129. await clocks(dut, 2500)
  130. if x_rises["n"] >= 2:
  131. break
  132. dut.x_limit_hs.value = 1
  133. dut.y_limit_hs.value = 1
  134. dut.z_limit_hs.value = 1
  135. dut.x_limit_ls.value = 0
  136. dut.y_limit_ls.value = 0
  137. dut.z_limit_ls.value = 0
  138. matched_startup = False
  139. for _ in range(200000):
  140. await clocks(dut, 2000)
  141. try:
  142. if int(dut.u_dut.startup_complete.value) == 1:
  143. matched_startup = True
  144. break
  145. except Exception:
  146. pass
  147. if not matched_startup:
  148. result.write_text("FAIL RTL startup_complete never asserted\n", encoding="utf-8")
  149. raise AssertionError("RTL startup_complete never asserted")
  150. Path(os.environ["HTH_STARTUP_FILE"]).write_text("1\n", encoding="utf-8")
  151. target = int(os.environ.get("HTH_EXPECT_PERCENT", "50"))
  152. matched = False
  153. for _ in range(40000):
  154. await Timer(0.2, unit="ms")
  155. try:
  156. x = int(dut.u_dut.door_percent_x.value)
  157. y = int(dut.u_dut.door_percent_y.value)
  158. z = int(dut.u_dut.door_percent_z.value)
  159. except Exception:
  160. continue
  161. if x == target and y == target and z == target:
  162. matched = True
  163. break
  164. if not matched:
  165. result.write_text(
  166. f"FAIL door percents never reached {target} sim={get_sim_time(unit='ns')}ns\n",
  167. encoding="utf-8",
  168. )
  169. raise AssertionError("RTL did not latch hthd SET_ALL percents")
  170. result.write_text(f"PASS percent={target}\n", encoding="utf-8")
  171. # Keep the UART bit-bang alive until the host proves GET_TEMPERATURE
  172. # after delayed-startup hold, then Safe / Resume / heartbeat. Returning
  173. # here used to drop the PTY bridge so GET_TEMP_AFTER stayed 0.
  174. stop = Path(os.environ.get("HTH_SIM_STOP", ""))
  175. for _ in range(400000):
  176. if stop and stop.is_file():
  177. return
  178. await Timer(1, unit="us")