| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235 |
- """Cocotb: UART-bit (accelerated clocks/bit) bridge for a real hthd PTY."""
- from __future__ import annotations
- import os
- import queue
- import socket
- import threading
- from pathlib import Path
- import cocotb
- from cocotb.triggers import FallingEdge, ReadWrite, RisingEdge, Timer, with_timeout
- from cocotb.utils import get_sim_time
- # Must match wrapper defparam. Fast path uses 8; production UART uses 217.
- CLKS_PER_BIT = int(os.environ.get("HTH_CLKS_PER_BIT", "8"))
- async def clocks(dut, count: int) -> None:
- clk = getattr(getattr(dut, "u_dut", None), "sys_clk", None)
- if clk is None or count <= 0:
- await Timer(max(count, 1) * 40, units="ns")
- return
- if count < 32:
- for _ in range(count):
- await RisingEdge(clk)
- return
- # Advance sim time in one wait, then sync to a clock edge. 217 RisingEdge
- # callbacks per bit made production UART miss the host probe window.
- await Timer((count - 1) * 40, units="ns")
- await RisingEdge(clk)
- async def send_uart_byte(dut, value: int) -> None:
- await ReadWrite()
- dut.host_uart_rx.value = 0
- await clocks(dut, CLKS_PER_BIT)
- for bit in range(8):
- await ReadWrite()
- dut.host_uart_rx.value = (value >> bit) & 1
- await clocks(dut, CLKS_PER_BIT)
- await ReadWrite()
- dut.host_uart_rx.value = 1
- await clocks(dut, CLKS_PER_BIT)
- async def receive_uart_byte(dut) -> int:
- # Wait until TX is high (idle or the stop bit of the previous byte), then
- # take the next falling edge as START. Do not consume an extra stop-bit
- # after the 8 data samples: back-to-back MOTOR_STATUS bytes have no idle
- # gap, and an extra CLKS_PER_BIT wait lands in the next start bit.
- while True:
- try:
- if int(dut.host_uart_tx.value) == 1:
- break
- except Exception:
- pass
- await clocks(dut, 1)
- await FallingEdge(dut.host_uart_tx)
- await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
- value = 0
- for bit in range(8):
- value |= int(dut.host_uart_tx.value) << bit
- await clocks(dut, CLKS_PER_BIT)
- return value
- def _result_path() -> Path:
- return Path(os.environ.get("HTH_RTL_RESULT", "/tmp/hth-rtl-result.txt"))
- def _start_socket_threads(sock: socket.socket) -> tuple[queue.Queue, queue.Queue]:
- # Bound host→RTL so a reconnect storm cannot queue hundreds of kilobytes
- # of SET_ALL/GET_MOTOR while Icarus still bit-bangs 217 clocks/bit.
- rx_q: queue.Queue[int] = queue.Queue(maxsize=64)
- tx_q: queue.Queue[int] = queue.Queue()
- sock.setblocking(True)
- def reader() -> None:
- try:
- while True:
- data = sock.recv(256)
- if not data:
- return
- for value in data:
- rx_q.put(value)
- except OSError:
- return
- def writer() -> None:
- try:
- while True:
- value = tx_q.get()
- sock.sendall(bytes([value]))
- except OSError:
- return
- threading.Thread(target=reader, daemon=True).start()
- threading.Thread(target=writer, daemon=True).start()
- return rx_q, tx_q
- async def finish_axis_calibration(dut, step_sig, limit_ls, limit_hs, axis: str) -> int:
- """Let one serial axis measure at least two open steps, then hit its open limit."""
- rises = {"n": 0}
- async def count_rises():
- while True:
- await RisingEdge(step_sig)
- rises["n"] += 1
- counter = cocotb.start_soon(count_rises())
- try:
- for _ in range(100_000):
- await clocks(dut, 625)
- if rises["n"] >= 2:
- break
- else:
- raise AssertionError(f"insufficient measure-open rises axis={axis} rises={rises['n']}")
- limit_hs.value = 1
- limit_ls.value = 0
- await clocks(dut, 4000)
- return rises["n"]
- finally:
- counter.kill()
- @cocotb.test()
- async def test_hthd_pty_set_all(dut):
- result = _result_path()
- result.write_text("RUNNING\n", encoding="utf-8")
- dut.host_uart_rx.value = 1
- dut.x_limit_ls.value = 1
- dut.x_limit_hs.value = 0
- dut.y_limit_ls.value = 1
- dut.y_limit_hs.value = 0
- dut.z_limit_ls.value = 1
- dut.z_limit_hs.value = 0
- dut.temp_scl.value = 1
- dut.temp_sda.value = 1
- await clocks(dut, 2000)
- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- sock.connect(os.environ["HTH_UART_BRIDGE"])
- rx_q, tx_q = _start_socket_threads(sock)
- Path(os.environ["HTH_BRIDGE_READY"]).write_text("ready\n", encoding="utf-8")
- async def host_to_dut():
- while True:
- try:
- value = rx_q.get_nowait()
- except queue.Empty:
- await Timer(1, units="us")
- continue
- await send_uart_byte(dut, value)
- # Wall-clock timeout must cover Icarus simulating one UART byte at 217
- # clocks/bit. A 50ms cap aborts mid MOTOR_STATUS frame (~80k clocks).
- rx_timeout_s = 30 if CLKS_PER_BIT >= 100 else 1
- async def dut_to_host():
- while True:
- try:
- value = await with_timeout(receive_uart_byte(dut), rx_timeout_s, "sec")
- tx_q.put(value)
- except Exception:
- await Timer(1, units="us")
- cocotb.start_soon(host_to_dut())
- cocotb.start_soon(dut_to_host())
- # Calibration is serial X -> Y -> Z. Asserting Y/Z open limits while they
- # are still in seek-close strands those axes until their 5000-step fault
- # cap, so each open limit is asserted only after that axis starts measure-open.
- x_rises = await finish_axis_calibration(
- dut, dut.x_step, dut.x_limit_ls, dut.x_limit_hs, "x"
- )
- y_rises = await finish_axis_calibration(
- dut, dut.y_step, dut.y_limit_ls, dut.y_limit_hs, "y"
- )
- z_rises = await finish_axis_calibration(
- dut, dut.z_step, dut.z_limit_ls, dut.z_limit_hs, "z"
- )
- cocotb.log.info(
- "serial calibration complete x_rises=%d y_rises=%d z_rises=%d",
- x_rises,
- y_rises,
- z_rises,
- )
- matched_startup = False
- for _ in range(200000):
- await clocks(dut, 2000)
- try:
- if int(dut.u_dut.startup_complete.value) == 1:
- matched_startup = True
- break
- except Exception:
- pass
- if not matched_startup:
- result.write_text("FAIL RTL startup_complete never asserted\n", encoding="utf-8")
- raise AssertionError("RTL startup_complete never asserted")
- Path(os.environ["HTH_STARTUP_FILE"]).write_text("1\n", encoding="utf-8")
- target = int(os.environ.get("HTH_EXPECT_PERCENT", "50"))
- matched = False
- for _ in range(40000):
- await Timer(0.2, units="ms")
- try:
- x = int(dut.u_dut.door_percent_x.value)
- y = int(dut.u_dut.door_percent_y.value)
- z = int(dut.u_dut.door_percent_z.value)
- except Exception:
- continue
- if x == target and y == target and z == target:
- matched = True
- break
- if not matched:
- result.write_text(
- f"FAIL door percents never reached {target} sim={get_sim_time(units='ns')}ns\n",
- encoding="utf-8",
- )
- raise AssertionError("RTL did not latch hthd SET_ALL percents")
- result.write_text(f"PASS percent={target}\n", encoding="utf-8")
- # Keep the UART bit-bang alive until the host proves GET_TEMPERATURE
- # after delayed-startup hold, then Safe / Resume / heartbeat. Returning
- # here used to drop the PTY bridge so GET_TEMP_AFTER stayed 0.
- stop = Path(os.environ.get("HTH_SIM_STOP", ""))
- for _ in range(400000):
- if stop and stop.is_file():
- return
- await Timer(1, units="us")
|