Source code for jitxlib.jlcpcb.export.bom

"""The bill of materials JLCPCB's assembly matcher reads."""

from __future__ import annotations

import re
from collections import defaultdict
from dataclasses import dataclass
from logging import getLogger
from pathlib import Path

from . import _csv
from .components import ExportError, Part

logger = getLogger(__name__)

HEADER = ("Comment", "Designator", "Footprint", "Quantity", "JLCPCB Part #")

MAX_DESIGNATORS = 200
"""JLCPCB caps one BOM line at 200 reference designators."""

_PREFIX = re.compile(r"^([A-Za-z]*)")
_DIGITS = re.compile(r"(\d+)")


[docs] @dataclass class Line: """One BOM row: a group of interchangeable parts.""" comment: str designators: list[str] footprint: str lcsc: str | None
[docs] def row(self) -> tuple[str, str, str, int, str]: return ( self.comment, ", ".join(self.designators), self.footprint, len(self.designators), self.lcsc or "", )
[docs] def write(path: Path, parts: list[Part]) -> list[Line]: """Write the BOM and return the lines written.""" check_designators(parts) lines = group(parts) _csv.write(path, HEADER, [line.row() for line in lines]) _report(lines) return lines
[docs] def group(parts: list[Part]) -> list[Line]: """Collect parts into BOM lines, splitting at the designator cap. The key carries the designator prefix because JLCPCB rejects a row holding more than one component type, which they determine by prefix: without it a jumper and a resistor sharing a 0 ohm part number would merge. """ groups: dict[tuple[str, str, str, str], list[Part]] = defaultdict(list) for part in parts: key = (prefix(part.designator), part.lcsc or "", part.comment, part.footprint) groups[key].append(part) lines: list[Line] = [] for key in sorted(groups): members = sorted(groups[key], key=lambda p: natural(p.designator)) first = members[0] for chunk in _chunks([p.designator for p in members], MAX_DESIGNATORS): lines.append( Line( comment=first.comment, designators=chunk, footprint=first.footprint, lcsc=first.lcsc, ) ) return lines
[docs] def check_designators(parts: list[Part]) -> None: """Refuse designators that collide once JLCPCB uppercases them. Their BOM page says every letter is capitalised for production, so `r1` and `R1` are one part there however distinct they are in the design. """ seen: dict[str, str] = {} for part in parts: folded = part.designator.upper() if folded in seen: raise ExportError( f"designators {seen[folded]!r} and {part.designator!r} differ " "only by case; JLCPCB capitalises them for production, so they " "would become one part" ) seen[folded] = part.designator
[docs] def prefix(designator: str) -> str: """The alphabetic head of a designator: `R` for `R12`.""" match = _PREFIX.match(designator) return match.group(1).upper() if match else ""
[docs] def natural(designator: str) -> tuple[object, ...]: """Sort key placing `C2` before `C10`.""" return tuple( int(part) if part.isdigit() else part for part in _DIGITS.split(designator) )
def _chunks(items: list[str], size: int) -> list[list[str]]: return [items[i : i + size] for i in range(0, len(items), size)] def _report(lines: list[Line]) -> None: unmatched = [line for line in lines if not line.lcsc] if unmatched: logger.info( "%d BOM line(s) have no LCSC part number and will need matching by " "hand at upload", len(unmatched), ) for line in lines: for field in (line.comment, line.footprint): if _csv.non_ascii(field): logger.info( "BOM field %r is not ASCII; JLCPCB's form may not handle it", field, )