Compare commits

..

7 Commits

Author SHA1 Message Date
Benny Megidish e2afaec677 chore: bump version 2025-04-30 19:35:08 +03:00
Guy Naor 1d441283f6 feat: added support for footprint rotation and position regex to also check the library nickname (#203)
This is because of the way Ultra Librarian setup the names with colon
2025-04-30 14:06:19 +03:00
Benny Megidish 08774e06ed chore: archive name PR cleanup #202, close #188 2025-03-25 18:59:00 +02:00
Lukas Lang 3778c9a1fa feat: add ability to customize archive name (#202)
* Add ability to customize archive name

* Remove incorrect autocomplete for ARCHIVE_NAME text box

---------

Co-authored-by: Lukas Lang <langl@phys.ethz.ch>
2025-03-25 18:47:04 +02:00
Lukas Lang 9922748010 fix: footprints rotations that are not a multiple of 90° (#198) 2025-03-20 11:56:20 +02:00
Randall Scharpf b98c02c743 feat: add common abbreviations for part number (pn, p/n, part no.) (#201) 2025-03-20 11:53:00 +02:00
Benny Megidish 89d587b1cd chore: initial v10 support #200 2025-03-18 09:01:17 +02:00
9 changed files with 151 additions and 43 deletions
+22 -14
View File
@@ -39,7 +39,9 @@ Options can be set in the dialog that appears when the plugin is invoked. They a
<img src="https://github.com/bennymeg/JLC-Plugin-for-KiCad/blob/master/assets/options.png?raw=true" height=275>
__Archive name__: Name of the archive file to be generated. Can include text variables, such as e.g. `${TITLE}_${REVISION}`</br>
__Additional layers__: Comma-separated list of additional layers to include in the gerber archive.</br>
__Plot all active layers__: Whether to include all layers, instead of just the layers required by JLCPCB.</br>
__Set User.1 as V-Cut layer__: Merge User.1 layer with the Edge-Cut layer in production.</br>
__Use User.2 for an alternative Edge-Cut layer__: Use the User.2 instead of the Edge-Cut layer for the board outline in production. This is useful if you need process edges or panelization during production but still want to keep the individual outline for prototyping, 3D model exports, or similar purposes.</br>
__Apply automatic translations__: Apply known translation fixes for common components.</br>
@@ -52,8 +54,8 @@ Add an 'LCSC Part #'* field with the LCSC component part number to the symbol's
<img src="https://github.com/bennymeg/JLC-Plugin-for-KiCad/blob/master/assets/mpn.png?raw=true" height=420>
#### Primary Fields*:
| 'LCSC Part #' | 'LCSC Part' | 'JLCPCB Part #' | 'JLCPCB Part' |
| --- | --- | --- | --- |
| 'LCSC Part #' | 'LCSC Part' | 'LCSC PN' | 'LCSC P/N' | 'LCSC Part No.' | 'JLCPCB Part #' | 'JLCPCB Part' | 'JLCPCB PN' | 'JLCPCB P/N' | 'JLCPCB Part No.' |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
_The fields will be query in the order denoted above._
@@ -178,25 +180,31 @@ The plugin can be called with the command below:
python3 -m plugins.cli -p /myProject/myBoard.kicad_pcb
```
The all options from the GUI are also available via the cli interface:
All the options from the GUI are also available via the cli interface:
```
python3 -m plugins.cli -h
usage: Fabrication Toolkit [-h] --path PATH [--additionalLayers LAYERS] [--user1VCut] [--user2AltVCut] [--autoTranslate] [--autoFill] [--excludeDNP] [--allActiveLayers] [--openBrowser]
usage: Fabrication Toolkit [-h] --path PATH [--additionalLayers LAYERS] [--user1VCut] [--user2AltVCut]
[--autoTranslate] [--autoFill] [--excludeDNP] [--allActiveLayers] [--archiveName NAME]
[--openBrowser]
Generates JLCPCB production files from a KiCAD board file
options:
-h, --help show this help message and exit
--path PATH, -p PATH Path to KiCAD board file
--additionalLayers LAYERS, -aL LAYERS Additional layers(comma-separated)
--user1VCut, -u1 Set User.1 as V-Cut layer
--user2AltVCut, -u2 Use User.2 for alternative Edge-Cut layer
--autoTranslate, -t Apply automatic position/rotation translations
--autoFill, -f Apply automatic fill for all zones
--excludeDNP, -e Exclude DNP components from BOM
--allActiveLayers, -aaL Export all active layers instead of only commonly used ones
--openBrowser, -b Open web browser with directory file overview after generation
-h, --help show this help message and exit
--path PATH, -p PATH Path to KiCAD board file
--additionalLayers LAYERS, -aL LAYERS
Additional layers(comma-separated)
--user1VCut, -u1 Set User.1 as V-Cut layer
--user2AltVCut, -u2 Use User.2 for alternative Edge-Cut layer
--autoTranslate, -t Apply automatic position/rotation translations
--autoFill, -f Apply automatic fill for all zones
--excludeDNP, -e Exclude DNP components from BOM
--allActiveLayers, -aaL
Export all active layers instead of only commonly used ones
--archiveName NAME, -aN NAME
Name of the generated archives
--openBrowser, -b Open web browser with directory file overview after generation
```
Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 16 KiB

+1 -1
View File
@@ -30,7 +30,7 @@
],
"versions": [
{
"version": "5.0.1",
"version": "5.1.0",
"status": "stable",
"kicad_version": "6.00"
}
+3 -1
View File
@@ -9,13 +9,14 @@ if __name__ == '__main__':
description="Generates JLCPCB production files from a KiCAD board file")
parser.add_argument("--path", "-p", type=str, help="Path to KiCAD board file", required=True)
parser.add_argument("--additionalLayers", "-aL", type=str, help="Additional layers(comma-separated)")
parser.add_argument("--additionalLayers", "-aL", type=str, help="Additional layers(comma-separated)", metavar="LAYERS")
parser.add_argument("--user1VCut", "-u1", action="store_true", help="Set User.1 as V-Cut layer")
parser.add_argument("--user2AltVCut", "-u2", action="store_true", help="Use User.2 for alternative Edge-Cut layer")
parser.add_argument("--autoTranslate", "-t", action="store_true", help="Apply automatic position/rotation translations")
parser.add_argument("--autoFill", "-f", action="store_true", help="Apply automatic fill for all zones")
parser.add_argument("--excludeDNP", "-e", action="store_true", help="Exclude DNP components from BOM")
parser.add_argument("--allActiveLayers", "-aaL",action="store_true", help="Export all active layers instead of only commonly used ones")
parser.add_argument("--archiveName", "-aN", type=str, help="Name of the generated archives", metavar="NAME")
parser.add_argument("--openBrowser", "-b", action="store_true", help="Open webbrowser with directory file overview after generation")
args = parser.parse_args()
@@ -26,6 +27,7 @@ if __name__ == '__main__':
options[EXTEND_EDGE_CUT_OPT] = args.user1VCut
options[ALTERNATIVE_EDGE_CUT_OPT] = args.user2AltVCut
options[ALL_ACTIVE_LAYERS_OPT] = args.allActiveLayers
options[ARCHIVE_NAME] = args.archiveName
options[EXTRA_LAYERS] = args.additionalLayers
openBrowser = args.openBrowser
+1
View File
@@ -5,4 +5,5 @@ OUTPUT_NAME_OPT = "OUTPUT NAME"
EXTEND_EDGE_CUT_OPT = "EXTEND_EDGE_CUT"
ALTERNATIVE_EDGE_CUT_OPT = "ALTERNATIVE_EDGE_CUT"
ALL_ACTIVE_LAYERS_OPT = "ALL_ACTIVE_LAYERS"
ARCHIVE_NAME = "ARCHIVE_NAME"
EXTRA_LAYERS = "EXTRA_LAYERS"
+10 -2
View File
@@ -4,7 +4,7 @@ import pcbnew # type: ignore
from .thread import ProcessThread
from .events import StatusEvent
from .options import AUTO_FILL_OPT, AUTO_TRANSLATE_OPT, EXCLUDE_DNP_OPT, EXTEND_EDGE_CUT_OPT, ALTERNATIVE_EDGE_CUT_OPT, EXTRA_LAYERS, ALL_ACTIVE_LAYERS_OPT
from .options import AUTO_FILL_OPT, AUTO_TRANSLATE_OPT, EXCLUDE_DNP_OPT, EXTEND_EDGE_CUT_OPT, ALTERNATIVE_EDGE_CUT_OPT, EXTRA_LAYERS, ALL_ACTIVE_LAYERS_OPT, ARCHIVE_NAME
from .utils import load_user_options, save_user_options, get_layer_names
@@ -30,6 +30,7 @@ class KiCadToJLCForm(wx.Frame):
userOptions = load_user_options({
EXTRA_LAYERS: "",
ALL_ACTIVE_LAYERS_OPT: False,
ARCHIVE_NAME: "",
EXTEND_EDGE_CUT_OPT: False,
ALTERNATIVE_EDGE_CUT_OPT: False,
AUTO_TRANSLATE_OPT: True,
@@ -42,10 +43,14 @@ class KiCadToJLCForm(wx.Frame):
layers = get_layer_names(pcbnew.GetBoard())
self.mAdditionalLayersControl = wx.TextCtrl(self, size=wx.Size(600, 50))
self.mAdditionalLayersControl.Hint = "Additional layers (comma-separated)"
self.mAdditionalLayersControl.Hint = "Additional layers (comma-separated) [optional]"
self.mAdditionalLayersControl.AutoComplete(layers)
self.mAdditionalLayersControl.Enable()
self.mAdditionalLayersControl.SetValue(userOptions[EXTRA_LAYERS])
self.mArchiveNameControl = wx.TextCtrl(self, size=wx.Size(600, 50))
self.mArchiveNameControl.Hint = "Archive name (e.g. ${TITLE}_${REVISION}) [optional]"
self.mArchiveNameControl.Enable()
self.mArchiveNameControl.SetValue(userOptions[ARCHIVE_NAME])
self.mAllActiveLayersCheckbox = wx.CheckBox(self, label='Plot all active layers')
self.mAllActiveLayersCheckbox.SetValue(userOptions[ALL_ACTIVE_LAYERS_OPT])
self.mExtendEdgeCutsCheckbox = wx.CheckBox(self, label='Set User.1 as V-Cut layer')
@@ -71,6 +76,7 @@ class KiCadToJLCForm(wx.Frame):
boxSizer.Add(self.mOptionsLabel, 0, wx.ALL, 5)
# boxSizer.Add(self.mOptionsSeparator, 0, wx.ALL, 5)
boxSizer.Add(self.mArchiveNameControl, 0, wx.ALL, 5)
boxSizer.Add(self.mAdditionalLayersControl, 0, wx.ALL, 5)
boxSizer.Add(self.mAllActiveLayersCheckbox, 0, wx.ALL, 5)
boxSizer.Add(self.mExtendEdgeCutsCheckbox, 0, wx.ALL, 5)
@@ -100,6 +106,7 @@ class KiCadToJLCForm(wx.Frame):
def onGenerateButtonClick(self, event):
options = dict()
options[ARCHIVE_NAME] = self.mArchiveNameControl.GetValue()
options[EXTRA_LAYERS] = self.mAdditionalLayersControl.GetValue()
options[ALL_ACTIVE_LAYERS_OPT] = self.mAllActiveLayersCheckbox.GetValue()
options[EXTEND_EDGE_CUT_OPT] = self.mExtendEdgeCutsCheckbox.GetValue()
@@ -111,6 +118,7 @@ class KiCadToJLCForm(wx.Frame):
save_user_options(options)
self.mOptionsLabel.Hide()
self.mArchiveNameControl.Hide()
self.mAdditionalLayersControl.Hide()
self.mAllActiveLayersCheckbox.Hide()
self.mExtendEdgeCutsCheckbox.Hide()
+74 -21
View File
@@ -67,7 +67,7 @@ class ProcessManager:
plot_options.SetSubtractMaskFromSilk(True)
plot_options.SetUseGerberX2format(False)
plot_options.SetDrillMarksType(0) # NO_DRILL_SHAPE
if hasattr(plot_options, "SetExcludeEdgeLayer"):
plot_options.SetExcludeEdgeLayer(True)
@@ -117,10 +117,21 @@ class ProcessManager:
netlist_writer = pcbnew.IPC356D_WRITER(self.board)
netlist_writer.Write(os.path.join(temp_dir, netlistFileName))
def _get_footprint_position(self, footprint):
def _get_footprint_rotation(self, footprint):
return footprint.GetOrientation().AsDegrees() if hasattr(footprint.GetOrientation(), 'AsDegrees') else footprint.GetOrientation() / 10.0
def _get_footprint_position(self, footprint):
"""Calculate position based on center of pads / bounding box."""
origin_type = self._get_origin_from_footprint(footprint)
footprint_rotation = self._get_footprint_rotation(footprint)
footprint_rotated = footprint_rotation % 90 != 0
# if the footprint is not rotated by a multiple of 90 degrees, the bounding boxes will be off, so we create a temporary copy that is rotated to 0
if footprint_rotated:
footprint = footprint.Duplicate()
footprint.SetOrientationDegrees(0)
if origin_type == 'Anchor':
position = footprint.GetPosition()
else: # if type_origin == 'Center' or anything else
@@ -133,7 +144,20 @@ class ProcessManager:
position = bbox.GetCenter()
else:
position = footprint.GetPosition() # if we have no pads we fallback to anchor
if footprint_rotated:
# now we determine the offset of the "true" position relative to the "KiCAD" position & apply the footprints rotation
raw_pos = footprint.GetPosition()
relative_position = (position[0] - raw_pos[0], position[1] - raw_pos[1])
rsin = math.sin(footprint_rotation / 180 * math.pi)
rcos = math.cos(footprint_rotation / 180 * math.pi)
relative_position = ( relative_position[0] * rcos + relative_position[1] * rsin, -relative_position[0] * rsin + relative_position[1] * rcos )
position = (raw_pos[0] + relative_position[0], raw_pos[1] + relative_position[1])
return position
def generate_tables(self, temp_dir, auto_translate, exclude_dnp):
@@ -164,6 +188,13 @@ class ProcessManager:
except AttributeError:
footprint_name = str(footprint.GetFPID().GetLibItemName())
# Get the library nickname when available
lib_nickname = None
try:
lib_nickname = str(footprint.GetFPID().GetLibNickname())
except AttributeError:
pass
layer = self._get_layer_override_from_footprint(footprint)
# mount_type = {
@@ -172,8 +203,8 @@ class ProcessManager:
# 2: 'unspecified'
# }.get(footprint.GetAttributes())
is_dnp = (footprint_has_field(footprint, 'dnp')
or (footprint.GetValue().upper() == 'DNP')
is_dnp = (footprint_has_field(footprint, 'dnp')
or (footprint.GetValue().upper() == 'DNP')
or getattr(footprint, 'IsDNP', bool)())
skip_dnp = exclude_dnp and is_dnp
@@ -188,14 +219,14 @@ class ProcessManager:
position = self._get_footprint_position(footprint)
mid_x = (position[0] - self.board.GetDesignSettings().GetAuxOrigin()[0]) / 1000000.0
mid_y = (position[1] - self.board.GetDesignSettings().GetAuxOrigin()[1]) * -1.0 / 1000000.0
rotation = footprint.GetOrientation().AsDegrees() if hasattr(footprint.GetOrientation(), 'AsDegrees') else footprint.GetOrientation() / 10.0
rotation_offset_db = self._get_rotation_from_db(footprint_name) # internal database offset
rotation_offset_manual = self._get_rotation_offset_from_footprint(footprint) # explicated offset by the designer
rotation = self._get_footprint_rotation(footprint)
rotation_offset_db = self._get_rotation_from_db(footprint_name, lib_nickname) # Try with lib_nickname if available
rotation_offset_manual = self._get_rotation_offset_from_footprint(footprint)
# position offset needs to take rotation into account
pos_offset = self._get_position_offset_from_footprint(footprint)
if auto_translate:
pos_offset_db = self._get_position_offset_from_db(footprint_name)
pos_offset_db = self._get_position_offset_from_db(footprint_name, lib_nickname) # Try with lib_nickname if available
pos_offset = (pos_offset[0] + pos_offset_db[0], pos_offset[1] + pos_offset_db[1])
rsin = math.sin(rotation / 180 * math.pi)
@@ -294,7 +325,7 @@ class ProcessManager:
os.remove(os.path.join(temp_dir, item))
return temp_file
""" Private """
def __read_rotation_db(self, filename: str = os.path.join(os.path.dirname(__file__), 'transformations.csv')) -> dict[str, float]:
@@ -352,14 +383,18 @@ class ProcessManager:
db[rowNum]['name'] = row['footprint']
db[rowNum]['rotation'] = rotation
db[rowNum]['x'] = delta_x
db[rowNum]['y'] = delta_y
db[rowNum]['y'] = delta_y
return db
def _get_rotation_from_db(self, footprint: str) -> float:
'''Get the rotation to be added from the database file.'''
# Look for regular expression math of the footprint name and not its root library.
def _get_rotation_from_db(self, footprint: str, lib_nickname: str = None) -> float:
'''Get the rotation to be added from the database file.
Args:
footprint: The footprint name
lib_nickname: The library nickname, if available
'''
# First try with the standard approach for backward compatibility
for entry in self.__rotation_db.items():
# If the expression in the DB contains a :, search for it literally.
if (re.search(':', entry[1]['name'])):
@@ -377,13 +412,23 @@ class ProcessManager:
if (re.search(entry[1]['name'], check)):
return float(entry[1]['rotation'])
# If no match found and we have a library nickname, try matching against that
if lib_nickname:
for entry in self.__rotation_db.items():
if (re.search(entry[1]['name'], lib_nickname)):
return float(entry[1]['rotation'])
# Not found, no rotation.
return 0.0
def _get_position_offset_from_db(self, footprint: str) -> Tuple[float, float]:
'''Get the rotation to be added from the database file.'''
# Look for regular expression math of the footprint name and not its root library.
def _get_position_offset_from_db(self, footprint: str, lib_nickname: str = None) -> Tuple[float, float]:
'''Get the position offset to be added from the database file.
Args:
footprint: The footprint name
lib_nickname: The library nickname, if available
'''
# First try with the standard approach for backward compatibility
for entry in self.__rotation_db.items():
# If the expression in the DB contains a :, search for it literally.
if (re.search(':', entry[1]['name'])):
@@ -399,14 +444,22 @@ class ProcessManager:
else:
check = footprint_segments[1]
if (re.search(entry[1]['name'], check)):
return ( float(entry[1]['x']), float(entry[1]['y']) )
return (float(entry[1]['x']), float(entry[1]['y']))
# If no match found and we have a library nickname, try matching against that
if lib_nickname:
for entry in self.__rotation_db.items():
if (re.search(entry[1]['name'], lib_nickname)):
return (float(entry[1]['x']), float(entry[1]['y']))
# Not found, no delta.
return (0.0, 0.0)
def _get_mpn_from_footprint(self, footprint) -> str:
''''Get the MPN/LCSC stock code from standard symbol fields.'''
keys = ['LCSC Part #', 'LCSC Part', 'JLCPCB Part #', 'JLCPCB Part']
supplier_names = ['LCSC', 'JLCPCB']
pn_abbrevs = ['Part #', 'Part', 'PN', 'P/N', 'Part No.']
keys = [(sn + " " + abr) for sn in supplier_names for abr in pn_abbrevs]
fallback_keys = ['LCSC', 'JLC', 'MPN', 'Mpn', 'mpn']
if footprint_has_field(footprint, 'dnp'):
@@ -479,7 +532,7 @@ class ProcessManager:
return (float(offset[0]), float(offset[1]))
except Exception as e:
raise RuntimeError("Position offset of {} is not a valid pair of numbers".format(footprint.GetReference()))
def _get_origin_from_footprint(self, footprint) -> float:
'''Get the origin from standard symbol fields.'''
keys = ['FT Origin']
@@ -490,7 +543,7 @@ class ProcessManager:
# determine origin type by package type
if attributes & pcbnew.FP_SMD:
origin_type = 'Anchor'
else:
else:
origin_type = 'Center'
for key in keys + fallback_keys:
+31 -2
View File
@@ -39,6 +39,30 @@ class ProcessThread(Thread):
self.openBrowser = openBrowser
self.start()
def expandTextVariables(self, string):
titleBlock = pcbnew.GetBoard().GetTitleBlock()
titleBlockVars = {
"ISSUE_DATE": titleBlock.GetDate(),
"CURRENT_DATE": datetime.datetime.now().strftime('%Y-%m-%d'),
"REVISION": titleBlock.GetRevision(),
"TITLE": titleBlock.GetTitle(),
"COMPANY": titleBlock.GetCompany(),
}
for comment_index in range(9):
titleBlockVars[f"COMMENT{comment_index + 1}"] = titleBlock.GetComment(comment_index)
for var, val in titleBlockVars.items():
string = string.replace(f"${{{var}}}", val)
if (hasattr(self.process_manager.board, "GetProject") and hasattr(pcbnew, "ExpandTextVars")):
project = self.process_manager.board.GetProject()
string = pcbnew.ExpandTextVars(string, project)
return string
def run(self):
# initializing
self.progress(0)
@@ -128,11 +152,16 @@ class ProcessThread(Thread):
os.makedirs(output_path)
# rename gerber archive
gerberArchiveName = ProcessManager.normalize_filename("_".join(("{} {}".format(title or filename, revision or '').strip() + '.zip').split()))
if self.options[ARCHIVE_NAME]:
baseName = self.expandTextVariables(self.options[ARCHIVE_NAME])
else:
baseName = "{} {}".format(title or filename, revision or '')
gerberArchiveName = ProcessManager.normalize_filename("_".join((baseName.strip() + '.zip').split()))
os.rename(temp_file, os.path.join(temp_dir, gerberArchiveName))
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')
backup_name = ProcessManager.normalize_filename("_".join(("{} {} {}".format(title or filename, revision or '', timestamp).strip()).split()))
backup_name = ProcessManager.normalize_filename("_".join(("{} {}".format(baseName, timestamp).strip()).split()))
shutil.make_archive(os.path.join(output_path, 'backups', backup_name), 'zip', temp_dir)
+9 -2
View File
@@ -7,6 +7,9 @@ import wx
def get_version():
return float('.'.join(pcbnew.GetBuildVersion().split(".")[0:2])) # e.g GetBuildVersion(): e.g. '7.99.0-3969-gc5ac2337e4'
def is_v10(version = get_version()):
return version >= 9.99 and version < 10.99
def is_v9(version = get_version()):
return version >= 8.99 and version < 9.99
@@ -22,7 +25,9 @@ def is_v6(version = get_version()):
def footprint_has_field(footprint, field_name):
version = get_version()
if is_v8(version) or is_v9(version):
if is_v10(version):
return footprint.HasField(field_name)
elif is_v8(version) or is_v9(version):
return footprint.HasFieldByName(field_name)
else:
return footprint.HasProperty(field_name)
@@ -30,7 +35,9 @@ def footprint_has_field(footprint, field_name):
def footprint_get_field(footprint, field_name):
version = get_version()
if is_v8(version) or is_v9(version):
if is_v10(version):
return footprint.GetField(field_name).GetText()
elif is_v8(version) or is_v9(version):
return footprint.GetFieldByName(field_name).GetText()
else:
return footprint.GetProperty(field_name)