Files
FacereDataset/tools/epro2/kicad/sym_writer.py
Knowit 54f0173947 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>
2026-04-28 23:43:11 +08:00

201 lines
7.3 KiB
Python

"""Convert one EPRO2 SYMBOL Document → a KiCad ``(symbol ...)`` lib entry.
Phase-2 scope: render the SYMBOL primitives so KiCad's lib_symbols block can
provide a real graphical body for each placement (vs the Phase-1 red ``?``).
Coverage / fidelity:
- PART → outer (symbol "facere:<partId>" ...) wrapper + properties
- PIN + ATTR → (pin <type> line (at x y rot) (length L) (name ...) (number ...))
with ATTR(parent=pin, key="Pin Name"/"Pin Number"/"Pin Type")
pulled from sibling ATTR ops
- RECT → (rectangle (start ...) (end ...) ...)
- POLY → (polyline (pts (xy ...) ...) ...) with closed→fill
- CIRCLE → (circle (center ...) (radius ...) ...)
- TEXT → (text "..." (at ...) ...)
- ATTR (no parent / on PART) → contributes to symbol-level Reference/Value/...
(best-effort; mostly ignored at body level)
Coordinate convention:
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
from ..relations import Relations
from ..replay import Document
from .sch_writer import MIL_TO_MM
from .sexpr import Sym
# EPRO2 Pin Type -> KiCad electrical type. Empirical mapping; defaults to passive.
PIN_TYPE_MAP: dict[str, str] = {
"IN": "input",
"OUT": "output",
"BIDIR": "bidirectional",
"BIDIRECTIONAL": "bidirectional",
"TRI_STATE": "tri_state",
"TRISTATE": "tri_state",
"PASSIVE": "passive",
"POWER_IN": "power_in",
"POWER_OUT": "power_out",
"OPEN_COLLECTOR": "open_collector",
"OPEN_EMITTER": "open_emitter",
"NC": "no_connect",
"NOT_CONNECTED": "no_connect",
"UNSPECIFIED": "unspecified",
}
def _pt(v) -> float:
"""Coerce a mil number to mm. None → 0.0."""
if v is None:
return 0.0
try:
return float(v) * MIL_TO_MM
except (TypeError, ValueError):
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")]]
def _fill(kind: str = "none") -> list:
return [Sym("fill"), [Sym("type"), Sym(kind)]]
def _font(size: float = 1.27) -> list:
return [Sym("effects"), [Sym("font"), [Sym("size"), size, size]]]
def _hidden_font(size: float = 1.27) -> list:
return [Sym("effects"), [Sym("font"), [Sym("size"), size, size]],
[Sym("hide"), Sym("yes")]]
def _property(name: str, value: str, idx: int, *, hide: bool = False) -> list:
return [
Sym("property"), name, value,
[Sym("at"), 0, 0, 0],
_hidden_font() if hide else _font(),
]
def write_lib_symbol(doc: Document, *, lib_prefix: str = "facere") -> list | None:
"""Render a SYMBOL Document as a KiCad ``(symbol ...)`` block (S-expr list).
Returns ``None`` if the doc has no PART (malformed lib doc). The caller
embeds the returned list into a parent ``(lib_symbols ...)`` container.
"""
if doc.doc_type != "SYMBOL":
return None
rel = Relations.build(doc)
if not rel.parts:
return None
# Pick the first PART (ESP-VoCat probe shows 1 PART per SYMBOL doc).
part_id, part = next(iter(rel.parts.items()))
title = str(part.get("title") or part_id)
# Body primitives: RECT, POLY, CIRCLE, TEXT, PIN.
body: list = [Sym("symbol"), f"{part_id}_1_1"]
for oid, obj in doc.objects.items():
t = obj.get("_type")
# Filter to primitives owned by this part (ignore stray objects)
if obj.get("partId") != part_id:
continue
if t == "RECT":
# 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],
[Sym("end"), x2, y2],
_stroke(),
_fill(),
])
elif t == "POLY":
pts = obj.get("points") or []
xy_list = [Sym("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
body.append([
Sym("polyline"),
xy_list,
_stroke(),
_fill("outline" if obj.get("closed") else "none"),
])
elif t == "CIRCLE":
body.append([
Sym("circle"),
[Sym("center"), _pt(obj.get("centerX")), _y(obj.get("centerY"))],
[Sym("radius"), _pt(obj.get("radius"))],
_stroke(),
_fill(),
])
elif t == "TEXT":
val = str(obj.get("value") or "").strip()
if not val:
continue
body.append([
Sym("text"), val,
[Sym("at"), _pt(obj.get("x")), _y(obj.get("y")),
_lib_rot(obj.get("rotation"))],
_font(),
])
elif t == "PIN":
attrs = rel.attrs_dict(oid)
pin_number = str(attrs.get("Pin Number") or "")
pin_name = str(attrs.get("Pin Name") or "")
pin_type_raw = str(attrs.get("Pin Type") or "").upper()
elec = PIN_TYPE_MAP.get(pin_type_raw, "passive")
body.append([
Sym("pin"), Sym(elec), Sym("line"),
[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()],
])
# KiCad 8 syntax: omit `(pin_numbers ...)` block entirely to mean "visible"
# (using `(pin_numbers (hide no))` is rejected as a parse error). To hide
# we'd emit the bare token `(pin_numbers hide)`.
return [
Sym("symbol"), f"{lib_prefix}:{part_id}",
[Sym("pin_names"), [Sym("offset"), 1.016]],
[Sym("in_bom"), Sym("yes")],
[Sym("on_board"), Sym("yes")],
_property("Reference", "U", 0),
_property("Value", title, 1),
_property("Footprint", "", 2, hide=True),
_property("Datasheet", "", 3, hide=True),
body,
]