"""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, unit="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, unit="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 @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") x_rises = {"n": 0} async def count_x(): while True: await RisingEdge(dut.x_step) x_rises["n"] += 1 cocotb.start_soon(count_x()) async def host_to_dut(): while True: try: value = rx_q.get_nowait() except queue.Empty: await Timer(1, unit="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, unit="us") cocotb.start_soon(host_to_dut()) cocotb.start_soon(dut_to_host()) for _ in range(40000): await clocks(dut, 2500) if x_rises["n"] >= 2: break dut.x_limit_hs.value = 1 dut.y_limit_hs.value = 1 dut.z_limit_hs.value = 1 dut.x_limit_ls.value = 0 dut.y_limit_ls.value = 0 dut.z_limit_ls.value = 0 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, unit="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(unit='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, unit="us")