Source code for jitxlib.jlcpcb.footprint

"""A catalogue footprint, fetched from LCSC and reduced to plain geometry.

EasyEDA is the source: `easyeda2kicad` fetches a part's CAD data and parses it
into its own intermediate model, and this module stops there. Nothing from
`easyeda2kicad.kicad` is used, so none of the KiCad file format's conventions
reach a JITX design. See `export/orientation.py`, which does the same thing
for pads alone.

Two things are normalized on the way in, and both are reflections rather than
sign conventions, so getting either wrong yields a mirror image rather than a
small error:

- coordinates are made relative to the footprint's own origin, which EasyEDA
  keeps in `bbox`, because everything it emits is in absolute canvas units;
- the y axis is flipped, because EasyEDA's points down and JITX's points up.

Lengths are millimetres and angles are counter-clockwise degrees once here,
which is what JITX wants. The result is JSON-serializable by design: it is
what `lcsc.lock.json` records, so that a design builds the same landpattern
on a machine that never reaches the network.
"""

from __future__ import annotations

from dataclasses import dataclass
from logging import getLogger
from typing import TYPE_CHECKING, Any, Mapping, Sequence

if TYPE_CHECKING:
    from easyeda2kicad.easyeda.parameters_easyeda import (
        EeFootprint,
        EeFootprintBbox,
    )

logger = getLogger(__name__)

Point = tuple[float, float]

# EasyEDA layer ids. Only the ones a footprint can carry are named; the rest
# are reported as-is when something lands on them.
TOP_COPPER = 1
BOTTOM_COPPER = 2
TOP_SILKSCREEN = 3
BOTTOM_SILKSCREEN = 4
TOP_PASTE = 5
BOTTOM_PASTE = 6
TOP_MASK = 7
BOTTOM_MASK = 8
BOARD_OUTLINE = 10
MULTI_LAYER = 11
DOCUMENT = 12
TOP_ASSEMBLY = 13
BOTTOM_ASSEMBLY = 14
MECHANICAL = 15
COMPONENT_SHAPE = 99
LEAD_SHAPE = 100
COMPONENT_POLARITY = 101

DECORATIVE = frozenset({LEAD_SHAPE, COMPONENT_POLARITY})
"""Layers EasyEDA draws for its own editor and that mean nothing on a board.

`LEAD_SHAPE` is the outline of the part's leads and `COMPONENT_POLARITY` the
little circle it puts on pin 1; neither is fabricated, and both would end up
as silkscreen if they were translated.
"""


