# SPDX-License-Identifier: MIT """Drive the closed box (Nick Mikstas's POKEY VHDL under GHDL) through its pins. The model is never opened (docs/restart.md rules 1 and 5). ``scripts/run_vhdl.py`` builds it from the pinned checkout and ``validation/pokey_tb.vhd`` (this repository's pin-level testbench); this module writes stimulus files in the testbench's language, runs the executable and parses one row per cycle. A stimulus is a list of commands, one per phi2 period except K/P/S, which take no cycle (see the head of validation/pokey_tb.vhd): ("W", register, value) write ("R", register) read ("N", count) count cycles with the chip deselected ("K", v) ("P", v) ("S", v) keyboard response, pot pins, serial in ``run(commands)`` returns a list of ``Row`` tuples, one per cycle. Values the model leaves undefined print as -1. Environment: ``OSS_CAD_SUITE`` (an unpacked oss-cad-suite holding ``bin/ghdl``). """ from __future__ import annotations import os import subprocess import sys import tempfile from pathlib import Path from typing import NamedTuple ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) import run_vhdl # noqa: E402 (same directory) class Row(NamedTuple): cycle: int kind: str # "W", "R" or "N" address: int data: int # the byte written, the byte read, or 255 audio: int # the 6-bit sum on the audio pin irq: int # the model's irq port: 1 while asserted (measured 2026-11-14: 0 with IRQEN = 0) sod: int oclk: int bclko: int dump: int k: int # K5-K0 as printed: the scan code itself ($3F held, then $00, $01, ...: 2026-11-14) _EXECUTABLE: Path | None = None def executable() -> Path: """Build the closed box once per process (cached by run_vhdl on disk).""" global _EXECUTABLE if _EXECUTABLE is None: oss = os.environ.get("OSS_CAD_SUITE") _EXECUTABLE = run_vhdl.build(run_vhdl.environment(Path(oss) if oss else None)) return _EXECUTABLE def available() -> bool: """Whether the closed box can be built here (the checkout and GHDL exist).""" if not run_vhdl.MODEL.is_dir(): return False try: executable() except (OSError, subprocess.CalledProcessError): return False return True def text(commands: list[tuple]) -> str: return "".join(" ".join(str(x) for x in command) + "\n" for command in commands) def run(commands: list[tuple], timeout: float = 600.0) -> list[Row]: """Run one stimulus through the closed box; one Row per phi2 period.""" exe = executable() with tempfile.NamedTemporaryFile( "w", suffix=".stim", dir=run_vhdl.WORK, delete=False, encoding="ascii" ) as handle: handle.write(text(commands)) stimulus = Path(handle.name) try: out = subprocess.run( ["nice", "-n", "19", str(exe), f"-gSTIM={stimulus}"], cwd=run_vhdl.WORK, check=True, capture_output=True, text=True, timeout=timeout, ).stdout # fmt: skip finally: stimulus.replace(stimulus.with_suffix(".last")) rows = [] for line in out.splitlines(): parts = line.split() if len(parts) == 11 and parts[0].isdigit(): rows.append(Row(int(parts[0]), parts[1], *(int(x) for x in parts[2:]))) return rows def preamble(audctl: int = 0, hold: int = 40) -> list[tuple]: """Every write register given a value (the model has no power-on state), init mode held. Ends in initialisation mode (SKCTL = 0) after ``hold`` idle cycles, which is long enough for the derived clocks and the polynomial counters to reach their reset states (AHRM 5.5: 18 cycles for the 17-bit register). """ commands: list[tuple] = [("W", 15, 0)] for register in range(8): # AUDC = $A0 (pure tone, volume 0): a poly-5-gated distortion in init mode # is closed-box difference D6 and would leave the flip-flops apart commands.append(("W", register, 0xA0 if register & 1 else 0)) commands += [ ("W", 8, audctl), ("W", 13, 0), ("W", 14, 0), ("W", 10, 0), ("W", 9, 0), ("N", hold), ] # fmt: skip return commands def channel_bits(audio: int, volumes: tuple[int, int, int, int] = (1, 2, 4, 8)) -> int: """Decode the audio pin's sum into four output bits (bit k = channel k+1). Valid only when the four channels' volumes are distinct powers of two, so that the sum is a binary number (validation.md, "What it still takes", 1). """ bits = 0 for index, volume in enumerate(volumes): if audio & volume: bits |= 1 << index return bits if __name__ == "__main__": rows = run([*preamble(), ("W", 15, 3), *[("R", 10)] * 8]) for row in rows[-8:]: print(row)