run_hthd_pty_rtl.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. #!/usr/bin/env python3
  2. """L3: real hthd + PTY + UART-bit bridge + current Prod2U top (Icarus/cocotb).
  3. Exit 0 on PASS, 1 on fail, 2 if tools/RTL/cocotb are missing (NOT RUN).
  4. """
  5. from __future__ import annotations
  6. import os
  7. import pty
  8. import select
  9. import socket
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import termios
  14. import threading
  15. import time
  16. from pathlib import Path
  17. HERE = Path(__file__).resolve().parent
  18. HOST = HERE.parents[1]
  19. REPO = HOST.parent
  20. sys.path.insert(0, str(REPO))
  21. OSS_CAD_POISON = ("PYTHONEXECUTABLE", "PYTHONHOME", "PYTHONNOUSERSITE")
  22. UART_FAST = HERE / "prod2u_hthd_fast_uart_top.v"
  23. UART_PROD = HERE / "prod2u_hthd_prod_uart_top.v"
  24. def _uart_choice() -> tuple[Path, str, str]:
  25. if os.environ.get("HTH_PRODUCTION_UART") == "1":
  26. return UART_PROD, "prod2u_hthd_prod_uart_top", "217"
  27. return UART_FAST, "prod2u_hthd_fast_uart_top", "8"
  28. def _cad_root() -> Path | None:
  29. for root in (Path("/data/prod2u/oss-cad-suite/latest"), Path("/data/prod2u/oss-cad-suite")):
  30. if (root / "libexec" / "iverilog").is_file() and (root / "libexec" / "vvp").is_file():
  31. return root
  32. return None
  33. def _write_clean_cad_shims(shim: Path, cad: Path) -> None:
  34. """Call libexec iverilog/vvp without the OSS CAD vvp wrapper's PYTHONEXECUTABLE poison."""
  35. shim.mkdir(parents=True, exist_ok=True)
  36. ld = cad / "lib" / "ld-linux-x86-64.so.2"
  37. lib = cad / "lib"
  38. iver = cad / "libexec" / "iverilog"
  39. vvp = cad / "libexec" / "vvp"
  40. vvp_shim = shim / "vvp"
  41. vvp_shim.write_text(
  42. f"#!/bin/bash\nexec {ld} --inhibit-cache --inhibit-rpath '' --library-path {lib} {vvp} \"$@\"\n",
  43. encoding="utf-8",
  44. )
  45. vvp_shim.chmod(0o755)
  46. iver_shim = shim / "iverilog"
  47. iver_shim.write_text(
  48. f"#!/bin/bash\nexec {ld} --inhibit-cache --inhibit-rpath '' --library-path {lib} {iver} -p VVP_EXECUTABLE={vvp_shim} \"$@\"\n",
  49. encoding="utf-8",
  50. )
  51. iver_shim.chmod(0o755)
  52. def _select_cocotb_python() -> Path | None:
  53. candidates = [
  54. Path(os.environ.get("PROD2U_P4_COCOTB_PYTHON", "")),
  55. Path("/opt/hth-cocotb312/bin/python"),
  56. Path("/opt/hth-cocotb/bin/python"),
  57. Path("/root/.cache/prod2u/venvs/verify/bin/python"),
  58. Path(sys.executable),
  59. ]
  60. for cand in candidates:
  61. if not cand.is_file():
  62. continue
  63. r = subprocess.run(
  64. [str(cand), "-B", "-c", "import cocotb, cocotb_tools"],
  65. stdout=subprocess.DEVNULL,
  66. stderr=subprocess.DEVNULL,
  67. timeout=20,
  68. env={k: v for k, v in os.environ.items() if k not in OSS_CAD_POISON},
  69. )
  70. if r.returncode == 0:
  71. return cand
  72. return None
  73. def _sdk_python() -> Path:
  74. cands = [
  75. Path(os.environ.get("HTH_SDK_PYTHON", "")),
  76. HOST / ".venv-sdk" / "bin" / "python3",
  77. HOST / ".venv-sdk" / "bin" / "python",
  78. Path("/opt/python-3.12/bin/python3.12"),
  79. Path("/usr/bin/python3.13"),
  80. Path(sys.executable),
  81. ]
  82. for cand in cands:
  83. if not cand.is_file():
  84. continue
  85. r = subprocess.run(
  86. [str(cand), "-c", "import grpc"],
  87. stdout=subprocess.DEVNULL,
  88. stderr=subprocess.DEVNULL,
  89. )
  90. if r.returncode == 0:
  91. return cand
  92. return Path(sys.executable)
  93. def _shim_dir(build: Path, python: Path, cad: Path) -> Path:
  94. shim = build / "path-shim"
  95. _write_clean_cad_shims(shim, cad)
  96. for name in ("python", "python3"):
  97. path = shim / name
  98. if path.exists() or path.is_symlink():
  99. path.unlink()
  100. path.symlink_to(python)
  101. return shim
  102. def _rtl_sources() -> list[Path]:
  103. from tools.prod2u_p4_normal_v3_build import PRODUCTION_RTL_SOURCES
  104. return [REPO / rel for rel in PRODUCTION_RTL_SOURCES]
  105. def _write_hthd_yaml(path: Path, slave: str, obs: str, ctl: str, runtime_root: str) -> None:
  106. path.write_text(
  107. f"""api_version: hth.api.v1
  108. device_id: prod2u-0
  109. backend: serial
  110. profile: {HOST / "profiles" / "prod2u-door-temp" / "profile.json"}
  111. runtime_root: {runtime_root}
  112. serial:
  113. path: {slave}
  114. io_timeout_ms: 28000
  115. inter_byte_timeout_ms: 2000
  116. response_timeout_ms: 28000
  117. get_temp_timeout_ms: 20000
  118. get_motor_timeout_ms: 28000
  119. probe_timeout_ms: 28000
  120. set_all_timeout_ms: 2000
  121. open_timeout_ms: 5000
  122. sockets:
  123. observe: {obs}
  124. control: {ctl}
  125. poll:
  126. temperature_ms: 600000
  127. motor_status_ms: 1500
  128. watchdog:
  129. heartbeat_period_ms: 8000
  130. lease:
  131. min_ttl_ms: 50
  132. max_ttl_ms: 30000
  133. safety:
  134. fan: 10
  135. ptc: 0
  136. door_close_percent: 0
  137. ring_buffer_size: 32
  138. subscriber_buffer_size: 4
  139. grpc:
  140. reflection: false
  141. """,
  142. encoding="utf-8",
  143. )
  144. def _set_raw_clocal(fd: int) -> None:
  145. """Binary 8N1-like PTY: no ICANON (or SET_ALL never leaves the line buffer)."""
  146. attrs = termios.tcgetattr(fd)
  147. attrs[0] &= ~(
  148. termios.IGNBRK | termios.BRKINT | termios.PARMRK | termios.ISTRIP
  149. | termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IXON
  150. )
  151. attrs[1] &= ~termios.OPOST
  152. attrs[2] |= termios.CS8 | termios.CLOCAL | termios.CREAD
  153. attrs[2] &= ~(termios.PARENB | termios.CSTOPB | termios.HUPCL)
  154. attrs[3] &= ~(termios.ECHO | termios.ECHONL | termios.ICANON | termios.ISIG | termios.IEXTEN)
  155. attrs[6][termios.VMIN] = 0
  156. attrs[6][termios.VTIME] = 0
  157. termios.tcsetattr(fd, termios.TCSANOW, attrs)
  158. def _crc16_ccitt_false(data: bytes) -> int:
  159. crc = 0xFFFF
  160. for b in data:
  161. crc ^= b << 8
  162. for _ in range(8):
  163. if crc & 0x8000:
  164. crc = ((crc << 1) & 0xFFFF) ^ 0x1021
  165. else:
  166. crc = (crc << 1) & 0xFFFF
  167. return crc
  168. def _extract_frames(buf: bytearray) -> list[bytes]:
  169. out: list[bytes] = []
  170. while len(buf) >= 6:
  171. if buf[0] != 0xA5:
  172. del buf[0]
  173. continue
  174. if buf[1] != 0x5A:
  175. del buf[0]
  176. continue
  177. plen = buf[3]
  178. need = 6 + plen
  179. if len(buf) < need:
  180. break
  181. out.append(bytes(buf[:need]))
  182. del buf[:need]
  183. return out
  184. def _clear_startup_complete(frame: bytes) -> bytes:
  185. if len(frame) < 7 or frame[2] != 0x83 or frame[3] != 31:
  186. return frame
  187. payload = bytearray(frame[4:-2])
  188. payload[0] &= 0xBF
  189. body = bytes([frame[2], frame[3]]) + bytes(payload)
  190. crc = _crc16_ccitt_false(body)
  191. return bytes([0xA5, 0x5A]) + body + bytes((crc & 0xFF, crc >> 8))
  192. class UartTap:
  193. """Hold MOTOR_STATUS startup_complete=0 for wall-clock delayed-startup tests."""
  194. def __init__(self, hold_s: float = 10.0) -> None:
  195. self.hold_s = hold_s
  196. self._start = 0.0
  197. self._started = threading.Event()
  198. self.up_buf = bytearray()
  199. self.dn_buf = bytearray()
  200. self.get_temp_during_hold = 0
  201. self.get_temp_after = 0
  202. self.motor_req_during_hold = 0
  203. self.motor_req_after = 0
  204. self.lock = threading.Lock()
  205. def mark_hthd_start(self) -> None:
  206. self._start = time.monotonic()
  207. self._started.set()
  208. def holding(self) -> bool:
  209. if not self._started.is_set():
  210. return False
  211. return time.monotonic() < self._start + self.hold_s
  212. def on_pty_to_rtl(self, data: bytes) -> None:
  213. self.up_buf.extend(data)
  214. for frame in _extract_frames(self.up_buf):
  215. if len(frame) < 3:
  216. continue
  217. typ = frame[2]
  218. with self.lock:
  219. hold = self.holding()
  220. if typ == 0x02:
  221. if hold:
  222. self.get_temp_during_hold += 1
  223. else:
  224. self.get_temp_after += 1
  225. elif typ == 0x03:
  226. if hold:
  227. self.motor_req_during_hold += 1
  228. else:
  229. self.motor_req_after += 1
  230. def rewrite_rtl_to_pty(self, data: bytes) -> bytes:
  231. self.dn_buf.extend(data)
  232. frames = _extract_frames(self.dn_buf)
  233. if not frames:
  234. return b""
  235. out = bytearray()
  236. hold = self.holding()
  237. for frame in frames:
  238. if hold and len(frame) >= 3 and frame[2] == 0x83:
  239. frame = _clear_startup_complete(frame)
  240. out.extend(frame)
  241. return bytes(out)
  242. def _shuttle(master_fd: int, conn: socket.socket, stop: threading.Event, tap: UartTap | None = None) -> None:
  243. log_path = Path(os.environ.get("HTH_UART_LOG", "/tmp/hth-uart-bridge.log"))
  244. n_up = n_dn = 0
  245. while not stop.is_set():
  246. try:
  247. ready, _, _ = select.select([master_fd, conn], [], [], 0.05)
  248. except (OSError, ValueError):
  249. break
  250. if master_fd in ready:
  251. try:
  252. data = os.read(master_fd, 256)
  253. except OSError:
  254. time.sleep(0.01)
  255. continue
  256. if data:
  257. n_up += len(data)
  258. line = f"pty->rtl {data.hex()}\n"
  259. if n_up <= 256:
  260. print(line, end="", flush=True)
  261. try:
  262. with log_path.open("a", encoding="utf-8") as f:
  263. if n_up <= 256:
  264. f.write(line)
  265. except OSError:
  266. pass
  267. if tap is not None:
  268. tap.on_pty_to_rtl(data)
  269. try:
  270. conn.sendall(data)
  271. except OSError:
  272. time.sleep(0.01)
  273. continue
  274. if conn in ready:
  275. try:
  276. data = conn.recv(256)
  277. except OSError:
  278. time.sleep(0.01)
  279. continue
  280. if data:
  281. if tap is not None:
  282. data = tap.rewrite_rtl_to_pty(data)
  283. if not data:
  284. continue
  285. n_dn += len(data)
  286. line = f"rtl->pty {data.hex()}\n"
  287. if n_dn <= 256:
  288. print(line, end="", flush=True)
  289. try:
  290. with log_path.open("a", encoding="utf-8") as f:
  291. if n_dn <= 256:
  292. f.write(line)
  293. except OSError:
  294. pass
  295. try:
  296. os.write(master_fd, data)
  297. except OSError:
  298. time.sleep(0.01)
  299. continue
  300. try:
  301. with log_path.open("a", encoding="utf-8") as f:
  302. f.write(f"totals pty_to_rtl={n_up} rtl_to_pty={n_dn}\n")
  303. except OSError:
  304. pass
  305. def _sdk_apply(obs: str, ctl: str) -> None:
  306. script = r"""
  307. import asyncio, os, sys
  308. from datetime import timedelta
  309. from pathlib import Path
  310. sys.path.insert(0, os.environ["HTH_SDK_SRC"])
  311. from hth_sdk.client import connect
  312. from hth_sdk.types import ActionBatch
  313. async def main():
  314. obs, ctl = os.environ["HTH_OBS"], os.environ["HTH_CTL"]
  315. async with await connect(observe=obs, control=ctl, role="control") as client:
  316. for _ in range(400):
  317. snap = await client.get_snapshot("prod2u-0")
  318. if snap.lifecycle == "READY":
  319. break
  320. await asyncio.sleep(0.5)
  321. else:
  322. raise SystemExit("hthd never reached READY against RTL")
  323. caps = await client.get_capabilities("prod2u-0")
  324. async with await client.acquire_lease("prod2u-0", "rtl-l3", timedelta(seconds=30), auto_renew=False) as lease:
  325. snap = await client.get_snapshot("prod2u-0")
  326. b = ActionBatch.builder("prod2u-0", capabilities=caps).based_on(snap.snapshot_seq, snap.control_revision)
  327. for act in caps.actuators:
  328. if "door" in act.id and "close_percent" in act.id:
  329. b.set(act.id, 50)
  330. elif act.id.startswith("fan."):
  331. b.set(act.id, 10)
  332. elif act.id.startswith("ptc."):
  333. b.set(act.id, 0)
  334. else:
  335. b.set(act.id, act.safety_default)
  336. res = await lease.apply(b.build())
  337. if not res.accepted:
  338. raise SystemExit(f"ApplyAction rejected: {res}")
  339. print("APPLY_ACCEPTED")
  340. asyncio.run(main())
  341. """
  342. env = os.environ.copy()
  343. env["HTH_OBS"] = obs
  344. env["HTH_CTL"] = ctl
  345. env["HTH_SDK_SRC"] = str(HOST / "sdk" / "python")
  346. r = subprocess.run([str(_sdk_python()), "-B", "-c", script], env=env, capture_output=True, text=True)
  347. sys.stdout.write(r.stdout)
  348. sys.stderr.write(r.stderr)
  349. if r.returncode != 0:
  350. raise RuntimeError("sdk apply failed")
  351. def _sdk_safe_resume(obs: str, ctl: str) -> None:
  352. script = r"""
  353. import asyncio, os, sys
  354. from datetime import timedelta
  355. sys.path.insert(0, os.environ["HTH_SDK_SRC"])
  356. from hth_sdk.client import connect
  357. from hth_sdk.types import ActionBatch
  358. async def main():
  359. obs, ctl = os.environ["HTH_OBS"], os.environ["HTH_CTL"]
  360. async with await connect(observe=obs, control=ctl, role="control") as client:
  361. snap = await client.get_snapshot("prod2u-0")
  362. temps = [m for m in snap.measurements if m.id.startswith("temperature.channel.")]
  363. if len(temps) < 27:
  364. raise SystemExit(f"expected 27 temperature channels after GET_TEMP, got {len(temps)}")
  365. print("TEMP_CHANNELS", len(temps), "EVENT_ID", snap.event_id, "QUALITY", sorted({m.quality for m in temps}))
  366. caps = await client.get_capabilities("prod2u-0")
  367. async with await client.acquire_lease("prod2u-0", "rtl-safe", timedelta(seconds=30), auto_renew=False) as lease:
  368. safe = await lease.enter_safe_mode("rtl-safe")
  369. print("SAFE_ACCEPTED", safe.accepted, safe.dispatch_state, safe.confirmation)
  370. snap = await client.get_snapshot("prod2u-0")
  371. rb = ActionBatch.builder("prod2u-0", capabilities=caps).based_on(snap.snapshot_seq, snap.control_revision)
  372. for act in caps.actuators:
  373. if act.id.startswith("fan."):
  374. rb.set(act.id, 10)
  375. elif act.id.startswith("ptc."):
  376. rb.set(act.id, 0)
  377. elif "door" in act.id and "close_percent" in act.id:
  378. rb.set(act.id, 0)
  379. else:
  380. rb.set(act.id, act.safety_default)
  381. resumed = await lease.resume_from_safe(rb.build())
  382. print("RESUME_ACCEPTED", resumed.accepted, resumed.dispatch_state, resumed.confirmation)
  383. snap2 = await client.get_snapshot("prod2u-0")
  384. if snap2.event_id < snap.event_id:
  385. raise SystemExit(f"event_id went backwards {snap.event_id} -> {snap2.event_id}")
  386. print("EVENT_ID_MONOTONIC", snap.event_id, snap2.event_id)
  387. hb_ok = False
  388. for _ in range(40):
  389. s = await client.get_snapshot("prod2u-0")
  390. if s.last_successful_hardware_heartbeat is not None:
  391. hb_ok = True
  392. print("HEARTBEAT_SEEN", s.last_successful_hardware_heartbeat, "REV", s.control_revision)
  393. break
  394. await asyncio.sleep(0.5)
  395. if not hb_ok:
  396. raise SystemExit("no hardware heartbeat after resume")
  397. print("RTL_SAFE_RESUME_HEARTBEAT_PATH_OK")
  398. asyncio.run(main())
  399. """
  400. env = os.environ.copy()
  401. env["HTH_OBS"] = obs
  402. env["HTH_CTL"] = ctl
  403. env["HTH_SDK_SRC"] = str(HOST / "sdk" / "python")
  404. r = subprocess.run([str(_sdk_python()), "-B", "-c", script], env=env, capture_output=True, text=True)
  405. sys.stdout.write(r.stdout)
  406. sys.stderr.write(r.stderr)
  407. if r.returncode != 0:
  408. raise RuntimeError("sdk safe/resume failed")
  409. def _run_sim_child() -> int:
  410. py = Path(os.environ["PYGPI_PYTHON_BIN"])
  411. from cocotb_tools.runner import get_runner
  412. uart_top, hdl_top, clks = _uart_choice()
  413. runner = get_runner("icarus")
  414. sources = _rtl_sources()
  415. runner.build(
  416. sources=[*sources, uart_top],
  417. hdl_toplevel=hdl_top,
  418. build_dir=os.environ["HTH_SIM_DIR"],
  419. build_args=["-I", str(REPO)],
  420. always=True,
  421. verbose=False,
  422. )
  423. runner.test(
  424. hdl_toplevel=hdl_top,
  425. test_module="test_hthd_pty_bridge",
  426. build_dir=os.environ["HTH_SIM_DIR"],
  427. test_dir=str(HERE),
  428. results_xml=os.environ["HTH_RESULTS_XML"],
  429. extra_env={
  430. "HTH_UART_BRIDGE": os.environ["HTH_UART_BRIDGE"],
  431. "HTH_RTL_RESULT": os.environ["HTH_RTL_RESULT"],
  432. "HTH_BRIDGE_READY": os.environ["HTH_BRIDGE_READY"],
  433. "HTH_STARTUP_FILE": os.environ["HTH_STARTUP_FILE"],
  434. "HTH_EXPECT_PERCENT": "50",
  435. "HTH_CLKS_PER_BIT": clks,
  436. "PYTHONPATH": str(HERE),
  437. "PYGPI_PYTHON_BIN": str(py),
  438. "PATH": os.environ["PATH"],
  439. "LIBPYTHON_LOC": os.environ.get("LIBPYTHON_LOC", ""),
  440. },
  441. )
  442. return 0
  443. def main() -> int:
  444. if "--production-uart" in sys.argv:
  445. os.environ["HTH_PRODUCTION_UART"] = "1"
  446. os.environ["HTH_CLKS_PER_BIT"] = "217"
  447. if "--sim" in sys.argv:
  448. return _run_sim_child()
  449. skip = "--skip-missing" in sys.argv
  450. cad = _cad_root()
  451. py = _select_cocotb_python()
  452. uart_top, hdl_top, clks = _uart_choice()
  453. try:
  454. sources = _rtl_sources()
  455. missing_rtl = [str(p) for p in sources if not p.is_file()]
  456. except Exception as exc:
  457. print("RTL-in-the-loop hthd+PTY+UART-bit: NOT RUN")
  458. print("source_manifest:", exc)
  459. return 2 if skip else 1
  460. if not uart_top.is_file():
  461. missing_rtl.append(str(uart_top))
  462. if cad is None or py is None or missing_rtl:
  463. print("RTL-in-the-loop hthd+PTY+UART-bit: NOT RUN")
  464. print("cad_root:", cad)
  465. print("cocotb_python:", py)
  466. print("missing_rtl:", ",".join(missing_rtl) or "none")
  467. return 2 if skip else 1
  468. if Path(sys.executable).resolve() != py.resolve():
  469. env = os.environ.copy()
  470. env["PROD2U_P4_COCOTB_PYTHON"] = str(py)
  471. env.setdefault("LIBPYTHON_LOC", "/opt/python-3.12/lib/libpython3.12.so.1.0")
  472. os.execve(str(py), [str(py), "-B", str(Path(__file__).resolve()), *sys.argv[1:]], env)
  473. work_root = REPO / "tmp"
  474. work_root.mkdir(parents=True, exist_ok=True)
  475. build = Path(tempfile.mkdtemp(prefix="hth-hthd-rtl-", dir=str(work_root)))
  476. shim = _shim_dir(build, py, cad)
  477. result = build / "result.txt"
  478. ready = build / "bridge.ready"
  479. startup = build / "startup.txt"
  480. sock_dir = Path(f"/tmp/hth-rtl-{os.getpid()}")
  481. sock_dir.mkdir(parents=True, exist_ok=True)
  482. (sock_dir / "observe").mkdir(exist_ok=True)
  483. (sock_dir / "control").mkdir(exist_ok=True)
  484. bridge = str(sock_dir / "uart.bridge")
  485. obs = str(sock_dir / "observe" / "observe.sock")
  486. ctl = str(sock_dir / "control" / "control.sock")
  487. cfg = build / "hthd.yaml"
  488. sim_dir = build / "sim"
  489. results_xml = build / "results.xml"
  490. master, slave = pty.openpty()
  491. _set_raw_clocal(master)
  492. try:
  493. _set_raw_clocal(slave)
  494. except termios.error:
  495. pass
  496. slave_name = os.ttyname(slave)
  497. _write_hthd_yaml(cfg, slave_name, obs, ctl, str(sock_dir))
  498. hthd_bin = build / "hthd"
  499. subprocess.check_call(
  500. ["go", "build", "-o", str(hthd_bin), "./cmd/hthd"],
  501. cwd=str(HOST),
  502. env={**os.environ, "CGO_ENABLED": "0", "GOTOOLCHAIN": os.environ.get("GOTOOLCHAIN", "local")},
  503. )
  504. env = {k: v for k, v in os.environ.items() if k not in OSS_CAD_POISON}
  505. env["PATH"] = os.pathsep.join([str(py.parent), str(shim), "/usr/bin", "/bin"])
  506. env["LD_LIBRARY_PATH"] = "/opt/python-3.12/lib" + os.pathsep + env.get("LD_LIBRARY_PATH", "")
  507. env["PYTHONPATH"] = str(HERE) + os.pathsep + str(REPO)
  508. env["PYGPI_PYTHON_BIN"] = str(py)
  509. env["VIRTUAL_ENV"] = str(py.parent.parent)
  510. env["TEMP"] = str(build)
  511. env["TMP"] = str(build)
  512. env["TMPDIR"] = str(build)
  513. env["HTH_UART_BRIDGE"] = bridge
  514. env["HTH_RTL_RESULT"] = str(result)
  515. env["HTH_BRIDGE_READY"] = str(ready)
  516. env["HTH_STARTUP_FILE"] = str(startup)
  517. env["HTH_SIM_DIR"] = str(sim_dir)
  518. env["HTH_RESULTS_XML"] = str(results_xml)
  519. env["HTH_UART_LOG"] = os.environ.get("HTH_UART_LOG", str(build / "uart-bridge.log"))
  520. env["HTH_CLKS_PER_BIT"] = clks
  521. env["HTH_PRODUCTION_UART"] = os.environ.get("HTH_PRODUCTION_UART", "0")
  522. env["PYTHONPATH"] = str(HERE) + os.pathsep + str(REPO)
  523. os.environ["PATH"] = env["PATH"]
  524. os.environ["PYGPI_PYTHON_BIN"] = str(py)
  525. os.environ["LIBPYTHON_LOC"] = os.environ.get("LIBPYTHON_LOC", "/opt/python-3.12/lib/libpython3.12.so.1.0")
  526. os.environ["HTH_UART_LOG"] = env["HTH_UART_LOG"]
  527. Path(env["HTH_UART_LOG"]).write_text("", encoding="utf-8")
  528. srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  529. srv.bind(bridge)
  530. srv.listen(1)
  531. srv.settimeout(300)
  532. sim = subprocess.Popen([str(py), "-B", str(HERE / "run_hthd_pty_rtl.py"), "--sim"], cwd=str(HERE), env=env)
  533. try:
  534. conn, _ = srv.accept()
  535. except socket.timeout:
  536. print("cocotb did not connect UART bridge", file=sys.stderr)
  537. sim.kill()
  538. return 1
  539. stop = threading.Event()
  540. tap = UartTap(hold_s=10.0)
  541. threading.Thread(target=_shuttle, args=(master, conn, stop, tap), daemon=True).start()
  542. for _ in range(900):
  543. if ready.is_file():
  544. break
  545. if sim.poll() is not None:
  546. print("simulator exited before bridge ready", file=sys.stderr)
  547. return 1
  548. time.sleep(0.1)
  549. else:
  550. print("bridge ready file missing", file=sys.stderr)
  551. return 1
  552. hthd = None
  553. try:
  554. for _ in range(600 if clks == "217" else 240):
  555. if startup.is_file():
  556. break
  557. time.sleep(0.5)
  558. else:
  559. print("RTL startup_complete file missing", file=sys.stderr)
  560. return 1
  561. time.sleep(1.0)
  562. # Start hthd only after RTL calibration. Overlapping host UART with
  563. # Icarus bit-banging 5000-step seek makes MOTOR_STATUS miss the 28s
  564. # timeout and look like a reconnect loop. After hthd starts, the UART
  565. # tap holds MOTOR_STATUS.startup_complete=0 for 10s wall-clock so the
  566. # production UART path proves no GET_TEMPERATURE during delayed startup.
  567. hthd = subprocess.Popen([str(hthd_bin), "--config", str(cfg)], cwd=str(HOST), env={**os.environ})
  568. tap.mark_hthd_start()
  569. for _ in range(200):
  570. if Path(obs).exists() and Path(ctl).exists():
  571. break
  572. time.sleep(0.1)
  573. else:
  574. print("hthd sockets not ready", file=sys.stderr)
  575. return 1
  576. try:
  577. _sdk_apply(obs, ctl)
  578. except Exception as exc:
  579. print("sdk apply failed:", exc, file=sys.stderr)
  580. deadline = time.time() + (300 if clks == "217" else 180)
  581. while time.time() < deadline:
  582. if result.is_file():
  583. text = result.read_text(encoding="utf-8")
  584. if text.startswith("PASS"):
  585. print(
  586. "DELAYED_STARTUP_HOLD_S",
  587. tap.hold_s,
  588. "GET_TEMP_DURING_HOLD",
  589. tap.get_temp_during_hold,
  590. "MOTOR_DURING_HOLD",
  591. tap.motor_req_during_hold,
  592. "GET_TEMP_AFTER",
  593. tap.get_temp_after,
  594. )
  595. if tap.get_temp_during_hold:
  596. print("GET_TEMPERATURE sent during delayed-startup hold", file=sys.stderr)
  597. return 1
  598. if tap.get_temp_after < 1:
  599. time.sleep(0.5)
  600. continue
  601. if tap.motor_req_during_hold == 0:
  602. print("no GET_MOTOR_STATUS during delayed-startup hold", file=sys.stderr)
  603. return 1
  604. try:
  605. _sdk_safe_resume(obs, ctl)
  606. except Exception as exc:
  607. print("sdk safe/resume failed:", exc, file=sys.stderr)
  608. return 1
  609. tag = "RTL_HTHD_PTY_PRODUCTION_UART_PASS" if clks == "217" else "RTL_HTHD_PTY_UART_BIT_PASS"
  610. print(tag)
  611. print("clks_per_bit", clks)
  612. print("hdl_top", hdl_top)
  613. print("RTL_DELAYED_STARTUP_PASS")
  614. print(text.strip())
  615. return 0
  616. if text.startswith("FAIL"):
  617. print(text, file=sys.stderr)
  618. return 1
  619. if sim.poll() is not None and (not result.is_file() or not result.read_text(encoding="utf-8").startswith("PASS")):
  620. print("simulator exited without PASS", file=sys.stderr)
  621. return 1
  622. time.sleep(0.5)
  623. print("timeout waiting for RTL PASS", file=sys.stderr)
  624. if result.is_file():
  625. print(result.read_text(encoding="utf-8"), file=sys.stderr)
  626. return 1
  627. finally:
  628. stop.set()
  629. if hthd is not None:
  630. hthd.send_signal(15)
  631. try:
  632. hthd.wait(timeout=8)
  633. except subprocess.TimeoutExpired:
  634. hthd.kill()
  635. sim.send_signal(15)
  636. try:
  637. sim.wait(timeout=5)
  638. except subprocess.TimeoutExpired:
  639. sim.kill()
  640. try:
  641. conn.close()
  642. except Exception:
  643. pass
  644. srv.close()
  645. os.close(master)
  646. os.close(slave)
  647. if __name__ == "__main__":
  648. raise SystemExit(main())