"""One walk of the design, feeding both fab files.
The BOM and the pick-and-place file are generated from the same records on
purpose. JLCPCB only recognises a component that appears in both, and a
designator in one and not the other is a documented upload failure, so the two
files are built from one enumeration rather than from two walks that have to
be kept in agreement.
"""
from __future__ import annotations
from dataclasses import dataclass
from logging import getLogger
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any
from jitx.component import Component
from jitx.feature import Cutout
from jitx.inspect import decompose, extract, visit
from jitx.landpattern import Landpattern, Pad
from jitx.layerindex import Side
from jitx.placement import Placement
from jitx.proxy import typeof
from ..part import AmbiguousPart, LCSCPart, part_of
from . import lock
from .values import render
if TYPE_CHECKING:
from jitx.run import RuntimeDesign
logger = getLogger(__name__)
DEFAULT_ORIENTATION = 0.0
"""Correction applied to a component with no explicit orientation, in degrees.
Zero, deliberately. There is no single offset between JITX's landpattern
generators and the orientation JLCPCB takes as zero: measured against their
placement preview on one board, an SOIC-8 needed -90, a 0603 LED needed +90,
and a through-hole header needed something else again. A part's zero is its
tape-and-reel orientation, which is a property of the catalogue part rather
than of the landpattern it is placed on, so no constant can be right for all
of them.
A revision of this file did default to -90, from an observation that every
part on one board needed turning 90 degrees clockwise. That observation was
confounded: the board's chip resistors are symmetric under a half turn and
so look correct at either value, and its header turned out to be the wrong
part. Correcting by a constant that is right for one package and 180 degrees
wrong for another is worse than correcting nothing, because a wrong rotation
that looks deliberate survives review.
So corrections are per part, via `LCSCPart(orientation=...)`, and are
measurements rather than guesses. The order sheet lists every part relying on
this default so the placement preview has a checklist.
"""
[docs]
class ExportError(Exception):
"""A design the packet cannot describe."""
[docs]
@dataclass
class Part:
"""One component, as both fab files need it."""
designator: str
comment: str
footprint: str
lcsc: str | None
x: float
y: float
rotation: float
side: Side
through_hole: bool
footprint_guessed: bool
"""The footprint came from a landpattern class name, which JLCPCB will
most likely flag with a package-verification warning."""
orientation_default: bool
"""The orientation came from `DEFAULT_ORIENTATION` rather than from an
`LCSCPart` that states one."""
@property
def layer(self) -> str:
return "Bottom" if self.side == Side.Bottom else "Top"
[docs]
@dataclass
class Inventory:
"""Everything the packet says about the design's components."""
parts: list[Part]
"""Ordered, soldered and in the BOM: one row in each fab file."""
not_soldered: list[str]
"""In the BOM sense but not placed. Omitted from both files and listed on
the order sheet, because a sourced part with no placement lands in
JLCPCB's UI as an unselected part."""
[docs]
def build(
design: "RuntimeDesign", orientations: Mapping[str, float] | None = None
) -> Inventory:
"""Enumerate the design's components into fab-file records.
Args:
design: the captured design to walk.
orientations: recorded corrections keyed by LCSC C-number, from the
lock file. These outrank `LCSCPart(orientation=...)`; see
`_correction`.
"""
parts: list[Part] = []
not_soldered: list[str] = []
for trace, comp in design.query(Component):
in_bom = comp.in_bom is not False
soldered = comp.soldered is not False
if not in_bom and not soldered:
continue
if soldered and not in_bom:
logger.warning(
"%s is soldered but not in the bill of materials; omitting it "
"from both fab files",
trace.path,
)
continue
designator = _designator(comp, trace.path)
if not soldered:
not_soldered.append(designator)
continue
parts.append(_part(comp, trace, designator, orientations or {}))
return Inventory(parts=parts, not_soldered=not_soldered)
def _part(
comp: Any, trace: Any, designator: str, orientations: Mapping[str, float]
) -> Part:
if not trace.transform or not comp.transform:
raise ExportError(
f"{trace.path} ({designator}) is soldered but has no placement; "
"a component with nowhere to go cannot be assembled"
)
placement = trace.transform * comp.transform
side = placement.side if isinstance(placement, Placement) else Side.Top
lcsc = _lcsc(comp, trace.path)
footprint, guessed = _footprint(comp, lcsc, trace.path, designator)
correction, defaulted = _correction(lcsc, orientations)
pads = [pad for _, pad in visit(comp, Pad)]
return Part(
designator=designator,
comment=_comment(comp),
footprint=footprint,
lcsc=lcsc.partnumber if lcsc else None,
x=placement.translation[0],
y=placement.translation[1],
rotation=rotation(placement.rotation + correction, side),
side=side,
through_hole=any(list(extract(pad, Cutout)) for pad in pads),
footprint_guessed=guessed,
orientation_default=defaulted,
)
def _correction(
lcsc: LCSCPart | None, orientations: Mapping[str, float]
) -> tuple[float, bool]:
"""The orientation correction for a part, and whether it was defaulted.
The lock file outranks the design. An `LCSCPart(orientation=...)` may have
come from a part library rather than from the user, and a library that
states the wrong orientation is otherwise uncorrectable from the design;
the lock file is the place a user can say so, so it wins and the
disagreement is reported rather than resolved silently.
"""
if lcsc is None:
return DEFAULT_ORIENTATION, True
recorded = orientations.get(lcsc.partnumber)
if recorded is not None:
if lcsc.orientation is not None and recorded != lcsc.orientation:
logger.info(
"%s is recorded at %g degrees in %s, overriding the %g "
"degrees its LCSCPart states",
lcsc.partnumber,
recorded,
lock.BASENAME,
lcsc.orientation,
)
return recorded, False
if lcsc.orientation is not None:
return lcsc.orientation, False
return DEFAULT_ORIENTATION, True
[docs]
def rotation(degrees: float, side: Side) -> float:
"""The pick-and-place rotation for a placement, counter-clockwise.
Top side is the placement rotation. Bottom side is its negation, which is
the conversion between JITX's frame and the one JLCPCB's recommended KiCad
plugin emits: JITX composes a placement as `R(r) . diag(sx, sy)` and a
bottom placement sets `sx = -1`, so a bottom part is `R(r) . diag(-1, 1)`.
The plugin's frame mirrors about the other axis, `R(t) . diag(1, -1)`, and
`diag(-1, 1) = R(180) . diag(1, -1)`, so `t = r + 180`. The plugin writes
`180 - t`, which is `-r`.
This is emphatically not `180 - r`: the two differ by 180 degrees at every
angle. See plans/jlcpcb-export-plan.md section 5.4.
"""
value = -degrees if side == Side.Bottom else degrees
return value % 360.0
def _designator(comp: Any, path: Any) -> str:
"""The reference designator, which both fab files are matched on.
Unlike ODB++, where the name is an internal handle, this is the key
JLCPCB matches the two files on and a human reads off the board, so there
is no useful fallback.
"""
designator = comp.reference_designator
if not designator:
raise ExportError(
f"{path} has no reference designator; JLCPCB matches the BOM and "
"pick-and-place files on it"
)
return str(designator)
def _lcsc(comp: Any, path: Any) -> LCSCPart | None:
"""The component's `LCSCPart`, if it has exactly one, named by its path."""
try:
return part_of(comp)
except AmbiguousPart as exc:
raise ExportError(f"{path} {exc}") from exc
def _comment(comp: Any) -> str:
"""The BOM `Comment`: what identifies the part to a human and the matcher."""
if comp.mpn:
return str(comp.mpn)
rendered = render(comp.value)
if rendered:
return rendered
return typeof(comp).__name__
def _footprint(
comp: Any, lcsc: LCSCPart | None, path: Any, designator: str
) -> tuple[str, bool]:
"""A package code for the BOM, and whether it had to be guessed.
The chain fails rather than inventing a value: a wrong package is one of
JLCPCB's documented matching failures, and an empty cell or a plausible
but wrong name pushes the error to upload time where the context to fix it
is gone.
"""
if lcsc is not None and lcsc.footprint:
return lcsc.footprint, False
landpatterns = list(decompose(comp, Landpattern))
case = _case_name(landpatterns)
if case is not None:
return case, False
catalogue = _catalogue_package(comp)
if catalogue is not None:
return catalogue, True
if len(landpatterns) == 1:
return typeof(landpatterns[0]).__name__, True
raise ExportError(
f"{path} ({designator}) has no footprint that can be determined "
"reliably; give it LCSCPart(footprint=...)"
)
def _catalogue_package(comp: Any) -> str | None:
"""EasyEDA's package name, when the landpattern came from the catalogue.
Verbose next to a curated package code, and still a guess, but it names
the package the part was drawn as rather than the class the builder
happened to use.
"""
from ..landpattern import LCSCLandpattern
for container in decompose(comp, LCSCLandpattern):
if container.package:
return str(container.package)
return None
def _case_name(landpatterns: list[Any]) -> str | None:
"""The canonical imperial case code of a two-pin SMT landpattern.
PRELIMINARY on two counts, both reaching into `jitxlib.landpatterns`
privates: `_case_name` on the generator, and `_ALIASES` to normalise it.
`SMT_CHIP_DEFS` is keyed by imperial name and by aliases, so a `case_name`
may legitimately be "1005m" or "Wide 0402", and the obvious normalisation
does not work because the alias rows are built with
`replace(row, name=alias)`, making `.name` the alias again. The upstream
ask is a single `canonical_case_name(landpattern)`, which would retire
both reaches at once.
"""
from jitxlib.landpatterns.twopin.smt import SMTBase
for landpattern in landpatterns:
if isinstance(landpattern, SMTBase):
name = getattr(landpattern, "_case_name", None)
if name:
return _canonical_case(str(name))
return None
def _canonical_case(name: str) -> str:
from jitxlib.landpatterns.twopin.SMT_table import _ALIASES
for canonical, aliases in _ALIASES.items():
if name == canonical or name in aliases:
return canonical
return name