-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkicad_cmp_converter.py
88 lines (73 loc) · 3.55 KB
/
kicad_cmp_converter.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
import sys
import os
import getopt
import json
class cmp_to_x_converter(object):
def __init__(self, infilepath, output_file_name, output_type='json'):
infilepath=os.path.abspath(infilepath)
infile_dir = os.path.dirname(infilepath)
output_file_path = os.path.join(infile_dir, output_file_name)
components={}
with open(infilepath,"r") as kicadCmpFile:
lastline=""
for line in kicadCmpFile:
#the cmp file delimeter is =, get everthing after the first occurence
value = line.split("=")[1:]
#rejoin with = in case there was an equal sign in the value
value = "=".join(value).strip()
# strip the semicolon at the end if present
if value.endswith(';'):
value = value[:-1]
if line.startswith('ValeurCmp'):
lastValeurCmp = value
if line.startswith('IdModule'):
#KiCad appends an _id
lastIdModule = value
if line.startswith('Reference'):
lastRef = value
if line.startswith('EndCmp'):
try:
components[(lastValeurCmp,lastIdModule)]['quantity'] += 1
components[(lastValeurCmp,lastIdModule)]['references'].append(lastRef)
except KeyError:
components[(lastValeurCmp,lastIdModule)] = {'quantity': 1, 'references': [lastRef] }
lastValeurCmp = ''
lastIdModule = ''
lastRef = ''
self.components=[]
#convert tuple to nested dict
for component in components:
self.components.append({'value':component[0], 'footprint':component[1], 'quantity': components[component]['quantity'], 'references': components[component]['references']})
of = open(output_file_path, 'w')
if output_type == 'json':
of.write(json.dumps(self.components))
elif output_type == 'csv':
first_item = self.components[0]
# write the column headers
of.write('quantity,value,footprint,references\n')
for item in self.components:
if len(item['references'])>1:
refs_string = ','.join(item['references'])
refs_string = '"{}"'.format(refs_string)
else:
refs_string = item['references'][0]
# create the text string for the row data
out_line = '{},{},{},{}\n'.format(item['quantity'], item['value'], item['footprint'], refs_string)
# write the row data
of.write(out_line)
of.close()
def convert_to_json_then_run_browser():
import webbrowser
print os.path.split(__file__)
webbrowser.open_new(os.path.abspath(os.path.join(os.path.split(__file__)[0], "main.html")))
def main2(argv):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input_file", help="input_file should be a KiCad .cmp file")
parser.add_argument("output_file_name", help="output_file_name is the name for the output file (CSV or JSON), it will be placed in the input_file's directory")
parser.add_argument("output_type", help="output_type is either CSV or JSON")
args = parser.parse_args()
#print args
p = cmp_to_x_converter(args.input_file, args.output_file_name, output_type=args.output_type.lower())
if __name__ == "__main__":
main2(sys.argv[1:])