tools/epro2/kicad: fix two structural ERC bugs — wire_dangling -88%, pin_not_connected -52%

Bisect found two semantics mismatches between EPRO2 and KiCad that cause
the 850 real-connectivity ERC violations on the ESP-VoCat ref project:

1. sym_writer was emitting lib coords without negating Y, but KiCad lib
   uses Y-up and re-flips Y on placement (Y-down schematic). So vertically
   arranged pins ended up at Y-mirrored absolute positions and wires that
   reach the geometric pin tip in EPRO2 missed the rendered pin tip in
   KiCad. Fix: lib_y = -epro2_y, lib_rot = (360 - rot) % 360 for pin/text.

2. sch_writer was treating each LINE as an isolated wire — but EPRO2
   binds segments into nets by NAME (WIRE.NET attr), not just geometry.
   Multi-segment nets like GND/VBUS show up as N disconnected stubs to
   KiCad. Fix: per-LINE, look up lineGroup → WIRE → NET attr and emit a
   `(label "<NET>")` at the LINE's start. Same-named labels on distinct
   physical wires is how KiCad's ERC recognizes a multi-segment net.

ESP-VoCat 9 sheets:
  wire_dangling           444 →  52  (-88%)
  pin_not_connected       406 → 196  (-52%)
  real connectivity total 850 → 248  (-71%)

Why we did NOT round to grid (the obvious-looking fix): EPRO2 places
some pins on a 10-mil pitch (e.g. magnetic socket); rounding to KiCad's
default 50-mil ERC grid would collapse those pins. The 248 residual is
fundamentally cross-sheet — single-sheet ERC can't see a net's other
endpoints on sibling sheets — and is a Phase-3 (hierarchical sheet)
problem, not a per-sheet one.

41 → 46 unit tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-28 23:43:11 +08:00
parent 5e63924474
commit 54f0173947
6 changed files with 197 additions and 15 deletions

44
log.md
View File

