167 lines
6.7 KiB
Python
167 lines
6.7 KiB
Python
"""板子一侧:铜箔上到底连没连。只能在装了 KiCad 的机器上跑。
|
||
|
||
这个模块存在的理由不是"再多一个 provider",而是**让两份来源互相作证**。
|
||
|
||
* 网表说的是**意图**:原理图上这两个脚属于同一条网。
|
||
* 板子说的是**现实**:铜箔、焊盘、过孔是不是真的把它们接通了。
|
||
|
||
成品板上两者一致,半布线的板上不一致。这个不一致不是 bug,是这类系统必须能表达
|
||
的东西:一份来源说"连上了",另一份说"没连上",正确结论是**不知道**,除非有第三方
|
||
信息(哪份更新、这块板本来就是半成品)。
|
||
|
||
``spatial/checker.py`` 目前没有"两份来源冲突"这个概念,只有"缺了东西"。所以这里先
|
||
只做测量,把冲突数数出来,再决定要不要、以及怎么把它接进契约。
|
||
|
||
用法(服务器)::
|
||
|
||
python3 -m spatial.providers.kicad_board <a.kicad_pcb> ...
|
||
python3 -m spatial.providers.kicad_board <a.kicad_pcb> <a.net> # 覆盖度
|
||
python3 -m spatial.providers.kicad_board control <a.kicad_pcb> # 阳性对照
|
||
|
||
关于"按网统计":``GetRatsnestForNet`` 在这个绑定里返回不透明对象(取不到长度),
|
||
``RunOnUnconnectedEdges`` 要的是 C++ 的 ``std::function``,传不了 Python 回调
|
||
(都在 KiCad 10.0.6 上实测过)。所以只报板级总数,不报"哪条网断了"——要那个就得
|
||
自己重写一遍连通性,不值得。
|
||
|
||
一条硬规矩:**这里没有 ``except`` 兜底**。第一版写了 ``try/except`` 返回 -1,而调用
|
||
方用 ``> 0`` 判断,于是所有失败都变成了"0 条未连通",报告上看起来完美。阳性对照
|
||
(删掉一条网的铜,看数字动不动)把这个洞捅了出来,见 :func:`control`。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import sys
|
||
|
||
|
||
def _pcbnew():
|
||
try:
|
||
import pcbnew
|
||
except Exception as exc: # noqa: BLE001 - reported, not hidden
|
||
raise SystemExit(
|
||
"this module needs pcbnew (KiCad's Python bindings); "
|
||
f"import failed with {type(exc).__name__}: {exc}")
|
||
return pcbnew
|
||
|
||
|
||
def _pads(board):
|
||
return list(board.GetPads())
|
||
|
||
|
||
def _ref(pad) -> str:
|
||
"""Footprint reference. ``GetParent()`` returns a container, not a footprint
|
||
(measured on KiCad 10.0.6), so the accessor is ``GetParentFootprint``."""
|
||
return pad.GetParentFootprint().GetReference()
|
||
|
||
|
||
def _missing(board) -> int:
|
||
"""Copper connections the board still owes. No swallowing: if this raises,
|
||
the measurement failed and must not be printed as zero."""
|
||
return int(board.GetConnectivity().GetUnconnectedCount(False))
|
||
|
||
|
||
def report(paths) -> None:
|
||
pcbnew = _pcbnew()
|
||
print(f"{'board':26s} {'焊盘':>5s} {'有网':>5s} {'无网':>5s} {'网数':>4s} {'缺连接':>6s}")
|
||
print("-" * 56)
|
||
for path in paths:
|
||
board = pcbnew.LoadBoard(path)
|
||
board.BuildConnectivity()
|
||
pads = _pads(board)
|
||
with_net = [p for p in pads if p.GetNetCode() != 0]
|
||
codes = {p.GetNetCode() for p in with_net}
|
||
print(f"{path.rsplit('/', 1)[-1]:26s} {len(pads):5d} {len(with_net):5d} "
|
||
f"{len(pads) - len(with_net):5d} {len(codes):4d} {_missing(board):6d}")
|
||
print()
|
||
print("焊盘 = 板上所有封装焊盘;有网 = 归属某条网的;无网 = netcode 0(无编号机械焊盘)")
|
||
print("缺连接 = 铜箔还没连上的连接数。0 表示这份板子与网表在连通性上没有冲突。")
|
||
|
||
|
||
def coverage(board_path: str, netlist_path: str) -> None:
|
||
"""How big the netlist provider's blind spot actually is.
|
||
|
||
Measured, not assumed. The first guess was "a netlist never mentions NC pins
|
||
or mechanical pads". Half wrong: KiCad gives every no-connect pin its own
|
||
single-node net, so NC pins *are* covered. What falls through are pads with
|
||
an empty pad number -- mounting holes and shield pads -- 0 to 0.7% of a board.
|
||
"""
|
||
pcbnew = _pcbnew()
|
||
from . import kicad_netlist
|
||
|
||
nl = kicad_netlist.load(netlist_path)
|
||
named = {(r, p) for r, p in nl.nodes()}
|
||
board = pcbnew.LoadBoard(board_path)
|
||
pads = _pads(board)
|
||
pad_keys = {(_ref(p), p.GetNumber()) for p in pads}
|
||
missing = pad_keys - named
|
||
extra = named - pad_keys
|
||
print(f"board {board_path.rsplit('/', 1)[-1]}: {len(pads)} pads, "
|
||
f"{len({_ref(p) for p in pads})} footprints")
|
||
print(f"netlist {netlist_path.rsplit('/', 1)[-1]}: {len(named)} named pads, "
|
||
f"{len(nl.comps)} parts")
|
||
print(f"板上有、网表没提:{len(missing)} "
|
||
f"({len(missing) / max(1, len(pad_keys)):.1%} of pads)")
|
||
print(f"网表提了、板上没有:{len(extra)} (非零 = 网表与板子版本不一致)")
|
||
if missing:
|
||
print(f" 举例:{sorted(missing)[:8]}")
|
||
print()
|
||
print("这就是 netlist provider 的盲区,而且只能由知道封装的一侧算出来。")
|
||
|
||
|
||
def control(board_path: str) -> None:
|
||
"""Positive control: cut one net's copper, require the detector to notice.
|
||
|
||
Every demo board is fully routed, so the disagreement count is zero -- and a
|
||
metric that only ever returns zero has not been tested. This removes the
|
||
tracks of one small net and demands the count go up.
|
||
"""
|
||
pcbnew = _pcbnew()
|
||
board = pcbnew.LoadBoard(board_path)
|
||
board.BuildConnectivity()
|
||
before = _missing(board)
|
||
|
||
per_net = {}
|
||
for track in board.GetTracks():
|
||
if track.GetNetCode():
|
||
per_net.setdefault(track.GetNetCode(), []).append(track)
|
||
if not per_net:
|
||
print("no tracks on this board")
|
||
return
|
||
code = min(per_net, key=lambda c: (len(per_net[c]), c))
|
||
net = board.FindNet(code)
|
||
name = net.GetNetname() if net else str(code)
|
||
cut = len(per_net[code])
|
||
for track in per_net[code]:
|
||
board.Remove(track)
|
||
board.BuildConnectivity()
|
||
after = _missing(board)
|
||
|
||
print(f"control on {board_path.rsplit('/', 1)[-1]}")
|
||
print(f" cut net {name!r}: removed {cut} track(s), "
|
||
f"{len([p for p in _pads(board) if p.GetNetCode() == code])} pads on it")
|
||
print(f" missing before: {before}")
|
||
print(f" missing after : {after}")
|
||
ok = after > before
|
||
print(f" {'PASS' if ok else 'FAIL'} the detector "
|
||
f"{'notices' if ok else 'did NOT notice'} the cut")
|
||
|
||
|
||
def main(argv=None) -> int:
|
||
argv = list(sys.argv[1:] if argv is None else argv)
|
||
if argv and argv[0] == "control":
|
||
if len(argv) < 2:
|
||
print("usage: kicad_board control <a.kicad_pcb>")
|
||
return 2
|
||
control(argv[1])
|
||
elif len(argv) == 2:
|
||
coverage(argv[0], argv[1])
|
||
elif argv:
|
||
report(argv)
|
||
else:
|
||
print("usage: kicad_board <pcb>... | kicad_board <pcb> <net> | "
|
||
"kicad_board control <pcb>")
|
||
return 2
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|