Newer
Older
SmTIAS-LightSim / scripts / draw_led_board_solder_map.py
"""LED 基板のどこにはんだを付けるかの図(部品の面から見た図)を描く.

EAGLE の .brd(Fusion から書き出したもの)を読み,銅(パッド・線)・部品の形(部品の外形の線.
LED は角の欠け,定電流 IC はダイオードの記号)・はんだを付けるパッド(赤丸)・部品の向き(カソード
の側)・ケーブルを付けるパッドを描く.

実行方法:
    uv run python scripts/draw_led_board_solder_map.py
"""

from __future__ import annotations

import argparse
import sys
import xml.etree.ElementTree as ET
from pathlib import Path

import matplotlib
from matplotlib.patches import Circle, FancyBboxPatch

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

from sm_tias_lightsim.pcb.eagle import _f, _packages, _rotate, parse_rotation  # noqa: E402

plt.rcParams["font.family"] = ["Yu Gothic", "MS Gothic", "DejaVu Sans"]
ROOT = Path(__file__).resolve().parents[1]
BRD_DIR = ROOT / "output" / "pcb" / "fusion_brd"

# ケーブルの付け方(SPEC_05: 下の基板の +X の端の内側の列で電源のケーブルを受け,外側の列から
# 左右の基板へ.左右の基板は外側の列で受ける.空く列は付け直し用・テスターで測る所).
# 基板は部品の面を下(−Z)にして付け,GND の線が下の壁の側に来る(Fusion の基板の写し方
# x = u・y = −83 − v).部品の面から見た図(.brd の上から見た図)では装置の +X が左になるので,
# 下の基板は図の左の端(J1・J2)が装置の右(ケーブルの切れ込みの側)
CABLES = {
    "SmTIASv4_LED_side_v3": {"J1": "下の基板\nから", "J2": "空き\n(テスター用)"},
    "SmTIASv4_LED_bottom_v3": {"J2": "電源の\nコネクタから", "J1": "右の\n基板へ",
                               "J3": "左の\n基板へ", "J4": "空き\n(テスター用)"},
}
TITLE = {
    "SmTIASv4_LED_side_v3": "左右用の基板(2 枚とも同じ)",
    "SmTIASv4_LED_bottom_v3": ("下用の基板.筐体に付けると図の左の端が装置の右"
                               "(ケーブルの切れ込みの側)"),
}


def _pads(root: ET.Element):
    """部品ごとのパッド(名前, 中心 x, y, 幅, 高さ)と部品の外形の線(layer 51)."""
    packages = _packages(root)
    parts = []
    for el in root.iter("element"):
        pkg = packages[(el.get("library", ""), el.get("package", ""))]
        ex, ey, rot = _f(el, "x"), _f(el, "y"), parse_rotation(el.get("rot"))
        pads, lines = [], []
        for p in pkg:
            if p.tag == "smd":
                px, py = _rotate(_f(p, "x"), _f(p, "y"), rot)
                w, h = _f(p, "dx"), _f(p, "dy")
                if round(rot / 90) % 2:
                    w, h = h, w
                pads.append((p.get("name"), ex + px, ey + py, w, h,
                             _f(p, "roundness", 0.0) >= 100))
            elif p.tag == "wire" and p.get("layer") == "51":
                a = _rotate(_f(p, "x1"), _f(p, "y1"), rot)
                b = _rotate(_f(p, "x2"), _f(p, "y2"), rot)
                lines.append(((ex + a[0], ey + a[1]), (ex + b[0], ey + b[1])))
        parts.append((el.get("name"), el.get("value"), ex, ey, pads, lines))
    return parts