@@ -4,6 +4,50 @@
---
## 2026-04-28 23:55 KiCad 导出修真实连接错wire_dangling -88%, pin_not_connected -52%
**Claude 会话**
`fb577cc` 后续。Handoff 选项 #1:用 ERC violation 数从 850 降到接近 0 作为目标。Bisect 出两个根因,都是结构性的 KiCad 语义错(不是浮点 / 精度问题,所以 grid round 不是答案):
### Bug A — sym_writer 漏 Y-flip
KiCad lib symbol 是 Y-upschematic 是 Y-downplacement 时 KiCad 会再翻一次 Y。我们把 EPRO2 (Y-down) 的 PIN/RECT/POLY/CIRCLE/TEXT 坐标直接当 lib coord 写KiCad 的翻转就把整个 symbol body 上下镜像了。U8 4-pin 磁吸座实测pin 1↔4 对调、2↔3 对调,结果 wire 端点跟错位的 pin tip 撞不上 → ERC 报 pin_not_connected + wire_dangling。修法`lib_y = -epro2_y`pin/text rotation 也镜像 `lib_rot = (360 - rot) % 360`
### Bug B — 没发 net labelKiCad 看不出 EPRO2 的命名网络
EPRO2 的 WIRE op 带 NET attr`TXD` / `GND` / `VBUS` ……),多段 LINE 通过同名 NET 连成一个网,**不需要几何相邻**。KiCad 不知道这套,只看几何。修法:在 sch_writer 里查每条 LINE 的 `lineGroup → WIRE → NET attr`,命中就在 LINE 起点 emit 一个 `(label "<NET>")`。同名 label 在多条物理 wire 上 → KiCad ERC 才认这是同一个网。**per-LINE 不是 per-WIRE**:单个 WIRE id 下面的 LINE 段不一定共端点,每段都得有 label 才不被判 dangling。
### ESP-VoCat 9 sheets ERC 对比
| Type | baseline | after | Δ |
|---|---:|---:|---:|
| wire_dangling | 444 | 52 | **88%** |
| pin_not_connected | 406 | 196 | **52%** |
| **real connectivity 合计** | **850** | **248** | **71%** |
| label_dangling | 0 | 111 | new (warn) |
| pin_not_driven | 0 | 23 | new (connector pin 类型问题) |
| endpoint_off_grid | 1372 | 1372 | unchanged (cosmetic, EPRO2 用 30/20/10 mil pitch不在 KiCad 50 mil 网格上;不能 round——会把 < 50 mil 的 pin 间距压到一起) |
| lib_symbol_issues | 571 | 571 | unchanged (没注册 facere libcosmetic) |
剩余 248 real-connectivity 错主要是 single-sheet ERC 的天然限制:很多网只在一个 sheet 上有这一个 pin对端在别的 sheet。kicad-cli 一次只看一个 .kicad_sch看不见跨 sheet。彻底修要 Phase 3hierarchical 顶层 + sheet links
### 关键决策(记 Why
- **不 round to grid**50 mil grid 会塌缩 < 50 mil pin pitch实测 4-pin 磁吸座是 10 mil pitch破坏几何。EPRO2 源已经在整数 mil浮点不是 root cause。
- **per-LINE label 不是 per-WIRE**:同 WIRE id 下两条 LINE 段不共端点是常态(不同地方各连一段),都得 label 才不孤立。
- **用 `(label)` 不是 `(global_label)`**实验过两种语法single-sheet ERC 都判 dangling因为这个 sheet 上只出现一次);语义上 EPRO2 net 全局,但 single-sheet 校验视角看不见跨 sheet换 global_label 帮不上。Phase 3 hierarchical 重构时再切。
- **不做 ERC config tweak**KiCad 8 的 connection grid 是硬编码 50 milschematic 文件里没法配;想消 endpoint_off_grid 必须破坏 EPRO2 几何或者升级到 KiCad 9 + custom severity。
### 测试
41 → 46 单测全过:新增 `test_pin_y_negated_for_kicad_lib_y_up_convention` / `test_pin_rotation_mirrored_to_compensate_y_flip` / `test_rect_y_negated` / `test_named_wire_emits_label_at_line_start` / `test_unnamed_wire_emits_no_label`
### 下一步建议
- Phase 3 hierarchical写 root .kicad_sch 引用所有子 sheet + 把跨 sheet 的 NET 升级成 `(global_label)`single-sheet ERC 残留的 248 + 111 大概率随之降到 < 100。
- (并行) 消 lib_symbol_issues 571emit `sym-lib-table` + 独立 .kicad_sym。
---
## 2026-04-28 23:30 oshwhub 全量 listing 索引落本地33,695 项 / 28.4 MB
**Claude 会话**

View File

