diff --git a/cad/gerber/SmTIASv4_LED_panel-Edge_Cuts.gbr b/cad/gerber/SmTIASv4_LED_panel-Edge_Cuts.gbr new file mode 100644 index 0000000..62fee8c --- /dev/null +++ b/cad/gerber/SmTIASv4_LED_panel-Edge_Cuts.gbr @@ -0,0 +1,68 @@ +%TF.GenerationSoftware,SmTIAS-LightSim pcb.gerber*% +%TF.FileFunction,Profile,NP*% +%FSLAX46Y46*% +G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)* +%MOMM*% +%LPD*% +G01* +G04 APERTURE LIST* +%ADD10C,0.050000*% +G04 APERTURE END LIST* +D10* +X0Y10150000D02* +X0Y66450000D01* +X0Y66450000D02* +X3500000Y72450000D01* +X3500000Y72450000D02* +X6500000Y72450000D01* +X6500000Y72450000D02* +X10000000Y66450000D01* +X10000000Y66450000D02* +X10000000Y10150000D01* +X10000000Y10150000D02* +X0Y10150000D01* +X16000000Y10150000D02* +X16000000Y66450000D01* +X16000000Y66450000D02* +X19500000Y72450000D01* +X19500000Y72450000D02* +X22500000Y72450000D01* +X22500000Y72450000D02* +X26000000Y66450000D01* +X26000000Y66450000D02* +X26000000Y10150000D01* +X26000000Y10150000D02* +X16000000Y10150000D01* +X32000000Y0D02* +X32000000Y82600000D01* +X32000000Y82600000D02* +X42000000Y82600000D01* +X42000000Y82600000D02* +X42000000Y0D01* +X42000000Y0D02* +X32000000Y0D01* +X6600000Y20450000D02* +G75* +G03X6600000Y20450000I-1600000J0D01* +G01* +X6600000Y68450000D02* +G75* +G03X6600000Y68450000I-1600000J0D01* +G01* +X22600000Y20450000D02* +G75* +G03X22600000Y20450000I-1600000J0D01* +G01* +X22600000Y68450000D02* +G75* +G03X22600000Y68450000I-1600000J0D01* +G01* +X38600000Y10300000D02* +G75* +G03X38600000Y10300000I-1600000J0D01* +G01* +X38600000Y72300000D02* +G75* +G03X38600000Y72300000I-1600000J0D01* +G01* +M02* diff --git a/cad/gerber/SmTIASv4_LED_panel-F_Cu.gbr b/cad/gerber/SmTIASv4_LED_panel-F_Cu.gbr new file mode 100644 index 0000000..7134b15 --- /dev/null +++ b/cad/gerber/SmTIASv4_LED_panel-F_Cu.gbr @@ -0,0 +1,391 @@ +%TF.GenerationSoftware,SmTIAS-LightSim pcb.gerber*% +%TF.FileFunction,Copper,L1,Top,Signal*% +%FSLAX46Y46*% +G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)* +%MOMM*% +%LPD*% +G01* +G04 APERTURE LIST* +%ADD10R,3.000000X2.000000*% +%ADD11O,3.000000X2.000000*% +%ADD12R,0.900000X1.200000*% +%ADD13R,2.500000X2.200000*% +%ADD14R,1.550000X2.200000*% +%ADD15C,0.600000*% +G04 APERTURE END LIST* +D10* +X7250000Y12350000D03* +D11* +X2750000Y12350000D03* +D10* +X7250000Y15850000D03* +D11* +X2750000Y15850000D03* +D12* +X6650000Y30450000D03* +X3350000Y30450000D03* +X6650000Y26450000D03* +X3350000Y26450000D03* +D13* +X6050000Y34450000D03* +D14* +X3475000Y34450000D03* +D13* +X6050000Y38450000D03* +D14* +X3475000Y38450000D03* +D13* +X6050000Y42450000D03* +D14* +X3475000Y42450000D03* +D12* +X6650000Y50450000D03* +X3350000Y50450000D03* +X6650000Y46450000D03* +X3350000Y46450000D03* +D13* +X6050000Y54450000D03* +D14* +X3475000Y54450000D03* +D13* +X6050000Y58450000D03* +D14* +X3475000Y58450000D03* +D13* +X6050000Y62450000D03* +D14* +X3475000Y62450000D03* +D10* +X23250000Y12350000D03* +D11* +X18750000Y12350000D03* +D10* +X23250000Y15850000D03* +D11* +X18750000Y15850000D03* +D12* +X22650000Y30450000D03* +X19350000Y30450000D03* +X22650000Y26450000D03* +X19350000Y26450000D03* +D13* +X22050000Y34450000D03* +D14* +X19475000Y34450000D03* +D13* +X22050000Y38450000D03* +D14* +X19475000Y38450000D03* +D13* +X22050000Y42450000D03* +D14* +X19475000Y42450000D03* +D12* +X22650000Y50450000D03* +X19350000Y50450000D03* +X22650000Y46450000D03* +X19350000Y46450000D03* +D13* +X22050000Y54450000D03* +D14* +X19475000Y54450000D03* +D13* +X22050000Y58450000D03* +D14* +X19475000Y58450000D03* +D13* +X22050000Y62450000D03* +D14* +X19475000Y62450000D03* +D10* +X39250000Y2200000D03* +D11* +X34750000Y2200000D03* +D10* +X39250000Y5700000D03* +D11* +X34750000Y5700000D03* +D10* +X39250000Y80400000D03* +D11* +X34750000Y80400000D03* +D10* +X39250000Y76900000D03* +D11* +X34750000Y76900000D03* +D12* +X38650000Y28300000D03* +X35350000Y28300000D03* +X38650000Y32300000D03* +X35350000Y32300000D03* +D13* +X38050000Y24300000D03* +D14* +X35475000Y24300000D03* +D13* +X38050000Y20300000D03* +D14* +X35475000Y20300000D03* +D13* +X38050000Y16300000D03* +D14* +X35475000Y16300000D03* +D12* +X38650000Y54300000D03* +X35350000Y54300000D03* +X38650000Y50300000D03* +X35350000Y50300000D03* +D13* +X38050000Y58300000D03* +D14* +X35475000Y58300000D03* +D13* +X38050000Y62300000D03* +D14* +X35475000Y62300000D03* +D13* +X38050000Y66300000D03* +D14* +X35475000Y66300000D03* +D15* +X3350000Y30450000D02* +X1750000Y30450000D01* +X3350000Y26450000D02* +X1750000Y26450000D01* +X3350000Y50450000D02* +X1750000Y50450000D01* +X3350000Y46450000D02* +X1750000Y46450000D01* +X1750000Y12350000D02* +X1750000Y50450000D01* +X6050000Y42450000D02* +X8250000Y42450000D01* +X6050000Y62450000D02* +X8250000Y62450000D01* +X8250000Y12350000D02* +X8250000Y62450000D01* +X6650000Y26450000D02* +X6650000Y30450000D01* +X6650000Y30450000D02* +X6650000Y31500000D01* +X6650000Y31500000D02* +X5900000Y32250000D01* +X5900000Y32250000D02* +X4300000Y32250000D01* +X4300000Y32250000D02* +X3475000Y33075000D01* +X3475000Y33075000D02* +X3475000Y34450000D01* +X6050000Y34450000D02* +X6050000Y35700000D01* +X6050000Y35700000D02* +X5400000Y36350000D01* +X5400000Y36350000D02* +X3900000Y36350000D01* +X3900000Y36350000D02* +X3475000Y36775000D01* +X3475000Y36775000D02* +X3475000Y38450000D01* +X6050000Y38450000D02* +X6050000Y39700000D01* +X6050000Y39700000D02* +X5400000Y40350000D01* +X5400000Y40350000D02* +X3900000Y40350000D01* +X3900000Y40350000D02* +X3475000Y40775000D01* +X3475000Y40775000D02* +X3475000Y42450000D01* +X6650000Y46450000D02* +X6650000Y50450000D01* +X6650000Y50450000D02* +X6650000Y51500000D01* +X6650000Y51500000D02* +X5900000Y52250000D01* +X5900000Y52250000D02* +X4300000Y52250000D01* +X4300000Y52250000D02* +X3475000Y53075000D01* +X3475000Y53075000D02* +X3475000Y54450000D01* +X6050000Y54450000D02* +X6050000Y55700000D01* +X6050000Y55700000D02* +X5400000Y56350000D01* +X5400000Y56350000D02* +X3900000Y56350000D01* +X3900000Y56350000D02* +X3475000Y56775000D01* +X3475000Y56775000D02* +X3475000Y58450000D01* +X6050000Y58450000D02* +X6050000Y59700000D01* +X6050000Y59700000D02* +X5400000Y60350000D01* +X5400000Y60350000D02* +X3900000Y60350000D01* +X3900000Y60350000D02* +X3475000Y60775000D01* +X3475000Y60775000D02* +X3475000Y62450000D01* +X19350000Y30450000D02* +X17750000Y30450000D01* +X19350000Y26450000D02* +X17750000Y26450000D01* +X19350000Y50450000D02* +X17750000Y50450000D01* +X19350000Y46450000D02* +X17750000Y46450000D01* +X17750000Y12350000D02* +X17750000Y50450000D01* +X22050000Y42450000D02* +X24250000Y42450000D01* +X22050000Y62450000D02* +X24250000Y62450000D01* +X24250000Y12350000D02* +X24250000Y62450000D01* +X22650000Y26450000D02* +X22650000Y30450000D01* +X22650000Y30450000D02* +X22650000Y31500000D01* +X22650000Y31500000D02* +X21900000Y32250000D01* +X21900000Y32250000D02* +X20300000Y32250000D01* +X20300000Y32250000D02* +X19475000Y33075000D01* +X19475000Y33075000D02* +X19475000Y34450000D01* +X22050000Y34450000D02* +X22050000Y35700000D01* +X22050000Y35700000D02* +X21400000Y36350000D01* +X21400000Y36350000D02* +X19900000Y36350000D01* +X19900000Y36350000D02* +X19475000Y36775000D01* +X19475000Y36775000D02* +X19475000Y38450000D01* +X22050000Y38450000D02* +X22050000Y39700000D01* +X22050000Y39700000D02* +X21400000Y40350000D01* +X21400000Y40350000D02* +X19900000Y40350000D01* +X19900000Y40350000D02* +X19475000Y40775000D01* +X19475000Y40775000D02* +X19475000Y42450000D01* +X22650000Y46450000D02* +X22650000Y50450000D01* +X22650000Y50450000D02* +X22650000Y51500000D01* +X22650000Y51500000D02* +X21900000Y52250000D01* +X21900000Y52250000D02* +X20300000Y52250000D01* +X20300000Y52250000D02* +X19475000Y53075000D01* +X19475000Y53075000D02* +X19475000Y54450000D01* +X22050000Y54450000D02* +X22050000Y55700000D01* +X22050000Y55700000D02* +X21400000Y56350000D01* +X21400000Y56350000D02* +X19900000Y56350000D01* +X19900000Y56350000D02* +X19475000Y56775000D01* +X19475000Y56775000D02* +X19475000Y58450000D01* +X22050000Y58450000D02* +X22050000Y59700000D01* +X22050000Y59700000D02* +X21400000Y60350000D01* +X21400000Y60350000D02* +X19900000Y60350000D01* +X19900000Y60350000D02* +X19475000Y60775000D01* +X19475000Y60775000D02* +X19475000Y62450000D01* +X35350000Y28300000D02* +X33750000Y28300000D01* +X35350000Y32300000D02* +X33750000Y32300000D01* +X35350000Y54300000D02* +X33750000Y54300000D01* +X35350000Y50300000D02* +X33750000Y50300000D01* +X33750000Y2200000D02* +X33750000Y80400000D01* +X38050000Y16300000D02* +X40250000Y16300000D01* +X38050000Y66300000D02* +X40250000Y66300000D01* +X40250000Y2200000D02* +X40250000Y80400000D01* +X38650000Y32300000D02* +X38650000Y28300000D01* +X38650000Y28300000D02* +X38650000Y27250000D01* +X38650000Y27250000D02* +X37900000Y26500000D01* +X37900000Y26500000D02* +X36300000Y26500000D01* +X36300000Y26500000D02* +X35475000Y25675000D01* +X35475000Y25675000D02* +X35475000Y24300000D01* +X38050000Y24300000D02* +X38050000Y23050000D01* +X38050000Y23050000D02* +X37400000Y22400000D01* +X37400000Y22400000D02* +X35900000Y22400000D01* +X35900000Y22400000D02* +X35475000Y21975000D01* +X35475000Y21975000D02* +X35475000Y20300000D01* +X38050000Y20300000D02* +X38050000Y19050000D01* +X38050000Y19050000D02* +X37400000Y18400000D01* +X37400000Y18400000D02* +X35900000Y18400000D01* +X35900000Y18400000D02* +X35475000Y17975000D01* +X35475000Y17975000D02* +X35475000Y16300000D01* +X38650000Y50300000D02* +X38650000Y54300000D01* +X38650000Y54300000D02* +X38650000Y55350000D01* +X38650000Y55350000D02* +X37900000Y56100000D01* +X37900000Y56100000D02* +X36300000Y56100000D01* +X36300000Y56100000D02* +X35475000Y56925000D01* +X35475000Y56925000D02* +X35475000Y58300000D01* +X38050000Y58300000D02* +X38050000Y59550000D01* +X38050000Y59550000D02* +X37400000Y60200000D01* +X37400000Y60200000D02* +X35900000Y60200000D01* +X35900000Y60200000D02* +X35475000Y60625000D01* +X35475000Y60625000D02* +X35475000Y62300000D01* +X38050000Y62300000D02* +X38050000Y63550000D01* +X38050000Y63550000D02* +X37400000Y64200000D01* +X37400000Y64200000D02* +X35900000Y64200000D01* +X35900000Y64200000D02* +X35475000Y64625000D01* +X35475000Y64625000D02* +X35475000Y66300000D01* +M02* diff --git a/cad/gerber/SmTIASv4_LED_panel_preview.png b/cad/gerber/SmTIASv4_LED_panel_preview.png new file mode 100644 index 0000000..d703c3e --- /dev/null +++ b/cad/gerber/SmTIASv4_LED_panel_preview.png Binary files differ diff --git a/scripts/export_led_board_gerbers.py b/scripts/export_led_board_gerbers.py new file mode 100644 index 0000000..a5f831b --- /dev/null +++ b/scripts/export_led_board_gerbers.py @@ -0,0 +1,155 @@ +"""LED 基板を 1 枚の材料に並べ,研究室の MITS 基板加工機用のガーバー・ドリルを書き出す. + +Fusion Electronics から EAGLE 形式で書き出した .brd(`scripts/fusion/export_eagle_boards.py`)を +読み,基板を長い向きを縦(基準ピンの向き)にして横に並べ,1 組のデータにする(Design Pro の面付けは +同じ基板の繰り返しだけなので). +形式は研究室で使っている KiCad の書き出しに合わせる(SPEC_05「MITS 基板加工機での作り方」): + +- `-F_Cu.gbr`: 銅(部品の面.SMD だけなので表) +- `-Edge_Cuts.gbr`: 外形と,外形のカッターで切り抜く M3 の穴(3.2 mm.ドリルは 3.0 mm まで) +- `.drl`: ドリル(ドリルで開ける穴があるときだけ) +- `_preview.png`: 確かめ用の図 + +実行方法: + # Fusion で scripts/fusion/export_eagle_boards.py を実行してから + uv run python scripts/export_led_board_gerbers.py + uv run python scripts/export_led_board_gerbers.py --brd-dir cad/eagle # 台本が作った .brd から +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.patches import Circle, FancyBboxPatch, Rectangle # noqa: E402 + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from sm_tias_lightsim.pcb.eagle import Board, load_brd # noqa: E402 +from sm_tias_lightsim.pcb.gerber import ( # noqa: E402 + copper_gerber, + drill_excellon, + edge_gerber, + min_copper_gap, + panelize, +) + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_LAYOUT = "SmTIASv4_LED_side_v2:2,SmTIASv4_LED_bottom_v2:1" +# Design Pro の決まり(共有サーバの「P1 位置の決定手順」): 1 枚の加工範囲は外形 + 1 mm, +# 加工範囲どうしの間は 5 mm,P1〜P2 の範囲はさらに + 4 mm.外形どうしの間は 1 + 5 = 6 mm +GAP = 6.0 +WORK_MARGIN = 1.0 +P1P2_MARGIN = 4.0 +# 材料(サンハヤトのカット基板.基準ピン B〜C の間 90 mm を縦).加工範囲は (横, 縦 90) に収める. +# 研究室で使う材料は s10(75 × 100.2026-11-05 ユーザー) +MATERIAL = {"s10": (75.0, 90.0), "s11": (100.0, 90.0), "s12": (150.0, 90.0)} +GROOVE = 0.3 # 銅を削る溝の幅(90 度のミリングカッタ) + + +def parse_layout(spec: str) -> list[tuple[str, int]]: + out = [] + for item in spec.split(","): + name, _, count = item.partition(":") + if not name or not count.isdigit() or int(count) < 1: + raise ValueError(f"並べ方の書き方は「名前:枚数,…」: {item!r}") + out.append((name, int(count))) + return out + + +def save_preview(panel: Board, path: Path, title: str) -> None: + fig, ax = plt.subplots(figsize=(9, 5)) + for x1, y1, x2, y2 in panel.outline: + ax.plot([x1, x2], [y1, y2], color="tab:cyan", lw=1) + for h in panel.holes: + ax.add_patch(Circle((h.x, h.y), h.diameter / 2, fill=False, + color="tab:cyan" if h.routed else "tab:blue")) + for t in panel.tracks: + ax.plot([t.x1, t.x2], [t.y1, t.y2], color="tab:orange", lw=t.width * 3, + solid_capstyle="round") + for p in panel.pads: + if p.shape == "circle": + ax.add_patch(Circle((p.x, p.y), p.width / 2, color="tab:orange")) + elif p.shape == "obround": + r = min(p.width, p.height) / 2 + ax.add_patch(FancyBboxPatch((p.x - p.width / 2 + r, p.y - p.height / 2 + r), + p.width - 2 * r, p.height - 2 * r, + boxstyle=f"round,pad={r}", color="tab:orange")) + else: + ax.add_patch(Rectangle((p.x - p.width / 2, p.y - p.height / 2), p.width, p.height, + color="tab:orange")) + ax.set_aspect("equal") + ax.set_xlabel("X [mm]") + ax.set_ylabel("Y [mm]") + ax.set_title(title) + ax.grid(True, lw=0.3) + fig.tight_layout() + fig.savefig(path, dpi=150) + plt.close(fig) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--brd-dir", type=Path, default=ROOT / "output" / "pcb" / "fusion_brd", + help="EAGLE 形式の .brd のフォルダ(既定: Fusion から書き出した所)") + parser.add_argument("--layout", default=DEFAULT_LAYOUT, help="並べる基板と枚数(名前:枚数,…)") + parser.add_argument("--material", choices=sorted(MATERIAL), default="s10", + help="材料(サンハヤトのカット基板)") + parser.add_argument("--horizontal", action="store_true", + help="基板の長い向きを横にして縦に並べる(既定は長い向きを縦にして横に並べる)") + parser.add_argument("--out", type=Path, default=ROOT / "cad" / "gerber") + parser.add_argument("--name", default="SmTIASv4_LED_panel") + args = parser.parse_args(argv) + + boards = [] + for name, count in parse_layout(args.layout): + path = args.brd_dir / f"{name}.brd" + if not path.exists(): + raise ValueError(f"{path} が無い(Fusion で scripts/fusion/export_eagle_boards.py を" + "実行して書き出す)") + board = load_brd(path) + boards += [board if args.horizontal else board.rotated90()] * count + # 基準ピンは材料の横の中央の線上にあるので,長さの中央をそろえて短い基板をピンから遠ざける + panel, placements = panelize(boards, GAP, direction="y" if args.horizontal else "x", + center=True) + xmin, ymin, xmax, ymax = panel.bounds() + p1p2 = (xmax - xmin + WORK_MARGIN + P1P2_MARGIN, ymax - ymin + WORK_MARGIN + P1P2_MARGIN) + limit = MATERIAL[args.material] + for p in placements: + print(f"[place] {p.name}: 左下 ({p.x:.1f}, {p.y:.1f}) mm・" + f"{p.width:.1f} × {p.height:.1f} mm") + print(f"[panel] 外形 {xmax - xmin:.1f} × {ymax - ymin:.1f} mm・P1〜P2 の範囲 " + f"{p1p2[0]:.1f} × {p1p2[1]:.1f} mm({args.material} の加工できる範囲 " + f"{limit[0]:.0f} × {limit[1]:.0f} mm)") + if p1p2[0] > limit[0] or p1p2[1] > limit[1]: + raise ValueError(f"{args.material} に収まらない.--material か並べ方を変える") + gap = min_copper_gap(panel) + print(f"[check] パッドどうしの一番狭い間 {gap:.2f} mm(削る溝の幅 {GROOVE} mm)") + if gap <= GROOVE + 1e-9: + print("[warn] 溝の幅以下のパッドの間がある.Design Pro のクリアランスチェックで確かめる" + "(電源パッドのはんだパッドの部品の間 0.3 mm.SPEC_05)") + + args.out.mkdir(parents=True, exist_ok=True) + files = {f"{args.name}-F_Cu.gbr": copper_gerber(panel), + f"{args.name}-Edge_Cuts.gbr": edge_gerber(panel)} + drill = drill_excellon(panel) + if drill is not None: + files[f"{args.name}.drl"] = drill + for fname, text in files.items(): + (args.out / fname).write_text(text, encoding="ascii", newline="\n") + print(f"[saved] {args.out / fname}") + if drill is None: + print("[info] ドリルで開ける穴は無い(M3 の穴は外形のデータで切り抜く)..drl は作らない") + preview = args.out / f"{args.name}_preview.png" + save_preview(panel, preview, f"{args.name} ({len(boards)} boards)") + print(f"[saved] {preview}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/fusion/export_eagle_boards.py b/scripts/fusion/export_eagle_boards.py new file mode 100644 index 0000000..741900d --- /dev/null +++ b/scripts/fusion/export_eagle_boards.py @@ -0,0 +1,52 @@ +"""Fusion Electronics に保存した LED 基板を EAGLE 形式(.brd)で書き出す. + +Fusion の中で実行するスクリプト(MCP の fusion_mcp_execute で,このファイルを `exec` で読み込んで +`run` を呼ぶ.TECH_12).基板の正本は Fusion なので,切削用のガーバーはここで書き出した .brd +から `scripts/export_led_board_gerbers.py` で作る(Fusion の CAM の書き出しは Python の API から +呼べない). + +- SmTIAS プロジェクトの一番上にある BOARDS の基板(.fbrd)を開き(開いていればそれを使う), + `Board.exportManager.createEagleBrdExportOptions` で OUT に書き出す +- .fbrd は見える状態でしか開けない(`documents.open(…, False)` は InternalValidationError). + 開くと電子デザイン・回路図・基板の 3 つのドキュメントが開く(変更はしないので閉じなくてよい) +""" + +import os + +import adsk.core +import adsk.electron + +REPO = "C:/Users/rinto/source/SmTIAS-LightSim" +OUT = f"{REPO}/output/pcb/fusion_brd" +BOARDS = ["SmTIASv4_LED_side_v2", "SmTIASv4_LED_bottom_v2"] +PROJECT = "SmTIAS" + + +def _board_doc(app, name): + for d in app.documents: + if d.name == name and d.products.item(0).objectType.endswith("::Board"): + return d + return None + + +def run(_context: str): + app = adsk.core.Application.get() + keep = app.activeDocument + os.makedirs(OUT, exist_ok=True) + project = [p for p in app.data.dataProjects if p.name == PROJECT][0] + files = {(f.name, f.fileExtension): f for f in project.rootFolder.dataFiles} + for name in BOARDS: + if _board_doc(app, name) is None: + if (name, "fbrd") not in files: + raise RuntimeError(f"{name}.fbrd が {PROJECT} に無い") + app.documents.open(files[(name, "fbrd")], True) + doc = _board_doc(app, name) + if doc is None: + raise RuntimeError(f"{name} の基板のドキュメントが開けない") + board = adsk.electron.Board.cast(doc.products.item(0)) + em = board.exportManager + path = f"{OUT}/{name}.brd" + if not em.execute(em.createEagleBrdExportOptions(path)): + raise RuntimeError(f"{name} を書き出せない") + print("exported", path) + keep.activate() diff --git a/src/sm_tias_lightsim/pcb/__init__.py b/src/sm_tias_lightsim/pcb/__init__.py new file mode 100644 index 0000000..2d31dbf --- /dev/null +++ b/src/sm_tias_lightsim/pcb/__init__.py @@ -0,0 +1 @@ +"""LED 基板の製造データ(EAGLE 形式の基板 → 切削用のガーバー・ドリル).""" diff --git a/src/sm_tias_lightsim/pcb/eagle.py b/src/sm_tias_lightsim/pcb/eagle.py new file mode 100644 index 0000000..56a0bf3 --- /dev/null +++ b/src/sm_tias_lightsim/pcb/eagle.py @@ -0,0 +1,225 @@ +"""EAGLE 形式の基板(.brd)を読み,切削に要る形(銅・外形・穴)を取り出す. + +Fusion Electronics から書き出した .brd(と `scripts/generate_led_module_boards.py` が作る .brd)を +読む.研究室の MITS 基板加工機は片面・めっき無しなので,扱うのは次だけにする(それ以外があれば +ValueError で止める): + +- 銅(層 1 = Top): 部品の SMD パッドと配線(直線) +- 外形(層 20 = Dimension): 直線で描いた閉じた形 +- 穴: 銅の輪の無いパッド(`pad` で直径 ≦ 穴の径)と `hole` は,外形のカッターで切り抜く円として扱う + (ドリルは最大 3.0 mm なので,M3 の 3.2 mm の穴はドリルで開けられない.SPEC_05). + 銅の輪のあるスルーホールのパッドは銅とドリルの穴にする + +座標は mm(EAGLE の座標そのまま). +""" + +from __future__ import annotations + +import math +import re +import xml.etree.ElementTree as ET +from dataclasses import dataclass, field +from pathlib import Path + +COPPER_TOP = "1" +COPPER_BOTTOM = "16" +DIMENSION = "20" + + +@dataclass(frozen=True) +class Pad: + """銅のパッド 1 つ(向きは 90° の倍数だけ.回した後の幅と高さで持つ).""" + + x: float + y: float + width: float + height: float + shape: str # "rect" / "obround"(両端が半円)/ "circle" + + +@dataclass(frozen=True) +class Track: + """銅の配線 1 本(直線).""" + + x1: float + y1: float + x2: float + y2: float + width: float + + +@dataclass(frozen=True) +class Hole: + """穴 1 つ.routed なら外形のカッターで切り抜く円,そうでなければドリル.""" + + x: float + y: float + diameter: float + routed: bool + + +@dataclass +class Board: + """切削に要る形の集まり(座標は mm).""" + + name: str + pads: list[Pad] = field(default_factory=list) + tracks: list[Track] = field(default_factory=list) + outline: list[tuple[float, float, float, float]] = field(default_factory=list) # 線分 + holes: list[Hole] = field(default_factory=list) + + def bounds(self) -> tuple[float, float, float, float]: + """外形の範囲 (xmin, ymin, xmax, ymax).""" + if not self.outline: + raise ValueError(f"{self.name}: 外形(層 20)が無い") + xs = [v for s in self.outline for v in (s[0], s[2])] + ys = [v for s in self.outline for v in (s[1], s[3])] + return min(xs), min(ys), max(xs), max(ys) + + def rotated90(self) -> Board: + """原点のまわりに 90° 回した写し((x, y) → (−y, x).長い向きを Y にそろえるため).""" + return Board( + self.name, + [Pad(-p.y, p.x, p.height, p.width, p.shape) for p in self.pads], + [Track(-t.y1, t.x1, -t.y2, t.x2, t.width) for t in self.tracks], + [(-b, a, -d, c) for a, b, c, d in self.outline], + [Hole(-h.y, h.x, h.diameter, h.routed) for h in self.holes], + ) + + def translated(self, dx: float, dy: float, name: str | None = None) -> Board: + """平行移動した写しを返す.""" + return Board( + name or self.name, + [Pad(p.x + dx, p.y + dy, p.width, p.height, p.shape) for p in self.pads], + [Track(t.x1 + dx, t.y1 + dy, t.x2 + dx, t.y2 + dy, t.width) for t in self.tracks], + [(a + dx, b + dy, c + dx, d + dy) for a, b, c, d in self.outline], + [Hole(h.x + dx, h.y + dy, h.diameter, h.routed) for h in self.holes], + ) + + +def parse_rotation(rot: str | None) -> float: + """EAGLE の回転("R90"・"SR180" など)を度で返す.鏡映(M)は裏面の部品なので扱わない.""" + if not rot: + return 0.0 + m = re.fullmatch(r"S?(M?)R(-?\d+(?:\.\d+)?)", rot) + if m is None: + raise ValueError(f"回転の書き方が分からない: {rot!r}") + if m.group(1): + raise ValueError(f"裏面(鏡映)の部品は扱わない(片面の基板): {rot!r}") + return float(m.group(2)) % 360.0 + + +def _quarter_turns(angle: float, what: str) -> int: + q = angle / 90.0 + if abs(q - round(q)) > 1e-6: + raise ValueError(f"{what}: 90° の倍数でない向き {angle}° は扱わない") + return int(round(q)) % 4 + + +def _rotate(x: float, y: float, angle: float) -> tuple[float, float]: + c, s = math.cos(math.radians(angle)), math.sin(math.radians(angle)) + return x * c - y * s, x * s + y * c + + +def _f(el: ET.Element, key: str, default: float | None = None) -> float: + v = el.get(key) + if v is None: + if default is None: + raise ValueError(f"<{el.tag}> に {key} が無い") + return default + return float(v) + + +def _wire(el: ET.Element, where: str) -> tuple[float, float, float, float, float]: + if abs(_f(el, "curve", 0.0)) > 1e-9: + raise ValueError(f"{where}: 曲線の線は扱わない") + return _f(el, "x1"), _f(el, "y1"), _f(el, "x2"), _f(el, "y2"), _f(el, "width") + + +def _packages(root: ET.Element) -> dict[tuple[str, str], ET.Element]: + out = {} + for lib in root.iter("library"): + for pkg in lib.iter("package"): + out[(lib.get("name", ""), pkg.get("name", ""))] = pkg + return out + + +def parse_brd(text: str, name: str = "board") -> Board: + """EAGLE の .brd の文字列から切削に要る形を取り出す. + + Args: + text: .brd ファイルの中身(XML). + name: 基板の名前(メッセージ用). + + Returns: + 銅のパッド・配線,外形,穴をまとめた Board. + + Raises: + ValueError: 片面の切削で扱えないもの(裏面の銅・ビア・ポリゴン・曲線・斜めの部品)が + あるとき. + """ + root = ET.fromstring(text) + board = Board(name) + plain = root.find(".//board/plain") + if plain is not None: + for el in plain: + layer = el.get("layer") + if el.tag == "wire" and layer == DIMENSION: + board.outline.append(_wire(el, f"{name} の外形")[:4]) + elif el.tag == "wire" and layer == COPPER_TOP: + board.tracks.append(Track(*_wire(el, f"{name} の銅"))) + elif el.tag == "circle" and layer == DIMENSION: + r = _f(el, "radius") + board.holes.append(Hole(_f(el, "x"), _f(el, "y"), 2 * r, routed=True)) + elif el.tag == "hole": + board.holes.append(Hole(_f(el, "x"), _f(el, "y"), _f(el, "drill"), routed=True)) + elif layer in (COPPER_TOP, COPPER_BOTTOM, DIMENSION): + raise ValueError(f"{name}: 層 {layer} の <{el.tag}> は扱わない") + + packages = _packages(root) + for el in root.iter("element"): + key = (el.get("library", ""), el.get("package", "")) + if key not in packages: + raise ValueError(f"{name}: 部品 {el.get('name')} の形 {key} がライブラリに無い") + ex, ey = _f(el, "x"), _f(el, "y") + erot = parse_rotation(el.get("rot")) + for p in packages[key]: + if p.tag == "smd": + if p.get("layer") != COPPER_TOP: + raise ValueError(f"{name}: 部品 {el.get('name')} に裏面のパッドがある") + angle = (erot + parse_rotation(p.get("rot"))) % 360.0 + q = _quarter_turns(angle, f"{name} の部品 {el.get('name')}") + dx, dy = _f(p, "dx"), _f(p, "dy") + w, h = (dx, dy) if q % 2 == 0 else (dy, dx) + px, py = _rotate(_f(p, "x"), _f(p, "y"), erot) + # roundness 100 は角の丸い形(両端が半円).それ未満は矩形として扱う(銅が少し + # 広くなるだけで,配線の間隔には影響しない) + shape = "obround" if _f(p, "roundness", 0.0) >= 100.0 else "rect" + board.pads.append(Pad(ex + px, ey + py, w, h, shape)) + elif p.tag in ("pad", "hole"): + px, py = _rotate(_f(p, "x"), _f(p, "y"), erot) + drill = _f(p, "drill") + diameter = _f(p, "diameter", 0.0) + if p.tag == "hole" or diameter <= drill + 1e-9: + board.holes.append(Hole(ex + px, ey + py, drill, routed=True)) + else: + board.pads.append(Pad(ex + px, ey + py, diameter, diameter, "circle")) + board.holes.append(Hole(ex + px, ey + py, drill, routed=False)) + elif p.tag in ("polygon",) and p.get("layer") in (COPPER_TOP, COPPER_BOTTOM): + raise ValueError(f"{name}: 部品 {el.get('name')} の銅のポリゴンは扱わない") + + for sig in root.iter("signal"): + for el in sig: + if el.tag == "wire" and el.get("layer") == COPPER_TOP: + board.tracks.append(Track(*_wire(el, f"{name} の配線 {sig.get('name')}"))) + elif el.tag == "wire" and el.get("layer") == COPPER_BOTTOM: + raise ValueError(f"{name}: 裏面の配線がある(片面の基板)") + elif el.tag in ("via", "polygon"): + raise ValueError(f"{name}: <{el.tag}> は扱わない(片面・ベタ無し)") + board.bounds() + return board + + +def load_brd(path: Path) -> Board: + """.brd ファイルを読む(名前はファイル名).""" + return parse_brd(path.read_text(encoding="utf-8"), path.stem) diff --git a/src/sm_tias_lightsim/pcb/gerber.py b/src/sm_tias_lightsim/pcb/gerber.py new file mode 100644 index 0000000..4271339 --- /dev/null +++ b/src/sm_tias_lightsim/pcb/gerber.py @@ -0,0 +1,195 @@ +"""基板を並べ(面付け),MITS の Design Pro が読むガーバー・ドリルの文字列を作る. + +形式は研究室で使っている KiCad の書き出しに合わせる(SPEC_05「MITS 基板加工機での作り方」): + +- ガーバー: RS-274X・mm・整数 4 桁 + 小数 6 桁(`%FSLAX46Y46*%`)・絶対座標 +- 銅(`*-F_Cu.gbr`): パッドは矩形・角の丸い形(O)・円のアパーチャの露光,配線は円のアパーチャの線 +- 外形(`*-Edge_Cuts.gbr`): 線幅 0.05 mm の線と,穴の円(`G75` + `G03` の全周) +- ドリル(`*.drl`): Excellon・mm・絶対座標.ドリルで開ける穴が無いときは作らない + +Design Pro のソフトの面付けは同じ基板の繰り返しだけなので,違う基板を 1 回で削るために +ここで 1 組のデータに並べる. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from sm_tias_lightsim.pcb.eagle import Board, Hole, Pad, Track + +EDGE_WIDTH = 0.05 +GENERATOR = "SmTIAS-LightSim pcb.gerber" + + +@dataclass(frozen=True) +class Placement: + """並べた基板 1 枚の位置(外形の左下が (x, y)).""" + + name: str + x: float + y: float + width: float + height: float + + +def panelize(boards: list[Board], gap: float, origin: tuple[float, float] = (0.0, 0.0), + direction: str = "y", center: bool = False) -> tuple[Board, list[Placement]]: + """基板を gap の間隔で 1 列に並べて 1 枚にまとめる. + + Args: + boards: 並べる基板(同じ基板を何枚も作るなら同じものを並べて渡す). + gap: 隣り合う外形の間の距離 [mm]. + origin: 1 枚目の外形の左下の位置 [mm]. + direction: "y" なら縦(+Y)に並べて左をそろえる,"x" なら横(+X)に並べて下をそろえる. + center: True なら端をそろえず,並べる向きと直交する向きで中央をそろえる(短い基板を + 材料の基準ピンから遠ざけるため). + + Returns: + まとめた基板と,各基板の位置. + """ + if gap <= 0: + raise ValueError(f"基板の間隔は正にする: {gap}") + if direction not in ("x", "y"): + raise ValueError(f"並べる向きは x か y: {direction!r}") + panel = Board("panel") + placements = [] + x, y = origin + sizes = [(b.bounds()[2] - b.bounds()[0], b.bounds()[3] - b.bounds()[1]) for b in boards] + span = max(w for w, _ in sizes) if direction == "y" else max(h for _, h in sizes) + for b in boards: + xmin, ymin, xmax, ymax = b.bounds() + if direction == "y": + x = origin[0] + ((span - (xmax - xmin)) / 2 if center else 0.0) + else: + y = origin[1] + ((span - (ymax - ymin)) / 2 if center else 0.0) + moved = b.translated(x - xmin, y - ymin) + panel.pads += moved.pads + panel.tracks += moved.tracks + panel.outline += moved.outline + panel.holes += moved.holes + placements.append(Placement(b.name, x, y, xmax - xmin, ymax - ymin)) + if direction == "y": + y += (ymax - ymin) + gap + else: + x += (xmax - xmin) + gap + return panel, placements + + +def _c(v: float) -> str: + """mm を 4.6 形式の整数に(0 を省く形式.負の値は符号付き).""" + return str(int(round(v * 1_000_000))) + + +def _xy(x: float, y: float) -> str: + return f"X{_c(x)}Y{_c(y)}" + + +def _header(function: str) -> list[str]: + return [ + f"%TF.GenerationSoftware,{GENERATOR}*%", + f"%TF.FileFunction,{function}*%", + "%FSLAX46Y46*%", + "G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)*", + "%MOMM*%", + "%LPD*%", + "G01*", + ] + + +def _fmt(v: float) -> str: + return f"{v:.6f}" + + +def copper_gerber(board: Board) -> str: + """銅(表)のガーバー.""" + apertures: dict[tuple, int] = {} + + def aperture(key: tuple) -> int: + if key not in apertures: + apertures[key] = 10 + len(apertures) + return apertures[key] + + body = [] + current = None + for p in board.pads: + kind = {"circle": "C", "rect": "R", "obround": "O"}[p.shape] + key = ("C", round(p.width, 6)) if kind == "C" else ( + kind, round(p.width, 6), round(p.height, 6)) + d = aperture(key) + if d != current: + body.append(f"D{d}*") + current = d + body.append(f"{_xy(p.x, p.y)}D03*") + for t in board.tracks: + d = aperture(("C", round(t.width, 6))) + if d != current: + body.append(f"D{d}*") + current = d + body.append(f"{_xy(t.x1, t.y1)}D02*") + body.append(f"{_xy(t.x2, t.y2)}D01*") + lines = _header("Copper,L1,Top,Signal") + lines.append("G04 APERTURE LIST*") + for key, d in apertures.items(): + if key[0] == "C": + lines.append(f"%ADD{d}C,{_fmt(key[1])}*%") + else: + lines.append(f"%ADD{d}{key[0]},{_fmt(key[1])}X{_fmt(key[2])}*%") + lines.append("G04 APERTURE END LIST*") + return "\n".join(lines + body + ["M02*", ""]) + + +def edge_gerber(board: Board) -> str: + """外形のガーバー(外形の線と,外形のカッターで切り抜く穴の円).""" + lines = _header("Profile,NP") + lines += ["G04 APERTURE LIST*", f"%ADD10C,{_fmt(EDGE_WIDTH)}*%", "G04 APERTURE END LIST*", + "D10*"] + for x1, y1, x2, y2 in board.outline: + lines += [f"{_xy(x1, y1)}D02*", f"{_xy(x2, y2)}D01*"] + for h in board.holes: + if not h.routed: + continue + r = h.diameter / 2 + lines += [f"{_xy(h.x + r, h.y)}D02*", "G75*", + f"G03{_xy(h.x + r, h.y)}I{_c(-r)}J0D01*", "G01*"] + return "\n".join(lines + ["M02*", ""]) + + +def drill_excellon(board: Board) -> str | None: + """ドリルの Excellon.ドリルで開ける穴が無ければ None.""" + drilled = [h for h in board.holes if not h.routed] + if not drilled: + return None + sizes = sorted({round(h.diameter, 3) for h in drilled}) + lines = ["M48", f";DRILL file {{{GENERATOR}}}", + ";FORMAT={3:3/ absolute / metric / suppress leading zeros}", "FMAT,2", "METRIC,TZ"] + lines += [f"T{i + 1}C{s:.3f}" for i, s in enumerate(sizes)] + lines += ["%", "G90", "G05", "M71"] + for i, s in enumerate(sizes): + lines.append(f"T{i + 1}") + for h in drilled: + if round(h.diameter, 3) == s: + lines.append(f"X{int(round(h.x * 1000))}Y{int(round(h.y * 1000))}") + lines += ["T0", "M30", ""] + return "\n".join(lines) + + +def min_copper_gap(board: Board) -> float: + """違う銅どうしの一番近い間隔の目安 [mm](パッドの矩形どうしの距離.配線は数えない). + + 削る溝の幅(0.3 mm)より狭い所が無いかを書き出しの前に確かめるための粗い検査. + 正しい検査は Design Pro のクリアランスチェックで行う. + """ + best = float("inf") + pads = board.pads + for i, a in enumerate(pads): + for b in pads[i + 1:]: + gx = abs(a.x - b.x) - (a.width + b.width) / 2 + gy = abs(a.y - b.y) - (a.height + b.height) / 2 + if gx < 0 and gy < 0: + continue # 重なる(同じ銅の続き) + best = min(best, (max(gx, 0.0) ** 2 + max(gy, 0.0) ** 2) ** 0.5) + return best + + +__all__ = ["Board", "Hole", "Pad", "Placement", "Track", "copper_gerber", "drill_excellon", + "edge_gerber", "min_copper_gap", "panelize"] diff --git a/tests/pcb/__init__.py b/tests/pcb/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/tests/pcb/__init__.py diff --git a/tests/pcb/test_eagle.py b/tests/pcb/test_eagle.py new file mode 100644 index 0000000..cf0b0c3 --- /dev/null +++ b/tests/pcb/test_eagle.py @@ -0,0 +1,146 @@ +"""pcb.eagle(EAGLE の .brd から切削に要る形を取り出す)のテスト. + +仕様出典: src/sm_tias_lightsim/pcb/eagle.py の docstring と SPEC_05「MITS 基板加工機での作り方」 +- 銅は層 1 の SMD パッドと配線,外形は層 20 の線 +- 銅の輪の無いパッド(直径 ≦ 穴の径)は外形のカッターで切り抜く円(routed) +- 部品の向きは 90° の倍数だけ.回すとパッドの幅と高さが入れ替わる +- 裏面の部品・ビア・曲線は ValueError +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from sm_tias_lightsim.pcb.eagle import load_brd, parse_brd, parse_rotation + +ROOT = Path(__file__).resolve().parents[2] + + +def _brd(elements: str = "", plain: str = "", signals: str = "") -> str: + outline = ( + '' + '' + '' + '' + ) + return f""" + +{outline}{plain} + + + + + + + + + + +{elements} +{signals} +""" + + +def test_parse_rotation_accepts_spin_and_rejects_mirror(): + assert parse_rotation(None) == 0.0 + assert parse_rotation("R90") == 90.0 + assert parse_rotation("SR270") == 270.0 + assert parse_rotation("R-90") == 270.0 + with pytest.raises(ValueError, match="裏面"): + parse_rotation("MR90") + + +def test_smd_pads_are_rotated_with_the_element(): + b = parse_brd(_brd('')) + pads = sorted((round(p.x, 6), round(p.y, 6), p.width, p.height) for p in b.pads) + # R90 で (−1, 0) → (0, −1),(1, 0) → (0, 1).幅 1 × 高さ 2 は 2 × 1 になる + assert pads == [(10.0, 4.0, 2.0, 1.0), (10.0, 6.0, 2.0, 1.0)] + + +def test_pad_without_copper_ring_becomes_routed_hole(): + b = parse_brd(_brd('')) + assert b.pads == [] + assert [(h.x, h.y, h.diameter, h.routed) for h in b.holes] == [(5.0, 5.0, 3.2, True)] + + +def test_through_hole_pad_gives_copper_and_drill(): + b = parse_brd(_brd('')) + assert [(p.width, p.shape) for p in b.pads] == [(1.6, "circle")] + assert [(h.diameter, h.routed) for h in b.holes] == [(0.8, False)] + + +def test_outline_and_signal_tracks_are_read(): + sig = ('' + '') + b = parse_brd(_brd(signals=sig)) + assert b.bounds() == (0.0, 0.0, 20.0, 10.0) + assert [(t.x1, t.x2, t.width) for t in b.tracks] == [(1.0, 9.0, 0.6)] + + +@pytest.mark.parametrize("kind, kwargs", [ + ("back pad", {"elements": ''}), + ("via", {"signals": ''}), + ("bottom track", {"signals": '' + ''}), + ("curve", {"signals": '' + ''}), + ("skewed part", {"elements": ''}), + ("missing package", {"elements": ''}), +]) +def test_unsupported_features_raise(kind, kwargs): + with pytest.raises(ValueError): + parse_brd(_brd(**kwargs)) + + +def test_board_without_outline_raises(): + text = _brd().replace('layer="20"', 'layer="51"') + with pytest.raises(ValueError, match="外形"): + parse_brd(text) + + +@pytest.mark.parametrize("name, n_pads, n_holes, size", [ + ("SmTIASv4_LED_side_v2", 24, 2, (62.3, 10.0)), + ("SmTIASv4_LED_bottom_v2", 28, 2, (82.6, 10.0)), +]) +def test_smtias_v4_boards(name, n_pads, n_holes, size): + """台本が作った SmTIASv4 の基板: LED 6(2 パッド)・IC 4(2)・電源パッド(2 パッド × 2 列). + + 下用は研究室の材料 s10 の基準ピンの間 90 mm に余白 5 mm 込みで収まる長さ(≦ 85 mm). + """ + b = load_brd(ROOT / "cad" / "eagle" / f"{name}.brd") + assert len(b.pads) == n_pads + assert all(h.routed and h.diameter == pytest.approx(3.2) for h in b.holes) + assert len(b.holes) == n_holes + xmin, ymin, xmax, ymax = b.bounds() + assert (xmax - xmin, ymax - ymin) == pytest.approx(size) + assert xmax - xmin + 5.0 <= 90.0 + + +def test_wire_pads_are_large_and_separated(): + """ケーブルをはんだ付けする電源パッド: 2.0 × 3.0 mm,+12V(角の丸い形)と GND の間 1.5 mm.""" + b = load_brd(ROOT / "cad" / "eagle" / "SmTIASv4_LED_side_v2.brd") + wire = [p for p in b.pads if {round(p.width, 3), round(p.height, 3)} == {2.0, 3.0}] + assert len(wire) == 4 + assert sum(p.shape == "obround" for p in wire) == 2 + for gnd in (p for p in wire if p.shape == "rect"): + v12 = min((p for p in wire if p.shape == "obround"), key=lambda p: abs(p.x - gnd.x)) + assert abs(gnd.y - v12.y) - (gnd.height + v12.height) / 2 == pytest.approx(1.5) + + +def test_roundness_100_gives_obround_pad(): + text = _brd('').replace( + '', + '') + shapes = sorted(p.shape for p in parse_brd(text).pads) + assert shapes == ["obround", "rect"] + + +def test_rotated90_maps_coordinates_and_swaps_pad_size(): + b = parse_brd(_brd('')) + r = b.rotated90() + assert r.bounds() == pytest.approx((-10, 0, 0, 20)) + assert sorted((p.x, p.y, p.width, p.height) for p in r.pads) == [ + (-5.0, 9.0, 2.0, 1.0), (-5.0, 11.0, 2.0, 1.0)] diff --git a/tests/pcb/test_gerber.py b/tests/pcb/test_gerber.py new file mode 100644 index 0000000..2902dac --- /dev/null +++ b/tests/pcb/test_gerber.py @@ -0,0 +1,110 @@ +"""pcb.gerber(面付けとガーバー・ドリルの書き出し)のテスト. + +仕様出典: src/sm_tias_lightsim/pcb/gerber.py の docstring と SPEC_05「MITS 基板加工機での作り方」 +- RS-274X・mm・4.6 形式(研究室の KiCad の書き出しと同じ) +- 外形のカッターで切り抜く穴は外形のガーバーに全周の円(G75 + G03)で入れ,ドリルには入れない +- 基板は左をそろえて縦に gap の間隔で並べる +""" + +from __future__ import annotations + +import re + +import pytest + +from sm_tias_lightsim.pcb.eagle import Board, Hole, Pad, Track +from sm_tias_lightsim.pcb.gerber import ( + copper_gerber, + drill_excellon, + edge_gerber, + min_copper_gap, + panelize, +) + + +def _rect_board(name: str, x0: float, y0: float, w: float, h: float) -> Board: + pts = [(x0, y0), (x0 + w, y0), (x0 + w, y0 + h), (x0, y0 + h)] + outline = [(*pts[i], *pts[(i + 1) % 4]) for i in range(4)] + return Board(name, outline=outline) + + +def test_panelize_stacks_boards_left_aligned_with_gap(): + a = _rect_board("a", 100, 50, 60, 10) + a.pads.append(Pad(101, 51, 1, 1, "rect")) + b = _rect_board("b", -5, 7, 90, 10) + panel, places = panelize([a, a, b], gap=6.0) + assert [(p.name, p.x, p.y) for p in places] == [("a", 0, 0), ("a", 0, 16), ("b", 0, 32)] + assert panel.bounds() == pytest.approx((0, 0, 90, 42)) + assert [(p.x, p.y) for p in panel.pads] == [(1, 1), (1, 17)] + + +def test_panelize_side_by_side_aligns_bottoms(): + a = _rect_board("a", 5, 5, 10, 60) + b = _rect_board("b", -3, 2, 10, 80) + panel, places = panelize([a, a, b], gap=6.0, direction="x") + assert [(p.x, p.y) for p in places] == [(0, 0), (16, 0), (32, 0)] + assert panel.bounds() == pytest.approx((0, 0, 42, 80)) + with pytest.raises(ValueError): + panelize([a], gap=6.0, direction="z") + + +def test_panelize_center_aligns_middles(): + a = _rect_board("a", 0, 0, 10, 60) + b = _rect_board("b", 0, 0, 10, 80) + _, places = panelize([a, b], gap=6.0, direction="x", center=True) + assert [(p.x, p.y) for p in places] == [(0, 10), (16, 0)] + _, places = panelize([_rect_board("c", 0, 0, 60, 10), _rect_board("d", 0, 0, 80, 10)], + gap=6.0, direction="y", center=True) + assert [(p.x, p.y) for p in places] == [(10, 0), (0, 16)] + + +def test_panelize_rejects_non_positive_gap(): + with pytest.raises(ValueError): + panelize([_rect_board("a", 0, 0, 1, 1)], gap=0.0) + + +def test_copper_gerber_format_and_apertures(): + b = _rect_board("a", 0, 0, 10, 10) + b.pads += [Pad(1.5, 2.25, 1.0, 1.5, "rect"), Pad(3, 3, 1.6, 1.6, "circle")] + b.tracks.append(Track(0, -1.2, 5, -1.2, 0.6)) + text = copper_gerber(b) + assert "%FSLAX46Y46*%" in text and "%MOMM*%" in text and text.rstrip().endswith("M02*") + assert "%ADD10R,1.000000X1.500000*%" in text + assert "%ADD11C,1.600000*%" in text + assert "%ADD12C,0.600000*%" in text + assert "X1500000Y2250000D03*" in text + assert "X0Y-1200000D02*" in text and "X5000000Y-1200000D01*" in text + + +def test_obround_pad_uses_o_aperture(): + b = _rect_board("a", 0, 0, 10, 10) + b.pads.append(Pad(2, 2, 3.0, 2.0, "obround")) + assert "%ADD10O,3.000000X2.000000*%" in copper_gerber(b) + + +def test_edge_gerber_has_outline_and_routed_hole_circles(): + b = _rect_board("a", 0, 0, 10, 5) + b.holes += [Hole(3, 2, 3.2, routed=True), Hole(7, 2, 0.8, routed=False)] + text = edge_gerber(b) + assert len(re.findall(r"D01\*", text)) == 4 + 1 # 外形 4 本 + 穴 1 つ + assert "X4600000Y2000000D02*" in text # 円の始点(中心 + 半径) + assert "G03X4600000Y2000000I-1600000J0D01*" in text + + +def test_drill_only_for_drilled_holes(): + b = _rect_board("a", 0, 0, 10, 5) + b.holes.append(Hole(3, 2, 3.2, routed=True)) + assert drill_excellon(b) is None + b.holes.append(Hole(7.5, 2.25, 0.8, routed=False)) + text = drill_excellon(b) + assert text is not None + assert "METRIC,TZ" in text and "T1C0.800" in text and "X7500Y2250" in text + assert "X3000Y2000" not in text + + +def test_min_copper_gap_measures_rectangle_separation(): + b = _rect_board("a", 0, 0, 10, 5) + b.pads += [Pad(0, 0, 1.0, 1.5, "rect"), Pad(1.3, 0, 1.0, 1.5, "rect")] + assert min_copper_gap(b) == pytest.approx(0.3) + b.pads.append(Pad(5, 5, 1, 1, "rect")) + assert min_copper_gap(b) == pytest.approx(0.3)