summaryrefslogtreecommitdiff
path: root/gerber/gerber.py
blob: 339c054234051dd74546c0ad63fd498691bcb568 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re


def red(s):
    return '\033[1;31m{0}\033[0;m'.format(s)


class Statement:
    def __init__(self):
        pass


class ParamStmt(Statement):
    def __init__(self, type):
        self.type = type


class FSParamStmt(ParamStmt):
    def __init__(self, type, zero, notation, x, y):
        ParamStmt.__init__(self, type)
        self.zero = zero
        self.notation = notation
        self.x = x
        self.y = y


class MOParamStmt(ParamStmt):
    def __init__(self, type, mo):
        ParamStmt.__init__(self, type)
        self.mo = mo


class IPParamStmt(ParamStmt):
    def __init__(self, type, ip):
        ParamStmt.__init__(self, type)
        self.ip = ip


class OFParamStmt(ParamStmt):
    def __init__(self, type, a, b):
        ParamStmt.__init__(self, type)
        self.a = a
        self.b = b


class LPParamStmt(ParamStmt):
    def __init__(self, type, lp):
        ParamStmt.__init__(self, type)
        self.lp = lp


class ADParamStmt(ParamStmt):
    def __init__(self, type, d, shape):
        ParamStmt.__init__(self, type)
        self.d = d
        self.shape = shape


class ADCircleParamStmt(ADParamStmt):
    def __init__(self, type, d, shape, definition):
        ADParamStmt.__init__(self, type, d, shape)
        self.definition = definition


class ADRectParamStmt(ADParamStmt):
    def __init__(self, type, d, shape, definition):
        ADParamStmt.__init__(self, type, d, shape)
        self.definition = definition


class ADObroundParamStmt(ADParamStmt):
    def __init__(self, type, d, shape, definition):
        ADParamStmt.__init__(self, type, d, shape)
        self.definition = definition


class ADPolyParamStmt(ADParamStmt):
    def __init__(self, type, d, shape, definition):
        ADParamStmt.__init__(self, type, d, shape)
        self.definition = definition


class ADMacroParamStmt(ADParamStmt):
    def __init__(self, type, d, name, definition):
        ADParamStmt.__init__(self, type, d, "M")
        self.name = name
        self.definition = definition


class AMParamStmt(ParamStmt):
    def __init__(self, type, name, macro):
        ParamStmt.__init__(self, type)
        self.name = name
        self.macro = macro


class INParamStmt(ParamStmt):
    def __init__(self, type, name):
        ParamStmt.__init__(self, type)
        self.name = name


class LNParamStmt(ParamStmt):
    def __init__(self, type, name):
        ParamStmt.__init__(self, type)
        self.name = name


class CoordStmt(Statement):
    def __init__(self, function, x, y, i, j, op):
        self.function = function
        self.x = x
        self.y = y
        self.i = i
        self.j = j
        self.op = op


class ApertureStmt(Statement):
    def __init__(self, d):
        self.d = int(d)


class CommentStmt(Statement):
    def __init__(self, comment):
        self.comment = comment


class EofStmt(Statement):
    pass


class UnknownStmt(Statement):
    def __init__(self, line):
        self.line = line


IMAGE_POLARITY_POSITIVE = 1
IMAGE_POLARITY_NEGATIVE = 2

LEVEL_POLARITY_DARK = 1
LEVEL_POLARITY_CLEAR = 2

NOTATION_ABSOLUTE = 1
NOTATION_INCREMENTAL = 2


class GerberCoordFormat:

    def __init__(self, zeroes, x, y):
        self.omit_leading_zeroes = True if zeroes == "L" else False
        self.omit_trailing_zeroes = True if zeroes == "T" else False
        self.x_int_digits, self.x_dec_digits = [int(d) for d in x]
        self.y_int_digits, self.y_dec_digits = [int(d) for d in y]

    def resolve(self, x, y):
        return x, y