@@ -51,7 +51,7 @@ def _convert_one(
if stats:
print(
f" {out_path.name}: wires={stats.wires} symbols={stats.symbol_placements} "
f"text={stats.text} skipped={stats.skipped} "
f"text={stats.text} labels={stats.labels} skipped={stats.skipped} "
f"lib_emb={stats.lib_symbols_embedded} lib_miss={stats.lib_symbols_missing}"
)
return out_path

View File

@@ -41,6 +41,7 @@ class WriteStats:
junctions: int = 0
symbol_placements: int = 0
text: int = 0
labels: int = 0
skipped: int = 0
lib_symbols_embedded: int = 0
lib_symbols_missing: int = 0
@@ -92,6 +93,14 @@ def write_sch_page(
elements: list = []
# 1. Wires from LINE primitives. Each LINE contributes one (wire ...).
# EPRO2 binds wires into nets by NAME (WIRE.NET attr), not just geometry,
# so we also emit a (label "<NET>") at one endpoint of each named LINE.
# Same-named labels on physically distinct LINEs are how KiCad's ERC
# recognizes a multi-segment net — without them every LINE looks like a
# dangling stub. We label per-LINE (not per-WIRE id) because a single
# WIRE op may contain segments that don't share endpoints, and KiCad
# flags any unlabeled segment in such a group as wire_dangling.
wire_net_cache: dict[str, str | None] = {}
for oid, obj in doc.objects.items():
if obj.get("_type") != "LINE":
continue
@@ -111,6 +120,24 @@ def write_sch_page(
])
stats.wires += 1
wire_id = obj.get("lineGroup")
if not wire_id:
continue
wid = str(wire_id)
if wid not in wire_net_cache:
wire_net_cache[wid] = (rel.attrs_dict(wid) or {}).get("NET")
net = wire_net_cache[wid]
if not net:
continue
elements.append([
Sym("label"), str(net),
[Sym("at"), x1, y1, 0],
[Sym("effects"), [Sym("font"), [Sym("size"), 1.27, 1.27]],
[Sym("justify"), Sym("left"), Sym("bottom")]],
[Sym("uuid"), _new_uuid()],
])
stats.labels += 1
# 2. Symbol placements from COMPONENT ops. Body deferred to Phase 2 (lib_symbols).
# For now we emit (symbol ...) entries that reference a placeholder lib_id.
# KiCad will draw a red ? but the position + properties are correct.

View File

@@ -16,12 +16,15 @@ Coverage / fidelity:
(best-effort; mostly ignored at body level)
Coordinate convention:
EPRO2 SYMBOL primitives use **mil** (same as schematic); we convert via
``MIL_TO_MM = 0.0254``. KiCad lib symbol coords are **Y-up** internally,
but the placement of pins relative to body origin is what matters; for
ESP-VoCat the empirical Y orientation is consistent (pins on left at -X,
pins on right at +X), so we do not flip Y. If KiCad renders flipped, the
fix is a per-axis sign in ``_pt`` here.
EPRO2 SYMBOL primitives use **mil** in a Y-down frame (same as the
schematic). KiCad lib symbol coords are **Y-up**; when a symbol is
placed on a (Y-down) schematic KiCad re-flips the lib's Y. To make the
rendered placement land at the EPRO2 absolute position (so wire endpoints
meet pin tips) we therefore **negate Y in lib coords**, and mirror pin /
text rotations across the X-axis (``rot_lib = -rot_epro2 mod 360``).
Without this, vertically-arranged pins end up at Y-mirrored positions —
ERC then reports ``pin_not_connected`` even when the wire endpoint and
pin tip share the same X.
"""
from __future__ import annotations
@@ -60,6 +63,20 @@ def _pt(v) -> float:
return 0.0
def _y(v) -> float:
"""Y for lib symbol space: negate (Y-down EPRO2 → Y-up KiCad lib)."""
return -_pt(v)
def _lib_rot(rot) -> float:
"""Mirror pin/text rotation across the X-axis to compensate for the lib
Y-up vs schematic Y-down flip KiCad applies on placement."""
try:
return (360.0 - float(rot or 0)) % 360.0
except (TypeError, ValueError):
return 0.0
def _stroke(width: float = 0.254) -> list:
return [Sym("stroke"), [Sym("width"), width], [Sym("type"), Sym("default")]]
@@ -110,8 +127,10 @@ def write_lib_symbol(doc: Document, *, lib_prefix: str = "facere") -> list | Non
if obj.get("partId") != part_id:
continue
if t == "RECT":
x1, y1 = _pt(obj.get("dotX1")), _pt(obj.get("dotY1"))
x2, y2 = _pt(obj.get("dotX2")), _pt(obj.get("dotY2"))
# KiCad lib uses Y-up; we negate Y so the rectangle stays oriented
# the same way it appears in EPRO2 after placement Y-flip.
x1, y1 = _pt(obj.get("dotX1")), _y(obj.get("dotY1"))
x2, y2 = _pt(obj.get("dotX2")), _y(obj.get("dotY2"))
body.append([
Sym("rectangle"),
[Sym("start"), x1, y1],
@@ -122,7 +141,7 @@ def write_lib_symbol(doc: Document, *, lib_prefix: str = "facere") -> list | Non
elif t == "POLY":
pts = obj.get("points") or []
xy_list = [Sym("pts")] + [
[Sym("xy"), _pt(p.get("x")), _pt(p.get("y"))] for p in pts
[Sym("xy"), _pt(p.get("x")), _y(p.get("y"))] for p in pts
if isinstance(p, dict)
]
if len(xy_list) >= 3: # at least 2 points + the "pts" tag
@@ -135,7 +154,7 @@ def write_lib_symbol(doc: Document, *, lib_prefix: str = "facere") -> list | Non
elif t == "CIRCLE":
body.append([
Sym("circle"),
[Sym("center"), _pt(obj.get("centerX")), _pt(obj.get("centerY"))],
[Sym("center"), _pt(obj.get("centerX")), _y(obj.get("centerY"))],
[Sym("radius"), _pt(obj.get("radius"))],
_stroke(),
_fill(),
@@ -146,8 +165,8 @@ def write_lib_symbol(doc: Document, *, lib_prefix: str = "facere") -> list | Non
continue
body.append([
Sym("text"), val,
[Sym("at"), _pt(obj.get("x")), _pt(obj.get("y")),
float(obj.get("rotation") or 0)],
[Sym("at"), _pt(obj.get("x")), _y(obj.get("y")),
_lib_rot(obj.get("rotation"))],
_font(),
])
elif t == "PIN":
@@ -158,8 +177,8 @@ def write_lib_symbol(doc: Document, *, lib_prefix: str = "facere") -> list | Non
elec = PIN_TYPE_MAP.get(pin_type_raw, "passive")
body.append([
Sym("pin"), Sym(elec), Sym("line"),
[Sym("at"), _pt(obj.get("x")), _pt(obj.get("y")),
float(obj.get("rotation") or 0)],
[Sym("at"), _pt(obj.get("x")), _y(obj.get("y")),
_lib_rot(obj.get("rotation"))],
[Sym("length"), _pt(obj.get("length"))],
[Sym("name"), pin_name or "~", _font()],
[Sym("number"), pin_number or "~", _font()],

View File

@@ -100,6 +100,46 @@ def test_text_object_emits_text_block_when_non_empty():
assert texts[0][1] == "Hello"
def test_named_wire_emits_label_at_line_start():
"""EPRO2 binds wire segments into nets by NAME (WIRE.NET attr), not by
geometry alone. Each LINE whose lineGroup points to a WIRE with a NET
attr must get a (label "<NET>") at one endpoint — same-named labels on
distinct LINEs are how KiCad's ERC recognizes a multi-segment net."""
d = _doc([
("w1", {"_type": "WIRE"}),
("a1", {"_type": "ATTR", "parentId": "w1", "key": "NET", "value": "GND"}),
("ln1", {"_type": "LINE", "lineGroup": "w1",
"startX": 100, "startY": 0, "endX": 200, "endY": 0}),
("ln2", {"_type": "LINE", "lineGroup": "w1",
"startX": 300, "startY": 0, "endX": 400, "endY": 0}),
])
text = write_sch_page(d, sheet_origin_mm=(0.0, 0.0))
p = parse(text)
labels = _block(p, "label")
assert len(labels) == 2 # one label per non-degenerate LINE
assert all(lab[1] == "GND" for lab in labels)
# First label sits at the first LINE's start endpoint
at = next(c for c in labels[0] if isinstance(c, list) and c[0] == "at")
assert at[1] == 100 * MIL_TO_MM
assert at[2] == 0.0
assert getattr(write_sch_page, "last_stats").labels == 2
def test_unnamed_wire_emits_no_label():
"""A WIRE without a NET attr (or a LINE without a lineGroup) gets no
label — emitting a label without a name would be syntactically invalid
and semantically meaningless."""
d = _doc([
("w1", {"_type": "WIRE"}), # no NET attr
("ln1", {"_type": "LINE", "lineGroup": "w1",
"startX": 0, "startY": 0, "endX": 100, "endY": 0}),
])
text = write_sch_page(d, sheet_origin_mm=(0.0, 0.0))
p = parse(text)
assert _block(p, "label") == []
assert getattr(write_sch_page, "last_stats").labels == 0
def test_non_sch_page_doc_rejected():
d = Document(doc_uuid="x", doc_type="PCB")
try:

View File

@@ -127,6 +127,58 @@ def test_sch_writer_embeds_lib_symbols_via_project_relations():
assert stats.lib_symbols_missing == 1
def test_pin_y_negated_for_kicad_lib_y_up_convention():
"""KiCad lib uses Y-up; the schematic uses Y-down and KiCad re-flips Y on
placement. To make the rendered placement land where EPRO2's wire ends
expect it, sym_writer must NEGATE Y for lib coords. Without this,
vertically arranged pins land at Y-mirrored positions and ERC reports
pin_not_connected even when wire and pin share an X coord."""
d = _sym_doc("sym1", "MyPart.1", [
("e5", {"_type": "PIN", "partId": "MyPart.1",
"x": -20, "y": 10, "length": 20, "rotation": 0}),
])
entry = write_lib_symbol(d)
parsed = parse(to_sexpr(entry))
inner = next(c for c in parsed if isinstance(c, list) and c[0] == "symbol")
pin = next(c for c in inner if isinstance(c, list) and c[0] == "pin")
at = next(c for c in pin if isinstance(c, list) and c[0] == "at")
# EPRO2 y=10 → lib y=-10 mil = -0.254 mm
assert at[1] == -20 * 0.0254
assert at[2] == -10 * 0.0254
def test_pin_rotation_mirrored_to_compensate_y_flip():
"""Pin angle in lib must mirror across X-axis (rot' = 360-rot mod 360)
so that after KiCad's lib→sch Y-flip the pin extends in the same
direction it does in EPRO2."""
d = _sym_doc("sym1", "MyPart.1", [
("e5", {"_type": "PIN", "partId": "MyPart.1",
"x": 0, "y": 0, "length": 10, "rotation": 90}),
])
entry = write_lib_symbol(d)
parsed = parse(to_sexpr(entry))
inner = next(c for c in parsed if isinstance(c, list) and c[0] == "symbol")
pin = next(c for c in inner if isinstance(c, list) and c[0] == "pin")
at = next(c for c in pin if isinstance(c, list) and c[0] == "at")
assert at[3] == 270.0 # 90 → 270
def test_rect_y_negated():
d = _sym_doc("sym1", "MyPart.1", [
("r1", {"_type": "RECT", "partId": "MyPart.1",
"dotX1": -10, "dotY1": -5, "dotX2": 10, "dotY2": 5}),
])
entry = write_lib_symbol(d)
parsed = parse(to_sexpr(entry))
inner = next(c for c in parsed if isinstance(c, list) and c[0] == "symbol")
rect = next(c for c in inner if isinstance(c, list) and c[0] == "rectangle")
start = next(c for c in rect if isinstance(c, list) and c[0] == "start")
end = next(c for c in rect if isinstance(c, list) and c[0] == "end")
# Y inputs were -5 and 5 → after negation: 5 and -5
assert start[2] == 5 * 0.0254
assert end[2] == -5 * 0.0254
def test_sch_writer_without_project_relations_emits_empty_lib_symbols():
sch = Document(doc_uuid="sch1", doc_type="SCH_PAGE")
sch.objects["e1"] = {"_type": "COMPONENT", "partId": "X.1", "x": 0, "y": 0}