| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720 |
- #!/usr/bin/env python3
- """L3: real hthd + PTY + UART-bit bridge + current Prod2U top (Icarus/cocotb).
- Exit 0 on PASS, 1 on fail, 2 if tools/RTL/cocotb are missing (NOT RUN).
- """
- from __future__ import annotations
- import os
- import pty
- import select
- import socket
- import subprocess
- import sys
- import tempfile
- import termios
- import threading
- import time
- from pathlib import Path
- HERE = Path(__file__).resolve().parent
- HOST = HERE.parents[1]
- REPO = HOST.parent
- sys.path.insert(0, str(REPO))
- OSS_CAD_POISON = ("PYTHONEXECUTABLE", "PYTHONHOME", "PYTHONNOUSERSITE")
- UART_FAST = HERE / "prod2u_hthd_fast_uart_top.v"
- UART_PROD = HERE / "prod2u_hthd_prod_uart_top.v"
- def _uart_choice() -> tuple[Path, str, str]:
- if os.environ.get("HTH_PRODUCTION_UART") == "1":
- return UART_PROD, "prod2u_hthd_prod_uart_top", "217"
- return UART_FAST, "prod2u_hthd_fast_uart_top", "8"
- def _cad_root() -> Path | None:
- for root in (Path("/data/prod2u/oss-cad-suite/latest"), Path("/data/prod2u/oss-cad-suite")):
- if (root / "libexec" / "iverilog").is_file() and (root / "libexec" / "vvp").is_file():
- return root
- return None
- def _write_clean_cad_shims(shim: Path, cad: Path) -> None:
- """Call libexec iverilog/vvp without the OSS CAD vvp wrapper's PYTHONEXECUTABLE poison."""
- shim.mkdir(parents=True, exist_ok=True)
- ld = cad / "lib" / "ld-linux-x86-64.so.2"
- lib = cad / "lib"
- iver = cad / "libexec" / "iverilog"
- vvp = cad / "libexec" / "vvp"
- vvp_shim = shim / "vvp"
- vvp_shim.write_text(
- f"#!/bin/bash\nexec {ld} --inhibit-cache --inhibit-rpath '' --library-path {lib} {vvp} \"$@\"\n",
- encoding="utf-8",
- )
- vvp_shim.chmod(0o755)
- iver_shim = shim / "iverilog"
- iver_shim.write_text(
- f"#!/bin/bash\nexec {ld} --inhibit-cache --inhibit-rpath '' --library-path {lib} {iver} -p VVP_EXECUTABLE={vvp_shim} \"$@\"\n",
- encoding="utf-8",
- )
- iver_shim.chmod(0o755)
- def _select_cocotb_python() -> Path | None:
- candidates = [
- Path(os.environ.get("PROD2U_P4_COCOTB_PYTHON", "")),
- Path("/opt/hth-cocotb312/bin/python"),
- Path("/opt/hth-cocotb/bin/python"),
- Path("/root/.cache/prod2u/venvs/verify/bin/python"),
- Path(sys.executable),
- ]
- for cand in candidates:
- if not cand.is_file():
- continue
- r = subprocess.run(
- [str(cand), "-B", "-c", "import cocotb, cocotb_tools"],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- timeout=20,
- env={k: v for k, v in os.environ.items() if k not in OSS_CAD_POISON},
- )
- if r.returncode == 0:
- return cand
- return None
- def _sdk_python() -> Path:
- cands = [
- Path(os.environ.get("HTH_SDK_PYTHON", "")),
- HOST / ".venv-sdk" / "bin" / "python3",
- HOST / ".venv-sdk" / "bin" / "python",
- Path("/opt/python-3.12/bin/python3.12"),
- Path("/usr/bin/python3.13"),
- Path(sys.executable),
- ]
- for cand in cands:
- if not cand.is_file():
- continue
- r = subprocess.run(
- [str(cand), "-c", "import grpc"],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- )
- if r.returncode == 0:
- return cand
- return Path(sys.executable)
- def _shim_dir(build: Path, python: Path, cad: Path) -> Path:
- shim = build / "path-shim"
- _write_clean_cad_shims(shim, cad)
- for name in ("python", "python3"):
- path = shim / name
- if path.exists() or path.is_symlink():
- path.unlink()
- path.symlink_to(python)
- return shim
- def _rtl_sources() -> list[Path]:
- from tools.prod2u_p4_normal_v3_build import PRODUCTION_RTL_SOURCES
- return [REPO / rel for rel in PRODUCTION_RTL_SOURCES]
- def _write_hthd_yaml(path: Path, slave: str, obs: str, ctl: str, runtime_root: str) -> None:
- path.write_text(
- f"""api_version: hth.api.v1
- device_id: prod2u-0
- backend: serial
- profile: {HOST / "profiles" / "prod2u-door-temp" / "profile.json"}
- runtime_root: {runtime_root}
- serial:
- path: {slave}
- io_timeout_ms: 28000
- inter_byte_timeout_ms: 2000
- response_timeout_ms: 28000
- get_temp_timeout_ms: 20000
- get_motor_timeout_ms: 28000
- probe_timeout_ms: 28000
- set_all_timeout_ms: 2000
- open_timeout_ms: 5000
- sockets:
- observe: {obs}
- control: {ctl}
- poll:
- temperature_ms: 12000
- motor_status_ms: 1500
- watchdog:
- heartbeat_period_ms: 8000
- lease:
- min_ttl_ms: 50
- max_ttl_ms: 30000
- safety:
- fan: 10
- ptc: 0
- door_close_percent: 0
- ring_buffer_size: 32
- subscriber_buffer_size: 64
- grpc:
- reflection: false
- """,
- encoding="utf-8",
- )
- def _set_raw_clocal(fd: int) -> None:
- """Binary 8N1-like PTY: no ICANON (or SET_ALL never leaves the line buffer)."""
- attrs = termios.tcgetattr(fd)
- attrs[0] &= ~(
- termios.IGNBRK | termios.BRKINT | termios.PARMRK | termios.ISTRIP
- | termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IXON
- )
- attrs[1] &= ~termios.OPOST
- attrs[2] |= termios.CS8 | termios.CLOCAL | termios.CREAD
- attrs[2] &= ~(termios.PARENB | termios.CSTOPB | termios.HUPCL)
- attrs[3] &= ~(termios.ECHO | termios.ECHONL | termios.ICANON | termios.ISIG | termios.IEXTEN)
- attrs[6][termios.VMIN] = 0
- attrs[6][termios.VTIME] = 0
- termios.tcsetattr(fd, termios.TCSANOW, attrs)
- def _crc16_ccitt_false(data: bytes) -> int:
- crc = 0xFFFF
- for b in data:
- crc ^= b << 8
- for _ in range(8):
- if crc & 0x8000:
- crc = ((crc << 1) & 0xFFFF) ^ 0x1021
- else:
- crc = (crc << 1) & 0xFFFF
- return crc
- def _extract_frames(buf: bytearray) -> list[bytes]:
- out: list[bytes] = []
- while len(buf) >= 6:
- if buf[0] != 0xA5:
- del buf[0]
- continue
- if buf[1] != 0x5A:
- del buf[0]
- continue
- plen = buf[3]
- need = 6 + plen
- if len(buf) < need:
- break
- out.append(bytes(buf[:need]))
- del buf[:need]
- return out
- def _clear_startup_complete(frame: bytes) -> bytes:
- if len(frame) < 7 or frame[2] != 0x83 or frame[3] != 31:
- return frame
- payload = bytearray(frame[4:-2])
- payload[0] &= 0xBF
- body = bytes([frame[2], frame[3]]) + bytes(payload)
- crc = _crc16_ccitt_false(body)
- return bytes([0xA5, 0x5A]) + body + bytes((crc & 0xFF, crc >> 8))
- class UartTap:
- """Hold MOTOR_STATUS startup_complete=0 for wall-clock delayed-startup tests."""
- def __init__(self, hold_s: float = 10.0) -> None:
- self.hold_s = hold_s
- self._start = 0.0
- self._started = threading.Event()
- self.up_buf = bytearray()
- self.dn_buf = bytearray()
- self.get_temp_during_hold = 0
- self.get_temp_after = 0
- self.motor_req_during_hold = 0
- self.motor_req_after = 0
- self.lock = threading.Lock()
- def mark_hthd_start(self) -> None:
- self._start = time.monotonic()
- self._started.set()
- def holding(self) -> bool:
- if not self._started.is_set():
- return False
- return time.monotonic() < self._start + self.hold_s
- def on_pty_to_rtl(self, data: bytes) -> None:
- self.up_buf.extend(data)
- for frame in _extract_frames(self.up_buf):
- if len(frame) < 3:
- continue
- typ = frame[2]
- with self.lock:
- hold = self.holding()
- if typ == 0x02:
- if hold:
- self.get_temp_during_hold += 1
- else:
- self.get_temp_after += 1
- elif typ == 0x03:
- if hold:
- self.motor_req_during_hold += 1
- else:
- self.motor_req_after += 1
- def rewrite_rtl_to_pty(self, data: bytes) -> bytes:
- self.dn_buf.extend(data)
- frames = _extract_frames(self.dn_buf)
- if not frames:
- return b""
- out = bytearray()
- hold = self.holding()
- for frame in frames:
- if hold and len(frame) >= 3 and frame[2] == 0x83:
- frame = _clear_startup_complete(frame)
- out.extend(frame)
- return bytes(out)
- def _shuttle(master_fd: int, conn: socket.socket, stop: threading.Event, tap: UartTap | None = None) -> None:
- log_path = Path(os.environ.get("HTH_UART_LOG", "/tmp/hth-uart-bridge.log"))
- n_up = n_dn = 0
- while not stop.is_set():
- try:
- ready, _, _ = select.select([master_fd, conn], [], [], 0.05)
- except (OSError, ValueError):
- break
- if master_fd in ready:
- try:
- data = os.read(master_fd, 256)
- except OSError:
- time.sleep(0.01)
- continue
- if data:
- n_up += len(data)
- line = f"pty->rtl {data.hex()}\n"
- if n_up <= 256:
- print(line, end="", flush=True)
- try:
- with log_path.open("a", encoding="utf-8") as f:
- if n_up <= 256:
- f.write(line)
- except OSError:
- pass
- if tap is not None:
- tap.on_pty_to_rtl(data)
- try:
- conn.sendall(data)
- except OSError:
- time.sleep(0.01)
- continue
- if conn in ready:
- try:
- data = conn.recv(256)
- except OSError:
- time.sleep(0.01)
- continue
- if data:
- if tap is not None:
- data = tap.rewrite_rtl_to_pty(data)
- if not data:
- continue
- n_dn += len(data)
- line = f"rtl->pty {data.hex()}\n"
- if n_dn <= 256:
- print(line, end="", flush=True)
- try:
- with log_path.open("a", encoding="utf-8") as f:
- if n_dn <= 256:
- f.write(line)
- except OSError:
- pass
- try:
- os.write(master_fd, data)
- except OSError:
- time.sleep(0.01)
- continue
- try:
- with log_path.open("a", encoding="utf-8") as f:
- f.write(f"totals pty_to_rtl={n_up} rtl_to_pty={n_dn}\n")
- except OSError:
- pass
- def _sdk_apply(obs: str, ctl: str) -> None:
- script = r"""
- import asyncio, os, sys
- from datetime import timedelta
- from pathlib import Path
- sys.path.insert(0, os.environ["HTH_SDK_SRC"])
- from hth_sdk.client import connect
- from hth_sdk.types import ActionBatch
- async def main():
- obs, ctl = os.environ["HTH_OBS"], os.environ["HTH_CTL"]
- async with await connect(observe=obs, control=ctl, role="control") as client:
- for _ in range(400):
- snap = await client.get_snapshot("prod2u-0")
- if snap.lifecycle == "READY":
- break
- await asyncio.sleep(0.5)
- else:
- raise SystemExit("hthd never reached READY against RTL")
- caps = await client.get_capabilities("prod2u-0")
- async with await client.acquire_lease("prod2u-0", "rtl-l3", timedelta(seconds=30), auto_renew=False) as lease:
- snap = await client.get_snapshot("prod2u-0")
- b = ActionBatch.builder("prod2u-0", capabilities=caps).based_on(snap.snapshot_seq, snap.control_revision)
- for act in caps.actuators:
- if "door" in act.id and "close_percent" in act.id:
- b.set(act.id, 50)
- elif act.id.startswith("fan."):
- b.set(act.id, 10)
- elif act.id.startswith("ptc."):
- b.set(act.id, 0)
- else:
- b.set(act.id, act.safety_default)
- res = await lease.apply(b.build())
- if not res.accepted:
- raise SystemExit(f"ApplyAction rejected: {res}")
- print("APPLY_ACCEPTED")
- asyncio.run(main())
- """
- env = os.environ.copy()
- env["HTH_OBS"] = obs
- env["HTH_CTL"] = ctl
- env["HTH_SDK_SRC"] = str(HOST / "sdk" / "python")
- r = subprocess.run([str(_sdk_python()), "-B", "-c", script], env=env, capture_output=True, text=True)
- sys.stdout.write(r.stdout)
- sys.stderr.write(r.stderr)
- if r.returncode != 0:
- raise RuntimeError("sdk apply failed")
- def _sdk_safe_resume(obs: str, ctl: str) -> None:
- script = r"""
- import asyncio, os, sys
- from datetime import timedelta
- sys.path.insert(0, os.environ["HTH_SDK_SRC"])
- from hth_sdk.client import connect
- from hth_sdk.types import ActionBatch
- async def main():
- obs, ctl = os.environ["HTH_OBS"], os.environ["HTH_CTL"]
- async with await connect(observe=obs, control=ctl, role="control") as client:
- snap = await client.get_snapshot("prod2u-0")
- temps = [m for m in snap.measurements if m.id.startswith("temperature.channel.")]
- if len(temps) < 27:
- raise SystemExit(f"expected 27 temperature channels after GET_TEMP, got {len(temps)}")
- print("TEMP_CHANNELS", len(temps), "EVENT_ID", snap.event_id, "QUALITY", sorted({m.quality for m in temps}))
- caps = await client.get_capabilities("prod2u-0")
- async with await client.acquire_lease("prod2u-0", "rtl-safe", timedelta(seconds=30), auto_renew=False) as lease:
- safe = await lease.enter_safe_mode("rtl-safe")
- print("SAFE_ACCEPTED", safe.accepted, safe.dispatch_state, safe.confirmation)
- snap = await client.get_snapshot("prod2u-0")
- rb = ActionBatch.builder("prod2u-0", capabilities=caps).based_on(snap.snapshot_seq, snap.control_revision)
- for act in caps.actuators:
- if act.id.startswith("fan."):
- rb.set(act.id, 10)
- elif act.id.startswith("ptc."):
- rb.set(act.id, 0)
- elif "door" in act.id and "close_percent" in act.id:
- rb.set(act.id, 0)
- else:
- rb.set(act.id, act.safety_default)
- resumed = await lease.resume_from_safe(rb.build())
- print("RESUME_ACCEPTED", resumed.accepted, resumed.dispatch_state, resumed.confirmation)
- snap2 = await client.get_snapshot("prod2u-0")
- if snap2.event_id < snap.event_id:
- raise SystemExit(f"event_id went backwards {snap.event_id} -> {snap2.event_id}")
- print("EVENT_ID_MONOTONIC", snap.event_id, snap2.event_id)
- hb_ok = False
- for _ in range(40):
- s = await client.get_snapshot("prod2u-0")
- if s.last_successful_hardware_heartbeat is not None:
- hb_ok = True
- print("HEARTBEAT_SEEN", s.last_successful_hardware_heartbeat, "REV", s.control_revision)
- break
- await asyncio.sleep(0.5)
- if not hb_ok:
- raise SystemExit("no hardware heartbeat after resume")
- print("RTL_SAFE_RESUME_HEARTBEAT_PATH_OK")
- asyncio.run(main())
- """
- env = os.environ.copy()
- env["HTH_OBS"] = obs
- env["HTH_CTL"] = ctl
- env["HTH_SDK_SRC"] = str(HOST / "sdk" / "python")
- r = subprocess.run([str(_sdk_python()), "-B", "-c", script], env=env, capture_output=True, text=True)
- sys.stdout.write(r.stdout)
- sys.stderr.write(r.stderr)
- if r.returncode != 0:
- raise RuntimeError("sdk safe/resume failed")
- def _run_sim_child() -> int:
- py = Path(os.environ["PYGPI_PYTHON_BIN"])
- from cocotb_tools.runner import get_runner
- uart_top, hdl_top, clks = _uart_choice()
- runner = get_runner("icarus")
- sources = _rtl_sources()
- runner.build(
- sources=[*sources, uart_top],
- hdl_toplevel=hdl_top,
- build_dir=os.environ["HTH_SIM_DIR"],
- build_args=["-I", str(REPO)],
- always=True,
- verbose=False,
- )
- runner.test(
- hdl_toplevel=hdl_top,
- test_module="test_hthd_pty_bridge",
- build_dir=os.environ["HTH_SIM_DIR"],
- test_dir=str(HERE),
- results_xml=os.environ["HTH_RESULTS_XML"],
- extra_env={
- "HTH_UART_BRIDGE": os.environ["HTH_UART_BRIDGE"],
- "HTH_RTL_RESULT": os.environ["HTH_RTL_RESULT"],
- "HTH_BRIDGE_READY": os.environ["HTH_BRIDGE_READY"],
- "HTH_STARTUP_FILE": os.environ["HTH_STARTUP_FILE"],
- "HTH_EXPECT_PERCENT": "50",
- "HTH_CLKS_PER_BIT": clks,
- "PYTHONPATH": str(HERE),
- "PYGPI_PYTHON_BIN": str(py),
- "PATH": os.environ["PATH"],
- "LIBPYTHON_LOC": os.environ.get("LIBPYTHON_LOC", ""),
- },
- )
- return 0
- def main() -> int:
- if "--production-uart" in sys.argv:
- os.environ["HTH_PRODUCTION_UART"] = "1"
- os.environ["HTH_CLKS_PER_BIT"] = "217"
- if "--sim" in sys.argv:
- return _run_sim_child()
- skip = "--skip-missing" in sys.argv
- cad = _cad_root()
- py = _select_cocotb_python()
- uart_top, hdl_top, clks = _uart_choice()
- try:
- sources = _rtl_sources()
- missing_rtl = [str(p) for p in sources if not p.is_file()]
- except Exception as exc:
- print("RTL-in-the-loop hthd+PTY+UART-bit: NOT RUN")
- print("source_manifest:", exc)
- return 2 if skip else 1
- if not uart_top.is_file():
- missing_rtl.append(str(uart_top))
- if cad is None or py is None or missing_rtl:
- print("RTL-in-the-loop hthd+PTY+UART-bit: NOT RUN")
- print("cad_root:", cad)
- print("cocotb_python:", py)
- print("missing_rtl:", ",".join(missing_rtl) or "none")
- return 2 if skip else 1
- if Path(sys.executable).resolve() != py.resolve():
- env = os.environ.copy()
- env["PROD2U_P4_COCOTB_PYTHON"] = str(py)
- env.setdefault("LIBPYTHON_LOC", "/opt/python-3.12/lib/libpython3.12.so.1.0")
- os.execve(str(py), [str(py), "-B", str(Path(__file__).resolve()), *sys.argv[1:]], env)
- work_root = REPO / "tmp"
- work_root.mkdir(parents=True, exist_ok=True)
- build = Path(tempfile.mkdtemp(prefix="hth-hthd-rtl-", dir=str(work_root)))
- shim = _shim_dir(build, py, cad)
- result = build / "result.txt"
- ready = build / "bridge.ready"
- startup = build / "startup.txt"
- sock_dir = Path(f"/tmp/hth-rtl-{os.getpid()}")
- sock_dir.mkdir(parents=True, exist_ok=True)
- (sock_dir / "observe").mkdir(exist_ok=True)
- (sock_dir / "control").mkdir(exist_ok=True)
- bridge = str(sock_dir / "uart.bridge")
- obs = str(sock_dir / "observe" / "observe.sock")
- ctl = str(sock_dir / "control" / "control.sock")
- cfg = build / "hthd.yaml"
- sim_dir = build / "sim"
- results_xml = build / "results.xml"
- master, slave = pty.openpty()
- _set_raw_clocal(master)
- try:
- _set_raw_clocal(slave)
- except termios.error:
- pass
- slave_name = os.ttyname(slave)
- _write_hthd_yaml(cfg, slave_name, obs, ctl, str(sock_dir))
- hthd_bin = build / "hthd"
- subprocess.check_call(
- ["go", "build", "-o", str(hthd_bin), "./cmd/hthd"],
- cwd=str(HOST),
- env={**os.environ, "CGO_ENABLED": "0", "GOTOOLCHAIN": os.environ.get("GOTOOLCHAIN", "local")},
- )
- env = {k: v for k, v in os.environ.items() if k not in OSS_CAD_POISON}
- env["PATH"] = os.pathsep.join([str(py.parent), str(shim), "/usr/bin", "/bin"])
- env["LD_LIBRARY_PATH"] = "/opt/python-3.12/lib" + os.pathsep + env.get("LD_LIBRARY_PATH", "")
- env["PYTHONPATH"] = str(HERE) + os.pathsep + str(REPO)
- env["PYGPI_PYTHON_BIN"] = str(py)
- env["VIRTUAL_ENV"] = str(py.parent.parent)
- env["TEMP"] = str(build)
- env["TMP"] = str(build)
- env["TMPDIR"] = str(build)
- env["HTH_UART_BRIDGE"] = bridge
- env["HTH_RTL_RESULT"] = str(result)
- env["HTH_BRIDGE_READY"] = str(ready)
- env["HTH_STARTUP_FILE"] = str(startup)
- env["HTH_SIM_DIR"] = str(sim_dir)
- env["HTH_RESULTS_XML"] = str(results_xml)
- env["HTH_UART_LOG"] = os.environ.get("HTH_UART_LOG", str(build / "uart-bridge.log"))
- env["HTH_CLKS_PER_BIT"] = clks
- env["HTH_PRODUCTION_UART"] = os.environ.get("HTH_PRODUCTION_UART", "0")
- env["HTH_SIM_STOP"] = str(build / "sim.stop")
- env["PYTHONPATH"] = str(HERE) + os.pathsep + str(REPO)
- os.environ["PATH"] = env["PATH"]
- os.environ["PYGPI_PYTHON_BIN"] = str(py)
- os.environ["LIBPYTHON_LOC"] = os.environ.get("LIBPYTHON_LOC", "/opt/python-3.12/lib/libpython3.12.so.1.0")
- os.environ["HTH_UART_LOG"] = env["HTH_UART_LOG"]
- Path(env["HTH_UART_LOG"]).write_text("", encoding="utf-8")
- srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- srv.bind(bridge)
- srv.listen(1)
- srv.settimeout(300)
- sim = subprocess.Popen([str(py), "-B", str(HERE / "run_hthd_pty_rtl.py"), "--sim"], cwd=str(HERE), env=env)
- try:
- conn, _ = srv.accept()
- except socket.timeout:
- print("cocotb did not connect UART bridge", file=sys.stderr)
- sim.kill()
- return 1
- stop = threading.Event()
- tap = UartTap(hold_s=10.0)
- threading.Thread(target=_shuttle, args=(master, conn, stop, tap), daemon=True).start()
- for _ in range(900):
- if ready.is_file():
- break
- if sim.poll() is not None:
- print("simulator exited before bridge ready", file=sys.stderr)
- return 1
- time.sleep(0.1)
- else:
- print("bridge ready file missing", file=sys.stderr)
- return 1
- hthd = None
- try:
- for _ in range(600 if clks == "217" else 240):
- if startup.is_file():
- break
- time.sleep(0.5)
- else:
- print("RTL startup_complete file missing", file=sys.stderr)
- return 1
- time.sleep(1.0)
- # Start hthd only after RTL calibration. Overlapping host UART with
- # Icarus bit-banging 5000-step seek makes MOTOR_STATUS miss the 28s
- # timeout and look like a reconnect loop. After hthd starts, the UART
- # tap holds MOTOR_STATUS.startup_complete=0 for 10s wall-clock so the
- # production UART path proves no GET_TEMPERATURE during delayed startup.
- hthd = subprocess.Popen([str(hthd_bin), "--config", str(cfg)], cwd=str(HOST), env={**os.environ})
- tap.mark_hthd_start()
- for _ in range(200):
- if Path(obs).exists() and Path(ctl).exists():
- break
- time.sleep(0.1)
- else:
- print("hthd sockets not ready", file=sys.stderr)
- return 1
- try:
- _sdk_apply(obs, ctl)
- except Exception as exc:
- print("sdk apply failed:", exc, file=sys.stderr)
- deadline = time.time() + (300 if clks == "217" else 180)
- while time.time() < deadline:
- if result.is_file():
- text = result.read_text(encoding="utf-8")
- if text.startswith("PASS"):
- print(
- "DELAYED_STARTUP_HOLD_S",
- tap.hold_s,
- "GET_TEMP_DURING_HOLD",
- tap.get_temp_during_hold,
- "MOTOR_DURING_HOLD",
- tap.motor_req_during_hold,
- "GET_TEMP_AFTER",
- tap.get_temp_after,
- )
- if tap.get_temp_during_hold:
- print("GET_TEMPERATURE sent during delayed-startup hold", file=sys.stderr)
- return 1
- if tap.get_temp_after < 1:
- time.sleep(0.5)
- continue
- if tap.motor_req_during_hold == 0:
- print("no GET_MOTOR_STATUS during delayed-startup hold", file=sys.stderr)
- return 1
- try:
- _sdk_safe_resume(obs, ctl)
- except Exception as exc:
- print("sdk safe/resume failed:", exc, file=sys.stderr)
- return 1
- tag = "RTL_HTHD_PTY_PRODUCTION_UART_PASS" if clks == "217" else "RTL_HTHD_PTY_UART_BIT_PASS"
- print(tag)
- print("clks_per_bit", clks)
- print("hdl_top", hdl_top)
- print("RTL_DELAYED_STARTUP_PASS")
- print(text.strip())
- return 0
- if text.startswith("FAIL"):
- print(text, file=sys.stderr)
- return 1
- if sim.poll() is not None and (not result.is_file() or not result.read_text(encoding="utf-8").startswith("PASS")):
- print("simulator exited without PASS", file=sys.stderr)
- return 1
- time.sleep(0.5)
- print("timeout waiting for RTL PASS", file=sys.stderr)
- if result.is_file():
- print(result.read_text(encoding="utf-8"), file=sys.stderr)
- return 1
- finally:
- stop.set()
- try:
- Path(env["HTH_SIM_STOP"]).write_text("stop\n", encoding="utf-8")
- except Exception:
- pass
- if hthd is not None:
- hthd.send_signal(15)
- try:
- hthd.wait(timeout=8)
- except subprocess.TimeoutExpired:
- hthd.kill()
- sim.send_signal(15)
- try:
- sim.wait(timeout=5)
- except subprocess.TimeoutExpired:
- sim.kill()
- try:
- conn.close()
- except Exception:
- pass
- srv.close()
- os.close(master)
- os.close(slave)
- if __name__ == "__main__":
- raise SystemExit(main())
|