run_hthd_pty_rtl.py 26 KB

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