run_hthd_pty_rtl.py 32 KB

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