-
Notifications
You must be signed in to change notification settings - Fork 65
/
kicad_parser.py
2904 lines (2510 loc) · 102 KB
/
kicad_parser.py
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
#****************************************************************************
# maui full integration of fcad_pcb from @realthunder commit 121 #maui
## from __future__ import (absolute_import, division,
## print_function, unicode_literals)
#from builtins import *
# from future.utils import iteritems
# from __future__ import (absolute_import, division,
# print_function, unicode_literals)
#from builtins import *
from collections import defaultdict
from math import sqrt, atan2, degrees, sin, cos, radians, pi, hypot
import traceback
import FreeCAD
import FreeCADGui
import Part
from FreeCAD import Console,Vector,Placement,Rotation
import DraftGeomUtils,DraftVecUtils
try:
import CAM
except:
import Path
CAM = Path
import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
#from . import KicadPCB,SexpList
# maui
import fcad_parser
from fcad_parser import KicadPCB,SexpList,SexpParser,parseSexp
#from .fcad_parser import KicadPCB,SexpList
#from .kicad_parser import unquote
from fcad_parser import unquote #maui
# from kicadStepUptools import KicadPCB,SexpList
__kicad_parser_version__ = '2.3.5'
# https://github.com/realthunder/fcad_pcb/issues/20#issuecomment-586042341
# FreeCAD.Console.PrintLog('kicad_parser_version '+__kicad_parser_version__+'\n') # maui
# print('kicad_parser_version '+__kicad_parser_version__)
# maui
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
def _disableElementMapping(_):
pass
disableTopoNaming = getattr(Part, 'disableElementMapping', _disableElementMapping)
def addObject(doc, tp, name):
obj = doc.addObject(tp, name)
disableTopoNaming(obj)
try:
obj.ValidateShape = False
obj.FixShape = 0
except Exception:
pass
return obj
def updateGui():
try:
FreeCADGui.updateGui()
except Exception:
pass
class FCADLogger:
def __init__(self, tag):
self.tag = tag
self.levels = { 'error':0, 'warning':1, 'info':2,
'log':3, 'trace':4 }
def _isEnabledFor(self,level):
return FreeCAD.getLogLevel(self.tag) >= level
def isEnabledFor(self,level):
return self._isEnabledFor(self.levels[level])
def trace(self,msg):
if self._isEnabledFor(4):
FreeCAD.Console.PrintLog(msg+'\n')
updateGui()
def log(self,msg):
if self._isEnabledFor(3):
FreeCAD.Console.PrintLog(msg+'\n')
updateGui()
def info(self,msg):
if self._isEnabledFor(2):
FreeCAD.Console.PrintMessage(msg+'\n')
updateGui()
def warning(self,msg):
if self._isEnabledFor(1):
FreeCAD.Console.PrintWarning(msg+'\n')
updateGui()
def error(self,msg):
if self._isEnabledFor(0):
FreeCAD.Console.PrintError(msg+'\n')
updateGui()
logger = FCADLogger('fcad_pcb')
def getActiveDoc():
if FreeCAD.ActiveDocument is None:
return FreeCAD.newDocument('kicad_fcad')
return FreeCAD.ActiveDocument
def fitView():
try:
FreeCADGui.ActiveDocument.ActiveView.fitAll()
except Exception:
pass
def isZero(f):
return round(f,DraftGeomUtils.precision())==0
def makeColor(*color):
if len(color)==1:
if isinstance(color[0],string_types):
color = int(color[0],0)
else:
color = color[0]
r = float((color>>24)&0xFF)
g = float((color>>16)&0xFF)
b = float((color>>8)&0xFF)
else:
r,g,b = color
return (r/255.0,g/255.0,b/255.0)
def makeVect(l):
return Vector(l[0],-l[1],0)
def getAt(sexp):
at = getattr(sexp, 'at', None)
if not at:
return Vector(0,0,0),0
v = makeVect(at)
return (v,0) if len(at)==2 else (v,at[2])
def product(v1,v2):
return Vector(v1.x*v2.x,v1.y*v2.y,v1.z*v2.z)
def make_rect(size,params=None):
_ = params
return Part.makePolygon([product(size,Vector(*v))
for v in ((-0.5,-0.5),(0.5,-0.5),(0.5,0.5),(-0.5,0.5),(-0.5,-0.5))])
def make_trapezoid(size,params):
pts = [product(size,Vector(*v)) \
for v in ((-0.5,0.5),(-0.5,-0.5),(0.5,-0.5),(0.5,0.5))]
try:
delta = params.rect_delta[0]
if delta:
# horizontal
idx = 1
length = size[1]
else:
# vertical
delta = params.rect_delta[1]
idx = 0
length = size[0]
if delta <= -length:
collapse = 1
delta = -length;
elif delta >= length:
collapse = -1
delta = length
else:
collapse = 0
pts[0][idx] += delta*0.5
pts[1][idx] -= delta*0.5
pts[2][idx] += delta*0.5
pts[3][idx] -= delta*0.5
if collapse:
del pts[collapse]
except Exception:
logger.warning('trapezoid pad has no rect_delta')
pts.append(pts[0])
return Part.makePolygon(pts)
def make_circle(size,params=None):
_ = params
return Part.Wire(Part.makeCircle(size.x*0.5))
def make_oval(size,params=None):
_ = params
if size.x == size.y:
return make_circle(size)
if size.x < size.y:
r = size.x*0.5
size.y -= size.x
s = ((0,0.5),(-0.5,0.5),(-0.5,-0.5),(0,-0.5),(0.5,-0.5),(0.5,0.5))
a = (0,180,180,360)
else:
r = size.y*0.5
size.x -= size.y
s = ((-0.5,0),(-0.5,-0.5),(0.5,-0.5),(0.5,0),(0.5,0.5),(-0.5,0.5))
a = (90,270,-90,-270)
pts = [product(size,Vector(*v)) for v in s]
return Part.Wire([
Part.makeCircle(r,pts[0],Vector(0,0,1),a[0],a[1]),
Part.makeLine(pts[1],pts[2]),
Part.makeCircle(r,pts[3],Vector(0,0,1),a[2],a[3]),
Part.makeLine(pts[4],pts[5])])
def make_roundrect(size,params):
rratio = 0.25
try:
rratio = params.roundrect_rratio
if rratio > 0.5:
return make_oval(size)
except Exception:
logger.warning('round rect pad has no rratio')
length = min(size.x, size.y)
r = length*rratio
n = Vector(0,0,1)
sx = size.x*0.5
sy = size.y*0.5
rounds = [(r,False)]*4
if 'chamfer_ratio' in params and 'chamfer' in params:
ratio = params.chamfer_ratio
if ratio < 0.0:
ratio = 0.0
elif ratio > 0.5:
ratio = 0.5
for i,corner in enumerate(('top_right',
'top_left',
'bottom_left',
'bottom_right')):
if corner in params.chamfer:
rounds[i] = (ratio*length,True)
edges = []
r,chamfer = rounds[0]
pstart = Vector(sx,sy-r)
pt = pstart
pnext = Vector(sx-r,sy)
if r:
if not chamfer:
edges.append(Part.makeCircle(r,Vector(sx-r,sy-r),n,0,90))
else:
edges.append(Part.makeLine(pt, pnext))
r,chamfer = rounds[1]
pt = pnext
pnext = Vector(r-sx,sy)
if pt != pnext:
edges.append(Part.makeLine(pt,pnext))
pt = pnext
pnext = Vector(-sx,sy-r)
if r:
if not chamfer:
edges.append(Part.makeCircle(r,Vector(r-sx,sy-r),n,90,180))
else:
edges.append(Part.makeLine(pt,pnext))
r,chamfer = rounds[2]
pt = pnext
pnext = Vector(-sx,r-sy)
if pt != pnext:
edges.append(Part.makeLine(pt,pnext))
pt = pnext
pnext = Vector(r-sx,-sy)
if r:
if not chamfer:
edges.append(Part.makeCircle(r,Vector(r-sx,r-sy),n,180,270))
else:
edges.append(Part.makeLine(pt,pnext))
r,chamfer = rounds[3]
pt = pnext
pnext = Vector(sx-r,-sy)
if pt != pnext:
edges.append(Part.makeLine(pt,pnext))
pt = pnext
pnext = Vector(sx,r-sy)
if r:
if not chamfer:
edges.append(Part.makeCircle(r,Vector(sx-r,r-sy),n,270,360))
else:
edges.append(Part.makeLine(pt,pnext))
pt = pnext
if pt != pstart:
edges.append(Part.makeLine(pt,pstart))
return Part.Wire(edges)
#maui
def make_gr_poly(params):
if hasattr(params.pts,"xy"): #try:
points = SexpList(params.pts.xy)
# close the polygon
points._append(params.pts.xy._get(0))
# KiCAD polygon runs in clockwise, but FreeCAD wants CCW, so must reverse.
return Part.makePolygon([makeVect(p) for p in reversed(points)])
else: # hasattr(params.pts,"arc") #except:
arcs = SexpList(params.pts.arc)
return Part.makeCompound([make_gr_arc(arc) for arc in (arcs)])
# maui
def make_fp_poly(params):
points = SexpList(params.pts.xy)
# close the polygon
points._append(params.pts.xy._get(0))
# KiCAD polygon runs in clockwise, but FreeCAD wants CCW, so must reverse.
return Part.makePolygon([makeVect(p) for p in reversed(points)])
# maui
def make_gr_line(params):
return Part.makeLine(makeVect(params.start),makeVect(params.end))
def make_gr_arc(params):
if hasattr(params, 'angle'):
return makeArc(makeVect(params.start),makeVect(params.end),params.angle)
return Part.ArcOfCircle(makeVect(params.start),
makeVect(params.mid),
makeVect(params.end)).toShape()
def make_gr_curve(params):
return makeCurve([makeVect(p) for p in SexpList(params.pts.xy)])
def make_gr_circle(params, width=0):
center = makeVect(params.center)
end = makeVect(params.end)
r = center.distanceToPoint(end)
if not width or r <= width*0.5:
return Part.makeCircle(r+width*0.5, center)
return Part.makeCompound([Part.Wire(Part.makeCircle(r+width*0.5,center)),
Part.Wire(Part.makeCircle(r-width*0.5,center,Vector(0,0,-1)))])
# maui
def make_gr_circle_outl(params, width=0):
center = makeVect(params.center)
end = makeVect(params.end)
r = center.distanceToPoint(end)
if not width or r <= width*0.5:
return Part.makeCircle(r+width*0.5, center)
return [Part.makeCircle(r+width*0.5, center), Part.makeCircle(r-width*0.5,center)]
# def make_gr_circle_outl(params, width=0):
# center = makeVect(params.center)
# end = makeVect(params.end)
# r = center.distanceToPoint(end)
# #print(r,width*0.5)
# if (r <= abs(width*0.5) and width<0):
# return None #Part.makeCircle(0.01, center)
# else:
# return Part.makeCircle(r+width*0.5, center)
# #return Part.makeCompound([Part.Wire(Part.makeCircle(r+width*0.5,center)),
# # Part.Wire(Part.makeCircle(r-width*0.5,center,Vector(0,0,-1)))])
# maui
def make_gr_rect(params):
start = makeVect(params.start)
end = makeVect(params.end)
return Part.makePolygon([start, Vector(start.x, end.y), end, Vector(end.x, start.y), start])
def makePrimitve(key, params):
for param in SexpList(params):
try:
width = getattr(param,'width',0)
if width and key == 'gr_circle':
return make_gr_circle(param, width), 0
else:
make_shape = globals()['make_{}'.format(key)]
#if key == 'gr_poly':
# Part.show(Part.Face(make_fp_poly(params)))
return make_shape(param), width
except KeyError:
logger.warning('Unknown primitive {} in custom pad'.format(key))
return None, None
#try:
# width = getattr(params,'width',0)
# if width and key == 'gr_circle':
# return make_gr_circle(params, width), 0
# else:
# make_shape = globals()['make_{}'.format(key)]
# return make_shape(params), width
#except KeyError:
# logger.warning('Unknown primitive {} in custom pad'.format(key))
# return None, None
def makeThickLine(p1,p2,width):
length = p1.distanceToPoint(p2)
line = make_oval(Vector(length+2*width,2*width))
p = p2.sub(p1)
a = -degrees(DraftVecUtils.angle(p))
line.translate(Vector(length*0.5))
line.rotate(Vector(),Vector(0,0,1),a)
line.translate(p1)
return line
def makeArc(center,start,angle):
p = start.sub(center)
r = p.Length
a = -degrees(DraftVecUtils.angle(p))
# NOTE: KiCAD pcb geometry runs in clockwise, while FreeCAD is CCW. So the
# resulting arc below is the reverse of what's specified in kicad_pcb
if angle>0:
arc = Part.makeCircle(r,center,Vector(0,0,1),a-angle,a)
arc.reverse();
else:
arc = Part.makeCircle(r,center,Vector(0,0,1),a,a-angle)
return arc
def makeCurve(poles):
return Part.BSplineCurve(poles).toShape()
def findWires(edges):
try:
return [Part.Wire(e) for e in Part.sortEdges(edges)]
except AttributeError:
msg = 'Missing Part.sortEdges.'\
'You need newer FreeCAD (0.17 git 799c43d2)'
logger.error(msg)
raise AttributeError(msg)
def getFaceCompound(shape,wire=False):
objs = []
for f in shape.Faces:
selected = True
for v in f.Vertexes:
if not isZero(v.Z):
selected = False
break
if not selected:
continue
################################################################
## TODO: FreeCAD curve.normalAt is not implemented
################################################################
# for e in f.Edges:
# if isinstance(e.Curve,(Part.LineSegment,Part.Line)): continue
# if not isZero(e.normalAt(Vector()).dot(Vector(0,0,1))):
# selected = False
# break
# if not selected: continue
if not wire:
objs.append(f)
continue
for w in f.Wires:
objs.append(w)
if not objs:
raise ValueError('null shape')
return Part.makeCompound(objs)
def unpack(obj):
if not obj:
raise ValueError('null shape')
if isinstance(obj,(list,tuple)) and len(obj)==1:
return obj[0]
return obj
def getKicadPath(env=''):
confpath = ''
if env:
confpath = os.path.expanduser(os.environ.get(env,''))
if not os.path.isdir(confpath):
confpath=''
if not confpath:
if sys.platform == 'darwin':
confpath = os.path.expanduser('~/Library/Preferences/kicad')
elif sys.platform == 'win32':
confpath = os.path.join(
os.path.abspath(os.environ['APPDATA']),'kicad')
else:
confpath=os.path.expanduser('~/.config/kicad')
import re
kicad_common = os.path.join(confpath,'kicad_common')
if not os.path.isfile(kicad_common):
kicad_common += ".json"
if not os.path.isfile(kicad_common):
logger.warning('cannot find kicad_common')
return None
with open(kicad_common,'r', encoding='utf-8') as f:
content = f.read()
match = re.search(r'^\s*"*KISYS3DMOD"*\s*[:=]\s*([^\r\n]+)',content,re.MULTILINE)
if not match:
logger.warning('no KISYS3DMOD found')
return None
return match.group(1).rstrip(' "')
_model_cache = {}
def clearModelCache():
_model_cache = {}
def recomputeObj(obj):
obj.recompute()
obj.purgeTouched()
def loadModel(filename):
mtime = None
try:
mtime = os.path.getmtime(filename)
obj = _model_cache[filename]
if obj[2] == mtime:
logger.info('model cache hit');
return obj
else:
logger.info('model reload due to time stamp change');
except KeyError:
pass
except OSError:
return
import ImportGui
doc = getActiveDoc()
if not os.path.isfile(filename):
return
count = len(doc.Objects)
dobjs = []
try:
ImportGui.insert(filename,doc.Name)
dobjs = doc.Objects[count:]
obj = addObject(doc,'Part::Compound','tmp')
obj.Links = dobjs
recomputeObj(obj)
dobjs = [obj]+dobjs
obj = (obj.Shape.copy(),obj.ViewObject.DiffuseColor,mtime)
_model_cache[filename] = obj
return obj
except Exception as ex:
logger.error('failed to load model: {}'.format(ex))
finally:
for o in dobjs:
doc.removeObject(o.Name)
class KicadFcad:
def __init__(self,filename=None,debug=False,**kwds):
#############################################################
# Beginning of user customizable parameters during construction
self.prefix = ''
self.indent = ' '
self.make_sketch = False
self.sketch_use_draft = False
self.sketch_radius_precision = -1
self.holes_cache = {}
self.work_plane = Part.makeCircle(1)
self.active_doc_uuid = None
self.sketch_constraint = True
self.sketch_align_constraint = False
self.merge_holes = not debug
self.merge_vias = not debug
self.merge_tracks = not debug
self.zone_merge_holes = not debug
self.merge_pads = not debug # False # maui to evaluate for better pad results
self.arc_fit_accuracy = 0.0005
self.layer_thickness = 0.01
self.copper_thickness = 0.05
self.board_thickness = None
self.stackup = None
self.quote_no_parse = None
# set -1 to disable via in pads, 0 to enable as normal, >0 to use as
# a ratio to via radius for creating a square to simplify via
self.via_bound = 0
# whether to skip via hole if there is via_bound
self.via_skip_hole = None
self.add_feature = True
self.part_path = None
self.path_env = 'KICAD_CONFIG_HOME'
self.hole_size_offset = 0.0001
self.pad_inflate = 0
self.zone_inflate = 0
self.nets = []
if filename is None:
filename = '/home/thunder/pwr.kicad_pcb'
if not os.path.isfile(filename):
raise ValueError("file not found");
self.filename = filename
self.colors = {
'board':makeColor("0x3A6629"),
'pad':{0:makeColor(219,188,126)}, # maui pads color
'zone':{0:makeColor(0,80,0)},
'track':{0:makeColor(0,120,0)},
'copper':{0:makeColor(200,117,51)},
'F.Cu':{0:makeColor(200,117,51)}, # maui start color
'B.Cu':{0:makeColor(200,117,51)},
'F.SilkS':{0:makeColor(0,0,255)},
'B.SilkS':{0:makeColor(0,0,255)},
'F.CrtYd':{0:makeColor(255,170,255)},
'B.CrtYd':{0:makeColor(255,170,255)},
'F.Fab':{0:makeColor(0,255,0)},
'B.Fab':{0:makeColor(0,255,0)},
'F.Adhes':{0:makeColor(0,127,255)},
'B.Adhes':{0:makeColor(127,0,255)},
'Edge.Cuts':{0:makeColor(255,0,0)},
'Margin':{0:makeColor(255,170,170)},
'holes':{0:makeColor(170,255,127)},
'NetTie':{0:makeColor(255,114,12)},
'Dwgs.User':{0:makeColor(188,188,188)}, # maui end color
'Cmts.User':{0:makeColor(0,170,255)}, # maui end color
}
self.layer_type = 0
self.layer_match = None
# Ending of user customizable parameters
#############################################################
# checking user overridden parameters
for key,value in kwds.items():
if not hasattr(self,key):
raise ValueError('unknown parameter "{}"'.format(key))
setattr(self,key,value)
if not self.part_path:
self.part_path = getKicadPath(self.path_env)
self.pcb = KicadPCB.load(self.filename, self.quote_no_parse)
#print(str(self.pcb))
if self.pcb._key == 'footprint':
self.pcb._key = 'module'
if self.pcb._key == 'module':
# this is a kicad_mod file, make it look like a kicad_pcb
pcb = KicadPCB(parseSexp('''
(kicad_pcb
(general
(thickness 1.6) # maui
(drawings 0)
(tracks 0)
(zones 0)
(modules 1)
(nets 0)
)
(layers
(0 F.Cu signal)
(31 B.Cu signal)
(32 B.Adhes user)
(33 F.Adhes user)
(34 B.Paste user)
(35 F.Paste user)
(36 B.SilkS user)
(37 F.SilkS user)
(38 B.Mask user)
(39 F.Mask user)
(40 Dwgs.User user)
(41 Cmts.User user)
(42 Eco1.User user)
(43 Eco2.User user)
(44 Edge.Cuts user)
(45 Margin user)
(46 B.CrtYd user)
(47 F.CrtYd user)
(48 B.Fab user)
(49 F.Fab user)
)
)'''))
self.module = self.pcb
pcb.module._append(self.pcb)
#print(str(self.pcb))
self.pcb = pcb
else:
self.module = None
if not self.board_thickness:
try:
self.board_thickness = self.pcb.general.thickness
except Exception:
pass
if not self.board_thickness:
self.board_thickness = 1.6 # maui
self._dielectric_layers = []
self._stackup_map = {}
self._initStackUp()
# stores layer name as read from the file, may contain quotes depending
# on kicad version
self.layer_name = ''
# stores layer name without quote
self.layer = ''
self.setLayer(self.layer_type)
if self.via_skip_hole is None and self.via_bound:
self.via_skip_hole = True
self._nets = set()
self.net_names = dict()
if 'net' in self.pcb:
for n in self.pcb.net:
self.net_names[n[0]] = n[1]
self.setNetFilter(*self.nets)
def findLayer(self,layer, deftype=None):
try:
layer = int(layer)
except:
for layer_type in self.pcb.layers:
name = self.pcb.layers[layer_type][0]
if name==layer or unquote(name)==layer:
return (int(layer_type),name)
if deftype is not None:
return deftype, layer
raise KeyError('layer {} not found'.format(layer))
else:
if str(layer) not in self.pcb.layers:
if deftype is not None:
return deftype, str(layer)
raise KeyError('layer {} not found'.format(layer))
return (layer, self.pcb.layers[str(layer)][0])
def setLayer(self,layer):
self.layer_type, self.layer_name = self.findLayer(layer)
self.layer = unquote(self.layer_name)
if self.layer_type <= 31:
self.layer_match = '*.Cu'
else:
self.layer_match = '*.{}'.format(self.layer.split('.')[-1])
def _copperLayers(self):
coppers = [ (int(t),unquote(self.pcb.layers[t][0])) \
for t in self.pcb.layers if int(t)<=31]
coppers.sort(key=lambda x : x[0])
return coppers
def _initStackUp(self):
if self.stackup is None:
self._log('{}','kicad version='+str(self.pcb.version),level='info') # maui
self.stackup = []
stackup = getattr(getattr(self.pcb, 'setup', None), 'stackup', None)
if stackup:
try:
# If no stackup given by user, extract stack info from setup
offset = 0.0
last_copper = 0.0
for layer in stackup.layer:
layer_type, _ = self.findLayer(layer[0], 99)
t = getattr(layer, 'thickness',
self.copper_thickness if layer_type<=32 else self.layer_thickness)
if layer_type <= 31:
last_copper = offset
# Some layer (e.g. dielectric) may have more than one
# thickness field. Add them all.
if isinstance(t, SexpList):
total = 0.0
for tt in t:
# And for some thickness field, there may be additional
# attribute, like (thickness, 0.05, locked).
if isinstance(tt, (float, int)):
total += tt
else:
total += tt[0]
t = total
elif not isinstance(t, (float, int)):
t = t[0]
offset -= t
self.stackup.append([unquote(layer[0]), offset, t])
# adjust offset to make the last copper's upper face at z = 0.
# In other word, make the last dielectric layer reset at z = 0.
# Right now, makeBoard() always assume it is at z = 0.
for entry in self.stackup:
entry[1] -= last_copper
except Exception as e:# maui logging error and keeping kv5 compatibility
# raise
# self._log('Failed parsing stackup info: {}', str(e), level='warning') # maui
# traceback.print_exc() # maui
error_message = traceback.format_exc() #maui
self._log('{}',error_message,level='error') # maui
pass # maui keeping kv5 compatibility
else:
self._log('{}','kicad v5 stack missing',level='warning') # maui end
board_thickness = 0.0
accumulate = None
for item in self.stackup:
layer, name = self.findLayer(item[0], 99)
self._stackup_map[unquote(name)] = item
thickness = item[2]
if layer <= 31: # is copper layer
if accumulate is not None:
# counting intermediate layer(s) thickness
board_thickness += accumulate
accumulate = 0.0
else:
accumulate = 0.0
continue
if accumulate is not None:
accumulate += thickness
# only respect stackup if all copper layers are specified
coppers = self._copperLayers()
if self.stackup:
for _,name in coppers:
if unquote(name) not in self._stackup_map:
self._log('stackup info ignored because copper layer {} is not found',
name, level='warning')
self.stackup = []
self._stackup_map = {}
break
if self.stackup:
if board_thickness:
self.board_thickness = board_thickness
elif len(coppers) == 1:
name = coppers[0][1]
self._stackup_map[name] = [name, 0, self.copper_thickness]
else:
step = (self.board_thickness + self.copper_thickness) / (len(coppers)-1)
offset = self.board_thickness
for _,name in coppers:
self._stackup_map[name] = [name, offset, self.copper_thickness]
offset -= step
# setup dielectric layer offset and thickness. Going backwards, because
# makeBoard() assumes the first dielectric layer to be located at z=0
current = 1000.0
for _, name in reversed(coppers):
_, offset, thickness = self._stackup_map[name]
if offset > current:
self._dielectric_layers.append([current, offset - current])
current = offset + thickness
def layerOffsets(self, thickness=None):
coppers = self._copperLayers()
offsets = dict()
if not thickness:
for _, name in coppers:
offsets[name] = self._stackup_map[name][1]
return offsets
if len(coppers) == 1:
offsets[coppers[0][1]] = 0
return offsets
step = thickness / (len(coppers)-1)
offset = 0.0
for _,name in coppers:
offsets[name] = offset
offset += step
return offsets
def setNetFilter(self,*nets):
self._nets.clear()
ndict = dict()
nset = set()
for n in self.pcb.net:
ndict[n[1]] = n[0]
nset.add(n[0])
for n in nets:
try:
self._nets.add(ndict[str(n)])
continue
except Exception:
pass
try:
if int(n) in nset:
self._nets.add(int(n))
continue
except Exception:
pass
logger.error('net {} not found'.format(n))
def getNet(self,p):
n = p.net
return n if not isinstance(n,list) else n[0]
def filterNets(self,p):
try:
return self._nets and self.getNet(p) not in self._nets
except Exception:
return bool(self._nets)
def filterLayer(self,p):
layers = []
l = getattr(p, 'layers', [])
if unquote(l) == 'F&B.Cu': # maui
layers.append('F.Cu')
layers.append('B.Cu')
else:
layers = [unquote(s) for s in l]
if hasattr(p, 'layer'):
layers.append(unquote(p.layer))
if not layers:
self._log('no layers specified', level='warning')
return True
if self.layer not in layers \
and self.layer_match not in layers \
and '*' not in layers:
self._log('skip layer {}, {}, {}',
self.layer, self.layer_match, layers, level='trace')
return True
def netName(self,p):
try:
return unquote(self.net_names[self.getNet(p)])
except Exception:
return 'net?'
def _log(self,msg,*arg,**kargs):
level = 'info'
if kargs:
if 'level' in kargs:
level = kargs['level']
if logger.isEnabledFor(level):
getattr(logger,level)('{}{}'.format(self.prefix,msg.format(*arg)))
def _pushLog(self,msg=None,*arg,**kargs):
if msg:
self._log(msg,*arg,**kargs)
if 'prefix' in kargs:
prefix = kargs['prefix']
if prefix is not None:
self.prefix = prefix
self.prefix += self.indent
def _popLog(self,msg=None,*arg,**kargs):
self.prefix = self.prefix[:-len(self.indent)]
if msg:
self._log(msg,*arg,**kargs)
def _makeLabel(self,obj,label):
if self.layer:
obj.Label = '{}#{}'.format(obj.Name,self.layer)
if label is not None:
obj.Label += '#{}'.format(label)
def _makeObject(self,otype,name,
label=None,links=None,shape=None):
doc = getActiveDoc()
obj = addObject(doc,otype,name)
self._makeLabel(obj,label)
if links is not None:
setattr(obj,links,shape)
for s in shape if isinstance(shape,(list,tuple)) else (shape,):
if hasattr(s,'ViewObject'):
s.ViewObject.Visibility = False
if hasattr(obj,'recompute'):
recomputeObj(obj)
return obj
def _makeSketch(self,objs,name,label=None):
if self.sketch_use_draft:
import Draft
getActiveDoc()
nobj = Draft.makeSketch(objs,name=name,autoconstraints=True,
delete=True,radiusPrecision=self.sketch_radius_precision)
self._makeLabel(nobj,label)
return nobj
from Sketcher import Constraint
StartPoint = 1
EndPoint = 2
doc = getActiveDoc()
nobj = addObject(doc,"Sketcher::SketchObject", '{}_sketch'.format(name))
self._makeLabel(nobj,label)
nobj.ViewObject.Autoconstraints = False
radiuses = {}
constraints = []
def addRadiusConstraint(edge):
try:
if self.sketch_radius_precision<0:
return
if self.sketch_radius_precision==0:
constraints.append(Constraint('Radius',
nobj.GeometryCount-1, edge.Curve.Radius))
return
r = round(edge.Curve.Radius,self.sketch_radius_precision)
constraints.append(Constraint('Equal',
radiuses[r], nobj.GeometryCount-1))
except KeyError:
radiuses[r] = nobj.GeometryCount-1
constraints.append(Constraint('Radius',nobj.GeometryCount-1,r))