-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkiexport.py
2192 lines (1729 loc) · 95 KB
/
kiexport.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
#=============================================================================================#
# KiExport
# Tool to export manufacturing files from KiCad PCB projects.
# Author: Vishnu Mohanan (@vishnumaiea, @vizmohanan)
# Version: 0.0.28
# Last Modified: +05:30 04:24:26 PM 20-02-2025, Thursday
# GitHub: https://github.com/vishnumaiea/KiExport
# License: MIT
#=============================================================================================#
import subprocess
import argparse
import os
import re
from datetime import datetime
import zipfile
import json
import pymupdf
#=============================================================================================#
APP_NAME = "KiExport"
APP_VERSION = "0.0.28"
SAMPLE_PCB_FILE = "Mitayi-Pico-D1/Mitayi-Pico-RP2040.kicad_pcb"
current_config = None
default_config = None
DEFAULT_CONFIG_JSON = '''
{
"name": "KiExport.JSON",
"description": "Configuration file for KiExport",
"filetype": "json",
"version": "1.3",
"project_name": "Mitayi-Pico-RP2040",
"commands": ["gerbers", "drills", "sch_pdf", "bom", "ibom", "pcb_pdf", "positions", "svg", ["ddd", "STEP"], ["ddd", "VRML"]],
"kicad_cli_path": "C:\\\\Program Files\\\\KiCad\\\\9.0\\\\bin\\\\kicad-cli.exe",
"kicad_python_path": "C:\\\\Program Files\\\\KiCad\\\\8.0\\\\bin\\\\python.exe",
"ibom_path": "C:\\\\Users\\\\vishn\\\\Documents\\\\KiCad\\\\8.0\\\\3rdparty\\\\plugins\\\\org_openscopeproject_InteractiveHtmlBom\\\\generate_interactive_bom.py",
"data": {
"gerbers": {
"--output_dir": "Export",
"--layers": ["F.Cu","B.Cu","F.Paste","B.Paste","F.Silkscreen","B.Silkscreen","F.Mask","B.Mask","User.Drawings","User.Comments","Edge.Cuts","F.Courtyard","B.Courtyard","F.Fab","B.Fab"],
"--drawing-sheet": false,
"--exclude-refdes": false,
"--exclude-value": false,
"--include-border-title": false,
"--no-x2": false,
"--no-netlist": true,
"--subtract-soldermask": false,
"--disable-aperture-macros": false,
"--use-drill-file-origin": true,
"--precision": 6,
"--no-protel-ext": true,
"--common-layers": false,
"--board-plot-params": false,
"kie_include_drill": true
},
"drills": {
"--output_dir": "Export",
"--format": "excellon",
"--drill-origin": "plot",
"--excellon-zeros-format": "decimal",
"--excellon-oval-format": "route",
"--excellon-units": "mm",
"--excellon-mirror-y": false,
"--excellon-min-header": false,
"--excellon-separate-th": true,
"--generate-map": true,
"--map-format": "pdf",
"--gerber-precision": false
},
"bom": {
"CSV": {
"--output_dir": "Export",
"--preset": "Group by MPN-DNP",
"--format-preset": "CSV",
"--fields": "${ITEM_NUMBER},Reference,Value,Name,Footprint,${QUANTITY},${DNP},MPN,MFR,Alt MPN",
"--labels": "#,Reference,Value,Name,Footprint,Qty,DNP,MPN,MFR,Alt MPN",
"--group-by": "${DNP},MPN",
"--sort-field": false,
"--sort-asc": false,
"--filter": false,
"--exclude-dnp": false,
"--field-delimiter": false,
"--string-delimiter": false,
"--ref-delimiter": false,
"--ref-range-delimiter": false,
"--keep-tabs": false,
"--keep-line-breaks": false
},
"iBoM": {
"--output_dir": "Export",
"--show-dialog": false,
"--dark-mode": true,
"--hide-pads": false,
"--show-fabrication": false,
"--hide-silkscreen": false,
"--highlight-pin1": "all",
"--no-redraw-on-drag": false,
"--board-rotation": "0",
"--offset-back-rotation": "0",
"--checkboxes": "Source,Placed",
"--bom-view": "left-right",
"--layer-view": "FB",
"--no-compression": false,
"--no-browser": true,
"--include-tracks": true,
"--include-nets": true,
"--sort-order": "C,R,L,D,U,Y,X,F,SW,A,~,HS,CNN,J,P,NT,MH",
"--blacklist": false,
"--no-blacklist-virtual": false,
"--blacklist-empty-value": false,
"--netlist-file": false,
"--extra-data-file": false,
"--extra-fields": false,
"--show-fields": "Value,Footprint",
"--group-fields": "Value,Footprint",
"--normalize-field-case": false,
"--variant-fields": false,
"--variants-whitelist": false,
"--dnp-field": false
}
},
"sch_pdf": {
"--output_dir": "Export",
"--drawing-sheet": false,
"--theme": "User",
"--black-and-white": false,
"--exclude-drawing-sheet": false,
"--exclude-pdf-property-popups": false,
"--no-background-color": false,
"--pages": false
},
"pcb_pdf": {
"--output_dir": "Export",
"--layers": ["F.Cu","B.Cu","F.Paste","B.Paste","F.Silkscreen","B.Silkscreen","F.Mask","B.Mask","User.Drawings","User.Comments","Edge.Cuts","F.Courtyard","B.Courtyard","F.Fab","B.Fab"],
"kie_common_layers": ["Edge.Cuts"],
"--drawing-sheet": false,
"--mirror": false,
"--exclude-refdes": false,
"--exclude-value": false,
"--include-border-title": true,
"--negative": false,
"--black-and-white": false,
"--theme": "User",
"--drill-shape-opt": 2,
"kie_single_file": false
},
"positions": {
"--output_dir": "Export",
"--side": "front,back,both",
"--format": "csv",
"--units": "mm",
"--bottom-negate-x": false,
"--use-drill-file-origin": true,
"--smd-only": false,
"--exclude-fp-th": false,
"--exclude-dnp": false,
"--gerber-board-edge": false
},
"svg": {
"--output_dir": "Export",
"--layers": ["F.Cu","B.Cu","F.Paste","B.Paste","F.Silkscreen","B.Silkscreen","F.Mask","B.Mask","User.Drawings","User.Comments","Edge.Cuts","F.Courtyard","B.Courtyard","F.Fab","B.Fab"],
"kie_common_layers": [""],
"--drawing-sheet": false,
"--mirror": false,
"--theme": "User",
"--negative": false,
"--black-and-white": false,
"--page-size-mode": 0,
"--exclude-drawing-sheet": false,
"--drill-shape-opt": 2
},
"ddd": {
"STEP": {
"--output_dir": "Export",
"--force": true,
"--grid-origin": false,
"--drill-origin": false,
"--no-unspecified": false,
"--no-dnp": false,
"--subst-models": true,
"--board-only": false,
"--include-tracks": true,
"--include-zones": true,
"--min-distance": false,
"--no-optimize-step": false,
"--user-origin": false
},
"VRML": {
"--output_dir": "Export",
"--force": true,
"--user-origin": false,
"--units": "mm",
"--models-dir": false,
"--models-relative": false
}
}
}
}
'''
#=============================================================================================#
class Colorize:
def __init__(self, text):
self.text = text
self.ansi_code = '\033[0m' # Default to reset
def _color_text (self):
return f"{self.ansi_code}{self.text}\033[0m"
def red (self):
self.ansi_code = '\033[31m'
return self._color_text()
def green (self):
self.ansi_code = '\033[32m'
return self._color_text()
def yellow (self):
self.ansi_code = '\033[33m'
return self._color_text()
def blue (self):
self.ansi_code = '\033[34m'
return self._color_text()
def magenta (self):
self.ansi_code = '\033[35m'
return self._color_text()
def cyan (self):
self.ansi_code = '\033[36m'
return self._color_text()
# Define ANSI escape codes for colors
COLORS = {
'red': '\033[91m',
'green': '\033[92m',
'yellow': '\033[93m',
'blue': '\033[94m',
'magenta': '\033[95m',
'cyan': '\033[96m',
'reset': '\033[0m'
}
class _color:
def __call__ (self, text, color):
return f"{COLORS[color]}{text}{COLORS['reset']}"
def __getattr__ (self, color):
if color in COLORS:
return lambda text: self(text, color)
raise AttributeError (f"Color '{color}' is not supported.")
# Create an instance of the Colorize class
color = _color()
#=============================================================================================#
def generateiBoM (output_dir = None, pcb_filename = None, extra_args = None):
"""
Runs the KiCad iBOM Python script on a specified PCB file.
Args:
pcb_filename (str): Path to the KiCad PCB file (.kicad_pcb).
output_dir (str): Directory to save the output files. Defaults to the PCB file's directory.
extra_args (list): Additional command-line arguments for customization (optional).
Returns:
str: Path to the generated iBOM HTML file.
"""
# Read the paths.
kicad_python_path = f'{current_config.get ("kicad_python_path", default_config ["kicad_python_path"])}'
ibom_path = f'{current_config.get ("ibom_path", default_config ["ibom_path"])}'
# Check if the KiCad Python path exists.
if not os.path.isfile (kicad_python_path):
print (color.red (f"generateiBoM() [ERROR]: The KiCad Python path '{kicad_python_path}' does not exist. This command will be skipped."))
return
# Check if the iBOM script path exists.
if not os.path.isfile (ibom_path):
print (color.red (f"generateiBoM() [ERROR]: The iBOM path '{ibom_path}' does not exist. This command will be skipped."))
return
# Construct the iBOM command.
ibom_export_command = [f'"{kicad_python_path}"', f'"{ibom_path}"']
#---------------------------------------------------------------------------------------------#
# Ensure PCB file exists.
if not os.path.isfile (pcb_filename):
print (color.red (f"generateiBoM() [ERROR]: The PCB file '{pcb_filename}' does not exist. The command will be skipped."))
return
#---------------------------------------------------------------------------------------------#
file_name = extract_pcb_file_name (pcb_filename)
file_name = file_name.replace (" ", "-") # If there are whitespace characters in the project name, replace them with a hyphen
project_name = extract_project_name (file_name)
info = extract_info_from_pcb (pcb_filename)
print (f"generateiBoM() [INFO]: Project name is '{color.magenta (project_name)}' and revision is {color.magenta ('R')}{color.magenta (info ['rev'])}.")
# ibom_filename = f"{project_name}-R{info ['rev']}-HTML-BoM-{filename_date}.html"
#---------------------------------------------------------------------------------------------#
file_path = os.path.abspath (pcb_filename) # Get the absolute path of the file.
# Get the directory path of the file and save it as the project directory.
# All other export directories will be relative to the project directory.
project_dir = os.path.dirname (file_path)
# Read the output directory name from the config file.
od_from_config = project_dir + "/" + current_config.get ("data", {}).get ("bom", {}).get ("iBoM").get ("--output_dir", default_config ["data"]["bom"]["iBoM"]["--output_dir"])
od_from_cli = output_dir # The directory specified by the command line argument
# Get the final directory path
final_directory, filename_date = create_final_directory (od_from_config, od_from_cli, "BoM", info ["rev"], "generateiBoM")
#---------------------------------------------------------------------------------------------#
# Form the initial part of the command
full_command = []
full_command.extend (ibom_export_command) # Add the base command
seq_number = 1
not_completed = True
# Create the output file name.
while not_completed:
file_name = f"{final_directory}/{project_name}-R{info ['rev']}-BoM-HTML-{filename_date}-{seq_number}.html" # Extension needed here
if os.path.exists (file_name):
seq_number += 1
not_completed = True
else:
full_command.append ("--dest-dir")
full_command.append (f'"{final_directory}"') # Add the output file name with double quotes around it
full_command.append ("--name-format")
file_name = f"{project_name}-R{info ['rev']}-BoM-HTML-{filename_date}-{seq_number}" # No extension needed
full_command.append (f'"{file_name}"')
break
#---------------------------------------------------------------------------------------------#
# Get the argument list from the config file.
arg_list = current_config.get ("data", {}).get ("bom", {}).get ("iBoM")
# Add the remaining arguments.
# Check if the argument list is not an empty dictionary.
if arg_list:
for key, value in arg_list.items():
if key.startswith ("--"): # Only fetch the arguments that start with "--"
if key == "--output_dir": # Skip the --output_dir argument, sice we already added it
continue
elif key == "--name-format": # Skip the --name-format argument
continue
else:
# Check if the value is empty
if value == "": # Skip if the value is empty
continue
else:
# Check if the vlaue is a JSON boolean
if isinstance (value, bool):
if value == True: # If the value is true, then append the key as an argument
full_command.append (key)
else:
# Check if the value is a string and not a numeral
if isinstance (value, str) and not value.isdigit():
full_command.append (key)
full_command.append (f'"{value}"') # Add as a double-quoted string
elif isinstance (value, (int, float)):
full_command.append (key)
full_command.append (str (value)) # Append the numeric value as string
# Finally add the input file
full_command.append (f'"{pcb_filename}"')
print ("generateBom [INFO]: Running command: ", color.blue (' '.join (full_command)))
#---------------------------------------------------------------------------------------------#
# Run the iBOM script with error handling
try:
full_command = ' '.join (full_command) # Convert the list to a string
subprocess.run (full_command, check = True)
print (color.green (f"generateiBoM() [INFO]: Interactive HTML BoM generated successfully."))
except subprocess.CalledProcessError as e:
print (color.red (f"generateiBoM() [ERROR]: Error during HTML BoM generation: {e}"))
print (color.red (f"generateiBoM() [INFO]: Make sure the 'Interactive HTML BoM' application is installed and available on the PATH."))
except Exception as e:
print (color.red (f" generateiBoM() [ERROR]: An unexpected error occurred: {e}"))
#=============================================================================================#
def merge_pdfs (folder_path, output_file):
"""
Merges PDF files in a folder and creates a TOC based on file names.
Args:
folder_path (str): Path to the folder containing PDF files.
output_file (str): Name of the output PDF file.
"""
try:
# List all PDF files in the specified folder.
pdf_files = [f for f in os.listdir (folder_path) if f.endswith ('.pdf')]
if not pdf_files:
print (f"merge_pdfs() [WARNING]: No PDF files found in the specified folder.")
return
# pdf_files.sort() # Optional: sort the files alphabetically
doc = pymupdf.open() # Create a new PDF document
toc = [] # List to hold the Table of Contents entries
# Add each PDF to the document and create TOC entries
for pdf in pdf_files:
pdf_path = os.path.join (folder_path, pdf)
try:
with pymupdf.open (pdf_path) as pdf_doc:
start_page = doc.page_count # Get the starting page number
doc.insert_pdf (pdf_doc) # Merge the PDF
toc.append ((1, pdf [:-4], start_page + 1)) # Add TOC entry
except Exception as e:
print (color.red (f"merge_pdfs() [ERROR]: Error processing file {pdf}: {e}"))
# Set the Table of Contents
doc.set_toc (toc)
# Save the merged document
output_path = os.path.join (folder_path, output_file)
doc.save (output_path)
doc.close()
# # Delete original PDF files.
# for pdf in pdf_files:
# os.remove (os.path.join (folder_path, pdf))
# print (f"Merged PDF created: {output_path}")
# print ("Original PDF files have been deleted.")
except PermissionError:
print (color.red ("merge_pdfs() [ERROR]: Unable to access the specified folder or files."))
except Exception as e:
print (color.red (f"merge_pdfs() [ERROR]: {e}"))
#=============================================================================================#
def generateGerbers (output_dir, pcb_filename, to_overwrite = True):
# Generate the drill files first if specified
kie_include_drill = current_config.get ("data", {}).get ("gerbers", {}).get ("kie_include_drill", default_config ["data"]["gerbers"]["kie_include_drill"])
# Get the KiCad CLI path.
kicad_cli_path = f'{current_config.get ("kicad_cli_path", default_config ["kicad_cli_path"])}'
# Check if the value is boolean and then true or false
if isinstance (kie_include_drill, bool):
kie_include_drill = str (kie_include_drill).lower()
if kie_include_drill == "true":
kie_include_drill = True
elif kie_include_drill == "false":
kie_include_drill = False
if kie_include_drill == True:
generateDrills (output_dir, pcb_filename)
#---------------------------------------------------------------------------------------------#
# Common base command
gerber_export_command = [f'"{kicad_cli_path}"', "pcb", "export", "gerbers"]
# Check if the pcb file exists
if not check_file_exists (pcb_filename):
print (color.red (f"generateGerbers [ERROR]: '{pcb_filename}' does not exist."))
return
#---------------------------------------------------------------------------------------------#
file_name = extract_pcb_file_name (pcb_filename)
file_name = file_name.replace (" ", "-") # If there are whitespace characters in the project name, replace them with a hyphen
project_name = extract_project_name (file_name)
info = extract_info_from_pcb (pcb_filename)
print (f"generateGerbers [INFO]: Project name is '{color.magenta (project_name)}' and revision is {color.magenta ('R')}{color.magenta (info ['rev'])}.")
#---------------------------------------------------------------------------------------------#
file_path = os.path.abspath (pcb_filename) # Get the absolute path of the file.
# Get the directory path of the file and save it as the project directory.
# All other export directories will be relative to the project directory.
project_dir = os.path.dirname (file_path)
# Read the output directory name from the config file.
od_from_config = project_dir + "/" + current_config.get ("data", {}).get ("gerbers", {}).get ("--output_dir", default_config ["data"]["gerbers"]["--output_dir"])
od_from_cli = output_dir # The output directory specified by the command line argument
# Get the final directory path.
final_directory, filename_date = create_final_directory (od_from_config, od_from_cli, "Gerber", info ["rev"], "generateGerbers")
#---------------------------------------------------------------------------------------------#
# Get the argument list from the config file.
arg_list = current_config.get ("data", {}).get ("gerbers", {})
seq_number = 1
not_completed = True
full_command = []
full_command.extend (gerber_export_command) # Add the base command
full_command.append ("--output")
full_command.append (f'"{final_directory}"')
# Add the remaining arguments.
# Check if the argument list is not an empty dictionary.
if arg_list:
for key, value in arg_list.items():
if key.startswith ("--"): # Only fetch the arguments that start with "--"
if key == "--output_dir": # Skip the --output_dir argument, sice we already added it
continue
elif key == "--layers":
full_command.append (key)
layers_csv = ",".join (value) # Convert the list to a comma-separated string
full_command.append (f'"{layers_csv}"')
else:
# Check if the value is empty
if value == "": # Skip if the value is empty
continue
else:
# Check if the vlaue is a JSON boolean
if isinstance (value, bool):
if value == True: # If the value is true, then append the key as an argument
full_command.append (key)
else:
# Check if the value is a string and not a numeral
if isinstance (value, str) and not value.isdigit():
full_command.append (key)
full_command.append (f'"{value}"') # Add as a double-quoted string
elif isinstance (value, (int, float)):
full_command.append (key)
full_command.append (str (value)) # Append the numeric value as string
# Finally add the input file
full_command.append (f'"{pcb_filename}"')
print ("generateGerbers [INFO]: Running command: ", color.blue (' '.join (full_command)))
#---------------------------------------------------------------------------------------------#
# Delete the existing files in the output directory
delete_files (final_directory, include_extensions = [".gbr", ".gbrjob"])
#---------------------------------------------------------------------------------------------#
# Run the command
try:
full_command = ' '.join (full_command) # Convert the list to a string
subprocess.run (full_command, check = True)
print (color.green ("generateGerbers [OK]: Gerber files exported successfully."))
except subprocess.CalledProcessError as e:
print (color.red (f"generateGerbers [ERROR]: Error occurred: {e}"))
return
#---------------------------------------------------------------------------------------------#
# Rename the files by adding Revision after the project name.
rename_files (final_directory, project_name, info ['rev'], [".gbr", ".gbrjob"])
#---------------------------------------------------------------------------------------------#
seq_number = 1
not_completed = True
files_to_include = [".gbr", ".gbrjob"]
if kie_include_drill:
files_to_include.extend ([".drl", ".ps", ".pdf"])
# Sequentially name and create the zip files.
while not_completed:
zip_file_name = f"{project_name}-R{info ['rev']}-Gerber-{filename_date}-{seq_number}.zip"
if os.path.exists (f"{final_directory}/{zip_file_name}"):
seq_number += 1
else:
# zip_all_files (final_directory, f"{final_directory}/{zip_file_name}")
zip_all_files_2 (final_directory, files_to_include, zip_file_name)
print (f"generateGerbers [OK]: ZIP file '{color.magenta (zip_file_name)}' created successfully.")
print()
not_completed = False
#=============================================================================================#
def generateDrills (output_dir, pcb_filename):
# Get the KiCad CLI path.
kicad_cli_path = f'{current_config.get ("kicad_cli_path", default_config ["kicad_cli_path"])}'
# Common base command
drill_export_command = [f'"{kicad_cli_path}"', "pcb", "export", "drill"]
# Check if the pcb file exists
if not check_file_exists (pcb_filename):
print (color.red (f"generateDrills [ERROR]: '{pcb_filename}' does not exist."))
return
#-------------------------------------------------------------------------------------------#
file_name = extract_pcb_file_name (pcb_filename)
file_name = file_name.replace (" ", "-") # If there are whitespace characters in the project name, replace them with a hyphen
project_name = extract_project_name (file_name)
info = extract_info_from_pcb (pcb_filename)
print (f"generateDrills [INFO]: Project name is '{color.magenta (project_name)}' and revision is {color.magenta ('R')}{color.magenta (info ['rev'])}.")
#-------------------------------------------------------------------------------------------#
file_path = os.path.abspath (pcb_filename) # Get the absolute path of the file.
# Get the directory path of the file and save it as the project directory.
# All other export directories will be relative to the project directory.
project_dir = os.path.dirname (file_path)
# Read the target directory name from the config file
od_from_config = project_dir + "/" + current_config.get ("data", {}).get ("drills", {}).get ("--output_dir", default_config ["data"]["drills"]["--output_dir"])
od_from_cli = output_dir # The directory specified by the command line argument
# Get the final directory path
final_directory, filename_date = create_final_directory (od_from_config, od_from_cli, "Gerber", info ["rev"], "generateDrills")
# Check if the final directory ends with a slash, and add one if not.
if final_directory [-1] != "/":
final_directory = f"{final_directory}/"
#-------------------------------------------------------------------------------------------#
# Get the argument list from the config file.
arg_list = current_config.get ("data", {}).get ("drills", {})
seq_number = 1
not_completed = True
full_command = []
full_command.extend (drill_export_command) # Add the base command
full_command.append ("--output")
full_command.append (f'"{final_directory}"')
# Add the remaining arguments.
# Check if the argument list is not an empty dictionary.
if arg_list:
for key, value in arg_list.items():
if key.startswith ("--"): # Only fetch the arguments that start with "--"
if key == "--output_dir": # Skip the --output_dir argument, sice we already added it
continue
else:
# Check if the value is empty
if value == "": # Skip if the value is empty
continue
else:
# Check if the vlaue is a JSON boolean
if isinstance (value, bool):
if value == True: # If the value is true, then append the key as an argument
full_command.append (key)
else:
# Check if the value is a string and not a numeral
if isinstance (value, str) and not value.isdigit():
full_command.append (key)
full_command.append (f'"{value}"') # Add as a double-quoted string
elif isinstance (value, (int, float)):
full_command.append (key)
full_command.append (str (value)) # Append the numeric value as string
# Finally add the input file
full_command.append (f'"{pcb_filename}"')
print ("generateDrills [INFO]: Running command: ", color.blue (' '.join (full_command)))
#-------------------------------------------------------------------------------------------#
# Delete the existing files in the output directory
delete_files (final_directory, include_extensions = [".drl", ".ps", ".pdf"])
#-------------------------------------------------------------------------------------------#
# Run the command
try:
full_command = ' '.join (full_command) # Convert the list to a string
subprocess.run (full_command, check = True)
print (color.green ("generateDrills [OK]: Drill files exported successfully."))
print()
except subprocess.CalledProcessError as e:
print (color.red (f"generateDrills [ERROR]: Error occurred: {e}"))
print()
return
#-------------------------------------------------------------------------------------------#
# Rename the files by adding Revision after the project name.
rename_files (final_directory, project_name, info ['rev'], [".drl", ".ps", ".pdf"])
#=============================================================================================#
def generatePositions (output_dir, pcb_filename, to_overwrite = True):
global current_config # Access the global config
global default_config # Access the global config
# Get the KiCad CLI path.
kicad_cli_path = f'{current_config.get ("kicad_cli_path", default_config ["kicad_cli_path"])}'
# Common base command
position_export_command = [f'"{kicad_cli_path}"', "pcb", "export", "pos"]
# Check if the input file exists
if not check_file_exists (pcb_filename):
print (color.red (f"generatePositions [ERROR]: '{pcb_filename}' does not exist."))
return
#---------------------------------------------------------------------------------------------#
file_name = extract_pcb_file_name (pcb_filename)
file_name = file_name.replace (" ", "-") # If there are whitespace characters in the project name, replace them with a hyphen
project_name = extract_project_name (file_name)
info = extract_info_from_pcb (pcb_filename)
print (f"generatePositions [INFO]: Project name is '{color.magenta (project_name)}' and revision is {color.magenta ('R')}{color.magenta (info ['rev'])}.")
#---------------------------------------------------------------------------------------------#
file_path = os.path.abspath (pcb_filename) # Get the absolute path of the file.
# Get the directory path of the file and save it as the project directory.
# All other export directories will be relative to the project directory.
project_dir = os.path.dirname (file_path)
# Read the output directory name from the config file.
od_from_config = project_dir + "/" + current_config.get ("data", {}).get ("positions", {}).get ("--output_dir", default_config ["data"]["positions"]["--output_dir"])
od_from_cli = output_dir # The directory specified by the command line argument
# Get the final directory path
final_directory, filename_date = create_final_directory (od_from_config, od_from_cli, "Assembly", info ["rev"], "generatePositions")
#---------------------------------------------------------------------------------------------#
pos_front_filename = f"{final_directory}/{project_name}-Pos-Front.csv"
pos_back_filename = f"{final_directory}/{project_name}-Pos-Back.csv"
pos_all_filename = f"{final_directory}/{project_name}-Pos-All.csv"
# Create a list of filenames for front, back, and both.
pos_filenames = [pos_front_filename, pos_back_filename, pos_all_filename]
# Create a list of three command sets for front, back, and both.
full_command_list = []
for filename in pos_filenames:
full_command = position_export_command.copy() # Copy the base command
full_command.append ("--output")
full_command.append (f'"{filename}"')
full_command_list.append (full_command)
# Get the argument list from the config file.
arg_list = current_config.get ("data", {}).get ("positions", {})
sides = arg_list.get ("--side", None) # Get the sides from the config file as a string
# Check if the sides are valid and apply the default value if not
if sides == None or sides == "":
print (color.yellow (f"generatePositions [INFO]: No sides specified. Using both sides."))
sides = "both"
# Add the remaining arguments.
# Check if the argument list is not an empty dictionary.
if arg_list:
for i, command_set in enumerate (full_command_list):
for key, value in arg_list.items():
if key.startswith ("--"): # Only fetch the arguments that start with "--"
if key == "--output_dir": # Skip the --output_dir argument, sice we already added it
continue
elif key == "--side":
if sides.__contains__ ("front") and i == 0:
command_set.append (key)
command_set.append ("front")
elif sides.__contains__ ("back") and i == 1:
command_set.append (key)
command_set.append ("back")
elif sides.__contains__ ("both") and i == 2:
command_set.append (key)
command_set.append ("both")
else:
# Check if the value is empty
if value == "": # Skip if the value is empty
continue
else:
# Check if the vlaue is a JSON boolean
if isinstance (value, bool):
if value == True: # If the value is true, then append the key as an argument
command_set.append (key)
else:
# Check if the value is a string and not a numeral
if isinstance (value, str) and not value.isdigit():
command_set.append (key)
command_set.append (f'"{value}"') # Add as a double-quoted string
elif isinstance (value, (int, float)):
command_set.append (key)
command_set.append (str (value)) # Append the numeric value as string
# Finally append the filename to the commands
for command_set in full_command_list:
# board_file_path = os.path.abspath (pcb_filename)
command_set.append (f'"{pcb_filename}"')
#---------------------------------------------------------------------------------------------#
# Delete all non-zip files
delete_non_zip_files (final_directory)
#---------------------------------------------------------------------------------------------#
# Run the commands
for i, full_command in enumerate (full_command_list):
if (sides.__contains__ ("front") and i == 0) or (sides.__contains__ ("back") and i == 1) or (sides.__contains__ ("both") and i == 2):
try:
command_string = ' '.join (full_command) # Convert the list to a string
print (f"generatePositions [INFO]: Running command: {color.blue (command_string)}")
subprocess.run (command_string, check = True)
except subprocess.CalledProcessError as e:
print (color.red (f"generatePositions [ERROR]: Error occurred while generating the files."))
return
print (color.green ("generatePositions [OK]: Position files exported successfully."))
#---------------------------------------------------------------------------------------------#
# Rename the files by adding Revision after the project name.
rename_files (final_directory, project_name, info ['rev'], [".csv"])
#---------------------------------------------------------------------------------------------#
seq_number = 1
not_completed = True
files_to_include = [".csv"]
# Sequentially name and create the zip files.
while not_completed:
zip_file_name = f"{project_name}-R{info ['rev']}-Position-Files-{filename_date}-{seq_number}.zip"
if os.path.exists (f"{final_directory}/{zip_file_name}"):
seq_number += 1
else:
# zip_all_files (final_directory, f"{final_directory}/{zip_file_name}")
zip_all_files_2 (final_directory, files_to_include, zip_file_name)
print (f"generatePositions [OK]: ZIP file '{color.magenta (zip_file_name)}' created successfully.")
not_completed = False
#=============================================================================================#
def generatePcbPdf (output_dir, pcb_filename, to_overwrite = True):
# Get the KiCad CLI path.
kicad_cli_path = f'{current_config.get ("kicad_cli_path", default_config ["kicad_cli_path"])}'
# Common base command
pcb_pdf_export_command = [f'"{kicad_cli_path}"', "pcb", "export", "pdf"]
# Check if the pcb file exists
if not check_file_exists (pcb_filename):
print (color.red (f"generatePcbPdf [ERROR]: '{pcb_filename}' does not exist."))
return
#---------------------------------------------------------------------------------------------#
file_name = extract_pcb_file_name (pcb_filename)
file_name = file_name.replace (" ", "-") # If there are whitespace characters in the project name, replace them with a hyphen
project_name = extract_project_name (file_name)
info = extract_info_from_pcb (pcb_filename)
print (f"generatePcbPdf [INFO]: Project name is '{color.magenta (project_name)}' and revision is {color.magenta ('R')}{color.magenta (info ['rev'])}.")
#---------------------------------------------------------------------------------------------#
file_path = os.path.abspath (pcb_filename) # Get the absolute path of the file.
# Get the directory path of the file and save it as the project directory.
# All other export directories will be relative to the project directory.
project_dir = os.path.dirname (file_path)
# Read the output directory name from the config file.
od_from_config = project_dir + "/" + current_config.get ("data", {}).get ("pcb_pdf", {}).get ("--output_dir", default_config ["data"]["pcb_pdf"]["--output_dir"])
od_from_cli = output_dir # The output directory specified by the command line argument
# Get the final directory path
final_directory, filename_date = create_final_directory (od_from_config, od_from_cli, "PCB", info ["rev"], "generatePcbPdf")
#---------------------------------------------------------------------------------------------#
# Delete the existing files in the output directory
delete_files (final_directory, include_extensions = [".pdf", ".ps"])
#---------------------------------------------------------------------------------------------#
# Get the argument list from the config file.
arg_list = current_config.get ("data", {}).get ("pcb_pdf", {})
# Check the number of technical layers to export. This is not the number of copper layers.
layer_count = len (arg_list.get ("--layers", []))
if layer_count <= 0:
print (color.red (f"generatePcbPdf [ERROR]: No layers specified for export."))
return
# Get the number of common layers to include in each of the PDF.
# common_layer_count = len (arg_list.get ("kie_common_layers", []))
seq_number = 1
not_completed = True
base_command = []
base_command.extend (pcb_pdf_export_command) # Add the base command
for i in range (layer_count):
full_command = base_command [:]
# Get the arguments.
if arg_list: # Check if the argument list is not an empty dictionary.
for key, value in arg_list.items():
if key.startswith ("--"): # Only fetch the arguments that start with "--"
if key == "--output_dir": # Skip the --output_dir argument, sice we already added it
continue
elif key == "--layers":
layer_name = arg_list ["--layers"][i] # Get a layer name from the layer list
layer_name = layer_name.replace (".", "_") # Replace dots with underscores
layer_name = layer_name.replace (" ", "_") # Replace spaces with underscores
full_command.append ("--output")
full_command.append (f'"{final_directory}/{project_name}-R{info ["rev"]}-{layer_name}.pdf"') # This is the ouput file name, and not a directory name
layer_name = arg_list ["--layers"][i] # Get a layer name from the layer list
layer_list = [f"{layer_name}"] # Now create a list with the first item as the layer name
common_layer_list = arg_list ["kie_common_layers"] # Add the common layers
layer_list.extend (common_layer_list) # Now combine the two lists
layers_csv = ",".join (layer_list) # Convert the list to a comma-separated string
full_command.append (key)
full_command.append (f'"{layers_csv}"')
else:
# Check if the value is empty
if value == "": # Skip if the value is empty
continue
else:
# Check if the vlaue is a JSON boolean
if isinstance (value, bool):
if value == True: # If the value is true, then append the key as an argument
full_command.append (key)
else:
# Check if the value is a string and not a numeral
if isinstance (value, str) and not value.isdigit():
full_command.append (key)
full_command.append (f'"{value}"') # Add as a double-quoted string
elif isinstance (value, (int, float)):
full_command.append (key)
full_command.append (str (value)) # Append the numeric value as string
full_command.append (f'"{pcb_filename}"')
print ("generatePcbPdf [INFO]: Running command: ", color.blue (' '.join (full_command)))
# Run the command
try:
full_command = ' '.join (full_command) # Convert the list to a string
subprocess.run (full_command, check = True)
# print (color.green ("generatePcbPdf [OK]: PCB PDF files exported successfully."))
except subprocess.CalledProcessError as e:
print (color.red (f"generatePcbPdf [ERROR]: Error occurred: {e}"))
continue
#---------------------------------------------------------------------------------------------#
# # Generate a single file if specified
# kie_single_file = current_config.get ("data", {}).get ("pcb_pdf", {}).get ("kie_single_file", default_config ["data"]["pcb_pdf"]["kie_single_file"])
# # Check if the value is boolean and then true or false
# if isinstance (kie_single_file, bool):
# kie_single_file = str (kie_single_file).lower()
# if kie_single_file == "true":
# kie_single_file = True
# elif kie_single_file == "false":
# kie_single_file = False
# if kie_single_file == True:
# full_command.append (f'"{pcb_filename}"')
#---------------------------------------------------------------------------------------------#