"""Merge parsed board facts, pin inventory, and curated annotations.""" from __future__ import annotations from collections import Counter from collections.abc import Mapping import math import re from typing import Any from .annotations import expand_annotation_templates, validate_annotation_references from .eligibility import evaluate_recommendation from .pcb import Footprint, Pad, ParsedBoard, select_resistors, select_touchpoints EVIDENCE_TIERS = {"board_database", "cross_verified", "name_inferred", "unknown"} CONNECTOR_ROW_TOLERANCE_MM = 0.05 INTERNAL_NET = re.compile(r"^(?:N\d+|NET_\d+)$", re.IGNORECASE) POWER_NET = re.compile(r"^(?:VCC|VDD|VBAT|PWR|\+)", re.IGNORECASE) ANNOTATION_RESISTOR_REF = re.compile(r"(?\d+(?:\.\d+)?)(?P[rRkKmM])(?P\d+)?|" r"(?P\d+(?:\.\d+)?)\s*(?:ohm|ohms|Ω)?\b", re.IGNORECASE, ) _RESISTANCE_REJECT = re.compile( r"^(?:dnp|nc|n/?c|no\s*connect|0603|0805|0402|1206|1210|2010|2512)$", re.IGNORECASE, ) _STRUCTURED_ZERO_OHM = re.compile( r"^R\s*/\s*0(?:\s*/|\s*$)", re.IGNORECASE, ) _NOT_FITTED_TOKEN = re.compile( r"(?:/\s*NC\b|\bDNP\b|\bN\s*/\s*C\b|\bnot[\s-]?fitted\b)", re.IGNORECASE, ) _PACKAGE_SIZE_TOKEN = re.compile( r"^(?:0603|0805|0402|1206|1210|2010|2512)$", re.IGNORECASE, ) def detect_assembly_status(raw: str | None) -> str: """Thin assembly hint from component_value text: unknown | fitted | not_fitted.""" text = str(raw or "").strip() if not text: return "unknown" if _NOT_FITTED_TOKEN.search(text): return "not_fitted" return "unknown" def _is_structured_zero_ohm(raw: str) -> bool: compact = re.sub(r"\s+", "", str(raw or "")) # R/0/1%/0805 or R/0/1%/0805/NC — not R/120R/... return bool(re.match(r"^R/0(?:/|$)", compact, flags=re.IGNORECASE)) BOARD_DATA_SCHEMA_ID = "board-viewer-data-v2" def _category(reference: str) -> str: for prefix in ("CON", "PL", "TP", "J", "R"): if reference.startswith(prefix) and (prefix != "R" or reference[1:].isdigit()): return prefix return "OTHER" def parse_resistance_ohms(raw: str | None) -> float | None: """Parse a human resistor value into ohms. Returns None when not parseable.""" text = str(raw or "").strip() if not text: return None compact = re.sub(r"\s+", "", text) if _RESISTANCE_REJECT.fullmatch(compact): return None if _PACKAGE_SIZE_TOKEN.fullmatch(compact): return None # Structured footprint strings: "R / 0 /1%/0805", "R/0/1%/1210", optional /NC. if _is_structured_zero_ohm(text): return 0.0 # Bare footprint size / DNP tokens mixed in manufacturer strings stay rejected # unless an explicit resistance token is also present. # Prefer explicit ohm tokens inside footprint strings such as "R / 120R/1%/0805". candidates = list(_RESISTANCE_COMPACT.finditer(compact)) if not candidates: candidates = list(_RESISTANCE_COMPACT.finditer(text)) parsed: list[float] = [] for match in candidates: if match.group("plain") is not None and match.group("a") is None: # Bare number only counts when the whole value is numeric-ish. if re.fullmatch(r"\d+(?:\.\d+)?", compact): parsed.append(float(match.group("plain"))) continue amount = float(match.group("a")) prefix = (match.group("prefix") or "r").lower() fraction = match.group("b") if fraction: amount = float(f"{match.group('a')}.{fraction}") multiplier = {"r": 1.0, "k": 1_000.0, "m": 1_000_000.0}[prefix] if amount < 0: continue parsed.append(amount * multiplier) if not parsed: return None # Ambiguous multi-value strings are treated as unparsed (conservative). first = parsed[0] if any(not math.isclose(value, first, rel_tol=0, abs_tol=1e-9) for value in parsed[1:]): return None return first def resistance_parse_status(raw: str | None, ohms: float | None = None) -> str: """Return parsed | unparsed | ambiguous for a component_value string.""" text = str(raw or "").strip() if not text: return "unparsed" value = ohms if ohms is not None else parse_resistance_ohms(text) if value is not None: return "parsed" compact = re.sub(r"\s+", "", text) if _RESISTANCE_REJECT.fullmatch(compact): return "unparsed" candidates = list(_RESISTANCE_COMPACT.finditer(compact)) or list(_RESISTANCE_COMPACT.finditer(text)) values: list[float] = [] for match in candidates: if match.group("plain") is not None and match.group("a") is None: continue if match.group("a") is None: continue amount = float(match.group("a")) prefix = (match.group("prefix") or "r").lower() fraction = match.group("b") if fraction: amount = float(f"{match.group('a')}.{fraction}") values.append(amount * {"r": 1.0, "k": 1_000.0, "m": 1_000_000.0}[prefix]) if len(values) >= 2 and any(not math.isclose(values[0], item, abs_tol=1e-9) for item in values[1:]): return "ambiguous" return "unparsed" def resistance_value_tokens(raw: str | None, ohms: float | None = None) -> list[str]: """Search tokens: normalized raw forms plus 4k7 / 4.7k / 4700 equivalents.""" text = str(raw or "").strip() tokens: list[str] = [] if text: lowered = text.casefold() tokens.append(lowered) tokens.append(re.sub(r"\s+", "", lowered)) value = ohms if ohms is not None else parse_resistance_ohms(text) if value is None: return _unique_strings(tokens) def add(token: str) -> None: cleaned = token.casefold().strip() if cleaned and cleaned not in tokens: tokens.append(cleaned) if value == 0: add("0") add("0r") add("0ohm") return tokens if value >= 1_000_000 and math.isclose(value % 1_000_000, 0, abs_tol=1e-9): megs = value / 1_000_000 add(f"{_format_resistance_number(megs)}m") if value >= 1000: kilos = value / 1000 add(f"{_format_resistance_number(kilos)}k") # 4.7k ↔ 4k7 if not float(kilos).is_integer(): whole, frac = f"{kilos:.12g}".split(".", 1) add(f"{whole}k{frac}") elif kilos >= 1: add(f"{_format_resistance_number(kilos)}k") if value < 1000 or value.is_integer(): add(f"{_format_resistance_number(value)}") add(f"{_format_resistance_number(value)}r") add(f"{_format_resistance_number(value)}ohm") return tokens def _format_resistance_number(value: float) -> str: if float(value).is_integer(): return str(int(value)) return f"{value:.12g}" def extract_annotation_resistor_refs(*texts: object) -> set[str]: """Extract discrete resistor refs from annotation text; skip FPGA balls like U3.R4.""" refs: set[str] = set() for value in texts: if isinstance(value, list): for item in value: refs.update(extract_annotation_resistor_refs(item)) continue if value is None: continue for match in ANNOTATION_RESISTOR_REF.finditer(str(value)): refs.add(f"R{match.group(1)}") return refs def _view_point(x: float, y: float, bounds: Mapping[str, float]) -> dict[str, float]: return {"x": x - bounds["x"], "y": y - bounds["y"]} def _view_bounds(item: Mapping[str, float], board_bounds: Mapping[str, float]) -> dict[str, float]: return { "x": item["x"] - board_bounds["x"], "y": item["y"] - board_bounds["y"], "width": item["width"], "height": item["height"], } def _pin_dict( reference: str, category: str, pad: Pad, board_bounds: Mapping[str, float], source_index: int, ) -> dict[str, Any]: role = "mechanical" if pad.mechanical else ("unknown" if category == "CON" else "contact") return { "id": f"{reference}.pad-{source_index + 1}", "number": pad.number, "pad_role": role, "row": None, "column": None, "board_order": None, "mechanical": pad.mechanical, "electrical": pad.electrical, "net": pad.net, "position": {"x": pad.x, "y": pad.y}, "view_position": _view_point(pad.x, pad.y, board_bounds), "size": { "width": pad.width, "height": pad.height, "drill_width": pad.drill_width, "drill_height": pad.drill_height, }, "rotation": pad.rotation, "shape": pad.shape, "layers": list(pad.layers), "direction": "unknown", "external_level": "unknown", "function_category": _classify_function(pad.net, []), "reserved": False, "fixed_load_conflict": False, "board_pull": None, "adc_pulltype": None, "active_level": "unknown", "polarity": "unknown", "external_components": [], "summary": _raw_pin_summary(pad), "path": [], "evidence_tier": "board_database", "evidence_sources": ["board:kicad_import"], "fpga": None, "mcu": None, "programming": {}, "recommendation": {"eligible": False, "reasons": ["pin_evidence_not_verified"]}, "related_resistors": [], } def _raw_pin_summary(pad: Pad) -> str: if pad.mechanical: return "机械焊盘" if pad.net: return f"板内网络 {pad.net}" return "未命名电气焊盘" def _classify_function(net: str | None, capabilities: list[str]) -> str: ordered = ( "uart_tx", "uart_rx", "pwm", "fan_tach", "tach", "presence", "gpio_output", "gpio_input", "gpio", ) normalized = {str(item).lower() for item in capabilities} for category in ordered: if category in normalized: return category upper_net = str(net or "").upper() if upper_net in {"GND", "AGND", "DGND", "PGND"}: return "ground" if upper_net.startswith(("+", "VCC", "VDD", "VBAT", "PWR")): return "power" if "PWM" in upper_net: return "pwm" if "TX" in upper_net and "UART" in upper_net: return "uart_tx" if "RX" in upper_net and "UART" in upper_net: return "uart_rx" if "FG" in upper_net or "TACH" in upper_net: return "tach" if "INSTALL" in upper_net or "PRESENT" in upper_net: return "presence" return "unknown" def _touchpoint_dict(footprint: Footprint, board_bounds: Mapping[str, float]) -> dict[str, Any]: category = _category(footprint.reference) category_name = {"CON": "连接器", "J": "接口", "PL": "插座", "TP": "测试点"}.get(category, category) return { "reference": footprint.reference, "category": category, "component_value": footprint.component_value, "position": {"x": footprint.x, "y": footprint.y}, "view_position": _view_point(footprint.x, footprint.y, board_bounds), "rotation": footprint.rotation, "bounds": dict(footprint.bounds), "view_bounds": _view_bounds(footprint.bounds, board_bounds), "side": footprint.side, "summary": f"{category_name},用途未注释", "connector": None, "pins": [ _pin_dict(footprint.reference, category, pad, board_bounds, index) for index, pad in enumerate(footprint.pads) ], } def _pad_board_bounds(pad: Pad) -> dict[str, float]: width = max(pad.width, pad.drill_width, 0.5) height = max(pad.height, pad.drill_height, 0.5) radians = math.radians(pad.rotation) cosine, sine = abs(math.cos(radians)), abs(math.sin(radians)) half_width = (width * cosine + height * sine) / 2 half_height = (width * sine + height * cosine) / 2 return { "x": pad.x - half_width, "y": pad.y - half_height, "width": half_width * 2, "height": half_height * 2, } def _resistor_pad_dict( reference: str, pad: Pad, board_bounds: Mapping[str, float], ) -> dict[str, Any]: bounds = _pad_board_bounds(pad) return { "id": f"{reference}.pad-{pad.number or 'x'}", "number": pad.number, "net": pad.net, "position": {"x": pad.x, "y": pad.y}, "view_position": _view_point(pad.x, pad.y, board_bounds), "bounds": bounds, "view_bounds": _view_bounds(bounds, board_bounds), "pad_role": "mechanical" if pad.mechanical else "electrical", "size": { "width": pad.width, "height": pad.height, "drill_width": pad.drill_width, "drill_height": pad.drill_height, }, "rotation": pad.rotation, "shape": pad.shape, "layers": list(pad.layers), } def _resistor_dict(footprint: Footprint, board_bounds: Mapping[str, float]) -> dict[str, Any]: ohms = parse_resistance_ohms(footprint.component_value) assembly = detect_assembly_status(footprint.component_value) pads = [_resistor_pad_dict(footprint.reference, pad, board_bounds) for pad in footprint.pads] nets = [pad["net"] for pad in pads if pad["pad_role"] == "electrical" and pad["net"]] value_label = footprint.component_value.strip() or "阻值未标注" net_label = "↔".join(nets) if nets else "无命名网络" status_note = " · 未装/NC" if assembly == "not_fitted" else "" return { "reference": footprint.reference, "category": "R", "component_value": footprint.component_value, "value_ohms": ohms, "value_tokens": resistance_value_tokens(footprint.component_value, ohms), "value_parse_status": resistance_parse_status(footprint.component_value, ohms), "assembly_status": assembly, "position": {"x": footprint.x, "y": footprint.y}, "view_position": _view_point(footprint.x, footprint.y, board_bounds), "rotation": footprint.rotation, "bounds": dict(footprint.bounds), "view_bounds": _view_bounds(footprint.bounds, board_bounds), "side": footprint.side, "summary": f"电阻 {value_label} · {net_label}{status_note}", "pads": pads, } def _iter_annotation_text_chunks(value: object) -> list[str]: if value is None: return [] if isinstance(value, list): chunks: list[str] = [] for item in value: chunks.extend(_iter_annotation_text_chunks(item)) return chunks text = str(value).strip() return [text] if text else [] def _resolve_related_resistors_for_pin( pin: Mapping[str, Any], resistor_by_ref: Mapping[str, Mapping[str, Any]], ) -> list[dict[str, Any]]: """Build structured related_resistors[] from path / external_components.""" links: list[dict[str, Any]] = [] seen: set[tuple[str, str | None, str]] = set() for field_name in ("path", "external_components"): for chunk in _iter_annotation_text_chunks(pin.get(field_name)): pad_hits = list(ANNOTATION_RESISTOR_PAD.finditer(chunk)) covered_spans = {(match.start(), match.end()) for match in pad_hits} for match in pad_hits: reference = f"R{match.group(1)}" pad_number = match.group(2) key = (reference, pad_number, field_name) if key in seen: continue seen.add(key) resistor = resistor_by_ref.get(reference) pcb_net = None status = "resolved" if resistor is None: status = "missing_reference" else: pad = next( ( item for item in resistor.get("pads", []) if isinstance(item, Mapping) and str(item.get("number")) == pad_number ), None, ) if pad is None: status = "missing_pad" else: pcb_net = pad.get("net") links.append( { "source_pin_id": str(pin.get("id") or ""), "source_field": field_name, "resistor_reference": reference, "pad_number": pad_number, "raw_context": chunk, "status": status, "pcb_net": pcb_net, "claimed_net": None, } ) for match in ANNOTATION_RESISTOR_REF.finditer(chunk): span = (match.start(), match.end()) if any(span[0] >= start and span[1] <= end for start, end in covered_spans): continue # Skip FPGA endpoints like U3.R4 (negative lookbehind already handles most). if match.start() >= 2 and chunk[match.start() - 1] == ".": continue reference = f"R{match.group(1)}" key = (reference, None, field_name) if key in seen: continue seen.add(key) resistor = resistor_by_ref.get(reference) status = "resolved" if resistor is not None else "missing_reference" links.append( { "source_pin_id": str(pin.get("id") or ""), "source_field": field_name, "resistor_reference": reference, "pad_number": None, "raw_context": chunk, "status": status, "pcb_net": None, "claimed_net": None, } ) return links def _attach_related_resistors( touchpoints: list[dict[str, Any]], resistors: list[dict[str, Any]], ) -> list[dict[str, Any]]: resistor_by_ref = {str(item["reference"]): item for item in resistors} conflicts: list[dict[str, Any]] = [] for touchpoint in touchpoints: for pin in touchpoint.get("pins", []): related = _resolve_related_resistors_for_pin(pin, resistor_by_ref) pin["related_resistors"] = related for link in related: if link["status"] == "missing_pad": conflicts.append( { "id": f"missing-pad-{link['resistor_reference']}.{link['pad_number']}", "subject_reference": link["resistor_reference"], "status": "unresolved", "kind": "missing_pad", "source_pin_id": link["source_pin_id"], "detail": link, } ) elif link["status"] == "missing_reference": conflicts.append( { "id": f"missing-ref-{link['resistor_reference']}-{link['source_pin_id']}", "subject_reference": link["resistor_reference"], "status": "unresolved", "kind": "missing_reference", "source_pin_id": link["source_pin_id"], "detail": link, } ) return conflicts def _normalize_evidence_conflicts( annotations: Mapping[str, object], resistors: list[dict[str, Any]], ) -> list[dict[str, Any]]: """Copy curated evidence conflicts; never override primary PCB pad nets.""" raw = annotations.get("evidence_conflicts", []) if not isinstance(raw, list): return [] index = {str(item["reference"]) for item in resistors} normalized: list[dict[str, Any]] = [] for item in raw: if not isinstance(item, Mapping): continue subject = str(item.get("subject_reference") or "") entry = { "id": str(item.get("id") or subject or "evidence-conflict"), "subject_reference": subject, "status": str(item.get("status") or "unresolved"), "kind": str(item.get("kind") or "cross_evidence"), "summary": str(item.get("summary") or ""), "primary_source": str(item.get("primary_source") or "pcb_pad_net"), "claims": list(item.get("claims") or []) if isinstance(item.get("claims"), list) else [], "subject_in_pcb_index": subject in index, } # Attach live PCB pad facts for the subject when present. resistor = next((row for row in resistors if row["reference"] == subject), None) if resistor is not None: entry["pcb_pads"] = [ { "number": pad.get("number"), "net": pad.get("net"), "pad_role": pad.get("pad_role"), } for pad in resistor.get("pads", []) if isinstance(pad, Mapping) ] normalized.append(entry) return normalized def annotation_resistor_refs_from_board_data(payload: Mapping[str, object]) -> set[str]: refs: set[str] = set() touchpoints = payload.get("touchpoints", []) if not isinstance(touchpoints, list): return refs for touchpoint in touchpoints: if not isinstance(touchpoint, Mapping): continue pins = touchpoint.get("pins", []) if not isinstance(pins, list): continue for pin in pins: if not isinstance(pin, Mapping): continue refs.update( extract_annotation_resistor_refs( pin.get("path"), pin.get("external_components"), ) ) return refs def validate_resistor_index( payload: Mapping[str, object], *, pcb_references: set[str] | None = None, ) -> None: """Fail-closed resistor index checks (passes A/B/G when inputs are available).""" schema = payload.get("schema") if schema not in (None, "board-viewer-data-v1", BOARD_DATA_SCHEMA_ID): raise ValueError(f"unsupported board-data schema: {schema}") if schema == "board-viewer-data-v1": raise ValueError("board-data schema is stale v1; regenerate for board-viewer-data-v2") resistors = payload.get("resistors") if not isinstance(resistors, list): raise ValueError("board-data resistors[] missing") counts = payload.get("counts") if not isinstance(counts, Mapping): raise ValueError("board-data counts missing") references = [str(item.get("reference") or "") for item in resistors if isinstance(item, Mapping)] if len(references) != len(set(references)): raise ValueError("duplicate resistor references in board-data") if counts.get("resistors") != len(references): raise ValueError( f"counts.resistors={counts.get('resistors')} != len(resistors)={len(references)}" ) pad_total = 0 electrical_total = 0 board = payload.get("board") view_box = board.get("view_box") if isinstance(board, Mapping) else None if not isinstance(view_box, Mapping): raise ValueError("board view_box missing") max_x = float(view_box["width"]) max_y = float(view_box["height"]) required_pad_fields = ( "id", "number", "net", "position", "view_position", "bounds", "view_bounds", "pad_role", "size", "rotation", "shape", "layers", ) for item in resistors: if not isinstance(item, Mapping): raise ValueError("invalid resistor entry") if item.get("category") != "R": raise ValueError(f"{item.get('reference')} category must be R") if item.get("side") not in {"front", "back"}: raise ValueError(f"{item.get('reference')} has invalid side") if "value_parse_status" in item and item.get("value_parse_status") not in { "parsed", "unparsed", "ambiguous", }: raise ValueError(f"{item.get('reference')} invalid value_parse_status") if "assembly_status" in item and item.get("assembly_status") not in { "unknown", "fitted", "not_fitted", }: raise ValueError(f"{item.get('reference')} invalid assembly_status") pads = item.get("pads") if not isinstance(pads, list) or not pads: raise ValueError(f"{item.get('reference')} has no pads") electrical = [ pad for pad in pads if isinstance(pad, Mapping) and pad.get("pad_role") == "electrical" ] if not electrical: raise ValueError(f"{item.get('reference')} has no electrical pad") pad_total += len(pads) electrical_total += len(electrical) for pad in pads: if not isinstance(pad, Mapping): raise ValueError(f"{item.get('reference')} has invalid pad") missing = [name for name in required_pad_fields if name not in pad] if missing: raise ValueError( f"{item.get('reference')} pad missing fields: {', '.join(missing)}" ) if not isinstance(pad.get("layers"), list): raise ValueError(f"{item.get('reference')} pad layers must be a list") position = item.get("view_position") if not isinstance(position, Mapping): raise ValueError(f"{item.get('reference')} missing view_position") x = float(position["x"]) y = float(position["y"]) if x < -1.0 or y < -1.0 or x > max_x + 1.0 or y > max_y + 1.0: raise ValueError(f"{item.get('reference')} view_position outside board bounds") if counts.get("resistor_pads") != pad_total: raise ValueError( f"counts.resistor_pads={counts.get('resistor_pads')} != pad_total={pad_total}" ) if "resistor_electrical_pads" in counts and counts.get("resistor_electrical_pads") != electrical_total: raise ValueError( "counts.resistor_electrical_pads does not match electrical pad total" ) categories = counts.get("categories") if not isinstance(categories, Mapping) or categories.get("R") != len(references): raise ValueError("counts.categories.R does not match resistors[]") touchpoint_sides = counts.get("touchpoint_sides") or counts.get("sides") resistor_sides = counts.get("resistor_sides") if isinstance(touchpoint_sides, Mapping): touchpoints = payload.get("touchpoints") if isinstance(touchpoints, list): expected = Counter( str(item.get("side")) for item in touchpoints if isinstance(item, Mapping) ) if int(touchpoint_sides.get("front", -1)) != expected.get("front", 0) or int( touchpoint_sides.get("back", -1) ) != expected.get("back", 0): raise ValueError("counts.touchpoint_sides does not match touchpoints[]") if isinstance(resistor_sides, Mapping): expected_r = Counter(str(item.get("side")) for item in resistors if isinstance(item, Mapping)) if int(resistor_sides.get("front", -1)) != expected_r.get("front", 0) or int( resistor_sides.get("back", -1) ) != expected_r.get("back", 0): raise ValueError("counts.resistor_sides does not match resistors[]") if int(resistor_sides.get("front", 0)) + int(resistor_sides.get("back", 0)) != len(references): raise ValueError("resistor_sides front+back != resistors total") if pcb_references is not None and set(references) != pcb_references: missing = sorted(pcb_references - set(references), key=lambda value: int(value[1:])) extra = sorted(set(references) - pcb_references, key=lambda value: int(value[1:])) raise ValueError( f"resistor set mismatch vs PCB: missing={missing[:20]} extra={extra[:20]}" ) annotated = annotation_resistor_refs_from_board_data(payload) index = set(references) orphaned = sorted(annotated - index, key=lambda value: int(value[1:])) if orphaned: raise ValueError( "annotation path/external_components resistor refs missing from index: " + ", ".join(orphaned[:40]) ) # G2: explicit R#.pad mentions must resolve to real pads. resistor_pads = { (str(item.get("reference")), str(pad.get("number"))) for item in resistors if isinstance(item, Mapping) for pad in item.get("pads", []) if isinstance(pad, Mapping) } for touchpoint in payload.get("touchpoints", []) if isinstance(payload.get("touchpoints"), list) else []: if not isinstance(touchpoint, Mapping): continue for pin in touchpoint.get("pins", []) if isinstance(touchpoint.get("pins"), list) else []: if not isinstance(pin, Mapping): continue related = pin.get("related_resistors") if isinstance(related, list): for link in related: if not isinstance(link, Mapping): continue if link.get("status") in {"missing_reference", "missing_pad"}: raise ValueError( f"related resistor link unresolved: {link.get('resistor_reference')} " f"status={link.get('status')} pin={link.get('source_pin_id')}" ) for field_name in ("path", "external_components"): for chunk in _iter_annotation_text_chunks(pin.get(field_name)): for match in ANNOTATION_RESISTOR_PAD.finditer(chunk): key = (f"R{match.group(1)}", match.group(2)) if key not in resistor_pads: raise ValueError( f"annotation {field_name} pad {key[0]}.{key[1]} missing from index" ) def _connector_profile_index( annotations: Mapping[str, object], ) -> dict[str, tuple[str, Mapping[str, object]]]: result: dict[str, tuple[str, Mapping[str, object]]] = {} profiles = annotations.get("connector_profiles", {}) if not isinstance(profiles, Mapping): return result for profile_name, profile in profiles.items(): if not isinstance(profile, Mapping): continue references = profile.get("references", []) if not isinstance(references, list): continue for reference in references: result[str(reference)] = (str(profile_name), profile) return result def _cluster_contact_rows(pins: list[dict[str, Any]]) -> list[list[dict[str, Any]]]: rows: list[list[dict[str, Any]]] = [] row_y: list[float] = [] ordered = sorted( pins, key=lambda item: (float(item["position"]["y"]), float(item["position"]["x"])), ) for pin in ordered: y = float(pin["position"]["y"]) if not rows or abs(y - row_y[-1]) > CONNECTOR_ROW_TOLERANCE_MM: rows.append([pin]) row_y.append(y) continue rows[-1].append(pin) row_y[-1] = sum(float(item["position"]["y"]) for item in rows[-1]) / len(rows[-1]) for row in rows: row.sort(key=lambda item: (float(item["position"]["x"]), str(item["number"]))) return rows def _pin_sort_key(pin: Mapping[str, object]) -> tuple[int, int, str]: role_order = {"contact": 0, "shield": 1, "mechanical": 2, "unknown": 3} board_order = pin.get("board_order") return ( role_order.get(str(pin.get("pad_role")), 4), int(board_order) if isinstance(board_order, int) else 1_000_000, str(pin.get("id") or ""), ) def _apply_connector_profile( touchpoint: dict[str, Any], profile_entry: tuple[str, Mapping[str, object]] | None, ) -> None: pins = touchpoint["pins"] if profile_entry is None: touchpoint["connector"] = { "profile": None, "review_status": "unknown", "view": "board_front", "contact_count": 0, "auxiliary_pad_count": len(pins), "rows": 0, "columns": 0, "contact_grid": [], "contact_order": [], "sources": [], } pins.sort(key=_pin_sort_key) return profile_name, profile = profile_entry contacts = {str(value) for value in profile.get("contact_pins", [])} shields = {str(value) for value in profile.get("shield_pads", [])} for pin in pins: number = str(pin["number"]) if pin["mechanical"]: pin["pad_role"] = "mechanical" elif number in contacts: pin["pad_role"] = "contact" elif number in shields: pin["pad_role"] = "shield" else: pin["pad_role"] = "unknown" contact_pins = [pin for pin in pins if pin["pad_role"] == "contact"] rows = _cluster_contact_rows(contact_pins) contact_grid: list[list[str]] = [] order = 1 for row_number, row in enumerate(rows, start=1): grid_row: list[str] = [] for column_number, pin in enumerate(row, start=1): pin["row"] = row_number pin["column"] = column_number pin["board_order"] = order grid_row.append(str(pin["number"])) order += 1 contact_grid.append(grid_row) touchpoint["connector"] = { "profile": profile_name, "review_status": str(profile.get("evidence_tier") or "unknown"), "view": "board_front", "contact_count": len(contact_pins), "auxiliary_pad_count": len(pins) - len(contact_pins), "rows": len(contact_grid), "columns": max((len(row) for row in contact_grid), default=0), "contact_grid": contact_grid, "contact_order": [number for row in contact_grid for number in row], "sources": [str(value) for value in profile.get("sources", [])], } pins.sort(key=_pin_sort_key) def _inventory_indexes(inventory: Mapping[str, object]) -> tuple[dict[tuple[str, str], Mapping[str, object]], dict[str, list[Mapping[str, object]]]]: direct: dict[tuple[str, str], Mapping[str, object]] = {} by_net: dict[str, list[Mapping[str, object]]] = {} pins = inventory.get("pins", []) if not isinstance(pins, list): return direct, by_net for item in pins: if not isinstance(item, Mapping): continue connector = item.get("board_connector") connector_pin = item.get("connector_pin") if connector and connector_pin is not None: direct[(str(connector), str(connector_pin))] = item for name in (item.get("function_net"), item.get("signal")): if name: by_net.setdefault(str(name), []).append(item) return direct, by_net def _inventory_match( reference: str, pin: Mapping[str, object], direct: Mapping[tuple[str, str], Mapping[str, object]], by_net: Mapping[str, list[Mapping[str, object]]], ) -> Mapping[str, object] | None: key = (reference, str(pin.get("number", ""))) if key in direct: item = direct[key] expected_net = item.get("connector_signal") or item.get("function_net") or item.get("signal") actual_net = pin.get("net") if expected_net and actual_net and str(expected_net) != str(actual_net): raise ValueError( f"connector net mismatch {reference}.{pin.get('number')}: " f"board={actual_net} inventory={expected_net}" ) return item net = pin.get("net") matches = by_net.get(str(net), []) if net else [] return matches[0] if len(matches) == 1 else None def _inventory_source(item: Mapping[str, object]) -> str: marker = item.get("screenshot_index") or item.get("source_confidence") or item.get("signal") return f"inventory:{marker}" def _merge_inventory(pin: dict[str, Any], item: Mapping[str, object]) -> None: capabilities = [str(value) for value in item.get("capability", [])] verified = item.get("manually_verified") is True evidence_tier = "cross_verified" if verified else "name_inferred" source = _inventory_source(item) board_pull = item.get("board_pull") if board_pull is None: board_pull = item.get("pullup") external_components = [] for key in ("transceiver", "series_link", "esd"): value = item.get(key) if value and str(value) not in external_components: external_components.append(str(value)) pin.update( { "direction": str(item.get("direction") or "unknown"), "external_level": str(item.get("external_level") or "unknown"), "function_category": _classify_function(str(item.get("function_net") or pin.get("net") or ""), capabilities), "reserved": item.get("reserved") is True, "fixed_load_conflict": item.get("fixed_load_conflict") is True, "board_pull": board_pull, "active_level": str(item.get("active_level") or "unknown"), "polarity": str(item.get("polarity") or "unknown"), "external_components": external_components, "evidence_tier": evidence_tier, "evidence_sources": [*pin["evidence_sources"], source], "fpga": { "ball": str(item.get("fpga_ball") or ""), "board_signal": str(item.get("signal") or item.get("function_net") or ""), "io_standard": str(item.get("io_standard") or ""), "capabilities": capabilities, "evidence_tier": evidence_tier, "sources": [source], }, } ) transceiver = item.get("transceiver") if transceiver: pin["path"] = [str(transceiver)] signal = item.get("signal") or item.get("function_net") if signal: pin["summary"] = str(signal) def _merge_annotation(pin: dict[str, Any], annotation: Mapping[str, object]) -> None: for key in ( "summary", "direction", "external_level", "function_category", "reserved", "fixed_load_conflict", "board_pull", "adc_pulltype", "active_level", "polarity", "external_components", "path", ): if key in annotation: pin[key] = annotation[key] grades = annotation.get("evidence_grades") if isinstance(grades, Mapping): pin["evidence_grades"] = { "physical_path": str(grades.get("physical_path") or "unknown"), "product_polarity": str(grades.get("product_polarity") or "unknown"), "hardware_measurement": str(grades.get("hardware_measurement") or "unknown"), } fpga = annotation.get("fpga") if isinstance(fpga, Mapping): pin["fpga"] = { "ball": str(fpga.get("ball") or ""), "board_signal": str(fpga.get("board_signal") or ""), "io_standard": str(fpga.get("io_standard") or ""), "capabilities": [str(value) for value in fpga.get("capabilities", [])], "evidence_tier": str(fpga.get("evidence_tier") or "unknown"), "sources": [str(value) for value in fpga.get("sources", [])], } mcu = annotation.get("mcu") if isinstance(mcu, Mapping): pin["mcu"] = { "device": str(mcu.get("device") or ""), "family": str(mcu.get("family") or ""), "pin": str(mcu.get("pin") or ""), "signal": str(mcu.get("signal") or ""), "capabilities": [str(value) for value in mcu.get("capabilities", [])], "evidence_tier": str(mcu.get("evidence_tier") or "unknown"), "sources": [str(value) for value in mcu.get("sources", [])], } tier = annotation.get("evidence_tier") if tier in EVIDENCE_TIERS: pin["evidence_tier"] = tier if isinstance(pin.get("fpga"), dict): pin["fpga"]["evidence_tier"] = tier sources = annotation.get("sources", []) if isinstance(sources, list): pin["evidence_sources"] = [*pin["evidence_sources"], *[str(item) for item in sources]] def _unique_strings(values: list[object]) -> list[str]: result: list[str] = [] for value in values: text = str(value) if text and text not in result: result.append(text) return result def _verified_fpga(pin: Mapping[str, object]) -> Mapping[str, object] | None: fpga = pin.get("fpga") if ( pin.get("evidence_tier") == "cross_verified" and isinstance(fpga, Mapping) and fpga.get("evidence_tier") == "cross_verified" and fpga.get("ball") and fpga.get("io_standard") ): return fpga return None def _verified_mcu(pin: Mapping[str, object]) -> Mapping[str, object] | None: mcu = pin.get("mcu") if ( pin.get("evidence_tier") == "cross_verified" and isinstance(mcu, Mapping) and mcu.get("evidence_tier") == "cross_verified" and mcu.get("device") and mcu.get("family") and mcu.get("pin") and mcu.get("signal") ): return mcu return None def _programming_guidance(reference: str, pin: Mapping[str, object]) -> dict[str, object]: number = str(pin.get("number") or "") net = str(pin.get("net") or "") role = str(pin.get("pad_role") or "unknown") function_category = str(pin.get("function_category") or "unknown") direction = str(pin.get("direction") or "unknown") external_level = str(pin.get("external_level") or "unknown") fpga = _verified_fpga(pin) mcu = _verified_mcu(pin) sources = _unique_strings(list(pin.get("evidence_sources", []))) if role == "mechanical" or pin.get("mechanical") is True or pin.get("electrical") is not True: return { "status": "not_programmable", "conclusion": "这是机械定位孔,不是电气针脚。", "network_explanation": "机械孔没有可用于编程的板内网络。", "hdl_guidance": "不要声明 RTL 端口,也不能生成 ADC 约束。", "connection_guidance": ["不要把机械孔作为信号、电源或地连接点。"], "constraints": [], "risks": ["它只承担机械定位或固定作用。"], "evidence_tier": "board_database", "sources": sources, } if role == "shield": grounded = net.upper() in {"GND", "AGND", "DGND", "PGND"} network = "并与板级 GND 相连" if grounded else f"板数据库网络为 {net or '未命名'}" return { "status": "not_programmable", "conclusion": "这是屏蔽/固定焊盘,不属于座子对外接触针。", "network_explanation": f"该焊盘用于连接器外壳或固定,{network}。", "hdl_guidance": "不要为它声明 RTL 端口,也不能生成 ADC 约束。", "connection_guidance": ["线束 pinout 只使用标记为“接触针”的焊盘。"], "constraints": [], "risks": ["把屏蔽固定焊盘当作外部 Pin 会造成针脚数量和顺序错误。"], "evidence_tier": str(pin.get("evidence_tier") or "board_database"), "sources": sources, } if function_category == "ground" or net.upper() in {"GND", "AGND", "DGND", "PGND"}: return { "status": "not_programmable", "conclusion": "这是接地针,用作信号参考和电流回路,不是 FPGA I/O。", "network_explanation": f"板数据库确认 {reference}.{number} 连接到板级 {net or 'GND'}。", "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。", "connection_guidance": ["作为外部设备的参考地/回流地连接,不要当作逻辑信号脚。"], "constraints": [], "risks": ["接线时仍需遵守整机接地和回流设计。"], "evidence_tier": str(pin.get("evidence_tier") or "board_database"), "sources": sources, } if mcu is not None: device = str(mcu.get("device")) family = str(mcu.get("family")) package_pin = str(mcu.get("pin")) signal = str(mcu.get("signal")) return { "status": "verified_mcu", "conclusion": ( f"GD32 MCU 固件测试点:{reference}.{number} 直连 " f"{device}.{package_pin}({signal},{family})。" ), "network_explanation": ( f"板数据库与原理图共同确认网络 {net or signal} 对应 " f"{device} 封装引脚 {package_pin} / 端口 {signal};它不是 FPGA 球位。" ), "hdl_guidance": ( f"不要在 FPGA RTL/ADC 中声明此针;应在 GD32 固件中按 {signal} " "配置 GPIO 或所需复用功能,方向和复用选择由当前 MCU 固件决定。" ), "connection_guidance": [ f"外接仪器或信号前按 {external_level} 边界检查,并与板级 GND 共参考。", "作为测量点使用时优先采用高阻探头,避免改变 MCU 引脚状态。", ], "constraints": [ f"MCU = {family} {device}", f"PACKAGE_PIN = {package_pin}", f"PORT = {signal}", ], "risks": [ "查看器不读取当前 MCU 固件,仍需检查端口复用、启动状态和外设占用。", "此映射不能生成 FPGA ADC 约束。", ], "evidence_tier": "cross_verified", "sources": sources, } if fpga is not None: signal = str(fpga.get("board_signal") or pin.get("summary") or net) ball = str(fpga.get("ball")) io_standard = str(fpga.get("io_standard")) components = [str(value) for value in pin.get("external_components", []) if value] transceiver = next((value for value in components if value.upper().startswith("U")), None) if direction == "output": route = f"经 {transceiver} 转换后" if transceiver else "通过板内网络" conclusion = f"FPGA 输出:RTL 驱动 {signal}(球位 {ball}),{route}从 {reference}.{number} 发出。" elif direction == "input": route = f"先经 {transceiver} 转换,再" if transceiver else "通过板内网络" conclusion = f"FPGA 输入:外部信号从 {reference}.{number} 进入,{route}由 {signal}(球位 {ball})采样。" elif direction in {"bidir", "bidirectional"} and function_category == "gpio": conclusion = ( f"已验证直连 FPGA GPIO:{reference}.{number} 对应 {signal}(球位 {ball})," "物理上支持输入或输出。" ) else: conclusion = f"已验证 FPGA 路径:{reference}.{number} 对应 {signal}(球位 {ball}),方向为 {direction}。" if transceiver: network_explanation = ( f"连接器侧原始网络是 {net or '未命名'};经 {transceiver} 后," f"FPGA 逻辑侧信号是 {signal}。" ) else: network_explanation = ( f"板数据库网络 {net or '未命名'} 已交叉验证到 FPGA 逻辑信号 {signal}({ball})。" ) connection_guidance: list[str] = [] if direction == "output" and function_category == "uart_tx": connection_guidance.append("连接到对端设备的接收端(RX)。") elif direction == "input" and function_category == "uart_rx": connection_guidance.append("连接到对端设备的发送端(TX)。") elif direction == "output": connection_guidance.append("这是板端输出;外部设备应作为接收端,不要与另一个主动输出直接相连。") elif direction == "input": connection_guidance.append("这是板端输入;由外部设备驱动,接入前确认电平和公共参考地。") elif direction in {"bidir", "bidirectional"} and function_category == "gpio": connection_guidance.append( "按实际用途选择输入或输出;配置为输入时由外部设备驱动,配置为输出时不要与另一个主动输出硬连接。" ) else: connection_guidance.append("按已验证方向使用;双向信号需要在 RTL 中正确控制输出使能。") if external_level.upper() == "RS232": connection_guidance.append("连接器侧是 RS-232 电平,不能直接接 3.3V TTL/CMOS 串口。") if direction in {"bidir", "bidirectional"} and function_category == "gpio": hdl_guidance = ( f"该物理脚支持 input、output 或 inout,按实际功能选择;" f"只有真正需要双向共享并实现输出使能时才使用三态 inout。FPGA 逻辑侧使用 {io_standard}。" ) else: hdl_guidance = f"RTL 端口方向应为 {direction};FPGA 逻辑侧使用 {io_standard}。" active_level = str(pin.get("active_level") or "unknown") if active_level in {"high", "low"}: active_cn = "高" if active_level == "high" else "低" hdl_guidance += f" 此功能为{active_cn}电平有效。" constraints = [f"LOCATION = {ball}", f"IOSTANDARD = {io_standard}"] board_pull = pin.get("board_pull") if board_pull: constraints.append(f"板上外部 pull:{board_pull}") if active_level in {"high", "low"}: constraints.append(f"有效电平:{'高电平' if active_level == 'high' else '低电平'}") risks = ["这里只证明物理路径和板级证据,仍需检查当前工程约束冲突。"] if direction in {"bidir", "bidirectional"} and function_category == "gpio": risks.insert(0, "不要因为物理上可双向就默认声明 inout;错误的三态控制可能造成总线争用。") if pin.get("reserved") is True: risks.insert(0, "当前 inventory 将此功能标记为保留,不能作为空闲 GPIO 重新分配。") if pin.get("fixed_load_conflict") is True: risks.insert(0, "此针存在已知固定负载冲突。") return { "status": "verified_fpga", "conclusion": conclusion, "network_explanation": network_explanation, "hdl_guidance": hdl_guidance, "connection_guidance": connection_guidance, "constraints": constraints, "risks": risks, "evidence_tier": "cross_verified", "sources": sources, } if function_category == "power" or POWER_NET.match(net): if pin.get("evidence_tier") == "cross_verified": summary = str(pin.get("summary") or f"电源网络 {net or '未命名'}").rstrip("。") path = [str(item) for item in pin.get("path", []) if item] path_text = " -> ".join(path) if path else f"{reference}.{number} {net or '未命名'}" direction_text = { "input": "板端电源输入", "output": "板端电源输出", "passive": "电源参考/分配节点", }.get(direction, f"方向 {direction}") if direction == "input": connection_guidance = [ f"这是{direction_text};只能接符合 {external_level} 边界的电源,并核对极性与公共地。" ] direction_risk = "不要反向供电或从该输入针向外取电。" elif direction == "output": connection_guidance = [ f"这是{direction_text};只用于给设计负载提供 {external_level},不要与另一电源输出并接。" ] direction_risk = "不要向该输出针反向供电。" else: connection_guidance = [ f"这是{direction_text};按原理图定义使用,并遵守 {external_level} 电气边界。" ] direction_risk = "不要把电源参考/分配节点当作普通信号或任意供电入口。" return { "status": "not_programmable", "conclusion": f"{summary}。这是{direction_text},不是 FPGA I/O,不能用于逻辑选脚。", "network_explanation": ( f"原理图与板数据库交叉确认路径:{path_text};" f"外部电气边界为 {external_level},方向为 {direction_text}。" ), "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。", "connection_guidance": connection_guidance, "constraints": [], "risks": [ direction_risk, "查看器不证明额定电流、线束载流能力或选配保护器件的实际装配状态,仍需核对 BOM 和整机规范。", ], "evidence_tier": "cross_verified", "sources": sources, } return { "status": "not_programmable", "conclusion": "这是电源网络,不是 FPGA I/O,不能用于逻辑选脚。", "network_explanation": ( f"按板数据库网名 {net or '未命名'} 可判断它属于电源域;" "供电方向、额定电流和是否允许外供尚未在查看器中交叉验证。" ), "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。", "connection_guidance": ["连接前必须查原理图和整机线束,确认电压、方向与电流能力。"], "constraints": [], "risks": ["错误接入 FPGA 3.3V I/O 可能造成硬件损坏。"], "evidence_tier": "name_inferred", "sources": sources, } if INTERNAL_NET.match(net): network_explanation = ( f"{net} 是 CAD 自动生成的内部网络编号,只能证明同名焊盘电气相连;" "编号本身不包含功能、方向或电平含义。" ) elif net: network_explanation = ( f"板数据库确认此焊盘连接到 {net};当前没有足够证据把该网名等同于某个 FPGA 端口。" ) else: network_explanation = "该电气焊盘没有可解释的网络名,功能保持未知。" return { "status": "board_only" if net else "unknown", "conclusion": f"当前只确认到板内网络 {net or '未知'},没有已验证 FPGA 路径。", "network_explanation": network_explanation, "hdl_guidance": "不能据此写 RTL 方向或 ADC 约束;需要原理图路径或人工交叉验证。", "connection_guidance": ["接线前先确认该网络经过的器件、外部电平和信号方向。"], "constraints": [], "risks": ["网名相似不等于功能相同,禁止仅凭名称推断 FPGA 映射。"], "evidence_tier": "board_database" if net else "unknown", "sources": sources, } def _merge_programming_annotation( programming: dict[str, object], annotation: Mapping[str, object] ) -> None: for key in ( "status", "conclusion", "network_explanation", "hdl_guidance", "connection_guidance", "constraints", "risks", ): if key in annotation: programming[key] = annotation[key] tier = annotation.get("evidence_tier") if tier in EVIDENCE_TIERS: programming["evidence_tier"] = tier sources = annotation.get("sources", []) if isinstance(sources, list): programming["sources"] = _unique_strings( [*list(programming.get("sources", [])), *sources] ) def _refresh_recommendation(pin: dict[str, Any]) -> None: fpga = pin.get("fpga") capabilities = fpga.get("capabilities", []) if isinstance(fpga, Mapping) else [] useful = [item for item in capabilities if item not in {"gpio", "rs232_via_transceiver"}] capability = str(useful[0] if useful else (capabilities[0] if capabilities else "gpio")) result = evaluate_recommendation(pin, capability) pin["recommendation"] = {"eligible": result.eligible, "reasons": result.reasons} def _build_value_coverage(resistors: list[dict[str, Any]]) -> dict[str, Any]: total = len(resistors) nonempty = sum(1 for item in resistors if str(item.get("component_value") or "").strip()) parsed = sum(1 for item in resistors if item.get("value_parse_status") == "parsed") zero = sum( 1 for item in resistors if item.get("value_ohms") == 0 and item.get("value_parse_status") == "parsed" and item.get("assembly_status") != "not_fitted" ) zero_not_fitted = sum( 1 for item in resistors if item.get("value_ohms") == 0 and item.get("assembly_status") == "not_fitted" ) not_fitted = sum(1 for item in resistors if item.get("assembly_status") == "not_fitted") missing = sum( 1 for item in resistors if item.get("value_parse_status") in {"unparsed", "ambiguous"} or item.get("value_ohms") is None ) # missing = not successfully parsed (includes empty and unparsed non-empty) missing = total - parsed return { "resistors_total": total, "component_value_nonempty": nonempty, "value_parsed": parsed, "value_zero_ohm_fitted_or_unknown": zero, "value_zero_ohm_not_fitted": zero_not_fitted, "assembly_not_fitted": not_fitted, "value_missing_or_unparsed": missing, "component_value_source_status": "brd_footprint_field_limited_coverage", "example_available_tokens": ["120R", "120", "0R", "0"], "note": ( "Values come from BRD footprint component_value text only; " "most resistors have no reliable ohm text. Do not infer from package size." ), } def _attach_structured_resistor_links( annotations: Mapping[str, object], resistors: list[dict[str, Any]], touchpoints: list[dict[str, Any]], ) -> list[dict[str, Any]]: """Resolve optional annotations.resistor_links[] against PCB pad.net.""" raw = annotations.get("resistor_links", []) if not isinstance(raw, list): return [] resistor_by_ref = {str(item["reference"]): item for item in resistors} pin_ids = { str(pin.get("id")) for touchpoint in touchpoints for pin in touchpoint.get("pins", []) if isinstance(pin, Mapping) } resolved_links: list[dict[str, Any]] = [] for item in raw: if not isinstance(item, Mapping): continue reference = str(item.get("resistor_reference") or "") pad_number = item.get("pad_number") pad_number_s = None if pad_number is None else str(pad_number) claimed = item.get("claimed_net") claimed_s = None if claimed is None else str(claimed) source_pin_id = str(item.get("source_pin_id") or "") evidence_source = str(item.get("evidence_source") or "curated") note = str(item.get("note") or "") status = "resolved" pcb_net = None resistor = resistor_by_ref.get(reference) if not reference or resistor is None: status = "missing_reference" elif pad_number_s is None: status = "missing_pad" else: pad = next( ( row for row in resistor.get("pads", []) if isinstance(row, Mapping) and str(row.get("number")) == pad_number_s ), None, ) if pad is None: status = "missing_pad" else: pcb_net = pad.get("net") if claimed_s is not None and str(pcb_net or "") != claimed_s: status = "net_conflict" if source_pin_id and source_pin_id not in pin_ids and status == "resolved": # Non-fatal: keep resolved net compare; note orphan source id. note = (note + " ; source_pin_id not in touchpoints").strip(" ;") link = { "source_pin_id": source_pin_id, "resistor_reference": reference, "pad_number": pad_number_s, "claimed_net": claimed_s, "pcb_net": pcb_net, "status": status, "evidence_source": evidence_source, "note": note, } resolved_links.append(link) # Mirror onto matching pin.related_resistors when source pin exists. if source_pin_id: for touchpoint in touchpoints: for pin in touchpoint.get("pins", []): if str(pin.get("id")) != source_pin_id: continue related = list(pin.get("related_resistors") or []) related.append( { "source_pin_id": source_pin_id, "source_field": "resistor_links", "resistor_reference": reference, "pad_number": pad_number_s, "raw_context": note or evidence_source, "status": status, "pcb_net": pcb_net, "claimed_net": claimed_s, } ) pin["related_resistors"] = related return resolved_links def validate_structured_resistor_links(payload: Mapping[str, object]) -> None: links = payload.get("resistor_links") if links is None: return if not isinstance(links, list): raise ValueError("resistor_links must be a list") for link in links: if not isinstance(link, Mapping): raise ValueError("invalid resistor_links entry") status = link.get("status") if status in {"missing_reference", "missing_pad", "net_conflict"}: # net_conflict is published for UI; fail-closed only for missing ref/pad # when validating curated package integrity — net_conflict is allowed as data. if status in {"missing_reference", "missing_pad"}: raise ValueError( f"resistor_links {link.get('resistor_reference')} status={status}" ) def build_board_data( board: ParsedBoard, inventory: Mapping[str, object], annotations: Mapping[str, object], *, board_name: str, ) -> dict[str, Any]: annotations = expand_annotation_templates(annotations) touchpoints = [_touchpoint_dict(footprint, board.bounds) for footprint in select_touchpoints(board)] resistors = [ _resistor_dict(footprint, board.bounds) for footprint in sorted(select_resistors(board), key=lambda item: int(item.reference[1:])) ] touchpoint_index = {item["reference"]: item for item in touchpoints} validate_annotation_references(annotations, touchpoint_index) connector_profiles = _connector_profile_index(annotations) direct, by_net = _inventory_indexes(inventory) annotated_touchpoints = annotations.get("touchpoints", {}) for touchpoint in touchpoints: reference = touchpoint["reference"] profile_entry = connector_profiles.get(reference) if touchpoint["category"] == "CON" or profile_entry is not None: _apply_connector_profile(touchpoint, profile_entry) touchpoint_annotation = ( annotated_touchpoints.get(reference, {}) if isinstance(annotated_touchpoints, Mapping) else {} ) if isinstance(touchpoint_annotation, Mapping) and touchpoint_annotation.get("summary"): touchpoint["summary"] = str(touchpoint_annotation["summary"]) pin_annotations = ( touchpoint_annotation.get("pins", {}) if isinstance(touchpoint_annotation, Mapping) else {} ) for pin in touchpoint["pins"]: inventory_item = _inventory_match(reference, pin, direct, by_net) if inventory_item is not None: _merge_inventory(pin, inventory_item) annotation = pin_annotations.get(pin["number"], {}) if isinstance(pin_annotations, Mapping) else {} if isinstance(annotation, Mapping): _merge_annotation(pin, annotation) pin["programming"] = _programming_guidance(reference, pin) programming_annotation = annotation.get("programming", {}) if isinstance(annotation, Mapping) else {} if isinstance(programming_annotation, Mapping): _merge_programming_annotation(pin["programming"], programming_annotation) _refresh_recommendation(pin) link_conflicts = _attach_related_resistors(touchpoints, resistors) structured_links = _attach_structured_resistor_links(annotations, resistors, touchpoints) evidence_conflicts = _normalize_evidence_conflicts(annotations, resistors) # Link-derived missing_* are fatal at validate time; keep them out of the # published evidence_conflicts list unless they were curated. _ = link_conflicts category_counts = Counter(item["category"] for item in touchpoints) touchpoint_side_counts = Counter(item["side"] for item in touchpoints) resistor_side_counts = Counter(item["side"] for item in resistors) connector_touchpoints = [item for item in touchpoints if item["category"] == "CON"] resistor_pad_count = sum(len(item["pads"]) for item in resistors) resistor_electrical_pad_count = sum( 1 for item in resistors for pad in item["pads"] if pad.get("pad_role") == "electrical" ) value_coverage = _build_value_coverage(resistors) payload = { "schema": BOARD_DATA_SCHEMA_ID, "board": { "id": str(annotations.get("board_id") or inventory.get("board_id") or "unknown"), "name": board_name, "source_bounds": dict(board.bounds), "view_box": {"x": 0.0, "y": 0.0, "width": board.bounds["width"], "height": board.bounds["height"]}, }, "counts": { "footprints": board.footprint_count, "touchpoints": len(touchpoints), # counts.pads keeps historical touchpoint-pin semantics (not all PCB pads). "pads": sum(len(item["pins"]) for item in touchpoints), "resistors": len(resistors), "resistor_pads": resistor_pad_count, "resistor_electrical_pads": resistor_electrical_pad_count, "connector_contacts": sum( int(item["connector"]["contact_count"]) for item in connector_touchpoints ), "connector_auxiliary_pads": sum( int(item["connector"]["auxiliary_pad_count"]) for item in connector_touchpoints ), "categories": { "CON": category_counts.get("CON", 0), "J": category_counts.get("J", 0), "PL": category_counts.get("PL", 0), "TP": category_counts.get("TP", 0), "R": len(resistors), }, # Legacy alias: touchpoint sides only (NOT all entities / resistors). "sides": {key: touchpoint_side_counts.get(key, 0) for key in ("front", "back")}, "touchpoint_sides": { key: touchpoint_side_counts.get(key, 0) for key in ("front", "back") }, "resistor_sides": { key: resistor_side_counts.get(key, 0) for key in ("front", "back") }, }, "value_coverage": value_coverage, "component_value_source_status": value_coverage["component_value_source_status"], "touchpoints": touchpoints, "resistors": resistors, "resistor_links": structured_links, "evidence_conflicts": evidence_conflicts, "interfaces": list(annotations.get("interfaces", [])) if isinstance(annotations.get("interfaces", []), list) else [], "photo_overlay": annotations.get("photo_overlay"), } # Structural self-check only; annotation ⊆ index (Pass G) is enforced by # validate/regression against the product board, not every fixture build. if payload["counts"]["resistors"] != len(resistors): raise ValueError("resistor count mismatch while building board data") if payload["counts"]["resistor_pads"] != sum(len(item["pads"]) for item in resistors): raise ValueError("resistor pad count mismatch while building board data") return payload