data.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611
  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. mcu = annotation.get("mcu")
  925. if isinstance(mcu, Mapping):
  926. pin["mcu"] = {
  927. "device": str(mcu.get("device") or ""),
  928. "family": str(mcu.get("family") or ""),
  929. "pin": str(mcu.get("pin") or ""),
  930. "signal": str(mcu.get("signal") or ""),
  931. "capabilities": [str(value) for value in mcu.get("capabilities", [])],
  932. "evidence_tier": str(mcu.get("evidence_tier") or "unknown"),
  933. "sources": [str(value) for value in mcu.get("sources", [])],
  934. }
  935. tier = annotation.get("evidence_tier")
  936. if tier in EVIDENCE_TIERS:
  937. pin["evidence_tier"] = tier
  938. if isinstance(pin.get("fpga"), dict):
  939. pin["fpga"]["evidence_tier"] = tier
  940. sources = annotation.get("sources", [])
  941. if isinstance(sources, list):
  942. pin["evidence_sources"] = [*pin["evidence_sources"], *[str(item) for item in sources]]
  943. def _unique_strings(values: list[object]) -> list[str]:
  944. result: list[str] = []
  945. for value in values:
  946. text = str(value)
  947. if text and text not in result:
  948. result.append(text)
  949. return result
  950. def _verified_fpga(pin: Mapping[str, object]) -> Mapping[str, object] | None:
  951. fpga = pin.get("fpga")
  952. if (
  953. pin.get("evidence_tier") == "cross_verified"
  954. and isinstance(fpga, Mapping)
  955. and fpga.get("evidence_tier") == "cross_verified"
  956. and fpga.get("ball")
  957. and fpga.get("io_standard")
  958. ):
  959. return fpga
  960. return None
  961. def _verified_mcu(pin: Mapping[str, object]) -> Mapping[str, object] | None:
  962. mcu = pin.get("mcu")
  963. if (
  964. pin.get("evidence_tier") == "cross_verified"
  965. and isinstance(mcu, Mapping)
  966. and mcu.get("evidence_tier") == "cross_verified"
  967. and mcu.get("device")
  968. and mcu.get("family")
  969. and mcu.get("pin")
  970. and mcu.get("signal")
  971. ):
  972. return mcu
  973. return None
  974. def _programming_guidance(reference: str, pin: Mapping[str, object]) -> dict[str, object]:
  975. number = str(pin.get("number") or "")
  976. net = str(pin.get("net") or "")
  977. role = str(pin.get("pad_role") or "unknown")
  978. function_category = str(pin.get("function_category") or "unknown")
  979. direction = str(pin.get("direction") or "unknown")
  980. external_level = str(pin.get("external_level") or "unknown")
  981. fpga = _verified_fpga(pin)
  982. mcu = _verified_mcu(pin)
  983. sources = _unique_strings(list(pin.get("evidence_sources", [])))
  984. if role == "mechanical" or pin.get("mechanical") is True or pin.get("electrical") is not True:
  985. return {
  986. "status": "not_programmable",
  987. "conclusion": "这是机械定位孔,不是电气针脚。",
  988. "network_explanation": "机械孔没有可用于编程的板内网络。",
  989. "hdl_guidance": "不要声明 RTL 端口,也不能生成 ADC 约束。",
  990. "connection_guidance": ["不要把机械孔作为信号、电源或地连接点。"],
  991. "constraints": [],
  992. "risks": ["它只承担机械定位或固定作用。"],
  993. "evidence_tier": "board_database",
  994. "sources": sources,
  995. }
  996. if role == "shield":
  997. grounded = net.upper() in {"GND", "AGND", "DGND", "PGND"}
  998. network = "并与板级 GND 相连" if grounded else f"板数据库网络为 {net or '未命名'}"
  999. return {
  1000. "status": "not_programmable",
  1001. "conclusion": "这是屏蔽/固定焊盘,不属于座子对外接触针。",
  1002. "network_explanation": f"该焊盘用于连接器外壳或固定,{network}。",
  1003. "hdl_guidance": "不要为它声明 RTL 端口,也不能生成 ADC 约束。",
  1004. "connection_guidance": ["线束 pinout 只使用标记为“接触针”的焊盘。"],
  1005. "constraints": [],
  1006. "risks": ["把屏蔽固定焊盘当作外部 Pin 会造成针脚数量和顺序错误。"],
  1007. "evidence_tier": str(pin.get("evidence_tier") or "board_database"),
  1008. "sources": sources,
  1009. }
  1010. if function_category == "ground" or net.upper() in {"GND", "AGND", "DGND", "PGND"}:
  1011. return {
  1012. "status": "not_programmable",
  1013. "conclusion": "这是接地针,用作信号参考和电流回路,不是 FPGA I/O。",
  1014. "network_explanation": f"板数据库确认 {reference}.{number} 连接到板级 {net or 'GND'}。",
  1015. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  1016. "connection_guidance": ["作为外部设备的参考地/回流地连接,不要当作逻辑信号脚。"],
  1017. "constraints": [],
  1018. "risks": ["接线时仍需遵守整机接地和回流设计。"],
  1019. "evidence_tier": str(pin.get("evidence_tier") or "board_database"),
  1020. "sources": sources,
  1021. }
  1022. if mcu is not None:
  1023. device = str(mcu.get("device"))
  1024. family = str(mcu.get("family"))
  1025. package_pin = str(mcu.get("pin"))
  1026. signal = str(mcu.get("signal"))
  1027. return {
  1028. "status": "verified_mcu",
  1029. "conclusion": (
  1030. f"GD32 MCU 固件测试点:{reference}.{number} 直连 "
  1031. f"{device}.{package_pin}({signal},{family})。"
  1032. ),
  1033. "network_explanation": (
  1034. f"板数据库与原理图共同确认网络 {net or signal} 对应 "
  1035. f"{device} 封装引脚 {package_pin} / 端口 {signal};它不是 FPGA 球位。"
  1036. ),
  1037. "hdl_guidance": (
  1038. f"不要在 FPGA RTL/ADC 中声明此针;应在 GD32 固件中按 {signal} "
  1039. "配置 GPIO 或所需复用功能,方向和复用选择由当前 MCU 固件决定。"
  1040. ),
  1041. "connection_guidance": [
  1042. f"外接仪器或信号前按 {external_level} 边界检查,并与板级 GND 共参考。",
  1043. "作为测量点使用时优先采用高阻探头,避免改变 MCU 引脚状态。",
  1044. ],
  1045. "constraints": [
  1046. f"MCU = {family} {device}",
  1047. f"PACKAGE_PIN = {package_pin}",
  1048. f"PORT = {signal}",
  1049. ],
  1050. "risks": [
  1051. "查看器不读取当前 MCU 固件,仍需检查端口复用、启动状态和外设占用。",
  1052. "此映射不能生成 FPGA ADC 约束。",
  1053. ],
  1054. "evidence_tier": "cross_verified",
  1055. "sources": sources,
  1056. }
  1057. if fpga is not None:
  1058. signal = str(fpga.get("board_signal") or pin.get("summary") or net)
  1059. ball = str(fpga.get("ball"))
  1060. io_standard = str(fpga.get("io_standard"))
  1061. components = [str(value) for value in pin.get("external_components", []) if value]
  1062. transceiver = next((value for value in components if value.upper().startswith("U")), None)
  1063. if direction == "output":
  1064. route = f"经 {transceiver} 转换后" if transceiver else "通过板内网络"
  1065. conclusion = f"FPGA 输出:RTL 驱动 {signal}(球位 {ball}),{route}从 {reference}.{number} 发出。"
  1066. elif direction == "input":
  1067. route = f"先经 {transceiver} 转换,再" if transceiver else "通过板内网络"
  1068. conclusion = f"FPGA 输入:外部信号从 {reference}.{number} 进入,{route}由 {signal}(球位 {ball})采样。"
  1069. elif direction in {"bidir", "bidirectional"} and function_category == "gpio":
  1070. conclusion = (
  1071. f"已验证直连 FPGA GPIO:{reference}.{number} 对应 {signal}(球位 {ball}),"
  1072. "物理上支持输入或输出。"
  1073. )
  1074. else:
  1075. conclusion = f"已验证 FPGA 路径:{reference}.{number} 对应 {signal}(球位 {ball}),方向为 {direction}。"
  1076. if transceiver:
  1077. network_explanation = (
  1078. f"连接器侧原始网络是 {net or '未命名'};经 {transceiver} 后,"
  1079. f"FPGA 逻辑侧信号是 {signal}。"
  1080. )
  1081. else:
  1082. network_explanation = (
  1083. f"板数据库网络 {net or '未命名'} 已交叉验证到 FPGA 逻辑信号 {signal}({ball})。"
  1084. )
  1085. connection_guidance: list[str] = []
  1086. if direction == "output" and function_category == "uart_tx":
  1087. connection_guidance.append("连接到对端设备的接收端(RX)。")
  1088. elif direction == "input" and function_category == "uart_rx":
  1089. connection_guidance.append("连接到对端设备的发送端(TX)。")
  1090. elif direction == "output":
  1091. connection_guidance.append("这是板端输出;外部设备应作为接收端,不要与另一个主动输出直接相连。")
  1092. elif direction == "input":
  1093. connection_guidance.append("这是板端输入;由外部设备驱动,接入前确认电平和公共参考地。")
  1094. elif direction in {"bidir", "bidirectional"} and function_category == "gpio":
  1095. connection_guidance.append(
  1096. "按实际用途选择输入或输出;配置为输入时由外部设备驱动,配置为输出时不要与另一个主动输出硬连接。"
  1097. )
  1098. else:
  1099. connection_guidance.append("按已验证方向使用;双向信号需要在 RTL 中正确控制输出使能。")
  1100. if external_level.upper() == "RS232":
  1101. connection_guidance.append("连接器侧是 RS-232 电平,不能直接接 3.3V TTL/CMOS 串口。")
  1102. if direction in {"bidir", "bidirectional"} and function_category == "gpio":
  1103. hdl_guidance = (
  1104. f"该物理脚支持 input、output 或 inout,按实际功能选择;"
  1105. f"只有真正需要双向共享并实现输出使能时才使用三态 inout。FPGA 逻辑侧使用 {io_standard}。"
  1106. )
  1107. else:
  1108. hdl_guidance = f"RTL 端口方向应为 {direction};FPGA 逻辑侧使用 {io_standard}。"
  1109. active_level = str(pin.get("active_level") or "unknown")
  1110. if active_level in {"high", "low"}:
  1111. active_cn = "高" if active_level == "high" else "低"
  1112. hdl_guidance += f" 此功能为{active_cn}电平有效。"
  1113. constraints = [f"LOCATION = {ball}", f"IOSTANDARD = {io_standard}"]
  1114. board_pull = pin.get("board_pull")
  1115. if board_pull:
  1116. constraints.append(f"板上外部 pull:{board_pull}")
  1117. if active_level in {"high", "low"}:
  1118. constraints.append(f"有效电平:{'高电平' if active_level == 'high' else '低电平'}")
  1119. risks = ["这里只证明物理路径和板级证据,仍需检查当前工程约束冲突。"]
  1120. if direction in {"bidir", "bidirectional"} and function_category == "gpio":
  1121. risks.insert(0, "不要因为物理上可双向就默认声明 inout;错误的三态控制可能造成总线争用。")
  1122. if pin.get("reserved") is True:
  1123. risks.insert(0, "当前 inventory 将此功能标记为保留,不能作为空闲 GPIO 重新分配。")
  1124. if pin.get("fixed_load_conflict") is True:
  1125. risks.insert(0, "此针存在已知固定负载冲突。")
  1126. return {
  1127. "status": "verified_fpga",
  1128. "conclusion": conclusion,
  1129. "network_explanation": network_explanation,
  1130. "hdl_guidance": hdl_guidance,
  1131. "connection_guidance": connection_guidance,
  1132. "constraints": constraints,
  1133. "risks": risks,
  1134. "evidence_tier": "cross_verified",
  1135. "sources": sources,
  1136. }
  1137. if function_category == "power" or POWER_NET.match(net):
  1138. if pin.get("evidence_tier") == "cross_verified":
  1139. summary = str(pin.get("summary") or f"电源网络 {net or '未命名'}").rstrip("。")
  1140. path = [str(item) for item in pin.get("path", []) if item]
  1141. path_text = " -> ".join(path) if path else f"{reference}.{number} {net or '未命名'}"
  1142. direction_text = {
  1143. "input": "板端电源输入",
  1144. "output": "板端电源输出",
  1145. "passive": "电源参考/分配节点",
  1146. }.get(direction, f"方向 {direction}")
  1147. if direction == "input":
  1148. connection_guidance = [
  1149. f"这是{direction_text};只能接符合 {external_level} 边界的电源,并核对极性与公共地。"
  1150. ]
  1151. direction_risk = "不要反向供电或从该输入针向外取电。"
  1152. elif direction == "output":
  1153. connection_guidance = [
  1154. f"这是{direction_text};只用于给设计负载提供 {external_level},不要与另一电源输出并接。"
  1155. ]
  1156. direction_risk = "不要向该输出针反向供电。"
  1157. else:
  1158. connection_guidance = [
  1159. f"这是{direction_text};按原理图定义使用,并遵守 {external_level} 电气边界。"
  1160. ]
  1161. direction_risk = "不要把电源参考/分配节点当作普通信号或任意供电入口。"
  1162. return {
  1163. "status": "not_programmable",
  1164. "conclusion": f"{summary}。这是{direction_text},不是 FPGA I/O,不能用于逻辑选脚。",
  1165. "network_explanation": (
  1166. f"原理图与板数据库交叉确认路径:{path_text};"
  1167. f"外部电气边界为 {external_level},方向为 {direction_text}。"
  1168. ),
  1169. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  1170. "connection_guidance": connection_guidance,
  1171. "constraints": [],
  1172. "risks": [
  1173. direction_risk,
  1174. "查看器不证明额定电流、线束载流能力或选配保护器件的实际装配状态,仍需核对 BOM 和整机规范。",
  1175. ],
  1176. "evidence_tier": "cross_verified",
  1177. "sources": sources,
  1178. }
  1179. return {
  1180. "status": "not_programmable",
  1181. "conclusion": "这是电源网络,不是 FPGA I/O,不能用于逻辑选脚。",
  1182. "network_explanation": (
  1183. f"按板数据库网名 {net or '未命名'} 可判断它属于电源域;"
  1184. "供电方向、额定电流和是否允许外供尚未在查看器中交叉验证。"
  1185. ),
  1186. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  1187. "connection_guidance": ["连接前必须查原理图和整机线束,确认电压、方向与电流能力。"],
  1188. "constraints": [],
  1189. "risks": ["错误接入 FPGA 3.3V I/O 可能造成硬件损坏。"],
  1190. "evidence_tier": "name_inferred",
  1191. "sources": sources,
  1192. }
  1193. if INTERNAL_NET.match(net):
  1194. network_explanation = (
  1195. f"{net} 是 CAD 自动生成的内部网络编号,只能证明同名焊盘电气相连;"
  1196. "编号本身不包含功能、方向或电平含义。"
  1197. )
  1198. elif net:
  1199. network_explanation = (
  1200. f"板数据库确认此焊盘连接到 {net};当前没有足够证据把该网名等同于某个 FPGA 端口。"
  1201. )
  1202. else:
  1203. network_explanation = "该电气焊盘没有可解释的网络名,功能保持未知。"
  1204. return {
  1205. "status": "board_only" if net else "unknown",
  1206. "conclusion": f"当前只确认到板内网络 {net or '未知'},没有已验证 FPGA 路径。",
  1207. "network_explanation": network_explanation,
  1208. "hdl_guidance": "不能据此写 RTL 方向或 ADC 约束;需要原理图路径或人工交叉验证。",
  1209. "connection_guidance": ["接线前先确认该网络经过的器件、外部电平和信号方向。"],
  1210. "constraints": [],
  1211. "risks": ["网名相似不等于功能相同,禁止仅凭名称推断 FPGA 映射。"],
  1212. "evidence_tier": "board_database" if net else "unknown",
  1213. "sources": sources,
  1214. }
  1215. def _merge_programming_annotation(
  1216. programming: dict[str, object], annotation: Mapping[str, object]
  1217. ) -> None:
  1218. for key in (
  1219. "status",
  1220. "conclusion",
  1221. "network_explanation",
  1222. "hdl_guidance",
  1223. "connection_guidance",
  1224. "constraints",
  1225. "risks",
  1226. ):
  1227. if key in annotation:
  1228. programming[key] = annotation[key]
  1229. tier = annotation.get("evidence_tier")
  1230. if tier in EVIDENCE_TIERS:
  1231. programming["evidence_tier"] = tier
  1232. sources = annotation.get("sources", [])
  1233. if isinstance(sources, list):
  1234. programming["sources"] = _unique_strings(
  1235. [*list(programming.get("sources", [])), *sources]
  1236. )
  1237. def _refresh_recommendation(pin: dict[str, Any]) -> None:
  1238. fpga = pin.get("fpga")
  1239. capabilities = fpga.get("capabilities", []) if isinstance(fpga, Mapping) else []
  1240. useful = [item for item in capabilities if item not in {"gpio", "rs232_via_transceiver"}]
  1241. capability = str(useful[0] if useful else (capabilities[0] if capabilities else "gpio"))
  1242. result = evaluate_recommendation(pin, capability)
  1243. pin["recommendation"] = {"eligible": result.eligible, "reasons": result.reasons}
  1244. def _build_value_coverage(resistors: list[dict[str, Any]]) -> dict[str, Any]:
  1245. total = len(resistors)
  1246. nonempty = sum(1 for item in resistors if str(item.get("component_value") or "").strip())
  1247. parsed = sum(1 for item in resistors if item.get("value_parse_status") == "parsed")
  1248. zero = sum(
  1249. 1
  1250. for item in resistors
  1251. if item.get("value_ohms") == 0
  1252. and item.get("value_parse_status") == "parsed"
  1253. and item.get("assembly_status") != "not_fitted"
  1254. )
  1255. zero_not_fitted = sum(
  1256. 1
  1257. for item in resistors
  1258. if item.get("value_ohms") == 0 and item.get("assembly_status") == "not_fitted"
  1259. )
  1260. not_fitted = sum(1 for item in resistors if item.get("assembly_status") == "not_fitted")
  1261. missing = sum(
  1262. 1
  1263. for item in resistors
  1264. if item.get("value_parse_status") in {"unparsed", "ambiguous"}
  1265. or item.get("value_ohms") is None
  1266. )
  1267. # missing = not successfully parsed (includes empty and unparsed non-empty)
  1268. missing = total - parsed
  1269. return {
  1270. "resistors_total": total,
  1271. "component_value_nonempty": nonempty,
  1272. "value_parsed": parsed,
  1273. "value_zero_ohm_fitted_or_unknown": zero,
  1274. "value_zero_ohm_not_fitted": zero_not_fitted,
  1275. "assembly_not_fitted": not_fitted,
  1276. "value_missing_or_unparsed": missing,
  1277. "component_value_source_status": "brd_footprint_field_limited_coverage",
  1278. "example_available_tokens": ["120R", "120", "0R", "0"],
  1279. "note": (
  1280. "Values come from BRD footprint component_value text only; "
  1281. "most resistors have no reliable ohm text. Do not infer from package size."
  1282. ),
  1283. }
  1284. def _attach_structured_resistor_links(
  1285. annotations: Mapping[str, object],
  1286. resistors: list[dict[str, Any]],
  1287. touchpoints: list[dict[str, Any]],
  1288. ) -> list[dict[str, Any]]:
  1289. """Resolve optional annotations.resistor_links[] against PCB pad.net."""
  1290. raw = annotations.get("resistor_links", [])
  1291. if not isinstance(raw, list):
  1292. return []
  1293. resistor_by_ref = {str(item["reference"]): item for item in resistors}
  1294. pin_ids = {
  1295. str(pin.get("id"))
  1296. for touchpoint in touchpoints
  1297. for pin in touchpoint.get("pins", [])
  1298. if isinstance(pin, Mapping)
  1299. }
  1300. resolved_links: list[dict[str, Any]] = []
  1301. for item in raw:
  1302. if not isinstance(item, Mapping):
  1303. continue
  1304. reference = str(item.get("resistor_reference") or "")
  1305. pad_number = item.get("pad_number")
  1306. pad_number_s = None if pad_number is None else str(pad_number)
  1307. claimed = item.get("claimed_net")
  1308. claimed_s = None if claimed is None else str(claimed)
  1309. source_pin_id = str(item.get("source_pin_id") or "")
  1310. evidence_source = str(item.get("evidence_source") or "curated")
  1311. note = str(item.get("note") or "")
  1312. status = "resolved"
  1313. pcb_net = None
  1314. resistor = resistor_by_ref.get(reference)
  1315. if not reference or resistor is None:
  1316. status = "missing_reference"
  1317. elif pad_number_s is None:
  1318. status = "missing_pad"
  1319. else:
  1320. pad = next(
  1321. (
  1322. row
  1323. for row in resistor.get("pads", [])
  1324. if isinstance(row, Mapping) and str(row.get("number")) == pad_number_s
  1325. ),
  1326. None,
  1327. )
  1328. if pad is None:
  1329. status = "missing_pad"
  1330. else:
  1331. pcb_net = pad.get("net")
  1332. if claimed_s is not None and str(pcb_net or "") != claimed_s:
  1333. status = "net_conflict"
  1334. if source_pin_id and source_pin_id not in pin_ids and status == "resolved":
  1335. # Non-fatal: keep resolved net compare; note orphan source id.
  1336. note = (note + " ; source_pin_id not in touchpoints").strip(" ;")
  1337. link = {
  1338. "source_pin_id": source_pin_id,
  1339. "resistor_reference": reference,
  1340. "pad_number": pad_number_s,
  1341. "claimed_net": claimed_s,
  1342. "pcb_net": pcb_net,
  1343. "status": status,
  1344. "evidence_source": evidence_source,
  1345. "note": note,
  1346. }
  1347. resolved_links.append(link)
  1348. # Mirror onto matching pin.related_resistors when source pin exists.
  1349. if source_pin_id:
  1350. for touchpoint in touchpoints:
  1351. for pin in touchpoint.get("pins", []):
  1352. if str(pin.get("id")) != source_pin_id:
  1353. continue
  1354. related = list(pin.get("related_resistors") or [])
  1355. related.append(
  1356. {
  1357. "source_pin_id": source_pin_id,
  1358. "source_field": "resistor_links",
  1359. "resistor_reference": reference,
  1360. "pad_number": pad_number_s,
  1361. "raw_context": note or evidence_source,
  1362. "status": status,
  1363. "pcb_net": pcb_net,
  1364. "claimed_net": claimed_s,
  1365. }
  1366. )
  1367. pin["related_resistors"] = related
  1368. return resolved_links
  1369. def validate_structured_resistor_links(payload: Mapping[str, object]) -> None:
  1370. links = payload.get("resistor_links")
  1371. if links is None:
  1372. return
  1373. if not isinstance(links, list):
  1374. raise ValueError("resistor_links must be a list")
  1375. for link in links:
  1376. if not isinstance(link, Mapping):
  1377. raise ValueError("invalid resistor_links entry")
  1378. status = link.get("status")
  1379. if status in {"missing_reference", "missing_pad", "net_conflict"}:
  1380. # net_conflict is published for UI; fail-closed only for missing ref/pad
  1381. # when validating curated package integrity — net_conflict is allowed as data.
  1382. if status in {"missing_reference", "missing_pad"}:
  1383. raise ValueError(
  1384. f"resistor_links {link.get('resistor_reference')} status={status}"
  1385. )
  1386. def build_board_data(
  1387. board: ParsedBoard,
  1388. inventory: Mapping[str, object],
  1389. annotations: Mapping[str, object],
  1390. *,
  1391. board_name: str,
  1392. ) -> dict[str, Any]:
  1393. annotations = expand_annotation_templates(annotations)
  1394. touchpoints = [_touchpoint_dict(footprint, board.bounds) for footprint in select_touchpoints(board)]
  1395. resistors = [
  1396. _resistor_dict(footprint, board.bounds)
  1397. for footprint in sorted(select_resistors(board), key=lambda item: int(item.reference[1:]))
  1398. ]
  1399. touchpoint_index = {item["reference"]: item for item in touchpoints}
  1400. validate_annotation_references(annotations, touchpoint_index)
  1401. connector_profiles = _connector_profile_index(annotations)
  1402. direct, by_net = _inventory_indexes(inventory)
  1403. annotated_touchpoints = annotations.get("touchpoints", {})
  1404. for touchpoint in touchpoints:
  1405. reference = touchpoint["reference"]
  1406. profile_entry = connector_profiles.get(reference)
  1407. if touchpoint["category"] == "CON" or profile_entry is not None:
  1408. _apply_connector_profile(touchpoint, profile_entry)
  1409. touchpoint_annotation = (
  1410. annotated_touchpoints.get(reference, {}) if isinstance(annotated_touchpoints, Mapping) else {}
  1411. )
  1412. if isinstance(touchpoint_annotation, Mapping) and touchpoint_annotation.get("summary"):
  1413. touchpoint["summary"] = str(touchpoint_annotation["summary"])
  1414. pin_annotations = (
  1415. touchpoint_annotation.get("pins", {}) if isinstance(touchpoint_annotation, Mapping) else {}
  1416. )
  1417. for pin in touchpoint["pins"]:
  1418. inventory_item = _inventory_match(reference, pin, direct, by_net)
  1419. if inventory_item is not None:
  1420. _merge_inventory(pin, inventory_item)
  1421. annotation = pin_annotations.get(pin["number"], {}) if isinstance(pin_annotations, Mapping) else {}
  1422. if isinstance(annotation, Mapping):
  1423. _merge_annotation(pin, annotation)
  1424. pin["programming"] = _programming_guidance(reference, pin)
  1425. programming_annotation = annotation.get("programming", {}) if isinstance(annotation, Mapping) else {}
  1426. if isinstance(programming_annotation, Mapping):
  1427. _merge_programming_annotation(pin["programming"], programming_annotation)
  1428. _refresh_recommendation(pin)
  1429. link_conflicts = _attach_related_resistors(touchpoints, resistors)
  1430. structured_links = _attach_structured_resistor_links(annotations, resistors, touchpoints)
  1431. evidence_conflicts = _normalize_evidence_conflicts(annotations, resistors)
  1432. # Link-derived missing_* are fatal at validate time; keep them out of the
  1433. # published evidence_conflicts list unless they were curated.
  1434. _ = link_conflicts
  1435. category_counts = Counter(item["category"] for item in touchpoints)
  1436. touchpoint_side_counts = Counter(item["side"] for item in touchpoints)
  1437. resistor_side_counts = Counter(item["side"] for item in resistors)
  1438. connector_touchpoints = [item for item in touchpoints if item["category"] == "CON"]
  1439. resistor_pad_count = sum(len(item["pads"]) for item in resistors)
  1440. resistor_electrical_pad_count = sum(
  1441. 1
  1442. for item in resistors
  1443. for pad in item["pads"]
  1444. if pad.get("pad_role") == "electrical"
  1445. )
  1446. value_coverage = _build_value_coverage(resistors)
  1447. payload = {
  1448. "schema": BOARD_DATA_SCHEMA_ID,
  1449. "board": {
  1450. "id": str(annotations.get("board_id") or inventory.get("board_id") or "unknown"),
  1451. "name": board_name,
  1452. "source_bounds": dict(board.bounds),
  1453. "view_box": {"x": 0.0, "y": 0.0, "width": board.bounds["width"], "height": board.bounds["height"]},
  1454. },
  1455. "counts": {
  1456. "footprints": board.footprint_count,
  1457. "touchpoints": len(touchpoints),
  1458. # counts.pads keeps historical touchpoint-pin semantics (not all PCB pads).
  1459. "pads": sum(len(item["pins"]) for item in touchpoints),
  1460. "resistors": len(resistors),
  1461. "resistor_pads": resistor_pad_count,
  1462. "resistor_electrical_pads": resistor_electrical_pad_count,
  1463. "connector_contacts": sum(
  1464. int(item["connector"]["contact_count"]) for item in connector_touchpoints
  1465. ),
  1466. "connector_auxiliary_pads": sum(
  1467. int(item["connector"]["auxiliary_pad_count"]) for item in connector_touchpoints
  1468. ),
  1469. "categories": {
  1470. "CON": category_counts.get("CON", 0),
  1471. "J": category_counts.get("J", 0),
  1472. "PL": category_counts.get("PL", 0),
  1473. "TP": category_counts.get("TP", 0),
  1474. "R": len(resistors),
  1475. },
  1476. # Legacy alias: touchpoint sides only (NOT all entities / resistors).
  1477. "sides": {key: touchpoint_side_counts.get(key, 0) for key in ("front", "back")},
  1478. "touchpoint_sides": {
  1479. key: touchpoint_side_counts.get(key, 0) for key in ("front", "back")
  1480. },
  1481. "resistor_sides": {
  1482. key: resistor_side_counts.get(key, 0) for key in ("front", "back")
  1483. },
  1484. },
  1485. "value_coverage": value_coverage,
  1486. "component_value_source_status": value_coverage["component_value_source_status"],
  1487. "touchpoints": touchpoints,
  1488. "resistors": resistors,
  1489. "resistor_links": structured_links,
  1490. "evidence_conflicts": evidence_conflicts,
  1491. "interfaces": list(annotations.get("interfaces", [])) if isinstance(annotations.get("interfaces", []), list) else [],
  1492. "photo_overlay": annotations.get("photo_overlay"),
  1493. }
  1494. # Structural self-check only; annotation ⊆ index (Pass G) is enforced by
  1495. # validate/regression against the product board, not every fixture build.
  1496. if payload["counts"]["resistors"] != len(resistors):
  1497. raise ValueError("resistor count mismatch while building board data")
  1498. if payload["counts"]["resistor_pads"] != sum(len(item["pads"]) for item in resistors):
  1499. raise ValueError("resistor pad count mismatch while building board data")
  1500. return payload