run_6400_acquisition.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #!/usr/bin/env python3
  2. """Run physical-port CT7428/BMC models through the current 6400 production top."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import re
  8. import shutil
  9. import subprocess
  10. import time
  11. from pathlib import Path
  12. def fixture_from_adc(adc: Path) -> tuple[str, dict[str, str]]:
  13. assignments = re.findall(
  14. r"set_pin_assignment\s*\{\s*([^{}]+?)\s*\}\s*\{[^{}]*?LOCATION\s*=\s*([A-Z]+\d+)\s*;[^{}]*\}",
  15. adc.read_text(encoding="utf-8"),
  16. )
  17. by_ball: dict[str, str] = {}
  18. by_port: dict[str, str] = {}
  19. for port, ball in assignments:
  20. port = port.strip()
  21. if ball in by_ball or port in by_port:
  22. raise ValueError(f"duplicate ADC ball/port {ball}/{port}")
  23. by_ball[ball], by_port[port] = port, ball
  24. for port, ball in {"sys_clk": "J1", "host_ttl_rx": "J4", "host_ttl_tx": "K2",
  25. "bmc_rs232_rx": "M9", "bmc_rs232_tx": "L10"}.items():
  26. if by_port.get(port) != ball:
  27. raise ValueError(f"physical connector {port} expected {ball}, ADC has {by_port.get(port)}")
  28. ct_mapping = {ball: by_ball.get(ball) for ball in ("B14", "A15", "M8", "N9")}
  29. for ball, signal in ct_mapping.items():
  30. if signal not in ("temp_scl", "temp_sda", "temp_scl_alt", "temp_sda_alt"):
  31. raise ValueError(f"physical CT branch {ball} has unsupported ADC signal {signal}")
  32. # B14/A15 are the populated R1888/R1889 path. M8/N9 lead through
  33. # R744/R745 marked NC and cannot drive the sensor in this assembly.
  34. fixture = """`timescale 1ns/1ps
  35. module prod2u_6400_v2_acquisition_fixture (
  36. input wire clk, host_rx, bmc_rx,
  37. output wire host_tx, bmc_tx,
  38. inout wire physical_ct_scl, physical_ct_sda,
  39. output wire nc_ct_scl, nc_ct_sda,
  40. output wire [23:0] ptc
  41. );
  42. tri temp_scl, temp_sda, temp_scl_alt, temp_sda_alt;
  43. prod2u_6400_v2_top #(.HOST_BAUD(921600)) dut (
  44. .sys_clk(clk), .host_ttl_rx(host_rx), .host_ttl_tx(host_tx),
  45. .host_rs232_rx(1'b1), .host_rs232_tx(),
  46. .bmc_rs232_rx(bmc_rx), .bmc_rs232_tx(bmc_tx),
  47. .ptc_pwm_out(ptc), .ptc_spare_zero(),
  48. .front_fan_pwm_out(), .rear_fan_pwm_out(),
  49. .temp_scl(temp_scl), .temp_sda(temp_sda),
  50. .temp_scl_alt(temp_scl_alt), .temp_sda_alt(temp_sda_alt),
  51. .ssr1_out(), .ssr2_out(), .ssr4_out(),
  52. .ssr_unused_zero(),
  53. .estop_btn_in(1'b0), .hood_open_btn_in(1'b0), .hood_close_btn_in(1'b0), .buzzer_out()
  54. );
  55. // Timer-only elaboration acceleration. UART bit timing, I2C timing,
  56. // 25 MHz clock and every acquisition/state/RAM path stay unchanged.
  57. defparam dut.u_bmc_poll.POLL_SECONDS = 0;
  58. defparam dut.u_bmc_poll.ROUND_TIMEOUT_CLKS = 750000;
  59. """
  60. fixture += f" tran u_scl_populated(physical_ct_scl, {ct_mapping['B14']});\n"
  61. fixture += f" tran u_sda_populated(physical_ct_sda, {ct_mapping['A15']});\n"
  62. fixture += f" assign nc_ct_scl = {ct_mapping['M8']};\n"
  63. fixture += f" assign nc_ct_sda = {ct_mapping['N9']};\n"
  64. fixture += "endmodule\n"
  65. return fixture, ct_mapping
  66. def main() -> int:
  67. parser = argparse.ArgumentParser(description=__doc__)
  68. parser.add_argument("--repo", type=Path, required=True)
  69. parser.add_argument("--tests", type=Path, help="directory containing the three new Verilog test/model files")
  70. parser.add_argument("--out", type=Path, required=True)
  71. args = parser.parse_args()
  72. repo, out = args.repo.resolve(), args.out.resolve()
  73. test_dir = args.tests or Path(__file__).resolve().parent
  74. if args.tests is None and not (test_dir / "prod2u_6400_v2_acquisition_tb.v").is_file():
  75. test_dir = repo / "tests/sim"
  76. test_files = [test_dir / name for name in (
  77. "prod2u_6400_v2_acquisition_tb.v", "ct7428_normal_slave_bfm.v", "bmc_uart_normal_bfm.v")]
  78. closure_path = repo / "products/6400-v2/source-closure.json"
  79. adc_path = repo / "constraints/prod2u_6400_v2.adc"
  80. closure = json.loads(closure_path.read_text(encoding="utf-8"))
  81. source_files = [repo / name for name in closure["sources"] if Path(name).suffix == ".v"]
  82. inputs = test_files + [adc_path, closure_path] + [repo / name for name in closure["sources"]]
  83. for path in inputs:
  84. if not path.is_file():
  85. parser.error(f"missing input: {path}")
  86. for tool in ("iverilog", "vvp"):
  87. if shutil.which(tool) is None:
  88. parser.error(f"required executable unavailable: {tool}")
  89. out.mkdir(parents=True, exist_ok=True)
  90. fixture_text, mapping = fixture_from_adc(adc_path)
  91. fixture_path = out / "actual_adc_acquisition_fixture.v"
  92. fixture_path.write_text(fixture_text, encoding="utf-8")
  93. receipt = {
  94. "test": "prod2u_6400_v2_acquisition_tb", "status": "NOT_RUN",
  95. "scope": "physical-port digital BFM through production RTL; not analog or actual CT7428 silicon validation",
  96. "ct_evidence": "U6 AD0 pin9 via populated R578=0ohm to VCC; physical B14/A15 via R1888/R1889; M8/N9 R744/R745 NC",
  97. "ct_protocol_basis": "0x49, registers 0..8 and raw>>7 from historical MCU contract; vendor brief does not fully specify address/register packing",
  98. "ct_model_raw_words": ["0000", "0cb0", "1400", "2378", "3200", "07c0", "0820", "08e0", "0900"],
  99. "ct_expected_celsius": [0, 25, 40, 70, 100, 15, 16, 17, 18],
  100. "ct_unfitted_channels": "9..26 always 0xFF",
  101. "bmc_rounds": ["43-byte command; echo plus 48 tokens on 3 lines plus prompt", "no response; all previous BMC values must become 0xFF"],
  102. "clock_hz": 25000000, "host_baud": 921600, "bmc_baud": 115200,
  103. "i2c_half_period_clocks": 125,
  104. "timer_only_elaboration_overrides": {"u_bmc_poll.POLL_SECONDS": 0, "u_bmc_poll.ROUND_TIMEOUT_CLKS": 750000},
  105. "hierarchical_force_or_ram_injection": False,
  106. "actual_adc_ct_mapping": mapping,
  107. "source_sha256": {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in inputs},
  108. "fixture_sha256": hashlib.sha256(fixture_path.read_bytes()).hexdigest(),
  109. "commands": [],
  110. }
  111. commands = [
  112. ["iverilog", "-g2012", "-I", str(repo), "-s", "prod2u_6400_v2_acquisition_tb",
  113. "-o", str(out / "acquisition.vvp"), *map(str, test_files), str(fixture_path), *map(str, source_files)],
  114. ["vvp", str(out / "acquisition.vvp")],
  115. ]
  116. success = True
  117. for name, command in zip(("compile", "simulate"), commands):
  118. started = time.monotonic()
  119. try:
  120. result = subprocess.run(command, cwd=repo, text=True, stdout=subprocess.PIPE,
  121. stderr=subprocess.STDOUT, timeout=240, check=False)
  122. text, code = result.stdout, result.returncode
  123. except subprocess.TimeoutExpired as exc:
  124. raw = exc.stdout or ""
  125. text = raw.decode(errors="replace") if isinstance(raw, bytes) else raw
  126. text += "\nTIMEOUT after 240 seconds\n"
  127. code = 124
  128. log = out / f"{name}.log"
  129. log.write_text(text, encoding="utf-8")
  130. print(text, end="" if text.endswith("\n") else "\n")
  131. receipt["commands"].append({"argv": command, "returncode": code,
  132. "seconds": round(time.monotonic()-started, 3), "log": str(log)})
  133. if code:
  134. success = False
  135. break
  136. if name == "simulate":
  137. success = "PASS prod2u_6400_v2_acquisition_tb:" in text
  138. receipt["status"] = "PASS" if success else "FAIL"
  139. (out / "receipt.json").write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  140. print(f"{receipt['status']}: {out / 'receipt.json'}")
  141. return 0 if success else 1
  142. if __name__ == "__main__":
  143. raise SystemExit(main())