This repository has been archived by the owner on Jan 9, 2021. It is now read-only.
forked from essele/kicad_jlcpcba
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jlcpcba_main.py
220 lines (180 loc) · 6.43 KB
/
jlcpcba_main.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
#
# Create a JLCPCB PCBA set of files to support PCBA, this requires us to
# produce a BOM file and a CPL (component placement file), which will be a
# .pos file.
#
# We do this by reading the associated schematic (mainly for part numbers)
# and then cross-matching the pcb modules.
#
import pcbnew
import os
import re
from . import sch_reader
#
# Setup a few useful globals...
#
global path
global name
global rotdb
#
# Read the rotations.cf config file so we know what rotations to apply
# later.
#
def read_rotdb(filename):
db = []
fh = open(filename, "r")
for line in fh:
line = line.rstrip()
line = re.sub('#.*$', '', line) # remove anything after a comment
line = re.sub('\s*$', '', line) # remove all trailing space
if (line == ""):
continue
m = re.match('^([^\s]+)\s+(\d+)$', line)
if m:
db.append((m.group(1), int(m.group(2))))
print(line)
return db
#
# Given the footprint name, work out what rotation is needed, we support
# matching against the long or short footprint names (if there is a colon
# in the regex)
#
def possible_rotate(footprint):
fpshort = footprint.split(':')[1]
for rot in rotdb:
ex = rot[0]
delta = rot[1]
fp = fpshort
if (re.search(':', ex)):
fp = footprint
if(re.search(ex, fp)):
return delta
return 0
def read_all_schematics(d):
"""
Read all schematics in the directory d
returns a list of SchematicPart
"""
all_parts = []
for fn in os.listdir(d):
fn_lower = fn.lower()
if fn_lower.endswith('.sch') or fn_lower.endswith('.kicad_sch'):
parts = sch_reader.read_schematic(os.path.join(d, fn))
all_parts += parts
return all_parts
used_refs = set()
def deduplicate_reference(ref):
global used_refs
ref_letters = ''.join(filter(lambda c: not c.isdigit(), ref))
ref_digits = ''.join(filter(lambda c: c.isdigit(), ref))
if not ref in used_refs:
used_refs.add(ref)
return ref
else:
# Try +100 etc, until we find an unused ref.
# Find number in ref
for n in range(1,10):
num = int(ref_digits) + (100*n)
newref = ref_letters + str(num)
if not newref in used_refs:
used_refs.add(newref)
return newref
#
# Actually create the PCBA files...
#
def create_pcba():
global path
global name
global rotdb
global used_refs
used_refs = set()
board = pcbnew.GetBoard()
boardfile = board.GetFileName()
path = os.path.dirname(boardfile)
# Grab all the schematics
all_schematic_parts = read_all_schematics(path)
if len(all_schematic_parts) == 0:
raise Exception("No JLCPCB parts found in any schematic in current dir")
name = os.path.splitext(os.path.basename(boardfile))[0]
# Open both layer files...
posfiles = [] # top and bottom files
for layer in 'top', 'bottom':
posfn = os.path.join(path, name + '_' + layer + '_pos.csv')
f = open(posfn, 'wt')
print("Designator,Val,Package,Mid X,Mid Y,Rotation,Layer", file=f)
posfiles.append(f)
del f
# Open bom file
bomfn = os.path.join(path, name + '_bom.csv')
bomfile = open(bomfn, 'wt')
print("Comment,Designator,Footprint,LCSC", file=bomfile)
#
# Populate the rotation db (do it here so editing and retrying is easy)
#
rotdb = read_rotdb(os.path.join(os.path.dirname(__file__), 'rotations.cf'))
for m in board.GetModules():
pathstr = m.GetPath().AsString()
# Gives something like: '/00000000-0000-0000-0000-00005e3c9710'
uid0 = pathstr.replace('/', '')
uid = uid0.replace('-', '')
# Remove leading zeroes
while uid.startswith('0'):
uid = uid[1:]
uid = uid.lower()
smd = ((m.GetAttributes() & pcbnew.MOD_CMS) == pcbnew.MOD_CMS)
x = m.GetPosition().x/1000000.0
y = m.GetPosition().y/1000000.0
rot = m.GetOrientation()/10.0
layer = m.GetLayerName()
print("Got module = " + uid + " smd=" + str(smd) + " x=" + str(x) + " y=" + str(y) + " rot=" + str(rot) + "layer="+str(layer))
if not (smd and (uid != '')):
# Skip this module, it is not interesting.
print(" ... Ignoring")
continue
# Find the part in the schematic to check its LCSC part number
# we should match reference, uid and value
# (in case someone panelised 2 variants of the same pcb with different resistor or capacitor...)
reference = m.GetReference()
value = m.GetValue()
print("Finding part, uid={} reference={} value={}".format(uid, reference, value))
# TODO
found_parts = []
for p in all_schematic_parts:
if p.uid.lower() in (uid.lower(), uid0.lower()):
if (p.reference, p.value) == (reference, value):
# Found
found_parts.append(p)
if len(found_parts) == 0:
# If part is not found, we will skip it.
print(" ... not found")
continue
if len(found_parts) > 1:
raise Exception("Duplicate part found for {}".format(reference))
found_part = found_parts[0]
print("Found part in schematic, part {} footprint {}".format(found_part.lcsc, found_part.footprint))
newref = deduplicate_reference(reference)
print(".. renamed reference to {}".format(newref))
footprint = found_part.footprint
# Now do the rotation needed...
rot = (rot + possible_rotate(footprint)) % 360
# Now write to the top and bottom file respectively
fpshort = footprint.split(':')[1]
fh = posfiles[0]
lname = "top"
y = y * -1 # y is negative always???
if (smd):
if (layer == "B.Cu"):
fh = posfiles[1]
lname = "bottom"
print('"{}","{}","{}",{},{},{},{}'.format(
newref, value, fpshort, x, y, rot, lname),
file=fh)
del fh
# comment, reference, footprint, lcsc
print('"{}","{}","{}","{}"'.format(
value, newref, fpshort, found_part.lcsc),
file=bomfile)
for f in posfiles:
f.close()
bomfile.close()
#create()