Metadata-Version: 2.5
Name: cadbuildr-electronics
Version: 0.2.0
Summary: 3D models of common PCB components plus a footprint-driven framework for assembling them into boards
Author: CADbuildr Team
License-File: LICENSE
Requires-Python: <4.0.0,>=3.10.0
Requires-Dist: cadbuildr-foundation<0.4.0,>=0.3.0
Requires-Dist: cadbuildr-stdlib<0.6.0,>=0.5.0
Description-Content-Type: text/markdown

# cadbuildr.electronics

## Summary

3D models of common PCB components (passives, LEDs, headers and sockets, USB-A/Micro-B/C,
HDMI, microSD, JST PH/XH/SH/GH, FPC, DF40, RJ45, barrel jacks, ICs in DIP/SOIC/QFP/QFN/SOT/TO
packages, RF modules, switches, displays) plus a footprint-driven framework: one `place(...)`
call drills the land pattern into the board and seats the 3D body, so holes and bodies can never
drift apart. Ready boards (Arduino incl. Nano ESP32, Raspberry Pi 5 / Zero 2 W / Pico W / CM4 +
IO board, ESP32-S3 DevKitC-1, STM32 Nucleo-64, Teensy 4.1, Feather, Pololu carriers, STEMMA QT /
Qwiic breakouts, OLED / TFT / LCD modules) take their outline, holes and connector positions
from the vendors' mechanical drawings (cited in each module), expose their mounting holes as
`ScrewHole` interfaces and their connectors / display windows as `ConnectorPort`s, so
standoffs, stdlib screws and the generated enclosure tray `connect` to them. Pololu drive parts
(micro metal gearmotors, brackets, wheels, ball casters) connect through `Shaft` / `Bore`.
Every item is a library configurable (manifest + widgets).

## Tags

cad, python, pcb, electronics, footprint, assembly

## Status

yellow

## Guidelines

- A component owns its footprint: define pads once in `footprint()`, never on the board.
- Dimensions are millimetres; through-hole pads use `drill > 0`, SMD lands `drill == 0`.
- The board is the only thing that drills holes (via `PCB.place` / `mounting_hole`).
- Build bodies from `Sketch` + `Extrusion` helpers in `_solids.py` to keep DAGs kernel-agnostic.
- Place with anchors and joints (`place_<ref>` on the board, `seat` on the part); never hand-build transforms.
- Every public part / board / module is a `@part` / `@assembly` with typed inputs (`OneOf` tables
  from `constants.py` or `data/packages.json`, `Num` with bounds) and a docstring `Args:` section.
- Interface names are a contract other libraries build on (enclosures, robotics): `mount_<n>` /
  `mount_<n>_under` (`ScrewHole`), `top` / `bottom` (`PlaneFace`), `port_<ref>` (`ConnectorPort`).
  Add, never rename.
- Bad input raises a named `ElectronicsError` subclass whose message names the fix.
- Agent/user-facing usage lives in [`SKILL.md`](SKILL.md).
- Ready boards take outline, holes, connector positions / heights from the vendor's mechanical
  drawing, cited by URL in the module docstring; anything read off a drawing rather than
  dimensioned on it, or guessed, is listed under `Estimated:`. The population between the
  connectors is stylised (stand-in packages), not pin-accurate.
- Hollow parts are hollow (connector mouths, header sockets, JST housings); outlines use true
  arcs (`outline.rounded_rect`, `CompactPolygon`), not chamfers.
- Checks go in a `__checks__` hook (`PCB.layout_issues`: off-board parts, collisions, mid-mount
  board thickness); never override `check()`.
- Never commit vendor STEP / CAD files or copied drawings; cite the URL instead.

## Install / develop

```bash
pip install cadbuildr-electronics      # from PyPI
# or, working from a clone:
uv sync && uv run pytest               # run the test suite
```

## Quick start

