from pathlib import Path
import wx,pcbnew,json
app=wx.App(False);quiet=wx.LogNull()
R=Path(__file__).resolve().parent;D=R/'cad';f=D/'vacuum_control_evt_a5_logic_fet.kicad_pcb';b=pcbnew.LoadBoard(str(f))
u=next(x for x in b.GetFootprints() if x.GetReference()=='U5')
nets={}
for name in ['/PANEL_SCL','/PANEL_SDA']:
 n=pcbnew.NETINFO_ITEM(b,name);b.Add(n);nets[name]=n
for num,name in [('13','/PANEL_SCL'),('14','/PANEL_SDA')]:next(x for x in u.Pads() if x.GetNumber()==num).SetNet(nets[name])
h=pcbnew.FootprintLoad(str(D/'Vacuum_Panel.pretty'),'PinHeader_1x04_P2.54mm_Drill1.2')
h.SetReference('J5');h.SetValue('PANEL I2C 3V3 ONLY');h.SetPosition(pcbnew.VECTOR2I(pcbnew.FromMM(130),pcbnew.FromMM(75)))
h.SetFPID(pcbnew.LIB_ID('Vacuum_Panel','PinHeader_1x04_P2.54mm_Drill1.2'))
info=json.loads((R/'schematic_change.json').read_text());path=pcbnew.KIID_PATH();path.push_back(pcbnew.KIID(info['sheet_uuid']));path.push_back(pcbnew.KIID(info['J5_uuid']));h.SetPath(path)
b.Add(h)
for p in h.Pads():
 name=info['J5_pin_nets'][int(p.GetNumber())-1];p.SetNet(nets[name] if name in nets else b.FindNet(name))
 # Engineering header finished drill 1.2 mm; final mating/DFM still open.
 p.SetDrillSize(pcbnew.VECTOR2I(pcbnew.FromMM(1.2),pcbnew.FromMM(1.2)))
def track(name,layer,points,w=.25):
 net=nets[name] if name in nets else b.FindNet(name)
 for a,z in zip(points,points[1:]):
  x=pcbnew.PCB_TRACK(b);x.SetStart(pcbnew.VECTOR2I(pcbnew.FromMM(a[0]),pcbnew.FromMM(a[1])));x.SetEnd(pcbnew.VECTOR2I(pcbnew.FromMM(z[0]),pcbnew.FromMM(z[1])));x.SetWidth(pcbnew.FromMM(w));x.SetLayer(layer);x.SetNet(net);b.Add(x)
def via(name,x,y):
 v=pcbnew.PCB_VIA(b);v.SetPosition(pcbnew.VECTOR2I(pcbnew.FromMM(x),pcbnew.FromMM(y)));v.SetWidth(pcbnew.FromMM(.6));v.SetDrill(pcbnew.FromMM(.3));v.SetViaType(pcbnew.VIATYPE_THROUGH);v.SetLayerPair(pcbnew.F_Cu,pcbnew.B_Cu);v.SetNet(nets[name]);b.Add(v)
b.BuildConnectivity();pcbnew.SaveBoard(str(f),b)
print('saved unrouted interface')
