Files
vibemake-pcb-studio/backend/tests/make_project.py
T

134 lines
6.2 KiB
Python

"""Generate a small, real native KiCad board for integration tests.
Two passive two-pin headers, two distinct nets, two tracks and a ground zone.
No prior user design, test history, server path, or provider credential is used.
Run with KiCad's Python, not the web API virtual environment.
"""
import argparse
import json
from pathlib import Path
import uuid
def symbol_definition(library, name):
text = library.read_text()
start = text.index(f'(symbol "{name}"')
depth = 0
quoted = escaped = False
for end in range(start, len(text)):
char = text[end]
if escaped:
escaped = False
elif char == "\\" and quoted:
escaped = True
elif char == '"':
quoted = not quoted
elif not quoted:
if char == "(":
depth += 1
elif char == ")":
depth -= 1
if depth == 0:
return text[start:end + 1]
raise ValueError("Incomplete library symbol")
def make_project(directory, variant="good"):
import pcbnew as pcb
directory = Path(directory)
directory.mkdir(parents=True, exist_ok=False)
name = "native-smoke"
root_id = str(uuid.uuid4())
ids = [str(uuid.uuid4()), str(uuid.uuid4())]
fp_id = "Connector_PinHeader_2.54mm:PinHeader_1x02_P2.54mm_Vertical"
lib_id = "Connector_Generic:Conn_01x02"
definition = symbol_definition(Path("/usr/share/kicad/symbols/Connector_Generic.kicad_sym"), "Conn_01x02")
definition = definition.replace('(symbol "Conn_01x02"', f'(symbol "{lib_id}"', 1)
sch = [f'(kicad_sch (version 20250114) (generator "vibemake_kicad_test") (uuid "{root_id}") (paper "A4")',
f'(lib_symbols {definition})']
for index, sid in enumerate(ids):
ref = f"J{index + 1}"
x, y = 76.2 + 50.8 * index, 76.2
sch.append(f'''(symbol (lib_id "{lib_id}") (at {x} {y} 0) (unit 1)
(in_bom yes) (on_board yes) (dnp no) (uuid "{sid}")
(property "Reference" "{ref}" (at {x + 2.54} {y} 0) (effects (font (size 1.27 1.27)) (justify left)))
(property "Value" "Conn_01x02" (at {x + 2.54} {y + 2.54} 0) (effects (font (size 1.27 1.27)) (justify left)))
(property "Footprint" "{fp_id}" (at {x} {y} 0) (effects (font (size 1.27 1.27)) (hide yes)))
(instances (project "{name}" (path "/{root_id}" (reference "{ref}") (unit 1)))))''')
for pin, net in [(1, "VIN"), (2, "GND")]:
px, py = x - 5.08, y + 2.54 * (pin - 1)
lx = px - 7.62
sch.append(f'(wire (pts (xy {lx:.4f} {py:.4f}) (xy {px:.4f} {py:.4f})) (stroke (width 0) (type default)) (uuid "{uuid.uuid4()}"))')
sch.append(f'(label "{net}" (at {lx:.4f} {py:.4f} 0) (effects (font (size 1.27 1.27)) (justify left bottom)) (uuid "{uuid.uuid4()}"))')
sch.append('(embedded_fonts no))')
(directory / f"{name}.kicad_sch").write_text("\n".join(sch))
(directory / f"{name}.kicad_pro").write_text(json.dumps({"meta": {"filename": f"{name}.kicad_pro", "version": 1}}))
# Project-local tables make the example independent of first-run GUI setup.
(directory / "sym-lib-table").write_text('(sym_lib_table (version 7) (lib (name "Connector_Generic")(type "KiCad")(uri "/usr/share/kicad/symbols/Connector_Generic.kicad_sym")(options "")(descr "")))')
(directory / "fp-lib-table").write_text('(fp_lib_table (version 7) (lib (name "Connector_PinHeader_2.54mm")(type "KiCad")(uri "/usr/share/kicad/footprints/Connector_PinHeader_2.54mm.pretty")(options "")(descr "")))')
board = pcb.BOARD()
nets = {}
for name_net in ["VIN", "GND"]:
net = pcb.NETINFO_ITEM(board, "/" + name_net)
board.Add(net)
nets[name_net] = net
footprints = []
for index, sid in enumerate(ids):
fp = pcb.FootprintLoad("/usr/share/kicad/footprints/Connector_PinHeader_2.54mm.pretty", "PinHeader_1x02_P2.54mm_Vertical")
fp.SetFPIDAsString(fp_id)
fp.SetReference(f"J{index + 1}")
fp.SetValue("Conn_01x02")
path = pcb.KIID_PATH()
path.push_back(pcb.KIID(root_id))
path.push_back(pcb.KIID(sid))
fp.SetPath(path)
fp.SetPosition(pcb.VECTOR2I(pcb.FromMM(10 + 20 * index), pcb.FromMM(10)))
board.Add(fp)
for pad in fp.Pads():
pad.SetNet(nets["VIN" if pad.GetNumber() == "1" else "GND"])
footprints.append(fp)
for start, end in [((3, 3), (37, 3)), ((37, 3), (37, 24)), ((37, 24), (3, 24)), ((3, 24), (3, 3))]:
shape = pcb.PCB_SHAPE()
shape.SetShape(pcb.SHAPE_T_SEGMENT)
shape.SetLayer(pcb.Edge_Cuts)
shape.SetStart(pcb.VECTOR2I(*[pcb.FromMM(v) for v in start]))
shape.SetEnd(pcb.VECTOR2I(*[pcb.FromMM(v) for v in end]))
shape.SetWidth(pcb.FromMM(.05))
board.Add(shape)
for pin, net in [("1", "VIN"), ("2", "GND")]:
if variant == "unrouted" and pin == "1":
continue
pads = [next(p for p in fp.Pads() if p.GetNumber() == pin) for fp in footprints]
track = pcb.PCB_TRACK(board)
track.SetStart(pads[0].GetPosition())
track.SetEnd(pads[1].GetPosition())
track.SetWidth(pcb.FromMM(.6))
track.SetLayer(pcb.F_Cu)
track.SetNet(nets[net])
board.Add(track)
zone = pcb.ZONE(board)
zone.SetLayer(pcb.B_Cu)
zone.SetNet(nets["GND"])
zone.SetLocalClearance(pcb.FromMM(.25))
zone.SetThermalReliefGap(pcb.FromMM(.3))
zone.SetThermalReliefSpokeWidth(pcb.FromMM(.3))
zone.SetPadConnection(pcb.ZONE_CONNECTION_FULL)
zone.Outline().NewOutline()
for x, y in [(4, 4), (36, 4), (36, 23), (4, 23)]:
zone.Outline().Append(pcb.FromMM(x), pcb.FromMM(y))
board.Add(zone)
if variant == "wrong-net":
pad = next(p for p in footprints[1].Pads() if p.GetNumber() == "1")
pad.SetNet(nets["GND"])
pcb.SaveBoard(str(directory / "native-smoke.kicad_pcb"), board)
return directory / "native-smoke.kicad_pro"
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("directory")
parser.add_argument("--variant", choices=["good", "unrouted", "wrong-net"], default="good")
args = parser.parse_args()
print(make_project(args.directory, args.variant))