boardwright 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
boardwright/circuit.py ADDED
@@ -0,0 +1,208 @@
1
+ """Describe a circuit as parts + pin->net maps, and emit a KiCad schematic.
2
+
3
+ Crude on purpose: every pin gets a short wire stub and a net label (or a
4
+ no-connect flag), so connectivity is exactly what the dict says and never
5
+ depends on wire geometry. Readable enough for review, correct by construction,
6
+ and KiCad's ERC + netlist export check it anyway.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+
15
+ from kicad_tools.schematic.models.schematic import Schematic
16
+ from kicad_tools.schematic.models.symbol import SymbolDef
17
+
18
+ GRID = 2.54
19
+ STUB = 2 * GRID
20
+
21
+
22
+ @dataclass
23
+ class Part:
24
+ ref: str
25
+ lib_id: str
26
+ value: str
27
+ footprint: str
28
+ pins: dict[str, str | None] # pin number -> net name, None = no-connect
29
+ unit: int = 1
30
+ bom: bool = True # False for mounting holes etc. (footprint is exclude_from_bom)
31
+
32
+
33
+ @dataclass
34
+ class Circuit:
35
+ title: str
36
+ parts: list[Part] = field(default_factory=list)
37
+ # nets that need a PWR_FLAG because no power_out pin drives them
38
+ # (e.g. a rail entering from a connector). Auto-detected if left empty.
39
+ pwr_flags: list[str] | None = None
40
+ # filled by write_schematic: (ref, pad, KiCad's "unconnected-(...)" net name)
41
+ nc_nets: list[tuple[str, str, str]] = field(default_factory=list)
42
+ # schematic grouping: lists of refs drawn together (functional blocks)
43
+ groups: list[list[str]] | None = None
44
+
45
+ def add(self, ref, lib_id, value, footprint, pins, unit=1, bom=True) -> Part:
46
+ p = Part(ref, lib_id, value, footprint, {str(k): v for k, v in pins.items()}, unit, bom)
47
+ self.parts.append(p)
48
+ return p
49
+
50
+ def nets(self) -> dict[str, list[tuple[str, str]]]:
51
+ out: dict[str, list[tuple[str, str]]] = {}
52
+ for p in self.parts:
53
+ for pin, net in p.pins.items():
54
+ if net:
55
+ out.setdefault(net, []).append((p.ref, pin))
56
+ return out
57
+
58
+
59
+ def _outward(angle_into_body: float) -> tuple[float, float]:
60
+ a = math.radians(angle_into_body + 180)
61
+ return round(math.cos(a)), -round(math.sin(a)) # lib y-up -> sheet y-down
62
+
63
+
64
+ def _label_rot(dx: float, dy: float) -> int:
65
+ return {(1, 0): 0, (-1, 0): 180, (0, -1): 90, (0, 1): 270}[(dx, dy)]
66
+
67
+
68
+ PAPERS = [("A4", 297, 210), ("A3", 420, 297), ("A2", 594, 420), ("A1", 841, 594), ("A0", 1189, 841)]
69
+ MARGIN, TITLE_H, GAP = 15.0, 40.0, 6 * GRID
70
+
71
+
72
+ def _snap(v: float) -> float:
73
+ return round(v / GRID) * GRID
74
+
75
+
76
+ def _rot_of(p: Part, sd) -> int:
77
+ """Draw vertical 2-pin parts (R, C) horizontally: labels then sit on one row."""
78
+ pins = [q for q in sd.pins if sd.get_pin_unit(q.number) in (0, p.unit)]
79
+ if len(pins) == 2 and all(q.angle in (90, 270) for q in pins):
80
+ return 90
81
+ return 0
82
+
83
+
84
+ def _rot_pt(x: float, y: float, r: int) -> tuple[float, float]:
85
+ """Rotate a sheet-space (y-down) offset by r degrees CCW as KiCad displays it."""
86
+ a = math.radians(r)
87
+ return round(x * math.cos(a) + y * math.sin(a), 4), round(-x * math.sin(a) + y * math.cos(a), 4)
88
+
89
+
90
+ def _extent(p: Part) -> tuple[float, float, float, float]:
91
+ """Sheet-space extent of a part relative to its origin, incl. stubs + labels."""
92
+ sd = SymbolDef.from_library(p.lib_id)
93
+ r = _rot_of(p, sd)
94
+ xs, ys = [-5.0, 5.0], [-5.0, 5.0]
95
+ for pin in sd.pins:
96
+ if sd.get_pin_unit(pin.number) not in (0, p.unit) or pin.number not in p.pins:
97
+ continue
98
+ px, py = _rot_pt(pin.x, -pin.y, r)
99
+ net = p.pins[pin.number]
100
+ dx, dy = _outward(pin.angle + r)
101
+ L = 0 if net is None else STUB + 0.85 * len(net) + 3
102
+ xs += [px, px + dx * L]
103
+ ys += [py, py + dy * L]
104
+ pad = 4.0
105
+ return min(xs) - pad, min(ys) - pad, max(xs) + pad, max(ys) + pad
106
+
107
+
108
+ def _pack(c: Circuit, items: list[tuple[str, tuple]], width: float) -> tuple[dict, float, float]:
109
+ """Shelf-pack each group; inside a shelf, short parts stack in columns.
110
+
111
+ Returns key -> origin offset, used width, used height.
112
+ """
113
+ groups = [list(g) for g in (c.groups or [])]
114
+ grouped = {r for g in groups for r in g}
115
+ rest = [k for k, _ in items if k not in grouped]
116
+ if rest:
117
+ groups.append(rest)
118
+ ext = dict(items)
119
+ size = {k: (e[2] - e[0], e[3] - e[1]) for k, e in ext.items()}
120
+ pos, y, used_w = {}, 0.0, 0.0
121
+ g2 = GAP / 2
122
+ for g in groups:
123
+ keys = sorted(g, key=lambda k: -size[k][1])
124
+ x, row_h, col_x, col_y, col_w = 0.0, None, 0.0, 0.0, 0.0
125
+ for key in keys:
126
+ w, h = size[key]
127
+ if row_h is None:
128
+ row_h = h
129
+ if col_y > 0 and col_y + h <= row_h: # stack in current column
130
+ px, py = col_x, col_y
131
+ col_w = max(col_w, w)
132
+ else: # new column
133
+ col_x = x if col_y == 0 else col_x + col_w + g2
134
+ if col_x > 0 and col_x + w > width: # new shelf
135
+ y += row_h + g2
136
+ row_h, col_x = h, 0.0
137
+ px, py, col_w = col_x, 0.0, w
138
+ x0, y0 = ext[key][0], ext[key][1]
139
+ pos[key] = (px - x0, y + py - y0)
140
+ col_y = py + h + g2
141
+ x = col_x + col_w + g2
142
+ used_w = max(used_w, col_x + col_w)
143
+ y += (row_h or 0) + GAP
144
+ return pos, used_w, y
145
+
146
+
147
+ def write_schematic(c: Circuit, path: Path) -> dict:
148
+ c.nc_nets.clear()
149
+ pin_types: dict[str, set[str]] = {}
150
+ for p in c.parts:
151
+ for _num, net in p.pins.items():
152
+ if net:
153
+ pin_types.setdefault(net, set())
154
+ items = [(p.ref, _extent(p)) for p in c.parts]
155
+ for paper, pw, ph in PAPERS: # noqa: B007 (used after the loop)
156
+ pos, uw, uh = _pack(c, items, pw - 2 * MARGIN)
157
+ if uh <= ph - 2 * MARGIN - TITLE_H:
158
+ break
159
+ sch = Schematic(title=c.title, paper=paper)
160
+ for p in c.parts:
161
+ ox, oy = pos[p.ref]
162
+ r = _rot_of(p, SymbolDef.from_library(p.lib_id))
163
+ s = sch.add_symbol(p.lib_id, x=_snap(MARGIN + ox), y=_snap(MARGIN + oy), ref=p.ref,
164
+ value=p.value, footprint=p.footprint, unit=p.unit, rotation=r)
165
+ defined = {}
166
+ for pin in s.symbol_def.pins:
167
+ if p.unit and s.symbol_def.get_pin_unit(pin.number) not in (0, p.unit):
168
+ continue
169
+ defined[pin.number] = pin
170
+ missing = set(p.pins) - set(defined)
171
+ if missing:
172
+ raise ValueError(f"{p.ref} ({p.lib_id}) has no pins {sorted(missing)}")
173
+ unassigned = set(defined) - set(p.pins)
174
+ if unassigned:
175
+ raise ValueError(f"{p.ref}: pins {sorted(unassigned)} not assigned (use None for NC)")
176
+ for num, net in p.pins.items():
177
+ pin = defined[num]
178
+ px, py = s.pin_position(num)
179
+ if net is None:
180
+ sch.add_no_connect(px, py)
181
+ c.nc_nets.append((p.ref, num, f"unconnected-({p.ref}-{pin.name}-Pad{num})"))
182
+ continue
183
+ dx, dy = _outward(pin.angle + r)
184
+ ex, ey = px + dx * STUB, py + dy * STUB
185
+ sch.add_wire((px, py), (ex, ey))
186
+ sch.add_global_label(net, ex, ey, rotation=_label_rot(dx, dy), snap=False)
187
+ pin_types[net].add(pin.pin_type)
188
+
189
+ flags = c.pwr_flags
190
+ if flags is None:
191
+ flags = [n for n, t in pin_types.items() if "power_in" in t and "power_out" not in t]
192
+ fx, fy = _snap(MARGIN + uw + 4 * GRID), _snap(MARGIN + 4 * GRID)
193
+ if fx > pw - MARGIN - 10:
194
+ fx, fy = _snap(MARGIN + 4 * GRID), _snap(MARGIN + uh)
195
+ for i, net in enumerate(sorted(flags)):
196
+ x = fx + i * 8 * GRID
197
+ sch.add_pwr_flag(x, fy)
198
+ sch.add_wire((x, fy), (x, fy + STUB))
199
+ sch.add_global_label(net, x, fy + STUB, rotation=270, snap=False)
200
+ sch.write(str(path), auto_size_paper=False)
201
+ nobom = {p.ref for p in c.parts if not p.bom}
202
+ if nobom:
203
+ blocks = Path(path).read_text().split("\n\t(symbol\n")
204
+ for i, b in enumerate(blocks):
205
+ if any(f'(property "Reference" "{r}"' in b for r in nobom):
206
+ blocks[i] = b.replace("(in_bom yes)", "(in_bom no)", 1)
207
+ Path(path).write_text("\n\t(symbol\n".join(blocks))
208
+ return {"pwr_flags": sorted(flags), "nets": len(c.nets()), "paper": paper}
boardwright/cli.py ADDED
@@ -0,0 +1,99 @@
1
+ """boardwright: generate and edit KiCad boards from a short Python description.
2
+
3
+ New board (a directory holding board.py):
4
+ boardwright place DIR place parts, write an instant preview with ratsnest
5
+ boardwright gen DIR schematic, board, routing, pours
6
+ boardwright check DIR [--quick] KiCad gate: ERC, DRC, netlist, fab outputs, plots
7
+ boardwright verify DIR read the gate's reports and the engineering review
8
+ boardwright pads DIR every pad with its net and position
9
+
10
+ Any board:
11
+ boardwright existing DIR STEP ... inspect, baseline, edit in place, reroute (see `existing`)
12
+ boardwright sch DIR CMD ... edit a schematic in place (see `sch`)
13
+ boardwright review PCB [SPEC.py] engineering review of any board file
14
+ boardwright preview PCB [OUT.png] placement view with ratsnest, no KiCad needed
15
+ boardwright edits SPEC.py PCB OUT.json [PRO] a plain list of board edits
16
+ boardwright selection SEL PCB describe text copied from KiCad's board editor
17
+ boardwright live CMD ... read and edit the board open in KiCad (needs [live])
18
+
19
+ Lookups:
20
+ boardwright pins LIB:SYMBOL [LIB:FOOTPRINT] [--libs DIR ...]
21
+ boardwright impedance [STACKUP [Z | Z W]]
22
+ boardwright doctor what this machine has for each step
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import importlib
28
+ import importlib.metadata
29
+ import shutil
30
+ import sys
31
+
32
+ from . import __version__
33
+
34
+ _BUILD = {"gen", "place", "verify", "pads"}
35
+ _MODULES = {
36
+ "check": "check", "existing": "existing", "sch": "sch", "review": "review",
37
+ "preview": "preview", "edits": "edits", "selection": "selection", "live": "live",
38
+ "pins": "pins", "impedance": "si",
39
+ }
40
+ _NEEDS_LIBS = {"gen", "place", "pins", "sch"}
41
+
42
+
43
+ def doctor() -> int:
44
+ from . import env
45
+
46
+ ok = True
47
+
48
+ def row(name: str, fn) -> None:
49
+ nonlocal ok
50
+ try:
51
+ print(f"ok {name:<12} {fn()}")
52
+ except (SystemExit, Exception) as e:
53
+ ok = False
54
+ print(f"MISS {name:<12} {e}")
55
+
56
+ row("symbols", lambda: env.libraries()[0])
57
+ row("footprints", lambda: env.libraries()[1])
58
+ row("kicad-cli", lambda: " ".join(env.kicad_cli()))
59
+ row("freerouting", lambda: " ".join(env.freerouting()))
60
+ row("kicad-tools", lambda: importlib.metadata.version("kicad-tools"))
61
+ try:
62
+ print(f"ok {'kicad-python':<12} {importlib.metadata.version('kicad-python')} (live)")
63
+ except importlib.metadata.PackageNotFoundError:
64
+ print(f"- {'kicad-python':<12} not installed; `live` needs boardwright[live]")
65
+ rsvg = shutil.which("rsvg-convert")
66
+ print(f"{'ok' if rsvg else '-':<5} {'rsvg-convert':<12} {rsvg or 'not found; previews stay SVG'}")
67
+ return 0 if ok else 1
68
+
69
+
70
+ def main(argv: list[str] | None = None) -> int:
71
+ argv = sys.argv[1:] if argv is None else argv
72
+ if not argv or argv[0] in ("-h", "--help", "help"):
73
+ print(__doc__)
74
+ return 0
75
+ cmd, rest = argv[0], argv[1:]
76
+ if cmd == "--version":
77
+ print(f"boardwright {__version__}")
78
+ return 0
79
+ if cmd == "doctor":
80
+ return doctor()
81
+ if cmd in _NEEDS_LIBS:
82
+ from . import env
83
+
84
+ env.use_libraries()
85
+ if cmd in _BUILD:
86
+ if not rest:
87
+ raise SystemExit(f"usage: boardwright {cmd} DIR")
88
+ from . import build
89
+
90
+ return build.cli([rest[0], cmd])
91
+ if cmd in _MODULES:
92
+ mod = importlib.import_module(f".{_MODULES[cmd]}", __package__)
93
+ return mod.cli(rest) or 0
94
+ print(f"unknown command {cmd!r}\n{__doc__}", file=sys.stderr)
95
+ return 2
96
+
97
+
98
+ if __name__ == "__main__":
99
+ sys.exit(main())
boardwright/copper.py ADDED
@@ -0,0 +1,211 @@
1
+ """Hand-placed copper and silk, appended to the .kicad_pcb as text.
2
+
3
+ Everything takes board-relative mm (0,0 = top-left of the outline), like PLACE.
4
+ Used for what an autorouter does badly: power polygons, stitching and thermal
5
+ vias, keepouts, hand-routed traces, silkscreen labels.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import uuid
12
+ from pathlib import Path
13
+
14
+
15
+ def origin(pcb) -> tuple[float, float]:
16
+ """File coordinates of the board-relative (0, 0), as kicad-tools defines it.
17
+
18
+ Takes a path. One definition for generated and hand-drawn boards alike, so
19
+ what `pads` prints is what TRACKS, VIAS and ZONES are written in.
20
+ """
21
+ from .model import Board
22
+ return Board(pcb).origin
23
+
24
+
25
+ def blocks(text: str, heads: tuple[str, ...]) -> list[tuple[int, int]]:
26
+ """(start, end) of every top-level-ish s-expression whose head is in `heads`,
27
+ found by matching parentheses (any nesting, any indentation, strings respected)."""
28
+ out = []
29
+ pat = re.compile(r"\n[ \t]*\((" + "|".join(map(re.escape, heads)) + r")\b")
30
+ pos = 0
31
+ while True:
32
+ m = pat.search(text, pos)
33
+ if not m:
34
+ return out
35
+ i = m.end(0) - len(m.group(1)) - 1
36
+ depth, j, instr = 0, i, False
37
+ while j < len(text):
38
+ ch = text[j]
39
+ if instr:
40
+ if ch == "\\":
41
+ j += 1
42
+ elif ch == '"':
43
+ instr = False
44
+ elif ch == '"':
45
+ instr = True
46
+ elif ch == "(":
47
+ depth += 1
48
+ elif ch == ")":
49
+ depth -= 1
50
+ if depth == 0:
51
+ break
52
+ j += 1
53
+ out.append((m.start(0), j + 1))
54
+ pos = j + 1
55
+
56
+
57
+ def ripup(text: str, nets: set[str]) -> tuple[str, int]:
58
+ """Remove every track, arc and via of the given nets."""
59
+ names = dict(re.findall(r'\n\s*\(net (\d+) "([^"]*)"\)', text))
60
+ drop = []
61
+ for s0, e0 in blocks(text, ("segment", "arc", "via")):
62
+ n = re.search(r'\(net (?:(\d+)(?: "([^"]*)")?|"([^"]*)")', text[s0:e0])
63
+ if not n:
64
+ continue
65
+ net = n.group(3) if n.group(3) is not None else (n.group(2) or names.get(n.group(1), ""))
66
+ if net in nets:
67
+ drop.append((s0, e0))
68
+ for s0, e0 in reversed(drop):
69
+ text = text[:s0] + text[e0:]
70
+ return text, len(drop)
71
+
72
+
73
+ def _net(text: str, name: str, zone: bool = False) -> str:
74
+ """Net reference in the file's own style: numbered (pre-KiCad-10 save) or by name."""
75
+ m = re.search(r'\n\t\(net (\d+) "%s"\)' % re.escape(name), text)
76
+ if not m:
77
+ return f'(net "{name}")'
78
+ return f'(net {m.group(1)}) (net_name "{name}")' if zone else f'(net {m.group(1)})'
79
+
80
+
81
+ def _u() -> str:
82
+ return str(uuid.uuid4())
83
+
84
+
85
+ def _pts(pts, ox, oy) -> str:
86
+ return " ".join(f"(xy {round(x + ox, 4)} {round(y + oy, 4)})" for x, y in pts)
87
+
88
+
89
+ def zone(netref, layer, pts, ox, oy, priority=1, clearance=0.25, solid=True, min_thickness=0.2) -> str:
90
+ connect = "(connect_pads yes (clearance %s))" % clearance if solid else "(connect_pads (clearance %s))" % clearance
91
+ return (f'\t(zone {netref} (layer "{layer}") (uuid "{_u()}") (hatch edge 0.5) (priority {priority})\n'
92
+ f'\t\t{connect} (min_thickness {min_thickness})\n'
93
+ f'\t\t(fill yes (thermal_gap 0.3) (thermal_bridge_width 0.4) (island_removal_mode 0))\n'
94
+ f'\t\t(polygon (pts {_pts(pts, ox, oy)}))\n\t)\n')
95
+
96
+
97
+ def keepout(layers, pts, ox, oy, tracks=True, vias=True, pour=True) -> str:
98
+ ls = " ".join(f'"{l}"' for l in layers)
99
+ na = lambda b: "not_allowed" if b else "allowed"
100
+ return (f'\t(zone (net 0) (net_name "") (layers {ls}) (uuid "{_u()}") (hatch edge 0.5)\n'
101
+ f'\t\t(connect_pads (clearance 0)) (min_thickness 0.25)\n'
102
+ f'\t\t(keepout (tracks {na(tracks)}) (vias {na(vias)}) (pads allowed) '
103
+ f'(copperpour {na(pour)}) (footprints allowed))\n'
104
+ f'\t\t(fill (thermal_gap 0.5) (thermal_bridge_width 0.5))\n'
105
+ f'\t\t(polygon (pts {_pts(pts, ox, oy)}))\n\t)\n')
106
+
107
+
108
+ def via(netref, x, y, ox, oy, size=0.6, drill=0.3) -> str:
109
+ return (f'\t(via (at {round(x + ox, 4)} {round(y + oy, 4)}) (size {size}) (drill {drill}) '
110
+ f'(layers "F.Cu" "B.Cu") {netref} (uuid "{_u()}"))\n')
111
+
112
+
113
+ def track(netref, pts, ox, oy, width=0.25, layer="F.Cu") -> str:
114
+ out = ""
115
+ for (x1, y1), (x2, y2) in zip(pts, pts[1:]):
116
+ out += (f'\t(segment (start {round(x1 + ox, 4)} {round(y1 + oy, 4)}) (end {round(x2 + ox, 4)} {round(y2 + oy, 4)}) '
117
+ f'(width {width}) (layer "{layer}") {netref} (uuid "{_u()}"))\n')
118
+ return out
119
+
120
+
121
+ def text(s, x, y, ox, oy, size=1.0, layer="F.SilkS", rot=0) -> str:
122
+ mirror = " (justify mirror)" if layer.startswith("B.") else ""
123
+ return (f'\t(gr_text "{s}" (at {round(x + ox, 4)} {round(y + oy, 4)} {rot}) (layer "{layer}") (uuid "{_u()}")\n'
124
+ f'\t\t(effects (font (size {size} {size}) (thickness {round(size * 0.15, 3)})){mirror})\n\t)\n')
125
+
126
+
127
+ def append(pcb: Path, chunks: list[str]) -> None:
128
+ if not chunks:
129
+ return
130
+ t = pcb.read_text().rstrip()
131
+ assert t.endswith(")")
132
+ pcb.write_text(t[:-1].rstrip() + "\n" + "".join(chunks) + ")\n")
133
+
134
+
135
+ def _cross(p1, p2, p3, p4) -> bool:
136
+ def o(a, b, c):
137
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
138
+ return o(p1, p2, p3) * o(p1, p2, p4) < 0 and o(p3, p4, p1) * o(p3, p4, p2) < 0
139
+
140
+
141
+ def check_tracks(m) -> None:
142
+ """Hand routes of different nets must not cross on a layer, or pass over a foreign hand via."""
143
+ import math
144
+ segs = [(t[0], a, b, t[3] if len(t) > 3 else "F.Cu", t[2] if len(t) > 2 else 0.25)
145
+ for t in getattr(m, "TRACKS", []) for a, b in zip(t[1], t[1][1:])]
146
+ for i, (n1, a, b, l1, _w) in enumerate(segs):
147
+ for n2, c, d, l2, _w2 in segs[i + 1:]:
148
+ if n1 != n2 and l1 == l2 and _cross(a, b, c, d):
149
+ raise ValueError(f"TRACKS: {n1} {a}->{b} crosses {n2} {c}->{d} on {l1}")
150
+ for v in getattr(m, "VIAS", []):
151
+ r = (v[3] if len(v) > 3 else 0.6) / 2
152
+ for n, a, b, _l, w in segs:
153
+ if n == v[0]:
154
+ continue
155
+ (x1, y1), (x2, y2), (px, py) = a, b, (v[1], v[2])
156
+ L2 = (x2 - x1) ** 2 + (y2 - y1) ** 2
157
+ t = max(0, min(1, ((px - x1) * (x2 - x1) + (py - y1) * (y2 - y1)) / L2)) if L2 else 0
158
+ dist = math.hypot(px - (x1 + t * (x2 - x1)), py - (y1 + t * (y2 - y1)))
159
+ if dist < r + w / 2 + 0.15:
160
+ raise ValueError(f"TRACKS: {n} {a}->{b} passes {dist:.2f} mm from the {v[0]} via at {(px, py)}")
161
+
162
+
163
+ def apply(pcb: Path, m, stage: str) -> None:
164
+ """stage 'pre' (before routing): VIAS, TRACKS, KEEPOUTS. 'post': ZONES, TEXT.
165
+
166
+ ZONES go in after routing: exported as DSN planes, Freerouting stops routing
167
+ those nets and still runs other nets through them (tried on tps54202_buck).
168
+ boardwright.review names any net that crosses a polygon; hand-route that one.
169
+ """
170
+ t = pcb.read_text()
171
+ ox, oy = origin(pcb)
172
+ ch = []
173
+ if stage == "pre":
174
+ check_tracks(m)
175
+ for v in getattr(m, "VIAS", []):
176
+ ch.append(via(_net(t, v[0]), v[1], v[2], ox, oy, *v[3:]))
177
+ for tr in getattr(m, "TRACKS", []): # (net, [(x,y)...], width, layer)
178
+ ch.append(track(_net(t, tr[0]), tr[1], ox, oy, *tr[2:]))
179
+ for k in getattr(m, "KEEPOUTS", []): # (layers, pts)
180
+ ch.append(keepout(k[0], k[1], ox, oy))
181
+ else:
182
+ for z in getattr(m, "ZONES", []): # (net, layer, pts[, priority])
183
+ ch.append(zone(_net(t, z[0], True), z[1], z[2], ox, oy, *z[3:]))
184
+ for tx in getattr(m, "TEXT", []): # (string, x, y[, size, layer, rot])
185
+ ch.append(text(tx[0], tx[1], tx[2], ox, oy, *tx[3:]))
186
+ append(pcb, ch)
187
+
188
+
189
+ class Pad(tuple):
190
+ """(ref, pad, net, x, y, layer) plus .reach, half the pad's longer side."""
191
+ def __new__(cls, t, reach):
192
+ o = super().__new__(cls, t)
193
+ o.reach = reach
194
+ return o
195
+
196
+
197
+ def pads(pcb: Path) -> list:
198
+ """(ref, pad, net, x, y, layer) board-relative, each with .reach; any KiCad file."""
199
+ from .model import Board
200
+ return [Pad((p.ref, p.num, p.net, round(p.x, 3), round(p.y, 3), p.layer), p.reach) for p in Board(pcb).pads]
201
+
202
+
203
+ def segments(text: str) -> list[tuple[float, float, float, float, float, str, str]]:
204
+ """(x1, y1, x2, y2, width, layer, net name) in file coordinates; either net style."""
205
+ names = dict(re.findall(r'\n\s*\(net (\d+) "([^"]*)"\)', text))
206
+ out = []
207
+ for m in re.finditer(r'\(segment\s+\(start ([-\d.]+) ([-\d.]+)\)\s+\(end ([-\d.]+) ([-\d.]+)\)'
208
+ r'\s+\(width ([\d.]+)\)\s+\(layer "([^"]+)"\)\s+\(net (?:(\d+)|"([^"]*)")', text):
209
+ net = m.group(8) if m.group(8) is not None else names.get(m.group(7), m.group(7))
210
+ out.append((*map(float, m.groups()[:5]), m.group(6), net))
211
+ return out
boardwright/edits.py ADDED
@@ -0,0 +1,110 @@
1
+ """A board edit as a plain list of operations.
2
+
3
+ boardwright edits SPEC.py BOARD.kicad_pcb OUT.json [PROJECT.kicad_pro]
4
+
5
+ PROJECT gives ROUTES their default width and clearance when the board file
6
+ is a copy that does not sit beside its project.
7
+
8
+ Turns a spec's MOVE, RIPUP, VIAS, TRACKS and ROUTES (board-relative mm, as
9
+ everywhere else in this tool; ROUTES are pad-to-pad connections worked out by
10
+ boardwright/route.py) into an edit list in the board file's own absolute
11
+ coordinates, checked against the board first: every reference and net must
12
+ exist, and hand tracks must not cross. The list is what `boardwright.live apply`
13
+ executes, and it is simple enough for anything else to execute too.
14
+
15
+ {"ops": [
16
+ {"op": "move_footprint", "ref": "U1", "x": 120.5, "y": 80.0, "rotation": 90},
17
+ {"op": "remove_routing", "nets": ["/SDA", "GND"]},
18
+ {"op": "add_via", "net": "GND", "x": 110.0, "y": 85.0, "diameter": 0.6, "drill": 0.3},
19
+ {"op": "add_track", "net": "GND", "x1": 110.0, "y1": 85.0, "x2": 115.0, "y2": 85.0,
20
+ "width": 0.25, "layer": "F.Cu"}
21
+ ]}
22
+
23
+ mm, absolute, y down; rotation in degrees and optional; vias are through
24
+ vias; remove_routing deletes every track, arc and via on those nets. Ops are
25
+ meant to run in order as one undoable change.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import importlib.util
31
+ import json
32
+ from pathlib import Path
33
+
34
+ from . import copper
35
+ from .model import Board
36
+
37
+
38
+ def from_spec(m, board: Board, project=None) -> dict:
39
+ copper.check_tracks(m)
40
+ ox, oy = board.origin
41
+ refs = {fp.reference for fp in board.pcb.footprints}
42
+ nets = {p.net for p in board.pads} | {t.net for t in board.tracks} | {z.net for z in board.zones}
43
+ r = lambda v: round(v, 4)
44
+ def need_net(n):
45
+ if n not in nets:
46
+ raise SystemExit(f"no net {n!r} on {board.path.name}")
47
+ return n
48
+ ops = []
49
+ if getattr(m, "ROUTES", None) and getattr(m, "MOVE", None):
50
+ raise SystemExit("ROUTES are worked out on the board as it is; apply the MOVE first, then route in a second edit")
51
+ from .route import expand
52
+ rtracks, rvias = expand(m, board, ignore=set(getattr(m, "RIPUP", [])), project=project)
53
+ for ref, pos in getattr(m, "MOVE", {}).items():
54
+ if ref not in refs:
55
+ raise SystemExit(f"no footprint {ref!r} on {board.path.name}")
56
+ op = {"op": "move_footprint", "ref": ref, "x": r(pos[0] + ox), "y": r(pos[1] + oy)}
57
+ if len(pos) > 2 and pos[2] is not None:
58
+ op["rotation"] = pos[2]
59
+ ops.append(op)
60
+ rip = [need_net(n) for n in getattr(m, "RIPUP", [])]
61
+ if rip:
62
+ ops.append({"op": "remove_routing", "nets": rip})
63
+ for v in list(getattr(m, "VIAS", [])) + rvias:
64
+ size, drill = (v[3], v[4]) if len(v) > 4 else (0.6, 0.3)
65
+ ops.append({"op": "add_via", "net": need_net(v[0]), "x": r(v[1] + ox), "y": r(v[2] + oy),
66
+ "diameter": size, "drill": drill})
67
+ for t in list(getattr(m, "TRACKS", [])) + rtracks:
68
+ width = t[2] if len(t) > 2 else 0.25
69
+ layer = t[3] if len(t) > 3 else "F.Cu"
70
+ if layer not in board.layers:
71
+ raise SystemExit(f"{board.path.name} has no layer {layer}")
72
+ for (x1, y1), (x2, y2) in zip(t[1], t[1][1:]):
73
+ ops.append({"op": "add_track", "net": need_net(t[0]), "x1": r(x1 + ox), "y1": r(y1 + oy),
74
+ "x2": r(x2 + ox), "y2": r(y2 + oy), "width": width, "layer": layer})
75
+ return {"ops": ops}
76
+
77
+
78
+ def describe(doc: dict) -> list[str]:
79
+ out = []
80
+ for o in doc["ops"]:
81
+ k = o["op"]
82
+ if k == "move_footprint":
83
+ out.append(f"move {o['ref']} to ({o['x']}, {o['y']})" + (f" rot {o['rotation']}" if "rotation" in o else ""))
84
+ elif k == "remove_routing":
85
+ out.append(f"remove all routing on {', '.join(o['nets'])}")
86
+ elif k == "add_via":
87
+ out.append(f"via {o['net']} at ({o['x']}, {o['y']}) {o['diameter']}/{o['drill']}")
88
+ elif k == "add_track":
89
+ out.append(f"track {o['net']} {o['layer']} w={o['width']}: ({o['x1']}, {o['y1']}) -> ({o['x2']}, {o['y2']})")
90
+ else:
91
+ raise SystemExit(f"unknown op {k!r}")
92
+ return out
93
+
94
+
95
+ def load_spec(path: str):
96
+ sp = importlib.util.spec_from_file_location("edit_spec", path)
97
+ m = importlib.util.module_from_spec(sp)
98
+ sp.loader.exec_module(m)
99
+ return m
100
+
101
+
102
+ def cli(argv: list[str]) -> int:
103
+ argv = ["boardwright", *argv]
104
+ if len(argv) not in (4, 5):
105
+ raise SystemExit(__doc__)
106
+ doc = from_spec(load_spec(argv[1]), Board(argv[2]), argv[4] if len(argv) == 5 else None)
107
+ Path(argv[3]).write_text(json.dumps(doc, indent=1) + "\n")
108
+ print(f"{len(doc['ops'])} op(s) -> {argv[3]} (absolute mm)")
109
+ print(*(" " + l for l in describe(doc)), sep="\n")
110
+ return 0