tools/epro2/kicad: Phase-1 EPRO2 → KiCad schematic exporter
写第一版 EPRO2 → .kicad_sch 转换:把 SCH_PAGE Document 的 wires +
COMPONENT placements + TEXT 输出到一个可被 KiCad 7+ 打开的 sch 文件。
不含 symbol 主体(lib_symbols 留空 stub),所以 KiCad 里组件会渲染
成红色 "?" 占位,但布线 + 位置 + Designator/Value 属性都正确。完整
symbol 库导出留 Phase 2。
模块结构:
tools/epro2/kicad/sexpr.py 手写 S-expr emitter,Sym 标记裸符号,
str 自动加引号 + 转义;float 去尾零;
bool→yes/no;NaN/Inf 主动报错
tools/epro2/kicad/_sexpr_reader.py 极简 S-expr parser,仅给 round-trip
测试用(非完整 KiCad reader)
tools/epro2/kicad/sch_writer.py write_sch_page(doc) → str;处理:
LINE → (wire (pts ...) ...)
COMPONENT → (symbol (lib_id facere:<partId>)
(at x y rot) (property Reference ...) ...)
TEXT → (text "..." (at ...))
单位 mil → mm × 0.0254;零长 wire 跳过
tools/epro2/kicad/__main__.py CLI: --doc <uuid> | --all-sch
ESP-VoCat 验证(python -m tools.epro2.kicad <project> --all-sch):
9 SCH_PAGE 全部转换成功
P1_408c9f4f.kicad_sch wires= 6 symbols= 10 text= 0 skipped= 2 (370 lines)
P1_ee409917.kicad_sch wires= 20 symbols= 14 text= 0 skipped= 3
P1_54743d77.kicad_sch wires= 42 symbols= 30 text= 3
Overview_dc13d6d2.kicad_sch wires= 0 symbols= 1 text= 34 (说明页)
MCU_510cff33.kicad_sch wires= 91 symbols= 86 text= 9
Interface_b336a7c7.kicad_sch wires= 99 symbols= 95 text= 6
P1_5c38f45b.kicad_sch wires=179 symbols= 86 text= 9
P1_45092758.kicad_sch wires=187 symbols=138 text= 10 (主图)
codec_0b0163fa.kicad_sch wires=190 symbols=112 text= 10
输出落在 data/processed/kicad_sch/<filename>.kicad_sch(gitignore 内,
可重新生成;不入库)。
测试:6 个 sexpr 测 + 6 个 sch_writer 测,含 round-trip parse 验证。
parser/relations/project_relations 的旧 21 个不动,合计 **33/33 通过**。
下一步:
1. Phase 2 — symbol library 导出 (.kicad_sym),把 SYMBOL doc 的 PIN/RECT/
TEXT primitives 转 KiCad symbol 主体;填 lib_symbols 块让组件渲染
出真正的 schematic 符号
2. footprint library + .kicad_pcb 导出
3. 用 KiCad CLI (kicad-cli sch erc) 跑 ERC 校验
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
186
tools/epro2/kicad/sch_writer.py
Normal file
186
tools/epro2/kicad/sch_writer.py
Normal file
@@ -0,0 +1,186 @@
|
||||
"""Convert one EPRO2 SCH_PAGE Document → a KiCad ``.kicad_sch`` S-expr.
|
||||
|
||||
Phase-1 scope: paper + wires + junctions + symbol placements (no symbol body
|
||||
bundled in lib_symbols). KiCad will render the resulting .kicad_sch with
|
||||
visible wires/junctions but the symbol instances will appear as red question
|
||||
marks until lib_symbols is populated (next phase).
|
||||
|
||||
Coordinate system:
|
||||
- EPRO2 schematic uses **mil** as its internal unit.
|
||||
- KiCad uses **mm**, with origin top-left, +Y down.
|
||||
- Y-axis already aligned (both Y-down), so we just apply ``MIL_TO_MM``.
|
||||
- We additionally translate so that the schematic's own bounding box has
|
||||
a small margin from page origin — keeps everything visible on A4.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import uuid as _uuid
|
||||
from dataclasses import dataclass
|
||||
|
||||
from ..relations import Relations
|
||||
from ..replay import Document
|
||||
from .sexpr import Sym, to_sexpr
|
||||
|
||||
MIL_TO_MM = 0.0254
|
||||
|
||||
# KiCad sch S-expr metadata that doesn't depend on content.
|
||||
KICAD_SCH_VERSION = 20231120
|
||||
KICAD_GENERATOR = "facere-epro2"
|
||||
|
||||
# Default A4 in mm (KiCad uses these by default for "A4").
|
||||
PAPER_A4_MM_W = 297.0
|
||||
PAPER_A4_MM_H = 210.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class WriteStats:
|
||||
wires: int = 0
|
||||
junctions: int = 0
|
||||
symbol_placements: int = 0
|
||||
text: int = 0
|
||||
skipped: int = 0
|
||||
|
||||
|
||||
def _new_uuid() -> str:
|
||||
return str(_uuid.uuid4())
|
||||
|
||||
|
||||
def _mil(v) -> float:
|
||||
"""Coerce an EPRO2 mil value to mm. None / non-numeric → 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.0, kind: str = "default") -> list:
|
||||
return [Sym("stroke"), [Sym("width"), width], [Sym("type"), Sym(kind)]]
|
||||
|
||||
|
||||
def write_sch_page(
|
||||
doc: Document,
|
||||
*,
|
||||
title: str | None = None,
|
||||
sheet_origin_mm: tuple[float, float] = (25.4, 25.4),
|
||||
) -> str:
|
||||
"""Render a single SCH_PAGE Document as kicad_sch text.
|
||||
|
||||
``sheet_origin_mm`` is added to every coordinate so the schematic doesn't
|
||||
sit at (0,0) (KiCad's title block lives there). Default 1 inch margin.
|
||||
"""
|
||||
if doc.doc_type != "SCH_PAGE":
|
||||
raise ValueError(f"expected SCH_PAGE doc, got {doc.doc_type!r}")
|
||||
|
||||
rel = Relations.build(doc)
|
||||
stats = WriteStats()
|
||||
|
||||
ox, oy = sheet_origin_mm
|
||||
elements: list = []
|
||||
|
||||
# 1. Wires from LINE primitives. Each LINE contributes one (wire ...).
|
||||
for oid, obj in doc.objects.items():
|
||||
if obj.get("_type") != "LINE":
|
||||
continue
|
||||
x1 = ox + _mil(obj.get("startX"))
|
||||
y1 = oy + _mil(obj.get("startY"))
|
||||
x2 = ox + _mil(obj.get("endX"))
|
||||
y2 = oy + _mil(obj.get("endY"))
|
||||
# KiCad rejects degenerate zero-length wires
|
||||
if math.isclose(x1, x2) and math.isclose(y1, y2):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
elements.append([
|
||||
Sym("wire"),
|
||||
[Sym("pts"), [Sym("xy"), x1, y1], [Sym("xy"), x2, y2]],
|
||||
_stroke(0.0),
|
||||
[Sym("uuid"), _new_uuid()],
|
||||
])
|
||||
stats.wires += 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.
|
||||
for cid, comp in rel.components.items():
|
||||
x = ox + _mil(comp.get("x"))
|
||||
y = oy + _mil(comp.get("y"))
|
||||
rot = float(comp.get("rotation") or 0)
|
||||
part_id = str(comp.get("partId") or "Unknown")
|
||||
attrs = rel.attrs_dict(cid)
|
||||
designator = str(attrs.get("Designator") or "")
|
||||
value = str(attrs.get("Value") or "")
|
||||
|
||||
sym_block: list = [
|
||||
Sym("symbol"),
|
||||
[Sym("lib_id"), f"facere:{part_id}"],
|
||||
[Sym("at"), x, y, rot],
|
||||
[Sym("unit"), 1],
|
||||
[Sym("exclude_from_sim"), Sym("no")],
|
||||
[Sym("in_bom"), Sym("yes")],
|
||||
[Sym("on_board"), Sym("yes")],
|
||||
[Sym("dnp"), Sym("no")],
|
||||
[Sym("uuid"), _new_uuid()],
|
||||
[Sym("property"), "Reference", designator,
|
||||
[Sym("at"), x, y - 5, 0],
|
||||
[Sym("effects"), [Sym("font"), [Sym("size"), 1.27, 1.27]]]],
|
||||
[Sym("property"), "Value", value,
|
||||
[Sym("at"), x, y + 5, 0],
|
||||
[Sym("effects"), [Sym("font"), [Sym("size"), 1.27, 1.27]]]],
|
||||
[Sym("property"), "Footprint", "",
|
||||
[Sym("at"), x, y, 0],
|
||||
[Sym("effects"), [Sym("font"), [Sym("size"), 1.27, 1.27]],
|
||||
[Sym("hide"), Sym("yes")]]],
|
||||
[Sym("property"), "Datasheet", "",
|
||||
[Sym("at"), x, y, 0],
|
||||
[Sym("effects"), [Sym("font"), [Sym("size"), 1.27, 1.27]],
|
||||
[Sym("hide"), Sym("yes")]]],
|
||||
]
|
||||
elements.append(sym_block)
|
||||
stats.symbol_placements += 1
|
||||
|
||||
# 3. Text labels from TEXT objects (best-effort — only those with a non-empty value).
|
||||
for oid, obj in doc.objects.items():
|
||||
if obj.get("_type") != "TEXT":
|
||||
continue
|
||||
val = str(obj.get("value") or "").strip()
|
||||
if not val:
|
||||
continue
|
||||
x = ox + _mil(obj.get("x"))
|
||||
y = oy + _mil(obj.get("y"))
|
||||
rot = float(obj.get("rotation") or 0)
|
||||
elements.append([
|
||||
Sym("text"),
|
||||
val,
|
||||
[Sym("at"), x, y, rot],
|
||||
[Sym("effects"), [Sym("font"), [Sym("size"), 1.27, 1.27]]],
|
||||
[Sym("uuid"), _new_uuid()],
|
||||
])
|
||||
stats.text += 1
|
||||
|
||||
sch_title = title or (
|
||||
(doc.objects.get("META") or {}).get("title")
|
||||
or doc.doc_uuid[:12]
|
||||
)
|
||||
|
||||
sch: list = [
|
||||
Sym("kicad_sch"),
|
||||
[Sym("version"), KICAD_SCH_VERSION],
|
||||
[Sym("generator"), KICAD_GENERATOR],
|
||||
[Sym("uuid"), _new_uuid()],
|
||||
[Sym("paper"), "A4"],
|
||||
[Sym("title_block"),
|
||||
[Sym("title"), sch_title],
|
||||
[Sym("comment"), 1, f"epro2 doc_uuid: {doc.doc_uuid}"],
|
||||
[Sym("comment"), 2, f"editor: {doc.head.get('editVersion','')}"]],
|
||||
[Sym("lib_symbols")], # empty for Phase 1; Phase 2 will populate
|
||||
*elements,
|
||||
[Sym("sheet_instances"),
|
||||
[Sym("path"), "/", [Sym("page"), "1"]]],
|
||||
]
|
||||
|
||||
# Stash stats on the function for tests / CLI to inspect.
|
||||
write_sch_page.last_stats = stats # type: ignore[attr-defined]
|
||||
return to_sexpr(sch, pretty=True)
|
||||
Reference in New Issue
Block a user