run_hthd_pty_rtl.py 21 KB

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