Source code for jitxlib.jlcpcb.landpattern

"""`LCSCLandpattern`: the landpattern of the catalogue part being ordered.

A component that names an LCSC part has already said which footprint it
wants, and LCSC publishes that footprint. This builds it, so that a part
whose package no generator draws does not have to be traced by hand, and so
that the landpattern and the part ordered against it cannot drift apart.

Put one in a component that carries an `LCSCPart`:

>>> class Sensor(jitx.Component):
...     lcsc = LCSCPart("C2874116")
...     SDA = Port()
...     SCL = Port()
...     landpattern = LCSCLandpattern(ports={"1": SDA, "2": SCL})

Which part's footprint that is comes off the component's own `LCSCPart`,
which may be assigned below the landpattern, so the constructor only
registers a post-processing step and JITX runs it once the component is
otherwise complete. Naming the part instead builds it there and then, and is
what a parts provider does when it attaches a catalogue footprint in
`materialize`:

>>> component.landpattern = LCSCLandpattern(partnumber="C2874116")

It is recorded in `lcsc.lock.json` next to the orientation, and read from
there on every later build. A design whose parts are all in the lock file
never reaches the network, and the footprint it builds is reviewable in a
diff rather than fetched afresh and silently different. An orientation of
zero is recorded with it: a landpattern built from the catalogue footprint is
already in the frame JLCPCB places the part in, so there is no correction to
measure. As everywhere in that file, a value already present wins.
"""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from logging import getLogger
from pathlib import Path
from typing import TYPE_CHECKING, Any

import jitx.log
from jitx.component import CurrentComponent
from jitx.container import Container
from jitx.context import Context
from jitx.feature import Courtyard, Custom, Silkscreen, Soldermask
from jitx.inspect import extract
from jitx.landpattern import Landpattern, Pad, PadMapping
from jitx.layerindex import Side
from jitx.memo import dememoize
from jitx.net import Port
from jitx.shapes import Shape
from jitx.shapes.composites import capsule, rectangle
from jitx.shapes.primitive import (
    Arc,
    ArcPolygon,
    ArcPolyline,
    Circle,
    Polygon,
    Polyline,
)
from jitx.transform import Transform
from jitxlib.landpatterns.pads import SMDPad, THPad

from . import footprint as fp
from .export import lock
from .part import part_of

if TYPE_CHECKING:
    from jitx.component import Component

logger = getLogger(__name__)

ARC_SEGMENTS = 32
"""How finely an elliptical arc is approximated, in segments per full turn.

Only true ellipses need it. A circular arc, which is all a footprint normally
draws, becomes a JITX `Arc` and is exact.
"""


