| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258 |
- """End-to-end unit test of the CPLD temperature chain (ulw-loop goal G002).
- The vectors start from the physical temperature (or from an explicitly given
- raw word) and are turned into the raw 16-bit register combination using the
- basis recorded in ``contracts/ct7428-format.json``: one raw count is
- ``1 / (16 * 2^3) = 1/128`` degrees Celsius, so the integer Celsius byte is the
- raw word shifted right by ``discard_low_bits + log2(degrees_denominator)``.
- Every expected byte is computed in Python with exact ``Fraction`` arithmetic
- and the invalid cases are tested *before* the candidate is truncated.
- Those raw words are then driven through the real ``src/acquisition/ct7428_scan.v``
- RTL (with the virtual CT7428 device model of ``tests/sim/ct7428_scan_tb.v``)
- and the byte the RTL actually stored in ``temp_ram`` is compared with the
- Python expectation. No expectation is derived from a DUT output; the only DUT
- values used are the observed result bytes under test.
- Two classic defects are pinned by this test: taking the low eight bits of the
- raw word (which would fabricate a valid 0 C from 0x8000) and rounding the
- fraction up (25.996 C must stay 25 C, not become 26 C).
- Real hardware was not used: ``contracts/ct7428-format.json`` records
- ``physical_validation: NOT_RUN``; this is a simulation and software test.
- """
- from __future__ import annotations
- import json
- import shutil
- import subprocess
- from dataclasses import dataclass
- from fractions import Fraction
- from pathlib import Path
- import pytest
- REPO_ROOT = Path(__file__).resolve().parents[2]
- CT_FORMAT_PATH = REPO_ROOT / "contracts" / "ct7428-format.json"
- INVALID = 0xFF
- SIGN_BIT = 0x8000
- MAX_VALID_CELSIUS = 254
- # The temperature section of AGENTS.md: BMC and CT are one uint8 per channel,
- # 00..FE = 0..254 C, FF = invalid.
- SCAN_TB = "ct7428_scan_tb"
- RTL_SOURCES = (
- "src/rtl/prod2u_p4_i2c_stop_start_read.v",
- "src/modules/i2c_word_reader.v",
- "src/acquisition/ct7428_scan.v",
- "src/acquisition/temp_ram.v",
- "tests/sim/ct7428_scan_tb.v",
- )
- def _resolve_tool(name: str) -> str | None:
- """Locate a simulator binary without importing the heavy tool modules."""
- located = shutil.which(name)
- if located:
- return located
- for candidate in (
- Path("/usr/bin") / name,
- Path("/usr/local/bin") / name,
- Path("/opt/oss-cad-suite/bin") / name,
- Path("/opt/oss-cad-suite/libexec") / name,
- ):
- if candidate.is_file():
- return str(candidate)
- return None
- def _contract() -> dict:
- return json.loads(CT_FORMAT_PATH.read_text(encoding="utf-8"))["temperature"]
- _BASIS = _contract()
- _DISCARD_LOW_BITS: int = int(_BASIS["discard_low_bits"])
- _DEGREES_DENOMINATOR: int = int(_BASIS["degrees_denominator"])
- # One raw count in degrees Celsius, derived from the contract (never hardcoded).
- CELSIUS_PER_COUNT = Fraction(1, _DEGREES_DENOMINATOR * (1 << _DISCARD_LOW_BITS))
- # The contract stores (raw >> discard_low_bits) in 1/degrees_denominator units,
- # so the integer Celsius candidate is the raw word shifted by this amount.
- INTEGER_SHIFT = _DISCARD_LOW_BITS + (
- _DEGREES_DENOMINATOR.bit_length() - 1
- )
- def raw_for_celsius(celsius: Fraction | int) -> int:
- """Raw 16-bit word a sensor would report for this positive temperature."""
- value = Fraction(celsius)
- assert value >= 0, "use an explicit raw word for negative temperatures"
- return int(value / CELSIUS_PER_COUNT)
- def celsius_from_raw(raw: int) -> Fraction:
- """The historical ct7428_conv_temp result, exactly (contract algorithm)."""
- assert 0 <= raw <= 0xFFFF
- if raw > 0x7FFF:
- magnitude = ((~raw) & 0xFFFF) + 1
- return -Fraction(magnitude >> _DISCARD_LOW_BITS, _DEGREES_DENOMINATOR)
- return Fraction(raw >> _DISCARD_LOW_BITS, _DEGREES_DENOMINATOR)
- def expected_byte(raw: int, error: bool = False) -> int:
- """Final uint8 Celsius byte, with every invalid case tested first."""
- if error:
- return INVALID
- if raw >= SIGN_BIT:
- return INVALID
- candidate = raw >> INTEGER_SHIFT
- if candidate >= INVALID:
- return INVALID
- return candidate
- @dataclass(frozen=True)
- class Vector:
- name: str
- raw: int
- error: bool
- @property
- def expected(self) -> int:
- return expected_byte(self.raw, self.error)
- def _vectors() -> list[Vector]:
- """27 vectors: the required coverage plus fillers, one per CT channel."""
- vectors = [
- Vector("0.0 C", raw_for_celsius(0), False),
- Vector("+25.4 C", raw_for_celsius(Fraction("25.4")), False),
- Vector("+40.0 C", raw_for_celsius(40), False),
- Vector("+70.9375 C", raw_for_celsius(Fraction(9080, 128)), False),
- Vector("+100.0 C", raw_for_celsius(100), False),
- Vector("raw 0xFFFF (magnitude 1 -> -0.0 C)", 0xFFFF, False),
- Vector("raw 0x8000 (negative zero)", 0x8000, False),
- Vector("raw 0x8008 (magnitude 32760 -> -255.9375 C)", 0x8008, False),
- Vector("I2C error at +25.4 C", raw_for_celsius(Fraction("25.4")), True),
- Vector("+254.0 C (highest valid)", raw_for_celsius(254), False),
- Vector("+255.0 C (>= 255 is invalid)", raw_for_celsius(255), False),
- Vector("+510.0 C (raw 0xFF00, low byte 0x00)", raw_for_celsius(510), False),
- Vector("+0.0546875 C (raw 7, fraction dropped)", raw_for_celsius(Fraction(7, 128)), False),
- Vector("+25.996 C (never rounded up)", raw_for_celsius(Fraction("25.996")), False),
- ]
- for celsius in range(14, 27):
- vectors.append(Vector(f"+{celsius}.0 C", raw_for_celsius(celsius), False))
- return vectors
- def _run_rtl_scan(vector_list: list[Vector], workdir: Path) -> dict[int, int]:
- """Compile and run the real scan RTL, returning the observed bytes."""
- iverilog = _resolve_tool("iverilog")
- vvp = _resolve_tool("vvp")
- if not iverilog or not vvp:
- pytest.skip("iverilog/vvp unavailable")
- vector_file = workdir / "ct7428_vectors.txt"
- vector_file.write_text(
- "".join(f"{vector.raw:04X} {int(vector.error)}\n" for vector in vector_list),
- encoding="ascii",
- )
- executable = workdir / f"{SCAN_TB}.vvp"
- compile_cmd = [
- iverilog,
- "-g2012",
- "-Wall",
- "-I",
- str(REPO_ROOT),
- "-s",
- SCAN_TB,
- "-o",
- str(executable),
- *[str(REPO_ROOT / source) for source in RTL_SOURCES],
- ]
- compiled = subprocess.run(
- compile_cmd, cwd=REPO_ROOT, capture_output=True, text=True, timeout=300
- )
- assert compiled.returncode == 0, (
- f"iverilog failed for the temperature chain:\n{compiled.stdout}\n{compiled.stderr}"
- )
- run = subprocess.run(
- [vvp, str(executable), f"+VECTOR_FILE={vector_file}"],
- cwd=REPO_ROOT,
- capture_output=True,
- text=True,
- timeout=300,
- )
- assert run.returncode == 0, (
- f"{SCAN_TB} exited non-zero:\n{run.stdout}\n{run.stderr}"
- )
- assert f"{SCAN_TB} PASS" in run.stdout, (
- f"{SCAN_TB} did not pass:\n{run.stdout}\n{run.stderr}"
- )
- observed: dict[int, int] = {}
- for line in run.stdout.splitlines():
- if line.startswith("RESULT "):
- _, channel, byte = line.split()
- observed[int(channel)] = int(byte, 16)
- return observed
- def test_contract_basis_is_one_sixteenth_degree_per_count() -> None:
- """The 0.625 / 0.0625 confusion must be visible in the contract numbers."""
- assert _DISCARD_LOW_BITS == 3
- assert _DEGREES_DENOMINATOR == 16
- assert CELSIUS_PER_COUNT == Fraction(1, 128)
- assert INTEGER_SHIFT == 7
- # 0x0780 counts must be exactly 15 C (a 0.625 C basis would read 150 C).
- assert celsius_from_raw(0x0780) == Fraction(15)
- # The signed decode keeps a fractional negative part.
- assert celsius_from_raw(0x8008) == Fraction(-32760 >> 3, 16)
- assert celsius_from_raw(0xFFFF) == Fraction(0)
- def test_invalid_cases_are_detected_before_truncation() -> None:
- """Expected bytes come from Python, with the classic traps spelled out."""
- # 0 C is a real, valid reading and must survive as 0x00.
- assert expected_byte(raw_for_celsius(0)) == 0x00
- # -0.0 C (raw 0xFFFF) and negative zero (0x8000) are invalid, not 0.
- assert celsius_from_raw(0xFFFF) == 0
- assert expected_byte(0xFFFF) == INVALID
- assert expected_byte(0x8000) == INVALID
- # Taking the low eight bits of 0x8000 would fabricate a valid 0 C.
- assert (0x8000 & 0xFF) == 0x00
- assert expected_byte(0x8000) != 0x00
- # 255 C and above must not wrap: 0xFF00's low byte is 0x00 as well.
- assert (0xFF00 & 0xFF) == 0x00
- assert expected_byte(0xFF00) == INVALID
- assert expected_byte(raw_for_celsius(255)) == INVALID
- # Fractions are discarded, never rounded.
- assert expected_byte(raw_for_celsius(Fraction("25.996"))) == 25
- assert expected_byte(raw_for_celsius(Fraction(7, 128))) == 0x00
- def test_rtl_scan_converts_real_raw_words_to_the_expected_bytes(tmp_path: Path) -> None:
- """The real ct7428_scan RTL must produce every independently expected byte."""
- vector_list = _vectors()
- assert len(vector_list) == 27, "one vector per CT channel"
- observed = _run_rtl_scan(vector_list, tmp_path)
- assert len(observed) == 27, f"scan did not report all channels: {observed}"
- for channel, vector in enumerate(vector_list):
- assert channel in observed, f"channel {channel} missing from the scan"
- assert observed[channel] == vector.expected, (
- f"channel {channel} ({vector.name}): raw 0x{vector.raw:04X} "
- f"produced 0x{observed[channel]:02X}, expected 0x{vector.expected:02X}"
- )
- # The specific traps, checked through the RTL result rather than a helper.
- assert observed[6] == INVALID, "raw 0x8000 must be invalid through the RTL"
- assert observed[8] == INVALID, "an I2C error must write 0xFF through the RTL"
- assert observed[7] == INVALID, "raw 0x8008 must be invalid through the RTL"
- assert observed[13] == 25, "+25.996 C must be 25 C through the RTL"
- assert observed[0] == 0x00, "a real 0 C sample must be a valid 0x00"
|