[docs] class FootprintError(Exception): """A catalogue footprint that cannot be fetched or understood."""
def _round(value: float) -> float: # EasyEDA works in 10-mil units and the conversion to millimetres is # exact to well within a nanometre, so the noise being cut here is # floating point's, not measurement's. It keeps the lock file readable. return round(value, 6)
[docs] @dataclass(frozen=True) class Segment: """One step of a path: a straight line, or an elliptical arc, to `to`. Args: to: the point the step ends at. radii: ellipse radii, or None for a straight line. rotation: the ellipse's x-axis rotation in counter-clockwise degrees. large: take the longer of the two arcs that fit. clockwise: sweep direction, clockwise in the y-up frame. """ to: Point radii: Point | None = None rotation: float = 0.0 large: bool = False clockwise: bool = False
[docs] def json(self) -> dict[str, Any]: entry: dict[str, Any] = {"to": list(self.to)} if self.radii is not None: entry["radii"] = list(self.radii) entry["rotation"] = self.rotation entry["large"] = self.large entry["clockwise"] = self.clockwise return entry
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Segment: radii = entry.get("radii") return Segment( to=_point(entry["to"]), radii=None if radii is None else _point(radii), rotation=float(entry.get("rotation", 0.0)), large=bool(entry.get("large", False)), clockwise=bool(entry.get("clockwise", False)), )
[docs] @dataclass(frozen=True) class Path: """A run of segments from `start`, closed into a region or left open.""" start: Point segments: tuple[Segment, ...] closed: bool = False @property def points(self) -> tuple[Point, ...]: """The path's corners, ignoring the curvature of any arc in it.""" return (self.start, *(segment.to for segment in self.segments)) @property def straight(self) -> bool: """Whether every segment is a straight line.""" return all(segment.radii is None for segment in self.segments)
[docs] def json(self) -> dict[str, Any]: return { "start": list(self.start), "segments": [segment.json() for segment in self.segments], "closed": self.closed, }
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Path: return Path( start=_point(entry["start"]), segments=tuple(Segment.parse(s) for s in entry["segments"]), closed=bool(entry.get("closed", False)), )
[docs] @dataclass(frozen=True) class Pad: """One pad of the catalogue footprint. Args: number: pin number as EasyEDA states it. Not necessarily a number, and not necessarily unique: a part with two pads on one pin states the same number twice. shape: "RECT", "ELLIPSE", "OVAL" or "POLYGON". x: centre, millimetres, y-up, relative to the footprint origin. y: centre, millimetres, y-up, relative to the footprint origin. width: x extent before `rotation` is applied. height: y extent before `rotation` is applied. rotation: counter-clockwise degrees. layer: EasyEDA layer id. `TOP_COPPER` is a surface-mount pad and `MULTI_LAYER` a through-hole one. hole_radius: drill radius, zero for a surface-mount pad. hole_length: drill length for a slot, zero for a round hole. outline: the corners of a "POLYGON" pad, empty otherwise. EasyEDA's plating flag is not carried: it marks every surface-mount pad unplated, and it marks a USB-C receptacle's shield tabs unplated as well, so it says nothing. A pad is somewhere a pin is connected and is therefore plated; an unplated hole is a `Hole`, which is what EasyEDA draws one as. """ number: str shape: str x: float y: float width: float height: float rotation: float = 0.0 layer: int = TOP_COPPER hole_radius: float = 0.0 hole_length: float = 0.0 outline: tuple[Point, ...] = () @property def through_hole(self) -> bool: return self.hole_radius > 0.0
[docs] def json(self) -> dict[str, Any]: entry: dict[str, Any] = { "number": self.number, "shape": self.shape, "x": self.x, "y": self.y, "width": self.width, "height": self.height, } if self.layer != TOP_COPPER: entry["layer"] = self.layer if self.rotation: entry["rotation"] = self.rotation if self.hole_radius: entry["hole_radius"] = self.hole_radius if self.hole_length: entry["hole_length"] = self.hole_length if self.outline: entry["outline"] = [list(point) for point in self.outline] return entry
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Pad: return Pad( number=str(entry["number"]), shape=str(entry["shape"]), x=float(entry["x"]), y=float(entry["y"]), width=float(entry["width"]), height=float(entry["height"]), rotation=float(entry.get("rotation", 0.0)), layer=int(entry.get("layer", TOP_COPPER)), hole_radius=float(entry.get("hole_radius", 0.0)), hole_length=float(entry.get("hole_length", 0.0)), outline=tuple(_point(p) for p in entry.get("outline", ())), )
[docs] @dataclass(frozen=True) class Hole: """An unplated hole that is not part of a pad.""" x: float y: float radius: float
[docs] def json(self) -> dict[str, Any]: return {"x": self.x, "y": self.y, "radius": self.radius}
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Hole: return Hole( x=float(entry["x"]), y=float(entry["y"]), radius=float(entry["radius"]) )
[docs] @dataclass(frozen=True) class Via: """A via drawn into the footprint itself, as a thermal pad's often is.""" x: float y: float diameter: float hole_radius: float
[docs] def json(self) -> dict[str, Any]: return { "x": self.x, "y": self.y, "diameter": self.diameter, "hole_radius": self.hole_radius, }
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Via: return Via( x=float(entry["x"]), y=float(entry["y"]), diameter=float(entry["diameter"]), hole_radius=float(entry["hole_radius"]), )
[docs] @dataclass(frozen=True) class Curve: """A stroked line or arc on a graphical layer.""" layer: int width: float path: Path
[docs] def json(self) -> dict[str, Any]: return {"layer": self.layer, "width": self.width, "path": self.path.json()}
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Curve: return Curve( layer=int(entry["layer"]), width=float(entry["width"]), path=Path.parse(entry["path"]), )
[docs] @dataclass(frozen=True) class Circle: """A stroked circle on a graphical layer.""" layer: int x: float y: float radius: float width: float
[docs] def json(self) -> dict[str, Any]: return { "layer": self.layer, "x": self.x, "y": self.y, "radius": self.radius, "width": self.width, }
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Circle: return Circle( layer=int(entry["layer"]), x=float(entry["x"]), y=float(entry["y"]), radius=float(entry["radius"]), width=float(entry["width"]), )
[docs] @dataclass(frozen=True) class Region: """A filled region on a graphical layer. Args: layer: EasyEDA layer id. kind: "solid", "cutout" or "npth", as EasyEDA states it. path: the region's boundary, closed. """ layer: int kind: str path: Path
[docs] def json(self) -> dict[str, Any]: return {"layer": self.layer, "kind": self.kind, "path": self.path.json()}
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Region: return Region( layer=int(entry["layer"]), kind=str(entry["kind"]), path=Path.parse(entry["path"]), )
[docs] @dataclass(frozen=True) class Text: """A text item on a graphical layer. Args: kind: "N" for a plain note, "P" for the part's prefix (reference designator) placeholder, "L" for its value placeholder. mirrored: EasyEDA draws it mirrored, which a bottom-side item is. visible: EasyEDA hides it in the editor. """ layer: int x: float y: float size: float width: float rotation: float string: str kind: str = "N" mirrored: bool = False visible: bool = True
[docs] def json(self) -> dict[str, Any]: return { "layer": self.layer, "x": self.x, "y": self.y, "size": self.size, "width": self.width, "rotation": self.rotation, "string": self.string, "kind": self.kind, "mirrored": self.mirrored, "visible": self.visible, }
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Text: return Text( layer=int(entry["layer"]), x=float(entry["x"]), y=float(entry["y"]), size=float(entry["size"]), width=float(entry["width"]), rotation=float(entry["rotation"]), string=str(entry["string"]), kind=str(entry.get("kind", "N")), mirrored=bool(entry.get("mirrored", False)), visible=bool(entry.get("visible", True)), )
[docs] @dataclass(frozen=True) class Footprint: """A catalogue footprint in millimetres, y-up, about its own origin. Args: name: EasyEDA's own name for the package, such as "SOIC-8_L4.9-W3.9-P1.27-LS6.0-BL". pads, holes, vias, curves, circles, regions, texts: the geometry, each item carrying the EasyEDA layer it was drawn on. """ name: str pads: tuple[Pad, ...] = () holes: tuple[Hole, ...] = () vias: tuple[Via, ...] = () curves: tuple[Curve, ...] = () circles: tuple[Circle, ...] = () regions: tuple[Region, ...] = () texts: tuple[Text, ...] = ()
[docs] def json(self) -> dict[str, Any]: """The record as it is written to `lcsc.lock.json`. Empty collections are left out, so that the common footprint is a handful of pads and nothing else. """ entry: dict[str, Any] = {"name": self.name} for key, items in ( ("pads", self.pads), ("holes", self.holes), ("vias", self.vias), ("curves", self.curves), ("circles", self.circles), ("regions", self.regions), ("texts", self.texts), ): if items: entry[key] = [item.json() for item in items] return entry
[docs] @staticmethod def parse(entry: Mapping[str, Any]) -> Footprint: """Read back a record written by `json`. Raises: FootprintError: the record is not one this understands. A hand edited lock file is the likely source, so the message says what was wrong rather than leaving a `KeyError` to surface. """ try: return Footprint( name=str(entry["name"]), pads=tuple(Pad.parse(e) for e in entry.get("pads", ())), holes=tuple(Hole.parse(e) for e in entry.get("holes", ())), vias=tuple(Via.parse(e) for e in entry.get("vias", ())), curves=tuple(Curve.parse(e) for e in entry.get("curves", ())), circles=tuple(Circle.parse(e) for e in entry.get("circles", ())), regions=tuple(Region.parse(e) for e in entry.get("regions", ())), texts=tuple(Text.parse(e) for e in entry.get("texts", ())), ) except (KeyError, TypeError, ValueError) as exc: raise FootprintError(f"footprint record is not readable: {exc}") from exc
def _point(value: Any) -> Point: x, y = value return (float(x), float(y)) # -------------------------------------------------------------------------- # EasyEDA translation # -------------------------------------------------------------------------- @dataclass class _Frame: """The change of coordinates from EasyEDA's canvas to the footprint's own. EasyEDA gives most dimensions in millimetres but leaves path and polygon strings in its raw 10-mil canvas units, so both have to be handled, and both are measured from the canvas origin rather than the footprint's. """ x: float y: float x_raw: float y_raw: float @staticmethod def of(bbox: EeFootprintBbox) -> _Frame: return _Frame(x=bbox.x, y=bbox.y, x_raw=bbox.x_px, y_raw=bbox.y_px) def mm(self, x: float, y: float) -> Point: """A point already in millimetres, relative to the canvas origin.""" return (_round(x - self.x), _round(self.y - y)) def raw(self, x: float, y: float) -> Point: """A point in EasyEDA's raw canvas units.""" from easyeda2kicad.easyeda.parameters_easyeda import convert_to_mm return ( _round(convert_to_mm(x - self.x_raw)), _round(convert_to_mm(self.y_raw - y)), ) def length(self, value: float) -> float: """A length in EasyEDA's raw canvas units.""" from easyeda2kicad.easyeda.parameters_easyeda import convert_to_mm return _round(convert_to_mm(value)) def _numbers(text: str) -> list[float]: """The numbers in a whitespace or comma separated EasyEDA point list.""" found = [] for token in text.replace(",", " ").split(): try: found.append(float(token)) except ValueError: logger.debug("Ignoring %r in an EasyEDA point list", token) return found def _pairs(values: Sequence[float]) -> list[tuple[float, float]]: return [(values[i], values[i + 1]) for i in range(0, len(values) - 1, 2)] def _svg_path(path: str, frame: _Frame) -> Path | None: """Translate one EasyEDA SVG path into the y-up frame. Only the commands EasyEDA emits are handled, which is what its own parser supports: move, line, elliptical arc and close. """ from easyeda2kicad.easyeda.svg_path_parser import ( SvgPathClosePath, SvgPathEllipticalArc, SvgPathLineTo, SvgPathMoveTo, parse_svg_path, ) start: Point | None = None segments: list[Segment] = [] closed = False for command in parse_svg_path(path): if isinstance(command, SvgPathMoveTo): if start is not None: logger.warning( "Ignoring a second subpath in an EasyEDA path; only the " "first is translated" ) break # The parser leaves every field as the string it parsed. start = frame.raw(float(command.start_x), float(command.start_y)) elif isinstance(command, SvgPathLineTo): segments.append( Segment(to=frame.raw(float(command.pos_x), float(command.pos_y))) ) elif isinstance(command, SvgPathEllipticalArc): segments.append( Segment( to=frame.raw(float(command.end_x), float(command.end_y)), radii=( frame.length(float(command.radius_x)), frame.length(float(command.radius_y)), ), # The y flip reverses both the sense of a rotation and the # sense of a sweep. SVG's sweep flag means the direction of # increasing angle in its own y-down frame, which is # clockwise once the picture is read y-up. rotation=-float(command.x_axis_rotation), large=bool(command.flag_large_arc), clockwise=bool(command.flag_sweep), ) ) elif isinstance(command, SvgPathClosePath): closed = True if start is None or not segments: return None return Path(start=start, segments=tuple(segments), closed=closed) def _polyline(points: str, frame: _Frame) -> Path | None: """Translate an EasyEDA `TRACK` point list into the y-up frame.""" pairs = _pairs(_numbers(points)) if len(pairs) < 2: return None start, *rest = [frame.raw(x, y) for x, y in pairs] return Path( start=start, segments=tuple(Segment(to=point) for point in rest), closed=False )
[docs] def from_easyeda(source: EeFootprint) -> Footprint: """Reduce an `easyeda2kicad` footprint to the normalized model. Decorative layers are dropped; everything else is kept with the layer it was drawn on, so that deciding what a layer means is the landpattern's job rather than this one's. """ frame = _Frame.of(source.bbox) pads = [] for pad in source.pads: # A pad's centre arrives in millimetres but its polygon outline does # not, so the two go through different paths, and the outline is # absolute rather than relative to the centre. EasyEDA states an # outline for every pad; only a polygon pad's is its shape. shape = str(pad.shape).upper() outline = ( [frame.raw(x, y) for x, y in _pairs(_numbers(pad.points))] if shape == "POLYGON" else [] ) centre = frame.mm(pad.center_x, pad.center_y) pads.append( Pad( number=str(pad.number), shape=shape, x=centre[0], y=centre[1], width=_round(float(pad.width)), height=_round(float(pad.height)), rotation=_round(-float(pad.rotation)) or 0.0, layer=int(pad.layer_id), hole_radius=_round(float(pad.hole_radius)), hole_length=_round(float(pad.hole_length)), outline=tuple(outline), ) ) holes = [ Hole( *frame.mm(hole.center_x, hole.center_y), radius=_round(float(hole.radius)), ) for hole in source.holes ] vias = [ Via( *frame.mm(via.center_x, via.center_y), diameter=_round(float(via.diameter)), hole_radius=_round(float(via.radius)), ) for via in source.vias ] curves: list[Curve] = [] for track in source.tracks: if int(track.layer_id) in DECORATIVE: continue path = _polyline(track.points, frame) if path is None: logger.debug("Dropping an EasyEDA track with fewer than two points") continue curves.append( Curve( layer=int(track.layer_id), width=_round(float(track.stroke_width)), path=path, ) ) for arc in source.arcs: if int(arc.layer_id) in DECORATIVE: continue path = _svg_path(arc.path, frame) if path is None: logger.warning("Dropping an EasyEDA arc whose path could not be read") continue curves.append( Curve( layer=int(arc.layer_id), width=_round(float(arc.stroke_width)), path=path, ) ) # A rectangle is a stroked outline like a track, so it becomes one rather # than a shape of its own. EasyEDA anchors it at its top-left corner. for rect in source.rectangles: if int(rect.layer_id) in DECORATIVE: continue left, top = frame.mm(rect.x, rect.y) right = _round(left + float(rect.width)) bottom = _round(top - float(rect.height)) corners = ((left, top), (right, top), (right, bottom), (left, bottom)) curves.append( Curve( layer=int(rect.layer_id), width=_round(float(rect.stroke_width)), path=Path( start=corners[0], segments=tuple(Segment(to=point) for point in corners[1:]), closed=True, ), ) ) circles = [ Circle( int(circle.layer_id), *frame.mm(circle.cx, circle.cy), radius=_round(float(circle.radius)), width=_round(float(circle.stroke_width)), ) for circle in source.circles if int(circle.layer_id) not in DECORATIVE ] regions: list[Region] = [] for region in source.solid_regions: if int(region.layer_id) in DECORATIVE: continue path = _svg_path(region.path, frame) if path is None: logger.warning("Dropping an EasyEDA region whose path could not be read") continue regions.append( Region( layer=int(region.layer_id), kind=str(region.region_type or "solid"), path=Path(path.start, path.segments, closed=True), ) ) texts = [ Text( int(text.layer_id), *frame.mm(text.center_x, text.center_y), size=_round(float(text.font_size)), width=_round(float(text.stroke_width)), rotation=_round(-float(text.rotation)) or 0.0, string=str(text.text), kind=str(text.type or "N"), mirrored=bool(text.mirror) and str(text.mirror) not in ("0", "false"), visible=bool(text.is_displayed), ) for text in source.texts if int(text.layer_id) not in DECORATIVE ] return Footprint( name=str(source.info.name), pads=tuple(pads), holes=tuple(holes), vias=tuple(vias), curves=tuple(curves), circles=tuple(circles), regions=tuple(regions), texts=tuple(texts), )
[docs] def fetch(partnumber: str) -> Footprint: """Fetch a part's catalogue footprint from LCSC. This reaches the network. Callers are expected to have looked in `lcsc.lock.json` first and to record what comes back, so that a build that has already seen a part never gets here. Raises: FootprintError: the part has no CAD data, or `easyeda2kicad` is not installed. """ try: from easyeda2kicad.easyeda.easyeda_api import EasyedaApi from easyeda2kicad.easyeda.easyeda_importer import EasyedaFootprintImporter except ImportError as exc: raise FootprintError( "easyeda2kicad is required to look up footprints; pip install easyeda2kicad" ) from exc data = EasyedaApi().get_cad_data_of_component(lcsc_id=partnumber) if not data: raise FootprintError(f"{partnumber} has no EasyEDA CAD data") return from_easyeda( EasyedaFootprintImporter(easyeda_cp_cad_data=data).get_footprint() )