data.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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 re
  6. from typing import Any
  7. from .annotations import expand_annotation_templates, validate_annotation_references
  8. from .eligibility import evaluate_recommendation
  9. from .pcb import Footprint, Pad, ParsedBoard, select_touchpoints
  10. EVIDENCE_TIERS = {"board_database", "cross_verified", "name_inferred", "unknown"}
  11. CONNECTOR_ROW_TOLERANCE_MM = 0.05
  12. INTERNAL_NET = re.compile(r"^(?:N\d+|NET_\d+)$", re.IGNORECASE)
  13. POWER_NET = re.compile(r"^(?:VCC|VDD|VBAT|PWR|\+)", re.IGNORECASE)
  14. def _category(reference: str) -> str:
  15. for prefix in ("CON", "PL", "TP", "J"):
  16. if reference.startswith(prefix):
  17. return prefix
  18. return "OTHER"
  19. def _view_point(x: float, y: float, bounds: Mapping[str, float]) -> dict[str, float]:
  20. return {"x": x - bounds["x"], "y": y - bounds["y"]}
  21. def _view_bounds(item: Mapping[str, float], board_bounds: Mapping[str, float]) -> dict[str, float]:
  22. return {
  23. "x": item["x"] - board_bounds["x"],
  24. "y": item["y"] - board_bounds["y"],
  25. "width": item["width"],
  26. "height": item["height"],
  27. }
  28. def _pin_dict(
  29. reference: str,
  30. category: str,
  31. pad: Pad,
  32. board_bounds: Mapping[str, float],
  33. source_index: int,
  34. ) -> dict[str, Any]:
  35. role = "mechanical" if pad.mechanical else ("unknown" if category == "CON" else "contact")
  36. return {
  37. "id": f"{reference}.pad-{source_index + 1}",
  38. "number": pad.number,
  39. "pad_role": role,
  40. "row": None,
  41. "column": None,
  42. "board_order": None,
  43. "mechanical": pad.mechanical,
  44. "electrical": pad.electrical,
  45. "net": pad.net,
  46. "position": {"x": pad.x, "y": pad.y},
  47. "view_position": _view_point(pad.x, pad.y, board_bounds),
  48. "size": {
  49. "width": pad.width,
  50. "height": pad.height,
  51. "drill_width": pad.drill_width,
  52. "drill_height": pad.drill_height,
  53. },
  54. "rotation": pad.rotation,
  55. "shape": pad.shape,
  56. "layers": list(pad.layers),
  57. "direction": "unknown",
  58. "external_level": "unknown",
  59. "function_category": _classify_function(pad.net, []),
  60. "reserved": False,
  61. "fixed_load_conflict": False,
  62. "board_pull": None,
  63. "adc_pulltype": None,
  64. "active_level": "unknown",
  65. "polarity": "unknown",
  66. "external_components": [],
  67. "summary": _raw_pin_summary(pad),
  68. "path": [],
  69. "evidence_tier": "board_database",
  70. "evidence_sources": ["board:kicad_import"],
  71. "fpga": None,
  72. "mcu": None,
  73. "programming": {},
  74. "recommendation": {"eligible": False, "reasons": ["pin_evidence_not_verified"]},
  75. }
  76. def _raw_pin_summary(pad: Pad) -> str:
  77. if pad.mechanical:
  78. return "机械焊盘"
  79. if pad.net:
  80. return f"板内网络 {pad.net}"
  81. return "未命名电气焊盘"
  82. def _classify_function(net: str | None, capabilities: list[str]) -> str:
  83. ordered = (
  84. "uart_tx",
  85. "uart_rx",
  86. "pwm",
  87. "fan_tach",
  88. "tach",
  89. "presence",
  90. "gpio_output",
  91. "gpio_input",
  92. "gpio",
  93. )
  94. normalized = {str(item).lower() for item in capabilities}
  95. for category in ordered:
  96. if category in normalized:
  97. return category
  98. upper_net = str(net or "").upper()
  99. if upper_net in {"GND", "AGND", "DGND", "PGND"}:
  100. return "ground"
  101. if upper_net.startswith(("+", "VCC", "VDD", "VBAT", "PWR")):
  102. return "power"
  103. if "PWM" in upper_net:
  104. return "pwm"
  105. if "TX" in upper_net and "UART" in upper_net:
  106. return "uart_tx"
  107. if "RX" in upper_net and "UART" in upper_net:
  108. return "uart_rx"
  109. if "FG" in upper_net or "TACH" in upper_net:
  110. return "tach"
  111. if "INSTALL" in upper_net or "PRESENT" in upper_net:
  112. return "presence"
  113. return "unknown"
  114. def _touchpoint_dict(footprint: Footprint, board_bounds: Mapping[str, float]) -> dict[str, Any]:
  115. category = _category(footprint.reference)
  116. category_name = {"CON": "连接器", "J": "接口", "PL": "插座", "TP": "测试点"}.get(category, category)
  117. return {
  118. "reference": footprint.reference,
  119. "category": category,
  120. "component_value": footprint.component_value,
  121. "position": {"x": footprint.x, "y": footprint.y},
  122. "view_position": _view_point(footprint.x, footprint.y, board_bounds),
  123. "rotation": footprint.rotation,
  124. "bounds": dict(footprint.bounds),
  125. "view_bounds": _view_bounds(footprint.bounds, board_bounds),
  126. "side": footprint.side,
  127. "summary": f"{category_name},用途未注释",
  128. "connector": None,
  129. "pins": [
  130. _pin_dict(footprint.reference, category, pad, board_bounds, index)
  131. for index, pad in enumerate(footprint.pads)
  132. ],
  133. }
  134. def _connector_profile_index(
  135. annotations: Mapping[str, object],
  136. ) -> dict[str, tuple[str, Mapping[str, object]]]:
  137. result: dict[str, tuple[str, Mapping[str, object]]] = {}
  138. profiles = annotations.get("connector_profiles", {})
  139. if not isinstance(profiles, Mapping):
  140. return result
  141. for profile_name, profile in profiles.items():
  142. if not isinstance(profile, Mapping):
  143. continue
  144. references = profile.get("references", [])
  145. if not isinstance(references, list):
  146. continue
  147. for reference in references:
  148. result[str(reference)] = (str(profile_name), profile)
  149. return result
  150. def _cluster_contact_rows(pins: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
  151. rows: list[list[dict[str, Any]]] = []
  152. row_y: list[float] = []
  153. ordered = sorted(
  154. pins,
  155. key=lambda item: (float(item["position"]["y"]), float(item["position"]["x"])),
  156. )
  157. for pin in ordered:
  158. y = float(pin["position"]["y"])
  159. if not rows or abs(y - row_y[-1]) > CONNECTOR_ROW_TOLERANCE_MM:
  160. rows.append([pin])
  161. row_y.append(y)
  162. continue
  163. rows[-1].append(pin)
  164. row_y[-1] = sum(float(item["position"]["y"]) for item in rows[-1]) / len(rows[-1])
  165. for row in rows:
  166. row.sort(key=lambda item: (float(item["position"]["x"]), str(item["number"])))
  167. return rows
  168. def _pin_sort_key(pin: Mapping[str, object]) -> tuple[int, int, str]:
  169. role_order = {"contact": 0, "shield": 1, "mechanical": 2, "unknown": 3}
  170. board_order = pin.get("board_order")
  171. return (
  172. role_order.get(str(pin.get("pad_role")), 4),
  173. int(board_order) if isinstance(board_order, int) else 1_000_000,
  174. str(pin.get("id") or ""),
  175. )
  176. def _apply_connector_profile(
  177. touchpoint: dict[str, Any],
  178. profile_entry: tuple[str, Mapping[str, object]] | None,
  179. ) -> None:
  180. pins = touchpoint["pins"]
  181. if profile_entry is None:
  182. touchpoint["connector"] = {
  183. "profile": None,
  184. "review_status": "unknown",
  185. "view": "board_front",
  186. "contact_count": 0,
  187. "auxiliary_pad_count": len(pins),
  188. "rows": 0,
  189. "columns": 0,
  190. "contact_grid": [],
  191. "contact_order": [],
  192. "sources": [],
  193. }
  194. pins.sort(key=_pin_sort_key)
  195. return
  196. profile_name, profile = profile_entry
  197. contacts = {str(value) for value in profile.get("contact_pins", [])}
  198. shields = {str(value) for value in profile.get("shield_pads", [])}
  199. for pin in pins:
  200. number = str(pin["number"])
  201. if pin["mechanical"]:
  202. pin["pad_role"] = "mechanical"
  203. elif number in contacts:
  204. pin["pad_role"] = "contact"
  205. elif number in shields:
  206. pin["pad_role"] = "shield"
  207. else:
  208. pin["pad_role"] = "unknown"
  209. contact_pins = [pin for pin in pins if pin["pad_role"] == "contact"]
  210. rows = _cluster_contact_rows(contact_pins)
  211. contact_grid: list[list[str]] = []
  212. order = 1
  213. for row_number, row in enumerate(rows, start=1):
  214. grid_row: list[str] = []
  215. for column_number, pin in enumerate(row, start=1):
  216. pin["row"] = row_number
  217. pin["column"] = column_number
  218. pin["board_order"] = order
  219. grid_row.append(str(pin["number"]))
  220. order += 1
  221. contact_grid.append(grid_row)
  222. touchpoint["connector"] = {
  223. "profile": profile_name,
  224. "review_status": str(profile.get("evidence_tier") or "unknown"),
  225. "view": "board_front",
  226. "contact_count": len(contact_pins),
  227. "auxiliary_pad_count": len(pins) - len(contact_pins),
  228. "rows": len(contact_grid),
  229. "columns": max((len(row) for row in contact_grid), default=0),
  230. "contact_grid": contact_grid,
  231. "contact_order": [number for row in contact_grid for number in row],
  232. "sources": [str(value) for value in profile.get("sources", [])],
  233. }
  234. pins.sort(key=_pin_sort_key)
  235. def _inventory_indexes(inventory: Mapping[str, object]) -> tuple[dict[tuple[str, str], Mapping[str, object]], dict[str, list[Mapping[str, object]]]]:
  236. direct: dict[tuple[str, str], Mapping[str, object]] = {}
  237. by_net: dict[str, list[Mapping[str, object]]] = {}
  238. pins = inventory.get("pins", [])
  239. if not isinstance(pins, list):
  240. return direct, by_net
  241. for item in pins:
  242. if not isinstance(item, Mapping):
  243. continue
  244. connector = item.get("board_connector")
  245. connector_pin = item.get("connector_pin")
  246. if connector and connector_pin is not None:
  247. direct[(str(connector), str(connector_pin))] = item
  248. for name in (item.get("function_net"), item.get("signal")):
  249. if name:
  250. by_net.setdefault(str(name), []).append(item)
  251. return direct, by_net
  252. def _inventory_match(
  253. reference: str,
  254. pin: Mapping[str, object],
  255. direct: Mapping[tuple[str, str], Mapping[str, object]],
  256. by_net: Mapping[str, list[Mapping[str, object]]],
  257. ) -> Mapping[str, object] | None:
  258. key = (reference, str(pin.get("number", "")))
  259. if key in direct:
  260. item = direct[key]
  261. expected_net = item.get("connector_signal") or item.get("function_net") or item.get("signal")
  262. actual_net = pin.get("net")
  263. if expected_net and actual_net and str(expected_net) != str(actual_net):
  264. raise ValueError(
  265. f"connector net mismatch {reference}.{pin.get('number')}: "
  266. f"board={actual_net} inventory={expected_net}"
  267. )
  268. return item
  269. net = pin.get("net")
  270. matches = by_net.get(str(net), []) if net else []
  271. return matches[0] if len(matches) == 1 else None
  272. def _inventory_source(item: Mapping[str, object]) -> str:
  273. marker = item.get("screenshot_index") or item.get("source_confidence") or item.get("signal")
  274. return f"inventory:{marker}"
  275. def _merge_inventory(pin: dict[str, Any], item: Mapping[str, object]) -> None:
  276. capabilities = [str(value) for value in item.get("capability", [])]
  277. verified = item.get("manually_verified") is True
  278. evidence_tier = "cross_verified" if verified else "name_inferred"
  279. source = _inventory_source(item)
  280. board_pull = item.get("board_pull")
  281. if board_pull is None:
  282. board_pull = item.get("pullup")
  283. external_components = []
  284. for key in ("transceiver", "series_link", "esd"):
  285. value = item.get(key)
  286. if value and str(value) not in external_components:
  287. external_components.append(str(value))
  288. pin.update(
  289. {
  290. "direction": str(item.get("direction") or "unknown"),
  291. "external_level": str(item.get("external_level") or "unknown"),
  292. "function_category": _classify_function(str(item.get("function_net") or pin.get("net") or ""), capabilities),
  293. "reserved": item.get("reserved") is True,
  294. "fixed_load_conflict": item.get("fixed_load_conflict") is True,
  295. "board_pull": board_pull,
  296. "active_level": str(item.get("active_level") or "unknown"),
  297. "polarity": str(item.get("polarity") or "unknown"),
  298. "external_components": external_components,
  299. "evidence_tier": evidence_tier,
  300. "evidence_sources": [*pin["evidence_sources"], source],
  301. "fpga": {
  302. "ball": str(item.get("fpga_ball") or ""),
  303. "board_signal": str(item.get("signal") or item.get("function_net") or ""),
  304. "io_standard": str(item.get("io_standard") or ""),
  305. "capabilities": capabilities,
  306. "evidence_tier": evidence_tier,
  307. "sources": [source],
  308. },
  309. }
  310. )
  311. transceiver = item.get("transceiver")
  312. if transceiver:
  313. pin["path"] = [str(transceiver)]
  314. signal = item.get("signal") or item.get("function_net")
  315. if signal:
  316. pin["summary"] = str(signal)
  317. def _merge_annotation(pin: dict[str, Any], annotation: Mapping[str, object]) -> None:
  318. for key in (
  319. "summary",
  320. "direction",
  321. "external_level",
  322. "function_category",
  323. "reserved",
  324. "fixed_load_conflict",
  325. "board_pull",
  326. "adc_pulltype",
  327. "active_level",
  328. "polarity",
  329. "external_components",
  330. "path",
  331. ):
  332. if key in annotation:
  333. pin[key] = annotation[key]
  334. fpga = annotation.get("fpga")
  335. if isinstance(fpga, Mapping):
  336. pin["fpga"] = {
  337. "ball": str(fpga.get("ball") or ""),
  338. "board_signal": str(fpga.get("board_signal") or ""),
  339. "io_standard": str(fpga.get("io_standard") or ""),
  340. "capabilities": [str(value) for value in fpga.get("capabilities", [])],
  341. "evidence_tier": str(fpga.get("evidence_tier") or "unknown"),
  342. "sources": [str(value) for value in fpga.get("sources", [])],
  343. }
  344. mcu = annotation.get("mcu")
  345. if isinstance(mcu, Mapping):
  346. pin["mcu"] = {
  347. "device": str(mcu.get("device") or ""),
  348. "family": str(mcu.get("family") or ""),
  349. "pin": str(mcu.get("pin") or ""),
  350. "signal": str(mcu.get("signal") or ""),
  351. "capabilities": [str(value) for value in mcu.get("capabilities", [])],
  352. "evidence_tier": str(mcu.get("evidence_tier") or "unknown"),
  353. "sources": [str(value) for value in mcu.get("sources", [])],
  354. }
  355. tier = annotation.get("evidence_tier")
  356. if tier in EVIDENCE_TIERS:
  357. pin["evidence_tier"] = tier
  358. if isinstance(pin.get("fpga"), dict):
  359. pin["fpga"]["evidence_tier"] = tier
  360. sources = annotation.get("sources", [])
  361. if isinstance(sources, list):
  362. pin["evidence_sources"] = [*pin["evidence_sources"], *[str(item) for item in sources]]
  363. def _unique_strings(values: list[object]) -> list[str]:
  364. result: list[str] = []
  365. for value in values:
  366. text = str(value)
  367. if text and text not in result:
  368. result.append(text)
  369. return result
  370. def _verified_fpga(pin: Mapping[str, object]) -> Mapping[str, object] | None:
  371. fpga = pin.get("fpga")
  372. if (
  373. pin.get("evidence_tier") == "cross_verified"
  374. and isinstance(fpga, Mapping)
  375. and fpga.get("evidence_tier") == "cross_verified"
  376. and fpga.get("ball")
  377. and fpga.get("io_standard")
  378. ):
  379. return fpga
  380. return None
  381. def _verified_mcu(pin: Mapping[str, object]) -> Mapping[str, object] | None:
  382. mcu = pin.get("mcu")
  383. if (
  384. pin.get("evidence_tier") == "cross_verified"
  385. and isinstance(mcu, Mapping)
  386. and mcu.get("evidence_tier") == "cross_verified"
  387. and mcu.get("device")
  388. and mcu.get("family")
  389. and mcu.get("pin")
  390. and mcu.get("signal")
  391. ):
  392. return mcu
  393. return None
  394. def _programming_guidance(reference: str, pin: Mapping[str, object]) -> dict[str, object]:
  395. number = str(pin.get("number") or "")
  396. net = str(pin.get("net") or "")
  397. role = str(pin.get("pad_role") or "unknown")
  398. function_category = str(pin.get("function_category") or "unknown")
  399. direction = str(pin.get("direction") or "unknown")
  400. external_level = str(pin.get("external_level") or "unknown")
  401. fpga = _verified_fpga(pin)
  402. mcu = _verified_mcu(pin)
  403. sources = _unique_strings(list(pin.get("evidence_sources", [])))
  404. if role == "mechanical" or pin.get("mechanical") is True or pin.get("electrical") is not True:
  405. return {
  406. "status": "not_programmable",
  407. "conclusion": "这是机械定位孔,不是电气针脚。",
  408. "network_explanation": "机械孔没有可用于编程的板内网络。",
  409. "hdl_guidance": "不要声明 RTL 端口,也不能生成 ADC 约束。",
  410. "connection_guidance": ["不要把机械孔作为信号、电源或地连接点。"],
  411. "constraints": [],
  412. "risks": ["它只承担机械定位或固定作用。"],
  413. "evidence_tier": "board_database",
  414. "sources": sources,
  415. }
  416. if role == "shield":
  417. grounded = net.upper() in {"GND", "AGND", "DGND", "PGND"}
  418. network = "并与板级 GND 相连" if grounded else f"板数据库网络为 {net or '未命名'}"
  419. return {
  420. "status": "not_programmable",
  421. "conclusion": "这是屏蔽/固定焊盘,不属于座子对外接触针。",
  422. "network_explanation": f"该焊盘用于连接器外壳或固定,{network}。",
  423. "hdl_guidance": "不要为它声明 RTL 端口,也不能生成 ADC 约束。",
  424. "connection_guidance": ["线束 pinout 只使用标记为“接触针”的焊盘。"],
  425. "constraints": [],
  426. "risks": ["把屏蔽固定焊盘当作外部 Pin 会造成针脚数量和顺序错误。"],
  427. "evidence_tier": str(pin.get("evidence_tier") or "board_database"),
  428. "sources": sources,
  429. }
  430. if function_category == "ground" or net.upper() in {"GND", "AGND", "DGND", "PGND"}:
  431. return {
  432. "status": "not_programmable",
  433. "conclusion": "这是接地针,用作信号参考和电流回路,不是 FPGA I/O。",
  434. "network_explanation": f"板数据库确认 {reference}.{number} 连接到板级 {net or 'GND'}。",
  435. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  436. "connection_guidance": ["作为外部设备的参考地/回流地连接,不要当作逻辑信号脚。"],
  437. "constraints": [],
  438. "risks": ["接线时仍需遵守整机接地和回流设计。"],
  439. "evidence_tier": str(pin.get("evidence_tier") or "board_database"),
  440. "sources": sources,
  441. }
  442. if mcu is not None:
  443. device = str(mcu.get("device"))
  444. family = str(mcu.get("family"))
  445. package_pin = str(mcu.get("pin"))
  446. signal = str(mcu.get("signal"))
  447. return {
  448. "status": "verified_mcu",
  449. "conclusion": (
  450. f"GD32 MCU 固件测试点:{reference}.{number} 直连 "
  451. f"{device}.{package_pin}({signal},{family})。"
  452. ),
  453. "network_explanation": (
  454. f"板数据库与原理图共同确认网络 {net or signal} 对应 "
  455. f"{device} 封装引脚 {package_pin} / 端口 {signal};它不是 FPGA 球位。"
  456. ),
  457. "hdl_guidance": (
  458. f"不要在 FPGA RTL/ADC 中声明此针;应在 GD32 固件中按 {signal} "
  459. "配置 GPIO 或所需复用功能,方向和复用选择由当前 MCU 固件决定。"
  460. ),
  461. "connection_guidance": [
  462. f"外接仪器或信号前按 {external_level} 边界检查,并与板级 GND 共参考。",
  463. "作为测量点使用时优先采用高阻探头,避免改变 MCU 引脚状态。",
  464. ],
  465. "constraints": [
  466. f"MCU = {family} {device}",
  467. f"PACKAGE_PIN = {package_pin}",
  468. f"PORT = {signal}",
  469. ],
  470. "risks": [
  471. "查看器不读取当前 MCU 固件,仍需检查端口复用、启动状态和外设占用。",
  472. "此映射不能生成 FPGA ADC 约束。",
  473. ],
  474. "evidence_tier": "cross_verified",
  475. "sources": sources,
  476. }
  477. if fpga is not None:
  478. signal = str(fpga.get("board_signal") or pin.get("summary") or net)
  479. ball = str(fpga.get("ball"))
  480. io_standard = str(fpga.get("io_standard"))
  481. components = [str(value) for value in pin.get("external_components", []) if value]
  482. transceiver = next((value for value in components if value.upper().startswith("U")), None)
  483. if direction == "output":
  484. route = f"经 {transceiver} 转换后" if transceiver else "通过板内网络"
  485. conclusion = f"FPGA 输出:RTL 驱动 {signal}(球位 {ball}),{route}从 {reference}.{number} 发出。"
  486. elif direction == "input":
  487. route = f"先经 {transceiver} 转换,再" if transceiver else "通过板内网络"
  488. conclusion = f"FPGA 输入:外部信号从 {reference}.{number} 进入,{route}由 {signal}(球位 {ball})采样。"
  489. elif direction in {"bidir", "bidirectional"} and function_category == "gpio":
  490. conclusion = (
  491. f"已验证直连 FPGA GPIO:{reference}.{number} 对应 {signal}(球位 {ball}),"
  492. "物理上支持输入或输出。"
  493. )
  494. else:
  495. conclusion = f"已验证 FPGA 路径:{reference}.{number} 对应 {signal}(球位 {ball}),方向为 {direction}。"
  496. if transceiver:
  497. network_explanation = (
  498. f"连接器侧原始网络是 {net or '未命名'};经 {transceiver} 后,"
  499. f"FPGA 逻辑侧信号是 {signal}。"
  500. )
  501. else:
  502. network_explanation = (
  503. f"板数据库网络 {net or '未命名'} 已交叉验证到 FPGA 逻辑信号 {signal}({ball})。"
  504. )
  505. connection_guidance: list[str] = []
  506. if direction == "output" and function_category == "uart_tx":
  507. connection_guidance.append("连接到对端设备的接收端(RX)。")
  508. elif direction == "input" and function_category == "uart_rx":
  509. connection_guidance.append("连接到对端设备的发送端(TX)。")
  510. elif direction == "output":
  511. connection_guidance.append("这是板端输出;外部设备应作为接收端,不要与另一个主动输出直接相连。")
  512. elif direction == "input":
  513. connection_guidance.append("这是板端输入;由外部设备驱动,接入前确认电平和公共参考地。")
  514. elif direction in {"bidir", "bidirectional"} and function_category == "gpio":
  515. connection_guidance.append(
  516. "按实际用途选择输入或输出;配置为输入时由外部设备驱动,配置为输出时不要与另一个主动输出硬连接。"
  517. )
  518. else:
  519. connection_guidance.append("按已验证方向使用;双向信号需要在 RTL 中正确控制输出使能。")
  520. if external_level.upper() == "RS232":
  521. connection_guidance.append("连接器侧是 RS-232 电平,不能直接接 3.3V TTL/CMOS 串口。")
  522. if direction in {"bidir", "bidirectional"} and function_category == "gpio":
  523. hdl_guidance = (
  524. f"该物理脚支持 input、output 或 inout,按实际功能选择;"
  525. f"只有真正需要双向共享并实现输出使能时才使用三态 inout。FPGA 逻辑侧使用 {io_standard}。"
  526. )
  527. else:
  528. hdl_guidance = f"RTL 端口方向应为 {direction};FPGA 逻辑侧使用 {io_standard}。"
  529. active_level = str(pin.get("active_level") or "unknown")
  530. if active_level in {"high", "low"}:
  531. active_cn = "高" if active_level == "high" else "低"
  532. hdl_guidance += f" 此功能为{active_cn}电平有效。"
  533. constraints = [f"LOCATION = {ball}", f"IOSTANDARD = {io_standard}"]
  534. board_pull = pin.get("board_pull")
  535. if board_pull:
  536. constraints.append(f"板上外部 pull:{board_pull}")
  537. if active_level in {"high", "low"}:
  538. constraints.append(f"有效电平:{'高电平' if active_level == 'high' else '低电平'}")
  539. risks = ["这里只证明物理路径和板级证据,仍需检查当前工程约束冲突。"]
  540. if direction in {"bidir", "bidirectional"} and function_category == "gpio":
  541. risks.insert(0, "不要因为物理上可双向就默认声明 inout;错误的三态控制可能造成总线争用。")
  542. if pin.get("reserved") is True:
  543. risks.insert(0, "当前 inventory 将此功能标记为保留,不能作为空闲 GPIO 重新分配。")
  544. if pin.get("fixed_load_conflict") is True:
  545. risks.insert(0, "此针存在已知固定负载冲突。")
  546. return {
  547. "status": "verified_fpga",
  548. "conclusion": conclusion,
  549. "network_explanation": network_explanation,
  550. "hdl_guidance": hdl_guidance,
  551. "connection_guidance": connection_guidance,
  552. "constraints": constraints,
  553. "risks": risks,
  554. "evidence_tier": "cross_verified",
  555. "sources": sources,
  556. }
  557. if function_category == "power" or POWER_NET.match(net):
  558. if pin.get("evidence_tier") == "cross_verified":
  559. summary = str(pin.get("summary") or f"电源网络 {net or '未命名'}").rstrip("。")
  560. path = [str(item) for item in pin.get("path", []) if item]
  561. path_text = " -> ".join(path) if path else f"{reference}.{number} {net or '未命名'}"
  562. direction_text = {
  563. "input": "板端电源输入",
  564. "output": "板端电源输出",
  565. "passive": "电源参考/分配节点",
  566. }.get(direction, f"方向 {direction}")
  567. if direction == "input":
  568. connection_guidance = [
  569. f"这是{direction_text};只能接符合 {external_level} 边界的电源,并核对极性与公共地。"
  570. ]
  571. direction_risk = "不要反向供电或从该输入针向外取电。"
  572. elif direction == "output":
  573. connection_guidance = [
  574. f"这是{direction_text};只用于给设计负载提供 {external_level},不要与另一电源输出并接。"
  575. ]
  576. direction_risk = "不要向该输出针反向供电。"
  577. else:
  578. connection_guidance = [
  579. f"这是{direction_text};按原理图定义使用,并遵守 {external_level} 电气边界。"
  580. ]
  581. direction_risk = "不要把电源参考/分配节点当作普通信号或任意供电入口。"
  582. return {
  583. "status": "not_programmable",
  584. "conclusion": f"{summary}。这是{direction_text},不是 FPGA I/O,不能用于逻辑选脚。",
  585. "network_explanation": (
  586. f"原理图与板数据库交叉确认路径:{path_text};"
  587. f"外部电气边界为 {external_level},方向为 {direction_text}。"
  588. ),
  589. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  590. "connection_guidance": connection_guidance,
  591. "constraints": [],
  592. "risks": [
  593. direction_risk,
  594. "查看器不证明额定电流、线束载流能力或选配保护器件的实际装配状态,仍需核对 BOM 和整机规范。",
  595. ],
  596. "evidence_tier": "cross_verified",
  597. "sources": sources,
  598. }
  599. return {
  600. "status": "not_programmable",
  601. "conclusion": "这是电源网络,不是 FPGA I/O,不能用于逻辑选脚。",
  602. "network_explanation": (
  603. f"按板数据库网名 {net or '未命名'} 可判断它属于电源域;"
  604. "供电方向、额定电流和是否允许外供尚未在查看器中交叉验证。"
  605. ),
  606. "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
  607. "connection_guidance": ["连接前必须查原理图和整机线束,确认电压、方向与电流能力。"],
  608. "constraints": [],
  609. "risks": ["错误接入 FPGA 3.3V I/O 可能造成硬件损坏。"],
  610. "evidence_tier": "name_inferred",
  611. "sources": sources,
  612. }
  613. if INTERNAL_NET.match(net):
  614. network_explanation = (
  615. f"{net} 是 CAD 自动生成的内部网络编号,只能证明同名焊盘电气相连;"
  616. "编号本身不包含功能、方向或电平含义。"
  617. )
  618. elif net:
  619. network_explanation = (
  620. f"板数据库确认此焊盘连接到 {net};当前没有足够证据把该网名等同于某个 FPGA 端口。"
  621. )
  622. else:
  623. network_explanation = "该电气焊盘没有可解释的网络名,功能保持未知。"
  624. return {
  625. "status": "board_only" if net else "unknown",
  626. "conclusion": f"当前只确认到板内网络 {net or '未知'},没有已验证 FPGA 路径。",
  627. "network_explanation": network_explanation,
  628. "hdl_guidance": "不能据此写 RTL 方向或 ADC 约束;需要原理图路径或人工交叉验证。",
  629. "connection_guidance": ["接线前先确认该网络经过的器件、外部电平和信号方向。"],
  630. "constraints": [],
  631. "risks": ["网名相似不等于功能相同,禁止仅凭名称推断 FPGA 映射。"],
  632. "evidence_tier": "board_database" if net else "unknown",
  633. "sources": sources,
  634. }
  635. def _merge_programming_annotation(
  636. programming: dict[str, object], annotation: Mapping[str, object]
  637. ) -> None:
  638. for key in (
  639. "status",
  640. "conclusion",
  641. "network_explanation",
  642. "hdl_guidance",
  643. "connection_guidance",
  644. "constraints",
  645. "risks",
  646. ):
  647. if key in annotation:
  648. programming[key] = annotation[key]
  649. tier = annotation.get("evidence_tier")
  650. if tier in EVIDENCE_TIERS:
  651. programming["evidence_tier"] = tier
  652. sources = annotation.get("sources", [])
  653. if isinstance(sources, list):
  654. programming["sources"] = _unique_strings(
  655. [*list(programming.get("sources", [])), *sources]
  656. )
  657. def _refresh_recommendation(pin: dict[str, Any]) -> None:
  658. fpga = pin.get("fpga")
  659. capabilities = fpga.get("capabilities", []) if isinstance(fpga, Mapping) else []
  660. useful = [item for item in capabilities if item not in {"gpio", "rs232_via_transceiver"}]
  661. capability = str(useful[0] if useful else (capabilities[0] if capabilities else "gpio"))
  662. result = evaluate_recommendation(pin, capability)
  663. pin["recommendation"] = {"eligible": result.eligible, "reasons": result.reasons}
  664. def build_board_data(
  665. board: ParsedBoard,
  666. inventory: Mapping[str, object],
  667. annotations: Mapping[str, object],
  668. *,
  669. board_name: str,
  670. ) -> dict[str, Any]:
  671. annotations = expand_annotation_templates(annotations)
  672. touchpoints = [_touchpoint_dict(footprint, board.bounds) for footprint in select_touchpoints(board)]
  673. touchpoint_index = {item["reference"]: item for item in touchpoints}
  674. validate_annotation_references(annotations, touchpoint_index)
  675. connector_profiles = _connector_profile_index(annotations)
  676. direct, by_net = _inventory_indexes(inventory)
  677. annotated_touchpoints = annotations.get("touchpoints", {})
  678. for touchpoint in touchpoints:
  679. reference = touchpoint["reference"]
  680. profile_entry = connector_profiles.get(reference)
  681. if touchpoint["category"] == "CON" or profile_entry is not None:
  682. _apply_connector_profile(touchpoint, profile_entry)
  683. touchpoint_annotation = (
  684. annotated_touchpoints.get(reference, {}) if isinstance(annotated_touchpoints, Mapping) else {}
  685. )
  686. if isinstance(touchpoint_annotation, Mapping) and touchpoint_annotation.get("summary"):
  687. touchpoint["summary"] = str(touchpoint_annotation["summary"])
  688. pin_annotations = (
  689. touchpoint_annotation.get("pins", {}) if isinstance(touchpoint_annotation, Mapping) else {}
  690. )
  691. for pin in touchpoint["pins"]:
  692. inventory_item = _inventory_match(reference, pin, direct, by_net)
  693. if inventory_item is not None:
  694. _merge_inventory(pin, inventory_item)
  695. annotation = pin_annotations.get(pin["number"], {}) if isinstance(pin_annotations, Mapping) else {}
  696. if isinstance(annotation, Mapping):
  697. _merge_annotation(pin, annotation)
  698. pin["programming"] = _programming_guidance(reference, pin)
  699. programming_annotation = annotation.get("programming", {}) if isinstance(annotation, Mapping) else {}
  700. if isinstance(programming_annotation, Mapping):
  701. _merge_programming_annotation(pin["programming"], programming_annotation)
  702. _refresh_recommendation(pin)
  703. category_counts = Counter(item["category"] for item in touchpoints)
  704. side_counts = Counter(item["side"] for item in touchpoints)
  705. connector_touchpoints = [item for item in touchpoints if item["category"] == "CON"]
  706. return {
  707. "schema": "board-viewer-data-v1",
  708. "board": {
  709. "id": str(inventory.get("board_id") or annotations.get("board_id") or "unknown"),
  710. "name": board_name,
  711. "source_bounds": dict(board.bounds),
  712. "view_box": {"x": 0.0, "y": 0.0, "width": board.bounds["width"], "height": board.bounds["height"]},
  713. },
  714. "counts": {
  715. "footprints": board.footprint_count,
  716. "touchpoints": len(touchpoints),
  717. "pads": sum(len(item["pins"]) for item in touchpoints),
  718. "connector_contacts": sum(
  719. int(item["connector"]["contact_count"]) for item in connector_touchpoints
  720. ),
  721. "connector_auxiliary_pads": sum(
  722. int(item["connector"]["auxiliary_pad_count"]) for item in connector_touchpoints
  723. ),
  724. "categories": {key: category_counts.get(key, 0) for key in ("CON", "J", "PL", "TP")},
  725. "sides": {key: side_counts.get(key, 0) for key in ("front", "back")},
  726. },
  727. "touchpoints": touchpoints,
  728. "interfaces": list(annotations.get("interfaces", [])) if isinstance(annotations.get("interfaces", []), list) else [],
  729. "photo_overlay": annotations.get("photo_overlay"),
  730. }