[docs] class LandpatternError(Exception): """A catalogue footprint that cannot be turned into a landpattern."""
[docs] @dataclass(frozen=True) class LockFile(Context): """Where the `lcsc.lock.json` to read and write lives. Set it when the file does not belong at the project root, which is where it is looked for otherwise. >>> class MyDesign(jitx.Design): ... lockfile = LockFile(Path("vendor/lcsc.lock.json")) """ path: Path
[docs] @dememoize class LCSCLandpattern(Container): """The landpattern of the component's LCSC part, from LCSC's own data. Holds a `Landpattern` built from the catalogue footprint and, when the ports are given, the `PadMapping` that binds them to it. Being a container, both are members of the component, exactly as if they had been written there. Args: ports: pad name to port. LCSC pad names are strings, and a name may appear on more than one pad; every pad with that name goes to the port named here. Giving the same port for more than one name works too and has the same effect, which is how a part with several pads on one pin is described. When it is omitted, no `PadMapping` is made and JITX's default in-order mapping binds the component's ports to the pads. That is only right when the pads are in pin order and there is exactly one of each, which is the common case; the exception is a footprint with repeated pad names, where the pads are grouped by name and mapped in order of first appearance. partnumber: the LCSC C-number to fetch, when the component's own `LCSCPart` is not the part whose footprint is wanted. Not memoized: what it builds depends on the component it is in rather than on its arguments, so two components must not share one. """ package: str = "" """EasyEDA's name for the package, once the footprint has been read. The exporter reads it for the BOM's package column, which is otherwise the landpattern's class name and would say nothing. """ def __init__( self, ports: Mapping[str | int, Port] | None = None, *, partnumber: str | None = None, ): # The ports are held in a local rather than on the container. A port # assigned to a container becomes a child of it, and a port belongs # to the component; JITX rejects the same port appearing in two # places in the tree. names = _names(ports) if partnumber is not None: # The part is named, so there is nothing to read off the component # and nothing to wait for. Building here is also what lets a parts # provider build one in `materialize`, after the constructor has # returned and a postprocess step would never run; the component # is optional for the same reason. self.__build(partnumber, names, _current_component()) return # The C-number has to come off the component's own `LCSCPart`, which # may be assigned below this line, so the build waits until the # component is otherwise complete. CurrentComponent.require().postprocess( lambda component: self.__build(_partnumber(component), names, component) ) def __build( self, partnumber: str, ports: dict[str, Port] | None, component: Component | None, ) -> None: """Fill this container with the catalogue footprint of `partnumber`. Args: component: the component it belongs to, when there is one. Only the port-to-pad fallback needs it, so a build with no component to hand is refused only if it reaches that. """ source = resolve(partnumber, _lockfile()) landpattern = Landpattern() built: list[tuple[str, str]] = [] for index, pad in enumerate(source.pads): shape = _pad(pad) if shape is None: continue # A catalogue pad name is neither unique nor necessarily a legal # identifier, so the pads are named after the order they were # drawn in and the catalogue names are kept alongside. attribute = f"p{index}" setattr(landpattern, attribute, shape) built.append((pad.number, attribute)) _graphics(landpattern, source) self.landpattern = landpattern self.package = source.name grouped: dict[str, list[Pad]] = {} for name, attribute in built: grouped.setdefault(name, []).append(getattr(self.landpattern, attribute)) mapping = _mapping(grouped, component, ports) if mapping: self.mapping = PadMapping(mapping)
def _partnumber(component: Component) -> str: """The C-number of the component's own `LCSCPart`.""" part = part_of(component) if part is None: raise LandpatternError( f"{typename(component)} has an LCSCLandpattern but no LCSCPart, " "so there is no catalogue footprint to build it from; add one, " "or give the landpattern a partnumber" ) return part.partnumber def _current_component() -> Component | None: """The component being constructed, if this runs while one is.""" context = CurrentComponent.get() return None if context is None else context.component def _names(ports: Mapping[str | int, Port] | None) -> dict[str, Port] | None: """The `ports` argument keyed by catalogue pad name, which is a string.""" return None if ports is None else {str(k): v for k, v in ports.items()} def _lockfile() -> Path: """The lock file this build reads, from the context or the project root.""" context = LockFile.get() return lock.path() if context is None else context.path
[docs] def resolve(partnumber: str, file: Path) -> fp.Footprint: """The part's catalogue footprint, from the lock file or from LCSC. The lock file is the authority. A part that is not in it is fetched and recorded, with an orientation of zero, so that the next build of the same design is offline and builds the same landpattern. Args: partnumber: the LCSC C-number. file: the `lcsc.lock.json` to read, and to extend on a miss. """ held = lock.read(file) recorded = held.footprint(partnumber) if recorded is not None: return fp.Footprint.parse(recorded) jitx.log.notice(logger, "Fetching the LCSC catalogue footprint for %s", partnumber) fetched = fp.fetch(partnumber) held.record_footprint(partnumber, fetched.json()) lock.write(held) jitx.log.notice(logger, "Recorded the footprint of %s in %s", partnumber, held.path) return fetched
# -------------------------------------------------------------------------- # Pads # -------------------------------------------------------------------------- def _pad(pad: fp.Pad) -> Pad | None: """One catalogue pad as a JITX pad, or None when it cannot be drawn. The soldermask and paste openings are left to the design's own rules rather than taken from the catalogue: they are the fabricator's business, and the part's footprint has no standing to state them. """ copper = _pad_shape(pad) if copper is None: return None if not pad.through_hole: if pad.layer != fp.TOP_COPPER: logger.warning( "Skipping pad %r on EasyEDA layer %d: a landpattern's pads " "are on the side the part is placed on", pad.number, pad.layer, ) return None built = SMDPad(copper) else: built = THPad(copper, _hole_shape(pad)) return built.at(pad.x, pad.y, rotate=pad.rotation) def _pad_shape(pad: fp.Pad) -> Shape | None: """The copper of one catalogue pad, in its own frame.""" if pad.shape == "POLYGON": if len(pad.outline) < 3: logger.warning( "Skipping polygon pad %r: it has %d corner(s)", pad.number, len(pad.outline), ) return None # A polygon pad's outline is absolute, so it is brought back into the # pad's own frame here and the placement transform puts it back. return Polygon([(x - pad.x, y - pad.y) for x, y in pad.outline]) if pad.width <= 0.0 or pad.height <= 0.0: logger.warning( "Skipping pad %r: it is %g by %g mm", pad.number, pad.width, pad.height ) return None if pad.shape == "RECT": return rectangle(pad.width, pad.height) if pad.shape in ("ELLIPSE", "OVAL"): return capsule(pad.width, pad.height) logger.warning( "Pad %r has EasyEDA shape %r, which is not known; drawing it as a rectangle", pad.number, pad.shape, ) return rectangle(pad.width, pad.height) def _hole_shape(pad: fp.Pad) -> Shape: """The drill of a through-hole pad: round, or a slot when it has a length. EasyEDA states a slot's length but not which way it runs. It runs along the pad's longer side, which is the only direction the copper leaves room for. """ diameter = 2 * pad.hole_radius if pad.hole_length <= 0.0: return Circle(radius=pad.hole_radius) if pad.height > pad.width: return capsule(diameter, max(pad.hole_length, diameter)) return capsule(max(pad.hole_length, diameter), diameter) def _mapping( grouped: dict[str, list[Pad]], component: Component | None, ports: dict[str, Port] | None, ) -> dict[Port, Pad | Sequence[Pad]]: """The port-to-pad mapping, empty when JITX's default should be used. A port may take several pads, which is how a part with more than one pad on a pin is wired, and is what both a repeated pad name and a port given twice in `ports` produce. Args: grouped: the pads that were built, keyed by catalogue pad name, in the order the catalogue draws them. """ if ports is None: if all(len(pads) == 1 for pads in grouped.values()): return {} if component is None: raise LandpatternError( "A catalogue footprint with repeated pad name(s) " f"({', '.join(name for name, pads in grouped.items() if len(pads) > 1)}) " "needs a ports= mapping when it is built without a component" ) jitx.log.notice( logger, "%s has repeated pad names (%s); mapping its ports to the pad " "groups in order", typename(component), ", ".join(name for name, pads in grouped.items() if len(pads) > 1), ) declared = list(extract(component, Port)) if len(declared) != len(grouped): raise LandpatternError( f"{typename(component)} has {len(declared)} port(s) and its " f"catalogue footprint has {len(grouped)} distinct pad " "name(s); give the landpattern a ports= mapping" ) return { port: _one_or_more(pads) for port, pads in zip(declared, grouped.values(), strict=True) } missing = sorted(set(ports) - set(grouped)) if missing: raise LandpatternError( f"{typename(component)} maps pad(s) {', '.join(missing)}, which " f"the catalogue footprint does not have; it has " f"{', '.join(sorted(grouped))}" ) unmapped = sorted(set(grouped) - set(ports)) if unmapped: logger.warning( "%s leaves pad(s) %s unmapped; they will carry no net", typename(component), ", ".join(unmapped), ) collected: dict[Port, list[Pad]] = {} for name, port in ports.items(): collected.setdefault(port, []).extend(grouped[name]) return {port: _one_or_more(pads) for port, pads in collected.items()} def _one_or_more(pads: list[Pad]) -> Pad | Sequence[Pad]: return pads[0] if len(pads) == 1 else pads # -------------------------------------------------------------------------- # Graphics # -------------------------------------------------------------------------- def _graphics(landpattern: Landpattern, source: fp.Footprint) -> None: """Add everything the footprint draws that is not a pad.""" index = 0 for feature in _features(source): setattr(landpattern, f"g{index}", feature) index += 1 def _features(source: fp.Footprint): """Every graphical item of the footprint, as a JITX feature.""" from jitx.feature import Cutout for hole in source.holes: yield Cutout(Transform((hole.x, hole.y)) * Circle(radius=hole.radius)) for via in source.vias: # A via drawn into a footprint, as a thermal pad's fan-out is, is # copper the design did not ask for and cannot route to. It is left # out rather than guessed at; the design places its own. logger.warning( "Ignoring a via at (%g, %g) in the catalogue footprint; place " "vias in the design instead", via.x, via.y, ) for circle in source.circles: shape = Transform((circle.x, circle.y)) * ArcPolyline( max(circle.width, 0.01), [Arc((0.0, 0.0), circle.radius, 0.0, 360.0)], ) feature = _surface(circle.layer, shape) if feature is not None: yield feature for curve in source.curves: shape = _stroke(curve) feature = _surface(curve.layer, shape) if feature is not None: yield feature for region in source.regions: if region.kind != "solid": logger.warning( "Ignoring a %r region on EasyEDA layer %d; only solid " "regions are drawn", region.kind, region.layer, ) continue feature = _surface(region.layer, _fill(region.path), filled=True) if feature is not None: yield feature for text in source.texts: if text.kind != "N" or not text.visible: # "P" and "L" are EasyEDA's placeholders for the reference # designator and the value, which JITX draws itself. continue logger.debug("Ignoring the text %r in the catalogue footprint", text.string) def _surface(layer: int, shape: Shape, filled: bool = False): """The JITX feature for one EasyEDA graphical layer, or None to drop it.""" if layer == fp.TOP_SILKSCREEN: return Silkscreen(shape) if layer == fp.BOTTOM_SILKSCREEN: return Silkscreen(shape, Side.Bottom) if layer == fp.TOP_MASK: return Soldermask(shape) if layer == fp.BOTTOM_MASK: return Soldermask(shape, Side.Bottom) if layer == fp.COMPONENT_SHAPE: # EasyEDA's component-shape layer is the part's body outline, which # is what a courtyard is. It has to be a closed shape. if filled: return Courtyard(shape) logger.debug("Ignoring an open outline on the component-shape layer") return None if layer == fp.TOP_ASSEMBLY: return Custom(shape, name="Assembly") if layer == fp.BOTTOM_ASSEMBLY: return Custom(shape, Side.Bottom, name="Assembly") if layer in (fp.DOCUMENT, fp.MECHANICAL): return Custom(shape, name="Document") if layer in (fp.TOP_PASTE, fp.BOTTOM_PASTE): # Paste belongs to the pads, and the design's rules decide it. return None logger.warning( "Ignoring footprint geometry on EasyEDA layer %d, which has no " "landpattern equivalent", layer, ) return None def _stroke(curve: fp.Curve) -> Shape: """A stroked path as a polyline, keeping any arc in it as an arc.""" width = max(curve.width, 0.01) elements = _elements(curve.path) if all(isinstance(element, tuple) for element in elements): return Polyline(width, [e for e in elements if isinstance(e, tuple)]) return ArcPolyline(width, elements) def _fill(path: fp.Path) -> Shape: """A closed path as a filled shape, keeping any arc in it as an arc.""" elements = _elements(path) if all(isinstance(element, tuple) for element in elements): return Polygon([e for e in elements if isinstance(e, tuple)]) return ArcPolygon(elements) def _elements(path: fp.Path) -> list[Arc | tuple[float, float]]: """A path as the element list `ArcPolyline` and `ArcPolygon` take. A circular arc becomes one `Arc`. An elliptical one has no JITX equivalent and is approximated by points, which is the only lossy step in the translation; footprints draw them rarely and small. """ elements: list[Arc | tuple[float, float]] = [path.start] here = path.start for segment in path.segments: if segment.radii is None: elements.append(segment.to) elif _circular(segment.radii): radius = (segment.radii[0] + segment.radii[1]) / 2 elements.append( Arc( here, segment.to, radius, clockwise=segment.clockwise, large=segment.large, ) ) else: elements.extend(_sampled(here, segment)) here = segment.to return elements def _circular(radii: tuple[float, float]) -> bool: return abs(radii[0] - radii[1]) <= 1e-6 * max(abs(radii[0]), abs(radii[1]), 1.0) def _sampled(start: tuple[float, float], segment: fp.Segment): """An elliptical arc as points, excluding its start and including its end.""" import math assert segment.radii is not None rx, ry = segment.radii phi = math.radians(segment.rotation) cos, sin = math.cos(phi), math.sin(phi) # The endpoint-to-centre conversion of the SVG specification, appendix # F.6.5, read in a y-up frame where the sweep flag means the direction of # increasing angle. sweep = not segment.clockwise dx = (start[0] - segment.to[0]) / 2 dy = (start[1] - segment.to[1]) / 2 x1 = cos * dx + sin * dy y1 = -sin * dx + cos * dy if rx == 0.0 or ry == 0.0: return [segment.to] scale = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry) if scale > 1.0: rx *= math.sqrt(scale) ry *= math.sqrt(scale) numerator = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1 denominator = rx * rx * y1 * y1 + ry * ry * x1 * x1 factor = math.sqrt(max(numerator / denominator, 0.0)) if denominator else 0.0 if segment.large == sweep: factor = -factor cx1 = factor * rx * y1 / ry cy1 = -factor * ry * x1 / rx cx = cos * cx1 - sin * cy1 + (start[0] + segment.to[0]) / 2 cy = sin * cx1 + cos * cy1 + (start[1] + segment.to[1]) / 2 theta = math.atan2((y1 - cy1) / ry, (x1 - cx1) / rx) end = math.atan2((-y1 - cy1) / ry, (-x1 - cx1) / rx) delta = end - theta if sweep and delta < 0: delta += 2 * math.pi elif not sweep and delta > 0: delta -= 2 * math.pi steps = max(2, int(ARC_SEGMENTS * abs(delta) / (2 * math.pi)) + 1) points = [] for step in range(1, steps + 1): angle = theta + delta * step / steps px = rx * math.cos(angle) py = ry * math.sin(angle) points.append((cx + cos * px - sin * py, cy + sin * px + cos * py)) points[-1] = segment.to return points # -------------------------------------------------------------------------- # Small helpers # --------------------------------------------------------------------------
[docs] def typename(component: Any) -> str: """A component's class name, for a message a user has to act on.""" from jitx.proxy import typeof if component is None: return "The component" return typeof(component).__name__