class GerberContext:
    coord_format = None
    coord_notation = NOTATION_ABSOLUTE

    unit = None

    x = 0
    y = 0

    current_aperture = 0
    interpolation = None

    region_mode = False
    quadrant_mode = False

    image_polarity = IMAGE_POLARITY_POSITIVE
    level_polarity = LEVEL_POLARITY_DARK

    steps = (1, 1)
    repeat = (None, None)

    def __init__(self):
        pass

    def set_coord_format(self, zeroes, x, y):
        self.coord_format = GerberCoordFormat(zeroes, x, y)

    def set_coord_notation(self, notation):
        self.coord_notation = NOTATION_ABSOLUTE if notation == "A" else NOTATION_INCREMENTAL

    def set_image_polarity(self, polarity):
        self.image_polarity = IMAGE_POLARITY_POSITIVE if polarity == "POS" else IMAGE_POLARITY_NEGATIVE

    def set_level_polarity(self, polarity):
        self.level_polarity = LEVEL_POLARITY_DARK if polarity == "D" else LEVEL_POLARITY_CLEAR

    def move(self, x, y):
        self.x = x
        self.y = y

    def aperture(self, d):
        self.current_aperture = d


class Gerber:
    NUMBER = r"[\+-]?\d+"
    FUNCTION = r"G\d{2}"
    STRING = r"[a-zA-Z0-9_+\-/!?<>”’(){}.\|&@# :]+"
    NAME = "[a-zA-Z_$][a-zA-Z_$0-9]+"

    COORD_OP = r"D[0]?[123]"

    FS = r"(?P<type>FS)(?P<zero>(L|T))(?P<notation>(A|I))X(?P<x>[0-7][0-7])Y(?P<y>[0-7][0-7])"
    MO = r"(?P<type>MO)(?P<mo>(MM|IN))"
    IP = r"(?P<type>IP)(?P<ip>(POS|NEG))"
    LP = r"(?P<type>LP)(?P<lp>(D|C))"
    AD_CIRCLE = r"(?P<type>ADD)(?P<d>\d+)(?P<shape>C)(?P<definition>.*)"
    AD_RECT = r"(?P<type>ADD)(?P<d>\d+)(?P<shape>R)(?P<definition>.*)"
    AD_OBROUND = r"(?P<type>ADD)(?P<d>\d+)(?P<shape>O)(?P<definition>.*)"
    AD_POLY = r"(?P<type>ADD)(?P<d>\d+)(?P<shape>P)(?P<definition>.*)"
    AD_MACRO = r"(?P<type>ADD)(?P<d>\d+)(?P<name>[^CROP,].*)(?P<definition>.*)".format(name=NAME)
    AM = r"(?P<type>AM)(?P<name>{name})\*(?P<macro>.*)".format(name=NAME)

    # begin deprecated
    OF = r"(?P<type>OF)(A(?P<a>[+-]?\d+(.?\d*)))?(B(?P<b>[+-]?\d+(.?\d*)))?"
    IN = r"(?P<type>IN)(?P<name>.*)"
    LN = r"(?P<type>LN)(?P<name>.*)"
    # end deprecated

    PARAMS = (FS, MO, IP, LP, AD_CIRCLE, AD_RECT, AD_OBROUND, AD_MACRO, AD_POLY, AM, OF, IN, LN)
    PARAM_STMT = [re.compile(r"%{0}\*%".format(p)) for p in PARAMS]

    COORD_STMT = re.compile((
        r"(?P<function>{function})?"
        r"(X(?P<x>{number}))?(Y(?P<y>{number}))?"
        r"(I(?P<i>{number}))?(J(?P<j>{number}))?"
        r"(?P<op>{op})?\*".format(number=NUMBER, function=FUNCTION, op=COORD_OP)))

    APERTURE_STMT = re.compile(r"(G54)?D(?P<d>\d+)\*")

    COMMENT_STMT = re.compile(r"G04(?P<comment>{string})(\*)?".format(string=STRING))

    EOF_STMT = re.compile(r"(?P<eof>M02)\*")

    def __init__(self):
        self.tokens = []
        self.ctx = GerberContext()

    def parse(self, filename):
        fp = open(filename, "r")
        data = fp.readlines()

        for token in self._tokenize(data):
            self._evaluate(token)

    def _tokenize(self, data):
        multiline = None

        for i, line in enumerate(data):
            # remove EOL
            if multiline:
                line = multiline + line.strip()
            else:
                line = line.strip()

            # skip empty lines
            if not len(line):
                continue

            # deal with multi-line parameters
            if line.startswith("%") and not line.endswith("%"):
                multiline = line
                continue
            else:
                multiline = None

            # coord
            coords = self._match_many(self.COORD_STMT, line)
            if coords:
                for coord in coords:
                    yield CoordStmt(**coord)
                continue

            # aperture selection
            aperture = self._match_one(self.APERTURE_STMT, line)
            if aperture:
                yield ApertureStmt(**aperture)
                continue

            # comment
            comment = self._match_one(self.COMMENT_STMT, line)
            if comment:
                yield CommentStmt(comment["comment"])
                continue

            # parameter
            param = self._match_one_from_many(self.PARAM_STMT, line)
            if param:
                if param["type"] == "FS":
                    yield FSParamStmt(**param)
                elif param["type"] == "MO":
                    yield MOParamStmt(**param)
                elif param["type"] == "IP":
                    yield IPParamStmt(**param)
                elif param["type"] == "LP":
                    yield LPParamStmt(**param)
                elif param["type"] == "AD":
                    if param["shape"] == "C":
                        yield ADCircleParamStmt(**param)
                    elif param["shape"] == "R":
                        yield ADRectParamStmt(**param)
                    elif param["shape"] == "O":
                        yield ADObroundParamStmt(**param)
                    elif param["shape"] == "P":
                        yield ADPolyParamStmt(**param)
                    else:
                        yield ADMacroParamStmt(**param)
                elif param["type"] == "AM":
                    yield AMParamStmt(**param)
                elif param["type"] == "OF":
                    yield OFParamStmt(**param)
                elif param["type"] == "IN":
                    yield INParamStmt(**param)
                elif param["type"] == "LN":
                    yield LNParamStmt(**param)
                else:
                    yield UnknownStmt(line)

                continue

            # eof
            eof = self._match_one(self.EOF_STMT, line)
            if eof:
                yield EofStmt()
                continue

            print red("UNKNOWN TOKEN")
            print "{0}:'{1}'".format(red(str(i+1)), line)

            if False:
                print self.COORD_STMT.pattern
                print self.APERTURE_STMT.pattern
                print self.COMMENT_STMT.pattern
                print self.EOF_STMT.pattern
                for i in self.PARAM_STMT:
                    print i.pattern

            yield UnknownStmt(line)

    def _match_one(self, expr, data):
        match = expr.match(data)
        if match is None:
            return {}
        else:
            return match.groupdict()

    def _match_one_from_many(self, exprs, data):
        for expr in exprs:
            match = expr.match(data)
            if match:
                return match.groupdict()

        return {}

    def _match_many(self, expr, data):
        result = []
        pos = 0
        while True:
            match = expr.match(data, pos)
            if match:
                result.append(match.groupdict())
                pos = match.endpos
            else:
                break

        return result

    def _evaluate(self, token):
        if isinstance(token, (CommentStmt, UnknownStmt, EofStmt)):
            return

        elif isinstance(token, ParamStmt):
            self._evaluate_param(token)

        elif isinstance(token, CoordStmt):
            self._evaluate_coord(token)

        elif isinstance(token, ApertureStmt):
            self._evaluate_aperture(token)

        else:
            raise Exception("Invalid token to evaluate")

    def _evaluate_param(self, param):
        if param.type == "FS":
            self.ctx.set_coord_format(param.zero, param.x, param.y)
            self.ctx.set_coord_notation(param.notation)

    def _evaluate_coord(self, coord):
        self.ctx.move(coord.x, coord.y)

    def _evaluate_aperture(self, aperture):
        self.ctx.aperture(aperture.d)


if __name__ == "__main__":
    import sys

    for f in sys.argv[1:]:
        print f
        g = Gerber()
        g.parse(f)