```python
from cadbuildr.foundation import show
from cadbuildr.electronics import BoardInEnclosure, GearmotorWheel
from cadbuildr.electronics.boards import RaspberryPi5, StemmaQTBreakout

pi = RaspberryPi5()                    # real outline, 58 x 49 holes, edge ports
print(sorted(pi.ports))                # port_J-ETH, port_J-HDMI0, port_J-PWR, ...
box = BoardInEnclosure(board="RaspberryPi5", screws=False)
assert box.check() == []               # every cutout lines up with its port
show(GearmotorWheel("100:1", "60x8"))  # Pololu motor + bracket + wheel
```

Building your own board:

```python
from cadbuildr.foundation import show
from cadbuildr.electronics import PCB, PinHeader, Resistor, LED

pcb = PCB(50, 24, color="blue")
pcb.place(PinHeader(positions=2), ref="J1", x=-20, y=0)   # drills board + seats body
pcb.place(Resistor("220"),        ref="R1", x=-2,  y=0)
pcb.place(LED("red"),             ref="D1", x=18,  y=0)
show(pcb)
```

Declarative form (the "standard format" of components + placements):

```python
from cadbuildr.electronics import PCB, Placement, Resistor, LED, PinHeader

PCB.from_placements(50, 24, [
    Placement(PinHeader(positions=2), "J1", -20, 0),
    Placement(Resistor("220"),        "R1",  -2, 0),
    Placement(LED("red"),             "D1",  18, 0, rotation=0),
])
```

## Scaling to catalog size

Writing a class per part doesn't scale; Digi-Key's ~18 M part numbers collapse
onto ~15 k footprints and a few dozen **package families**, because geometry is
a pure function of `Package/Case + Mounting + pins + pitch`, never the
electrical value. So there's a **data-driven catalog layer** (`catalog/`,
`families/`, `data/`):

```
 K family generators  ◀──  M packages (data)  ◀──  N parts (data)
   families/                data/packages.json       data/parts.csv
```

```python
from cadbuildr.electronics import Catalog, PCB
cat = Catalog.load()
pcb = PCB(40, 30)
pcb.place(cat.build_part("ATMEGA328P-AU"), "U1", 0, 0)  # MPN → TQFP-32, generated
pcb.place(cat.build_part("NE555P"),        "U2", 12, -8)  # MPN → DIP-8, generated

# ingest a Digi-Key Package/Case string straight to geometry:
cat.resolve_package_case("0805 (2012 Metric)", mounting="Surface Mount")  # → R_0805
```

Adding a part is one CSV row; a new package is one JSON row; a new family is one
generator class. Land patterns are generated to **IPC-7351B**. Full design in
[`docs/SCALING.md`](docs/SCALING.md). Generated parts on a board:

![generated parts](docs/gallery/catalog_generated.png)

## How the dual-action works

```
pcb.place(part, "R1", x, y, rotation, side)
  └─▶ board anchor  place_R1  (x, y, θ on the top or bottom face)
        ├─▶ PartModifier: pad anchors = place_R1.offset(pad) → copper lands + Hole drills
        └─▶ RigidJoint(place_R1 → part.seat), in Components   → the 3D body
```

One placement pose drives both the drills and the body, as one foundation
`Connection`, so holes always line up — at any rotation, on either side
(bottom-side parts are flipped over their X axis, which mirrors the land
pattern).

- **`Footprint` / `Pad`** (`footprint.py`) — the single source of truth for a
  part's pads, in the part's own frame. `seat_anchor(part)` gives any part
  its `seat` anchor.
- **`ElectronicComponent`** — base class for parts; subclasses build geometry
  and implement `footprint()`. Any `Part` can instead be decorated with
  `@footprint(...)`.
- **`PCBBoard`** (`board.py`) — the FR-4 slab with `top` / `bottom` anchors;
  `add_placement_anchor`, `footprint_operations`, `drill_operations`, `drill`.
- **`PCB`** (`pcb.py`) — the `Assembly` template that wires the two together
  and exposes `place`, `from_placements`, `mounting_holes_rect` and `bom`.

