run_hthd_pty_rtl.py 29 KB

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