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

# copyright 2014 Hamilton Kibbe <ham@hamiltonkib.be>
# Modified from parser.py by Paulo Henrique Silva <ph.silva@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import math
import re
from .cam import CamFile, FileSettings
from .primitives import TestRecord

# Net Name Variables
_NNAME = re.compile(r'^NNAME\d+$')

# Board Edge Coordinates
_COORD = re.compile(r'X?(?P<x>[\d\s]*)?Y?(?P<y>[\d\s]*)?')


def read(filename):
    """ Read data from filename and return an IPC_D_356
    Parameters
        ----------
    filename : string
        Filename of file to parse

    Returns
    -------
    file : :class:`gerber.ipc356.IPC_D_356`
        An IPC_D_356 object created from the specified file.

    """
    # File object should use settings from source file by default.
    return IPC_D_356.from_file(filename)


class IPC_D_356(CamFile):

    @classmethod
    def from_file(self, filename):
        p = IPC_D_356_Parser()
        return p.parse(filename)


    def __init__(self, statements, settings, primitives=None):
        self.statements = statements
        self.units = settings.units
        self.angle_units = settings.angle_units
        self.primitives = [TestRecord((rec.x_coord, rec.y_coord), rec.net_name,
                                      rec.access) for rec in self.test_records]

    @property
    def settings(self):
        return FileSettings(units=self.units, angle_units=self.angle_units)

    @property
    def comments(self):
        return [record for record in self.statements
                if isinstance(record, IPC356_Comment)]

    @property
    def parameters(self):
        return [record for record in self.statements
                if isinstance(record, IPC356_Parameter)]

    @property
    def test_records(self):
        return [record for record in self.statements
                if isinstance(record, IPC356_TestRecord)]

    @property
    def nets(self):
        return list(set([rec.net_name for rec in self.test_records
                         if rec.net_name is not None]))

    @property
    def components(self):
        return list(set([rec.id for rec in self.test_records
                         if rec.id is not None and rec.id != 'VIA']))

    @property
    def vias(self):
        return [rec.id for rec in self.test_records if rec.id == 'VIA']

    @property
    def board_outline(self):
        outline = [stmt for stmt in self.statements if isinstance(stmt, IPC356_BoardEdge)]
        if len(outline):
            return outline[0].points
        else:
            return None


    def render(self, ctx, layer='both', filename=None):
        for p in self.primitives:
            if layer == 'both' and p.layer in ('top', 'bottom', 'both'):
                ctx.render(p)
            elif layer == 'top' and p.layer in ('top', 'both'):
                ctx.render(p)
            elif layer == 'bottom' and p.layer in ('bottom', 'both'):
                ctx.render(p)
        if filename is not None:
            ctx.dump(filename)


class IPC_D_356_Parser(object):
    # TODO: Allow multi-line statements (e.g. Altium board edge)
    def __init__(self):
        self.units = 'inch'
        self.angle_units = 'degrees'
        self.statements = []
        self.nnames = {}

    @property
    def settings(self):
        return FileSettings(units=self.units, angle_units=self.angle_units)

    def parse(self, filename):
        with open(filename, 'r') as f:
            oldline = ''
            for line in f:
                # Check for existing multiline data...
                if oldline != '':
                    if len(line) and line[0] == '0':
                        oldline = oldline.rstrip('\r\n') + line[3:].rstrip()
                    else:
                        self._parse_line(oldline)
                        oldline = line
                else:
                    oldline = line
        self._parse_line(oldline)

        return IPC_D_356(self.statements, self.settings)


    def _parse_line(self, line):
        if not len(line):
            return
        if line[0] == 'C':
            # Comment
            self.statements.append(IPC356_Comment.from_line(line))

        elif line[0] == 'P':
            # Parameter
            p = IPC356_Parameter.from_line(line)
            if p.parameter == 'UNITS':
                if p.value in ('CUST', 'CUST 0'):
                    self.units = 'inch'
                    self.angle_units = 'degrees'
                elif p.value == 'CUST 1':
                    self.units = 'metric'
                    self.angle_units = 'degrees'
                elif p.value == 'CUST 2':
                    self.units = 'inch'
                    self.angle_units = 'radians'
            self.statements.append(p)
            if _NNAME.match(p.parameter):
                # Add to list of net name variables
                self.nnames[p.parameter] = p.value

        elif line[0] == '9':
            self.statements.append(IPC356_EndOfFile())

        elif line[0:3] in ('317', '327', '367'):
            # Test Record
            record = IPC356_TestRecord.from_line(line, self.settings)

            # Substitute net name variables
            net = record.net_name
            if (_NNAME.match(net) and net in self.nnames.keys()):
                record.net_name = self.nnames[record.net_name]
            self.statements.append(record)

        elif line[0:3] == '379':
            # Net Adjacency Info
            pass
        elif line[0:3] == '389':
            # Altium Board Edge Info
            self.statements.append(IPC356_BoardEdge.from_line(line, self.settings))


