data.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. """Merge parsed board facts, pin inventory, and curated annotations."""
  2. from __future__ import annotations
  3. from collections import Counter
  4. from collections.abc import Mapping
  5. import math
  6. import re
  7. from typing import Any
  8. from .annotations import expand_annotation_templates, validate_annotation_references
  9. from .eligibility import evaluate_recommendation
  10. from .pcb import Footprint, Pad, ParsedBoard, select_resistors, select_touchpoints
  11. EVIDENCE_TIERS = {"board_database", "cross_verified", "name_inferred", "unknown"}
  12. CONNECTOR_ROW_TOLERANCE_MM = 0.05
  13. INTERNAL_NET = re.compile(r"^(?:N\d+|NET_\d+)$", re.IGNORECASE)
  14. POWER_NET = re.compile(r"^(?:VCC|VDD|VBAT|PWR|\+)", re.IGNORECASE)
  15. ANNOTATION_RESISTOR_REF = re.compile(r"(?<![A-Za-z0-9.])R(\d+)\b")
  16. ANNOTATION_RESISTOR_PAD = re.compile(r"(?<![A-Za-z0-9.])R(\d+)\.(\d+)\b")
  17. # 4.7k / 4k7 / 4700 / 22R / 0R / 120 ohm / R / 120R/1%/0805
  18. _RESISTANCE_COMPACT = re.compile(
  19. r"(?P<a>\d+(?:\.\d+)?)(?P<prefix>[rRkKmM])(?P<b>\d+)?|"
  20. r"(?P<plain>\d+(?:\.\d+)?)\s*(?:ohm|ohms|Ω)?\b",
  21. re.IGNORECASE,
  22. )
  23. _RESISTANCE_REJECT = re.compile(
  24. r"^(?:dnp|nc|n/?c|no\s*connect|0603|0805|0402|1206|1210|2010|2512)$",
  25. re.IGNORECASE,
  26. )
  27. _STRUCTURED_ZERO_OHM = re.compile(
  28. r"^R\s*/\s*0(?:\s*/|\s*$)",
  29. re.IGNORECASE,
  30. )
  31. _NOT_FITTED_TOKEN = re.compile(
  32. r"(?:/\s*NC\b|\bDNP\b|\bN\s*/\s*C\b|\bnot[\s-]?fitted\b)",
  33. re.IGNORECASE,
  34. )
  35. _PACKAGE_SIZE_TOKEN = re.compile(
  36. r"^(?:0603|0805|0402|1206|1210|2010|2512)$",
  37. re.IGNORECASE,
  38. )
  39. def detect_assembly_status(raw: str | None) -> str:
  40. """Thin assembly hint from component_value text: unknown | fitted | not_fitted."""
  41. text = str(raw or "").strip()
  42. if not text:
  43. return "unknown"
  44. if _NOT_FITTED_TOKEN.search(text):
  45. return "not_fitted"
  46. return "unknown"
  47. def _is_structured_zero_ohm(raw: str) -> bool:
  48. compact = re.sub(r"\s+", "", str(raw or ""))
  49. # R/0/1%/0805 or R/0/1%/0805/NC — not R/120R/...
  50. return bool(re.match(r"^R/0(?:/|$)", compact, flags=re.IGNORECASE))
  51. BOARD_DATA_SCHEMA_ID = "board-viewer-data-v2"
  52. def _category(reference: str) -> str:
  53. for prefix in ("CON", "PL", "TP", "J", "R"):
  54. if reference.startswith(prefix) and (prefix != "R" or reference[1:].isdigit()):
  55. return prefix
  56. return "OTHER"
  57. def parse_resistance_ohms(raw: str | None) -> float | None:
  58. """Parse a human resistor value into ohms. Returns None when not parseable."""
  59. text = str(raw or "").strip()
  60. if not text:
  61. return None
  62. compact = re.sub(r"\s+", "", text)
  63. if _RESISTANCE_REJECT.fullmatch(compact):
  64. return None
  65. if _PACKAGE_SIZE_TOKEN.fullmatch(compact):
  66. return None
  67. # Structured footprint strings: "R / 0 /1%/0805", "R/0/1%/1210", optional /NC.
  68. if _is_structured_zero_ohm(text):
  69. return 0.0
  70. # Bare footprint size / DNP tokens mixed in manufacturer strings stay rejected
  71. # unless an explicit resistance token is also present.
  72. # Prefer explicit ohm tokens inside footprint strings such as "R / 120R/1%/0805".
  73. candidates = list(_RESISTANCE_COMPACT.finditer(compact))
  74. if not candidates:
  75. candidates = list(_RESISTANCE_COMPACT.finditer(text))
  76. parsed: list[float] = []
  77. for match in candidates:
  78. if match.group("plain") is not None and match.group("a") is None:
  79. # Bare number only counts when the whole value is numeric-ish.
  80. if re.fullmatch(r"\d+(?:\.\d+)?", compact):
  81. parsed.append(float(match.group("plain")))
  82. continue
  83. amount = float(match.group("a"))
  84. prefix = (match.group("prefix") or "r").lower()
  85. fraction = match.group("b")
  86. if fraction:
  87. amount = float(f"{match.group('a')}.{fraction}")
  88. multiplier = {"r": 1.0, "k": 1_000.0, "m": 1_000_000.0}[prefix]
  89. if amount < 0:
  90. continue
  91. parsed.append(amount * multiplier)
  92. if not parsed:
  93. return None
  94. # Ambiguous multi-value strings are treated as unparsed (conservative).
  95. first = parsed[0]
  96. if any(not math.isclose(value, first, rel_tol=0, abs_tol=1e-9) for value in parsed[1:]):
  97. return None
  98. return first
  99. def resistance_parse_status(raw: str | None, ohms: float | None = None) -> str:
  100. """Return parsed | unparsed | ambiguous for a component_value string."""
  101. text = str(raw or "").strip()
  102. if not text:
  103. return "unparsed"
  104. value = ohms if ohms is not None else parse_resistance_ohms(text)
  105. if value is not None:
  106. return "parsed"
  107. compact = re.sub(r"\s+", "", text)
  108. if _RESISTANCE_REJECT.fullmatch(compact):
  109. return "unparsed"
  110. candidates = list(_RESISTANCE_COMPACT.finditer(compact)) or list(_RESISTANCE_COMPACT.finditer(text))
  111. values: list[float] = []
  112. for match in candidates:
  113. if match.group("plain") is not None and match.group("a") is None:
  114. continue
  115. if match.group("a") is None:
  116. continue
  117. amount = float(match.group("a"))
  118. prefix = (match.group("prefix") or "r").lower()
  119. fraction = match.group("b")
  120. if fraction:
  121. amount = float(f"{match.group('a')}.{fraction}")
  122. values.append(amount * {"r": 1.0, "k": 1_000.0, "m": 1_000_000.0}[prefix])
  123. if len(values) >= 2 and any(not math.isclose(values[0], item, abs_tol=1e-9) for item in values[1:]):
  124. return "ambiguous"
  125. return "unparsed"
  126. def resistance_value_tokens(raw: str | None, ohms: float | None = None) -> list[str]:
  127. """Search tokens: normalized raw forms plus 4k7 / 4.7k / 4700 equivalents."""
  128. text = str(raw or "").strip()
  129. tokens: list[str] = []
  130. if text:
  131. lowered = text.casefold()
  132. tokens.append(lowered)
  133. tokens.append(re.sub(r"\s+", "", lowered))
  134. value = ohms if ohms is not None else parse_resistance_ohms(text)
  135. if value is None:
  136. return _unique_strings(tokens)
  137. def add(token: str) -> None:
  138. cleaned = token.casefold().strip()
  139. if cleaned and cleaned not in tokens:
  140. tokens.append(cleaned)
  141. if value == 0:
  142. add("0")
  143. add("0r")
  144. add("0ohm")
  145. return tokens
  146. if value >= 1_000_000 and math.isclose(value % 1_000_000, 0, abs_tol=1e-9):
  147. megs = value / 1_000_000
  148. add(f"{_format_resistance_number(megs)}m")
  149. if value >= 1000:
  150. kilos = value / 1000
  151. add(f"{_format_resistance_number(kilos)}k")
  152. # 4.7k ↔ 4k7
  153. if not float(kilos).is_integer():
  154. whole, frac = f"{kilos:.12g}".split(".", 1)
  155. add(f"{whole}k{frac}")
  156. elif kilos >= 1:
  157. add(f"{_format_resistance_number(kilos)}k")
  158. if value < 1000 or value.is_integer():
  159. add(f"{_format_resistance_number(value)}")
  160. add(f"{_format_resistance_number(value)}r")
  161. add(f"{_format_resistance_number(value)}ohm")
  162. return tokens
  163. def _format_resistance_number(value: float) -> str:
  164. if float(value).is_integer():
  165. return str(int(value))
  166. return f"{value:.12g}"
  167. def extract_annotation_resistor_refs(*texts: object) -> set[str]:
  168. """Extract discrete resistor refs from annotation text; skip FPGA balls like U3.R4."""
  169. refs: set[str] = set()
  170. for value in texts:
  171. if isinstance(value, list):
  172. for item in value:
  173. refs.update(extract_annotation_resistor_refs(item))
  174. continue
  175. if value is None:
  176. continue
  177. for match in ANNOTATION_RESISTOR_REF.finditer(str(value)):
  178. refs.add(f"R{match.group(1)}")
  179. return refs
  180. def _view_point(x: float, y: float, bounds: Mapping[str, float]) -> dict[str, float]:
  181. return {"x": x - bounds["x"], "y": y - bounds["y"]}
  182. def _view_bounds(item: Mapping[str, float], board_bounds: Mapping[str, float]) -> dict[str, float]:
  183. return {
  184. "x": item["x"] - board_bounds["x"],
  185. "y": item["y"] - board_bounds["y"],
  186. "width": item["width"],
  187. "height": item["height"],
  188. }
  189. def _pin_dict(
  190. reference: str,
  191. category: str,
  192. pad: Pad,
  193. board_bounds: Mapping[str, float],
  194. source_index: int,
  195. ) -> dict[str, Any]:
  196. role = "mechanical" if pad.mechanical else ("unknown" if category == "CON" else "contact")
  197. return {
  198. "id": f"{reference}.pad-{source_index + 1}",
  199. "number": pad.number,
  200. "pad_role": role,
  201. "row": None,
  202. "column": None,
  203. "board_order": None,
  204. "mechanical": pad.mechanical,
  205. "electrical": pad.electrical,
  206. "net": pad.net,
  207. "position": {"x": pad.x, "y": pad.y},
  208. "view_position": _view_point(pad.x, pad.y, board_bounds),
  209. "size": {
  210. "width": pad.width,
  211. "height": pad.height,
  212. "drill_width": pad.drill_width,
  213. "drill_height": pad.drill_height,
  214. },
  215. "rotation": pad.rotation,
  216. "shape": pad.shape,
  217. "layers": list(pad.layers),
  218. "direction": "unknown",
  219. "external_level": "unknown",
  220. "function_category": _classify_function(pad.net, []),
  221. "reserved": False,
  222. "fixed_load_conflict": False,
  223. "board_pull": None,
  224. "adc_pulltype": None,
  225. "active_level": "unknown",
  226. "polarity": "unknown",
  227. "external_components": [],
  228. "summary": _raw_pin_summary(pad),
  229. "path": [],
  230. "evidence_tier": "board_database",
  231. "evidence_sources": ["board:kicad_import"],
  232. "fpga": None,
  233. "mcu": None,
  234. "programming": {},
  235. "recommendation": {"eligible": False, "reasons": ["pin_evidence_not_verified"]},
  236. "related_resistors": [],
  237. }
  238. def _raw_pin_summary(pad: Pad) -> str:
  239. if pad.mechanical:
  240. return "机械焊盘"
  241. if pad.net:
  242. return f"板内网络 {pad.net}"
  243. return "未命名电气焊盘"
  244. def _classify_function(net: str | None, capabilities: list[str]) -> str:
  245. ordered = (
  246. "uart_tx",
  247. "uart_rx",
  248. "pwm",
  249. "fan_tach",
  250. "tach",
  251. "presence",
  252. "gpio_output",
  253. "gpio_input",
  254. "gpio",
  255. )
  256. normalized = {str(item).lower() for item in capabilities}
  257. for category in ordered:
  258. if category in normalized:
  259. return category
  260. upper_net = str(net or "").upper()
  261. if upper_net in {"GND", "AGND", "DGND", "PGND"}:
  262. return "ground"
  263. if upper_net.startswith(("+", "VCC", "VDD", "VBAT", "PWR")):
  264. return "power"
  265. if "PWM" in upper_net:
  266. return "pwm"
  267. if "TX" in upper_net and "UART" in upper_net:
  268. return "uart_tx"
  269. if "RX" in upper_net and "UART" in upper_net:
  270. return "uart_rx"
  271. if "FG" in upper_net or "TACH" in upper_net:
  272. return "tach"
  273. if "INSTALL" in upper_net or "PRESENT" in upper_net:
  274. return "presence"
  275. return "unknown"
  276. def _touchpoint_dict(footprint: Footprint, board_bounds: Mapping[str, float]) -> dict[str, Any]:
  277. category = _category(footprint.reference)
  278. category_name = {"CON": "连接器", "J": "接口", "PL": "插座", "TP": "测试点"}.get(category, category)
  279. return {
  280. "reference": footprint.reference,
  281. "category": category,
  282. "component_value": footprint.component_value,
  283. "position": {"x": footprint.x, "y": footprint.y},
  284. "view_position": _view_point(footprint.x, footprint.y, board_bounds),
  285. "rotation": footprint.rotation,
  286. "bounds": dict(footprint.bounds),
  287. "view_bounds": _view_bounds(footprint.bounds, board_bounds),
  288. "side": footprint.side,
  289. "summary": f"{category_name},用途未注释",
  290. "connector": None,
  291. "pins": [
  292. _pin_dict(footprint.reference, category, pad, board_bounds, index)
  293. for index, pad in enumerate(footprint.pads)
  294. ],
  295. }
  296. def _pad_board_bounds(pad: Pad) -> dict[str, float]:
  297. width = max(pad.width, pad.drill_width, 0.5)
  298. height = max(pad.height, pad.drill_height, 0.5)
  299. radians = math.radians(pad.rotation)
  300. cosine, sine = abs(math.cos(radians)), abs(math.sin(radians))
  301. half_width = (width * cosine + height * sine) / 2
  302. half_height = (width * sine + height * cosine) / 2
  303. return {
  304. "x": pad.x - half_width,
  305. "y": pad.y - half_height,
  306. "width": half_width * 2,
  307. "height": half_height * 2,
  308. }
  309. def _resistor_pad_dict(
  310. reference: str,
  311. pad: Pad,
  312. board_bounds: Mapping[str, float],
  313. ) -> dict[str, Any]:
  314. bounds = _pad_board_bounds(pad)
  315. return {
  316. "id": f"{reference}.pad-{pad.number or 'x'}",
  317. "number": pad.number,
  318. "net": pad.net,
  319. "position": {"x": pad.x, "y": pad.y},
  320. "view_position": _view_point(pad.x, pad.y, board_bounds),
  321. "bounds": bounds,
  322. "view_bounds": _view_bounds(bounds, board_bounds),
  323. "pad_role": "mechanical" if pad.mechanical else "electrical",
  324. "size": {
  325. "width": pad.width,
  326. "height": pad.height,
  327. "drill_width": pad.drill_width,
  328. "drill_height": pad.drill_height,
  329. },
  330. "rotation": pad.rotation,
  331. "shape": pad.shape,
  332. "layers": list(pad.layers),
  333. }
  334. def _resistor_dict(footprint: Footprint, board_bounds: Mapping[str, float]) -> dict[str, Any]:
  335. ohms = parse_resistance_ohms(footprint.component_value)
  336. assembly = detect_assembly_status(footprint.component_value)
  337. pads = [_resistor_pad_dict(footprint.reference, pad, board_bounds) for pad in footprint.pads]
  338. nets = [pad["net"] for pad in pads if pad["pad_role"] == "electrical" and pad["net"]]
  339. value_label = footprint.component_value.strip() or "阻值未标注"
  340. net_label = "↔".join(nets) if nets else "无命名网络"
  341. status_note = " · 未装/NC" if assembly == "not_fitted" else ""
  342. return {
  343. "reference": footprint.reference,
  344. "category": "R",
  345. "component_value": footprint.component_value,
  346. "value_ohms": ohms,
  347. "value_tokens": resistance_value_tokens(footprint.component_value, ohms),
  348. "value_parse_status": resistance_parse_status(footprint.component_value, ohms),
  349. "assembly_status": assembly,
  350. "position": {"x": footprint.x, "y": footprint.y},
  351. "view_position": _view_point(footprint.x, footprint.y, board_bounds),
  352. "rotation": footprint.rotation,
  353. "bounds": dict(footprint.bounds),
  354. "view_bounds": _view_bounds(footprint.bounds, board_bounds),
  355. "side": footprint.side,
  356. "summary": f"电阻 {value_label} · {net_label}{status_note}",
  357. "pads": pads,
  358. }
  359. def _iter_annotation_text_chunks(value: object) -> list[str]:
  360. if value is None:
  361. return []
  362. if isinstance(value, list):
  363. chunks: list[str] = []
  364. for item in value:
  365. chunks.extend(_iter_annotation_text_chunks(item))
  366. return chunks
  367. text = str(value).strip()
  368. return [text] if text else []
  369. def _resolve_related_resistors_for_pin(
  370. pin: Mapping[str, Any],
  371. resistor_by_ref: Mapping[str, Mapping[str, Any]],
  372. ) -> list[dict[str, Any]]:
  373. """Build structured related_resistors[] from path / external_components."""
  374. links: list[dict[str, Any]] = []
  375. seen: set[tuple[str, str | None, str]] = set()
  376. for field_name in ("path", "external_components"):
  377. for chunk in _iter_annotation_text_chunks(pin.get(field_name)):
  378. pad_hits = list(ANNOTATION_RESISTOR_PAD.finditer(chunk))
  379. covered_spans = {(match.start(), match.end()) for match in pad_hits}
  380. for match in pad_hits:
  381. reference = f"R{match.group(1)}"
  382. pad_number = match.group(2)
  383. key = (reference, pad_number, field_name)
  384. if key in seen:
  385. continue
  386. seen.add(key)
  387. resistor = resistor_by_ref.get(reference)
  388. pcb_net = None
  389. status = "resolved"
  390. if resistor is None:
  391. status = "missing_reference"
  392. else:
  393. pad = next(
  394. (
  395. item
  396. for item in resistor.get("pads", [])
  397. if isinstance(item, Mapping) and str(item.get("number")) == pad_number
  398. ),
  399. None,
  400. )
  401. if pad is None:
  402. status = "missing_pad"
  403. else:
  404. pcb_net = pad.get("net")
  405. links.append(
  406. {
  407. "source_pin_id": str(pin.get("id") or ""),
  408. "source_field": field_name,
  409. "resistor_reference": reference,
  410. "pad_number": pad_number,
  411. "raw_context": chunk,
  412. "status": status,
  413. "pcb_net": pcb_net,
  414. "claimed_net": None,
  415. }
  416. )
  417. for match in ANNOTATION_RESISTOR_REF.finditer(chunk):
  418. span = (match.start(), match.end())
  419. if any(span[0] >= start and span[1] <= end for start, end in covered_spans):
  420. continue
  421. # Skip FPGA endpoints like U3.R4 (negative lookbehind already handles most).
  422. if match.start() >= 2 and chunk[match.start() - 1] == ".":
  423. continue
  424. reference = f"R{match.group(1)}"
  425. key = (reference, None, field_name)
  426. if key in seen:
  427. continue
  428. seen.add(key)
  429. resistor = resistor_by_ref.get(reference)
  430. status = "resolved" if resistor is not None else "missing_reference"
  431. links.append(
  432. {
  433. "source_pin_id": str(pin.get("id") or ""),
  434. "source_field": field_name,
  435. "resistor_reference": reference,
  436. "pad_number": None,
  437. "raw_context": chunk,
  438. "status": status,
  439. "pcb_net": None,
  440. "claimed_net": None,
  441. }
  442. )
  443. return links
  444. def _attach_related_resistors(
  445. touchpoints: list[dict[str, Any]],
  446. resistors: list[dict[str, Any]],
  447. ) -> list[dict[str, Any]]:
  448. resistor_by_ref = {str(item["reference"]): item for item in resistors}
  449. conflicts: list[dict[str, Any]] = []
  450. for touchpoint in touchpoints:
  451. for pin in touchpoint.get("pins", []):
  452. related = _resolve_related_resistors_for_pin(pin, resistor_by_ref)
  453. pin["related_resistors"] = related
  454. for link in related:
  455. if link["status"] == "missing_pad":
  456. conflicts.append(
  457. {
  458. "id": f"missing-pad-{link['resistor_reference']}.{link['pad_number']}",
  459. "subject_reference": link["resistor_reference"],
  460. "status": "unresolved",
  461. "kind": "missing_pad",
  462. "source_pin_id": link["source_pin_id"],
  463. "detail": link,
  464. }
  465. )
  466. elif link["status"] == "missing_reference":
  467. conflicts.append(
  468. {
  469. "id": f"missing-ref-{link['resistor_reference']}-{link['source_pin_id']}",
  470. "subject_reference": link["resistor_reference"],
  471. "status": "unresolved",
  472. "kind": "missing_reference",
  473. "source_pin_id": link["source_pin_id"],
  474. "detail": link,
  475. }
  476. )
  477. return conflicts
  478. def _normalize_evidence_conflicts(
  479. annotations: Mapping[str, object],
  480. resistors: list[dict[str, Any]],
  481. ) -> list[dict[str, Any]]:
  482. """Copy curated evidence conflicts; never override primary PCB pad nets."""
  483. raw = annotations.get("evidence_conflicts", [])
  484. if not isinstance(raw, list):
  485. return []
  486. index = {str(item["reference"]) for item in resistors}
  487. normalized: list[dict[str, Any]] = []
  488. for item in raw:
  489. if not isinstance(item, Mapping):
  490. continue
  491. subject = str(item.get("subject_reference") or "")
  492. entry = {
  493. "id": str(item.get("id") or subject or "evidence-conflict"),
  494. "subject_reference": subject,
  495. "status": str(item.get("status") or "unresolved"),
  496. "kind": str(item.get("kind") or "cross_evidence"),
  497. "summary": str(item.get("summary") or ""),
  498. "primary_source": str(item.get("primary_source") or "pcb_pad_net"),
  499. "claims": list(item.get("claims") or []) if isinstance(item.get("claims"), list) else [],
  500. "subject_in_pcb_index": subject in index,
  501. }
  502. # Attach live PCB pad facts for the subject when present.
  503. resistor = next((row for row in resistors if row["reference"] == subject), None)
  504. if resistor is not None:
  505. entry["pcb_pads"] = [
  506. {
  507. "number": pad.get("number"),
  508. "net": pad.get("net"),
  509. "pad_role": pad.get("pad_role"),
  510. }
  511. for pad in resistor.get("pads", [])
  512. if isinstance(pad, Mapping)
  513. ]
  514. normalized.append(entry)
  515. return normalized
  516. def annotation_resistor_refs_from_board_data(payload: Mapping[str, object]) -> set[str]:
  517. refs: set[str] = set()
  518. touchpoints = payload.get("touchpoints", [])
  519. if not isinstance(touchpoints, list):
  520. return refs
  521. for touchpoint in touchpoints:
  522. if not isinstance(touchpoint, Mapping):
  523. continue
  524. pins = touchpoint.get("pins", [])
  525. if not isinstance(pins, list):
  526. continue
  527. for pin in pins:
  528. if not isinstance(pin, Mapping):
  529. continue
  530. refs.update(
  531. extract_annotation_resistor_refs(
  532. pin.get("path"),
  533. pin.get("external_components"),
  534. )
  535. )
  536. return refs
  537. def validate_resistor_index(
  538. payload: Mapping[str, object],
  539. *,
  540. pcb_references: set[str] | None = None,
  541. ) -> None:
  542. """Fail-closed resistor index checks (passes A/B/G when inputs are available)."""
  543. schema = payload.get("schema")
  544. if schema not in (None, "board-viewer-data-v1", BOARD_DATA_SCHEMA_ID):
  545. raise ValueError(f"unsupported board-data schema: {schema}")
  546. if schema == "board-viewer-data-v1":
  547. raise ValueError("board-data schema is stale v1; regenerate for board-viewer-data-v2")
  548. resistors = payload.get("resistors")
  549. if not isinstance(resistors, list):
  550. raise ValueError("board-data resistors[] missing")
  551. counts = payload.get("counts")
  552. if not isinstance(counts, Mapping):
  553. raise ValueError("board-data counts missing")
  554. references = [str(item.get("reference") or "") for item in resistors if isinstance(item, Mapping)]
  555. if len(references) != len(set(references)):
  556. raise ValueError("duplicate resistor references in board-data")
  557. if counts.get("resistors") != len(references):
  558. raise ValueError(
  559. f"counts.resistors={counts.get('resistors')} != len(resistors)={len(references)}"
  560. )
  561. pad_total = 0
  562. electrical_total = 0
  563. board = payload.get("board")
  564. view_box = board.get("view_box") if isinstance(board, Mapping) else None
  565. if not isinstance(view_box, Mapping):
  566. raise ValueError("board view_box missing")
  567. max_x = float(view_box["width"])
  568. max_y = float(view_box["height"])
  569. required_pad_fields = (
  570. "id",
  571. "number",
  572. "net",
  573. "position",
  574. "view_position",
  575. "bounds",
  576. "view_bounds",
  577. "pad_role",
  578. "size",
  579. "rotation",
  580. "shape",
  581. "layers",
  582. )
  583. for item in resistors:
  584. if not isinstance(item, Mapping):
  585. raise ValueError("invalid resistor entry")
  586. if item.get("category") != "R":
  587. raise ValueError(f"{item.get('reference')} category must be R")
  588. if item.get("side") not in {"front", "back"}:
  589. raise ValueError(f"{item.get('reference')} has invalid side")
  590. if "value_parse_status" in item and item.get("value_parse_status") not in {
  591. "parsed",
  592. "unparsed",
  593. "ambiguous",
  594. }:
  595. raise ValueError(f"{item.get('reference')} invalid value_parse_status")
  596. if "assembly_status" in item and item.get("assembly_status") not in {
  597. "unknown",
  598. "fitted",
  599. "not_fitted",
  600. }:
  601. raise ValueError(f"{item.get('reference')} invalid assembly_status")
  602. pads = item.get("pads")
  603. if not isinstance(pads, list) or not pads:
  604. raise ValueError(f"{item.get('reference')} has no pads")
  605. electrical = [
  606. pad for pad in pads
  607. if isinstance(pad, Mapping) and pad.get("pad_role") == "electrical"
  608. ]
  609. if not electrical:
  610. raise ValueError(f"{item.get('reference')} has no electrical pad")
  611. pad_total += len(pads)
  612. electrical_total += len(electrical)
  613. for pad in pads:
  614. if not isinstance(pad, Mapping):
  615. raise ValueError(f"{item.get('reference')} has invalid pad")
  616. missing = [name for name in required_pad_fields if name not in pad]
  617. if missing:
  618. raise ValueError(
  619. f"{item.get('reference')} pad missing fields: {', '.join(missing)}"
  620. )
  621. if not isinstance(pad.get("layers"), list):
  622. raise ValueError(f"{item.get('reference')} pad layers must be a list")
  623. position = item.get("view_position")
  624. if not isinstance(position, Mapping):
  625. raise ValueError(f"{item.get('reference')} missing view_position")
  626. x = float(position["x"])
  627. y = float(position["y"])
  628. if x < -1.0 or y < -1.0 or x > max_x + 1.0 or y > max_y + 1.0:
  629. raise ValueError(f"{item.get('reference')} view_position outside board bounds")
  630. if counts.get("resistor_pads") != pad_total:
  631. raise ValueError(
  632. f"counts.resistor_pads={counts.get('resistor_pads')} != pad_total={pad_total}"
  633. )
  634. if "resistor_electrical_pads" in counts and counts.get("resistor_electrical_pads") != electrical_total:
  635. raise ValueError(
  636. "counts.resistor_electrical_pads does not match electrical pad total"
  637. )
  638. categories = counts.get("categories")
  639. if not isinstance(categories, Mapping) or categories.get("R") != len(references):
  640. raise ValueError("counts.categories.R does not match resistors[]")
  641. touchpoint_sides = counts.get("touchpoint_sides") or counts.get("sides")
  642. resistor_sides = counts.get("resistor_sides")
  643. if isinstance(touchpoint_sides, Mapping):
  644. touchpoints = payload.get("touchpoints")
  645. if isinstance(touchpoints, list):
  646. expected = Counter(
  647. str(item.get("side")) for item in touchpoints if isinstance(item, Mapping)
  648. )
  649. if int(touchpoint_sides.get("front", -1)) != expected.get("front", 0) or int(
  650. touchpoint_sides.get("back", -1)
  651. ) != expected.get("back", 0):
  652. raise ValueError("counts.touchpoint_sides does not match touchpoints[]")
  653. if isinstance(resistor_sides, Mapping):
  654. expected_r = Counter(str(item.get("side")) for item in resistors if isinstance(item, Mapping))
  655. if int(resistor_sides.get("front", -1)) != expected_r.get("front", 0) or int(
  656. resistor_sides.get("back", -1)
  657. ) != expected_r.get("back", 0):
  658. raise ValueError("counts.resistor_sides does not match resistors[]")
  659. if int(resistor_sides.get("front", 0)) + int(resistor_sides.get("back", 0)) != len(references):
  660. raise ValueError("resistor_sides front+back != resistors total")
  661. if pcb_references is not None and set(references) != pcb_references:
  662. missing = sorted(pcb_references - set(references), key=lambda value: int(value[1:]))
  663. extra = sorted(set(references) - pcb_references, key=lambda value: int(value[1:]))
  664. raise ValueError(
  665. f"resistor set mismatch vs PCB: missing={missing[:20]} extra={extra[:20]}"
  666. )
  667. annotated = annotation_resistor_refs_from_board_data(payload)
  668. index = set(references)
  669. orphaned = sorted(annotated - index, key=lambda value: int(value[1:]))
  670. if orphaned:
  671. raise ValueError(
  672. "annotation path/external_components resistor refs missing from index: "
  673. + ", ".join(orphaned[:40])
  674. )
  675. # G2: explicit R#.pad mentions must resolve to real pads.
  676. resistor_pads = {
  677. (str(item.get("reference")), str(pad.get("number")))
  678. for item in resistors
  679. if isinstance(item, Mapping)
  680. for pad in item.get("pads", [])
  681. if isinstance(pad, Mapping)
  682. }
  683. for touchpoint in payload.get("touchpoints", []) if isinstance(payload.get("touchpoints"), list) else []:
  684. if not isinstance(touchpoint, Mapping):
  685. continue
  686. for pin in touchpoint.get("pins", []) if isinstance(touchpoint.get("pins"), list) else []:
  687. if not isinstance(pin, Mapping):
  688. continue
  689. related = pin.get("related_resistors")
  690. if isinstance(related, list):
  691. for link in related:
  692. if not isinstance(link, Mapping):
  693. continue
  694. if link.get("status") in {"missing_reference", "missing_pad"}:
  695. raise ValueError(
  696. f"related resistor link unresolved: {link.get('resistor_reference')} "
  697. f"status={link.get('status')} pin={link.get('source_pin_id')}"
  698. )
  699. for field_name in ("path", "external_components"):
  700. for chunk in _iter_annotation_text_chunks(pin.get(field_name)):
  701. for match in ANNOTATION_RESISTOR_PAD.finditer(chunk):
  702. key = (f"R{match.group(1)}", match.group(2))
  703. if key not in resistor_pads:
  704. raise ValueError(
  705. f"annotation {field_name} pad {key[0]}.{key[1]} missing from index"
  706. )
  707. def _connector_profile_index(
  708. annotations: Mapping[str, object],
  709. ) -> dict[str, tuple[str, Mapping[str, object]]]:
  710. result: dict[str, tuple[str, Mapping[str, object]]] = {}
  711. profiles = annotations.get("connector_profiles", {})
  712. if not isinstance(profiles, Mapping):
  713. return result
  714. for profile_name, profile in profiles.items():
  715. if not isinstance(profile, Mapping):
  716. continue
  717. references = profile.get("references", [])
  718. if not isinstance(references, list):
  719. continue
  720. for reference in references:
  721. result[str(reference)] = (str(profile_name), profile)
  722. return result
  723. def _cluster_contact_rows(pins: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
  724. rows: list[list[dict[str, Any]]] = []
  725. row_y: list[float] = []
  726. ordered = sorted(
  727. pins,
  728. key=lambda item: (float(item["position"]["y"]), float(item["position"]["x"])),
  729. )
  730. for pin in ordered:
  731. y = float(pin["position"]["y"])
  732. if not rows or abs(y - row_y[-1]) > CONNECTOR_ROW_TOLERANCE_MM:
  733. rows.append([pin])
  734. row_y.append(y)
  735. continue
  736. rows[-1].append(pin)
  737. row_y[-1] = sum(float(item["position"]["y"]) for item in rows[-1]) / len(rows[-1])
  738. for row in rows:
  739. row.sort(key=lambda item: (float(item["position"]["x"]), str(item["number"])))
  740. return rows
  741. def _pin_sort_key(pin: Mapping[str, object]) -> tuple[int, int, str]:
  742. role_order = {"contact": 0, "shield": 1, "mechanical": 2, "unknown": 3}
  743. board_order = pin.get("board_order")
  744. return (
  745. role_order.get(str(pin.get("pad_role")), 4),
  746. int(board_order) if isinstance(board_order, int) else 1_000_000,
  747. str(pin.get("id") or ""),
  748. )
  749. def _apply_connector_profile(
  750. touchpoint: dict[str, Any],
  751. profile_entry: tuple[str, Mapping[str, object]] | None,
  752. ) -> None:
  753. pins = touchpoint["pins"]
  754. if profile_entry is None:
  755. touchpoint["connector"] = {
  756. "profile": None,
  757. "review_status": "unknown",
  758. "view": "board_front",
  759. "contact_count": 0,
  760. "auxiliary_pad_count": len(pins),
  761. "rows": 0,
  762. "columns": 0,
  763. "contact_grid": [],
  764. "contact_order": [],
  765. "sources": [],
  766. }
  767. pins.sort(key=_pin_sort_key)
  768. return
  769. profile_name, profile = profile_entry
  770. contacts = {str(value) for value in profile.get("contact_pins", [])}
  771. shields = {str(value) for value in profile.get("shield_pads", [])}
  772. for pin in pins:
  773. number = str(pin["number"])
  774. if pin["mechanical"]:
  775. pin["pad_role"] = "mechanical"
  776. elif number in contacts:
  777. pin["pad_role"] = "contact"
  778. elif number in shields:
  779. pin["pad_role"] = "shield"
  780. else:
  781. pin["pad_role"] = "unknown"
  782. contact_pins = [pin for pin in pins if pin["pad_role"] == "contact"]
  783. rows = _cluster_contact_rows(contact_pins)
  784. contact_grid: list[list[str]] = []
  785. order = 1
  786. for row_number, row in enumerate(rows, start=1):
  787. grid_row: list[str] = []
  788. for column_number, pin in enumerate(row, start=1):
  789. pin["row"] = row_number
  790. pin["column"] = column_number
  791. pin["board_order"] = order
  792. grid_row.append(str(pin["number"]))
  793. order += 1
  794. contact_grid.append(grid_row)
  795. touchpoint["connector"] = {
  796. "profile": profile_name,
  797. "review_status": str(profile.get("evidence_tier") or "unknown"),
  798. "view": "board_front",
  799. "contact_count": len(contact_pins),
  800. "auxiliary_pad_count": len(pins) - len(contact_pins),
  801. "rows": len(contact_grid),
  802. "columns": max((len(row) for row in contact_grid), default=0),
  803. "contact_grid": contact_grid,
  804. "contact_order": [number for row in contact_grid for number in row],
  805. "sources": [str(value) for value in profile.get("sources", [])],
  806. }
  807. pins.sort(key=_pin_sort_key)
  808. def _inventory_indexes(inventory: Mapping[str, object]) -> tuple[dict[tuple[str, str], Mapping[str, object]], dict[str, list[Mapping[str, object]]]]:
  809. direct: dict[tuple[str, str], Mapping[str, object]] = {}
  810. by_net: dict[str, list[Mapping[str, object]]] = {}
  811. pins = inventory.get("pins", [])
  812. if not isinstance(pins, list):
  813. return direct, by_net
  814. for item in pins:
  815. if not isinstance(item, Mapping):
  816. continue
  817. connector = item.get("board_connector")
  818. connector_pin = item.get("connector_pin")
  819. if connector and connector_pin is not None:
  820. direct[(str(connector), str(connector_pin))] = item
  821. for name in (item.get("function_net"), item.get("signal")):
  822. if name:
  823. by_net.setdefault(str(name), []).append(item)
  824. return direct, by_net
  825. def _inventory_match(
  826. reference: str,
  827. pin: Mapping[str, object],
  828. direct: Mapping[tuple[str, str], Mapping[str, object]],
  829. by_net: Mapping[str, list[Mapping[str, object]]],
  830. ) -> Mapping[str, object] | None:
  831. key = (reference, str(pin.get("number", "")))
  832. if key in direct:
  833. item = direct[key]
  834. expected_net = item.get("connector_signal") or item.get("function_net") or item.get("signal")
  835. actual_net = pin.get("net")
  836. if expected_net and actual_net and str(expected_net) != str(actual_net):
  837. raise ValueError(
  838. f"connector net mismatch {reference}.{pin.get('number')}: "
  839. f"board={actual_net} inventory={expected_net}"
  840. )
  841. return item
  842. net = pin.get("net")
  843. matches = by_net.get(str(net), []) if net else []
  844. return matches[0] if len(matches) == 1 else None
  845. def _inventory_source(item: Mapping[str, object]) -> str:
  846. marker = item.get("screenshot_index") or item.get("source_confidence") or item.get("signal")
  847. return f"inventory:{marker}"
  848. def _merge_inventory(pin: dict[str, Any], item: Mapping[str, object]) -> None:
  849. capabilities = [str(value) for value in item.get("capability", [])]
  850. verified = item.get("manually_verified") is True
  851. evidence_tier = "cross_verified" if verified else "name_inferred"
  852. source = _inventory_source(item)
  853. board_pull = item.get("board_pull")
  854. if board_pull is None:
  855. board_pull = item.get("pullup")
  856. external_components = []
  857. for key in ("transceiver", "series_link", "esd"):
  858. value = item.get(key)
  859. if value and str(value) not in external_components:
  860. external_components.append(str(value))
  861. pin.update(
  862. {
  863. "direction": str(item.get("direction") or "unknown"),
  864. "external_level": str(item.get("external_level") or "unknown"),
  865. "function_category": _classify_function(str(item.get("function_net") or pin.get("net") or ""), capabilities),
  866. "reserved": item.get("reserved") is True,
  867. "fixed_load_conflict": item.get("fixed_load_conflict") is True,
  868. "board_pull": board_pull,
  869. "active_level": str(item.get("active_level") or "unknown"),
  870. "polarity": str(item.get("polarity") or "unknown"),
  871. "external_components": external_components,
  872. "evidence_tier": evidence_tier,
  873. "evidence_sources": [*pin["evidence_sources"], source],
  874. "fpga": {
  875. "ball": str(item.get("fpga_ball") or ""),
  876. "board_signal": str(item.get("signal") or item.get("function_net") or ""),
  877. "io_standard": str(item.get("io_standard") or ""),
  878. "capabilities": capabilities,
  879. "evidence_tier": evidence_tier,
  880. "sources": [source],
  881. },
  882. }
  883. )
  884. transceiver = item.get("transceiver")
  885. if transceiver:
  886. pin["path"] = [str(transceiver)]
  887. signal = item.get("signal") or item.get("function_net")
  888. if signal:
  889. pin["summary"] = str(signal)
  890. def _merge_annotation(pin: dict[str, Any], annotation: Mapping[str, object]) -> None:
  891. for key in (
  892. "summary",
  893. "direction",
  894. "external_level",
  895. "function_category",
  896. "reserved",
  897. "fixed_load_conflict",
  898. "board_pull",
  899. "adc_pulltype",
  900. "active_level",
  901. "polarity",
  902. "external_components",
  903. "path",
  904. ):
  905. if key in annotation:
  906. pin[key] = annotation[key]
  907. grades = annotation.get("evidence_grades")
  908. if isinstance(grades, Mapping):
  909. pin["evidence_grades"] = {
  910. "physical_path": str(grades.get("physical_path") or "unknown"),
  911. "product_polarity": str(grades.get("product_polarity") or "unknown"),
  912. "hardware_measurement": str(grades.get("hardware_measurement") or "unknown"),
  913. }
  914. fpga = annotation.get("fpga")
  915. if isinstance(fpga, Mapping):
  916. pin["fpga"] = {
  917. "ball": str(fpga.get("ball") or ""),
  918. "board_signal": str(fpga.get("board_signal") or ""),
  919. "io_standard": str(fpga.get("io_standard") or ""),
  920. "capabilities": [str(value) for value in fpga.get("capabilities", [])],
  921. "evidence_tier": str(fpga.get("evidence_tier") or "unknown"),
  922. "sources": [str(value) for value in fpga.get("sources", [])],
  923. }
  924. elif "fpga" in annotation:
  925. pin["fpga"] = None
  926. mcu = annotation.get("mcu")
  927. if isinstance(mcu, Mapping):
  928. pin["mcu"] = {
  929. "device": str(mcu.get("device") or ""),
  930. "family": str(mcu.get("family") or ""),
  931. "pin": str(mcu.get("pin") or ""),
  932. "signal": str(mcu.get("signal") or ""),
  933. "capabilities": [str(value) for value in mcu.get("capabilities", [])],
  934. "evidence_tier": str(mcu.get("evidence_tier") or "unknown"),
  935. "sources": [str(value) for value in mcu.get("sources", [])],
  936. }
  937. elif "mcu" in annotation:
  938. pin["mcu"] = None
  939. tier = annotation.get("evidence_tier")
  940. if tier in EVIDENCE_TIERS:
  941. pin["evidence_tier"] = tier
  942. if isinstance(pin.get("fpga"), dict):
  943. pin["fpga"]["evidence_tier"] = tier
  944. sources = annotation.get("sources", [])
  945. if isinstance(sources, list):
  946. pin["evidence_sources"] = [*pin["evidence_sources"], *[str(item) for item in sources]]
  947. def _unique_strings(values: list[object]) -> list[str]:
  948. result: list[str] = []
  949. for value in values:
  950. text = str(value)
  951. if text and text not in result:
  952. result.append(text)
  953. return result
  954. def _verified_fpga(pin: Mapping[str, object]) -> Mapping[str, object] | None:
  955. fpga = pin.get("fpga")
  956. if (
  957. pin.get("evidence_tier") == "cross_verified"
  958. and isinstance(fpga, Mapping)
  959. and fpga.get("evidence_tier") == "cross_verified"
  960. and fpga.get("ball")
  961. and fpga.get("io_standard")
  962. ):
  963. return fpga
  964. return None
  965. def _verified_mcu(pin: Mapping[str, object]) -> Mapping[str, object] | None:
  966. mcu = pin.get("mcu")
  967. if (
  968. pin.get("evidence_tier") == "cross_verified"
  969. and isinstance(mcu, Mapping)
  970. and mcu.get("evidence_tier") == "cross_verified"
  971. and mcu.get("device")
  972. and mcu.get("family")
  973. and mcu.get("pin")
  974. and mcu.get("signal")
  975. ):
  976. return mcu
  977. return None
  978. def _programming_guidance(reference: str, pin: Mapping[str, object]) -> dict[str, object]:
  979. number = str(pin.get("number") or "")
  980. net = str(pin.get("net") or "")
  981. role = str(pin.get("pad_role") or "unknown")
  982. function_category = str(pin.get("function_category") or "unknown")
  983. direction = str(pin.get("direction") or "unknown")
  984. external_level = str(pin.get("external_level") or "unknown")
  985. fpga = _verified_fpga(pin)
  986. mcu = _verified_mcu(pin)
  987. sources = _unique_strings(list(pin.get("evidence_sources", [])))
  988. if role == "mechanical" or pin.get("mechanical") is True or pin.get("electrical") is not True:
  989. return {
  990. "status": "not_programmable",
  991. "conclusion": "这是机械定位孔,不是电气针脚。",
  992. "network_explanation": "机械孔没有可用于编程的板内网络。",
  993. "hdl_guidance": "不要声明 RTL 端口,也不能生成 ADC 约束。",
  994. "connection_guidance": ["不要把机械孔作为信号、电源或地连接点。"],
  995. "constraints": [],
  996. "risks": ["它只承担机械定位或固定作用。"],
  997. "evidence_tier": "board_database",
  998. "sources": sources,
  999. }
  1000. if role == "shield":
  1001. grounded = net.upper() in {"GND", "AGND", "DGND", "PGND"}
  1002. network = "并与板级 GND 相连" if grounded else f"板数据库网络为 {net or '未命名'}"
  1003. return {
  1004. "status": "not_programmable",
  1005. "conclusion": "这是屏蔽/固定焊盘,不属于座子对外接触针。",
  1006. "network_explanation": f"该焊盘用于连接器外壳或固定,{network}。",
  1007. "hdl_guidance": "不要为它声明 RTL 端口,也不能生成 ADC 约束。",
  1008. "connection_guidance": ["线束 pinout 只使用标记为“接触针”的焊盘。"],
  1009. "constraints": [],
  1010. "risks": ["把屏蔽固定焊盘当作外部 Pin 会造成针脚数量和顺序错误。"],
  1011. "evidence_tier": str(pin.get("evidence_tier") or "board_database"),
  1012. "sources": sources,
  1013. }
  1014. if function_category == "ground" or net.upper() in {"GND", "AGND", "DGND", "PGND"}:
  1015. return {
  1016. "status": "not_programmable",
  1017. "conclusion": "这是接地针,用作信号参考和电流回路,不是 FPGA I/O。",
  1018. "network_explanation": f"板数据库确认 {reference}.{number} 连接到板级 {net or 'GND'}。",
  1019. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  1020. "connection_guidance": ["作为外部设备的参考地/回流地连接,不要当作逻辑信号脚。"],
  1021. "constraints": [],
  1022. "risks": ["接线时仍需遵守整机接地和回流设计。"],
  1023. "evidence_tier": str(pin.get("evidence_tier") or "board_database"),
  1024. "sources": sources,
  1025. }
  1026. if mcu is not None:
  1027. device = str(mcu.get("device"))
  1028. family = str(mcu.get("family"))
  1029. package_pin = str(mcu.get("pin"))
  1030. signal = str(mcu.get("signal"))
  1031. return {
  1032. "status": "verified_mcu",
  1033. "conclusion": (
  1034. f"GD32 MCU 固件测试点:{reference}.{number} 直连 "
  1035. f"{device}.{package_pin}({signal},{family})。"
  1036. ),
  1037. "network_explanation": (
  1038. f"板数据库与原理图共同确认网络 {net or signal} 对应 "
  1039. f"{device} 封装引脚 {package_pin} / 端口 {signal};它不是 FPGA 球位。"
  1040. ),
  1041. "hdl_guidance": (
  1042. f"不要在 FPGA RTL/ADC 中声明此针;应在 GD32 固件中按 {signal} "
  1043. "配置 GPIO 或所需复用功能,方向和复用选择由当前 MCU 固件决定。"
  1044. ),
  1045. "connection_guidance": [
  1046. f"外接仪器或信号前按 {external_level} 边界检查,并与板级 GND 共参考。",
  1047. "作为测量点使用时优先采用高阻探头,避免改变 MCU 引脚状态。",
  1048. ],
  1049. "constraints": [
  1050. f"MCU = {family} {device}",
  1051. f"PACKAGE_PIN = {package_pin}",
  1052. f"PORT = {signal}",
  1053. ],
  1054. "risks": [
  1055. "查看器不读取当前 MCU 固件,仍需检查端口复用、启动状态和外设占用。",
  1056. "此映射不能生成 FPGA ADC 约束。",
  1057. ],
  1058. "evidence_tier": "cross_verified",
  1059. "sources": sources,
  1060. }
  1061. if fpga is not None:
  1062. signal = str(fpga.get("board_signal") or pin.get("summary") or net)
  1063. ball = str(fpga.get("ball"))
  1064. io_standard = str(fpga.get("io_standard"))
  1065. components = [str(value) for value in pin.get("external_components", []) if value]
  1066. transceiver = next((value for value in components if value.upper().startswith("U")), None)
  1067. if direction == "output":
  1068. route = f"经 {transceiver} 转换后" if transceiver else "通过板内网络"
  1069. conclusion = f"FPGA 输出:RTL 驱动 {signal}(球位 {ball}),{route}从 {reference}.{number} 发出。"
  1070. elif direction == "input":
  1071. route = f"先经 {transceiver} 转换,再" if transceiver else "通过板内网络"
  1072. conclusion = f"FPGA 输入:外部信号从 {reference}.{number} 进入,{route}由 {signal}(球位 {ball})采样。"
  1073. elif direction in {"bidir", "bidirectional"} and function_category == "gpio":
  1074. conclusion = (
  1075. f"已验证直连 FPGA GPIO:{reference}.{number} 对应 {signal}(球位 {ball}),"
  1076. "物理上支持输入或输出。"
  1077. )
  1078. else:
  1079. conclusion = f"已验证 FPGA 路径:{reference}.{number} 对应 {signal}(球位 {ball}),方向为 {direction}。"
  1080. if transceiver:
  1081. network_explanation = (
  1082. f"连接器侧原始网络是 {net or '未命名'};经 {transceiver} 后,"
  1083. f"FPGA 逻辑侧信号是 {signal}。"
  1084. )
  1085. else:
  1086. network_explanation = (
  1087. f"板数据库网络 {net or '未命名'} 已交叉验证到 FPGA 逻辑信号 {signal}({ball})。"
  1088. )
  1089. connection_guidance: list[str] = []
  1090. if direction == "output" and function_category == "uart_tx":
  1091. connection_guidance.append("连接到对端设备的接收端(RX)。")
  1092. elif direction == "input" and function_category == "uart_rx":
  1093. connection_guidance.append("连接到对端设备的发送端(TX)。")
  1094. elif direction == "output":
  1095. connection_guidance.append("这是板端输出;外部设备应作为接收端,不要与另一个主动输出直接相连。")
  1096. elif direction == "input":
  1097. connection_guidance.append("这是板端输入;由外部设备驱动,接入前确认电平和公共参考地。")
  1098. elif direction in {"bidir", "bidirectional"} and function_category == "gpio":
  1099. connection_guidance.append(
  1100. "按实际用途选择输入或输出;配置为输入时由外部设备驱动,配置为输出时不要与另一个主动输出硬连接。"
  1101. )
  1102. else:
  1103. connection_guidance.append("按已验证方向使用;双向信号需要在 RTL 中正确控制输出使能。")
  1104. if external_level.upper() == "RS232":
  1105. connection_guidance.append("连接器侧是 RS-232 电平,不能直接接 3.3V TTL/CMOS 串口。")
  1106. if direction in {"bidir", "bidirectional"} and function_category == "gpio":
  1107. hdl_guidance = (
  1108. f"该物理脚支持 input、output 或 inout,按实际功能选择;"
  1109. f"只有真正需要双向共享并实现输出使能时才使用三态 inout。FPGA 逻辑侧使用 {io_standard}。"
  1110. )
  1111. else:
  1112. hdl_guidance = f"RTL 端口方向应为 {direction};FPGA 逻辑侧使用 {io_standard}。"
  1113. active_level = str(pin.get("active_level") or "unknown")
  1114. if active_level in {"high", "low"}:
  1115. active_cn = "高" if active_level == "high" else "低"
  1116. hdl_guidance += f" 此功能为{active_cn}电平有效。"
  1117. constraints = [f"LOCATION = {ball}", f"IOSTANDARD = {io_standard}"]
  1118. board_pull = pin.get("board_pull")
  1119. if board_pull:
  1120. constraints.append(f"板上外部 pull:{board_pull}")
  1121. if active_level in {"high", "low"}:
  1122. constraints.append(f"有效电平:{'高电平' if active_level == 'high' else '低电平'}")
  1123. risks = ["这里只证明物理路径和板级证据,仍需检查当前工程约束冲突。"]
  1124. if direction in {"bidir", "bidirectional"} and function_category == "gpio":
  1125. risks.insert(0, "不要因为物理上可双向就默认声明 inout;错误的三态控制可能造成总线争用。")
  1126. if pin.get("reserved") is True:
  1127. risks.insert(0, "当前 inventory 将此功能标记为保留,不能作为空闲 GPIO 重新分配。")
  1128. if pin.get("fixed_load_conflict") is True:
  1129. risks.insert(0, "此针存在已知固定负载冲突。")
  1130. return {
  1131. "status": "verified_fpga",
  1132. "conclusion": conclusion,
  1133. "network_explanation": network_explanation,
  1134. "hdl_guidance": hdl_guidance,
  1135. "connection_guidance": connection_guidance,
  1136. "constraints": constraints,
  1137. "risks": risks,
  1138. "evidence_tier": "cross_verified",
  1139. "sources": sources,
  1140. }
  1141. if function_category == "power" or POWER_NET.match(net):
  1142. if pin.get("evidence_tier") == "cross_verified":
  1143. summary = str(pin.get("summary") or f"电源网络 {net or '未命名'}").rstrip("。")
  1144. path = [str(item) for item in pin.get("path", []) if item]
  1145. path_text = " -> ".join(path) if path else f"{reference}.{number} {net or '未命名'}"
  1146. direction_text = {
  1147. "input": "板端电源输入",
  1148. "output": "板端电源输出",
  1149. "passive": "电源参考/分配节点",
  1150. }.get(direction, f"方向 {direction}")
  1151. if direction == "input":
  1152. connection_guidance = [
  1153. f"这是{direction_text};只能接符合 {external_level} 边界的电源,并核对极性与公共地。"
  1154. ]
  1155. direction_risk = "不要反向供电或从该输入针向外取电。"
  1156. elif direction == "output":
  1157. connection_guidance = [
  1158. f"这是{direction_text};只用于给设计负载提供 {external_level},不要与另一电源输出并接。"
  1159. ]
  1160. direction_risk = "不要向该输出针反向供电。"
  1161. else:
  1162. connection_guidance = [
  1163. f"这是{direction_text};按原理图定义使用,并遵守 {external_level} 电气边界。"
  1164. ]
  1165. direction_risk = "不要把电源参考/分配节点当作普通信号或任意供电入口。"
  1166. return {
  1167. "status": "not_programmable",
  1168. "conclusion": f"{summary}。这是{direction_text},不是 FPGA I/O,不能用于逻辑选脚。",
  1169. "network_explanation": (
  1170. f"原理图与板数据库交叉确认路径:{path_text};"
  1171. f"外部电气边界为 {external_level},方向为 {direction_text}。"
  1172. ),
  1173. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  1174. "connection_guidance": connection_guidance,
  1175. "constraints": [],
  1176. "risks": [
  1177. direction_risk,
  1178. "查看器不证明额定电流、线束载流能力或选配保护器件的实际装配状态,仍需核对 BOM 和整机规范。",
  1179. ],
  1180. "evidence_tier": "cross_verified",
  1181. "sources": sources,
  1182. }
  1183. return {
  1184. "status": "not_programmable",
  1185. "conclusion": "这是电源网络,不是 FPGA I/O,不能用于逻辑选脚。",
  1186. "network_explanation": (
  1187. f"按板数据库网名 {net or '未命名'} 可判断它属于电源域;"
  1188. "供电方向、额定电流和是否允许外供尚未在查看器中交叉验证。"
  1189. ),
  1190. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  1191. "connection_guidance": ["连接前必须查原理图和整机线束,确认电压、方向与电流能力。"],
  1192. "constraints": [],
  1193. "risks": ["错误接入 FPGA 3.3V I/O 可能造成硬件损坏。"],
  1194. "evidence_tier": "name_inferred",
  1195. "sources": sources,
  1196. }
  1197. if INTERNAL_NET.match(net):
  1198. network_explanation = (
  1199. f"{net} 是 CAD 自动生成的内部网络编号,只能证明同名焊盘电气相连;"
  1200. "编号本身不包含功能、方向或电平含义。"
  1201. )
  1202. elif net:
  1203. network_explanation = (
  1204. f"板数据库确认此焊盘连接到 {net};当前没有足够证据把该网名等同于某个 FPGA 端口。"
  1205. )
  1206. else:
  1207. network_explanation = "该电气焊盘没有可解释的网络名,功能保持未知。"
  1208. return {
  1209. "status": "board_only" if net else "unknown",
  1210. "conclusion": f"当前只确认到板内网络 {net or '未知'},没有已验证 FPGA 路径。",
  1211. "network_explanation": network_explanation,
  1212. "hdl_guidance": "不能据此写 RTL 方向或 ADC 约束;需要原理图路径或人工交叉验证。",
  1213. "connection_guidance": ["接线前先确认该网络经过的器件、外部电平和信号方向。"],
  1214. "constraints": [],
  1215. "risks": ["网名相似不等于功能相同,禁止仅凭名称推断 FPGA 映射。"],
  1216. "evidence_tier": "board_database" if net else "unknown",
  1217. "sources": sources,
  1218. }
  1219. def _merge_programming_annotation(
  1220. programming: dict[str, object], annotation: Mapping[str, object]
  1221. ) -> None:
  1222. for key in (
  1223. "status",
  1224. "conclusion",
  1225. "network_explanation",
  1226. "hdl_guidance",
  1227. "connection_guidance",
  1228. "constraints",
  1229. "risks",
  1230. ):
  1231. if key in annotation:
  1232. programming[key] = annotation[key]
  1233. tier = annotation.get("evidence_tier")
  1234. if tier in EVIDENCE_TIERS:
  1235. programming["evidence_tier"] = tier
  1236. sources = annotation.get("sources", [])
  1237. if isinstance(sources, list):
  1238. programming["sources"] = _unique_strings(
  1239. [*list(programming.get("sources", [])), *sources]
  1240. )
  1241. def _refresh_recommendation(pin: dict[str, Any]) -> None:
  1242. fpga = pin.get("fpga")
  1243. capabilities = fpga.get("capabilities", []) if isinstance(fpga, Mapping) else []
  1244. useful = [item for item in capabilities if item not in {"gpio", "rs232_via_transceiver"}]
  1245. capability = str(useful[0] if useful else (capabilities[0] if capabilities else "gpio"))
  1246. result = evaluate_recommendation(pin, capability)
  1247. pin["recommendation"] = {"eligible": result.eligible, "reasons": result.reasons}
  1248. def _build_value_coverage(resistors: list[dict[str, Any]]) -> dict[str, Any]:
  1249. total = len(resistors)
  1250. nonempty = sum(1 for item in resistors if str(item.get("component_value") or "").strip())
  1251. parsed = sum(1 for item in resistors if item.get("value_parse_status") == "parsed")
  1252. zero = sum(
  1253. 1
  1254. for item in resistors
  1255. if item.get("value_ohms") == 0
  1256. and item.get("value_parse_status") == "parsed"
  1257. and item.get("assembly_status") != "not_fitted"
  1258. )
  1259. zero_not_fitted = sum(
  1260. 1
  1261. for item in resistors
  1262. if item.get("value_ohms") == 0 and item.get("assembly_status") == "not_fitted"
  1263. )
  1264. not_fitted = sum(1 for item in resistors if item.get("assembly_status") == "not_fitted")
  1265. missing = sum(
  1266. 1
  1267. for item in resistors
  1268. if item.get("value_parse_status") in {"unparsed", "ambiguous"}
  1269. or item.get("value_ohms") is None
  1270. )
  1271. # missing = not successfully parsed (includes empty and unparsed non-empty)
  1272. missing = total - parsed
  1273. return {
  1274. "resistors_total": total,
  1275. "component_value_nonempty": nonempty,
  1276. "value_parsed": parsed,
  1277. "value_zero_ohm_fitted_or_unknown": zero,
  1278. "value_zero_ohm_not_fitted": zero_not_fitted,
  1279. "assembly_not_fitted": not_fitted,
  1280. "value_missing_or_unparsed": missing,
  1281. "component_value_source_status": "brd_footprint_field_limited_coverage",
  1282. "example_available_tokens": ["120R", "120", "0R", "0"],
  1283. "note": (
  1284. "Values come from BRD footprint component_value text only; "
  1285. "most resistors have no reliable ohm text. Do not infer from package size."
  1286. ),
  1287. }
  1288. def _attach_structured_resistor_links(
  1289. annotations: Mapping[str, object],
  1290. resistors: list[dict[str, Any]],
  1291. touchpoints: list[dict[str, Any]],
  1292. ) -> list[dict[str, Any]]:
  1293. """Resolve optional annotations.resistor_links[] against PCB pad.net."""
  1294. raw = annotations.get("resistor_links", [])
  1295. if not isinstance(raw, list):
  1296. return []
  1297. resistor_by_ref = {str(item["reference"]): item for item in resistors}
  1298. pin_ids = {
  1299. str(pin.get("id"))
  1300. for touchpoint in touchpoints
  1301. for pin in touchpoint.get("pins", [])
  1302. if isinstance(pin, Mapping)
  1303. }
  1304. resolved_links: list[dict[str, Any]] = []
  1305. for item in raw:
  1306. if not isinstance(item, Mapping):
  1307. continue
  1308. reference = str(item.get("resistor_reference") or "")
  1309. pad_number = item.get("pad_number")
  1310. pad_number_s = None if pad_number is None else str(pad_number)
  1311. claimed = item.get("claimed_net")
  1312. claimed_s = None if claimed is None else str(claimed)
  1313. source_pin_id = str(item.get("source_pin_id") or "")
  1314. evidence_source = str(item.get("evidence_source") or "curated")
  1315. note = str(item.get("note") or "")
  1316. status = "resolved"
  1317. pcb_net = None
  1318. resistor = resistor_by_ref.get(reference)
  1319. if not reference or resistor is None:
  1320. status = "missing_reference"
  1321. elif pad_number_s is None:
  1322. status = "missing_pad"
  1323. else:
  1324. pad = next(
  1325. (
  1326. row
  1327. for row in resistor.get("pads", [])
  1328. if isinstance(row, Mapping) and str(row.get("number")) == pad_number_s
  1329. ),
  1330. None,
  1331. )
  1332. if pad is None:
  1333. status = "missing_pad"
  1334. else:
  1335. pcb_net = pad.get("net")
  1336. if claimed_s is not None and str(pcb_net or "") != claimed_s:
  1337. status = "net_conflict"
  1338. if source_pin_id and source_pin_id not in pin_ids and status == "resolved":
  1339. # Non-fatal: keep resolved net compare; note orphan source id.
  1340. note = (note + " ; source_pin_id not in touchpoints").strip(" ;")
  1341. link = {
  1342. "source_pin_id": source_pin_id,
  1343. "resistor_reference": reference,
  1344. "pad_number": pad_number_s,
  1345. "claimed_net": claimed_s,
  1346. "pcb_net": pcb_net,
  1347. "status": status,
  1348. "evidence_source": evidence_source,
  1349. "note": note,
  1350. }
  1351. resolved_links.append(link)
  1352. # Mirror onto matching pin.related_resistors when source pin exists.
  1353. if source_pin_id:
  1354. for touchpoint in touchpoints:
  1355. for pin in touchpoint.get("pins", []):
  1356. if str(pin.get("id")) != source_pin_id:
  1357. continue
  1358. related = list(pin.get("related_resistors") or [])
  1359. related.append(
  1360. {
  1361. "source_pin_id": source_pin_id,
  1362. "source_field": "resistor_links",
  1363. "resistor_reference": reference,
  1364. "pad_number": pad_number_s,
  1365. "raw_context": note or evidence_source,
  1366. "status": status,
  1367. "pcb_net": pcb_net,
  1368. "claimed_net": claimed_s,
  1369. }
  1370. )
  1371. pin["related_resistors"] = related
  1372. return resolved_links
  1373. def validate_structured_resistor_links(payload: Mapping[str, object]) -> None:
  1374. links = payload.get("resistor_links")
  1375. if links is None:
  1376. return
  1377. if not isinstance(links, list):
  1378. raise ValueError("resistor_links must be a list")
  1379. for link in links:
  1380. if not isinstance(link, Mapping):
  1381. raise ValueError("invalid resistor_links entry")
  1382. status = link.get("status")
  1383. if status in {"missing_reference", "missing_pad", "net_conflict"}:
  1384. # net_conflict is published for UI; fail-closed only for missing ref/pad
  1385. # when validating curated package integrity — net_conflict is allowed as data.
  1386. if status in {"missing_reference", "missing_pad"}:
  1387. raise ValueError(
  1388. f"resistor_links {link.get('resistor_reference')} status={status}"
  1389. )
  1390. def build_board_data(
  1391. board: ParsedBoard,
  1392. inventory: Mapping[str, object],
  1393. annotations: Mapping[str, object],
  1394. *,
  1395. board_name: str,
  1396. ) -> dict[str, Any]:
  1397. annotations = expand_annotation_templates(annotations)
  1398. touchpoints = [_touchpoint_dict(footprint, board.bounds) for footprint in select_touchpoints(board)]
  1399. resistors = [
  1400. _resistor_dict(footprint, board.bounds)
  1401. for footprint in sorted(select_resistors(board), key=lambda item: int(item.reference[1:]))
  1402. ]
  1403. touchpoint_index = {item["reference"]: item for item in touchpoints}
  1404. validate_annotation_references(annotations, touchpoint_index)
  1405. connector_profiles = _connector_profile_index(annotations)
  1406. direct, by_net = _inventory_indexes(inventory)
  1407. annotated_touchpoints = annotations.get("touchpoints", {})
  1408. for touchpoint in touchpoints:
  1409. reference = touchpoint["reference"]
  1410. profile_entry = connector_profiles.get(reference)
  1411. if touchpoint["category"] == "CON" or profile_entry is not None:
  1412. _apply_connector_profile(touchpoint, profile_entry)
  1413. touchpoint_annotation = (
  1414. annotated_touchpoints.get(reference, {}) if isinstance(annotated_touchpoints, Mapping) else {}
  1415. )
  1416. if isinstance(touchpoint_annotation, Mapping) and touchpoint_annotation.get("summary"):
  1417. touchpoint["summary"] = str(touchpoint_annotation["summary"])
  1418. pin_annotations = (
  1419. touchpoint_annotation.get("pins", {}) if isinstance(touchpoint_annotation, Mapping) else {}
  1420. )
  1421. for pin in touchpoint["pins"]:
  1422. inventory_item = _inventory_match(reference, pin, direct, by_net)
  1423. if inventory_item is not None:
  1424. _merge_inventory(pin, inventory_item)
  1425. annotation = pin_annotations.get(pin["number"], {}) if isinstance(pin_annotations, Mapping) else {}
  1426. if isinstance(annotation, Mapping):
  1427. _merge_annotation(pin, annotation)
  1428. pin["programming"] = _programming_guidance(reference, pin)
  1429. programming_annotation = annotation.get("programming", {}) if isinstance(annotation, Mapping) else {}
  1430. if isinstance(programming_annotation, Mapping):
  1431. _merge_programming_annotation(pin["programming"], programming_annotation)
  1432. _refresh_recommendation(pin)
  1433. link_conflicts = _attach_related_resistors(touchpoints, resistors)
  1434. structured_links = _attach_structured_resistor_links(annotations, resistors, touchpoints)
  1435. evidence_conflicts = _normalize_evidence_conflicts(annotations, resistors)
  1436. # Link-derived missing_* are fatal at validate time; keep them out of the
  1437. # published evidence_conflicts list unless they were curated.
  1438. _ = link_conflicts
  1439. category_counts = Counter(item["category"] for item in touchpoints)
  1440. touchpoint_side_counts = Counter(item["side"] for item in touchpoints)
  1441. resistor_side_counts = Counter(item["side"] for item in resistors)
  1442. connector_touchpoints = [item for item in touchpoints if item["category"] == "CON"]
  1443. resistor_pad_count = sum(len(item["pads"]) for item in resistors)
  1444. resistor_electrical_pad_count = sum(
  1445. 1
  1446. for item in resistors
  1447. for pad in item["pads"]
  1448. if pad.get("pad_role") == "electrical"
  1449. )
  1450. value_coverage = _build_value_coverage(resistors)
  1451. payload = {
  1452. "schema": BOARD_DATA_SCHEMA_ID,
  1453. "board": {
  1454. "id": str(annotations.get("board_id") or inventory.get("board_id") or "unknown"),
  1455. "name": board_name,
  1456. "source_bounds": dict(board.bounds),
  1457. "view_box": {"x": 0.0, "y": 0.0, "width": board.bounds["width"], "height": board.bounds["height"]},
  1458. },
  1459. "counts": {
  1460. "footprints": board.footprint_count,
  1461. "touchpoints": len(touchpoints),
  1462. # counts.pads keeps historical touchpoint-pin semantics (not all PCB pads).
  1463. "pads": sum(len(item["pins"]) for item in touchpoints),
  1464. "resistors": len(resistors),
  1465. "resistor_pads": resistor_pad_count,
  1466. "resistor_electrical_pads": resistor_electrical_pad_count,
  1467. "connector_contacts": sum(
  1468. int(item["connector"]["contact_count"]) for item in connector_touchpoints
  1469. ),
  1470. "connector_auxiliary_pads": sum(
  1471. int(item["connector"]["auxiliary_pad_count"]) for item in connector_touchpoints
  1472. ),
  1473. "categories": {
  1474. "CON": category_counts.get("CON", 0),
  1475. "J": category_counts.get("J", 0),
  1476. "PL": category_counts.get("PL", 0),
  1477. "TP": category_counts.get("TP", 0),
  1478. "R": len(resistors),
  1479. },
  1480. # Legacy alias: touchpoint sides only (NOT all entities / resistors).
  1481. "sides": {key: touchpoint_side_counts.get(key, 0) for key in ("front", "back")},
  1482. "touchpoint_sides": {
  1483. key: touchpoint_side_counts.get(key, 0) for key in ("front", "back")
  1484. },
  1485. "resistor_sides": {
  1486. key: resistor_side_counts.get(key, 0) for key in ("front", "back")
  1487. },
  1488. },
  1489. "value_coverage": value_coverage,
  1490. "component_value_source_status": value_coverage["component_value_source_status"],
  1491. "touchpoints": touchpoints,
  1492. "resistors": resistors,
  1493. "resistor_links": structured_links,
  1494. "evidence_conflicts": evidence_conflicts,
  1495. "interfaces": list(annotations.get("interfaces", [])) if isinstance(annotations.get("interfaces", []), list) else [],
  1496. "photo_overlay": annotations.get("photo_overlay"),
  1497. }
  1498. # Structural self-check only; annotation ⊆ index (Pass G) is enforced by
  1499. # validate/regression against the product board, not every fixture build.
  1500. if payload["counts"]["resistors"] != len(resistors):
  1501. raise ValueError("resistor count mismatch while building board data")
  1502. if payload["counts"]["resistor_pads"] != sum(len(item["pads"]) for item in resistors):
  1503. raise ValueError("resistor pad count mismatch while building board data")
  1504. return payload