tools/epro2/kicad: Phase-2 lib_symbols — render symbol bodies from SYMBOL docs
Phase 1 emit的 .kicad_sch 里组件位置 + 属性都对,但 lib_symbols 是空
stub —— KiCad 渲染时每个组件显示成红色 "?"。Phase 2 把 SYMBOL 文档
里的 PART + RECT/POLY/CIRCLE/TEXT/PIN primitives 翻成 KiCad lib symbol
块,填到 lib_symbols 里,让 KiCad 显示真正的原理图符号。
新增 tools/epro2/kicad/sym_writer.py:
write_lib_symbol(symbol_doc) → S-expr list 形如:
(symbol "facere:<partId>"
(pin_numbers (hide no))
(pin_names (offset 1.016))
(in_bom yes) (on_board yes)
(property "Reference" "U" ...)
(property "Value" "<title>" ...)
(property "Footprint" "" hide)
(property "Datasheet" "" hide)
(symbol "<partId>_1_1"
(rectangle ...) ← from RECT.dotX1/Y1/dotX2/Y2
(polyline (pts ...)) ← from POLY.points + closed → fill
(circle ...) ← from CIRCLE.center/radius
(text "..." ...) ← from TEXT.value/x/y/rotation
(pin <type> line (at ...) (length ...) (name ...) (number ...))
← from PIN + sibling ATTR ops
))
PIN 名字/编号/电气类型解析(这是关键数据探测点):
EPRO2 PIN 不直接带 number/name/type 字段;这些信息存为独立 ATTR 操作
(parentId=<pin_id>, key="Pin Name"/"Pin Number"/"Pin Type")
Pin Type 取值映射:IN→input, OUT→output, BIDIR→bidirectional,
POWER_IN→power_in, POWER_OUT→power_out, NC→no_connect, ...
默认 passive(保守)
sch_writer 集成(lib_symbols 自动填):
write_sch_page(doc, project_relations=pr) — 增 pr 可选参数
内部 _build_lib_symbols(): 收集本 sheet 用到的 partIds → 通过
ProjectRelations.parts_by_id 解析到 SYMBOL 文档 → write_lib_symbol →
组装 (lib_symbols ...) 块;同 partId 多 SYMBOL 候选取第一个,去重
WriteStats 增 lib_symbols_embedded / lib_symbols_missing
CLI 加 --no-lib-symbols 用于回到 Phase-1 行为(占位符调试用)。
ESP-VoCat 重导出验证:9/9 SCH_PAGE 全部 0 lib_miss
P1_45092758.kicad_sch wires=187 symbols=138 lib_emb=29
codec_0b0163fa.kicad_sch wires=190 symbols=112 lib_emb=20
Interface_b336a7c7.kicad_sch symbols=95 lib_emb=13
...
P1_408c9f4f.kicad_sch wires= 6 symbols= 10 lib_emb= 3
测试:6 个新单测覆盖 outer wrapper / pin ATTR pull / 多形状 primitives /
sch_writer 集成路径 / 缺失 lib 计数 / no-pr 回退到 Phase 1。
合计 **39/39 通过**(parser 6 + relations 9 + project_relations 6 +
sexpr 6 + sch_writer 6 + sym_writer 6)。
下一步 Phase 3:footprint library + .kicad_pcb 导出。
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
179
tools/epro2/kicad/sym_writer.py
Normal file
179
tools/epro2/kicad/sym_writer.py
Normal file
@@ -0,0 +1,179 @@
|
||||
"""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** (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.
|
||||
"""
|
||||
|
||||
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 _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":
|
||||
x1, y1 = _pt(obj.get("dotX1")), _pt(obj.get("dotY1"))
|
||||
x2, y2 = _pt(obj.get("dotX2")), _pt(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")), _pt(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")), _pt(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")), _pt(obj.get("y")),
|
||||
float(obj.get("rotation") or 0)],
|
||||
_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")), _pt(obj.get("y")),
|
||||
float(obj.get("rotation") or 0)],
|
||||
[Sym("length"), _pt(obj.get("length"))],
|
||||
[Sym("name"), pin_name or "~", _font()],
|
||||
[Sym("number"), pin_number or "~", _font()],
|
||||
])
|
||||
|
||||
return [
|
||||
Sym("symbol"), f"{lib_prefix}:{part_id}",
|
||||
[Sym("pin_numbers"), [Sym("hide"), Sym("no")]],
|
||||
[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,
|
||||
]
|
||||
Reference in New Issue
Block a user