From 43b599106f746dd42423eda1f91a592813ecc224 Mon Sep 17 00:00:00 2001 From: Hamilton Kibbe Date: Sun, 28 Sep 2014 13:04:32 -0400 Subject: Add Excellon support --- .gitignore | 4 ++ gerber/excellon.py | 180 +++++++++++++++++++++++++++++++++++++++++++++++++++ gerber/render.py | 3 + gerber/render_svg.py | 12 +++- gerber/utils.py | 54 +++++++++++++++- 5 files changed, 248 insertions(+), 5 deletions(-) create mode 100755 gerber/excellon.py diff --git a/.gitignore b/.gitignore index 4c6b1be..e7e1b23 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,7 @@ nosetests.xml .idea/workspace.xml .idea/misc.xml .idea + +# OS Files +.DS_Store +Thumbs.db \ No newline at end of file diff --git a/gerber/excellon.py b/gerber/excellon.py new file mode 100755 index 0000000..1e746ad --- /dev/null +++ b/gerber/excellon.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright 2014 Hamilton Kibbe + +# 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 re +from itertools import tee, izip +from .utils import parse_gerber_value + + + + +class Tool(object): + + @classmethod + def from_line(cls, line, settings): + commands = re.split('([BCFHSTZ])', line)[1:] + commands = [(command, value) for command, value in pairwise(commands)] + args = {} + format = settings['format'] + zero_suppression = settings['zero_suppression'] + for cmd, val in commands: + if cmd == 'B': + args['retract_rate'] = parse_gerber_value(val, format, zero_suppression) + elif cmd == 'C': + args['diameter'] = parse_gerber_value(val, format, zero_suppression) + elif cmd == 'F': + args['feed_rate'] = parse_gerber_value(val, format, zero_suppression) + elif cmd == 'H': + args['max_hit_count'] = parse_gerber_value(val, format, zero_suppression) + elif cmd == 'S': + args['rpm'] = 1000 * parse_gerber_value(val, format, zero_suppression) + elif cmd == 'T': + args['number'] = int(val) + elif cmd == 'Z': + args['depth_offset'] = parse_gerber_value(val, format, zero_suppression) + return cls(settings, **args) + + def __init__(self, settings, **kwargs): + self.number = kwargs.get('number') + self.feed_rate = kwargs.get('feed_rate') + self.retract_rate = kwargs.get('retract_rate') + self.rpm = kwargs.get('rpm') + self.diameter = kwargs.get('diameter') + self.max_hit_count = kwargs.get('max_hit_count') + self.depth_offset = kwargs.get('depth_offset') + self.units = settings.get('units', 'inch') + + def __repr__(self): + unit = 'in.' if self.units == 'inch' else 'mm' + return '' % (self.number, self.diameter, unit) + + + +class ExcellonParser(object): + def __init__(self, ctx=None): + self.ctx=ctx + self.notation = 'absolute' + self.units = 'inch' + self.zero_suppression = 'trailing' + self.format = (2,5) + self.state = 'INIT' + self.tools = {} + self.hits = [] + self.active_tool = None + self.pos = [0., 0.] + if ctx is not None: + zeros = 'L' if self.zero_suppression == 'leading' else 'T' + x = self.format + y = self.format + self.ctx.set_coord_format(zeros, x, y) + def parse(self, filename): + with open(filename, 'r') as f: + for line in f: + self._parse(line) + + def dump(self, filename='teste.svg'): + if self.ctx is not None: + self.ctx.dump(filename) + + def _parse(self, line): + if 'M48' in line: + self.state = 'HEADER' + + if 'G00' in line: + self.state = 'ROUT' + + if 'G05' in line: + self.state = 'DRILL' + + elif line[0] == '%' and self.state == 'HEADER': + self.state = 'DRILL' + + if 'INCH' in line or line.strip() == 'M72': + self.units = 'inch' + + elif 'METRIC' in line or line.strip() == 'M71': + self.units = 'metric' + + if 'LZ' in line: + self.zero_suppression = 'trailing' + + elif 'TZ' in line: + self.zero_suppression = 'leading' + + if 'ICI' in line and 'ON' in line or line.strip() == 'G91': + self.notation = 'incremental' + + if 'ICI' in line and 'OFF' in line or line.strip() == 'G90': + self.notation = 'absolute' + + zs = self._settings()['zero_suppression'] + fmt = self._settings()['format'] + + # tool definition + if line[0] == 'T' and self.state == 'HEADER': + tool = Tool.from_line(line,self._settings()) + self.tools[tool.number] = tool + + elif line[0] == 'T' and self.state != 'HEADER': + self.active_tool = self.tools[int(line.strip().split('T')[1])] + + + if line[0] in ['X', 'Y']: + x = None + y = None + if line[0] == 'X': + splitline = line.strip('X').split('Y') + x = parse_gerber_value(splitline[0].strip(), fmt, zs) + if len(splitline) == 2: + y = parse_gerber_value(splitline[1].strip(), fmt,zs) + else: + y = parse_gerber_value(line.strip(' Y'), fmt,zs) + + if self.notation == 'absolute': + if x is not None: + self.pos[0] = x + if y is not None: + self.pos[1] = y + else: + if x is not None: + self.pos[0] += x + if y is not None: + self.pos[1] += y + if self.state == 'DRILL': + self.hits.append((self.active_tool, self.pos)) + if self.ctx is not None: + self.ctx.drill(self.pos[0], self.pos[1], + self.active_tool.diameter) + + def _settings(self): + return {'units':self.units, 'zero_suppression':self.zero_suppression, + 'format': self.format} + +def pairwise(iterator): + itr = iter(iterator) + while True: + yield tuple([itr.next() for i in range(2)]) + +if __name__ == '__main__': + from .render_svg import GerberSvgContext + tools = [] + p = ExcellonParser(GerberSvgContext()) + p.parse('examples/ncdrill.txt') + p.dump('excellon.svg') + + \ No newline at end of file diff --git a/gerber/render.py b/gerber/render.py index 201f793..183a59f 100644 --- a/gerber/render.py +++ b/gerber/render.py @@ -140,6 +140,9 @@ class GerberContext(object): def flash(self, x, y): pass + def drill(self, x, y, diameter): + pass + def evaluate(self, stmt): if isinstance(stmt, (CommentStmt, UnknownStmt, EofStmt)): return diff --git a/gerber/render_svg.py b/gerber/render_svg.py index bfe6859..cb42371 100644 --- a/gerber/render_svg.py +++ b/gerber/render_svg.py @@ -44,6 +44,9 @@ class Rect(Shape): stroke_width=2, stroke_linecap="butt") def flash(self, ctx, x, y): + # Center the rectange on x,y + x -= (self.size[0] / 2.0) + y -= (self.size[0] / 2.0) return ctx.dwg.rect(insert=(300*x, 300*y), size=(300*float(self.size[0]), 300*float(self.size[1])), fill="rgb(184, 115, 51)") @@ -102,5 +105,10 @@ class GerberSvgContext(GerberContext): self.move(x, y, resolve=False) - def dump(self): - self.dwg.saveas("teste.svg") + def drill(self, x, y, diameter): + hit = self.dwg.circle(center=(x*300, y*300), r=300*(diameter/2.0), fill="gray") + self.dwg.add(hit) + + + def dump(self,filename='teste.svg'): + self.dwg.saveas(filename) diff --git a/gerber/utils.py b/gerber/utils.py index 02a8a14..00b821b 100644 --- a/gerber/utils.py +++ b/gerber/utils.py @@ -1,5 +1,19 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- + +# Copyright 2014 Hamilton Kibbe + +# 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. """ gerber.utils ============ @@ -9,8 +23,6 @@ This module provides utility functions for working with Gerber and Excellon files. """ -# Author: Hamilton Kibbe -# License: MIT def parse_gerber_value(value, format=(2, 5), zero_suppression='trailing'): """ Convert gerber/excellon formatted string to floating-point number @@ -54,6 +66,7 @@ def parse_gerber_value(value, format=(2, 5), zero_suppression='trailing'): raise ValueError('Parser only supports precision up to 6:7 format') # Remove extraneous information + value = value.strip() value = value.strip(' +') negative = '-' in value if negative: @@ -67,7 +80,8 @@ def parse_gerber_value(value, format=(2, 5), zero_suppression='trailing'): offset = 0 if zero_suppression == 'trailing' else (MAX_DIGITS - len(value)) for i, digit in enumerate(value): digits[i + offset] = digit - + + result = float(''.join(digits[:integer_digits] + ['.'] + digits[integer_digits:])) return -1.0 * result if negative else result @@ -128,3 +142,37 @@ def write_gerber_value(value, format=(2, 5), zero_suppression='trailing'): return ''.join(digits) if not negative else ''.join(['-'] + digits) + + +def decimal_string(value, precision=6): + """ Convert float to string with limited precision + + Parameters + ---------- + value : float + A floating point value. + + precision : + Maximum number of decimal places to print + + Returns + ------- + value : string + The specified value as a string. + + """ + floatstr = '%0.20g' % value + integer = None + decimal = None + if '.' in floatstr: + integer, decimal = floatstr.split('.') + elif ',' in floatstr: + integer, decimal = floatstr.split(',') + if len(decimal) > precision: + decimal = decimal[:precision] + if integer or decimal: + return ''.join([integer, '.', decimal]) + else: + return int(floatstr) + + -- cgit From feda1a639b9ccf1d54938b31c511074b9243c814 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Silva Date: Tue, 7 Oct 2014 09:51:08 -0300 Subject: Add setuptools support --- setup.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 setup.py diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..31fdcfa --- /dev/null +++ b/setup.py @@ -0,0 +1,23 @@ +import os +from setuptools import setup + +def read(fname): + return open(os.path.join(os.path.dirname(__file__), fname)).read() + +setup( + name = "gerber-tools", + version = "0.1", + author = "Paulo Henrique Silva", + author_email = "ph.silva@gmail.com", + description = ("Utilities to handle Gerber (RS-274X) files."), + license = "Apache", + keywords = "gerber tools", + url = "http://github.com/curtacircuitos/gerber-tools", + packages=['gerber'], + long_description=read('README.md'), + classifiers=[ + "Development Status :: 3 - Alpha", + "Topic :: Utilities", + "License :: OSI Approved :: Apple Public Source License", + ], +) -- cgit From e1285079745914b436a70cd1d9ee38dd4885a309 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Silva Date: Fri, 17 Oct 2014 17:20:23 -0300 Subject: Fix parsing of Unknown statements --- gerber/parser.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/gerber/parser.py b/gerber/parser.py index 8f89211..4900cb1 100644 --- a/gerber/parser.py +++ b/gerber/parser.py @@ -262,7 +262,7 @@ class GerberParser(object): for i, line in enumerate(data): line = oldline + line.strip() - + # skip empty lines if not len(line): continue @@ -287,7 +287,7 @@ class GerberParser(object): (aperture, r) = self._match_one(self.APERTURE_STMT, line) if aperture: yield ApertureStmt(**aperture) - + did_something = True line = r continue @@ -334,7 +334,7 @@ class GerberParser(object): did_something = True line = r continue - + if False: print self.COORD_STMT.pattern print self.APERTURE_STMT.pattern @@ -345,6 +345,10 @@ class GerberParser(object): if line.find('*') > 0: yield UnknownStmt(line) + did_something = True + line = "" + continue + oldline = line def _match_one(self, expr, data): -- cgit From cb18cc4635afa14a1dd61bd9a678d8f28aadc38a Mon Sep 17 00:00:00 2001 From: Paulo Henrique Silva Date: Fri, 17 Oct 2014 17:20:49 -0300 Subject: Fix parsing of COORD with +000 styled numbers --- gerber/render.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gerber/render.py b/gerber/render.py index 183a59f..8accf09 100644 --- a/gerber/render.py +++ b/gerber/render.py @@ -41,8 +41,8 @@ class GerberCoordFormat(object): self.y_int_digits, self.y_dec_digits = [int(d) for d in y] def resolve(self, x, y): - new_x = x - new_y = y + new_x = x.replace("+", "") + new_y = y.replace("+", "") if new_x is not None: negative = "-" in new_x -- cgit From 0d4cb55c97a6f417f65e458093f3f2a9c36a421f Mon Sep 17 00:00:00 2001 From: Paulo Henrique Silva Date: Tue, 21 Oct 2014 20:46:37 -0200 Subject: Fix parsing when x or y coordinate is missing on COORD statement --- gerber/render.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gerber/render.py b/gerber/render.py index 8accf09..c6f086a 100644 --- a/gerber/render.py +++ b/gerber/render.py @@ -41,8 +41,8 @@ class GerberCoordFormat(object): self.y_int_digits, self.y_dec_digits = [int(d) for d in y] def resolve(self, x, y): - new_x = x.replace("+", "") - new_y = y.replace("+", "") + new_x = x.replace("+", "") if x else None + new_y = y.replace("+", "") if y else None if new_x is not None: negative = "-" in new_x -- cgit From 5c4705fcee7786dc82d57cd09afeeca6abfcbb1b Mon Sep 17 00:00:00 2001 From: Paulo Henrique Silva Date: Wed, 22 Oct 2014 00:53:40 -0200 Subject: Fix coordinate computation when x or y is 0 in non standard way --- gerber/render.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gerber/render.py b/gerber/render.py index c6f086a..585b340 100644 --- a/gerber/render.py +++ b/gerber/render.py @@ -117,7 +117,7 @@ class GerberContext(object): def resolve(self, x, y): x, y = self.coord_format.resolve(x, y) - return x or self.x, y or self.y + return x if x is not None else self.x, y if y is not None else self.y def define_aperture(self, d, shape, modifiers): pass -- cgit From d0eedf3dd7ee4fbf19f51de319e48dd964b93561 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Silva Date: Sat, 25 Oct 2014 12:52:13 -0200 Subject: Support for zero size C apertures and fix parsing of ADDNN --- gerber/parser.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/gerber/parser.py b/gerber/parser.py index 4900cb1..67893af 100644 --- a/gerber/parser.py +++ b/gerber/parser.py @@ -98,7 +98,10 @@ class ADParamStmt(ParamStmt): ParamStmt.__init__(self, param) self.d = d self.shape = shape - self.modifiers = [[x for x in m.split("X")] for m in modifiers.split(",")] + if modifiers is not None: + self.modifiers = [[x for x in m.split("X")] for m in modifiers.split(",")] + else: + self.modifiers = [] def to_gerber(self): return '%ADD{0}{1},{2}*%'.format(self.d, self.shape, @@ -191,7 +194,7 @@ class GerberParser(object): NUMBER = r"[\+-]?\d+" DECIMAL = r"[\+-]?\d+([.]?\d+)?" STRING = r"[a-zA-Z0-9_+\-/!?<>”’(){}.\|&@# :]+" - NAME = "[a-zA-Z_$][a-zA-Z_$0-9]+" + NAME = r"[a-zA-Z_$][a-zA-Z_$0-9]+" FUNCTION = r"G\d{2}" COORD_OP = r"D[0]?[123]" @@ -201,10 +204,10 @@ class GerberParser(object): IP = r"(?PIP)(?P(POS|NEG))" LP = r"(?PLP)(?P(D|C))" AD_CIRCLE = r"(?PAD)D(?P\d+)(?PC)[,](?P[^,]*)" - AD_RECT = r"(?PAD)D(?P\d+)(?PR)[,](?P[^,]*)" + AD_RECT = r"(?PAD)D(?P\d+)(?PR)[,]?(?P[^,]+)?" AD_OBROUND = r"(?PAD)D(?P\d+)(?PO)[,](?P[^,]*)" AD_POLY = r"(?PAD)D(?P\d+)(?PP)[,](?P[^,]*)" - AD_MACRO = r"(?PAD)D(?P\d+)+(?P{name})[,](?P[^,]*)".format(name=NAME) + AD_MACRO = r"(?PAD)D(?P\d+)(?P{name})[,]?(?P[^,]+)?".format(name=NAME) AM = r"(?PAM)(?P{name})\*(?P.*)".format(name=NAME) # begin deprecated @@ -213,7 +216,7 @@ class GerberParser(object): LN = r"(?PLN)(?P.*)" # end deprecated - PARAMS = (FS, MO, IP, LP, AD_CIRCLE, AD_RECT, AD_OBROUND, AD_MACRO, AD_POLY, AM, OF, IN, LN) + PARAMS = (FS, MO, IP, LP, AD_CIRCLE, AD_RECT, AD_OBROUND, AD_POLY, AD_MACRO, AM, OF, IN, LN) PARAM_STMT = [re.compile(r"%{0}\*%".format(p)) for p in PARAMS] COORD_STMT = re.compile(( -- cgit