def draw(path: Path, out_png: Path) -> None:
    root = ET.fromstring(path.read_text(encoding="utf-8"))
    parts = _pads(root)
    outline = [tuple(_f(w, k) for k in ("x1", "y1", "x2", "y2"))
               for w in root.find(".//board/plain") if w.tag == "wire" and w.get("layer") == "20"]
    xs = [v for s in outline for v in (s[0], s[2])]
    ys = [v for s in outline for v in (s[1], s[3])]
    x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys)
    cy = (y0 + y1) / 2

    fig, ax = plt.subplots(figsize=(max(14, (x1 - x0) * 0.32), 6.2))
    for xa, ya, xb, yb in outline:
        ax.plot([xa, xb], [ya, yb], color="0.3", lw=1.5)
    # 銅の線
    for sig in root.iter("signal"):
        for w in sig.iter("wire"):
            if w.get("layer") == "1":
                ax.plot([_f(w, "x1"), _f(w, "x2")], [_f(w, "y1"), _f(w, "y2")],
                        color="#e8a25a", lw=_f(w, "width") * 7, solid_capstyle="round",
                        zorder=1)
    cables = CABLES.get(path.stem, {})
    for name, value, ex, ey, pads, lines in parts:
        kind = name[0]
        if name.startswith("H"):
            ax.add_patch(Circle((ex, ey), 1.6, fc="white", ec="0.2", lw=1.2, zorder=3))
            ax.text(ex, ey, "M3", ha="center", va="center", fontsize=8, color="0.3")
            continue
        for _pname, px, py, w, h, rnd in pads:
            # roundness 100 のパッド(電源パッドの +12V)は両端が半円の形
            style = f"round,pad=0,rounding_size={min(w, h) / 2}" if rnd else "square,pad=0"
            ax.add_patch(FancyBboxPatch((px - w / 2, py - h / 2), w, h, boxstyle=style,
                                        fc="#e8a25a", ec="#a8641e", lw=0.6, zorder=2))
            used = not (kind == "J" and "空き" in cables.get(name, ""))
            if used:
                ax.add_patch(Circle((px, py), 0.45, fc="red", ec="darkred", lw=0.6, zorder=6,
                                    alpha=0.9))
        for (xa, ya), (xb, yb) in lines:
            ax.plot([xa, xb], [ya, yb], color="0.15", lw=0.9, zorder=5)
        if kind == "D" and value.startswith("LP"):  # LED
            cath = next(p for p in pads if p[0] == "1")
            ax.text(ex, y1 + 1.0, name, ha="center", va="bottom", fontsize=9, weight="bold")
            ax.text(cath[1], cath[2], "K", ha="center", va="center", fontsize=6.5,
                    color="white", weight="bold", zorder=7)
        elif kind == "D":  # 定電流 IC
            cath = next(p for p in pads if p[0] == "1")
            ax.text(ex, y1 + 1.0, f"{name}\n定電流 IC", ha="center", va="bottom", fontsize=7.5,
                    color="#1f4e9a", weight="bold")
            ax.text(cath[1], cath[2], "K", ha="center", va="center", fontsize=6.5,
                    color="white", weight="bold", zorder=7)
        elif kind == "J":
            note = cables.get(name, "")
            for pname, px, py, _w, _h, _r in pads:
                ax.text(px + 0.0, py + (1.5 if py > cy else -1.5),
                        "GND" if pname == "1" else "+12V", ha="center",
                        va="bottom" if py > cy else "top", fontsize=7,
                        color="black" if pname == "1" else "#c00000", weight="bold", zorder=7)
            ax.text(ex, y0 - 0.8, f"{name}\n{note}", ha="center", va="top", fontsize=7.5,
                    color="0.45" if "空き" in note else "#006400", weight="bold")
    ax.set_xlim(x0 - 4, x1 + 4)
    ax.set_ylim(y0 - 6.0, y1 + 4.5)
    ax.set_aspect("equal")
    ax.axis("off")
    n_dot = sum(1 for p in parts if not p[0].startswith("H")
                for _ in p[4]) - 2 * sum(1 for v in cables.values() if "空き" in v)
    ax.set_title(f"{TITLE.get(path.stem, path.stem)}({path.stem})— 部品の面から見た図."
                 f"赤丸がはんだを付ける所({n_dot} か所)\n"
                 "K = カソード(LED は大きいパッド・角の欠けた側,定電流 IC は帯の側)."
                 "LED は GND の縁の側が K",
                 fontsize=9.5)
    fig.tight_layout()
    fig.savefig(out_png, dpi=170)
    plt.close(fig)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--brd", type=Path, nargs="+",
                        default=[BRD_DIR / f"{n}.brd" for n in CABLES])
    parser.add_argument("--out", type=Path, default=ROOT / "output" / "pcb" / "solder_map")
    args = parser.parse_args(argv)
    args.out.mkdir(parents=True, exist_ok=True)
    for path in args.brd:
        png = args.out / f"{path.stem}.png"
        draw(path, png)
        print(f"[saved] {png}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())