class IPC356_Comment(object):
    @classmethod
    def from_line(cls, line):
        if line[0] != 'C':
            raise ValueError('Not a valid comment statment')
        comment = line[2:].strip()
        return cls(comment)

    def __init__(self, comment):
        self.comment = comment

    def __repr__(self):
        return '<IPC-D-356 Comment: %s>' % self.comment


class IPC356_Parameter(object):
    @classmethod
    def from_line(cls, line):
        if line[0] != 'P':
            raise ValueError('Not a valid parameter statment')
        splitline = line[2:].split()
        parameter = splitline[0].strip()
        value = ' '.join(splitline[1:]).strip()
        return cls(parameter, value)

    def __init__(self, parameter, value):
        self.parameter = parameter
        self.value = value

    def __repr__(self):
        return '<IPC-D-356 Parameter: %s=%s>' % (self.parameter, self.value)


class IPC356_TestRecord(object):
    @classmethod
    def from_line(cls, line, settings):
        units = settings.units
        angle = settings.angle_units
        feature_types = {'1':'through-hole', '2': 'smt',
                         '3':'tooling-feature', '4':'tooling-hole'}
        access = ['both', 'top', 'layer2', 'layer3', 'layer4', 'layer5',
                  'layer6', 'layer7', 'bottom']
        record = {}
        line = line.strip()
        if line[0] != '3':
            raise ValueError('Not a valid test record statment')
        record['feature_type'] = feature_types[line[1]]

        end = len(line) - 1 if len(line) < 18 else 17
        record['net_name'] = line[3:end].strip()

        end = len(line) - 1 if len(line) < 27 else 26
        record['id'] = line[20:end].strip()

        end = len(line) - 1 if len(line) < 32 else 31
        record['pin'] = (line[27:end].strip() if line[27:end].strip() != ''
                         else None)

        record['location'] = 'middle' if line[31] == 'M' else 'end'
        if line[32] == 'D':
            end = len(line) - 1 if len(line) < 38 else 37
            dia = int(line[33:end].strip())
            record['hole_diameter'] = (dia * 0.0001 if units == 'inch'
                                       else dia * 0.001)
        if len(line) >= 38:
            record['plated'] = (line[37] == 'P')

        if len(line) >= 40:
            end = len(line) - 1 if len(line) < 42 else 41
            record['access'] = access[int(line[39:end])]

        if len(line) >= 43:
            end = len(line) - 1 if len(line) < 50 else 49
            coord = int(line[42:49].strip())
            record['x_coord'] = (coord *  0.0001 if units == 'inch'
                                 else coord * 0.001)

        if len(line) >= 51:
            end = len(line) - 1 if len(line) < 58 else 57
            coord = int(line[50:57].strip())
            record['y_coord'] = (coord *  0.0001 if units == 'inch'
            else coord * 0.001)

        if len(line) >= 59:
            end = len(line) - 1 if len(line) < 63 else 62
            dim = line[58:62].strip()
            if dim != '':
                record['rect_x'] = (int(dim) * 0.0001 if units == 'inch'
                                else int(dim) * 0.001)

        if len(line) >= 64:
            end = len(line) - 1 if len(line) < 68 else 67
            dim = line[63:67].strip()
            if dim != '':
                record['rect_y'] = (int(dim) * 0.0001 if units == 'inch'
                                    else int(dim) * 0.001)

        if len(line) >= 69:
            end = len(line) - 1 if len(line) < 72 else 71
            rot = line[68:71].strip()
            if rot != '':
                record['rect_rotation'] = (int(rot) if angle == 'degrees'
                                           else math.degrees(rot))

        if len(line) >= 74:
            end = len(line) - 1 if len(line) < 75 else 74
            record['soldermask_info'] = line[73:74].strip()

        if len(line) >= 76:
            end = len(line) - 1 if len(line < 80) else 79
            record['optional_info'] = line[75:end]

        return cls(**record)

    def __init__(self, **kwargs):
        for key in kwargs:
            setattr(self, key, kwargs[key])

    def __repr__(self):
        return '<IPC-D-356 Test Record: Net: %s Type: %s>' % (self.net_name,
                                                            self.feature_type)

class IPC356_BoardEdge(object):

    @classmethod
    def from_line(cls, line, settings):
        scale = 0.0001 if settings.units == 'inch' else 0.001
        points = []
        x = 0
        y = 0
        coord_strings = line.strip().split()[1:]
        for coord in coord_strings:
            coord_dict = _COORD.match(coord).groupdict()
            x = int(coord_dict['x']) if coord_dict['x'] is not '' else x
            y = int(coord_dict['y']) if coord_dict['y'] is not '' else y
            points.append((x * scale, y * scale))
        return cls(points)

    def __init__(self, points):
        self.points = points

    def __repr__(self):
        return '<IPC-D-356 Board Edge Definition>'


class IPC356_Adjacency(object):

    @classmethod
    def from_line(cls, line):
        nets = line.strip().split()[1:]
        return cls(nets)

    def __init__(self, nets):
        self.nets = nets

    def __repr__(self):
        return '<IPC-D-356 Adjacency Record>'


class IPC356_EndOfFile(object):
    def __init__(self):
        pass

    def to_netlist(self):
        return '999'

    def __repr__(self):
        return '<IPC-D-356 EOF>'