| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797 |
- """Merge parsed board facts, pin inventory, and curated annotations."""
- from __future__ import annotations
- from collections import Counter
- from collections.abc import Mapping
- 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_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)
- def _category(reference: str) -> str:
- for prefix in ("CON", "PL", "TP", "J"):
- if reference.startswith(prefix):
- return prefix
- return "OTHER"
- 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"]},
- }
- 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 _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]
- 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_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)]
- 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)
- category_counts = Counter(item["category"] for item in touchpoints)
- side_counts = Counter(item["side"] for item in touchpoints)
- connector_touchpoints = [item for item in touchpoints if item["category"] == "CON"]
- return {
- "schema": "board-viewer-data-v1",
- "board": {
- "id": str(inventory.get("board_id") or annotations.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),
- "pads": sum(len(item["pins"]) for item in touchpoints),
- "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": {key: category_counts.get(key, 0) for key in ("CON", "J", "PL", "TP")},
- "sides": {key: side_counts.get(key, 0) for key in ("front", "back")},
- },
- "touchpoints": touchpoints,
- "interfaces": list(annotations.get("interfaces", [])) if isinstance(annotations.get("interfaces", []), list) else [],
- "photo_overlay": annotations.get("photo_overlay"),
- }
|