Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5359729140 | ||
|
|
5ab69a835c | ||
|
|
f79c722e68 | ||
|
|
7e872cfbc3 | ||
|
|
3046c4aeee | ||
|
|
b32d581d27 | ||
|
|
29e1a3033d |
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
from collections import defaultdict
|
||||
|
||||
from backend.periscopex.af_rlgc import cascade_sparam
|
||||
@@ -24,8 +25,9 @@ from backend.periscopex.hf_line_check import COORD_QUANT_MM, ENDPOINT_SNAP_MM
|
||||
from backend.periscopex.impedance import GeometryError
|
||||
from backend.periscopex.impedance_traces import analyze_specified_nets
|
||||
from backend.periscopex.models import DesignGraph, Finding, LayoutGraph, LayoutVia
|
||||
from backend.periscopex.pcb_net_match import kicad_nets_match
|
||||
from backend.periscopex.si_check import partner_net
|
||||
from backend.periscopex.pcb_net_match import kicad_nets_match, refs_on_matched_net
|
||||
from backend.periscopex.protocol_catalog import load_catalog
|
||||
from backend.periscopex.si_check import bus_class, partner_net, phy_mac_kind, single_ended_eth_mac
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
SOURCE = "af_trace_check"
|
||||
@@ -35,6 +37,200 @@ _WIDTH_STEP_MM = 0.05
|
||||
_PARALLEL_MIN_MM = 5.0
|
||||
|
||||
|
||||
_MDI_POL = re.compile(
|
||||
r"^(?P<stem>.*(?:TX|RX|TD|RD|TRD\d|TP))(?P<pol>[PN])$",
|
||||
re.I,
|
||||
)
|
||||
_GBE_RE = re.compile(r"1000\s*BASE|1000BASE|\bGBE\b|GIGABIT", re.I)
|
||||
_FAST_RE = re.compile(r"LAN8720|10\s*/\s*100|100BASE|10BASE|BASE[\s\-]?TX", re.I)
|
||||
|
||||
|
||||
def _mdi_mate(name: str) -> str | None:
|
||||
"""TXP/TXN and RXP/RXN, plus the existing _P/_N and +/- partners."""
|
||||
m = _MDI_POL.match(name or "")
|
||||
if m:
|
||||
pol = m.group("pol").upper()
|
||||
return m.group("stem") + ("N" if pol == "P" else "P")
|
||||
return partner_net(name)
|
||||
|
||||
|
||||
def _is_eth_mdi_net(net: str) -> bool:
|
||||
if single_ended_eth_mac(net):
|
||||
return False
|
||||
return bus_class(net) == "eth_mdi"
|
||||
|
||||
|
||||
def _coalesce_eth_pairs(units: list[AfUnit]) -> list[AfUnit]:
|
||||
"""Treat each RJ45/PHY MDI pair as one unit, including TXP/TXN names."""
|
||||
by_net = {n: u for u in units for n in u.nets}
|
||||
out: list[AfUnit] = []
|
||||
seen: set[str] = set()
|
||||
for unit in units:
|
||||
if unit.nets[0] in seen:
|
||||
continue
|
||||
if len(unit.nets) == 1 and _is_eth_mdi_net(unit.nets[0]):
|
||||
mate = _mdi_mate(unit.nets[0])
|
||||
other = by_net.get(mate or "")
|
||||
if mate and other is not None and mate not in seen:
|
||||
nets = tuple(sorted((unit.nets[0], mate)))
|
||||
seen.update(nets)
|
||||
length = max(unit.length_mm, other.length_mm)
|
||||
out.append(AfUnit(nets=nets, length_mm=length, bus="eth_mdi"))
|
||||
continue
|
||||
if all(_is_eth_mdi_net(n) for n in unit.nets):
|
||||
seen.update(unit.nets)
|
||||
out.append(AfUnit(
|
||||
nets=tuple(sorted(unit.nets)),
|
||||
length_mm=unit.length_mm,
|
||||
bus="eth_mdi",
|
||||
))
|
||||
continue
|
||||
seen.update(unit.nets)
|
||||
out.append(unit)
|
||||
return out
|
||||
|
||||
|
||||
def _eth_speed(graph: DesignGraph, nets: tuple[str, ...]) -> str | None:
|
||||
"""10/100 or gbe from the PHY/jack actually on these nets. Else None."""
|
||||
bits: list[str] = []
|
||||
for net in nets:
|
||||
for ref in refs_on_matched_net(graph, net):
|
||||
comp = graph.components.get(ref)
|
||||
if comp is None:
|
||||
continue
|
||||
bits.extend([
|
||||
comp.mpn or "", comp.value or "", comp.footprint or "",
|
||||
comp.component_subtype or "",
|
||||
])
|
||||
row = (graph.bom_fields or {}).get(ref) or {}
|
||||
for key in ("description", "Description", "value", "Value"):
|
||||
if row.get(key):
|
||||
bits.append(str(row.get(key)))
|
||||
text = " ".join(bits)
|
||||
if _GBE_RE.search(text):
|
||||
return "gbe"
|
||||
if _FAST_RE.search(text):
|
||||
return "10/100"
|
||||
return None
|
||||
|
||||
|
||||
def _eth_cite(speed: str) -> tuple[float, str] | None:
|
||||
"""Packed cable_channel ohm for the identified speed. Nothing invented."""
|
||||
want = "1000base-t-mdi" if speed == "gbe" else "100base-tx-mdi"
|
||||
cat = load_catalog()
|
||||
for iface in cat.physical_interfaces:
|
||||
if iface.id != want:
|
||||
continue
|
||||
for c in iface.constraints:
|
||||
if c.parameter != "cable_channel" or c.unit != "ohm" or c.value is None:
|
||||
continue
|
||||
src = c.source
|
||||
doc = (src.document if src and src.document else "IEEE Std 802.3")
|
||||
section = (src.section if src and src.section else "")
|
||||
if speed == "gbe":
|
||||
label = f"{doc} Clause 40 (§{section})" if section else f"{doc} Clause 40"
|
||||
else:
|
||||
label = (
|
||||
f"{doc} 100BASE-TX 25.4.9 (§{section})"
|
||||
if section else f"{doc} 100BASE-TX 25.4.9"
|
||||
)
|
||||
return float(c.value), label
|
||||
return None
|
||||
|
||||
|
||||
def _pair_z_ohm(layout: LayoutGraph, unit: AfUnit) -> float | None:
|
||||
"""One Z for the pair. None when stackup or geometry cannot produce it."""
|
||||
if layout.stackup is None or len(unit.nets) < 2:
|
||||
return None
|
||||
samples = _samples(layout, unit)
|
||||
vals = _z_vals(samples, True)
|
||||
if not vals:
|
||||
return None
|
||||
return sum(vals) / len(vals)
|
||||
|
||||
|
||||
def _ethernet_mdi_finding(
|
||||
graph: DesignGraph,
|
||||
layout: LayoutGraph,
|
||||
unit: AfUnit,
|
||||
) -> Finding:
|
||||
"""Calculated pair Z vs the cited clause for the speed on the board.
|
||||
|
||||
Inside → PASS. Outside → FAIL. Cannot calculate → ERROR.
|
||||
"""
|
||||
speed = _eth_speed(graph, unit.nets)
|
||||
cite = _eth_cite(speed) if speed else None
|
||||
measured = _pair_z_ohm(layout, unit)
|
||||
label = _label(unit)
|
||||
if cite is None:
|
||||
text = (
|
||||
f"Ethernet not certified — because the speed on {label} is not "
|
||||
"identified on the PHY/jack, so no cited clause was applied."
|
||||
)
|
||||
req = "Pair Z is certified only against the cited clause for the identified speed."
|
||||
rec = "Identify the PHY/jack speed. No ohm value is assumed."
|
||||
return _finding(
|
||||
rule_id="PE-AF-002", unit=unit, finding=text,
|
||||
facts=f"nets={label}; speed=unidentified; measured=none.",
|
||||
requirement=req, rec=rec, status="ERROR", cls="RULE",
|
||||
evidence="SUFFICIENT", provenance="MANDATORY",
|
||||
)
|
||||
limit, cite_label = cite
|
||||
req = f"Cited limit {limit:g} Ω, {cite_label}."
|
||||
if measured is None:
|
||||
missing: list[str] = []
|
||||
if len(unit.nets) < 2:
|
||||
missing.append("pair")
|
||||
if layout.stackup is None:
|
||||
missing.append("stackup")
|
||||
else:
|
||||
missing.append("geometry")
|
||||
miss = "/".join(missing)
|
||||
text = (
|
||||
"Ethernet not certified — because Z cannot be calculated from the "
|
||||
f"PCB stackup/geometry ({miss} missing). Cited {limit:g} Ω ({cite_label})."
|
||||
)
|
||||
rec = (
|
||||
f"Pair Z was not calculated ({miss} missing). "
|
||||
f"Cited {limit:g} Ω ({cite_label})."
|
||||
)
|
||||
return _finding(
|
||||
rule_id="PE-AF-002", unit=unit, finding=text,
|
||||
facts=f"nets={label}; speed={speed}; missing={miss}; measured=none.",
|
||||
requirement=req, rec=rec, status="ERROR", cls="RULE",
|
||||
evidence="SUFFICIENT", provenance="MANDATORY",
|
||||
calculation=f"no computed Z; cited {limit:g} Ω.",
|
||||
)
|
||||
inside = abs(measured - limit) <= 1e-6 * max(1.0, abs(limit))
|
||||
if inside:
|
||||
text = (
|
||||
f"Ethernet certified — calculated Z {measured:g} Ω vs cited "
|
||||
f"{limit:g} Ω ({cite_label})."
|
||||
)
|
||||
rec = f"Calculated pair Z matches cited {limit:g} Ω ({cite_label})."
|
||||
return _finding(
|
||||
rule_id="PE-AF-002", unit=unit, finding=text,
|
||||
facts=f"nets={label}; speed={speed}; Z={measured:g} Ω; limit={limit:g} Ω.",
|
||||
requirement=req, rec=rec, status="INFO", cls="INFO",
|
||||
evidence="SUFFICIENT", provenance="MANDATORY",
|
||||
calculation=f"pair Z {measured:g} Ω compared to {limit:g} Ω.",
|
||||
)
|
||||
text = (
|
||||
f"Ethernet not certified — because Z {measured:g} Ω is outside cited "
|
||||
f"{limit:g} Ω ({cite_label})."
|
||||
)
|
||||
rec = (
|
||||
f"Calculated pair Z {measured:g} Ω is outside cited {limit:g} Ω ({cite_label})."
|
||||
)
|
||||
return _finding(
|
||||
rule_id="PE-AF-002", unit=unit, finding=text,
|
||||
facts=f"nets={label}; speed={speed}; Z={measured:g} Ω; limit={limit:g} Ω.",
|
||||
requirement=req, rec=rec, status="ERROR", cls="RULE",
|
||||
evidence="SUFFICIENT", provenance="MANDATORY",
|
||||
calculation=f"pair Z {measured:g} Ω compared to {limit:g} Ω.",
|
||||
)
|
||||
|
||||
|
||||
def check_af_traces(
|
||||
graph: DesignGraph,
|
||||
constraints_map: dict,
|
||||
@@ -50,7 +246,18 @@ def check_af_traces(
|
||||
if f.rule_id == "PE-SI-002" and f.net
|
||||
}
|
||||
zrows = _z_rows(impedance_nets)
|
||||
for unit in iter_af_units(layout, graph):
|
||||
rmii_nets: list[str] = []
|
||||
for unit in _coalesce_eth_pairs(list(iter_af_units(layout, graph))):
|
||||
if any(single_ended_eth_mac(n) or phy_mac_kind(n) == "rmii" for n in unit.nets):
|
||||
if not any(_is_eth_mdi_net(n) for n in unit.nets):
|
||||
rmii_nets.extend(unit.nets)
|
||||
continue
|
||||
if unit.bus == "eth_mdi":
|
||||
if any(single_ended_eth_mac(n) for n in unit.nets):
|
||||
rmii_nets.extend(unit.nets)
|
||||
continue
|
||||
out.append(_ethernet_mdi_finding(graph, layout, unit))
|
||||
continue
|
||||
trig = evaluate_trigger(graph, constraints_map, layout, unit)
|
||||
if trig.missing and not trig.af:
|
||||
out.append(_skip(unit, trig.missing))
|
||||
@@ -58,10 +265,65 @@ def check_af_traces(
|
||||
if not trig.af:
|
||||
continue
|
||||
out.extend(_analyze_triggered(graph, constraints_map, layout, trig, zrows, seen_si_z))
|
||||
if rmii_nets:
|
||||
out.append(_rmii_cert_finding(graph, rmii_nets))
|
||||
complete_findings(out)
|
||||
return out
|
||||
|
||||
|
||||
def _rmii_cert_finding(graph: DesignGraph, nets: list[str]) -> Finding:
|
||||
"""One line: PHY–MAC is RMII/MII, not RJ45 100 Ω. No invented ohm."""
|
||||
uniq = sorted({n for n in nets if n})
|
||||
label = " / ".join(uniq[:6]) + (" / …" if len(uniq) > 6 else "")
|
||||
kinds = {phy_mac_kind(n) or "rmii" for n in uniq}
|
||||
if kinds == {"mii"}:
|
||||
iface = "MII"
|
||||
elif "rgmii" in kinds and "rmii" not in kinds:
|
||||
iface = "RGMII"
|
||||
else:
|
||||
iface = "RMII"
|
||||
phy_refs = sorted({
|
||||
ref
|
||||
for net in uniq
|
||||
for ref in refs_on_matched_net(graph, net)
|
||||
if (graph.components.get(ref) or None) is not None
|
||||
and "LAN8720" in (
|
||||
(graph.components[ref].mpn or "") + (graph.components[ref].value or "")
|
||||
).upper()
|
||||
})
|
||||
host = phy_refs[0] if phy_refs else "layout"
|
||||
text = (
|
||||
f"{iface} certified — {label} identified as single-ended {iface} PHY–MAC "
|
||||
"(not an RJ45/MDI 100 Ω differential pair). No invented ohm."
|
||||
)
|
||||
rec = (
|
||||
f"Keep {iface} as single-ended PHY–MAC. Do not apply the MDI 100 Ω pair cite."
|
||||
)
|
||||
return Finding(
|
||||
designator=host,
|
||||
mpn="",
|
||||
aspect="si",
|
||||
finding=text,
|
||||
facts=f"nets={label}; interface={iface}; phy={','.join(phy_refs) or '—'}.",
|
||||
requirement=(
|
||||
f"{iface} data/enable nets are single-ended MAC–PHY. "
|
||||
"They are not certified against the RJ45/MDI 100 Ω clause."
|
||||
),
|
||||
inference="Interface class from net names and PHY on the nets. No Z invented.",
|
||||
why=text,
|
||||
status="INFO",
|
||||
recommendation=rec,
|
||||
action=rec,
|
||||
source=SOURCE,
|
||||
rule_id="PE-AF-003",
|
||||
finding_class="INFO",
|
||||
provenance="TYPICAL",
|
||||
evidence_status="SUFFICIENT",
|
||||
net=uniq[0] if uniq else None,
|
||||
pins=[],
|
||||
)
|
||||
|
||||
|
||||
def _z_rows(impedance_nets: list[dict] | dict | None) -> list[dict]:
|
||||
raw = impedance_nets
|
||||
if isinstance(impedance_nets, dict):
|
||||
@@ -75,12 +337,15 @@ def _label(unit: AfUnit) -> str:
|
||||
|
||||
def _skip(unit: AfUnit, missing: tuple[str, ...], extra: str = "") -> Finding:
|
||||
miss = ", ".join(missing)
|
||||
text = f"Pista ad alta frequenza non controllata per mancanza di {miss}."
|
||||
text = (
|
||||
f"HF not certified — because {miss} is missing on {_label(unit)}. "
|
||||
"No invented ohm."
|
||||
)
|
||||
if extra:
|
||||
text = f"{text} {extra}".strip()
|
||||
rec = (
|
||||
f"Fornire {miss} dal datasheet o dallo stackup KiCad. "
|
||||
"Non si assume 50 Ω o 90 Ω."
|
||||
f"Provide {miss} from the datasheet or KiCad stackup. "
|
||||
"50 Ω or 90 Ω is not assumed."
|
||||
)
|
||||
return Finding(
|
||||
designator="layout",
|
||||
@@ -116,7 +381,9 @@ def _finding(
|
||||
cls: str = "RISK",
|
||||
evidence: str = "SUFFICIENT",
|
||||
calculation: str = "",
|
||||
provenance: str = "",
|
||||
) -> Finding:
|
||||
prov = provenance or ("RECOMMENDED" if cls != "REVIEW" else "TYPICAL")
|
||||
return Finding(
|
||||
designator="layout",
|
||||
mpn="",
|
||||
@@ -132,7 +399,7 @@ def _finding(
|
||||
source=SOURCE,
|
||||
rule_id=rule_id,
|
||||
finding_class=cls, # type: ignore[arg-type]
|
||||
provenance="RECOMMENDED" if cls != "REVIEW" else "TYPICAL",
|
||||
provenance=prov,
|
||||
evidence_status=evidence, # type: ignore[arg-type]
|
||||
net=unit.nets[0],
|
||||
pins=[],
|
||||
|
||||
@@ -52,7 +52,8 @@ _MODULE_FP = re.compile(
|
||||
re.I,
|
||||
)
|
||||
_EP_PAD = re.compile(
|
||||
r"^(?:EP|EXP|EPAD|PAD|TAB|TH|THERMAL|DIEPAD|THERMAL[\s_]?PAD)(?:[_-]?\d+)?$",
|
||||
r"^(?:EP|EXP|EPAD|PAD|TAB|TH|THERMAL|DIEPAD|"
|
||||
r"THERMAL[\s_]?PAD|EXPOSED[\s_]?PAD)(?:[_-]?\d+)?$",
|
||||
re.I,
|
||||
)
|
||||
_EP_SPLIT = re.compile(r"^\d+_\d+$")
|
||||
@@ -112,6 +113,45 @@ def _is_ep_land(number: str, pinfunction: str = "", pin_count: int | None = None
|
||||
return False
|
||||
|
||||
|
||||
def _is_exposed_alias(name: str) -> bool:
|
||||
"""EP, EPAD, THERMAL PAD, exposed pad. Not a signal pin number."""
|
||||
s = str(name or "").strip()
|
||||
if not s:
|
||||
return False
|
||||
if _EP_PAD.match(s):
|
||||
return True
|
||||
compact = re.sub(r"[\s_\-]+", "", s).lower()
|
||||
return compact in {"thermalpad", "exposedpad", "epad", "thermal"}
|
||||
|
||||
|
||||
def _ids_have_exposed(
|
||||
ids: list[tuple[str, str]] | None,
|
||||
pin_count: int | None,
|
||||
) -> bool:
|
||||
if not ids:
|
||||
return False
|
||||
return any(_is_ep_land(n, pf, pin_count) for n, pf in ids)
|
||||
|
||||
|
||||
def _drop_exposed_name_mismatch(
|
||||
miss: list[str],
|
||||
extra: list[str],
|
||||
*,
|
||||
left_has: bool,
|
||||
right_has: bool,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Same exposed pad under two names is not a missing/extra pin.
|
||||
|
||||
Datasheet EP with no exposed land on the other side stays a miss.
|
||||
"""
|
||||
if not (left_has and right_has):
|
||||
return miss, extra
|
||||
return (
|
||||
[m for m in miss if not _is_exposed_alias(m)],
|
||||
[e for e in extra if not _is_exposed_alias(e)],
|
||||
)
|
||||
|
||||
|
||||
def _is_shield_land(number: str, pinfunction: str = "") -> bool:
|
||||
s = str(number).strip()
|
||||
pf = str(pinfunction or "").strip()
|
||||
@@ -273,6 +313,16 @@ def resolve_kicad_mod(
|
||||
return None
|
||||
|
||||
|
||||
def _lib_pad_ids(
|
||||
footprint: str,
|
||||
search_dirs: list[Path] | None,
|
||||
) -> list[tuple[str, str]] | None:
|
||||
path = resolve_kicad_mod(footprint, search_dirs)
|
||||
if path is None:
|
||||
return None
|
||||
return parse_kicad_mod_pads(path)
|
||||
|
||||
|
||||
def _lib_join_keys(
|
||||
footprint: str,
|
||||
*,
|
||||
@@ -489,6 +539,10 @@ def _pinout_findings(
|
||||
declared = _declared_io_pins(pkg, cad)
|
||||
ep_count = declared or pin_count
|
||||
pcb = _join_keys_from_ids(pcb_ids, pin_count=ep_count, ds_keys=ds)
|
||||
pcb_has_ep = _ids_have_exposed(pcb_ids, ep_count)
|
||||
ds_has_ep = any(_is_exposed_alias(k) for k in ds)
|
||||
lib_raw = _lib_pad_ids(fp_name, footprint_dirs)
|
||||
lib_has_ep = _ids_have_exposed(lib_raw, ep_count)
|
||||
lib, lib_path = _lib_join_keys(
|
||||
fp_name, pin_count=ep_count, ds_keys=ds, search_dirs=footprint_dirs,
|
||||
)
|
||||
@@ -522,8 +576,10 @@ def _pinout_findings(
|
||||
)
|
||||
|
||||
if lib is not None:
|
||||
miss_lib = sorted(ds - lib)
|
||||
extra_lib = sorted(lib - ds)
|
||||
miss_lib, extra_lib = _drop_exposed_name_mismatch(
|
||||
sorted(ds - lib), sorted(lib - ds),
|
||||
left_has=ds_has_ep, right_has=lib_has_ep,
|
||||
)
|
||||
if miss_lib or extra_lib:
|
||||
rec = (
|
||||
f"Change {ref}'s KiCad footprint library so pad names match "
|
||||
@@ -547,8 +603,11 @@ def _pinout_findings(
|
||||
)
|
||||
if fnd:
|
||||
out.append(fnd)
|
||||
miss_emb = sorted(lib - pcb) if pcb else sorted(lib)
|
||||
extra_emb = sorted(pcb - lib) if pcb else []
|
||||
miss_emb, extra_emb = _drop_exposed_name_mismatch(
|
||||
sorted(lib - pcb) if pcb else sorted(lib),
|
||||
sorted(pcb - lib) if pcb else [],
|
||||
left_has=lib_has_ep, right_has=pcb_has_ep,
|
||||
)
|
||||
if pcb and (miss_emb or extra_emb):
|
||||
rec = (
|
||||
f"Replace {ref}'s embedded PCB footprint so it matches the "
|
||||
@@ -571,8 +630,10 @@ def _pinout_findings(
|
||||
out.append(fnd)
|
||||
return out
|
||||
if pcb:
|
||||
miss = sorted(ds - pcb)
|
||||
extra = sorted(pcb - ds)
|
||||
miss, extra = _drop_exposed_name_mismatch(
|
||||
sorted(ds - pcb), sorted(pcb - ds),
|
||||
left_has=ds_has_ep, right_has=pcb_has_ep,
|
||||
)
|
||||
if miss or extra:
|
||||
rec = (
|
||||
f"Fix {ref} pinout: PCB pad names vs datasheet pintable. "
|
||||
|
||||
@@ -27,7 +27,14 @@ _NC_NET_RE = re.compile(
|
||||
re.I,
|
||||
)
|
||||
_ONBOARD_POWER_RE = re.compile(
|
||||
r"^(?:GND|AGND|DGND|PGND|GNDA|VSYS|3V3|\+3V3|3\.3V)$",
|
||||
r"^(?:GND|AGND|DGND|PGND|GNDA|VSYS|VCC\d*|VDD\d*|3V3|\+3V3|3\.3V)"
|
||||
r"(?:[_./-].*)?$",
|
||||
re.I,
|
||||
)
|
||||
_VBUS_LEAF_RE = re.compile(r"(?:^|[_./-])VBUS(?:$|[_./-])", re.I)
|
||||
_SPDIF_RE = re.compile(r"SP(?:DIF|IF)", re.I)
|
||||
_OPTICAL_RE = re.compile(
|
||||
r"TOSLINK|OPTOCOUPL|OPTICAL|OPTODEVICE|\bAFBR\b|PHOTO[-_ ]?COUPL",
|
||||
re.I,
|
||||
)
|
||||
|
||||
@@ -57,6 +64,50 @@ def _skip_esd_net(net: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _optical_evidence(graph: DesignGraph, comp) -> bool:
|
||||
"""Schematic/BOM/footprint shows TOSLINK, optocoupler, or optical."""
|
||||
parts = [
|
||||
comp.value or "",
|
||||
comp.footprint or "",
|
||||
comp.mpn or "",
|
||||
comp.component_subtype or "",
|
||||
]
|
||||
row = (graph.bom_fields or {}).get(comp.reference) or {}
|
||||
for key in ("description", "Description", "value", "Value", "footprint", "Footprint"):
|
||||
if row.get(key):
|
||||
parts.append(str(row.get(key)))
|
||||
return bool(_OPTICAL_RE.search(" ".join(parts)))
|
||||
|
||||
|
||||
def _esd_cite(cons, *, need_vbus: bool) -> str | None:
|
||||
"""Part + section/page quote. None when the datasheet is not cited."""
|
||||
if cons is None:
|
||||
return None
|
||||
for rule in cons.layout_rules or []:
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
blob = " ".join(
|
||||
str(rule.get(k) or "")
|
||||
for k in ("kind", "parameter", "note", "net", "pin", "requirement")
|
||||
)
|
||||
if "esd" not in blob.lower():
|
||||
continue
|
||||
if need_vbus and not re.search(r"vbus", blob, re.I):
|
||||
continue
|
||||
doc = str(
|
||||
rule.get("document") or rule.get("part") or rule.get("source") or ""
|
||||
).strip()
|
||||
section = str(rule.get("section") or "").strip()
|
||||
page = str(rule.get("page") or "").strip()
|
||||
if not doc or not (section or page):
|
||||
continue
|
||||
loc = section
|
||||
if page:
|
||||
loc = f"{loc} p.{page}".strip()
|
||||
return f"{doc} {loc}".strip()
|
||||
return None
|
||||
|
||||
|
||||
def _is_j_connector(comp) -> bool:
|
||||
if comp.component_type != ComponentType.CONNECTOR:
|
||||
return False
|
||||
@@ -68,7 +119,8 @@ def check_esd(
|
||||
constraints_map: dict[str, ComponentConstraints] | None = None,
|
||||
) -> list[Finding]:
|
||||
"""One REVIEW per J* connector → IC net with no ESD part. No GPIO/NC/rail spam."""
|
||||
_ = constraints_map
|
||||
from backend.periscopex.constraints_lookup import match_constraints
|
||||
|
||||
out: list[Finding] = []
|
||||
seen: set[tuple[str, str, str]] = set()
|
||||
|
||||
@@ -106,28 +158,64 @@ def check_esd(
|
||||
(str(p) for p, n in ic.pins.items() if n and kicad_nets_match(n, net)),
|
||||
"",
|
||||
)
|
||||
leaf = _net_leaf(net)
|
||||
is_vbus = bool(_VBUS_LEAF_RE.search(leaf))
|
||||
is_rail = bool(_ONBOARD_POWER_RE.match(leaf))
|
||||
is_spdif = bool(_SPDIF_RE.search(leaf))
|
||||
optical = _optical_evidence(graph, j_comp)
|
||||
cons = match_constraints(ic.mpn or ic.value, constraints_map or {})
|
||||
quote = _esd_cite(cons, need_vbus=is_vbus)
|
||||
if is_spdif and optical:
|
||||
continue
|
||||
if is_vbus and not quote:
|
||||
continue
|
||||
if is_rail and not quote:
|
||||
continue
|
||||
if is_spdif and not optical:
|
||||
finding = (
|
||||
f"{net} ({j_ref}–{ic_ref}) was not verified as optical "
|
||||
"S/PDIF."
|
||||
)
|
||||
rec = (
|
||||
f"Add a datasheet-specified ESD device on {net} between "
|
||||
f"{j_ref} and {ic_ref}."
|
||||
f"Confirm whether {net} is photo-coupled "
|
||||
"(TOSLINK/optocoupler). The path was not verified as optical."
|
||||
)
|
||||
requirement = (
|
||||
"Optical S/PDIF is not an external copper signal. "
|
||||
"Without TOSLINK/optocoupler evidence the path stays visible."
|
||||
)
|
||||
else:
|
||||
finding = (
|
||||
f"{net} is a {j_ref}–{ic_ref} path with no ESD/"
|
||||
"protection part on the net."
|
||||
)
|
||||
if quote:
|
||||
rec = (
|
||||
f"Add a datasheet-specified ESD device ({quote}) on "
|
||||
f"{net} between {j_ref} and {ic_ref}."
|
||||
)
|
||||
requirement = f"Cited ESD requirement: {quote}."
|
||||
else:
|
||||
rec = (
|
||||
f"Review board ESD on {net} between {j_ref} and {ic_ref}."
|
||||
)
|
||||
requirement = (
|
||||
"Connector–IC nets are reviewed for a board ESD part. "
|
||||
"No datasheet section is cited for this net."
|
||||
)
|
||||
out.append(Finding(
|
||||
designator=ic_ref,
|
||||
mpn=ic.mpn or "",
|
||||
aspect="esd",
|
||||
finding=(
|
||||
f"{net} is a {j_ref}–{ic_ref} path with no ESD/"
|
||||
"protection part on the net."
|
||||
),
|
||||
finding=finding,
|
||||
facts=(
|
||||
f"Net {net}; connector={j_ref}.{j_pin}; IC={ic_ref}; "
|
||||
"ESD parts on net: 0."
|
||||
+ (f" cite={quote}." if quote else " cite=none.")
|
||||
),
|
||||
requirement=(
|
||||
"External ESD is recommended on connector–IC nets unless "
|
||||
"the extraction lists a mandatory clamp with a measured FACT."
|
||||
),
|
||||
requirement=requirement,
|
||||
inference="REVIEW — on-die esd_clamp_pins are not a board RULE.",
|
||||
why="Only J* ∩ IC nets; NC, unconnected, VSYS/GND/3V3 excluded.",
|
||||
why="Only J* ∩ IC nets; NC, unconnected, onboard rails excluded.",
|
||||
status="WARNING",
|
||||
recommendation=rec,
|
||||
action=rec,
|
||||
|
||||
@@ -385,7 +385,7 @@ class ValidationReport(BaseModel):
|
||||
coverage: dict[str, list[str]] = {} # designator -> areas checked and found OK
|
||||
review_errors: dict[str, str] = {} # designator -> error message for ICs whose review raised
|
||||
not_reviewed: list[dict] = [] # [{"designator","reason"}] — ICs skipped (e.g. no datasheet PDF)
|
||||
# M0 protocol cert: empty instances / "nessun protocollo riconosciuto". No Z.
|
||||
# M0 protocol cert: empty instances / "No protocol recognized.". No Z.
|
||||
protocol_certification: dict[str, Any] | None = None
|
||||
|
||||
|
||||
|
||||
@@ -149,6 +149,52 @@ def check_pcb_derating(graph: DesignGraph) -> list[Finding]:
|
||||
return out
|
||||
|
||||
|
||||
def _expand_not_reviewed(rows: list) -> list[dict]:
|
||||
"""One designator per entry. Comma-joined refs become separate rows."""
|
||||
out: list[dict] = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
raw = str(row.get("designator") or "").strip()
|
||||
reason = str(row.get("reason") or "").strip() or "not reviewed"
|
||||
if not raw:
|
||||
continue
|
||||
parts = [p.strip() for p in raw.replace(";", ",").split(",") if p.strip()]
|
||||
if not parts:
|
||||
parts = [raw]
|
||||
for ref in parts:
|
||||
out.append({"designator": ref, "reason": reason})
|
||||
return out
|
||||
|
||||
|
||||
def _merge_not_reviewed(
|
||||
schema_nr: list,
|
||||
pcb_nr: list,
|
||||
covered: set[str],
|
||||
review_errors: dict[str, str] | None = None,
|
||||
) -> list[dict]:
|
||||
"""Dedupe by designator. Drop ICs that were reviewed. Count == list length.
|
||||
|
||||
Legacy ``pcb_review error`` rows move into ``review_errors`` when possible
|
||||
and are not kept as not-reviewed.
|
||||
"""
|
||||
errors = review_errors if review_errors is not None else {}
|
||||
merged: dict[str, str] = {}
|
||||
for row in _expand_not_reviewed(list(schema_nr or []) + list(pcb_nr or [])):
|
||||
ref = row["designator"]
|
||||
if ref in covered:
|
||||
continue
|
||||
reason = row["reason"]
|
||||
if reason == "pcb_review error":
|
||||
errors.setdefault(ref, "pcb_review error")
|
||||
continue
|
||||
prev = merged.get(ref)
|
||||
if prev and prev != "pcb_review error" and reason == "pcb_review error":
|
||||
continue
|
||||
merged[ref] = reason
|
||||
return [{"designator": k, "reason": merged[k]} for k in sorted(merged)]
|
||||
|
||||
|
||||
def merge_schema_pcb_reports(
|
||||
schema: dict | None, pcb: dict | None,
|
||||
) -> dict | None:
|
||||
@@ -189,10 +235,17 @@ def merge_schema_pcb_reports(
|
||||
if st in summary:
|
||||
summary[st] = summary.get(st, 0) + 1
|
||||
out["summary"] = summary
|
||||
covered = set((schema or {}).get("coverage") or {}) | set((pcb or {}).get("coverage") or {})
|
||||
schema_err = dict((schema or {}).get("review_errors") or {})
|
||||
pcb_err = dict((pcb or {}).get("review_errors") or {})
|
||||
merged_err = {**schema_err, **pcb_err}
|
||||
schema_nr = list((schema or {}).get("not_reviewed") or [])
|
||||
pcb_nr = list((pcb or {}).get("not_reviewed") or [])
|
||||
if schema_nr or pcb_nr:
|
||||
out["not_reviewed"] = schema_nr + pcb_nr
|
||||
out["not_reviewed"] = _merge_not_reviewed(schema_nr, pcb_nr, covered, merged_err)
|
||||
if merged_err:
|
||||
out["review_errors"] = merged_err
|
||||
elif "review_errors" in out and not out["review_errors"]:
|
||||
out.pop("review_errors", None)
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ CATALOG_DIR = Path(__file__).resolve().parent / "protocol_data"
|
||||
CATALOG_PATH = CATALOG_DIR / "catalog.json"
|
||||
SCHEMA_PATH = CATALOG_DIR / f"schema-{SCHEMA_VERSION}.json"
|
||||
|
||||
EMPTY_PROTOCOL_MESSAGE = "nessun protocollo riconosciuto"
|
||||
EMPTY_PROTOCOL_MESSAGE = "No protocol recognized."
|
||||
|
||||
BusType = Literal[
|
||||
"MEMORY",
|
||||
@@ -582,9 +582,19 @@ DOC_USB_LSFS = (
|
||||
"Universal Serial Bus Specification Revision 2.0 §7 (field not a single PCB number)"
|
||||
)
|
||||
DOC_USB_PD_VSAFE = (
|
||||
"USB Power Delivery specification vSafe5V (not on file; Type-C CabCon R2.5 names vSafe5V "
|
||||
"and tVBUSON as the minimum vSafe5V threshold without restating the volt range. "
|
||||
"Type-C Current charger 4.75–5.5 V is not vSafe5V)"
|
||||
"USB Power Delivery Specification (USB-IF; not on file). "
|
||||
"USB Type-C Cable and Connector Specification Release 2.5, March 2026 "
|
||||
"§1.6 p.35: vSafe5V is VBUS “5 volts” as defined by the USB PD specification "
|
||||
"(no volt range restated). "
|
||||
"Alta Frequenza zip snla027b.pdf (AN-807 Reflections SNLA027B–May 2004–Revised May 2004) "
|
||||
"and sdaa499.pdf (Simple Methods to Reduce EMI from a PCB Trace, SDAA499 – September 2026) "
|
||||
"do not state vSafe5V. Type-C Current charger Figure 4-39 4.75–5.5 V is not vSafe5V."
|
||||
)
|
||||
DOC_USB_PD_VSAFE0 = (
|
||||
"USB Power Delivery Specification (USB-IF; not on file). "
|
||||
"USB Type-C Cable and Connector Specification Release 2.5, March 2026 "
|
||||
"§1.6 p.35: vSafe0V is VBUS “0 volts” as defined by the USB PD specification "
|
||||
"(no volt range restated). Alta Frequenza TI SI PDFs do not state vSafe0V."
|
||||
)
|
||||
DOC_IEEE_8023 = "IEEE 802.3 (clause for this variant; not on file)"
|
||||
DOC_IEEE_2012 = "IEEE Std 802.3-2012 IEEE Standard for Ethernet"
|
||||
@@ -1173,6 +1183,10 @@ def build_m0_catalog() -> dict[str, Any]:
|
||||
pid, "vsafe5v", "UNKNOWN",
|
||||
needed_document=DOC_USB_PD_VSAFE,
|
||||
))
|
||||
out.append(_c(
|
||||
pid, "vsafe0v", "UNKNOWN",
|
||||
needed_document=DOC_USB_PD_VSAFE0,
|
||||
))
|
||||
return out
|
||||
|
||||
def _eth_cons(pid: str, lid: str) -> list[dict[str, Any]]:
|
||||
@@ -1949,7 +1963,7 @@ def build_m0_catalog() -> dict[str, Any]:
|
||||
hints=["USB_C", "TYPE_C", "CC1", "CC2"],
|
||||
notes=(
|
||||
"USB Type-C connector/interface system. Not USB 2.0/3.x/USB4 protocol. "
|
||||
"Rp/Rd/Ra from CabCon R2.5 Tables 4-27/4-28/4-29. VBUS volts still USB PD vSafe5V."
|
||||
"Rp/Rd/Ra from CabCon R2.5 Tables 4-27/4-28/4-29. Figure 4-39 charger volts are not vSafe5V. USB PD vSafe still not on file."
|
||||
),
|
||||
))
|
||||
usb2_over_c = _usb2_cons("usb-c-usb2-receptacle", speed="hs")
|
||||
|
||||
@@ -2930,10 +2930,25 @@
|
||||
"conditions": [],
|
||||
"value_origin": "SPEC",
|
||||
"typical": false,
|
||||
"needed_document": "USB Power Delivery specification vSafe5V (not on file; Type-C CabCon R2.5 names vSafe5V and tVBUSON as the minimum vSafe5V threshold without restating the volt range. Type-C Current charger 4.75\u20135.5 V is not vSafe5V)"
|
||||
"needed_document": "USB Power Delivery Specification (USB-IF; not on file). USB Type-C Cable and Connector Specification Release 2.5, March 2026 \u00a71.6 p.35: vSafe5V is VBUS \u201c5 volts\u201d as defined by the USB PD specification (no volt range restated). Alta Frequenza zip snla027b.pdf (AN-807 Reflections SNLA027B\u2013May 2004\u2013Revised May 2004) and sdaa499.pdf (Simple Methods to Reduce EMI from a PCB Trace, SDAA499 \u2013 September 2026) do not state vSafe5V. Type-C Current charger Figure 4-39 4.75\u20135.5 V is not vSafe5V."
|
||||
},
|
||||
{
|
||||
"id": "usb-c-receptacle-vsafe0v",
|
||||
"parameter": "vsafe0v",
|
||||
"value_kind": "UNKNOWN",
|
||||
"mandatory": "MANDATORY",
|
||||
"source_type": "STANDARD",
|
||||
"source_class": "NORMATIVE",
|
||||
"value": null,
|
||||
"unit": null,
|
||||
"source": null,
|
||||
"conditions": [],
|
||||
"value_origin": "SPEC",
|
||||
"typical": false,
|
||||
"needed_document": "USB Power Delivery Specification (USB-IF; not on file). USB Type-C Cable and Connector Specification Release 2.5, March 2026 \u00a71.6 p.35: vSafe0V is VBUS \u201c0 volts\u201d as defined by the USB PD specification (no volt range restated). Alta Frequenza TI SI PDFs do not state vSafe0V."
|
||||
}
|
||||
],
|
||||
"notes": "USB Type-C connector/interface system. Not USB 2.0/3.x/USB4 protocol. Rp/Rd/Ra from CabCon R2.5 Tables 4-27/4-28/4-29. VBUS volts still USB PD vSafe5V.",
|
||||
"notes": "USB Type-C connector/interface system. Not USB 2.0/3.x/USB4 protocol. Rp/Rd/Ra from CabCon R2.5 Tables 4-27/4-28/4-29. Figure 4-39 charger volts are not vSafe5V. USB PD vSafe still not on file.",
|
||||
"incomplete": false
|
||||
},
|
||||
{
|
||||
@@ -3902,7 +3917,22 @@
|
||||
"conditions": [],
|
||||
"value_origin": "SPEC",
|
||||
"typical": false,
|
||||
"needed_document": "USB Power Delivery specification vSafe5V (not on file; Type-C CabCon R2.5 names vSafe5V and tVBUSON as the minimum vSafe5V threshold without restating the volt range. Type-C Current charger 4.75\u20135.5 V is not vSafe5V)"
|
||||
"needed_document": "USB Power Delivery Specification (USB-IF; not on file). USB Type-C Cable and Connector Specification Release 2.5, March 2026 \u00a71.6 p.35: vSafe5V is VBUS \u201c5 volts\u201d as defined by the USB PD specification (no volt range restated). Alta Frequenza zip snla027b.pdf (AN-807 Reflections SNLA027B\u2013May 2004\u2013Revised May 2004) and sdaa499.pdf (Simple Methods to Reduce EMI from a PCB Trace, SDAA499 \u2013 September 2026) do not state vSafe5V. Type-C Current charger Figure 4-39 4.75\u20135.5 V is not vSafe5V."
|
||||
},
|
||||
{
|
||||
"id": "usb-c-usb2-receptacle-vsafe0v",
|
||||
"parameter": "vsafe0v",
|
||||
"value_kind": "UNKNOWN",
|
||||
"mandatory": "MANDATORY",
|
||||
"source_type": "STANDARD",
|
||||
"source_class": "NORMATIVE",
|
||||
"value": null,
|
||||
"unit": null,
|
||||
"source": null,
|
||||
"conditions": [],
|
||||
"value_origin": "SPEC",
|
||||
"typical": false,
|
||||
"needed_document": "USB Power Delivery Specification (USB-IF; not on file). USB Type-C Cable and Connector Specification Release 2.5, March 2026 \u00a71.6 p.35: vSafe0V is VBUS \u201c0 volts\u201d as defined by the USB PD specification (no volt range restated). Alta Frequenza TI SI PDFs do not state vSafe0V."
|
||||
},
|
||||
{
|
||||
"id": "usb-c-usb2-receptacle-cc_rd_rp",
|
||||
|
||||
@@ -13,8 +13,18 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.periscopex.finding_engine import complete_finding
|
||||
from backend.periscopex.models import DesignGraph, Finding, LayoutGraph
|
||||
from backend.periscopex.pcb_net_match import normalize_kicad_hierarchy_net
|
||||
from backend.periscopex.models import (
|
||||
Component,
|
||||
ComponentType,
|
||||
DesignGraph,
|
||||
Finding,
|
||||
LayoutGraph,
|
||||
ResistorSpecs,
|
||||
)
|
||||
from backend.periscopex.pcb_net_match import (
|
||||
normalize_kicad_hierarchy_net,
|
||||
refs_on_matched_net,
|
||||
)
|
||||
from backend.periscopex.protocol_catalog import (
|
||||
SCHEMA_VERSION,
|
||||
PhysicalInterface,
|
||||
@@ -47,7 +57,8 @@ L0_CHECKS = frozenset({
|
||||
"superspeed_pairs",
|
||||
})
|
||||
|
||||
_CC_RE = re.compile(r"(?:^|[_/.])CC[12]$", re.I)
|
||||
_OHM_EMBEDDED = re.compile(r"^(\d+)([RKMG])(\d+)$", re.I)
|
||||
_OHM_SUFFIX = re.compile(r"^(\d*\.?\d+)([RKMG])$", re.I)
|
||||
_VBUS_RE = re.compile(r"VBUS|\+?VUSB|USB_VBUS", re.I)
|
||||
_GND_RE = re.compile(r"(?:^|[_/.])(?:GND|VSS|DGND)(?:$|[_/.])", re.I)
|
||||
_SS_RE = re.compile(r"SSTX|SSRX|SS_T[XR]|USB3|USB_SS", re.I)
|
||||
@@ -160,6 +171,156 @@ def certify_instance_l0(
|
||||
return out
|
||||
|
||||
|
||||
def _parse_ohms(raw: str | None) -> float | None:
|
||||
t = (raw or "").strip().upper().replace("OHMS", "").replace("OHM", "")
|
||||
t = t.replace("Ω", "").replace(" ", "")
|
||||
if not t:
|
||||
return None
|
||||
m = _OHM_EMBEDDED.match(t)
|
||||
if m:
|
||||
mult = {"R": 1.0, "K": 1e3, "M": 1e6, "G": 1e9}[m.group(2)]
|
||||
return (float(m.group(1)) + float(f"0.{m.group(3)}")) * mult
|
||||
m = _OHM_SUFFIX.match(t)
|
||||
if m:
|
||||
mult = {"R": 1.0, "K": 1e3, "M": 1e6, "G": 1e9}[m.group(2)]
|
||||
return float(m.group(1)) * mult
|
||||
try:
|
||||
return float(t)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _resistor_ohms(comp: Component) -> float | None:
|
||||
specs = comp.specs
|
||||
if isinstance(specs, ResistorSpecs) and specs.value_ohms > 0:
|
||||
return float(specs.value_ohms)
|
||||
return _parse_ohms(comp.value)
|
||||
|
||||
|
||||
def _rd_cite() -> tuple[float | None, str]:
|
||||
"""CabCon Rd already packed. No other USB number is introduced here."""
|
||||
cat = load_catalog()
|
||||
chosen = None
|
||||
fallback = None
|
||||
for iface in cat.physical_interfaces:
|
||||
if iface.id not in {"usb-c-usb2-receptacle", "usb-c-receptacle"}:
|
||||
continue
|
||||
for c in iface.constraints:
|
||||
if c.parameter == "rd" and c.value is not None:
|
||||
if iface.id == "usb-c-usb2-receptacle":
|
||||
chosen = c
|
||||
elif fallback is None:
|
||||
fallback = c
|
||||
chosen = chosen or fallback
|
||||
if chosen is None or chosen.value is None:
|
||||
return None, "CabCon Rd cite is not in the protocol pack."
|
||||
src = chosen.source
|
||||
bits = []
|
||||
if src and src.document:
|
||||
bits.append(src.document)
|
||||
if src and src.revision:
|
||||
bits.append(src.revision)
|
||||
if src and src.section:
|
||||
bits.append(f"§{src.section}")
|
||||
if src and src.table:
|
||||
bits.append(src.table)
|
||||
if src and src.page:
|
||||
bits.append(f"p.{src.page}")
|
||||
nominal = "nominal 5.1 kΩ" if any(
|
||||
"5.1" in (cond or "") for cond in (chosen.conditions or [])
|
||||
) else f"{chosen.value:g} {chosen.unit or 'ohm'}"
|
||||
cite = ", ".join(bits) if bits else chosen.id
|
||||
return float(chosen.value), f"{cite}; {nominal}"
|
||||
|
||||
|
||||
def _cc_pin_pairs(comp: Component) -> list[tuple[str, str | None]]:
|
||||
"""Receptacle CC pins. A5/B5 are the Type-C CC contacts, not net names."""
|
||||
pins = {str(k).upper(): v for k, v in comp.pins.items()}
|
||||
if "A5" in pins or "B5" in pins:
|
||||
return [("A5", pins.get("A5")), ("B5", pins.get("B5"))]
|
||||
if "CC1" in pins or "CC2" in pins:
|
||||
return [("CC1", pins.get("CC1")), ("CC2", pins.get("CC2"))]
|
||||
return []
|
||||
|
||||
|
||||
def _typec_receptacle(graph: DesignGraph, inst: PhysicalBusInstance) -> Component | None:
|
||||
found: list[Component] = []
|
||||
for comp in graph.components.values():
|
||||
if comp.component_type != ComponentType.CONNECTOR:
|
||||
continue
|
||||
if _cc_pin_pairs(comp):
|
||||
found.append(comp)
|
||||
if not found:
|
||||
return None
|
||||
for comp in found:
|
||||
if comp.reference == inst.host_ref:
|
||||
return comp
|
||||
inst_nets = set(inst.nets)
|
||||
for g in inst.groups:
|
||||
inst_nets.update(g.nets)
|
||||
for comp in found:
|
||||
if inst_nets.intersection(v for v in comp.pins.values() if v):
|
||||
return comp
|
||||
return found[0]
|
||||
|
||||
|
||||
def _rd_refs_on_net(graph: DesignGraph, net: str, nominal: float) -> list[str]:
|
||||
"""Resistors on this net whose value is the packed Rd (float slack 1 Ω)."""
|
||||
hits: list[str] = []
|
||||
for ref in refs_on_matched_net(graph, net):
|
||||
comp = graph.components.get(ref)
|
||||
if comp is None or comp.component_type != ComponentType.RESISTOR:
|
||||
continue
|
||||
ohms = _resistor_ohms(comp)
|
||||
if ohms is not None and abs(ohms - nominal) <= 1.0:
|
||||
hits.append(ref)
|
||||
return hits
|
||||
|
||||
|
||||
def _cc_rd_on_pins(
|
||||
graph: DesignGraph,
|
||||
inst: PhysicalBusInstance,
|
||||
mand: MandatoryClass,
|
||||
) -> L0CheckResult:
|
||||
"""Pin → net → Rd. The net does not have to be named CC1/CC2."""
|
||||
nominal, cite = _rd_cite()
|
||||
jack = _typec_receptacle(graph, inst)
|
||||
if jack is None or nominal is None:
|
||||
return _pack(
|
||||
"cc_rd_rp", "FAIL", mand,
|
||||
notes=(
|
||||
"Type-C CC pins were not followed to an Rd. "
|
||||
f"{cite}"
|
||||
),
|
||||
)
|
||||
pairs = _cc_pin_pairs(jack)
|
||||
nets: list[str] = []
|
||||
missing: list[str] = []
|
||||
present: list[str] = []
|
||||
for pin, net in pairs:
|
||||
if not net:
|
||||
missing.append(f"{jack.reference}.{pin} has no net")
|
||||
continue
|
||||
nets.append(net)
|
||||
refs = _rd_refs_on_net(graph, net, nominal)
|
||||
if refs:
|
||||
present.append(f"{jack.reference}.{pin} net {net} Rd {', '.join(refs)}")
|
||||
else:
|
||||
missing.append(
|
||||
f"{jack.reference}.{pin} net {net} has no {nominal:g} Ω Rd"
|
||||
)
|
||||
if missing or len(present) < 2:
|
||||
detail = "; ".join(missing) if missing else "both CC pins need an Rd"
|
||||
return _pack(
|
||||
"cc_rd_rp", "FAIL", mand, nets=nets,
|
||||
notes=f"{detail}. {cite}. Net name is not required.",
|
||||
)
|
||||
return _pack(
|
||||
"cc_rd_rp", "PASS", mand, nets=nets,
|
||||
notes=f"{'; '.join(present)}. {cite}.",
|
||||
)
|
||||
|
||||
|
||||
def _run_l0_check(
|
||||
graph: DesignGraph,
|
||||
inst: PhysicalBusInstance,
|
||||
@@ -212,11 +373,7 @@ def _run_l0_check(
|
||||
ok, msg = _structural_nets_ok(graph, clocks)
|
||||
return _pack(check, "PASS" if ok else "FAIL", mand, nets=clocks, notes=msg)
|
||||
if check == "cc_rd_rp":
|
||||
ccs = [n for n in graph.nets if _CC_RE.search(_leaf(n))]
|
||||
if len(ccs) < 1:
|
||||
return _pack(check, "FAIL", mand, notes="CC1/CC2 net not present.")
|
||||
ok, msg = _structural_nets_ok(graph, ccs)
|
||||
return _pack(check, "PASS" if ok else "FAIL", mand, nets=ccs, notes=msg)
|
||||
return _cc_rd_on_pins(graph, inst, mand)
|
||||
if check == "vbus_gnd":
|
||||
vbus = [n for n in graph.nets if _VBUS_RE.search(_leaf(n))]
|
||||
gnd = [n for n in graph.nets if _GND_RE.search(_leaf(n))]
|
||||
|
||||
@@ -4,7 +4,9 @@ Skew is compared only when the constraint is NUMERIC (length unit) or an
|
||||
explicit DESIGN LIMIT. Otherwise UNKNOWN / CONTROLLER_DEPENDENT /
|
||||
PHY_DEPENDENT / VENDOR_DEPENDENT. Length is not delay. Not electrical.
|
||||
RECOMMENDED never FAIL. Internal interfaces are NOT_APPLICABLE.
|
||||
Missing DQ/DQS grouping or missing PCB geometry is a visible skip, not PASS.
|
||||
Missing DQ/DQS grouping is a visible skip, not PASS. A geometric check
|
||||
with no NUMERIC or DESIGN millimetre limit does not warn: the standard
|
||||
did not set a mm limit, and one is not invented.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -497,11 +499,14 @@ def l1_findings(inst: PhysicalBusInstance, results: list[L1CheckResult]) -> list
|
||||
finding = f"L1 geometric {r.check}: {r.notes}"
|
||||
elif skip_family:
|
||||
grouping = "grouping" in (r.notes or "").lower() or "dq/dqs" in (r.notes or "").lower()
|
||||
if not grouping and r.limit_mm is None:
|
||||
# No NUMERIC/DESIGN millimetre limit in the pack. Silence.
|
||||
continue
|
||||
rule_id = "PE-PRT-L1-002" if grouping else "PE-PRT-L1-001"
|
||||
status = "WARNING"
|
||||
finding = r.notes or (
|
||||
f"Interfaccia {inst.physical_interface_id} non certificata a L1 "
|
||||
f"per {r.check} ({r.result}). Not electrical."
|
||||
f"{inst.physical_interface_id} L1 {r.check} is {r.result}. "
|
||||
"Geometric only, not electrical."
|
||||
)
|
||||
else:
|
||||
rule_id = "PE-PRT-L0-002"
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
"""M4: L2 ELECTRICAL protocol certifier. Z, termination, levels, rise/fall.
|
||||
|
||||
Z only from datasheet / stackup / fabricator / cited pack — never invented
|
||||
90 Ω USB. USB-IF/IEEE numbers only if the pack has a cite. Silicon cross is
|
||||
max PCB × PHY subset when datasheet windows exist. Length is not delay.
|
||||
Not L3 / OpenEMS. L0/L1 are not electrical certification.
|
||||
RECOMMENDED never FAIL. MISSING_SOURCE / UNKNOWN when cite is absent.
|
||||
Visible skip (PE-AF-002 style) when Z cannot be obtained.
|
||||
Z only from datasheet / stackup / fabricator / cited pack. USB 2.0 HS
|
||||
D+/D− pair Z is compared to the packed ``pcb_trace_nominal_zdiff``
|
||||
(RECOMMENDED). That number is not invented here and is not a MANDATORY
|
||||
FAIL. Silicon cross is max PCB × PHY subset when datasheet windows exist.
|
||||
A missing field (termination cite, rise/fall, return path, voltage) does
|
||||
not emit a warning. Length is not delay. Not L3 / OpenEMS.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.periscopex.constraints_lookup import match_constraints
|
||||
from backend.periscopex.finding_engine import complete_finding
|
||||
from backend.periscopex.impedance import GeometryError, TraceGeometry, coupled_diff_z
|
||||
from backend.periscopex.models import (
|
||||
ComponentConstraints,
|
||||
ComponentType,
|
||||
@@ -23,7 +25,6 @@ from backend.periscopex.models import (
|
||||
Finding,
|
||||
LayoutGraph,
|
||||
)
|
||||
from backend.periscopex.pcb_net_match import kicad_nets_match
|
||||
from backend.periscopex.protocol_catalog import (
|
||||
PhysicalInterface,
|
||||
ProtocolCatalog,
|
||||
@@ -31,8 +32,10 @@ from backend.periscopex.protocol_catalog import (
|
||||
load_catalog,
|
||||
map_protocol_outcome,
|
||||
)
|
||||
from backend.periscopex.pcb_net_match import kicad_nets_match
|
||||
from backend.periscopex.protocol_l0 import _constraint_for, _mandatory
|
||||
from backend.periscopex.protocol_recognize import PhysicalBusInstance
|
||||
from backend.periscopex.si_check import single_ended_eth_mac
|
||||
|
||||
PACK_MACROPHASE = "M4"
|
||||
SOURCE = "protocol_l2"
|
||||
@@ -81,6 +84,8 @@ class L2CheckResult(BaseModel):
|
||||
notes: str = ""
|
||||
finding_class: str = ""
|
||||
status: str = ""
|
||||
# "" legacy, "silent" no finding, "warn" one WARNING, "error" one ERROR.
|
||||
emit: str = ""
|
||||
|
||||
|
||||
def _pack(
|
||||
@@ -95,6 +100,7 @@ def _pack(
|
||||
limit_ohm_max: float | None = None,
|
||||
value_kind: str = "",
|
||||
notes: str = "",
|
||||
emit: str = "",
|
||||
) -> L2CheckResult:
|
||||
if result == "FAIL" and mandatory != "MANDATORY":
|
||||
result = "WARNING"
|
||||
@@ -120,6 +126,7 @@ def _pack(
|
||||
notes=notes,
|
||||
finding_class=cls,
|
||||
status=status,
|
||||
emit=emit,
|
||||
)
|
||||
|
||||
|
||||
@@ -286,6 +293,24 @@ def _pack_ohm_window(cons: ProtocolConstraint | None) -> tuple[float, float] | N
|
||||
return None
|
||||
|
||||
|
||||
_NOISE_CHECKS = frozenset({
|
||||
"differential_impedance",
|
||||
"impedance",
|
||||
"impedance_if_required",
|
||||
"termination",
|
||||
"cc_termination",
|
||||
"voltage",
|
||||
"levels",
|
||||
"rise_time",
|
||||
"fall_time",
|
||||
"timing",
|
||||
"return_path",
|
||||
"magnetics",
|
||||
"phy_requirements",
|
||||
"ac_coupling",
|
||||
})
|
||||
|
||||
|
||||
def _skip_z(check: str, mand: MandatoryClass, inst: PhysicalBusInstance, kind: str) -> L2CheckResult:
|
||||
return _pack(
|
||||
check, "UNKNOWN" if kind not in {
|
||||
@@ -294,10 +319,10 @@ def _skip_z(check: str, mand: MandatoryClass, inst: PhysicalBusInstance, kind: s
|
||||
} else kind,
|
||||
mand,
|
||||
value_kind=kind,
|
||||
emit="silent",
|
||||
notes=(
|
||||
f"Interfaccia {inst.physical_interface_id} non certificata a L2 "
|
||||
f"per mancanza di Z (datasheet/stackup/fab/cited pack). "
|
||||
f"Not USB/IEC folklore. L0/L1 are not electrical certification."
|
||||
f"{inst.physical_interface_id} has no cited Z window "
|
||||
"(datasheet, stackup, fabricator, or pack). Not a warning."
|
||||
),
|
||||
)
|
||||
|
||||
@@ -349,8 +374,8 @@ def _run_l2_check(
|
||||
"differential_impedance", "impedance", "impedance_if_required",
|
||||
}:
|
||||
return _z_check(
|
||||
check, mand, cons, kind, inst, graph, nets,
|
||||
constraints_map, impedance_nets,
|
||||
check, mand, cons, kind, inst, iface, graph, nets,
|
||||
constraints_map, impedance_nets, layout,
|
||||
)
|
||||
|
||||
if check in {"termination", "cc_termination"}:
|
||||
@@ -362,10 +387,10 @@ def _run_l2_check(
|
||||
if check in {"rise_time", "fall_time", "timing"}:
|
||||
return _pack(
|
||||
check, "UNKNOWN" if kind in {"NUMERIC", "UNKNOWN", ""} else kind, mand,
|
||||
nets=nets, value_kind=kind,
|
||||
nets=nets, value_kind=kind, emit="silent",
|
||||
notes=(
|
||||
"Length is not delay. Rise/fall/timing UNKNOWN without a cited "
|
||||
"time source (no tpd invented from mm). Not L3."
|
||||
"Length is not delay. Rise/fall/timing stays UNKNOWN without a cited "
|
||||
"time source (no tpd invented from mm). Not L3. Not a warning."
|
||||
),
|
||||
)
|
||||
|
||||
@@ -374,27 +399,234 @@ def _run_l2_check(
|
||||
if verdict == "NUMERIC":
|
||||
verdict = "UNKNOWN"
|
||||
return _pack(
|
||||
check, verdict, mand, nets=nets, value_kind=kind,
|
||||
check, verdict, mand, nets=nets, value_kind=kind, emit="silent",
|
||||
notes=(
|
||||
f"{check} not certified without a cited electrical source. "
|
||||
f"Not invented. L0/L1 are not electrical certification."
|
||||
f"{check} has no cited electrical source. "
|
||||
"Not invented. Not a warning."
|
||||
),
|
||||
)
|
||||
return _pack(check, "UNKNOWN", mand, value_kind=kind, notes="Not an L2 electrical check.")
|
||||
|
||||
|
||||
def _pcb_zdiff_cite(iface: PhysicalInterface) -> ProtocolConstraint | None:
|
||||
"""Packed board Zdiff recommendation. Never a number typed in this module."""
|
||||
for c in iface.constraints:
|
||||
if c.parameter != "pcb_trace_nominal_zdiff":
|
||||
continue
|
||||
if c.value_kind != "NUMERIC" or c.value is None:
|
||||
continue
|
||||
unit = (c.unit or "").strip().lower()
|
||||
if unit not in _OHM_UNITS:
|
||||
continue
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def _usb_dp_dm(inst: PhysicalBusInstance) -> tuple[str, str] | None:
|
||||
for g in inst.groups:
|
||||
if g.kind != "DIFFERENTIAL_PAIR" or len(g.nets) < 2:
|
||||
continue
|
||||
dp = g.roles.get("D+") or g.nets[0]
|
||||
dm = g.roles.get("D-") or g.nets[1]
|
||||
if single_ended_eth_mac(dp) or single_ended_eth_mac(dm):
|
||||
return None
|
||||
return dp, dm
|
||||
return None
|
||||
|
||||
|
||||
def _cite_label(cons: ProtocolConstraint) -> str:
|
||||
src = cons.source
|
||||
bits: list[str] = []
|
||||
if src is not None:
|
||||
if src.document:
|
||||
bits.append(src.document)
|
||||
if src.section:
|
||||
bits.append(f"§{src.section}")
|
||||
if src.page:
|
||||
bits.append(f"p.{src.page}")
|
||||
return ", ".join(bits) if bits else "cited pack"
|
||||
|
||||
|
||||
def _zdiff_measured(nets: list[str], impedance_nets: list[dict] | dict | None) -> float | None:
|
||||
"""Pair Z only. Single-ended Z0 is not a differential result."""
|
||||
rows = _z_rows(impedance_nets)
|
||||
vals: list[float] = []
|
||||
for net in nets:
|
||||
row = _row_for(rows, net)
|
||||
if not row:
|
||||
continue
|
||||
for key in ("zdiff_ohm", "zdiff_avg_ohms", "zdiff_ohms"):
|
||||
v = _num(row.get(key))
|
||||
if v is not None and v > 0:
|
||||
vals.append(v)
|
||||
break
|
||||
if not vals:
|
||||
return None
|
||||
return sum(vals) / len(vals)
|
||||
|
||||
|
||||
def _median_width_mm(layout: LayoutGraph, net: str) -> float | None:
|
||||
widths = sorted(
|
||||
s.width for s in layout.segments
|
||||
if s.net and kicad_nets_match(s.net, net) and s.width > 0
|
||||
)
|
||||
if not widths:
|
||||
return None
|
||||
return widths[len(widths) // 2]
|
||||
|
||||
|
||||
def _pair_gap_mm(layout: LayoutGraph, a: str, b: str) -> float | None:
|
||||
sa = [s for s in layout.segments if s.net and kicad_nets_match(s.net, a) and s.width > 0]
|
||||
sb = [s for s in layout.segments if s.net and kicad_nets_match(s.net, b) and s.width > 0]
|
||||
gaps: list[float] = []
|
||||
for x in sa:
|
||||
for y in sb:
|
||||
if x.layer and y.layer and x.layer != y.layer:
|
||||
continue
|
||||
for px, py in (
|
||||
(x.start, y.start), (x.start, y.end),
|
||||
(x.end, y.start), (x.end, y.end),
|
||||
):
|
||||
edge = math.hypot(px[0] - py[0], px[1] - py[1]) - x.width / 2.0 - y.width / 2.0
|
||||
if edge > 1e-6:
|
||||
gaps.append(edge)
|
||||
if not gaps:
|
||||
return None
|
||||
return min(gaps)
|
||||
|
||||
|
||||
def usb_pair_z_ohm(
|
||||
layout: LayoutGraph | None,
|
||||
nets: tuple[str, str],
|
||||
impedance_nets: list[dict] | dict | None,
|
||||
) -> tuple[float | None, str]:
|
||||
"""Calculated differential Z for one pair.
|
||||
|
||||
Returns (ohms, missing). missing is empty when ohms is set, otherwise
|
||||
``stackup``, ``geometry``, or ``stackup/geometry``.
|
||||
"""
|
||||
stored = _zdiff_measured(list(nets), impedance_nets)
|
||||
if stored is not None:
|
||||
return stored, ""
|
||||
has_copper = bool(
|
||||
layout is not None and any(
|
||||
s.net and s.width > 0 and (
|
||||
kicad_nets_match(s.net, nets[0]) or kicad_nets_match(s.net, nets[1])
|
||||
)
|
||||
for s in layout.segments
|
||||
)
|
||||
)
|
||||
stack = layout.stackup if layout is not None else None
|
||||
dielectric = stack.dielectrics[0] if stack and stack.dielectrics else None
|
||||
stack_ok = (
|
||||
stack is not None
|
||||
and dielectric is not None
|
||||
and dielectric.er > 0
|
||||
and dielectric.height_mm > 0
|
||||
and stack.copper_thickness_mm is not None
|
||||
and stack.copper_thickness_mm > 0
|
||||
)
|
||||
if not stack_ok:
|
||||
return None, "stackup/geometry" if not has_copper else "stackup"
|
||||
assert layout is not None and stack is not None and dielectric is not None
|
||||
wa = _median_width_mm(layout, nets[0])
|
||||
wb = _median_width_mm(layout, nets[1])
|
||||
gap = _pair_gap_mm(layout, nets[0], nets[1])
|
||||
if wa is None or wb is None or gap is None:
|
||||
return None, "geometry"
|
||||
try:
|
||||
_zodd, _zeven, zdiff = coupled_diff_z(TraceGeometry(
|
||||
h=dielectric.height_mm,
|
||||
er=dielectric.er,
|
||||
t=stack.copper_thickness_mm,
|
||||
w=(wa + wb) / 2.0,
|
||||
s=gap,
|
||||
))
|
||||
except GeometryError:
|
||||
return None, "geometry"
|
||||
if zdiff <= 0:
|
||||
return None, "geometry"
|
||||
return zdiff, ""
|
||||
|
||||
|
||||
def _matches_cited(measured: float, cited: float) -> bool:
|
||||
return abs(measured - cited) <= 1e-6 * max(1.0, abs(cited))
|
||||
|
||||
|
||||
def _usb_line(kind: str, *, measured: float | None, cited: float, label: str) -> str:
|
||||
"""One report line. The ohm value is the packed cite, not a second number."""
|
||||
if kind == "certified" and measured is not None:
|
||||
return (
|
||||
f"USB certified — calculated Z {measured:g} Ω vs cited {cited:g} Ω ({label})."
|
||||
)
|
||||
if measured is not None:
|
||||
return (
|
||||
f"USB not certified — because Z {measured:g} Ω is outside cited "
|
||||
f"{cited:g} Ω ({label})."
|
||||
)
|
||||
return (
|
||||
"USB not certified — because Z cannot be calculated from the PCB "
|
||||
f"stackup/geometry. Cited {cited:g} Ω ({label})."
|
||||
)
|
||||
|
||||
|
||||
def _usb_board_z(
|
||||
check: str,
|
||||
inst: PhysicalBusInstance,
|
||||
cite: ProtocolConstraint,
|
||||
pair: tuple[str, str],
|
||||
layout: LayoutGraph | None,
|
||||
impedance_nets: list[dict] | dict | None,
|
||||
) -> L2CheckResult:
|
||||
"""One line: calculated pair Z vs the packed board cite."""
|
||||
cited = float(cite.value) # type: ignore[arg-type]
|
||||
label = _cite_label(cite)
|
||||
measured, _missing = usb_pair_z_ohm(layout, pair, impedance_nets)
|
||||
mand: MandatoryClass = "RECOMMENDED"
|
||||
if measured is None:
|
||||
return L2CheckResult(
|
||||
check=check, result="FAIL", mandatory=mand, nets=list(pair),
|
||||
limit_ohm=cited, value_kind="NUMERIC", emit="not_certified",
|
||||
notes=_usb_line("missing", measured=None, cited=cited, label=label),
|
||||
finding_class="RULE", status="ERROR",
|
||||
)
|
||||
if _matches_cited(measured, cited):
|
||||
return L2CheckResult(
|
||||
check=check, result="PASS", mandatory=mand, nets=list(pair),
|
||||
measured_ohm=measured, limit_ohm=cited,
|
||||
limit_ohm_min=cited, limit_ohm_max=cited,
|
||||
value_kind="NUMERIC", emit="certified",
|
||||
notes=_usb_line("certified", measured=measured, cited=cited, label=label),
|
||||
finding_class="INFO", status="INFO",
|
||||
)
|
||||
return L2CheckResult(
|
||||
check=check, result="FAIL", mandatory=mand, nets=list(pair),
|
||||
measured_ohm=measured, limit_ohm=cited,
|
||||
limit_ohm_min=cited, limit_ohm_max=cited,
|
||||
value_kind="NUMERIC", emit="not_certified",
|
||||
notes=_usb_line("outside", measured=measured, cited=cited, label=label),
|
||||
finding_class="RULE", status="ERROR",
|
||||
)
|
||||
|
||||
|
||||
def _z_check(
|
||||
check: str,
|
||||
mand: MandatoryClass,
|
||||
cons: ProtocolConstraint | None,
|
||||
kind: str,
|
||||
inst: PhysicalBusInstance,
|
||||
iface: PhysicalInterface,
|
||||
graph: DesignGraph,
|
||||
nets: list[str],
|
||||
constraints_map: dict[str, ComponentConstraints] | None,
|
||||
impedance_nets: list[dict] | dict | None,
|
||||
layout: LayoutGraph | None,
|
||||
) -> L2CheckResult:
|
||||
pair = _usb_dp_dm(inst)
|
||||
cite = _pcb_zdiff_cite(iface)
|
||||
phy = _phy_z_windows(graph, inst, constraints_map)
|
||||
if cite is not None and pair is not None and not phy:
|
||||
return _usb_board_z(check, inst, cite, pair, layout, impedance_nets)
|
||||
pack_w = _pack_ohm_window(cons)
|
||||
windows: list[tuple[float, float]] = []
|
||||
if pack_w:
|
||||
@@ -403,7 +635,6 @@ def _z_check(
|
||||
window = intersect_windows(windows) if windows else None
|
||||
measured = measured_z_ohm(nets, impedance_nets)
|
||||
if window is None:
|
||||
# no cited pack number and no datasheet PHY window → never invent 90 Ω
|
||||
if measured is None:
|
||||
return _skip_z(check, mand, inst, kind)
|
||||
return _pack(
|
||||
@@ -413,15 +644,15 @@ def _z_check(
|
||||
"VENDOR_DEPENDENT", "UNKNOWN",
|
||||
} else "UNKNOWN",
|
||||
mand,
|
||||
nets=nets, measured_ohm=measured, value_kind=kind,
|
||||
nets=nets, measured_ohm=measured, value_kind=kind, emit="silent",
|
||||
notes=(
|
||||
f"Interfaccia {inst.physical_interface_id} non certificata a L2 "
|
||||
f"per mancanza di Z target (cited pack or PHY datasheet). "
|
||||
f"Measured stackup/fab Z is not compared to invented USB/IEC ohms. "
|
||||
f"L0/L1 are not electrical certification."
|
||||
f"{inst.physical_interface_id} has measured Z and no cited target. "
|
||||
"Not compared to an invented ohm. Not a warning."
|
||||
),
|
||||
)
|
||||
if measured is None:
|
||||
if cite is not None and pair is not None:
|
||||
return _usb_board_z(check, inst, cite, pair, layout, impedance_nets)
|
||||
return _skip_z(check, mand, inst, kind)
|
||||
verdict = electrical_verdict(cons, measured, window)
|
||||
source_note = (
|
||||
@@ -474,10 +705,10 @@ def _termination_check(
|
||||
"VENDOR_DEPENDENT", "UNKNOWN", "NOT_APPLICABLE",
|
||||
} else "UNKNOWN"
|
||||
return _pack(
|
||||
check, verdict, mand, nets=nets, value_kind=kind,
|
||||
check, verdict, mand, nets=nets, value_kind=kind, emit="silent",
|
||||
notes=(
|
||||
f"Interfaccia {inst.physical_interface_id} non certificata a L2 "
|
||||
f"per mancanza di termination cite. No invented Rd/ohm."
|
||||
f"{inst.physical_interface_id} has no termination cite. "
|
||||
"No invented resistor. Not a warning."
|
||||
),
|
||||
)
|
||||
measured = None
|
||||
@@ -517,8 +748,8 @@ def _levels_check(
|
||||
unit = (cons.unit or "").strip().lower()
|
||||
if unit in _VOLT_UNITS:
|
||||
return _pack(
|
||||
check, "UNKNOWN", mand, value_kind="NUMERIC",
|
||||
notes="Voltage NUMERIC in pack but PCB rail FACT not supplied — not invented 3.3 V.",
|
||||
check, "UNKNOWN", mand, value_kind="NUMERIC", emit="silent",
|
||||
notes="Voltage NUMERIC in pack but PCB rail FACT not supplied — not invented 3.3 V. Not a warning.",
|
||||
)
|
||||
if constraints_map:
|
||||
for ref in [inst.host_ref, *inst.peer_refs]:
|
||||
@@ -528,10 +759,10 @@ def _levels_check(
|
||||
ds = match_constraints(comp.mpn or comp.value, constraints_map)
|
||||
if ds and ds.absolute_maximum_ratings:
|
||||
return _pack(
|
||||
check, "UNKNOWN", mand, value_kind=kind,
|
||||
check, "UNKNOWN", mand, value_kind=kind, emit="silent",
|
||||
notes=(
|
||||
"Silicon abs-max present; L2 levels need a cited operating "
|
||||
"window vs measured rail — not assumed. Not L3."
|
||||
"window vs measured rail — not assumed. Not L3. Not a warning."
|
||||
),
|
||||
)
|
||||
verdict = kind if kind in {
|
||||
@@ -539,15 +770,58 @@ def _levels_check(
|
||||
"VENDOR_DEPENDENT", "UNKNOWN", "NOT_APPLICABLE",
|
||||
} else "UNKNOWN"
|
||||
return _pack(
|
||||
check, verdict, mand, value_kind=kind,
|
||||
notes="Levels/voltage UNKNOWN without a cited electrical source. Not invented.",
|
||||
check, verdict, mand, value_kind=kind, emit="silent",
|
||||
notes="Levels/voltage UNKNOWN without a cited electrical source. Not invented. Not a warning.",
|
||||
)
|
||||
|
||||
|
||||
def _pair_line_finding(inst: PhysicalBusInstance, r: L2CheckResult) -> Finding:
|
||||
"""Certified or not certified. English. Not the datasheet boilerplate."""
|
||||
designator = inst.host_ref or inst.physical_interface_id
|
||||
certified = r.emit == "certified"
|
||||
text = r.notes
|
||||
if certified:
|
||||
status = "INFO"
|
||||
cls = "INFO"
|
||||
action = "Calculated pair Z matches the cited limit."
|
||||
else:
|
||||
status = "ERROR"
|
||||
cls = "RULE"
|
||||
action = "Calculated pair Z is not certified. The finding states the reason."
|
||||
f = Finding(
|
||||
designator=designator,
|
||||
mpn="",
|
||||
aspect="protocol_l2",
|
||||
finding=text,
|
||||
why=text,
|
||||
status=status, # type: ignore[arg-type]
|
||||
source=SOURCE,
|
||||
net=r.nets[0] if r.nets else None,
|
||||
rule_id="PE-PRT-L2-002",
|
||||
facts=text,
|
||||
requirement=text,
|
||||
inference="Calculated differential Z compared with the packed cite.",
|
||||
provenance="MANDATORY",
|
||||
finding_class=cls, # type: ignore[arg-type]
|
||||
evidence_status="SUFFICIENT",
|
||||
recommendation=action,
|
||||
action=action,
|
||||
)
|
||||
return complete_finding(f)
|
||||
|
||||
|
||||
def l2_findings(inst: PhysicalBusInstance, results: list[L2CheckResult]) -> list[Finding]:
|
||||
out: list[Finding] = []
|
||||
designator = inst.host_ref or inst.physical_interface_id
|
||||
for r in results:
|
||||
if r.emit in {"certified", "not_certified"}:
|
||||
out.append(_pair_line_finding(inst, r))
|
||||
continue
|
||||
if r.emit == "silent" or (r.result in {
|
||||
"UNKNOWN", "VENDOR_DEPENDENT", "CONTROLLER_DEPENDENT",
|
||||
"PHY_DEPENDENT", "MISSING_SOURCE",
|
||||
} and r.check in _NOISE_CHECKS):
|
||||
continue
|
||||
if r.result == "PASS":
|
||||
continue
|
||||
if r.result == "FAIL" and r.mandatory != "MANDATORY":
|
||||
@@ -568,8 +842,7 @@ def l2_findings(inst: PhysicalBusInstance, results: list[L2CheckResult]) -> list
|
||||
rule_id = "PE-PRT-L2-001"
|
||||
status = "WARNING"
|
||||
finding = r.notes or (
|
||||
f"Interfaccia {inst.physical_interface_id} non certificata a L2 "
|
||||
f"per {r.check} ({r.result})."
|
||||
f"{inst.physical_interface_id} L2 {r.check} is {r.result}."
|
||||
)
|
||||
else:
|
||||
rule_id = "PE-PRT-L0-002"
|
||||
|
||||
@@ -509,9 +509,28 @@ def certify_instance_l3(
|
||||
if c in L3_CHECKS and c not in checks:
|
||||
checks.append(c)
|
||||
facts = lookup_channel_facts(inst, channel_data)
|
||||
if not _channel_fact_present(facts):
|
||||
return []
|
||||
return [_run_l3_check(inst, iface, c, facts) for c in checks]
|
||||
|
||||
|
||||
def _channel_fact_present(facts: dict[str, Any]) -> bool:
|
||||
"""True only when reduced channel FACT is already on hand."""
|
||||
if not facts:
|
||||
return False
|
||||
if _looks_like_raw_sparam(facts):
|
||||
return False
|
||||
if _blob_mentions_fem(facts.get("method") or facts.get("solver") or ""):
|
||||
return False
|
||||
if _il_measured(facts) is not None or _rl_measured(facts) is not None:
|
||||
return True
|
||||
if _xt_measured(facts) is not None:
|
||||
return True
|
||||
if _num(facts.get("total_budget_ps")) is not None:
|
||||
return True
|
||||
return facts.get("channel_complete") is True
|
||||
|
||||
|
||||
def l3_findings(inst: PhysicalBusInstance, results: list[L3CheckResult]) -> list[Finding]:
|
||||
out: list[Finding] = []
|
||||
designator = inst.host_ref or inst.physical_interface_id
|
||||
@@ -533,12 +552,8 @@ def l3_findings(inst: PhysicalBusInstance, results: list[L3CheckResult]) -> list
|
||||
status = "ERROR"
|
||||
finding = f"L3 channel {r.check}: {r.notes}"
|
||||
elif skip_family:
|
||||
rule_id = "PE-PRT-L3-001"
|
||||
status = "WARNING"
|
||||
finding = r.notes or (
|
||||
f"Interfaccia {inst.physical_interface_id} non certificata a L3 "
|
||||
f"per {r.check} ({r.result})."
|
||||
)
|
||||
# No channel FACT, or a field with nothing to certify. Omit the warning.
|
||||
continue
|
||||
else:
|
||||
rule_id = "PE-PRT-L0-002"
|
||||
status = "INFO"
|
||||
|
||||
@@ -114,6 +114,12 @@ def check_to_report_row(
|
||||
result = str(dump.get("result") or "")
|
||||
cons = _constraint_for(iface, check) if iface is not None else None
|
||||
doc, section, method = _cite(cons)
|
||||
if check == "differential_impedance" and not doc and iface is not None:
|
||||
for alt in iface.constraints:
|
||||
if alt.parameter == "pcb_trace_nominal_zdiff" and alt.source is not None:
|
||||
doc, section, method = _cite(alt)
|
||||
cons = alt
|
||||
break
|
||||
nets = list(dump.get("nets") or [])
|
||||
net = nets[0] if nets else (inst.nets[0] if inst.nets else "")
|
||||
group = _group_for_net(inst, net or None)
|
||||
@@ -130,6 +136,7 @@ def check_to_report_row(
|
||||
"source": doc,
|
||||
"method": method,
|
||||
"notes": dump.get("notes") or "",
|
||||
"emit": dump.get("emit") or "",
|
||||
"skip_visible": skip,
|
||||
"rank": result_rank(result),
|
||||
"chain": {
|
||||
@@ -181,6 +188,21 @@ def format_chain(chain: dict[str, Any]) -> str:
|
||||
return " → ".join(parts)
|
||||
|
||||
|
||||
def _noise_row(row: dict[str, Any]) -> bool:
|
||||
"""Missing-field skips are not a certification line."""
|
||||
if row.get("emit") == "silent":
|
||||
return True
|
||||
result = str(row.get("result") or "")
|
||||
if result not in _SKIP:
|
||||
return False
|
||||
notes = str(row.get("notes") or "").lower()
|
||||
if "grouping" in notes or "dq/dqs" in notes:
|
||||
return False
|
||||
if row.get("measured") is not None or row.get("limit") is not None:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def attach_instance_report(
|
||||
inst: PhysicalBusInstance,
|
||||
iface: PhysicalInterface | None,
|
||||
@@ -195,9 +217,7 @@ def attach_instance_report(
|
||||
+ [c.model_dump() if hasattr(c, "model_dump") else dict(c) for c in l2]
|
||||
+ [c.model_dump() if hasattr(c, "model_dump") else dict(c) for c in (l3 or [])]
|
||||
)
|
||||
rows = [check_to_report_row(d, inst, iface) for d in dumps]
|
||||
if not any(r["level"] == "L3" for r in rows):
|
||||
rows.append(l3_not_run_row(inst))
|
||||
rows = [r for r in (check_to_report_row(d, inst, iface) for d in dumps) if not _noise_row(r)]
|
||||
rows.sort(key=lambda r: (r["rank"], str(r["level"]), str(r["check"])))
|
||||
worst = instance_worst_result([str(r["result"]) for r in rows if r["level"] != "L3"])
|
||||
# L3 skip/UNKNOWN must not upgrade instance to PASS or hide FAIL
|
||||
|
||||
@@ -42,7 +42,12 @@ _HS_CLASS_RE = (
|
||||
("hdmi", re.compile(r"HDMI", re.I)),
|
||||
("pcie", re.compile(r"PCIE|PEX_", re.I)),
|
||||
("sgmii", re.compile(r"SGMII", re.I)),
|
||||
("rgmii", re.compile(r"RGMII|(?:^|[_/])GMII", re.I)),
|
||||
("rgmii", re.compile(r"RGMII|(?:^|[_/])GMII|TX_CTL|RX_CTL|(?:ETH|MAC).*GTX", re.I)),
|
||||
("rmii", re.compile(
|
||||
r"(?:^|[_/])RMII|"
|
||||
r"(?:ETH|MAC).*(?:TXD|RXD|TXEN|RXDV|CRS_DV|REF_CLK)",
|
||||
re.I,
|
||||
)),
|
||||
("eth_mdi", re.compile(
|
||||
r"(?:^|[_/])(MDI|TRD[0-3]|TCT|RCT)|"
|
||||
r"ETH.?(?:TD|RD|TX|RX|TP)[+\-_PN0-3]|1000BASE|RJ45",
|
||||
@@ -92,8 +97,10 @@ _BUS_TOKEN_EXPAND: dict[str, frozenset[str]] = {
|
||||
"magnetics": frozenset({"eth_mdi"}),
|
||||
"rgmii": frozenset({"rgmii"}),
|
||||
"gmii": frozenset({"rgmii"}),
|
||||
"mac_phy": frozenset({"rgmii", "sgmii"}),
|
||||
"mac": frozenset({"rgmii", "sgmii"}),
|
||||
"rmii": frozenset({"rmii"}),
|
||||
"mii": frozenset({"rmii"}),
|
||||
"mac_phy": frozenset({"rmii", "rgmii", "sgmii"}),
|
||||
"mac": frozenset({"rmii", "rgmii", "sgmii"}),
|
||||
"sgmii": frozenset({"sgmii"}),
|
||||
"ddr": frozenset({"ddr3_clk", "ddr3_dqs", "ddr3_dq", "ddr3_addr"}),
|
||||
"ddr3": frozenset({"ddr3_clk", "ddr3_dqs", "ddr3_dq", "ddr3_addr"}),
|
||||
@@ -143,6 +150,31 @@ def partner_net(name: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
# RMII/MII data and TX enable. Not an MDI pair. Not a 100 Ω differential net.
|
||||
_SINGLE_ENDED_ETH_RE = re.compile(
|
||||
r"(?:^|[^A-Za-z0-9])(?:ETH_|MAC_)?(?:RXD|TXD|TXEN|RXDV|CRS_DV)(?:\d+)?(?:[^A-Za-z0-9]|$)",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def single_ended_eth_mac(net: str) -> bool:
|
||||
"""ETH_RXD / ETH_TXD / ETH_TXEN are single-ended. Not a differential pair."""
|
||||
leaf = _leaf(net)
|
||||
return bool(_SINGLE_ENDED_ETH_RE.search(leaf) or _SINGLE_ENDED_ETH_RE.search(net or ""))
|
||||
|
||||
|
||||
def phy_mac_kind(net: str) -> str | None:
|
||||
"""``rmii``, ``rgmii``, or ``mii`` for a PHY–MAC net. Never ``eth_mdi``."""
|
||||
leaf = _leaf(net).upper()
|
||||
if re.search(r"RGMII|(?:^|[_/])GMII|TX_CTL|RX_CTL|(?:ETH|MAC).*GTX", leaf):
|
||||
return "rgmii"
|
||||
if single_ended_eth_mac(net) or "RMII" in leaf:
|
||||
if re.search(r"(?:^|[_/])MII(?:$|[_/])", leaf) and "RMII" not in leaf:
|
||||
return "mii"
|
||||
return "rmii"
|
||||
return None
|
||||
|
||||
|
||||
def _leaf(net: str) -> str:
|
||||
n = normalize_kicad_hierarchy_net(net)
|
||||
return n.split("/")[-1] if n else ""
|
||||
@@ -173,8 +205,10 @@ def bus_class(net: str) -> str | None:
|
||||
return "usb3"
|
||||
if "USB" in u and re.search(r"(D\+|D-|DP|DM)", leaf, re.I):
|
||||
return "usb2"
|
||||
if re.search(r"(?:ETH|MAC).*(TXD|RXD|TXC|RXC|TX_CLK|RX_CLK|TX_CTL|RX_CTL|TXEN|RXDV|GTX)", u):
|
||||
if re.search(r"RGMII|(?:^|[_/])GMII|TX_CTL|RX_CTL|(?:ETH|MAC).*GTX", u):
|
||||
return "rgmii"
|
||||
if re.search(r"(?:ETH|MAC).*(TXD|RXD|TXC|RXC|TX_CLK|RX_CLK|TXEN|RXDV|CRS_DV|REF_CLK)|(?:^|[_/])RMII", u):
|
||||
return "rmii"
|
||||
if re.search(r"(?:^|[_/])ETH(?:$|[_/])", u) and re.search(r"[+\-]|_P$|_N$|_P/|_N/", leaf):
|
||||
return "eth_mdi"
|
||||
for cls, cre in _HS_CLASS_RE:
|
||||
@@ -228,6 +262,7 @@ def _rule_target_buses(rule: dict) -> frozenset[str]:
|
||||
scans: tuple[tuple[str, str], ...] = (
|
||||
(r"super\s*speed|usb\s*3|sstx|ssrx", "usb3"),
|
||||
(r"rgmii|gtx_clk|tx_ctl|rx_ctl", "rgmii"),
|
||||
(r"\brmii\b|\bmii\b|txen|rxdv|crs_dv", "rmii"),
|
||||
(r"sgmii", "sgmii"),
|
||||
(r"mdi|rj-?45|magnetics|trd[0-3]|1000\s*base", "eth_mdi"),
|
||||
(r"ddr3|\bddr\b", "ddr3"),
|
||||
@@ -358,6 +393,8 @@ def _rule_nets(layout: LayoutGraph, rule: dict, graph: DesignGraph) -> list[str]
|
||||
if targets:
|
||||
if not _bus_in_targets(bc, targets):
|
||||
continue
|
||||
if single_ended_eth_mac(net) and "eth_mdi" in targets:
|
||||
continue
|
||||
else:
|
||||
# No bus on the quote: pin-scoped only. Never paint USB/DDR/PHY.
|
||||
if not pin:
|
||||
@@ -530,6 +567,8 @@ def check_si(
|
||||
want_diff = _num(rule.get("zdiff_ohm")) is not None or kind == "zdiff"
|
||||
paired: set[tuple[str, str]] = set()
|
||||
for net in nets:
|
||||
if want_diff and single_ended_eth_mac(net):
|
||||
continue
|
||||
zrow = _z_row(rows, net)
|
||||
partner = _partner_on_board(layout, net, zrow) if want_diff else None
|
||||
key_net = _pair_key(net, partner) if partner else (net, "")
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
@@ -153,16 +154,15 @@ def si_extract_needed_skips(
|
||||
}
|
||||
if not needs_layout_rules_refresh(payload, min_scan_version=scan_ver):
|
||||
continue
|
||||
refs = ",".join(sorted(refs_by_mpn.get(mpn, []))) or mpn
|
||||
out.append({
|
||||
"designator": refs,
|
||||
"reason": (
|
||||
refs = sorted(refs_by_mpn.get(mpn, [])) or [mpn]
|
||||
reason = (
|
||||
f"SI layout_rules empty at model_version="
|
||||
f"{cons.model_version}; re-run schematic review "
|
||||
f"to re-extract pintable {scan_ver} "
|
||||
"(PCB does not re-read the PDF)."
|
||||
),
|
||||
})
|
||||
)
|
||||
for ref in refs:
|
||||
out.append({"designator": ref, "reason": reason})
|
||||
return out
|
||||
|
||||
|
||||
@@ -220,6 +220,14 @@ async def run_pcb_pipeline(
|
||||
pcb_state=None,
|
||||
)
|
||||
|
||||
t_total = time.perf_counter()
|
||||
stage_seconds: dict[str, float] = {}
|
||||
|
||||
def _lap(name: str, started: float) -> float:
|
||||
seconds = round(time.perf_counter() - started, 3)
|
||||
stage_seconds[name] = seconds
|
||||
return seconds
|
||||
|
||||
try:
|
||||
async with PipelineWorkspace(storage, user_id, project_id) as ws:
|
||||
if _cancelled(storage, user_id, project_id):
|
||||
@@ -247,7 +255,10 @@ async def run_pcb_pipeline(
|
||||
return
|
||||
|
||||
_step(project_id, "classify", "running", "domains and groups")
|
||||
t_extract = time.perf_counter()
|
||||
cmap = _load_constraints_map(ws.local_path("extracted"), storage)
|
||||
extract_s = _lap("extract", t_extract)
|
||||
_step(project_id, "extract", "complete", f"loaded stored extractions; {extract_s}s")
|
||||
plan = build_placement_plan(graph, cmap)
|
||||
fg_path = ws.local_path("functional_groups.json")
|
||||
fg_path.write_text(plan.model_dump_json(indent=2) + "\n")
|
||||
@@ -306,7 +317,9 @@ async def run_pcb_pipeline(
|
||||
return
|
||||
|
||||
_step(project_id, "checks", "running")
|
||||
t_checks = time.perf_counter()
|
||||
findings = run_pcb_checks(graph, cmap, layout, plan, zrep)
|
||||
checks_s = _lap("pcb_checks", t_checks)
|
||||
scan_ver = app_settings.get_default_model_version()
|
||||
si_skip = si_extract_needed_skips(graph, cmap, scan_ver)
|
||||
sipath = ws.local_path("si_extract_needed.json")
|
||||
@@ -315,7 +328,8 @@ async def run_pcb_pipeline(
|
||||
_step(
|
||||
project_id, "checks", "complete",
|
||||
f"{len(findings)} deterministic findings"
|
||||
+ (f"; {len(si_skip)} SI re-extract" if si_skip else ""),
|
||||
+ (f"; {len(si_skip)} SI re-extract" if si_skip else "")
|
||||
+ f"; {checks_s}s",
|
||||
)
|
||||
|
||||
if _cancelled(storage, user_id, project_id):
|
||||
@@ -323,6 +337,7 @@ async def run_pcb_pipeline(
|
||||
return
|
||||
|
||||
_step(project_id, "af_trace", "running", "AF trigger + closed-form/cascade (not OpenEMS)")
|
||||
t_af_trace = time.perf_counter()
|
||||
try:
|
||||
extra_af = check_af_traces(graph, cmap, layout, zrep, findings)
|
||||
findings.extend(extra_af)
|
||||
@@ -330,9 +345,10 @@ async def run_pcb_pipeline(
|
||||
except Exception:
|
||||
logger.exception("AF trace analysis failed — keeping PCB checks")
|
||||
n_trace = 0
|
||||
af_trace_s = _lap("af_trace", t_af_trace)
|
||||
_step(
|
||||
project_id, "af_trace", "complete",
|
||||
f"{n_trace} AF trace findings (SI/HF checks kept)",
|
||||
f"{n_trace} AF trace findings (SI/HF checks kept); {af_trace_s}s",
|
||||
)
|
||||
|
||||
if _cancelled(storage, user_id, project_id):
|
||||
@@ -340,10 +356,13 @@ async def run_pcb_pipeline(
|
||||
return
|
||||
|
||||
_step(project_id, "af_ai", "running", "AI HF flags then deterministic investigate")
|
||||
t_af_ai = time.perf_counter()
|
||||
n_af = _run_af_ai_section(ws, graph, cmap, layout, zrep, findings)
|
||||
af_ai_s = _lap("af_ai", t_af_ai)
|
||||
stage_seconds["af"] = round(stage_seconds.get("af_trace", 0) + af_ai_s, 3)
|
||||
_step(
|
||||
project_id, "af_ai", "complete",
|
||||
f"{n_af} extra AF+AI findings (SI/HF checks kept)",
|
||||
f"{n_af} extra AF+AI findings (SI/HF checks kept); {af_ai_s}s; af={stage_seconds['af']}s",
|
||||
)
|
||||
|
||||
if _cancelled(storage, user_id, project_id):
|
||||
@@ -353,6 +372,7 @@ async def run_pcb_pipeline(
|
||||
_step(project_id, "ai_review", "running", "layout vs shared library extraction")
|
||||
coverage: dict[str, list[str]] = {}
|
||||
skipped: list[dict] = []
|
||||
review_errors: dict[str, str] = {}
|
||||
try:
|
||||
from backend.services.api_logs import ApiLogger
|
||||
from backend.services.pcb_validation import review_pcb_ics
|
||||
@@ -367,7 +387,7 @@ async def run_pcb_pipeline(
|
||||
f"{ref} {tool} {detail}".strip(),
|
||||
)
|
||||
|
||||
ai_findings, coverage, skipped = await review_pcb_ics(
|
||||
ai_findings, coverage, skipped, review_errors = await review_pcb_ics(
|
||||
graph, cmap, layout, plan, inventory,
|
||||
pdf_dir, storage=storage, api_logger=logger_api,
|
||||
on_progress=_prog,
|
||||
@@ -376,6 +396,7 @@ async def run_pcb_pipeline(
|
||||
logger_api.flush(storage, user_id, project_id)
|
||||
detail = (
|
||||
f"{len(ai_findings)} AI findings, {len(skipped)} skipped"
|
||||
+ (f", {len(review_errors)} review errors" if review_errors else "")
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("PCB AI review failed — keeping deterministic findings")
|
||||
@@ -387,11 +408,14 @@ async def run_pcb_pipeline(
|
||||
return
|
||||
|
||||
_step(project_id, "write_report", "running")
|
||||
t_protocol = time.perf_counter()
|
||||
proto_section, proto_findings = protocol_exam(
|
||||
graph, layout=layout,
|
||||
constraints_map=cmap, impedance_nets=zrep,
|
||||
channel_data=_load_channel_data(ws),
|
||||
)
|
||||
protocol_s = _lap("protocol", t_protocol)
|
||||
_step(project_id, "protocol", "complete", f"{protocol_s}s")
|
||||
findings.extend(proto_findings)
|
||||
assign_pcb_finding_ids(findings)
|
||||
annotate_findings_cad(findings, cad_index_from_graph(graph))
|
||||
@@ -404,13 +428,20 @@ async def run_pcb_pipeline(
|
||||
summary: dict[str, int] = {"ERROR": 0, "WARNING": 0, "INFO": 0}
|
||||
for f in findings:
|
||||
summary[f.status] = summary.get(f.status, 0) + 1
|
||||
# Drop not_reviewed entries for ICs that were actually reviewed.
|
||||
covered = set(coverage)
|
||||
not_reviewed = [
|
||||
row for row in (skipped + si_skip)
|
||||
if str(row.get("designator") or "") not in covered
|
||||
]
|
||||
report = ValidationReport(
|
||||
project=project_id,
|
||||
timestamp=datetime.now(timezone.utc).isoformat(),
|
||||
findings=findings,
|
||||
summary=summary,
|
||||
coverage=coverage,
|
||||
not_reviewed=skipped + si_skip,
|
||||
review_errors=review_errors,
|
||||
not_reviewed=not_reviewed,
|
||||
protocol_certification=proto_section.model_dump(),
|
||||
)
|
||||
report_path = ws.local_path("pcb_report.json")
|
||||
@@ -422,10 +453,22 @@ async def run_pcb_pipeline(
|
||||
ws._upload_file("periscope-findings.json")
|
||||
_step(project_id, "write_report", "complete", f"{len(findings)} findings")
|
||||
|
||||
stage_seconds["total"] = round(time.perf_counter() - t_total, 3)
|
||||
_step(
|
||||
project_id, "timing", "complete",
|
||||
"extract={extract}s pcb_checks={pcb_checks}s protocol={protocol}s af={af}s total={total}s".format(
|
||||
extract=stage_seconds.get("extract"),
|
||||
pcb_checks=stage_seconds.get("pcb_checks"),
|
||||
protocol=stage_seconds.get("protocol"),
|
||||
af=stage_seconds.get("af"),
|
||||
total=stage_seconds.get("total"),
|
||||
),
|
||||
)
|
||||
_publish(project_id, "pcb_complete", {
|
||||
"findings": len(findings),
|
||||
"domains": len(plan.domains),
|
||||
"groups": len(plan.groups),
|
||||
"stage_seconds": stage_seconds,
|
||||
})
|
||||
proj_svc.update_project(
|
||||
storage, user_id, project_id,
|
||||
@@ -435,15 +478,17 @@ async def run_pcb_pipeline(
|
||||
"domains": len(plan.domains),
|
||||
"groups": len(plan.groups),
|
||||
"skipped": len(skipped),
|
||||
"stage_seconds": stage_seconds,
|
||||
},
|
||||
pcb_cancel_requested=False,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("pcb pipeline failed for %s", project_id)
|
||||
stage_seconds["total"] = round(time.perf_counter() - t_total, 3)
|
||||
proj_svc.update_project(
|
||||
storage, user_id, project_id,
|
||||
pcb_status="error",
|
||||
pcb_state={"error": str(e)},
|
||||
pcb_state={"error": str(e), "stage_seconds": stage_seconds},
|
||||
)
|
||||
_publish(project_id, "pcb_error", {"error": str(e)})
|
||||
|
||||
|
||||
@@ -54,15 +54,20 @@ async def review_pcb_ics(
|
||||
storage=None,
|
||||
api_logger: ApiLogger | None = None,
|
||||
on_progress=None,
|
||||
) -> tuple[list[Finding], dict[str, list[str]], list[dict]]:
|
||||
) -> tuple[list[Finding], dict[str, list[str]], list[dict], dict[str, str]]:
|
||||
"""Layout-only AI exam using ``library/extracted`` (or project extracted/).
|
||||
|
||||
Does not attach a datasheet PDF. ICs without a library pintable are skipped
|
||||
with a reason to run schematic review first.
|
||||
|
||||
Returns ``(findings, coverage, not_reviewed, review_errors)``.
|
||||
Real review exceptions go in ``review_errors`` — never as
|
||||
``not_reviewed`` with the blanket label ``pcb_review error``.
|
||||
"""
|
||||
findings: list[Finding] = []
|
||||
coverage: dict[str, list[str]] = {}
|
||||
skipped: list[dict] = []
|
||||
review_errors: dict[str, str] = {}
|
||||
cache: dict = {}
|
||||
for ref, comp in sorted(graph.components.items()):
|
||||
if comp.component_type != ComponentType.IC:
|
||||
@@ -102,15 +107,21 @@ async def review_pcb_ics(
|
||||
system_prompt=PCB_SYSTEM_PROMPT,
|
||||
log_stage="pcb_review",
|
||||
)
|
||||
except Exception:
|
||||
log.exception("PCB AI review failed for %s — skipping", ref)
|
||||
skipped.append({"designator": ref, "reason": "pcb_review error"})
|
||||
except Exception as exc:
|
||||
msg = f"{type(exc).__name__}: {exc}"
|
||||
log.exception("PCB AI review failed for %s — recording review_errors", ref)
|
||||
review_errors[ref] = msg
|
||||
continue
|
||||
if not isinstance(result, ReviewResult):
|
||||
# Prefer a visible false positive over a silent miss.
|
||||
skipped.append({
|
||||
"designator": ref,
|
||||
"reason": "PCB review returned no result",
|
||||
})
|
||||
continue
|
||||
_ensure_recs(result.findings)
|
||||
annotate_findings_cad(result.findings, cad_index_from_graph(graph))
|
||||
findings.extend(result.findings)
|
||||
if result.checked_areas:
|
||||
coverage[ref] = list(result.checked_areas)
|
||||
return findings, coverage, skipped
|
||||
# Empty checked_areas still means the IC was reviewed (no issues).
|
||||
coverage[ref] = list(result.checked_areas or ["layout"])
|
||||
return findings, coverage, skipped, review_errors
|
||||
|
||||
@@ -2,14 +2,45 @@
|
||||
|
||||
What's new in Periscope.
|
||||
|
||||
## 2.83.0 — 2026-09-22 — Apple-like shell, findings tree, HDMI 1.4 UNKNOWN
|
||||
## 2.85.0 — 2026-09-23 — USB / RMII cert lines; not_reviewed count
|
||||
|
||||
Shell Finder/Settings: sidebar, large title, system font, hairline. Findings tree keeps Error / Warning / Info folders (FAIL first) with + disclosure, then domains/rules, then Certificazioni/Protocolli. HDMI 1.4 TMDS electrical displays UNKNOWN — no guessed Zdiff. Catalog JSON untouched.
|
||||
USB 2.0 D+/D− is one line: calculated pair Z versus the packed 90 Ω board cite. Certified names the measured ohm and the cite. Not certified says why — Z is outside that cite, or Z cannot be calculated from the PCB stackup/geometry. Missing length, stub, via, termination, rise/fall, and channel fields do not each warn. L3 is omitted when no channel fact is on file.
|
||||
|
||||
LAN8720A ETH_RXD / ETH_TXD / ETH_TXEN are RMII (single-ended PHY–MAC), not RJ45/MDI 100 Ω. One line: `RMII certified — …`. No Italian «mancanza di tr, f» on those nets. RJ45 pairs keep `Ethernet certified / not certified`.
|
||||
|
||||
`not_reviewed` count matches the list (one designator per row). Real PCB AI failures go to `review_errors` with the exception message — not a blanket `pcb_review error` on every skip. ICs already in coverage are not listed as not-reviewed.
|
||||
|
||||
- [Changed] `protocol_l1.py`, `protocol_l2.py`, `protocol_l3.py`, `protocol_report.py`, `af_trace_check.py`, `si_check.py`.
|
||||
- [Changed] `pcb_validation.py`, `pcb_pipeline.py`, `pcb_checks.py` merge; report UI copy.
|
||||
- [Changed] Protocol tree shows the certification sentence.
|
||||
- [Changed] pytest `tests/pcb/test_j2_usb_cert_line.py`, `test_rmii_cert_line.py`, `test_not_reviewed_count.py`.
|
||||
|
||||
## 2.84.0 — 2026-09-22 — Exposed-pad names, ESD cites, CC-via-net, Ethernet pair Z
|
||||
|
||||
PE-BOM-011 treats EP, EPAD, THERMAL PAD, exposed pad, and the footprint's exposed land (including pin_count+1) as the same pad when both sides have one. A datasheet exposed pad with no land on the footprint stays ERROR.
|
||||
|
||||
PE-ESD-001 says "datasheet-specified" only with a part and section/page. A 3V3 jack rail and VBUS are not warned without that cite. Optical S/PDIF (TOSLINK/optocoupler) is not an ESD warning; an unverified S/PDIF path stays a visible warning.
|
||||
|
||||
PE-PRT-L0-001 follows Type-C CC pins (A5/B5) to the net and looks for the packed CabCon Rd 5.1 kΩ. The net does not have to be named CC1/CC2.
|
||||
|
||||
PE-AF-002 on an Ethernet MDI pair compares one calculated pair Z to the packed cite for the speed on the board (LAN8720A 10/100 → 100 Ω, IEEE 100BASE-TX 25.4.9; Clause 40 only if gigabit). Inside is PASS, outside is FAIL, and no calculation is ERROR. No tr/f request.
|
||||
|
||||
- [Changed] `bom_pcb_check.py`, `esd_return_check.py`, `protocol_l0.py`, `af_trace_check.py`.
|
||||
- [Changed] pytest `tests/pcb/test_bom_esd_ep_cc_eth.py`.
|
||||
- [Changed] Findings tree labels are English: domains, Certifications, Protocols, actions, and empty states. Error / Warning / Info stay.
|
||||
|
||||
## 2.83.0 — 2026-09-22 — Apple-like shell; USB-C vSafe still UNKNOWN
|
||||
|
||||
Shell Finder/Settings: sidebar, large title, system font, hairline. Findings tree keeps Error / Warning / Info folders (FAIL first) with + disclosure, then domains/rules, then Certificazioni/Protocolli. HDMI 1.4 TMDS electrical displays UNKNOWN — no guessed Zdiff.
|
||||
|
||||
Alta Frequenza zip and `af-allegati` were searched for vSafe5V / vSafe0V. Contents are TI SI (`snla027b` AN-807, `sdaa499` EMI) — they do not state vSafe voltages. USB Type-C CabCon R2.5 §1.6 p.35 points at USB PD without a volt range. Charger Figure 4-39 4.75–5.5 V stays not-vSafe.
|
||||
|
||||
- [Changed] App chrome (`sidebar`, `globals.css`, dashboard list, report large title).
|
||||
- [Changed] Findings tree grouping + protocol section inside the tree.
|
||||
- [Changed] Protocol UI: HDMI 1.4 TMDS Zdiff/limit/measured show `UNKNOWN`.
|
||||
- [Changed] Frontend tests `findings-forest`, `protocol-report`.
|
||||
- [Changed] `vsafe5v` / `vsafe0v` needed_document; `catalog.json`.
|
||||
- [Changed] INDEX archives AF TI SI as not packed for vSafe.
|
||||
|
||||
## 2.82.0 — 2026-09-22 — HDMI 2.0+ TI fields use source_type VENDOR
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "periscope-web",
|
||||
"version": "2.83.0",
|
||||
"version": "2.84.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"sync-version": "node scripts/sync-version.mjs",
|
||||
|
||||
@@ -328,7 +328,10 @@ function ReportContent({ projectId }: { projectId: string }) {
|
||||
{report.not_reviewed.length} component{report.not_reviewed.length === 1 ? "" : "s"} not reviewed
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
These components have no datasheet on file, so they were not checked against one. A reversed or mis-wired pin on an unreviewed part (e.g. a DNP footprint with no BOM entry) cannot be caught here — verify these manually.
|
||||
Each line is one designator. The reason is per part — missing
|
||||
datasheet, missing library extraction, or SI re-extract needed.
|
||||
Parts that were reviewed are not listed here. Review failures
|
||||
(with an error message) appear under failed reviews above.
|
||||
</p>
|
||||
<ul className="space-y-1 text-xs">
|
||||
{report.not_reviewed.map((nr) => (
|
||||
@@ -343,9 +346,9 @@ function ReportContent({ projectId }: { projectId: string }) {
|
||||
{report.summary.total === 0 &&
|
||||
!(report.protocol_certification?.recognized_instances?.length) ? (
|
||||
<div className="rounded-[11px] border border-black/10 px-5 py-10 text-center">
|
||||
<p className="text-[15px] font-medium tracking-tight">Nessun finding</p>
|
||||
<p className="text-[15px] font-medium tracking-tight">No findings</p>
|
||||
<p className="mt-1 text-[13px] text-neutral-500">
|
||||
Carica i datasheet degli IC sulla pagina progetto e rilancia l’esame.
|
||||
Upload the IC datasheets on the project page and run the exam again.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -161,7 +161,7 @@ type NavItem =
|
||||
|
||||
const PRIMARY_NAV: NavItem[] = [
|
||||
{ type: "tab", tab: "bom", label: "Esame", icon: ScanLine },
|
||||
{ type: "route", path: "/report", label: "Protocolli", icon: BookOpen },
|
||||
{ type: "route", path: "/report", label: "Protocols", icon: BookOpen },
|
||||
{ type: "route", path: "/report", label: "Report", icon: ClipboardList },
|
||||
];
|
||||
|
||||
@@ -216,7 +216,7 @@ function ProjectNav({
|
||||
const onReport = pathname === `${base}/report`;
|
||||
|
||||
function isActive(item: NavItem): boolean {
|
||||
if (item.label === "Protocolli") return onReport;
|
||||
if (item.label === "Protocols") return onReport;
|
||||
if (item.label === "Report") return onReport;
|
||||
if (item.type === "route") {
|
||||
return pathname === `${base}${item.path}` && !currentTab;
|
||||
@@ -228,7 +228,7 @@ function ProjectNav({
|
||||
}
|
||||
|
||||
function getHref(item: NavItem): string {
|
||||
if (item.label === "Protocolli") return `${base}/report`;
|
||||
if (item.label === "Protocols") return `${base}/report`;
|
||||
if (item.type === "route") return `${base}${item.path}`;
|
||||
return `${base}?tab=${item.tab}`;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
forestHasCertifications,
|
||||
groupByWorstStatus,
|
||||
isProtocolFinding,
|
||||
protocolEmptyMessage,
|
||||
protocolInstancesFromSection,
|
||||
protocolInstancesForStatus,
|
||||
worstStatus,
|
||||
@@ -172,10 +173,10 @@ export function FindingsTree(props: FindingsTreeProps) {
|
||||
))}
|
||||
{cert ? (
|
||||
<CertificationsBranch
|
||||
{...props}
|
||||
status={status}
|
||||
instances={inst}
|
||||
findings={protocolAtStatus}
|
||||
{...props}
|
||||
/>
|
||||
) : null}
|
||||
</TreeBranch>
|
||||
@@ -267,9 +268,9 @@ function CertificationsBranch({
|
||||
} & FindingsTreeProps) {
|
||||
const all = [...findings, ...instances.map(() => ({ status }))];
|
||||
return (
|
||||
<TreeBranch label="Certificazioni" findings={all.length ? all : [{ status }]} defaultOpen>
|
||||
<TreeBranch label="Certifications" findings={all.length ? all : [{ status }]} defaultOpen>
|
||||
<TreeBranch
|
||||
label="Protocolli"
|
||||
label="Protocols"
|
||||
findings={all.length ? all : [{ status }]}
|
||||
defaultOpen
|
||||
>
|
||||
@@ -318,7 +319,7 @@ function CertificationsBranch({
|
||||
) : null}
|
||||
{instances.length === 0 && findings.length === 0 ? (
|
||||
<p className="px-2 py-2 text-[13px] text-neutral-500">
|
||||
{props.protocolSection?.message || "Nessun protocollo riconosciuto."}
|
||||
{protocolEmptyMessage(props.protocolSection?.message)}
|
||||
</p>
|
||||
) : null}
|
||||
</TreeBranch>
|
||||
@@ -329,9 +330,9 @@ function CertificationsBranch({
|
||||
export function FindingsTreeEmpty() {
|
||||
return (
|
||||
<div className="rounded-[11px] border border-black/10 px-5 py-10 text-center dark:border-white/10">
|
||||
<p className="text-[15px] font-medium tracking-tight">Nessun finding visibile</p>
|
||||
<p className="text-[15px] font-medium tracking-tight">No visible findings</p>
|
||||
<p className="mt-1 text-[13px] text-neutral-500">
|
||||
I filtri nascondono l’elenco. Togli un filtro, oppure apri i findings già rivisti sotto.
|
||||
Filters are hiding the list. Clear a filter, or open the reviewed findings below.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type ProtocolReportCheck,
|
||||
} from "@/lib/protocol-report";
|
||||
import {
|
||||
protocolEmptyMessage,
|
||||
protocolInstancesFromSection,
|
||||
type ProtocolTreeInstance,
|
||||
} from "@/lib/findings-forest";
|
||||
@@ -20,15 +21,23 @@ export function ProtocolInstanceBody({ instance }: { instance: ProtocolTreeInsta
|
||||
const fail = instance.worst === "FAIL" || instance.status === "ERROR";
|
||||
const logical = instance.logicalId;
|
||||
const physical = instance.physicalId;
|
||||
const certLine = checks.find((c) =>
|
||||
/^(USB|Ethernet|RMII|MII|RGMII) (certified|not certified) —/.test(c.notes || ""),
|
||||
);
|
||||
return (
|
||||
<div className="space-y-2 py-2 pr-2">
|
||||
{certLine?.notes ? (
|
||||
<p className="text-[13px] font-medium tracking-tight text-neutral-900 dark:text-neutral-100">
|
||||
{certLine.notes}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="text-[11px] tabular-nums text-neutral-500">
|
||||
{logical} → {physical}
|
||||
{instance.recognition ? ` · ${instance.recognition}` : ""}
|
||||
{instance.worst ? ` · ${instance.worst}` : ""}
|
||||
</p>
|
||||
{fail ? (
|
||||
<p className="text-[11px] text-[rgb(180,40,35)]">FAIL in testa — non sotto Warning.</p>
|
||||
<p className="text-[11px] text-[rgb(180,40,35)]">FAIL is listed first — not under Warning.</p>
|
||||
) : null}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-[11px] tabular-nums">
|
||||
@@ -57,7 +66,7 @@ export function ProtocolInstanceBody({ instance }: { instance: ProtocolTreeInsta
|
||||
</table>
|
||||
</div>
|
||||
{instance.chainExample ? (
|
||||
<p className="break-all text-[11px] text-neutral-500">Catena: {instance.chainExample}</p>
|
||||
<p className="break-all text-[11px] text-neutral-500">Chain: {instance.chainExample}</p>
|
||||
) : null}
|
||||
{checks
|
||||
.filter((c) => c.result === "FAIL" || c.skip_visible)
|
||||
@@ -113,12 +122,12 @@ export function ProtocolSection({
|
||||
section?: ProtocolCertificationSection | null;
|
||||
}) {
|
||||
const instances = protocolInstancesFromSection(section);
|
||||
const message = section?.message || "Nessun protocollo riconosciuto.";
|
||||
const message = protocolEmptyMessage(section?.message);
|
||||
const maxLevel = section?.max_level_reached || "—";
|
||||
return (
|
||||
<section className="space-y-2">
|
||||
<p className="text-[11px] text-neutral-500">
|
||||
Livello massimo {maxLevel} (L0–L3). HDMI 1.4 TMDS resta UNKNOWN — niente Zdiff inventato.
|
||||
Max level {maxLevel} (L0–L3). HDMI 1.4 TMDS stays UNKNOWN — no invented Zdiff.
|
||||
</p>
|
||||
{instances.length === 0 ? (
|
||||
<p className="text-[13px] text-neutral-600">{message}</p>
|
||||
|
||||
@@ -20,18 +20,18 @@ export function ReportSummary({
|
||||
const infos = summary.INFO ?? 0;
|
||||
const total = summary.total || errors + warnings + infos;
|
||||
const outcome =
|
||||
errors > 0 ? "Error" : warnings > 0 ? "Attenzione" : total > 0 ? "Completato" : "Senza findings";
|
||||
errors > 0 ? "Error" : warnings > 0 ? "Warning" : total > 0 ? "Complete" : "No findings";
|
||||
const bits = [
|
||||
`${errors} Error`,
|
||||
`${warnings} Warning`,
|
||||
`${infos} Info`,
|
||||
`${reviewedCount} rivisti`,
|
||||
`${reviewedCount} reviewed`,
|
||||
];
|
||||
if (typeof totalCostUsd === "number" && totalCostUsd > 0) {
|
||||
bits.push(`$${totalCostUsd.toFixed(2)}`);
|
||||
}
|
||||
if (typeof creditsSpent === "number" && creditsSpent > 0) {
|
||||
bits.push(`${creditsSpent.toFixed(2)} crediti`);
|
||||
bits.push(`${creditsSpent.toFixed(2)} credits`);
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { groupByWorstStatus, groupDomains, isProtocolFinding, worstStatus } from "./findings-forest.ts";
|
||||
import { isPcbExamFinding } from "./layout-finding.ts";
|
||||
import type { Finding } from "./types.ts";
|
||||
import {
|
||||
groupByWorstStatus,
|
||||
groupDomains,
|
||||
isProtocolFinding,
|
||||
protocolEmptyMessage,
|
||||
ruleDomain,
|
||||
worstStatus,
|
||||
} from "./findings-forest";
|
||||
import { isPcbExamFinding } from "./layout-finding";
|
||||
import type { Finding } from "./types";
|
||||
|
||||
function f(partial: Partial<Finding> & Pick<Finding, "designator" | "status">): Finding {
|
||||
return {
|
||||
@@ -72,6 +79,16 @@ test("Error folder lists domains and rules after status, protocol stays out of t
|
||||
assert.equal(groupDomains(groups[0].findings.filter((x) => !isProtocolFinding(x))).length, 1);
|
||||
});
|
||||
|
||||
test("protocol folder label is Protocols, including a stored Italian empty message", () => {
|
||||
const domain = ruleDomain(
|
||||
f({ designator: "J2", status: "ERROR", rule_id: "PE-PRT-L0-001", source: "protocol_l0" }),
|
||||
);
|
||||
assert.equal(domain.label, "Protocols");
|
||||
assert.equal(protocolEmptyMessage("nessun protocollo riconosciuto"), "No protocol recognized.");
|
||||
assert.equal(protocolEmptyMessage(""), "No protocol recognized.");
|
||||
assert.equal(protocolEmptyMessage("USB2 recognized"), "USB2 recognized");
|
||||
});
|
||||
|
||||
test("PE-PLC stays in the PCB exam bucket with PE-BOM", () => {
|
||||
assert.equal(
|
||||
isPcbExamFinding({ source: "placement_check", rule_id: "PE-PLC-002" }),
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/** Group report findings for the tree: status folders, then domains/rules, then Certificazioni. */
|
||||
/** Group report findings for the tree: status folders, then domains/rules, then Certifications. */
|
||||
|
||||
import type { Finding, FindingStatus, ProtocolCertificationSection } from "./types";
|
||||
import {
|
||||
instanceWorstResult,
|
||||
protocolResultToFindingStatus,
|
||||
type ProtocolReportCheck,
|
||||
} from "./protocol-report.ts";
|
||||
} from "./protocol-report";
|
||||
|
||||
export const STATUS_FOLDER: Record<FindingStatus, string> = {
|
||||
ERROR: "Error",
|
||||
@@ -45,7 +45,7 @@ const DOMAIN_LABEL: Record<string, string> = {
|
||||
PDN: "PDN",
|
||||
PD: "USB-PD",
|
||||
AF: "AF Board + AI",
|
||||
PRT: "Protocolli",
|
||||
PRT: "Protocols",
|
||||
MUX: "Pin mux",
|
||||
NC: "NC pins",
|
||||
DEC: "Decoupling",
|
||||
@@ -112,6 +112,17 @@ export function groupByDesignator(findings: Finding[]): DesignatorGroup[] {
|
||||
.map(([designator, items]) => ({ designator, findings: items }));
|
||||
}
|
||||
|
||||
export const PROTOCOL_EMPTY_MESSAGE = "No protocol recognized.";
|
||||
|
||||
/** Tree copy. Stored 2.83 reports still carry the Italian empty phrase. */
|
||||
export function protocolEmptyMessage(message?: string | null): string {
|
||||
const text = (message || "").trim();
|
||||
if (!text || text.toLowerCase() === "nessun protocollo riconosciuto") {
|
||||
return PROTOCOL_EMPTY_MESSAGE;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
export function isProtocolFinding(f: {
|
||||
source?: string | null;
|
||||
rule_id?: string | null;
|
||||
@@ -122,7 +133,7 @@ export function isProtocolFinding(f: {
|
||||
}
|
||||
|
||||
export function ruleDomain(f: Finding): { id: string; label: string } {
|
||||
if (isProtocolFinding(f)) return { id: "PRT", label: "Protocolli" };
|
||||
if (isProtocolFinding(f)) return { id: "PRT", label: "Protocols" };
|
||||
const rid = f.rule_id || "";
|
||||
const m = rid.match(/^PE-([A-Z]+)/);
|
||||
if (m) {
|
||||
@@ -173,7 +184,7 @@ export function groupDomains(findings: Finding[]): DomainGroup[] {
|
||||
/**
|
||||
* Error / Warning / Info folders. A ref lives in the folder of its worst child.
|
||||
* U18 with PE-PLC-002 ERROR + five WARNING → Error, badge ERROR, count 6.
|
||||
* Protocol findings (PE-PRT) are excluded from domain folders — they sit under Certificazioni.
|
||||
* Protocol findings (PE-PRT) are excluded from domain folders — they sit under Certifications.
|
||||
*/
|
||||
export function groupByWorstStatus(findings: Finding[]): StatusGroup[] {
|
||||
const buckets: Record<FindingStatus, DesignatorGroup[]> = {
|
||||
|
||||
@@ -9,9 +9,9 @@ import {
|
||||
protocolResultRank,
|
||||
protocolResultToFindingStatus,
|
||||
sortProtocolChecks,
|
||||
} from "./protocol-report.ts";
|
||||
import { groupByWorstStatus } from "./findings-forest.ts";
|
||||
import type { Finding } from "./types.ts";
|
||||
} from "./protocol-report";
|
||||
import { groupByWorstStatus } from "./findings-forest";
|
||||
import type { Finding } from "./types";
|
||||
|
||||
function f(partial: Partial<Finding> & Pick<Finding, "designator" | "status">): Finding {
|
||||
return {
|
||||
@@ -71,7 +71,7 @@ test("protocol FAIL finding stays in Error folder with WARNING skips on same ref
|
||||
status: "WARNING",
|
||||
rule_id: "PE-PRT-L2-001",
|
||||
source: "protocol_l2",
|
||||
finding: "non certificata a L2 per mancanza di Z",
|
||||
finding: "USB not certified — because Z cannot be calculated from the PCB stackup/geometry. Cited 90 Ω.",
|
||||
}),
|
||||
]);
|
||||
assert.equal(groups[0].label, "Error");
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
/** Stamped from content/changelog.md by scripts/sync-version.mjs. */
|
||||
export const APP_VERSION = "2.83.0";
|
||||
export const APP_VERSION = "2.84.0";
|
||||
export const APP_VERSION_DATE = "2026-09-22";
|
||||
|
||||
@@ -21,5 +21,7 @@ TI files are **source_type VENDOR**, never HDMI Forum STANDARD. `https://pcbsync
|
||||
| `tmds1204.pdf` | TMDS1204 12Gbps HDMI Hybrid Redriver | SLLSF57A – August 2022 / revised April 2024 | `tmds1204-hdmi-sink`, `tmds1204-hdmi-source`; HDMI **2.0 / FRL** common layout `source_type=VENDOR` | **VENDOR** |
|
||||
| `slla633.pdf` | TMDS_CLOCK/FRL_Data Detection Design in HDMI Sink Applications TMDS1204 | SLLA633 – May 2024 | HDMI 2.0+/`tmds1204-*` `sigdet_wakeup` PHY_DEPENDENT (no layout ohms) | **VENDOR** |
|
||||
| `HDMI-FRL-Software-Datasheet-61W6169600.pdf` | HDMI 2.1 FRL Compliance Test Solution Datasheet (Tektronix) | (on file; 4 pages) | **not packed** — test-equipment datasheet, not HDMI Forum Adopter | archived only |
|
||||
| `snla027b.pdf` | AN-807 Reflections: Computations and Waveforms | SNLA027B – May 2004 / revised May 2004 | **not packed** for USB-C vSafe — TI SI, no vSafe5V/vSafe0V | archived only |
|
||||
| `sdaa499.pdf` | Simple Methods to Reduce EMI from a PCB Trace | SDAA499 – September 2026 | **not packed** for USB-C vSafe — TI EMI, no vSafe | archived only |
|
||||
|
||||
Duplicates on Desktop (same MD5, not stored twice here): `USB2_Electrical_Compliance.pdf`, `DVI_Spec_v1.0.pdf`, `USB_TypeC_Functional_Test.pdf`.
|
||||
|
||||
@@ -142,12 +142,14 @@ def test_missing_tr_f_is_visible_skip_no_ohm():
|
||||
assert all(f.rule_id == "PE-AF-002" for f in out)
|
||||
assert len(out) == 1
|
||||
text = out[0].finding
|
||||
assert "Pista ad alta frequenza non controllata per mancanza di" in text
|
||||
assert text.startswith("HF not certified — because")
|
||||
assert "tr" in text and "f" in text
|
||||
assert "mancanza" not in text
|
||||
assert out[0].evidence_status == "INSUFFICIENT"
|
||||
assert out[0].finding_class == "REVIEW"
|
||||
blob = (out[0].finding + out[0].facts).lower()
|
||||
assert "90" not in blob and "50" not in blob and "ω" not in blob and "ohm" not in blob
|
||||
assert "90 Ω" not in blob and "50 Ω" not in blob
|
||||
assert "invented" in blob
|
||||
|
||||
|
||||
def test_short_pair_with_tr_is_not_af():
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
"""HubAudio false findings: exposed-pad names, ESD cites, CC-via-net, Ethernet Z."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.periscopex.af_trace_check import check_af_traces
|
||||
from backend.periscopex.bom_pcb_check import check_bom_pcb_datasheet
|
||||
from backend.periscopex.esd_return_check import check_esd
|
||||
from backend.periscopex.models import (
|
||||
Component,
|
||||
ComponentConstraints,
|
||||
ComponentType,
|
||||
DesignGraph,
|
||||
LayoutFootprint,
|
||||
LayoutGraph,
|
||||
LayoutPad,
|
||||
LayoutSegment,
|
||||
Net,
|
||||
NetType,
|
||||
PackageInfo,
|
||||
Pin,
|
||||
PinConnection,
|
||||
)
|
||||
from backend.periscopex.protocol_l0 import _run_l0_check, l0_findings
|
||||
from backend.periscopex.protocol_recognize import PhysicalBusInstance
|
||||
|
||||
|
||||
def _ic(ref: str, mpn: str, pins: dict[str, str], *, footprint: str = "") -> Component:
|
||||
return Component(
|
||||
reference=ref, value=mpn, footprint=footprint,
|
||||
component_type=ComponentType.IC, mpn=mpn, pins=pins,
|
||||
)
|
||||
|
||||
|
||||
def _net(name: str, *pairs: tuple[str, str]) -> Net:
|
||||
return Net(
|
||||
name=name, net_type=NetType.SIGNAL,
|
||||
pins=[PinConnection(component_ref=r, pin_number=p) for r, p in pairs],
|
||||
)
|
||||
|
||||
|
||||
def _cons(mpn: str, numbers: list[str], pin_count: int) -> ComponentConstraints:
|
||||
return ComponentConstraints(
|
||||
mpn=mpn,
|
||||
package_info=PackageInfo(base_family="QFN", package=f"QFN-{pin_count}", pin_count=pin_count),
|
||||
pintable=[Pin(number=n, name=n) for n in numbers],
|
||||
absolute_maximum_ratings=[],
|
||||
rules=[],
|
||||
)
|
||||
|
||||
|
||||
def _layout(ref: str, pads: list[tuple[str, str]], *, footprint: str) -> LayoutGraph:
|
||||
return LayoutGraph(
|
||||
footprints={
|
||||
ref: LayoutFootprint(
|
||||
reference=ref, footprint=footprint, x=0, y=0,
|
||||
pads=[
|
||||
LayoutPad(number=n, x=0, y=0, net="GND", pinfunction=pf)
|
||||
for n, pf in pads
|
||||
],
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _bom(ref: str, mpn: str, numbers: list[str], pads: list[tuple[str, str]], pin_count: int):
|
||||
graph = DesignGraph(components={
|
||||
ref: _ic(ref, mpn, {n: "N" for n, _pf in pads if n}, footprint="Lib:Part"),
|
||||
})
|
||||
# Schematic pins follow the pintable numbers that are real contacts.
|
||||
graph.components[ref].pins = {n: "N" for n in numbers if n not in {"EP", "THERMAL PAD"}}
|
||||
layout = _layout(ref, pads, footprint="Lib:Part")
|
||||
findings = check_bom_pcb_datasheet(graph, {mpn: _cons(mpn, numbers, pin_count)}, layout)
|
||||
return [f for f in findings if f.rule_id == "PE-BOM-011"]
|
||||
|
||||
|
||||
def test_u16_ep_matches_pad_41():
|
||||
"""AXP2101: pintable EP, footprint pad 41 / EP_41."""
|
||||
hits = _bom(
|
||||
"U16", "AXP2101", ["1", "EP"],
|
||||
[("1", "CHGLED_1"), ("41", "EP_41")],
|
||||
40,
|
||||
)
|
||||
assert hits == []
|
||||
|
||||
|
||||
def test_u18_ep_matches_pad_89():
|
||||
"""ADAU1467: pintable EP, footprint pad 89 / EP_89."""
|
||||
hits = _bom(
|
||||
"U18", "ADAU1467", ["1", "EP"],
|
||||
[("1", "DGND_1_1"), ("89", "EP_89")],
|
||||
88,
|
||||
)
|
||||
assert hits == []
|
||||
|
||||
|
||||
def test_u19_ep_matches_pad_25_vss():
|
||||
"""LAN8720A: pintable EP, VQFN-24 land is pad 25 / VSS_25."""
|
||||
hits = _bom(
|
||||
"U19", "LAN8720A", ["1", "EP"],
|
||||
[("1", "VDD2A_1"), ("25", "VSS_25")],
|
||||
24,
|
||||
)
|
||||
assert hits == []
|
||||
|
||||
|
||||
def test_u5_thermal_pad_matches_epad_29():
|
||||
"""TAC5212: pintable THERMAL PAD, footprint pad 29 / EPAD_29."""
|
||||
hits = _bom(
|
||||
"U5", "XTAC5212", ["1", "THERMAL PAD"],
|
||||
[("1", "DREG_1"), ("29", "EPAD_29")],
|
||||
24,
|
||||
)
|
||||
assert hits == []
|
||||
|
||||
|
||||
def test_exposed_pad_absent_from_footprint_stays_error():
|
||||
hits = _bom(
|
||||
"U9", "BARE", ["1", "EP"],
|
||||
[("1", "PIN_1")],
|
||||
24,
|
||||
)
|
||||
assert hits
|
||||
assert any("EP" in (f.finding or "") for f in hits)
|
||||
|
||||
|
||||
def _esd_graph(net: str, *, j_fp: str = "", j_value: str = "JACK") -> DesignGraph:
|
||||
return DesignGraph(
|
||||
components={
|
||||
"J1": Component(
|
||||
reference="J1", value=j_value, footprint=j_fp,
|
||||
component_type=ComponentType.CONNECTOR, mpn="",
|
||||
pins={"13": net},
|
||||
),
|
||||
"U19": _ic("U19", "LAN8720A", {"1": net}),
|
||||
},
|
||||
nets={net: _net(net, ("J1", "13"), ("U19", "1"))},
|
||||
)
|
||||
|
||||
|
||||
def test_esd_does_not_say_datasheet_specified_without_a_cite():
|
||||
findings = check_esd(_esd_graph("USB_DP"))
|
||||
assert findings and findings[0].rule_id == "PE-ESD-001"
|
||||
blob = f"{findings[0].action} {findings[0].recommendation}"
|
||||
assert "datasheet-specified" not in blob
|
||||
|
||||
|
||||
def test_esd_quotes_datasheet_when_part_and_section_exist():
|
||||
cons = ComponentConstraints(
|
||||
mpn="LAN8720A",
|
||||
pintable=[],
|
||||
absolute_maximum_ratings=[],
|
||||
rules=[],
|
||||
layout_rules=[{
|
||||
"kind": "esd",
|
||||
"document": "LAN8720A datasheet",
|
||||
"section": "3.2",
|
||||
"page": "12",
|
||||
"note": "ESD on USB_DP",
|
||||
}],
|
||||
)
|
||||
findings = check_esd(_esd_graph("USB_DP"), {"LAN8720A": cons})
|
||||
assert findings
|
||||
blob = f"{findings[0].action} {findings[0].finding}"
|
||||
assert "datasheet-specified" in blob
|
||||
assert "LAN8720A datasheet" in blob
|
||||
assert "3.2" in blob
|
||||
|
||||
|
||||
def test_3v3_ethernet_rail_is_not_an_esd_warning():
|
||||
assert check_esd(_esd_graph("3V3_ETHERNET")) == []
|
||||
|
||||
|
||||
def test_vbus_without_cite_is_not_an_esd_warning():
|
||||
graph = _esd_graph("VBUS")
|
||||
graph.components["U16"] = _ic("U16", "AXP2101", {"37": "VBUS"})
|
||||
graph.components["J2"] = Component(
|
||||
reference="J2", value="USB_C", footprint="Connector_USB:USB_C_Receptacle",
|
||||
component_type=ComponentType.CONNECTOR,
|
||||
pins={"A4": "VBUS"},
|
||||
)
|
||||
graph.nets = {"VBUS": _net("VBUS", ("J2", "A4"), ("U16", "37"))}
|
||||
findings = check_esd(graph)
|
||||
assert findings == []
|
||||
blob = " ".join(f.action or "" for f in findings)
|
||||
assert "datasheet-specified" not in blob
|
||||
|
||||
|
||||
def test_optical_spdif_is_not_an_esd_warning():
|
||||
findings = check_esd(_esd_graph(
|
||||
"SPIF_IN",
|
||||
j_fp="OptoDevice:Broadcom_AFBR-16xxZ_Horizontal",
|
||||
j_value="TOSLINK",
|
||||
))
|
||||
assert findings == []
|
||||
|
||||
|
||||
def test_unverified_spdif_warns_it_was_not_seen_as_optical():
|
||||
findings = check_esd(_esd_graph("SPIF_OUT", j_fp="Connector:PinHeader"))
|
||||
assert findings
|
||||
assert findings[0].status == "WARNING"
|
||||
assert "not verified as optical" in (findings[0].finding or "")
|
||||
assert "datasheet-specified" not in (findings[0].action or "")
|
||||
|
||||
|
||||
def _cc_inst() -> PhysicalBusInstance:
|
||||
return PhysicalBusInstance(
|
||||
instance_id="usb-c-usb2-receptacle:J2",
|
||||
logical_protocol_id="usb2-hs",
|
||||
physical_interface_id="usb-c-usb2-receptacle",
|
||||
pcb_relevant="YES",
|
||||
confidence=1.0,
|
||||
evidence_kind="pinout",
|
||||
recognition_status="RECOGNIZED",
|
||||
host_ref="J2",
|
||||
nets=["Net-(J2-A5)", "Net-(J2-B5)"],
|
||||
)
|
||||
|
||||
|
||||
def _cc_graph(*, both: bool) -> DesignGraph:
|
||||
comps = {
|
||||
"J2": Component(
|
||||
reference="J2",
|
||||
value="USB_C_Receptacle_USB2.0_16P",
|
||||
footprint="Connector_USB:USB_C_Receptacle_HRO_TYPE-C-31-M-12",
|
||||
component_type=ComponentType.CONNECTOR,
|
||||
pins={"A5": "Net-(J2-A5)", "B5": "Net-(J2-B5)", "A4": "VBUS"},
|
||||
),
|
||||
"R1": Component(
|
||||
reference="R1", value="5.1k", footprint="R_0603",
|
||||
component_type=ComponentType.RESISTOR,
|
||||
pins={"1": "Net-(J2-A5)", "2": "GND"},
|
||||
),
|
||||
}
|
||||
nets = {
|
||||
"Net-(J2-A5)": _net("Net-(J2-A5)", ("J2", "A5"), ("R1", "1")),
|
||||
"Net-(J2-B5)": _net("Net-(J2-B5)", ("J2", "B5")),
|
||||
"GND": _net("GND", ("R1", "2")),
|
||||
}
|
||||
if both:
|
||||
comps["R2"] = Component(
|
||||
reference="R2", value="5.1k", footprint="R_0603",
|
||||
component_type=ComponentType.RESISTOR,
|
||||
pins={"1": "Net-(J2-B5)", "2": "GND"},
|
||||
)
|
||||
nets["Net-(J2-B5)"] = _net("Net-(J2-B5)", ("J2", "B5"), ("R2", "1"))
|
||||
nets["GND"] = _net("GND", ("R1", "2"), ("R2", "2"))
|
||||
return DesignGraph(components=comps, nets=nets)
|
||||
|
||||
|
||||
def test_cc_rd_present_on_unnamed_nets_does_not_fail():
|
||||
row = _run_l0_check(_cc_graph(both=True), _cc_inst(), "cc_rd_rp", "MANDATORY")
|
||||
assert row.result == "PASS"
|
||||
assert "5.1" in row.notes
|
||||
assert "CC1/CC2 net not present" not in row.notes
|
||||
findings = l0_findings(_cc_inst(), [row])
|
||||
assert not any(f.rule_id == "PE-PRT-L0-001" for f in findings)
|
||||
|
||||
|
||||
def test_cc_rd_missing_on_pin_net_fails():
|
||||
row = _run_l0_check(_cc_graph(both=False), _cc_inst(), "cc_rd_rp", "MANDATORY")
|
||||
assert row.result == "FAIL"
|
||||
assert "B5" in row.notes
|
||||
assert "CC1/CC2 net not present" not in row.notes
|
||||
assert "5.1" in row.notes
|
||||
findings = l0_findings(_cc_inst(), [row])
|
||||
assert any(f.rule_id == "PE-PRT-L0-001" and f.status == "ERROR" for f in findings)
|
||||
|
||||
|
||||
def _eth_graph(mpn: str, *, value: str = "") -> DesignGraph:
|
||||
return DesignGraph(
|
||||
components={
|
||||
"J1": Component(
|
||||
reference="J1", value="RJ45",
|
||||
footprint="Connector_RJ:RJ45_Abracon_ARJP11A-MA_Horizontal",
|
||||
component_type=ComponentType.CONNECTOR,
|
||||
pins={"9": "RJ45_TXP", "10": "RJ45_TXN"},
|
||||
),
|
||||
"U19": _ic("U19", mpn, {"21": "RJ45_TXP", "20": "RJ45_TXN"}, footprint="VQFN-24"),
|
||||
},
|
||||
nets={
|
||||
"RJ45_TXP": _net("RJ45_TXP", ("J1", "9"), ("U19", "21")),
|
||||
"RJ45_TXN": _net("RJ45_TXN", ("J1", "10"), ("U19", "20")),
|
||||
},
|
||||
) if not value else DesignGraph(
|
||||
components={
|
||||
"J1": Component(
|
||||
reference="J1", value="RJ45",
|
||||
footprint="Connector_RJ:RJ45",
|
||||
component_type=ComponentType.CONNECTOR,
|
||||
pins={"9": "RJ45_TXP", "10": "RJ45_TXN"},
|
||||
),
|
||||
"U19": Component(
|
||||
reference="U19", value=value, footprint="",
|
||||
component_type=ComponentType.IC, mpn=mpn,
|
||||
pins={"21": "RJ45_TXP", "20": "RJ45_TXN"},
|
||||
),
|
||||
},
|
||||
nets={
|
||||
"RJ45_TXP": _net("RJ45_TXP", ("J1", "9"), ("U19", "21")),
|
||||
"RJ45_TXN": _net("RJ45_TXN", ("J1", "10"), ("U19", "20")),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _eth_layout() -> LayoutGraph:
|
||||
return LayoutGraph(
|
||||
segments=[
|
||||
LayoutSegment(start=(0, 0), end=(20, 0), width=0.2, layer="F.Cu", net="RJ45_TXP"),
|
||||
LayoutSegment(start=(0, 0.2), end=(20, 0.2), width=0.2, layer="F.Cu", net="RJ45_TXN"),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _eth_findings(graph: DesignGraph, monkeypatch, z: float | None):
|
||||
if z is not None:
|
||||
monkeypatch.setattr(
|
||||
"backend.periscopex.af_trace_check._pair_z_ohm",
|
||||
lambda layout, unit: z,
|
||||
)
|
||||
return [f for f in check_af_traces(graph, {}, _eth_layout()) if f.rule_id == "PE-AF-002"]
|
||||
|
||||
|
||||
def test_lan8720_pair_without_z_is_error_with_100base_cite(monkeypatch):
|
||||
findings = _eth_findings(_eth_graph("LAN8720A"), monkeypatch, None)
|
||||
assert len(findings) == 1
|
||||
f = findings[0]
|
||||
assert f.status == "ERROR"
|
||||
blob = f"{f.finding} {f.action} {f.requirement}"
|
||||
assert f.finding.startswith("Ethernet not certified — because Z cannot be calculated")
|
||||
assert "100" in blob and "25.4.9" in blob
|
||||
assert "stackup" in blob
|
||||
assert "Fornire" not in blob
|
||||
assert "mancanza di tr" not in blob.lower()
|
||||
assert "mancanza di f" not in blob.lower()
|
||||
assert "90" not in blob
|
||||
assert "Clause 40" not in blob
|
||||
assert "1000BASE" not in blob
|
||||
assert "PASS" not in f.finding
|
||||
|
||||
|
||||
def test_lan8720_pair_z_inside_cite_is_pass(monkeypatch):
|
||||
findings = _eth_findings(_eth_graph("LAN8720A"), monkeypatch, 100.0)
|
||||
assert len(findings) == 1
|
||||
assert findings[0].finding.startswith("Ethernet certified —")
|
||||
assert findings[0].status == "INFO"
|
||||
assert "RJ45_TXP" in (findings[0].facts or "") or "RJ45_TXP" in findings[0].finding
|
||||
assert "RJ45_TXN" in (findings[0].facts or "") or "RJ45_TXN" in findings[0].finding
|
||||
assert "25.4.9" in findings[0].finding
|
||||
|
||||
|
||||
def test_lan8720_pair_z_outside_cite_is_fail(monkeypatch):
|
||||
findings = _eth_findings(_eth_graph("LAN8720A"), monkeypatch, 90.0)
|
||||
assert len(findings) == 1
|
||||
assert findings[0].finding.startswith("Ethernet not certified — because Z")
|
||||
assert findings[0].status == "ERROR"
|
||||
assert "PASS" not in findings[0].finding
|
||||
assert "25.4.9" in findings[0].finding
|
||||
|
||||
|
||||
def test_gigabit_phy_uses_clause_40_not_100base(monkeypatch):
|
||||
findings = _eth_findings(
|
||||
_eth_graph("RTL8211F", value="1000BASE-T"),
|
||||
monkeypatch,
|
||||
None,
|
||||
)
|
||||
assert len(findings) == 1
|
||||
blob = findings[0].finding
|
||||
assert findings[0].status == "ERROR"
|
||||
assert "Clause 40" in blob
|
||||
assert "25.4.9" not in blob
|
||||
assert "PASS" not in blob
|
||||
@@ -0,0 +1,134 @@
|
||||
"""USB Type-C D+/D− one-line certification; J2 has no WARNING wall."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.periscopex.models import (
|
||||
Component,
|
||||
ComponentType,
|
||||
DesignGraph,
|
||||
LayoutDielectric,
|
||||
LayoutGraph,
|
||||
LayoutSegment,
|
||||
LayoutStackup,
|
||||
Net,
|
||||
NetType,
|
||||
PinConnection,
|
||||
ResistorSpecs,
|
||||
)
|
||||
from backend.periscopex.protocol_l0 import protocol_exam
|
||||
from backend.periscopex.protocol_l2 import certify_l2, usb_pair_z_ohm
|
||||
from backend.periscopex.protocol_recognize import recognize_physical_buses
|
||||
|
||||
|
||||
def _ic(ref: str, pins: dict[str, str], *, mpn: str = "") -> Component:
|
||||
return Component(
|
||||
reference=ref, value=mpn or ref, footprint="",
|
||||
component_type=ComponentType.IC, mpn=mpn or None, pins=pins,
|
||||
)
|
||||
|
||||
|
||||
def _net(name: str, *pairs: tuple[str, str]) -> Net:
|
||||
return Net(
|
||||
name=name, net_type=NetType.SIGNAL,
|
||||
pins=[PinConnection(component_ref=r, pin_number=p) for r, p in pairs],
|
||||
)
|
||||
|
||||
|
||||
def _usb_c_graph() -> DesignGraph:
|
||||
return DesignGraph(
|
||||
components={
|
||||
"U1": _ic("U1", {"1": "USB_D+", "2": "USB_D-"}, mpn="CH340E"),
|
||||
"J2": Component(
|
||||
reference="J2", value="USB_C",
|
||||
footprint="Connector_USB:USB_C_Receptacle",
|
||||
component_type=ComponentType.CONNECTOR,
|
||||
pins={"A6": "USB_D+", "A7": "USB_D-", "A5": "CC1", "B5": "CC2",
|
||||
"A4": "VBUS", "A1": "GND"},
|
||||
),
|
||||
"R1": Component(
|
||||
reference="R1", value="5.1k", footprint="",
|
||||
component_type=ComponentType.RESISTOR,
|
||||
pins={"1": "CC1", "2": "GND"},
|
||||
specs=ResistorSpecs(value_ohms=5100.0, value_formatted="5.1k"),
|
||||
),
|
||||
"R2": Component(
|
||||
reference="R2", value="5.1k", footprint="",
|
||||
component_type=ComponentType.RESISTOR,
|
||||
pins={"1": "CC2", "2": "GND"},
|
||||
specs=ResistorSpecs(value_ohms=5100.0, value_formatted="5.1k"),
|
||||
),
|
||||
},
|
||||
nets={
|
||||
"USB_D+": _net("USB_D+", ("U1", "1"), ("J2", "A6")),
|
||||
"USB_D-": _net("USB_D-", ("U1", "2"), ("J2", "A7")),
|
||||
"CC1": _net("CC1", ("J2", "A5"), ("R1", "1")),
|
||||
"CC2": _net("CC2", ("J2", "B5"), ("R2", "1")),
|
||||
"VBUS": _net("VBUS", ("J2", "A4")),
|
||||
"GND": Net(
|
||||
name="GND", net_type=NetType.GROUND,
|
||||
pins=[
|
||||
PinConnection(component_ref="J2", pin_number="A1"),
|
||||
PinConnection(component_ref="R1", pin_number="2"),
|
||||
PinConnection(component_ref="R2", pin_number="2"),
|
||||
],
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _stack() -> LayoutStackup:
|
||||
return LayoutStackup(
|
||||
copper_layers=["F.Cu", "B.Cu"],
|
||||
dielectrics=[LayoutDielectric(name="core", er=4.5, height_mm=0.15)],
|
||||
copper_thickness_mm=0.035,
|
||||
)
|
||||
|
||||
|
||||
def test_usb_missing_z_is_one_not_certified_line():
|
||||
sec, findings = protocol_exam(_usb_c_graph())
|
||||
usb = [i for i in sec.recognized_instances if "usb" in (i.get("logical_protocol_id") or "")]
|
||||
assert usb
|
||||
notes = [
|
||||
c.get("notes") or ""
|
||||
for row in usb
|
||||
for c in (row.get("report_checks") or row.get("l2_checks") or [])
|
||||
]
|
||||
cert = [n for n in notes if n.startswith("USB not certified —") or n.startswith("USB certified —")]
|
||||
assert len(cert) == 1
|
||||
assert cert[0].startswith("USB not certified — because Z cannot be calculated")
|
||||
assert "90" in cert[0]
|
||||
# No Italian warning wall on missing fields.
|
||||
j2 = [f for f in findings if f.designator == "J2" and (f.rule_id or "").startswith("PE-PRT-L")]
|
||||
assert not any("mancanza" in (f.finding or "") for f in j2)
|
||||
assert not any(f.rule_id == "PE-PRT-L1-001" for f in j2)
|
||||
assert not any(f.rule_id == "PE-PRT-L3-001" for f in j2)
|
||||
# At most one L2 cert finding for the pair (optional L0 FAIL allowed separately).
|
||||
l2 = [f for f in j2 if f.rule_id == "PE-PRT-L2-002"]
|
||||
assert len(l2) <= 1
|
||||
|
||||
|
||||
def test_usb_calculated_z_inside_cite_is_certified(monkeypatch):
|
||||
graph = _usb_c_graph()
|
||||
layout = LayoutGraph(
|
||||
segments=[
|
||||
LayoutSegment(start=(0, 0), end=(20, 0), width=0.2, layer="F.Cu", net="USB_D+"),
|
||||
LayoutSegment(start=(0, 0.15), end=(20, 0.15), width=0.2, layer="F.Cu", net="USB_D-"),
|
||||
],
|
||||
stackup=_stack(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"backend.periscopex.protocol_l2.usb_pair_z_ohm",
|
||||
lambda layout, nets, impedance_nets: (90.0, ""),
|
||||
)
|
||||
insts = recognize_physical_buses(graph)
|
||||
_by, findings = certify_l2(graph, insts, layout=layout)
|
||||
lines = [f.finding for f in findings if (f.finding or "").startswith("USB certified —")]
|
||||
assert len(lines) == 1
|
||||
assert "90" in lines[0]
|
||||
assert "not invented" not in lines[0].lower()
|
||||
|
||||
|
||||
def test_usb_pair_z_reports_missing_geometry():
|
||||
z, missing = usb_pair_z_ohm(None, ("USB_D+", "USB_D-"), None)
|
||||
assert z is None
|
||||
assert "stackup" in missing or "geometry" in missing
|
||||
@@ -0,0 +1,131 @@
|
||||
"""not_reviewed count matches list; pcb_review error is not a blanket label."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from backend.periscopex.models import Component, ComponentConstraints, ComponentType, DesignGraph, Pin
|
||||
from backend.periscopex.pcb_checks import merge_schema_pcb_reports
|
||||
from backend.periscopex.review_parse import ReviewResult
|
||||
from backend.services.pcb_validation import review_pcb_ics
|
||||
|
||||
|
||||
def test_merge_expands_joined_designators_and_matches_count():
|
||||
schema = {
|
||||
"findings": [],
|
||||
"coverage": {"U1": ["power"]},
|
||||
"not_reviewed": [
|
||||
{"designator": "U2,U3,U4", "reason": "no datasheet PDF"},
|
||||
],
|
||||
}
|
||||
pcb = {
|
||||
"findings": [],
|
||||
"coverage": {"U5": ["layout"]},
|
||||
"not_reviewed": [
|
||||
{"designator": "U6", "reason": "no library extraction — run schematic review first"},
|
||||
{"designator": "U1", "reason": "pcb_review error"}, # reviewed → drop
|
||||
{"designator": "U7", "reason": "pcb_review error"}, # → review_errors
|
||||
],
|
||||
"review_errors": {},
|
||||
}
|
||||
merged = merge_schema_pcb_reports(schema, pcb)
|
||||
nr = merged["not_reviewed"]
|
||||
refs = [r["designator"] for r in nr]
|
||||
assert refs == ["U2", "U3", "U4", "U6"]
|
||||
assert len(nr) == len(refs)
|
||||
assert "U1" not in refs # covered
|
||||
assert "U7" not in refs
|
||||
assert merged["review_errors"]["U7"] == "pcb_review error"
|
||||
assert "pcb_review error" not in {r["reason"] for r in nr}
|
||||
|
||||
|
||||
def test_merge_does_not_list_reviewed_as_not_reviewed():
|
||||
schema = {
|
||||
"findings": [],
|
||||
"coverage": {"U10": ["abs_max"], "U11": ["pinout"]},
|
||||
"not_reviewed": [{"designator": "U10", "reason": "no datasheet PDF"}],
|
||||
}
|
||||
pcb = {
|
||||
"findings": [],
|
||||
"coverage": {"U11": ["layout"]},
|
||||
"not_reviewed": [{"designator": "U11", "reason": "pcb_review error"}],
|
||||
}
|
||||
merged = merge_schema_pcb_reports(schema, pcb)
|
||||
assert merged["not_reviewed"] == []
|
||||
|
||||
|
||||
def test_pcb_review_exception_goes_to_review_errors_not_not_reviewed():
|
||||
graph = DesignGraph(
|
||||
components={
|
||||
"U1": Component(
|
||||
reference="U1", value="LAN8720A", footprint="",
|
||||
component_type=ComponentType.IC, mpn="LAN8720A",
|
||||
pins={"1": "TXEN"},
|
||||
),
|
||||
},
|
||||
nets={},
|
||||
)
|
||||
cons = ComponentConstraints(
|
||||
mpn="LAN8720A",
|
||||
pintable=[Pin(number="1", name="TXEN")],
|
||||
absolute_maximum_ratings=[],
|
||||
rules=[],
|
||||
)
|
||||
|
||||
async def _boom(*_a, **_k):
|
||||
raise RuntimeError("model timeout")
|
||||
|
||||
async def _run():
|
||||
with patch(
|
||||
"backend.services.pcb_validation.review_ic_async",
|
||||
new=AsyncMock(side_effect=_boom),
|
||||
):
|
||||
return await review_pcb_ics(
|
||||
graph, {"LAN8720A": cons}, None, None, None, Path("/tmp"),
|
||||
)
|
||||
|
||||
findings, coverage, skipped, errors = asyncio.run(_run())
|
||||
assert findings == []
|
||||
assert coverage == {}
|
||||
assert skipped == []
|
||||
assert "U1" in errors
|
||||
assert "RuntimeError" in errors["U1"]
|
||||
assert "pcb_review error" not in errors["U1"]
|
||||
|
||||
|
||||
def test_successful_pcb_review_is_covered_not_skipped():
|
||||
graph = DesignGraph(
|
||||
components={
|
||||
"U1": Component(
|
||||
reference="U1", value="X", footprint="",
|
||||
component_type=ComponentType.IC, mpn="HASPINTABLE",
|
||||
pins={"1": "GND"},
|
||||
),
|
||||
},
|
||||
nets={},
|
||||
)
|
||||
cons = ComponentConstraints(
|
||||
mpn="HASPINTABLE",
|
||||
pintable=[Pin(number="1", name="GND")],
|
||||
absolute_maximum_ratings=[],
|
||||
rules=[],
|
||||
)
|
||||
|
||||
async def _ok(*_a, **_k):
|
||||
return ReviewResult([], []), {}
|
||||
|
||||
async def _run():
|
||||
with patch(
|
||||
"backend.services.pcb_validation.review_ic_async",
|
||||
new=AsyncMock(side_effect=_ok),
|
||||
):
|
||||
return await review_pcb_ics(
|
||||
graph, {"HASPINTABLE": cons}, None, None, None, Path("/tmp"),
|
||||
)
|
||||
|
||||
_f, coverage, skipped, errors = asyncio.run(_run())
|
||||
assert coverage == {"U1": ["layout"]}
|
||||
assert skipped == []
|
||||
assert errors == {}
|
||||
@@ -619,8 +619,9 @@ def test_pcb_ai_skips_without_library_extraction():
|
||||
graph, {}, None, None, None, Path("/tmp"),
|
||||
)
|
||||
|
||||
_f, _c, skipped = asyncio.run(_run())
|
||||
_f, _c, skipped, errors = asyncio.run(_run())
|
||||
assert skipped
|
||||
assert errors == {}
|
||||
assert "library extraction" in skipped[0]["reason"]
|
||||
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ def test_reject_same_logical_and_physical_id():
|
||||
def test_empty_report_section_has_no_z():
|
||||
section = empty_protocol_section()
|
||||
dumped = section.model_dump()
|
||||
assert section.message == "nessun protocollo riconosciuto"
|
||||
assert section.message == "No protocol recognized."
|
||||
assert section.recognized_instances == []
|
||||
assert dumped.get("max_level_reached") is None
|
||||
blob = json.dumps(dumped)
|
||||
@@ -238,7 +238,7 @@ def test_empty_report_section_has_no_z():
|
||||
summary={"ERROR": 0, "WARNING": 0, "INFO": 0},
|
||||
protocol_certification=dumped,
|
||||
)
|
||||
assert report.protocol_certification["message"] == "nessun protocollo riconosciuto"
|
||||
assert report.protocol_certification["message"] == "No protocol recognized."
|
||||
|
||||
|
||||
def test_pcie_cxl_physical_packs_are_empty_numbers():
|
||||
|
||||
@@ -155,8 +155,7 @@ def test_usb_no_layout_is_visible_skip_not_pass():
|
||||
assert rows
|
||||
assert all(r.result != "PASS" or r.check == "never" for r in rows)
|
||||
assert any(r.result == "UNKNOWN" for r in rows)
|
||||
assert any(f.rule_id == "PE-PRT-L1-001" for f in findings)
|
||||
assert any("non certificata a L1" in (f.finding or "") for f in findings)
|
||||
assert not any(f.rule_id == "PE-PRT-L1-001" for f in findings)
|
||||
|
||||
|
||||
def test_axi_internal_l1_not_applicable():
|
||||
|
||||
@@ -109,21 +109,25 @@ def test_usb_z_missing_source_never_invents_90():
|
||||
rows, findings, _ = _l2_for(_usb_connected(), "usb2", impedance_nets=zrep)
|
||||
z = [r for r in rows if r.check == "differential_impedance"]
|
||||
assert z
|
||||
assert z[0].result in {"MISSING_SOURCE", "UNKNOWN"}
|
||||
assert z[0].result != "PASS"
|
||||
blob = json.dumps(z[0].model_dump())
|
||||
assert "90" not in blob
|
||||
assert any(f.rule_id == "PE-PRT-L2-001" for f in findings)
|
||||
assert any("non certificata a L2" in (f.finding or "") for f in findings)
|
||||
assert z[0].result == "FAIL"
|
||||
assert z[0].limit_ohm == 90.0
|
||||
assert z[0].measured_ohm is None
|
||||
line = z[0].notes
|
||||
assert line.startswith("USB not certified — because Z cannot be calculated")
|
||||
assert "90" in line
|
||||
assert "not invented" not in line.lower()
|
||||
assert not any(f.rule_id == "PE-PRT-L2-001" for f in findings)
|
||||
assert any(f.finding == line for f in findings)
|
||||
|
||||
|
||||
def test_usb_z_skip_when_no_stackup_measurement():
|
||||
rows, findings, _ = _l2_for(_usb_connected(), "usb2")
|
||||
z = [r for r in rows if r.check == "differential_impedance"]
|
||||
assert z
|
||||
assert z[0].result in {"MISSING_SOURCE", "UNKNOWN"}
|
||||
assert z[0].result == "FAIL"
|
||||
assert z[0].measured_ohm is None
|
||||
assert any("mancanza di Z" in (f.finding or "") for f in findings)
|
||||
assert z[0].limit_ohm == 90.0
|
||||
assert any(f.finding.startswith("USB not certified —") for f in findings)
|
||||
|
||||
|
||||
def test_cited_pack_z_pass_and_fail():
|
||||
@@ -220,7 +224,7 @@ def test_ddr_impedance_phy_dependent_not_invented_ohm():
|
||||
blob = json.dumps(z[0].model_dump())
|
||||
assert "40" not in blob
|
||||
assert "90" not in blob
|
||||
assert any(f.rule_id == "PE-PRT-L2-001" for f in findings)
|
||||
assert not any(f.rule_id == "PE-PRT-L2-001" for f in findings)
|
||||
|
||||
|
||||
def test_length_is_not_delay_timing_unknown():
|
||||
|
||||
@@ -173,6 +173,7 @@ def test_remaining_margin_is_total_minus_used():
|
||||
|
||||
|
||||
def test_usb_hdmi_pcie_skip_without_channel_data():
|
||||
"""No channel FACT → no L3 warning wall (silence, not Italian mancanza)."""
|
||||
for graph, token in ((_usb_connected(), "usb"), (_hdmi_graph(), "hdmi"), (_pcie_graph(), "pcie")):
|
||||
sec, findings = protocol_exam(graph)
|
||||
assert sec.max_level_reached == "L3"
|
||||
@@ -183,17 +184,9 @@ def test_usb_hdmi_pcie_skip_without_channel_data():
|
||||
or token in str(r.get("physical_interface_id")).lower()
|
||||
)
|
||||
l3 = row["l3_checks"]
|
||||
assert l3
|
||||
names = {c["check"] for c in l3}
|
||||
assert {"timing_budget", "insertion_loss", "return_loss", "crosstalk", "channel"} <= names
|
||||
assert all(c["result"] != "PASS" for c in l3)
|
||||
notes = " ".join(c.get("notes") or "" for c in l3)
|
||||
assert "non certificata a L3 per mancanza" in notes
|
||||
assert "OpenEMS" in notes
|
||||
blob = json.dumps(l3)
|
||||
assert "90" not in blob
|
||||
assert any(f.rule_id == "PE-PRT-L3-001" for f in findings)
|
||||
assert "s21" not in blob.lower() or "invent" in notes.lower()
|
||||
assert l3 == []
|
||||
assert not any(f.rule_id == "PE-PRT-L3-001" for f in findings)
|
||||
assert not any("mancanza" in (f.finding or "") for f in findings if f.source == "protocol_l3")
|
||||
|
||||
|
||||
def test_axi_l3_not_applicable_not_fail():
|
||||
@@ -269,13 +262,8 @@ def test_raw_touchstone_without_fact_is_skip_not_invented():
|
||||
inst = _inst()
|
||||
data = {inst.instance_id: {"sparam_file": "lane.s4p", "touchstone": "lane.s4p"}}
|
||||
rows = certify_instance_l3(inst, iface, channel_data=data)
|
||||
assert all(r.result != "PASS" for r in rows)
|
||||
notes = " ".join(r.notes for r in rows)
|
||||
assert "non certificata a L3" in notes
|
||||
assert "invent" in notes.lower() or "non inventati" in notes.lower() or "not invented" in notes.lower()
|
||||
blob = json.dumps([r.model_dump() for r in rows])
|
||||
# no synthesized S21 numbers
|
||||
assert '"measured_db": null' in blob or all(r.measured_db is None for r in rows)
|
||||
# Raw S-param file is not reduced channel FACT — omit L3 (no warning wall).
|
||||
assert rows == []
|
||||
|
||||
|
||||
def test_openems_method_is_explicit_skip():
|
||||
@@ -289,8 +277,8 @@ def test_openems_method_is_explicit_skip():
|
||||
}
|
||||
}
|
||||
rows = certify_instance_l3(inst, iface, channel_data=data)
|
||||
notes = " ".join(r.notes for r in rows)
|
||||
assert "non certificata a L3" in notes
|
||||
# OpenEMS/FEM is out of product — omit L3 rather than invent S-parameters.
|
||||
assert rows == []
|
||||
assert all(r.result != "PASS" for r in rows)
|
||||
|
||||
|
||||
@@ -298,19 +286,16 @@ def test_no_sparam_invention_on_empty_channel_data():
|
||||
insts = recognize_physical_buses(_usb_connected())
|
||||
by, findings = certify_l3(insts, channel_data=None)
|
||||
rows = [r for lst in by.values() for r in lst]
|
||||
blob = json.dumps([r.model_dump() for r in rows])
|
||||
assert "s21" not in blob.lower()
|
||||
assert all(r.measured_db is None for r in rows)
|
||||
assert any("mancanza" in r.notes for r in rows)
|
||||
assert any(f.rule_id == "PE-PRT-L3-001" for f in findings)
|
||||
assert rows == []
|
||||
assert not any(f.rule_id == "PE-PRT-L3-001" for f in findings)
|
||||
|
||||
|
||||
def test_protocol_exam_attaches_l3_and_does_not_call_l0_electrical():
|
||||
sec, _ = protocol_exam(_usb_connected())
|
||||
row = sec.recognized_instances[0]
|
||||
assert row.get("l3_checks")
|
||||
assert all(c.get("level") == "L3" for c in row["l3_checks"])
|
||||
notes = " ".join(c.get("notes") or "" for c in row["l3_checks"])
|
||||
assert "L0/L1 are not electrical" in notes
|
||||
# L3 omitted without channel FACT; L0/L1/L2 still attached.
|
||||
assert row.get("l3_checks") == []
|
||||
assert row.get("l0_checks")
|
||||
assert row.get("l2_checks")
|
||||
l0notes = json.dumps(row.get("l0_checks") or [])
|
||||
assert "ohm" not in l0notes.lower() or "not" in l0notes.lower()
|
||||
|
||||
@@ -123,7 +123,17 @@ def test_type_c_rp_rd_from_cabcon_r25_vbus_volts_unknown():
|
||||
assert by["t_vbuson_max"].source.page == "247"
|
||||
assert "2.5" in by["t_vbuson_max"].source.revision
|
||||
assert by["vsafe5v"].value_kind == "UNKNOWN"
|
||||
assert "vSafe5V" in (by["vsafe5v"].needed_document or "")
|
||||
assert by["vsafe5v"].value is None
|
||||
assert "USB Power Delivery" in (by["vsafe5v"].needed_document or "")
|
||||
assert "snla027b" in (by["vsafe5v"].needed_document or "")
|
||||
assert "Figure 4-39" in (by["vsafe5v"].needed_document or "")
|
||||
assert by["vsafe0v"].value_kind == "UNKNOWN"
|
||||
assert by["vsafe0v"].value is None
|
||||
assert "vSafe0V" in (by["vsafe0v"].needed_document or "")
|
||||
hdmi14 = next(p for p in cat.physical_interfaces if p.id == "hdmi-1.4-tmds-type-a")
|
||||
hz14 = next(c for c in hdmi14.constraints if c.parameter == "differential_impedance")
|
||||
assert hz14.value_kind == "UNKNOWN"
|
||||
assert hz14.value is None
|
||||
_cite_ok(by["gnd_ir_drop_cable"])
|
||||
assert by["gnd_ir_drop_cable"].value == 250.0
|
||||
assert by["gnd_ir_drop_cable"].source_type == "CABLE"
|
||||
|
||||
@@ -138,9 +138,9 @@ def test_axi4_internal_does_not_create_pcb_nets():
|
||||
assert "AXI_WDATA" not in one.nets
|
||||
|
||||
|
||||
def test_empty_graph_keeps_nessun_protocollo():
|
||||
def test_empty_graph_keeps_no_protocol_message():
|
||||
sec = protocol_section_for_graph(DesignGraph())
|
||||
assert sec.message == "nessun protocollo riconosciuto"
|
||||
assert sec.message == "No protocol recognized."
|
||||
assert sec.recognized_instances == []
|
||||
blob = json.dumps(sec.model_dump())
|
||||
assert "ohm" not in blob.lower()
|
||||
|
||||
@@ -93,7 +93,7 @@ def test_result_rank_fail_before_warning():
|
||||
assert instance_worst_result(["UNKNOWN", "FAIL", "PASS"]) == "FAIL"
|
||||
|
||||
|
||||
def test_usb2_pair_l0_pass_l2_z_unknown_no_invented_ohm():
|
||||
def test_usb2_pair_l0_pass_l2_z_cert_line():
|
||||
sec, _ = protocol_exam(_usb_connected())
|
||||
assert sec.max_level_reached == "L3"
|
||||
assert sec.macrophase == "M9"
|
||||
@@ -106,20 +106,19 @@ def test_usb2_pair_l0_pass_l2_z_unknown_no_invented_ohm():
|
||||
assert l0_topo and l0_topo[0]["result"] == "PASS"
|
||||
z = [c for c in checks if c["check"] == "differential_impedance"]
|
||||
assert z
|
||||
assert z[0]["result"] in {"MISSING_SOURCE", "UNKNOWN"}
|
||||
assert z[0]["skip_visible"] is True
|
||||
assert z[0]["measured"] is None
|
||||
assert z[0]["limit"] is None
|
||||
blob = json.dumps(z[0])
|
||||
assert "90" not in blob
|
||||
assert z[0]["result"] == "FAIL"
|
||||
assert z[0]["limit"] == 90.0 or (z[0].get("notes") or "").find("90") >= 0
|
||||
notes = z[0].get("notes") or ""
|
||||
assert notes.startswith("USB not certified —")
|
||||
assert "90" in notes
|
||||
assert "not invented" not in notes.lower()
|
||||
chain = z[0]["chain"]
|
||||
assert chain["physical_interface_id"]
|
||||
assert chain["logical_protocol_id"]
|
||||
assert chain["physical_interface_id"] != chain["logical_protocol_id"]
|
||||
# No L3 warning wall without channel FACT.
|
||||
l3 = [c for c in checks if c["level"] == "L3"]
|
||||
assert l3 and l3[0]["skip_visible"]
|
||||
assert l3[0]["result"] != "PASS"
|
||||
assert "OpenEMS" in l3[0]["notes"]
|
||||
assert l3 == []
|
||||
|
||||
|
||||
def test_fail_listed_before_warning_in_report_checks():
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
"""RMII PHY–MAC is not RJ45 100 Ω; one English certification line."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.periscopex.af_trace_check import check_af_traces
|
||||
from backend.periscopex.models import (
|
||||
Component,
|
||||
ComponentType,
|
||||
DesignGraph,
|
||||
LayoutDielectric,
|
||||
LayoutGraph,
|
||||
LayoutSegment,
|
||||
LayoutStackup,
|
||||
Net,
|
||||
NetType,
|
||||
PinConnection,
|
||||
)
|
||||
from backend.periscopex.si_check import bus_class, phy_mac_kind, single_ended_eth_mac
|
||||
|
||||
|
||||
def _ic(ref: str, mpn: str, pins: dict[str, str]) -> Component:
|
||||
return Component(
|
||||
reference=ref, value=mpn, footprint="",
|
||||
component_type=ComponentType.IC, mpn=mpn, pins=pins,
|
||||
)
|
||||
|
||||
|
||||
def _net(name: str, *pairs: tuple[str, str]) -> Net:
|
||||
return Net(
|
||||
name=name, net_type=NetType.SIGNAL,
|
||||
pins=[PinConnection(component_ref=r, pin_number=p) for r, p in pairs],
|
||||
)
|
||||
|
||||
|
||||
def _rmii_graph() -> DesignGraph:
|
||||
return DesignGraph(
|
||||
components={
|
||||
"U19": _ic("U19", "LAN8720A", {
|
||||
"1": "ETH_RXD0", "2": "ETH_RXD1",
|
||||
"3": "ETH_TXD0", "4": "ETH_TXD1", "5": "ETH_TXEN",
|
||||
}),
|
||||
"U3": _ic("U3", "MCU", {
|
||||
"10": "ETH_RXD0", "11": "ETH_RXD1",
|
||||
"12": "ETH_TXD0", "13": "ETH_TXD1", "14": "ETH_TXEN",
|
||||
}),
|
||||
},
|
||||
nets={
|
||||
"ETH_RXD0": _net("ETH_RXD0", ("U19", "1"), ("U3", "10")),
|
||||
"ETH_RXD1": _net("ETH_RXD1", ("U19", "2"), ("U3", "11")),
|
||||
"ETH_TXD0": _net("ETH_TXD0", ("U19", "3"), ("U3", "12")),
|
||||
"ETH_TXD1": _net("ETH_TXD1", ("U19", "4"), ("U3", "13")),
|
||||
"ETH_TXEN": _net("ETH_TXEN", ("U19", "5"), ("U3", "14")),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _layout() -> LayoutGraph:
|
||||
segs = []
|
||||
y = 0.0
|
||||
for net in ("ETH_RXD0", "ETH_RXD1", "ETH_TXD0", "ETH_TXD1", "ETH_TXEN"):
|
||||
segs.append(LayoutSegment(
|
||||
start=(0, y), end=(40, y), width=0.15, layer="F.Cu", net=net,
|
||||
))
|
||||
y += 0.5
|
||||
return LayoutGraph(
|
||||
segments=segs,
|
||||
stackup=LayoutStackup(
|
||||
copper_layers=["F.Cu", "B.Cu"],
|
||||
dielectrics=[LayoutDielectric(name="core", er=4.5, height_mm=0.15)],
|
||||
copper_thickness_mm=0.035,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_eth_rxd_is_rmii_not_mdi():
|
||||
for n in ("ETH_RXD0", "ETH_TXD0", "ETH_TXEN"):
|
||||
assert single_ended_eth_mac(n)
|
||||
assert bus_class(n) == "rmii"
|
||||
assert phy_mac_kind(n) == "rmii"
|
||||
assert bus_class(n) != "eth_mdi"
|
||||
|
||||
|
||||
def test_rmii_one_certified_line_no_italian_tr_f():
|
||||
findings = check_af_traces(_rmii_graph(), {}, _layout())
|
||||
rmii = [f for f in findings if (f.finding or "").startswith("RMII certified —")]
|
||||
assert len(rmii) == 1
|
||||
blob = rmii[0].finding
|
||||
assert "ETH_RXD" in blob or "ETH_TXD" in blob or "ETH_TXEN" in blob
|
||||
assert "not an RJ45/MDI" in blob or "not an RJ45" in blob
|
||||
assert "mancanza" not in blob
|
||||
assert not any(
|
||||
"mancanza di tr" in (f.finding or "") or "mancanza di f" in (f.finding or "")
|
||||
for f in findings
|
||||
)
|
||||
assert not any(
|
||||
f.rule_id == "PE-AF-002" and any(
|
||||
single_ended_eth_mac(n) for n in ((f.net,) if f.net else ())
|
||||
)
|
||||
for f in findings
|
||||
)
|
||||
|
||||
|
||||
def test_rmii_not_given_100_ohm_mdi_finding():
|
||||
findings = check_af_traces(_rmii_graph(), {}, _layout())
|
||||
assert not any("25.4.9" in (f.finding or "") for f in findings)
|
||||
assert not any(
|
||||
f.finding.startswith("Ethernet certified") or f.finding.startswith("Ethernet not certified")
|
||||
for f in findings
|
||||
if f.net and single_ended_eth_mac(f.net)
|
||||
)
|
||||
Reference in New Issue
Block a user