Rendered in the CADbuildr Prototype from [`examples/two_sided.py`](examples/two_sided.py) (iso · top · bottom). The bottom view is mirrored, as seen from below:

![two-sided board: top and bottom parts at several rotations](docs/gallery/two_sided.png)

![view sequence](docs/gallery/two_sided_views.gif)

## What's in the box

| Family | Parts |
|--------|-------|
| Passives | `Resistor` (E12 values), `ResistorSMD`, `CeramicCapacitor`, `ElectrolyticCapacitor` (standard cans), `ChipPackage` (0402–2512 R/C, SOD-123, SMA) |
| Semiconductors | `LED`, `Diode` (DO-35/DO-41/DO-201AD), `SOTPackage` (SOT-23-3/5/6, SOT-223), `TOPackage` (TO-92, TO-220 with heatsink `ScrewHole`) |
| ICs | `DIP`, `SOIC`, `QFP`, `DualInlinePackage`, `SmallOutlinePackage` (SOIC/TSSOP/MSOP/SSOP), `QuadFlatPackage`, `QFNPackage` (QFN/DFN + EP), `CatalogPart` (by MPN) |
| Connectors | `PinHeader` / `FemaleHeader` (WR-PHD geometry, hollow sockets), `ScrewTerminal`, `USBTypeA` (single / dual stacked), `USBMicroB`, `USBTypeC` (top / mid mount, Type-C spec shell), `HDMIConnector`, `MicroSDSocket`, `JSTConnector` (PH / XH / SH / GH, top / side entry), `FPCConnector`, `BoardToBoardConnector` (Hirose DF40), `RJ45`, `BarrelJack` (5.5 x 2.1 / 2.5) |
| Electromechanical | `Crystal`, `TactileButton` (6x6 / 12x12), `SlideSwitch`, `Buzzer`, `Trimmer` |
| RF modules | `RFModule` (ESP32-S3-WROOM-1, ESP32-WROOM-32E, NORA-W106) |
| Displays | `DisplayPanel` (0.91" / 0.96" / 1.3" OLED, 2.4" / 2.8" TFT, 1602/2004 LCD; `screen` = active area) |
| Hardware | `Standoff` (M2/M2.5/M3, F-F / M-F) |
| Boards | `ArduinoUno`, `ArduinoNano`, `ArduinoNanoESP32`, `ArduinoMega`, `RaspberryPi`, `RaspberryPi5`, `RaspberryPiZero`, `RaspberryPiZero2W`, `RaspberryPiPico` (Pico / Pico W, castellated), `ComputeModule4`, `CM4IOBoard`, `ESP32DevKit`, `ESP32S3DevKitC1`, `Nucleo64`, `Teensy41`, `Feather`, `FeatherWing` |
| Modules | `OledModule`, `CharacterLCD`, `TFTModule` (2.8" ILI9341), `StepperDriverCarrier` (A4988 / DRV8825), `MotorDriverCarrier` (TB6612FNG / DRV8833), `VoltageRegulator` (S7V8F5 / D24V25F5 / D24V50F5), `StemmaQTBreakout`, `QwiicBreakout` |
| Pololu drive | `MicroMetalGearmotor`, `GearmotorBracket`, `PololuWheel` (32x7 .. 90x10), `BallCaster` (3/8", 1/2"), `GearmotorWheel` |
| Enclosures | `PCBEnclosure` (tray from mounts + ports), `BoardInEnclosure` |
| Showcase | `MacroKeypad` |

## Interfaces: connect hardware and enclosures to a board

```python
from cadbuildr.foundation import Assembly
from cadbuildr.stdlib.fasteners.screws_and_bolts.din912_part import DIN912Screw
from cadbuildr.electronics import Standoff, BoardInEnclosure
from cadbuildr.electronics.boards import RaspberryPi

pi = RaspberryPi()
asm = Assembly()
asm.ground(pi)
asm.connect_all(lambda: Standoff("M2.5", 11, "male-female"), pi.group("mount_under"), own="top")
asm.connect_all(lambda: DIN912Screw("M2.5", 6, with_thread=False), pi.group("mount"))
assert asm.check() == []

box = BoardInEnclosure(board="ArduinoUno")   # tray bosses + USB / barrel cutouts, loop-checked
```

| Interface on a `PCB` | Type | Group |
|---|---|---|
| `mount_<n>` / `mount_<n>_under` | `ScrewHole(size, depth, drilled=True)` (+Z up / down) | `mount` / `mount_under` |
| `top` / `bottom` | `PlaneFace` | — |
| `port_<ref>` | `ConnectorPort(kind, width, height)`, +Z out of the mouth | `ports` |

`ConnectorPort` / `PanelCutout` and `HeaderPins` / `HeaderSocket` (with their mate rules) live in
`cadbuildr.electronics.interfaces`. Examples: [`examples/enclosure.py`](examples/enclosure.py),
[`examples/pi_on_standoffs.py`](examples/pi_on_standoffs.py),
[`examples/robot_base.py`](examples/robot_base.py).

A display module's `port_DS1` is its **active area** (kind `display-<panel>`), so a lid
window cut to it shows exactly the pixels. Mid-mount parts (`USBTypeC("mid")`) cut their own
board slot and `PCB.check()` flags a board of the wrong thickness.

## Library manifest

```bash
python -m cadbuildr.foundation.library manifest cadbuildr.electronics
```

lists every item (toolbar tab *Electronics*: Boards, Modules, Passives, Semiconductors, ICs,
Connectors, Electromechanical, Displays, Hardware, Enclosures, PCB, Catalog, Showcase) with its
inputs, configurations (package / value tables become named configurations), anchors and
interfaces.

For the standard names (KiCad / JEDEC / IPC), canonical dimensions, and
authoritative + license-clean 3D-model sources behind each part, see
[`docs/COMPONENT_REFERENCE.md`](docs/COMPONENT_REFERENCE.md).

## Visual verification

The library is checked by actually *rendering* it. `scripts/render.py` sends a
part's DAG to a local **kernel-api** (the same replicad/OpenCascade kernel the
web viewer uses — no GPU, no display, no cloud auth) and rasterizes the colored
mesh to a PNG. Full setup in
[`docs/VISUAL_VERIFICATION.md`](docs/VISUAL_VERIFICATION.md):

```bash
# kernel-api running locally on :8087 (see the doc), then:
python scripts/render.py --target arduino -o /tmp/arduino.png
python scripts/render.py --gallery        -o /tmp/pcb_gallery
```

Checked-in reference renders (regenerate any time):

![component gallery](docs/gallery/components.png)

| Arduino Uno | Raspberry Pi |
|---|---|
| ![Arduino](docs/gallery/arduino_uno.png) | ![Raspberry Pi](docs/gallery/raspberry_pi.png) |

## Dependencies

### Upstream

- cadbuildr-foundation
- cadbuildr-stdlib

### Downstream

- cadbuildr-projects-sesame-robot (ESP32 board)
- cadbuildr-enclosures (consumes `bottom`, `mount_<n>[_under]`, `port_<ref>`; the
  `TactileButton` `actuator` port)
- cadbuildr-robotics (ESP32 boards, motor drivers, Pololu drive parts)

## GitHub Pages demo (Vite + R3F)

A static browser demo (`kernel-api` + Pyodide) lives in `github-io/`. It builds
PCB examples in-browser and renders them via
[`@cadbuildr/sdk-react`](https://www.npmjs.com/package/@cadbuildr/sdk-react):

```bash
uv build                                   # produce the wheel for micropip
cd github-io && npm install && npm run dev # http://localhost:3008
```

See `github-io/README.md` for auth, the wheel pipeline, and the GitHub Pages
deploy workflow.
