1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
|
"""Compose a base board from routed module boards: each module's footprints, tracks, vias, pours and
drawings are copied onto the base board as one tile, turned and moved, with references and nets
renamed to the base board's schematic.
The base board's schematic uses the modules' block sheets with references offset per sheet
(e.g. U1 -> U101 on the first sheet). The net of every copied pad and
track comes from the base board's netlist through the pads: a module net takes the base net of its
pads (all its pads must agree, except pads listed under "repin", whose net the root sheet changed,
e.g. an address strap). Module-only footprints such as housing posts (`skip`) are left out, since
the base board's housing footprint carries the posts.
Spec (JSON):
{"board": base .kicad_pcb (template copy), "netlist": base netlist,
"modules": [{"board": module .kicad_pcb, "sheet": "RS485 1", "offset": 600,
"block": [x0, y0, x1, y1] (module coordinates), "rot": 0 | 180,
"at": [x0, y0] (block's top-left corner on the base board, after turning),
"skip": ["P1"], "repin": ["U2.1"]}],
"parts": {"R1": [x, y, rot]}, base-sheet parts: footprint from the netlist, placed here
"tabs": {"bottom": ["J101"], "top": ["J301"]}, connectors that get a board tab (connector_tab)
"tab_merge": 2.0} bodies closer than this share one tab (default connector_tab.MERGE, 3 mm)
usage (KiCad's Python, from the repo root, board closed in KiCad):
.../Python.framework/Versions/3.9/bin/python3 tools/compose_board.py SPEC.json
then tools/sync_board.py NETLIST BOARD for paths, values and fields, and DRC with parity.
Notes: knowledge/tooling/compose-board.md
"""
import json
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pcbnew # noqa: E402
from connector_tab import MERGE, add_tabs # noqa: E402
from sexpr import find, first, parse # noqa: E402
from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402
KFP = FOOTPRINTS
HWFP = os.path.join(ROOT, "libraries/footprints/HW.pretty")
mm = pcbnew.FromMM
def renum(ref, off):
m = re.fullmatch(r"(#?[A-Za-z_]+)(\d+)", ref)
assert m, ref
return "%s%d" % (m.group(1), int(m.group(2)) + off)
def read_netlist(path):
net = parse(open(path).read())
pinnet, fpid = {}, {}
for n in find(first(net, "nets"), "net"):
for nd in find(n, "node"):
pinnet[(first(nd, "ref")[1], first(nd, "pin")[1])] = first(n, "name")[1]
for c in find(first(net, "components"), "comp"):
fpid[first(c, "ref")[1]] = first(c, "footprint")[1]
return pinnet, fpid
def dup(item):
"""Copy of a board item (FOOTPRINT::Duplicate takes addToParentGroup, the others nothing)."""
try:
return item.Duplicate(False)
except TypeError:
return item.Duplicate()
def branch(mb, pad):
"""Tracks of the pad's (module) net that run from the pad up to the first via or junction: the
copper a repinned pad must lose. Other pads do not stop the walk: a branch that crosses a
neighbour's pad end (e.g. an address-strap track running over the next strap pad) would otherwise stay too close to the
repinned pad. A pad that loses its only link shows up in DRC as unconnected."""
tracks = [t for t in mb.GetTracks() if t.GetNetCode() == pad.GetNetCode()]
vias = [t for t in tracks if t.GetClass() == "PCB_VIA"]
segs = [t for t in tracks if t.GetClass() != "PCB_VIA"]
def ends(t):
return (t.GetStart(), t.GetEnd())
out = []
todo = [(t, t.GetEnd() if pad.HitTest(t.GetStart()) else t.GetStart())
for t in segs if pad.IsOnLayer(t.GetLayer()) and any(pad.HitTest(e) for e in ends(t))]
while todo:
t, far = todo.pop()
if t in out:
continue
out.append(t)
nxt = [u for u in segs if u not in out and far in ends(u)]
if len(nxt) != 1 or any(v.GetPosition() == far for v in vias):
continue
u = nxt[0]
todo.append((u, u.GetEnd() if u.GetStart() == far else u.GetStart()))
return out
def rect_to_segments(b):
"""Edge.Cuts rectangles -> four segments (add_tabs splits straight segments)."""
for d in list(b.GetDrawings()):
if d.GetLayer() == pcbnew.Edge_Cuts and d.GetShape() == pcbnew.SHAPE_T_RECTANGLE:
p, q = d.GetStart(), d.GetEnd()
pts = [(p.x, p.y), (q.x, p.y), (q.x, q.y), (p.x, q.y), (p.x, p.y)]
for a, c in zip(pts, pts[1:]):
s = pcbnew.PCB_SHAPE(b)
s.SetShape(pcbnew.SHAPE_T_SEGMENT)
s.SetStart(pcbnew.VECTOR2I(*a))
s.SetEnd(pcbnew.VECTOR2I(*c))
s.SetLayer(pcbnew.Edge_Cuts)
s.SetWidth(d.GetWidth())
b.Add(s)
b.Remove(d)
def main(spec_path):
spec = json.load(open(spec_path))
pinnet, fpid = read_netlist(spec["netlist"])
pro = spec["board"][:-len(".kicad_pcb")] + ".kicad_pro"
keep = open(pro).read() if os.path.exists(pro) else None
b = pcbnew.LoadBoard(spec["board"])
assert not [f for f in b.GetFootprints() if not f.IsBoardOnly()], "base board already has parts"
rect_to_segments(b)
nets = {str(k): v for k, v in b.GetNetsByName().items()}
def getnet(name):
if name not in nets:
ni = pcbnew.NETINFO_ITEM(b, name)
b.Add(ni)
nets[name] = ni
return nets[name]
for prio, m in enumerate(spec["modules"], start=1):
mb = pcbnew.LoadBoard(m["board"])
off, skip, repin = m["offset"], set(m.get("skip", [])), set(m.get("repin", []))
x0, y0, x1, y1 = m["block"]
rot = m.get("rot", 0)
w, h = (x1 - x0, y1 - y0) if rot in (0, 180) else (y1 - y0, x1 - x0)
centre = pcbnew.VECTOR2I(mm((x0 + x1) / 2), mm((y0 + y1) / 2))
target = pcbnew.VECTOR2I(mm(m["at"][0] + w / 2), mm(m["at"][1] + h / 2))
angle = pcbnew.EDA_ANGLE(rot, pcbnew.DEGREES_T)
# module net -> base net, through the pads
nmap, clash = {}, []
for fp in mb.GetFootprints():
if fp.GetReference() in skip:
continue
ref = renum(fp.GetReference(), off)
for pad in fp.Pads():
old, new = pad.GetNetname(), pinnet.get((ref, pad.GetNumber()))
if not old or new is None or "%s.%s" % (fp.GetReference(), pad.GetNumber()) in repin:
continue
if nmap.setdefault(old, new) != new:
clash.append("%s.%s %s: %s / %s" % (ref, pad.GetNumber(), old, nmap[old], new))
assert not clash, "module nets that split on the base board (add to repin?):\n " + "\n ".join(clash)
# copper that tied a repinned pad to its old net stays behind
drop = set()
for pr in repin:
ref, num = pr.split(".")
pad = [p for p in mb.FindFootprintByReference(ref).Pads() if p.GetNumber() == num][0]
for t in branch(mb, pad):
drop.add(t.m_Uuid.AsString())
print(" %s: %d %s tracks left out" % (pr, len(drop), pad.GetNetname()))
group = pcbnew.PCB_GROUP(b)
group.SetName(m["sheet"])
b.Add(group)
def place(item):
if rot:
item.Rotate(centre, angle)
item.Move(target - centre)
b.Add(item)
group.AddItem(item)
n = {"fp": 0, "track": 0, "zone": 0, "drawing": 0}
for fp in mb.GetFootprints():
if fp.GetReference() in skip:
continue
c = pcbnew.Cast_to_FOOTPRINT(dup(fp))
ref = renum(fp.GetReference(), off)
c.SetReference(ref)
place(c)
for pad in c.Pads():
name = pinnet.get((ref, pad.GetNumber()))
pad.SetNet(getnet(name) if name else b.FindNet(0))
n["fp"] += 1
for t in mb.GetTracks():
if t.m_Uuid.AsString() in drop:
continue
c = dup(t).Cast()
place(c)
c.SetNet(getnet(nmap[t.GetNetname()]))
n["track"] += 1
for z in mb.Zones():
c = pcbnew.Cast_to_ZONE(dup(z))
# butting tiles' pours touch: each tile gets its own priority (DRC zones_intersect)
c.SetAssignedPriority(z.GetAssignedPriority() + prio)
place(c)
if z.GetNetname():
c.SetNet(getnet(nmap[z.GetNetname()]))
n["zone"] += 1
for d in mb.GetDrawings():
if d.GetLayer() == pcbnew.Edge_Cuts:
continue
place(dup(d).Cast())
n["drawing"] += 1
print("%-14s rot %3d at (%.2f, %.2f) %s" % (m["sheet"], rot, m["at"][0], m["at"][1],
", ".join("%d %ss" % (v, k) for k, v in n.items())))
for ref, (x, y, r) in spec.get("parts", {}).items():
nick, name = fpid[ref].split(":")
fp = pcbnew.FootprintLoad(HWFP if nick == "HW" else os.path.join(KFP, nick + ".pretty"), name)
assert fp, fpid[ref]
fp.SetFPID(pcbnew.LIB_ID(nick, name))
b.Add(fp)
fp.SetReference(ref)
fp.SetPosition(pcbnew.VECTOR2I(mm(x), mm(y)))
fp.SetOrientationDegrees(r)
fp.Reference().SetTextSize(pcbnew.VECTOR2I(mm(0.8), mm(0.8)))
fp.Reference().SetTextThickness(mm(0.12))
for pad in fp.Pads():
name = pinnet.get((ref, pad.GetNumber()))
pad.SetNet(getnet(name) if name else b.FindNet(0))
print("part", ref, fpid[ref], "at", x, y, r)
for side, refs in spec.get("tabs", {}).items():
add_tabs(b, refs, side=side, merge=spec.get("tab_merge", MERGE))
pcbnew.ZONE_FILLER(b).Fill(b.Zones())
pcbnew.SaveBoard(spec["board"], b)
if keep is not None:
open(pro, "w").write(keep) # SaveBoard resets the project's net settings
if __name__ == "__main__":
main(sys.argv[1])
|