aboutsummaryrefslogtreecommitdiff
path: root/tools/router/write_board.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/router/write_board.py')
-rw-r--r--tools/router/write_board.py131
1 files changed, 131 insertions, 0 deletions
diff --git a/tools/router/write_board.py b/tools/router/write_board.py
new file mode 100644
index 0000000..a4eaa6d
--- /dev/null
+++ b/tools/router/write_board.py
@@ -0,0 +1,131 @@
+"""Write router output (tracks, vias) and copper pours into a board.
+
+Run with KiCad's bundled Python (pcbnew):
+
+ $KPY tools/router/write_board.py src.kicad_pcb routes.json out.kicad_pcb [--zones zones.json] [--replace]
+
+ --replace delete all existing tracks and vias first (routes.json then holds everything)
+ --diff routes.json holds everything (a route with the board's copper as [[fixed]]): only
+ tracks/vias that differ are touched; untouched copper keeps its exact drill and width
+ --zones zones.json: {"zones": [{net, layer, pts, priority, clearance?}]}; zones are filled
+
+pcbnew.SaveBoard rewrites the project file next to `out` with default net settings
+(knowledge/tooling/kicad.md, pcbnew quirks), so an existing .kicad_pro is copied
+before the save and written back afterwards. Close the board in KiCad before writing to
+its own path; an open editor overwrites the file on its next save.
+"""
+import argparse
+import json
+import os
+
+import pcbnew
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("src")
+ ap.add_argument("routes")
+ ap.add_argument("out")
+ ap.add_argument("--zones")
+ ap.add_argument("--replace", action="store_true")
+ ap.add_argument("--diff", action="store_true")
+ ap.add_argument("--prune-vias", metavar="NET", help="after filling, drop vias of NET that touch no track and do not sit in a fill on both layers (stitching vias that ended up isolated)")
+ a = ap.parse_args()
+
+ mm = pcbnew.FromMM
+ b = pcbnew.LoadBoard(a.src)
+ nets = b.GetNetsByName()
+ if a.replace:
+ for t in list(b.GetTracks()):
+ b.Remove(t)
+ r = json.load(open(a.routes))
+ if a.diff:
+ def skey(net, layer, x1, y1, x2, y2):
+ e = sorted([(round(x1, 3), round(y1, 3)), (round(x2, 3), round(y2, 3))])
+ return (net, layer, e[0], e[1])
+ want_s = {skey(t["net"], t["layer"], t["x1"], t["y1"], t["x2"], t["y2"]) for t in r["segs"]}
+ want_v = {(v["net"], round(v["x"], 3), round(v["y"], 3)) for v in r["vias"]}
+ have_s, have_v, gone = set(), set(), []
+ for t in list(b.GetTracks()):
+ if t.GetClass() == "PCB_VIA":
+ k = (t.GetNetname(), round(t.GetPosition().x / 1e6, 3), round(t.GetPosition().y / 1e6, 3))
+ if k in want_v:
+ have_v.add(k)
+ else:
+ gone.append(t)
+ elif t.GetClass() == "PCB_TRACK":
+ k = skey(t.GetNetname(), b.GetLayerName(t.GetLayer()), t.GetStart().x / 1e6, t.GetStart().y / 1e6,
+ t.GetEnd().x / 1e6, t.GetEnd().y / 1e6)
+ if k in want_s:
+ have_s.add(k)
+ else:
+ gone.append(t)
+ for t in gone:
+ b.Delete(t)
+ r["segs"] = [t for t in r["segs"] if skey(t["net"], t["layer"], t["x1"], t["y1"], t["x2"], t["y2"]) not in have_s]
+ r["vias"] = [v for v in r["vias"] if (v["net"], round(v["x"], 3), round(v["y"], 3)) not in have_v]
+ print("diff: %d tracks/vias removed" % len(gone))
+ for s in r["segs"]:
+ t = pcbnew.PCB_TRACK(b)
+ t.SetStart(pcbnew.VECTOR2I(mm(s["x1"]), mm(s["y1"])))
+ t.SetEnd(pcbnew.VECTOR2I(mm(s["x2"]), mm(s["y2"])))
+ t.SetWidth(mm(s["w"]))
+ t.SetLayer(pcbnew.F_Cu if s["layer"] == "F.Cu" else pcbnew.B_Cu)
+ t.SetNet(nets[s["net"]])
+ b.Add(t)
+ for v in r["vias"]:
+ t = pcbnew.PCB_VIA(b)
+ t.SetPosition(pcbnew.VECTOR2I(mm(v["x"]), mm(v["y"])))
+ t.SetWidth(mm(v["d"]))
+ t.SetDrill(mm(v["drill"]))
+ t.SetViaType(pcbnew.VIATYPE_THROUGH)
+ t.SetNet(nets[v["net"]])
+ b.Add(t)
+ if a.zones:
+ for zd in json.load(open(a.zones))["zones"]:
+ zn = pcbnew.ZONE(b)
+ zn.SetLayer(pcbnew.F_Cu if zd["layer"] == "F.Cu" else pcbnew.B_Cu)
+ zn.SetNet(nets[zd["net"]])
+ zn.SetZoneName(zd.get("name", zd["net"] + " " + zd["layer"]))
+ o = zn.Outline()
+ o.NewOutline()
+ for (x, y) in zd["pts"]:
+ o.Append(mm(x), mm(y))
+ zn.SetAssignedPriority(zd.get("priority", 0))
+ zn.SetLocalClearance(mm(zd.get("clearance", 0.3)))
+ zn.SetMinThickness(mm(0.25))
+ zn.SetPadConnection(pcbnew.ZONE_CONNECTION_THERMAL)
+ zn.SetThermalReliefGap(mm(0.3))
+ zn.SetThermalReliefSpokeWidth(mm(0.4))
+ zn.SetIslandRemovalMode(pcbnew.ISLAND_REMOVAL_MODE_ALWAYS)
+ b.Add(zn)
+ if b.Zones():
+ pcbnew.ZONE_FILLER(b).Fill(b.Zones())
+ if a.prune_vias and b.Zones():
+ net = nets[a.prune_vias]
+ ends = [(t.GetStart(), t.GetEnd(), t.GetLayer()) for t in b.GetTracks() if t.GetClass() == "PCB_TRACK" and t.GetNetCode() == net.GetNetCode()]
+ zones = [z for z in b.Zones() if not z.GetIsRuleArea() and z.GetNetCode() == net.GetNetCode()]
+ dropped = 0
+ for v in [t for t in b.GetTracks() if t.GetClass() == "PCB_VIA" and t.GetNetCode() == net.GetNetCode()]:
+ p, rad = v.GetPosition(), v.GetWidth(pcbnew.F_Cu) / 2
+ if any((e - p).EuclideanNorm() <= rad for s_, e_, _ in ends for e in (s_, e_)):
+ continue
+ inF = any(z.IsOnLayer(pcbnew.F_Cu) and z.GetFilledPolysList(pcbnew.F_Cu).Contains(p) for z in zones)
+ inB = any(z.IsOnLayer(pcbnew.B_Cu) and z.GetFilledPolysList(pcbnew.B_Cu).Contains(p) for z in zones)
+ if not (inF and inB):
+ b.Remove(v)
+ dropped += 1
+ if dropped:
+ pcbnew.ZONE_FILLER(b).Fill(b.Zones())
+ print("pruned %d isolated %s vias" % (dropped, a.prune_vias))
+
+ pro = a.out[:-len(".kicad_pcb")] + ".kicad_pro"
+ keep = open(pro).read() if os.path.exists(pro) else None
+ pcbnew.SaveBoard(a.out, b)
+ if keep is not None:
+ open(pro, "w").write(keep)
+ print("saved %s: %d segments, %d vias added" % (a.out, len(r["segs"]), len(r["vias"])))
+
+
+if __name__ == "__main__":
+ main()