| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391 |
- """Extract footprint and pad metadata from a KiCad PCB."""
- from __future__ import annotations
- import math
- import re
- from dataclasses import dataclass, field
- from pathlib import Path
- from typing import TextIO
- from .sexpr import SExpr, iter_root_forms
- TOUCHPOINT_REFERENCE = re.compile(r"^(?:CON|J|PL|TP)\d+$")
- def _head(form: list[SExpr]) -> str:
- return str(form[0]) if form and isinstance(form[0], str) else ""
- def _children(form: list[SExpr], name: str) -> list[list[SExpr]]:
- return [item for item in form[1:] if isinstance(item, list) and _head(item) == name]
- def _child(form: list[SExpr], name: str) -> list[SExpr] | None:
- return next(iter(_children(form, name)), None)
- def _float(value: SExpr | None, default: float = 0.0) -> float:
- try:
- return float(str(value))
- except (TypeError, ValueError):
- return default
- def _values(form: list[SExpr] | None) -> list[str]:
- if form is None:
- return []
- return [str(item) for item in form[1:] if isinstance(item, str)]
- def _xy_angle(form: list[SExpr] | None) -> tuple[float, float, float]:
- values = _values(form)
- return (
- _float(values[0]) if values else 0.0,
- _float(values[1]) if len(values) > 1 else 0.0,
- _float(values[2]) if len(values) > 2 else 0.0,
- )
- def _normalize_angle(value: float) -> float:
- result = value % 360
- return 0.0 if math.isclose(result, 360.0) else result
- def _transform_point(
- local_x: float,
- local_y: float,
- origin_x: float,
- origin_y: float,
- rotation: float,
- ) -> tuple[float, float]:
- radians = math.radians(-rotation)
- cosine, sine = math.cos(radians), math.sin(radians)
- return (
- origin_x + local_x * cosine - local_y * sine,
- origin_y + local_x * sine + local_y * cosine,
- )
- @dataclass(frozen=True)
- class Pad:
- number: str
- pad_type: str
- shape: str
- x: float
- y: float
- width: float
- height: float
- rotation: float
- net: str | None
- layers: tuple[str, ...]
- drill_width: float
- drill_height: float
- mechanical: bool
- electrical: bool
- @dataclass
- class Footprint:
- reference: str
- component_value: str
- x: float
- y: float
- rotation: float
- side: str
- layer: str
- pads: list[Pad] = field(default_factory=list)
- bounds: dict[str, float] = field(default_factory=dict)
- def pad_by_number(self, number: str) -> Pad:
- for pad in self.pads:
- if pad.number == str(number):
- return pad
- raise KeyError(f"unknown pad {self.reference}.{number}")
- @dataclass
- class ParsedBoard:
- footprints: list[Footprint]
- footprint_count: int
- bounds: dict[str, float]
- def footprint_by_reference(self, reference: str) -> Footprint:
- for footprint in self.footprints:
- if footprint.reference == reference:
- return footprint
- raise KeyError(f"unknown footprint {reference}")
- def _reference(form: list[SExpr]) -> str | None:
- for prop in _children(form, "property"):
- values = _values(prop)
- if len(values) < 2 or values[0] != "Reference":
- continue
- reference = values[1].strip()
- if reference and reference != "${REFERENCE}":
- return reference
- for text in _children(form, "fp_text"):
- values = _values(text)
- if len(values) >= 2 and values[0] == "reference" and values[1] != "${REFERENCE}":
- return values[1]
- return None
- def _component_value(form: list[SExpr]) -> str:
- properties: dict[str, str] = {}
- for prop in _children(form, "property"):
- values = _values(prop)
- if len(values) >= 2 and values[1] and values[1] != "${REFERENCE}":
- properties.setdefault(values[0], values[1].strip())
- for name in ("Component Value", "Value"):
- if properties.get(name):
- return properties[name]
- if len(form) > 1 and isinstance(form[1], str):
- return form[1].strip()
- return ""
- def _drill_size(form: list[SExpr]) -> tuple[float, float]:
- drill = _child(form, "drill")
- if drill is None:
- return 0.0, 0.0
- numeric: list[float] = []
- for value in _values(drill):
- try:
- numeric.append(float(value))
- except ValueError:
- continue
- if not numeric:
- return 0.0, 0.0
- return numeric[0], numeric[1] if len(numeric) > 1 else numeric[0]
- def _parse_pad(
- form: list[SExpr],
- origin_x: float,
- origin_y: float,
- footprint_rotation: float,
- ) -> Pad:
- values = _values(form)
- number = values[0] if values else ""
- pad_type = values[1] if len(values) > 1 else "unknown"
- shape = values[2] if len(values) > 2 else "unknown"
- local_x, local_y, local_rotation = _xy_angle(_child(form, "at"))
- x, y = _transform_point(
- local_x,
- local_y,
- origin_x,
- origin_y,
- footprint_rotation,
- )
- size = _values(_child(form, "size"))
- width = _float(size[0]) if size else 0.0
- height = _float(size[1]) if len(size) > 1 else width
- drill_width, drill_height = _drill_size(form)
- net_values = _values(_child(form, "net"))
- net = net_values[-1] if net_values else None
- layers = tuple(_values(_child(form, "layers")))
- mechanical = pad_type == "np_thru_hole" or not number
- rotation = local_rotation
- return Pad(
- number=number,
- pad_type=pad_type,
- shape=shape,
- x=x,
- y=y,
- width=width,
- height=height,
- rotation=_normalize_angle(rotation),
- net=net,
- layers=layers,
- drill_width=drill_width,
- drill_height=drill_height,
- mechanical=mechanical,
- electrical=not mechanical,
- )
- def _pad_bounds(pad: Pad) -> tuple[float, float, float, float]:
- width = max(pad.width, pad.drill_width, 0.5)
- height = max(pad.height, pad.drill_height, 0.5)
- radians = math.radians(pad.rotation)
- cosine, sine = abs(math.cos(radians)), abs(math.sin(radians))
- half_width = (width * cosine + height * sine) / 2
- half_height = (width * sine + height * cosine) / 2
- return (
- pad.x - half_width,
- pad.y - half_height,
- pad.x + half_width,
- pad.y + half_height,
- )
- def _footprint_bounds(pads: list[Pad], origin_x: float, origin_y: float) -> dict[str, float]:
- extents = [_pad_bounds(pad) for pad in pads]
- if not extents:
- extents = [(origin_x - 0.5, origin_y - 0.5, origin_x + 0.5, origin_y + 0.5)]
- minimum_x = min(item[0] for item in extents)
- minimum_y = min(item[1] for item in extents)
- maximum_x = max(item[2] for item in extents)
- maximum_y = max(item[3] for item in extents)
- return {
- "x": minimum_x,
- "y": minimum_y,
- "width": maximum_x - minimum_x,
- "height": maximum_y - minimum_y,
- }
- def _parse_footprint(form: list[SExpr]) -> Footprint | None:
- reference = _reference(form)
- if not reference:
- return None
- layer_values = _values(_child(form, "layer"))
- layer = layer_values[0] if layer_values else ""
- side = "back" if layer.startswith("B.") else "front"
- x, y, rotation = _xy_angle(_child(form, "at"))
- pads = [
- _parse_pad(pad, x, y, rotation)
- for pad in _children(form, "pad")
- ]
- return Footprint(
- reference=reference,
- component_value=_component_value(form),
- x=x,
- y=y,
- rotation=_normalize_angle(rotation),
- side=side,
- layer=layer,
- pads=pads,
- bounds=_footprint_bounds(pads, x, y),
- )
- def _point(form: list[SExpr] | None) -> tuple[float, float]:
- values = _values(form)
- return (
- _float(values[0]) if values else 0.0,
- _float(values[1]) if len(values) > 1 else 0.0,
- )
- def _arc_points(form: list[SExpr]) -> list[tuple[float, float]]:
- start = _point(_child(form, "start"))
- middle = _point(_child(form, "mid"))
- end = _point(_child(form, "end"))
- points = [start, middle, end]
- determinant = 2 * (
- start[0] * (middle[1] - end[1])
- + middle[0] * (end[1] - start[1])
- + end[0] * (start[1] - middle[1])
- )
- if math.isclose(determinant, 0.0, abs_tol=1e-12):
- return points
- start_sq = start[0] ** 2 + start[1] ** 2
- middle_sq = middle[0] ** 2 + middle[1] ** 2
- end_sq = end[0] ** 2 + end[1] ** 2
- center_x = (
- start_sq * (middle[1] - end[1])
- + middle_sq * (end[1] - start[1])
- + end_sq * (start[1] - middle[1])
- ) / determinant
- center_y = (
- start_sq * (end[0] - middle[0])
- + middle_sq * (start[0] - end[0])
- + end_sq * (middle[0] - start[0])
- ) / determinant
- radius = math.hypot(start[0] - center_x, start[1] - center_y)
- tau = math.tau
- start_angle = math.atan2(start[1] - center_y, start[0] - center_x) % tau
- middle_angle = math.atan2(middle[1] - center_y, middle[0] - center_x) % tau
- end_angle = math.atan2(end[1] - center_y, end[0] - center_x) % tau
- ccw_span = (end_angle - start_angle) % tau
- middle_ccw = (middle_angle - start_angle) % tau
- counter_clockwise = middle_ccw <= ccw_span + 1e-9
- def included(angle: float) -> bool:
- if counter_clockwise:
- return (angle - start_angle) % tau <= ccw_span + 1e-9
- clockwise_span = (start_angle - end_angle) % tau
- return (start_angle - angle) % tau <= clockwise_span + 1e-9
- for angle in (0.0, math.pi / 2, math.pi, 3 * math.pi / 2):
- if included(angle):
- points.append((center_x + radius * math.cos(angle), center_y + radius * math.sin(angle)))
- return points
- def _edge_points(form: list[SExpr]) -> list[tuple[float, float]]:
- layer = _values(_child(form, "layer"))
- if not layer or layer[0] != "Edge.Cuts":
- return []
- kind = _head(form)
- if kind == "gr_line":
- return [_point(_child(form, "start")), _point(_child(form, "end"))]
- if kind == "gr_rect":
- start = _point(_child(form, "start"))
- end = _point(_child(form, "end"))
- return [start, end, (start[0], end[1]), (end[0], start[1])]
- if kind == "gr_circle":
- center = _point(_child(form, "center"))
- end = _point(_child(form, "end"))
- radius = math.hypot(end[0] - center[0], end[1] - center[1])
- return [
- (center[0] - radius, center[1]),
- (center[0] + radius, center[1]),
- (center[0], center[1] - radius),
- (center[0], center[1] + radius),
- ]
- if kind == "gr_arc":
- return _arc_points(form)
- if kind in {"gr_poly", "gr_curve"}:
- points_form = _child(form, "pts")
- return [_point(item) for item in _children(points_form or [], "xy")]
- return []
- def _board_bounds(edge_points: list[tuple[float, float]], footprints: list[Footprint]) -> dict[str, float]:
- if edge_points:
- minimum_x = min(point[0] for point in edge_points)
- minimum_y = min(point[1] for point in edge_points)
- maximum_x = max(point[0] for point in edge_points)
- maximum_y = max(point[1] for point in edge_points)
- elif footprints:
- minimum_x = min(item.bounds["x"] for item in footprints)
- minimum_y = min(item.bounds["y"] for item in footprints)
- maximum_x = max(item.bounds["x"] + item.bounds["width"] for item in footprints)
- maximum_y = max(item.bounds["y"] + item.bounds["height"] for item in footprints)
- else:
- minimum_x = minimum_y = maximum_x = maximum_y = 0.0
- return {
- "x": minimum_x,
- "y": minimum_y,
- "width": maximum_x - minimum_x,
- "height": maximum_y - minimum_y,
- }
- def parse_kicad_pcb(source: Path | str | TextIO) -> ParsedBoard:
- footprints: list[Footprint] = []
- footprint_count = 0
- edge_points: list[tuple[float, float]] = []
- for form in iter_root_forms(source):
- kind = _head(form)
- if kind != "footprint":
- edge_points.extend(_edge_points(form))
- continue
- footprint_count += 1
- footprint = _parse_footprint(form)
- if footprint is not None:
- footprints.append(footprint)
- return ParsedBoard(
- footprints=footprints,
- footprint_count=footprint_count,
- bounds=_board_bounds(edge_points, footprints),
- )
- def select_touchpoints(board: ParsedBoard) -> list[Footprint]:
- return [footprint for footprint in board.footprints if TOUCHPOINT_REFERENCE.fullmatch(footprint.reference)]
|