kicad2easyeda 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ """Export KiCad projects (schematic + PCB) to EasyEDA Standard format."""
2
+
3
+ __version__ = '0.1.0'
4
+
5
+ from .project import ExportResult, export_project # noqa: E402
6
+
7
+ __all__ = ['ExportResult', 'export_project', '__version__']
@@ -0,0 +1,43 @@
1
+ """kicad2easyeda: export a KiCad project to an EasyEDA Standard project.
2
+
3
+ Writes, into the output directory (default: ./easyeda_out):
4
+ PCB_<name>.json, SCH_<name>.json open via File > Open > EasyEDA...
5
+ BackupProjects_<name>.zip EasyEDA project backup (both documents)
6
+ <name>_export_report.txt everything that could not be mapped 1:1
7
+ """
8
+
9
+ import argparse
10
+ import os
11
+ import sys
12
+
13
+ from . import __version__
14
+ from .project import export_project
15
+
16
+
17
+ def main(argv=None):
18
+ ap = argparse.ArgumentParser(prog='kicad2easyeda', description=__doc__,
19
+ formatter_class=argparse.RawDescriptionHelpFormatter)
20
+ ap.add_argument('project', help='.kicad_pro, .kicad_pcb, .kicad_sch or project directory')
21
+ ap.add_argument('-o', '--output', default='easyeda_out', help='output directory')
22
+ ap.add_argument('--name', help='document name (default: the project name)')
23
+ ap.add_argument('--no-sch', action='store_true', help='skip the schematic')
24
+ ap.add_argument('--no-pcb', action='store_true', help='skip the PCB')
25
+ ap.add_argument('-q', '--quiet', action='store_true', help='print nothing on success')
26
+ ap.add_argument('--version', action='version', version='%(prog)s ' + __version__)
27
+ args = ap.parse_args(argv)
28
+
29
+ try:
30
+ result = export_project(args.project, args.output, pcb=not args.no_pcb,
31
+ schematic=not args.no_sch, name=args.name)
32
+ except (OSError, ValueError) as e:
33
+ print('kicad2easyeda: error: %s' % e, file=sys.stderr)
34
+ return 1
35
+ if not args.quiet:
36
+ print('\n'.join(result.summary))
37
+ print('Notes: %d (see %s)' % (len(result.notes),
38
+ os.path.basename(result.files['report'])))
39
+ return 0
40
+
41
+
42
+ if __name__ == '__main__':
43
+ sys.exit(main())
@@ -0,0 +1,240 @@
1
+ """Helpers shared by the PCB and schematic exporters."""
2
+
3
+ import math
4
+ import re
5
+
6
+ EDITOR_VERSION = '6.5.34'
7
+
8
+ # EasyEDA Standard reserves these sequences as field / item separators.
9
+ _FORBIDDEN = (('#@$', '#'), ('^^', '^'), ('~', '-'), ('`', "'"))
10
+
11
+
12
+ class Warnings:
13
+ """Collects conversion notes, de-duplicated with an occurrence count."""
14
+
15
+ def __init__(self):
16
+ self._items = {}
17
+
18
+ def add(self, msg):
19
+ self._items[msg] = self._items.get(msg, 0) + 1
20
+
21
+ def lines(self):
22
+ return ['%s%s' % (msg, ' (x%d)' % n if n > 1 else '') for msg, n in self._items.items()]
23
+
24
+
25
+ class IdGen:
26
+ def __init__(self, start=1):
27
+ self.n = start
28
+
29
+ def __call__(self):
30
+ self.n += 1
31
+ return 'gge%d' % self.n
32
+
33
+
34
+ def clean_field(text):
35
+ """Make text safe to place inside a '~'-separated EasyEDA field."""
36
+ text = str(text).replace('\r', '').replace('\n', '\\n')
37
+ for bad, good in _FORBIDDEN:
38
+ text = text.replace(bad, good)
39
+ return text
40
+
41
+
42
+ _MARKUP = re.compile(r'([~_^])\{([^{}]*)\}')
43
+
44
+
45
+ def plain_text(text):
46
+ """Strip KiCad text markup: ~{X} -> X#, _{X} -> _X / X, ^{X} -> X."""
47
+
48
+ def repl(m):
49
+ kind, body = m.groups()
50
+ if kind == '~':
51
+ return body + '#'
52
+ if kind == '_':
53
+ return '_' + body
54
+ return body
55
+
56
+ prev = None
57
+ while prev != text:
58
+ prev, text = text, _MARKUP.sub(repl, text)
59
+ return text
60
+
61
+
62
+ class NetNames:
63
+ """Maps KiCad net names to unique EasyEDA-safe names (shared by PCB and SCH)."""
64
+
65
+ def __init__(self):
66
+ self._map = {}
67
+ self._used = set()
68
+
69
+ def __call__(self, name):
70
+ if not name:
71
+ return ''
72
+ if name in self._map:
73
+ return self._map[name]
74
+ base = clean_field(plain_text(name))
75
+ out, n = base, 1
76
+ while out in self._used:
77
+ n += 1
78
+ out = '%s_%d' % (base, n)
79
+ self._map[name] = out
80
+ self._used.add(out)
81
+ return out
82
+
83
+ def renamed(self):
84
+ return {k: v for k, v in self._map.items() if k != v}
85
+
86
+
87
+ def num(v, nd=4):
88
+ """Compact number formatting used in EasyEDA source."""
89
+ if abs(v) < 0.5 * 10 ** -nd:
90
+ return '0'
91
+ s = ('%.*f' % (nd, v)).rstrip('0').rstrip('.')
92
+ return '0' if s in ('-0', '') else s
93
+
94
+
95
+ def rotate(x, y, deg):
96
+ """Rotate (x, y) by deg using KiCad's convention (CCW on screen, Y down)."""
97
+ if not deg:
98
+ return x, y
99
+ r = math.radians(deg)
100
+ c, s = math.cos(r), math.sin(r)
101
+ return x * c + y * s, -x * s + y * c
102
+
103
+
104
+ def arc_center(p1, p2, p3):
105
+ """Circle through three points; returns (cx, cy) or None if collinear."""
106
+ (x1, y1), (x2, y2), (x3, y3) = p1, p2, p3
107
+ d = 2 * (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2))
108
+ if abs(d) < 1e-12:
109
+ return None
110
+ ux = ((x1 * x1 + y1 * y1) * (y2 - y3) + (x2 * x2 + y2 * y2) * (y3 - y1)
111
+ + (x3 * x3 + y3 * y3) * (y1 - y2)) / d
112
+ uy = ((x1 * x1 + y1 * y1) * (x3 - x2) + (x2 * x2 + y2 * y2) * (x1 - x3)
113
+ + (x3 * x3 + y3 * y3) * (x2 - x1)) / d
114
+ return ux, uy
115
+
116
+
117
+ def arc_sweep(start, mid, end, center):
118
+ """Signed sweep (degrees, positive = increasing screen angle = clockwise)."""
119
+ cx, cy = center
120
+ a0 = math.atan2(start[1] - cy, start[0] - cx)
121
+ am = math.atan2(mid[1] - cy, mid[0] - cx)
122
+ a1 = math.atan2(end[1] - cy, end[0] - cx)
123
+
124
+ def norm(a):
125
+ return a % (2 * math.pi)
126
+
127
+ ccw = norm(am - a0) <= norm(a1 - a0) # going "increasing angle" passes mid
128
+ sweep = norm(a1 - a0)
129
+ if not ccw:
130
+ sweep = sweep - 2 * math.pi
131
+ return math.degrees(sweep)
132
+
133
+
134
+ def arc_points(center, radius, a_start_deg, sweep_deg, max_err):
135
+ """Approximate an arc by points (screen angles, Y down)."""
136
+ if radius <= 0:
137
+ return []
138
+ max_err = min(max_err, radius)
139
+ step = 2 * math.degrees(math.acos(max(-1.0, 1 - max_err / radius))) or 10
140
+ n = max(1, int(math.ceil(abs(sweep_deg) / step)))
141
+ cx, cy = center
142
+ out = []
143
+ for i in range(n + 1):
144
+ a = math.radians(a_start_deg + sweep_deg * i / n)
145
+ out.append((cx + radius * math.cos(a), cy + radius * math.sin(a)))
146
+ return out
147
+
148
+
149
+ def _norm(key):
150
+ return re.sub(r'[^a-z0-9]', '', key.lower())
151
+
152
+
153
+ _LCSC_RE = re.compile(r'^C\d{3,}$')
154
+
155
+
156
+ def bom_fields(props):
157
+ """Find supplier/MPN/manufacturer in arbitrarily named KiCad fields.
158
+
159
+ Returns a dict with any of 'Supplier Part' (LCSC "C" number), 'Manufacturer Part'
160
+ and 'Manufacturer'. Field names are matched loosely ("LCSC ID", "LCSC Part #",
161
+ "JLCPCB Part", "MPN", "Manufacturer_Part_Number", ...).
162
+ """
163
+ out = {}
164
+ for key, value in props.items():
165
+ value = str(value).strip()
166
+ if not value or value == '~':
167
+ continue
168
+ k = _norm(key)
169
+ if 'Supplier Part' not in out and ('lcsc' in k or 'jlc' in k) \
170
+ and _LCSC_RE.match(value.upper()):
171
+ out['Supplier Part'] = value.upper()
172
+ elif 'Manufacturer Part' not in out and (
173
+ k in ('mpn', 'pn', 'partnumber', 'mfrpn', 'mfrpartnumber')
174
+ or ('manufacturer' in k and ('part' in k or 'pn' in k))):
175
+ out['Manufacturer Part'] = value
176
+ elif 'Manufacturer' not in out and k in ('manufacturer', 'mfr', 'manufacturername',
177
+ 'mfg', 'vendor'):
178
+ out['Manufacturer'] = value
179
+ return out
180
+
181
+
182
+ def signed_area(pts):
183
+ return sum(x1 * y2 - x2 * y1 for (x1, y1), (x2, y2) in zip(pts, pts[1:] + pts[:1])) / 2
184
+
185
+
186
+ def fracture(outer, holes=()):
187
+ """Merge holes into the outline through zero-width bridges, giving one closed
188
+ outline (EasyEDA regions cannot hold holes). Same idea as KiCad's Fracture()."""
189
+ poly = list(outer)
190
+ if signed_area(poly) < 0:
191
+ poly.reverse()
192
+ pending = []
193
+ for h in holes:
194
+ h = list(h)
195
+ if len(h) < 3:
196
+ continue
197
+ if signed_area(h) > 0:
198
+ h.reverse()
199
+ pending.append(h)
200
+ # bridge the right-most hole first so later rays never cross earlier bridges
201
+ pending.sort(key=lambda h: -max(p[0] for p in h))
202
+ for hole in pending:
203
+ mi = max(range(len(hole)), key=lambda i: (hole[i][0], -hole[i][1]))
204
+ mx, my = hole[mi]
205
+ best, best_x = None, None
206
+ n = len(poly)
207
+ for i in range(n):
208
+ (ax, ay), (bx, by) = poly[i], poly[(i + 1) % n]
209
+ if (ay > my) == (by > my) or ay == by:
210
+ continue
211
+ x = ax + (my - ay) * (bx - ax) / (by - ay)
212
+ if x >= mx and (best_x is None or x < best_x):
213
+ best_x = x
214
+ best = i if ax > bx else (i + 1) % n # edge end point with larger x
215
+ if best is None:
216
+ best = min(range(n), key=lambda i: (poly[i][0] - mx) ** 2 + (poly[i][1] - my) ** 2)
217
+ else:
218
+ # a reflex vertex inside the ray triangle may block the view: take the one
219
+ # closest in angle to the ray instead
220
+ px, py = poly[best]
221
+ tri = ((mx, my), (best_x, my), (px, py))
222
+ cands = [i for i in range(n) if i != best and poly[i][0] >= mx
223
+ and _in_triangle(poly[i], tri)]
224
+ if cands:
225
+ best = min(cands, key=lambda i: (abs(math.atan2(poly[i][1] - my,
226
+ poly[i][0] - mx)),
227
+ (poly[i][0] - mx) ** 2))
228
+ ring = hole[mi:] + hole[:mi] + [hole[mi]]
229
+ poly = poly[:best + 1] + ring + poly[best:]
230
+ return poly
231
+
232
+
233
+ def _in_triangle(p, tri):
234
+ (x1, y1), (x2, y2), (x3, y3) = tri
235
+ d1 = (p[0] - x2) * (y1 - y2) - (x1 - x2) * (p[1] - y2)
236
+ d2 = (p[0] - x3) * (y2 - y3) - (x2 - x3) * (p[1] - y3)
237
+ d3 = (p[0] - x1) * (y3 - y1) - (x3 - x1) * (p[1] - y1)
238
+ neg = d1 < 0 or d2 < 0 or d3 < 0
239
+ pos = d1 > 0 or d2 > 0 or d3 > 0
240
+ return not (neg and pos)