-
Notifications
You must be signed in to change notification settings - Fork 2
/
fabrication.py
258 lines (226 loc) · 9.51 KB
/
fabrication.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
import csv
import logging
import os
import re
from pathlib import Path
from zipfile import ZipFile
from pcbnew import (
EXCELLON_WRITER,
PCB_PLOT_PARAMS,
PLOT_CONTROLLER,
PLOT_FORMAT_GERBER,
ZONE_FILLER,
B_Cu,
B_Mask,
B_Paste,
B_SilkS,
Cmts_User,
Edge_Cuts,
F_Cu,
F_Mask,
F_Paste,
F_SilkS,
GetBoard,
GetBuildVersion,
In1_Cu,
In2_Cu,
In3_Cu,
In4_Cu,
Refresh,
ToMM,
)
from .helpers import get_exclude_from_pos, get_footprint_by_ref, get_smd, is_nightly
class Fabrication:
def __init__(self, parent):
self.logger = logging.getLogger(__name__)
self.parent = parent
self.board = GetBoard()
self.corrections = []
self.path, self.filename = os.path.split(self.board.GetFileName())
self.create_folders()
def create_folders(self):
"""Create output folders if they not already exist."""
self.outputdir = os.path.join(self.path, "nextpcb_amf", "output_files")
Path(self.outputdir).mkdir(parents=True, exist_ok=True)
self.gerberdir = os.path.join(self.path, "nextpcb_amf", "gerber")
Path(self.gerberdir).mkdir(parents=True, exist_ok=True)
def fill_zones(self):
"""Refill copper zones following user prompt."""
#if self.parent.settings.get("gerber", {}).get("fill_zones", True):
filler = ZONE_FILLER(self.board)
zones = self.board.Zones()
filler.Fill(zones)
Refresh()
def get_position(self, footprint):
"""Calculate position based on center of bounding box"""
if get_smd(footprint):
return footprint.GetPosition()
bbox = footprint.GetBoundingBox(False, False)
return bbox.GetCenter()
def generate_geber(self, layer_count=None):
"""Generating Gerber files"""
# inspired by https://github.com/KiCad/kicad-source-mirror/blob/master/demos/python_scripts_examples/gen_gerber_and_drill_files_board.py
pctl = PLOT_CONTROLLER(self.board)
popt = pctl.GetPlotOptions()
# https://github.com/KiCad/kicad-source-mirror/blob/master/pcbnew/pcb_plot_params.h
popt.SetOutputDirectory(self.gerberdir)
# Plot format to Gerber
# https://github.com/KiCad/kicad-source-mirror/blob/master/include/plotter.h#L67-L78
popt.SetFormat(1)
# General Options
popt.SetPlotValue(True)
popt.SetPlotReference(True)
popt.SetPlotInvisibleText(False)
popt.SetSketchPadsOnFabLayers(False)
# Gerber Options
popt.SetUseGerberProtelExtensions(False)
popt.SetCreateGerberJobFile(False)
popt.SetSubtractMaskFromSilk(True)
popt.SetPlotViaOnMaskLayer(False) # Set this to True if you need untented vias
popt.SetUseAuxOrigin(True)
# Tented vias or not, selcted by user in settings
popt.SetPlotViaOnMaskLayer(True)
popt.SetUseGerberX2format(True)
popt.SetIncludeGerberNetlistInfo(True)
popt.SetDisableGerberMacros(False)
if is_nightly(GetBuildVersion()):
from pcbnew import DRILL_MARKS_NO_DRILL_SHAPE
popt.SetDrillMarksType(DRILL_MARKS_NO_DRILL_SHAPE)
else:
popt.SetDrillMarksType(PCB_PLOT_PARAMS.NO_DRILL_SHAPE)
popt.SetPlotFrameRef(False)
# delete all existing files in the output directory first
for f in os.listdir(self.gerberdir):
os.remove(os.path.join(self.gerberdir, f))
# if no layer_count is given, get the layer count from the board
if not layer_count:
layer_count = self.board.GetCopperLayerCount()
if layer_count == 1:
plot_plan = [
("CuTop", F_Cu, "Top layer"),
("SilkTop", F_SilkS, "Silk top"),
("MaskTop", F_Mask, "Mask top"),
("PasteTop", F_Paste, "Paste top"),
("EdgeCuts", Edge_Cuts, "Edges"),
("VScore", Cmts_User, "V score cut"),
]
elif layer_count == 2:
plot_plan = [
("CuTop", F_Cu, "Top layer"),
("SilkTop", F_SilkS, "Silk top"),
("MaskTop", F_Mask, "Mask top"),
("PasteTop", F_Paste, "Paste top"),
("CuBottom", B_Cu, "Bottom layer"),
("SilkBottom", B_SilkS, "Silk top"),
("MaskBottom", B_Mask, "Mask bottom"),
("PasteBottom", B_Paste, "Paste bottom"),
("EdgeCuts", Edge_Cuts, "Edges"),
("VScore", Cmts_User, "V score cut"),
]
elif layer_count == 4:
plot_plan = [
("CuTop", F_Cu, "Top layer"),
("SilkTop", F_SilkS, "Silk top"),
("MaskTop", F_Mask, "Mask top"),
("PasteTop", F_Paste, "Paste top"),
("CuIn1", In1_Cu, "Inner layer 1"),
("CuIn2", In2_Cu, "Inner layer 2"),
("CuBottom", B_Cu, "Bottom layer"),
("SilkBottom", B_SilkS, "Silk top"),
("MaskBottom", B_Mask, "Mask bottom"),
("PasteBottom", B_Paste, "Paste bottom"),
("EdgeCuts", Edge_Cuts, "Edges"),
("VScore", Cmts_User, "V score cut"),
]
elif layer_count == 6:
plot_plan = [
("CuTop", F_Cu, "Top layer"),
("SilkTop", F_SilkS, "Silk top"),
("MaskTop", F_Mask, "Mask top"),
("PasteTop", F_Paste, "Paste top"),
("CuIn1", In1_Cu, "Inner layer 1"),
("CuIn2", In2_Cu, "Inner layer 2"),
("CuIn3", In3_Cu, "Inner layer 3"),
("CuIn4", In4_Cu, "Inner layer 4"),
("CuBottom", B_Cu, "Bottom layer"),
("SilkBottom", B_SilkS, "Silk top"),
("MaskBottom", B_Mask, "Mask bottom"),
("PasteBottom", B_Paste, "Paste bottom"),
("EdgeCuts", Edge_Cuts, "Edges"),
("VScore", Cmts_User, "V score cut"),
]
for layer_info in plot_plan:
if layer_info[1] <= B_Cu:
popt.SetSkipPlotNPTH_Pads(True)
else:
popt.SetSkipPlotNPTH_Pads(False)
pctl.SetLayer(layer_info[1])
pctl.OpenPlotfile(layer_info[0], PLOT_FORMAT_GERBER, layer_info[2])
if pctl.PlotLayer() is False:
self.logger.error(f"Error plotting {layer_info[2]}")
self.logger.info(f"Successfully plotted {layer_info[2]}")
pctl.ClosePlot()
def generate_excellon(self):
"""Generate Excellon files."""
drlwriter = EXCELLON_WRITER(self.board)
mirror = False
minimalHeader = False
offset = self.board.GetDesignSettings().GetAuxOrigin()
mergeNPTH = False
drlwriter.SetOptions(mirror, minimalHeader, offset, mergeNPTH)
drlwriter.SetFormat(False)
genDrl = True
genMap = True
drlwriter.CreateDrillandMapFilesSet(self.gerberdir, genDrl, genMap)
self.logger.info("Finished generating Excellon files")
def zip_gerber_excellon(self):
"""Zip Gerber and Excellon files, ready for upload."""
zipname = f"GERBER-{self.filename.split('.')[0]}.zip"
with ZipFile(os.path.join(self.outputdir, zipname), "w") as zipfile:
for folderName, subfolders, filenames in os.walk(self.gerberdir):
for filename in filenames:
if not filename.endswith(("gbr", "drl", "pdf")):
continue
filePath = os.path.join(folderName, filename)
zipfile.write(filePath, os.path.basename(filePath))
self.logger.info("Finished generating ZIP file")
def generate_cpl(self):
"""Generate placement file (CPL)."""
cplname = f"CPL-{self.filename.split('.')[0]}.csv"
#self.corrections = self.parent.library.get_all_correction_data()
aux_orgin = self.board.GetDesignSettings().GetAuxOrigin()
with open(
os.path.join(self.outputdir, cplname), "w", newline="", encoding="utf-8"
) as csvfile:
writer = csv.writer(csvfile, delimiter=",")
writer.writerow(
["Designator", "Val", "Package", "Mid X", "Mid Y", "Rotation", "Layer"]
)
for part in self.parent.store.read_pos_parts():
for fp in get_footprint_by_ref(self.board, part[0]):
if get_exclude_from_pos(fp):
continue
position = self.get_position(fp) - aux_orgin
writer.writerow(
[
part[0],
part[1],
part[2],
ToMM(position.x),
ToMM(position.y) * -1,
'',
"top" if fp.GetLayer() == 0 else "bottom",
]
)
self.logger.info("Finished generating CPL file")
def generate_bom(self):
"""Generate BOM file."""
bomname = f"BOM-{self.filename.split('.')[0]}.csv"
with open(
os.path.join(self.outputdir, bomname), "w", newline="", encoding="utf-8"
) as csvfile:
writer = csv.writer(csvfile, delimiter=",")
writer.writerow(["Value", "Designator", "Footprint", "MPN"])
for part in self.parent.store.read_bom_parts():
writer.writerow(part)
self.logger.info("Finished generating BOM file")