Skip to content
Commits on Source (39)
*~
__pycache__
doc/sphinx/build/
doc/sphinx/source/api/
# Build files
__pycache__
_lextab.py
_parsetab.py
lextab.py
parser.out
parsetab.py
doc/sphinx/build/
# Generated files
doc/sphinx/source/api/
doc/sphinx/source/examples/
doc/sphinx/source/gcode-reference/rs-274/execution_order.rst
doc/sphinx/source/gcode-reference/rs-274/gcodes.rst
doc/sphinx/source/gcode-reference/rs-274/letters.rst
doc/sphinx/source/gcode-reference/rs-274/modal_groups.rst
doc/sphinx/source/gcode-reference/rs-274/parameters.rst
doc/sphinx/source/gcode-reference/linuxcnc/images/*_fr.png
doc/sphinx/source/gcode-reference/linuxcnc/images/*_fr.svg
doc/sphinx/source/gcode-reference/linuxcnc/tmp/
pandoc
PythonicGcodeMachine/PythonLexYacc/yacc.py
ressources
......
####################################################################################################
#
# PythonicGcodeMachine - @licence_header_description@
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
......@@ -19,6 +19,8 @@
####################################################################################################
"""Module to implement an AST for RS-274 G-code.
All classes are clonable.
"""
####################################################################################################
......@@ -64,12 +66,34 @@ __all__ = [
####################################################################################################
import math
import re
import colors
####################################################################################################
class Program:
class MachineMixin:
"""Mixin to define the target machine for the AST node"""
##############################################
def __init__(self, machine=None):
self._machine = machine
##############################################
@property
def machine(self):
return self._machine
@machine.setter
def machine(self, value):
self._machine = value
####################################################################################################
class Program(MachineMixin):
"""Class to implement a G-code program
......@@ -84,15 +108,28 @@ class Program:
str(program)
program2 = program.clone()
"""
##############################################
def __init__(self):
def __init__(self, machine=None):
super().__init__(machine)
self._lines = []
##############################################
def clone(self):
program = self.__class__(machine=self._machine)
for line in self:
program += line.clone()
return program
##############################################
def push(self, line):
self._lines.append(line)
......@@ -134,14 +171,53 @@ class Program:
####################################################################################################
class LineItem:
class CloneMixin:
"""Mixin to provide a method to clone value"""
@staticmethod
def _clone_value(value):
if hasattr(value, 'clone'):
return value.clone()
else:
return value
####################################################################################################
class LineItem(MachineMixin, CloneMixin):
"""Base class for line item"""
##############################################
def _check_value(self, value):
if (isinstance(value, (int, float)) or
isinstance(value, RealValue)):
return value
else:
try:
str_value = str(value)
except:
raise ValueError("Invalid value {}".format(value))
# Fixme:
from .Parser import GcodeParser, GcodeParserError
parser = GcodeParser()
try:
# Fixme: parser hack
ast = parser.parse('X' + value)
return ast[0].value
except GcodeParserError:
raise ValueError("Invalid G-code value {}".format(value))
##############################################
def ansi_str(self):
return str(self)
####################################################################################################
class Line:
class Line(MachineMixin):
"""Class to implement a G-code line
......@@ -162,11 +238,13 @@ class Line:
line += Comment('move')
line += Word('X', 10)
line += Comment('Y value')
line += Word('Y', 20)
line += Word('Y', 20.)
line += ParameterSetting('1', 1.2)
# using expression
# using expression, AST way
line += Word('Z', Addition(30, Multiply(Parameter(100), Cosine(30))))
# string way
line += Word('Z', '[30 + [#100 * cos[30]]]')
# Array interface
for item in line:
......@@ -175,6 +253,18 @@ class Line:
str(line)
print(line.ansi_str()) # use ANSI colors, see Line.ANSI_... attributes
a_line = line.clone()
Values can be passed as:
* int or float,
* AST for expression,
* any object that "str" evaluate to a valid G-code expression.
As a shortcut, a G/M-code operation can be passed as string::
line += 'G0'
Expression can be evaluated using :code:`float(obj.value)`, excepted when we must access a parameter
value.
......@@ -190,7 +280,9 @@ class Line:
##############################################
def __init__(self, deleted=False, line_number=None, comment=None):
def __init__(self, deleted=False, line_number=None, comment=None, machine=None):
super().__init__(machine)
self.deleted = deleted
self.line_number = line_number
......@@ -200,6 +292,16 @@ class Line:
##############################################
def clone(self):
line = self.__class__(self._deleted, self._line_number, self._comment, self._machine)
for item in self:
line += item.clone()
return line
##############################################
@property
def deleted(self):
return self._deleted
......@@ -233,13 +335,26 @@ class Line:
##############################################
def _push_item(self, item):
if not isinstance(item, LineItem):
item = Word.from_str(item)
# Fixme: try to parse ???
self._items.append(item)
def push_items(self, iterable):
"""Method to push an iterable"""
for item in iterable:
self.push(item)
def push(self, item):
if isinstance(item, LineItem):
self._items.append(item)
"""Method to push a valid item, a 'G/Mxxx' shortcut string, a list or tuple"""
if isinstance(item, (list, tuple, Line)):
self.push_items(item)
else:
raise ValueError
self._push_item(item)
def __iadd__(self, item):
"""push shortcut"""
self.push(item)
return self
......@@ -261,6 +376,75 @@ class Line:
##############################################
def iter_on_word(self):
for item in self:
if isinstance(item, Word):
yield item
def iter_on_gm_word(self):
for item in self.iter_on_word():
if item.is_gm_gcode:
yield item
def iter_on_x_word(self):
for item in self.iter_on_word():
if not item.is_gm_gcode:
yield item
def iter_on_letter(self, letters):
for item in self.iter_on_word():
if item.letter in letters:
yield item
def iter_on_g_word(self):
return self.iter_on_letter('G')
def iter_on_m_word(self):
return self.iter_on_letter('M')
def iter_on_setting(self):
for item in self:
if isinstance(item, ParameterSetting):
yield item
def iter_in_order(self):
words = [word for word in self.iter_on_gm_word()]
words.sort(key=lambda word: word.execution_order.index)
return words
##############################################
def toggle(self):
"""Toggle deleted flag"""
self._deleted = not self._deleted
def remove_line_number(self):
self._line_number = None
##############################################
def remove_comment(self):
self._comment = None
for i, item in enumerate(self):
if isinstance(item, Comment):
# self._items.pop(i)
del self._items[i]
##############################################
def check_modal_group(self):
modal_groups = {}
for item in self.iter_on_gm_word():
group = item.modal_group
modal_groups.setdefault(group, 0)
modal_groups[group] += 1
errors = [modal_group for modal_group, count in modal_groups.items() if count > 1]
if errors:
raise ValueError("Modal group errors {}".format(errors))
##############################################
def __repr__(self):
items = []
......@@ -311,11 +495,17 @@ class Comment(LineItem):
##############################################
def __init__(self, text):
def __init__(self, text, machine=None):
super().__init__(machine)
self.set(text)
##############################################
def clone(self):
return self.__class__(self._text, self._machine)
##############################################
def set(self, text):
if '(' in text:
raise ValueError('Comment cannot contains a "("')
......@@ -348,6 +538,7 @@ class Word(LineItem):
"""Class to implement word"""
# Fixme: config ???
LETTERS = (
'A', 'B', 'C', 'D',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', # 'N',
......@@ -355,14 +546,34 @@ class Word(LineItem):
'X', 'Y', 'Z',
)
WORD_RE = re.compile('(G|M)(\d+)')
##############################################
@classmethod
def from_str(cls, obj):
str_obj = str(obj)
match = cls.WORD_RE.match(str_obj)
if match is not None:
return cls(*match.groups())
else:
raise ValueError(obj)
##############################################
def __init__(self, letter, value):
def __init__(self, letter, value, machine=None):
super().__init__(machine)
self.letter = letter
self.value = value
##############################################
def clone(self):
return self.__class__(self._letter, self._clone_value(self._value), self._machine)
##############################################
@property
def letter(self):
return self._letter
......@@ -380,33 +591,110 @@ class Word(LineItem):
@value.setter
def value(self, value):
# float expression ...
self._value = value
self._value = self._check_value(value)
##############################################
def __repr__(self):
return 'Word({0._letter} {0._value})'.format(self)
return 'Word({0._letter}, {0._value})'.format(self)
def __str__(self):
return '{0._letter}{0._value}'.format(self)
def ansi_str(self):
if self._letter in 'GM':
if self._machine:
gm = self._machine.GM_LETTERS
else:
gm = 'GM'
if self._letter in gm:
return Line.ANSI_G(str(self))
else:
return Line.ANSI_X(self._letter) + Line.ANSI_VALUE(str(self._value))
##############################################
def _check_machine(self):
if self._machine is None:
raise NameError('Machine is not defined')
@property
def _machine_config(self):
self._check_machine()
return self._machine.config
##############################################
@property
def is_gm_gcode(self):
return self._machine_config.letters.is_gm_word(self)
@property
def is_axis_gcode(self):
return self._machine_config.letters.is_axis_word(self)
##############################################
@property
def is_valid_gcode(self):
if self.is_gm_gcode:
return str(self) in self._machine.config.gcodes
else:
return True
##############################################
@property
def _gcode_info(self):
return self._machine.config.gcodes[str(self)]
##############################################
@property
def gcode_info(self):
if self.is_gm_gcode:
return self._gcode_info
##############################################
@property
def meaning(self):
if self.is_gm_gcode:
return self._gcode_info.meaning
else:
return self._machine.config.letters[self.letter].meaning
##############################################
@property
def modal_group(self):
if self.is_gm_gcode:
return self._gcode_info.modal_group
else:
return None
##############################################
@property
def execution_order(self):
if self.is_gm_gcode:
return self._gcode_info.execution_order
else:
return None
####################################################################################################
class RealValue:
class RealValue(MachineMixin, CloneMixin):
"""Base class for real value"""
pass
####################################################################################################
class ParameterMixin:
"""Mixin for parameter"""
##############################################
def __init__(self, parameter):
......@@ -434,10 +722,16 @@ class ParameterSetting(LineItem, ParameterMixin):
##############################################
def __init__(self, parameter, value):
def __init__(self, parameter, value, machine=None):
super().__init__(machine)
ParameterMixin.__init__(self, parameter)
self.value = value
##############################################
def clone(self):
return self.__class__(self._parameter, self._clone_value(self._value), self._machine)
##############################################
@property
def value(self):
......@@ -445,8 +739,7 @@ class ParameterSetting(LineItem, ParameterMixin):
@value.setter
def value(self, value):
# float expression ...
self._value = value
self._value = self._check_value(value)
##############################################
......@@ -467,11 +760,17 @@ class Parameter(RealValue, ParameterMixin):
##############################################
def __init__(self, parameter):
def __init__(self, parameter, machine=None):
super().__init__(machine)
ParameterMixin.__init__(self, parameter)
##############################################
def clone(self):
return self.__class__(self._parameter, self._machine)
##############################################
def __repr__(self):
return 'Parameter({0._parameter})'.format(self)
......@@ -487,16 +786,24 @@ class Parameter(RealValue, ParameterMixin):
class UnaryOperation(RealValue):
"""Base class for unary operation"""
__function__ = None
__gcode__ = None
##############################################
def __init__(self, arg):
def __init__(self, arg, machine=None):
super().__init__(machine)
self.arg = arg
##############################################
def clone(self):
return self.__class__(self._clone_value(self._arg), self._machine)
##############################################
@property
def arg(self):
return self._arg
......@@ -578,17 +885,25 @@ class Tangent(UnaryOperation):
class BinaryOperation(RealValue):
"""Base class for binary operation"""
__function__ = None
__gcode__ = None
##############################################
def __init__(self, arg1, arg2):
def __init__(self, arg1, arg2, machine=None):
super().__init__(machine)
self.arg1 = arg1
self.arg2 = arg2
##############################################
def clone(self):
return self.__class__(self._clone_value(self._arg1), self._clone_value(self.arg2), self._machine)
##############################################
@property
def arg1(self):
return self._arg1
......
####################################################################################################
#
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
"""Module to implement a G-code implementation configuration and an Oriented Object API for the YAML
configuration files.
See YAML files for examples and :ref:`rs-274-reference-page`.
API implements an array interface or a dictionary interface for a table.
"""
####################################################################################################
__all__ = [
'Config',
'MeaningMixin',
'ExecutionGroup',
'ExecutionOrder',
'Gcode',
'GcodeSet',
'LetterSet',
'ModalGroup',
'ModalGroupSet',
'Parameter',
'ParameterSet',
]
####################################################################################################
import yaml
####################################################################################################
def ensure_list(obj):
if not isinstance(obj, list):
obj = [obj]
return obj
def format_gcode_list(gcodes):
return ' '.join([str(gcode) for gcode in gcodes])
####################################################################################################
class YamlMixin:
def _load_yaml(self, yaml_path):
with open(yaml_path, 'r') as fh:
data = yaml.load(fh.read())
return data
####################################################################################################
class MeaningMixin:
##############################################
def __init__(self, meaning):
self._meaning = str(meaning)
##############################################
@property
def meaning(self):
"""A comment"""
return self._meaning
####################################################################################################
class RstMixin:
##############################################
def _make_rst(self, headers, columns, **kwargs):
number_of_columns = len(headers)
if len(columns) != number_of_columns:
raise ValueError('Number of columns mismatch')
number_of_lines = len(self)
table = []
rule = ''
line_format = ''
for c, title in enumerate(headers):
if rule:
rule += ' '
line_format += ' '
length = len(title)
column = columns[c]
str_columns = []
if hasattr(self, 'sorted_iter'):
it = self.sorted_iter()
else:
it = self
for line_number, item in enumerate(it):
formater = kwargs.get('str_' + column, str)
field = getattr(item, column)
text = formater(field)
length = max(len(text), length)
str_columns.append(text)
rule += '='*length
line_format += '{:' + str(length) + '}'
table.append(str_columns)
rst = ''
rst += rule + '\n'
rst += line_format.format(*headers) + '\n'
rst += rule + '\n'
for line_number in range(number_of_lines):
fields = [table[c][line_number] for c in range(number_of_columns)]
rst += line_format.format(*fields) + '\n'
rst += rule + '\n'
return rst
##############################################
def _write_rst(self, path, *args, **kwargs):
print('Write {}'.format(path))
with open(path, 'w') as fh:
fh.write(self._make_rst(*args, **kwargs))
####################################################################################################
class Parameter(MeaningMixin):
##############################################
def __init__(self, index, meaning, value):
MeaningMixin.__init__(self, meaning)
self._index = int(index)
self._value = float(value)
##############################################
@property
def index(self):
"""Parameter's index (table key)"""
return self._index
@property
def default_value(self):
return self._value
##############################################
def __repr__(self):
return '#{0._index}: {0._meaning}'.format(self)
####################################################################################################
class ParameterSet(YamlMixin, RstMixin):
"""Class for the table of parameters."""
##############################################
def __init__(self, yaml_path):
data = self._load_yaml(yaml_path)
self._parameters = {}
for index, d in data.items():
parameter = Parameter(index, d['meaning'], d['value'])
self._parameters[index] = parameter
##############################################
def __len__(self):
return len(self._parameters)
def __iter__(self):
return iter(self._parameters.values())
def __getitem__(self, index):
return self._parameters[index]
##############################################
def to_rst(self, path):
self._write_rst(
path,
headers=('Parameter Number', 'Parameter Value', 'Comment'),
columns=('index', 'default_value', 'meaning'),
)
####################################################################################################
class Letter(MeaningMixin):
##############################################
def __init__(self, letter, meaning):
MeaningMixin.__init__(self, meaning)
self._letter = str(letter)
##############################################
@property
def letter(self):
"""G-code letter (table key)"""
return self._letter
##############################################
def __repr__(self):
return '#{0._letter}: {0._meaning}'.format(self)
####################################################################################################
class LetterSet(YamlMixin, RstMixin):
"""Class for the table of letters."""
GM_LETTERS = 'GM'
AXIS_LETTERS = 'XYZABC' # 6-axis
##############################################
def is_gm_letter(self, letter):
return letter in self.GM_LETTERS
def is_axis_letter(self, letter):
return letter in self.AXIS_LETTERS
##############################################
def is_gm_word(self, word):
return self.is_gm_letter(word.letter)
def is_axis_word(self, word):
return self.is_axis_letter(word.letter)
##############################################
def __init__(self, yaml_path):
data = self._load_yaml(yaml_path)
self._letters = {}
for letter, d in data.items():
self._letters[letter] = Letter(letter, d['meaning'])
##############################################
def __len__(self):
return len(self._letters)
def __iter__(self):
return iter(self._letters.values())
def __getitem__(self, letter):
return self._letters[letter]
##############################################
def to_rst(self, path):
self._write_rst(
path,
headers=('Letter', 'Meaning'),
columns=('letter', 'meaning'),
)
####################################################################################################
class Gcode(MeaningMixin):
##############################################
def __init__(self, gcode, meaning,
modal_group=None,
execution_order=None,
doc=None,
):
MeaningMixin.__init__(self, meaning)
self._gcode = str(gcode)
# Those are set later due to the initialisation process
self._modal_group = modal_group
self._execution_order = execution_order
self._doc = doc
##############################################
@property
def gcode(self):
"""G-code (table key)"""
return self._gcode
@property
def modal_group(self):
return self._modal_group
@property
def execution_order(self):
return self._execution_order
@property
def execution_order_index(self):
return self._execution_order.index
@property
def doc(self):
return self._doc
##############################################
def __str__(self):
return self._gcode
##############################################
def convert_doc(self, format):
import pypandoc
return pypandoc.convert_text(self.doc, 'rst', format=format)
####################################################################################################
class GcodeSet(YamlMixin, RstMixin):
"""Class for the table of G-codes."""
##############################################
def __init__(self, yaml_path):
data = self._load_yaml(yaml_path)
self._gcodes = {}
for gcode_txt, d in data.items():
gcode = Gcode(gcode_txt, d['meaning'])
self._gcodes[gcode_txt] = gcode
self._sorted_gcodes = None
##############################################
def __len__(self):
return len(self._gcodes)
def __iter__(self):
return iter(self._gcodes.values())
def __getitem__(self, code):
return self._gcodes[code]
def __contains__(self, code):
return code in self._gcodes
##############################################
def _sort(self):
if self._sorted_gcodes is None:
items = list(self)
items.sort(key=lambda item: str(ord(item.gcode[0])*1000) + item.gcode[1:])
self._sorted_gcodes = items
return self._sorted_gcodes
##############################################
def sorted_iter(self):
return iter(self._sort())
##############################################
def iter_on_slice(self, start, stop):
start_index = None
stop_index = None
for i, item in enumerate(self._sort()):
if item.gcode == start:
start_index = i
elif item.gcode == stop:
stop_index = i
if start_index > stop_index:
raise ValueError('{} > {}'.format(start, stop))
return iter(self._sorted_gcodes[start_index:stop_index+1])
##############################################
def to_rst(self, path):
self._write_rst(
path,
headers=('G-code', 'Meaning'),
columns=('gcode', 'meaning'),
)
####################################################################################################
class ExecutionGroup(MeaningMixin):
##############################################
def __init__(self, index, gcodes, raw_gcodes, meaning):
MeaningMixin.__init__(self, meaning)
self._index = int(index)
self._gcodes = list(gcodes)
self._raw_gcodes = list(raw_gcodes)
##############################################
@property
def index(self):
"""Order index (table key)"""
return self._index
@property
def gcodes(self):
"""G-Codes list"""
return self._gcodes
@property
def raw_gcodes(self):
"""Raw G-Codes list"""
return self._raw_gcodes
##############################################
def __str__(self):
return '#{0._index} Meaning: {0._meaning}'.format(self)
####################################################################################################
class ExecutionOrder(YamlMixin, RstMixin):
"""Class for the execution order table."""
##############################################
def __init__(self, yaml_path, gcode_set):
data = self._load_yaml(yaml_path)
self._order = []
count = 1
for index, d in data.items():
if index != count:
raise ValueError('Unexpected index {} versus {}'.format(index, count))
count += 1
raw_gcodes = ensure_list(d['gcodes'])
gcodes = []
for gcode in raw_gcodes:
if '-' in gcode:
start, stop = [int(code[1:]) for code in gcode.split('-')]
letter = gcode[0]
for i in range(start, stop+1):
_gcode = '{}{}'.format(letter, i)
gcodes.append(gcode_set[_gcode])
else:
try:
gcode = gcode_set[gcode]
except KeyError:
if gcode != 'COMMENT':
raise ValueError('Invalid G-code {}'.format(gcode))
gcodes.append(gcode)
group = ExecutionGroup(index, gcodes, raw_gcodes, d['meaning'])
self._order.append(group)
for gcode in gcodes:
if isinstance(gcode, Gcode):
gcode._execution_order = group
##############################################
def __len__(self):
return len(self._order)
def __iter__(self):
return iter(self._order)
def __getitem__(self, index):
return self._order[index]
##############################################
def to_rst(self, path):
self._write_rst(
path,
headers=('Order', 'G-codes', 'Comment'),
columns=('index', 'raw_gcodes', 'meaning'),
str_raw_gcodes=lambda gcodes: format_gcode_list(gcodes),
)
####################################################################################################
class ModalGroup(MeaningMixin):
##############################################
def __init__(self, index, gcodes, meaning):
MeaningMixin.__init__(self, meaning)
self._index = int(index)
self._gcodes = list(gcodes)
##############################################
@property
def index(self):
"""Group id (table key)"""
return self._index
@property
def gcodes(self):
"""G-Codes list"""
return self._gcodes
##############################################
def __repr__(self):
return '#{0._index}: ({1}) Meaning: {0._meaning}'.format(self, format_gcode_list(self._gcodes))
####################################################################################################
class ModalGroupSet(YamlMixin, RstMixin):
"""Class for the table of modal groups."""
##############################################
def __init__(self, yaml_path, gcode_set):
data = self._load_yaml(yaml_path)
self._groups = {}
for index, d in data.items():
gcodes = ensure_list(d['gcodes'])
gcodes = [gcode_set[gcode] for gcode in gcodes]
group = ModalGroup(index, gcodes, d['meaning'])
self._groups[index] = group
for gcode in gcodes:
gcode._modal_group = group
##############################################
def __len__(self):
return len(self._groups)
def __iter__(self):
return iter(self._groups.values())
def __getitem__(self, index):
return self._groups[index]
##############################################
def sorted_iter(self):
items = list(self)
items.sort(key=lambda item: item.index)
return items
##############################################
def to_rst(self, path):
self._write_rst(
path,
headers=('Group', 'G-codes', 'Comment'),
columns=('index', 'gcodes', 'meaning'),
str_gcodes=lambda gcodes: format_gcode_list(gcodes),
)
####################################################################################################
class Config:
"""Class to register a G-code implementation configuration.
An instance is build from a set of YAML files.
"""
##############################################
def __init__(self,
execution_order,
gcodes,
letters,
modal_groups,
parameters,
):
"""Each argument is a path to the corresponding YAML file.
"""
self._gcodes = GcodeSet(gcodes)
self._execution_order = ExecutionOrder(execution_order, self._gcodes)
self._modal_groups = ModalGroupSet(modal_groups, self._gcodes)
# self._letters = str(letters)
# self._parameters = str(parameters)
self._letters = LetterSet(letters)
self._parameters = ParameterSet(parameters)
self._load_doc()
##############################################
def _load_doc(self):
from . import GcodeDoc as gcode_doc
for obj in gcode_doc.__dict__.values():
if isinstance(obj, type):
self._load_gcode_doc_cls(obj)
##############################################
def _set_gcode_doc(self, gcode, cls):
rst_doc = cls.__doc__
rst_doc = rst_doc.replace('\n' + ' '*4, '\n')
self._gcodes[gcode]._doc = rst_doc
##############################################
def _load_gcode_doc_cls(self, cls):
cls_name = cls.__name__
for letter in self._letters.GM_LETTERS:
cls_name = cls_name.replace('_' + letter, ' ' + letter)
cls_name = cls_name.replace('_to', '-')
cls_name = cls_name.replace('_', '.')
gcodes = cls_name.split(' ')
i = 0
while i < len(gcodes):
gcode = gcodes[i]
if gcode.endswith('-'):
start = gcode[:-1]
i += 1
stop = gcodes[i]
for _gcode in self._gcodes.iter_on_slice(start, stop):
self._set_gcode_doc(str(_gcode), cls)
else:
self._set_gcode_doc(gcode, cls)
i += 1
##############################################
@property
def execution_order(self):
""":class:`ExecutionOrder` instance"""
return self._execution_order
@property
def gcodes(self):
""":class:`GcodeSet` instance"""
return self._gcodes
@property
def letters(self):
""":class:`LetterSet` instance"""
# if isinstance(self._letters, str):
# self._letters = LetterSet(self._letters)
return self._letters
@property
def modal_groups(self):
""":class:`ModalGroupSet` instance"""
return self._modal_groups
@property
def parameters(self):
""":class:`ParameterSet` instance"""
# if isinstance(self._parameters, str):
# self._parameters = ParameterSet(self._parameters)
return self._parameters
####################################################################################################
#
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
"""Module to implement a machine coordinate.
"""
####################################################################################################
__all__ = [
'Coordinate',
]
####################################################################################################
import numpy as np
####################################################################################################
class Coordinate:
##############################################
def __init__(self, *args, dimension=None):
if args:
self._v = numpy.array(args)
else:
self._v = numpy.zeros(dimension)
##############################################
def clone(self):
return self.__class__(self._v)
##############################################
@property
def dimension(self):
return self._v.shape[0]
##############################################
def __len__(self):
return self.dimension
def __iter__(self):
return iter(self._v)
def __getitem__(self, slice_):
return self._v[slice_]
##############################################
def set(self, v):
if isintance(self, Coordinate):
self._v = self._v
else:
self._v = v
##############################################
def __eq__(self, v):
return self._v == self._v
##############################################
def __iadd__(self, v):
self._v += self._v
return self
##############################################
def __isub__(self, v):
self._v -= self._v
return self
####################################################################################################
#
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
#
# G-code documentation
#
# Note: This file contains only doc strings for G-codes.
# Each G-code has a corresponding class with a doc string.
# See also class name format, cf. supra.
# For simplicity, doc strings are stored in a Python file instead of a YAML file.
# But this documentation can be converted to HTML and stored in a JSON file, if needed for
# other purposes.
#
####################################################################################################
"""G-code documentation from NIST paper, see :ref:`rs-274-reference-page`.
.. warning::
Must be checked for PDF to rST errors.
.. note::
Class Name Format:
* G1_G2 for G1 and G2,
* G1_1 for G1.1,
* G1_to_G10 for G1 to G10.
G codes of the RS274/NGC language are shown in Table 5 and described following that.
In the command prototypes, three dots (…) stand for a real value. As described earlier, a real value
may be (1) an explicit number, 4, for example, (2) an expression, [2+2], for example, (3) a
parameter value, #88, for example, or (4) a unary function value, acos[0], for example.
In most cases, if axis words (any or all of X…, Y…, Z…, A…, B…, C…) are given, they specify a
destination point. Axis numbers are in the currently active coordinate system, unless explicitly
described as being in the absolute coordinate system. Where axis words are optional, any omitted
axes will have their current value. Any items in the command prototypes not explicitly described as
optional are required. **It is an error if a required item is omitted.**
In the prototypes, the values following letters are often given as explicit numbers. Unless stated
otherwise, the explicit numbers can be real values. For example, G10 L2 could equally well be
written G[2*5] L[1+1]. If the value of parameter 100 were 2, G10 L#100 would also mean the
same. Using real values which are not explicit numbers as just shown in the examples is rarely
useful.
If L… is written in a prototype the “…” will often be referred to as the “L number”. Similarly the
“…” in H… may be called the “H number”, and so on for any other letter.
"""
####################################################################################################
class G0:
"""**Rapid Linear Motion — G0**
For rapid linear motion, program G0 X… Y… Z… A… B… C…, where all the axis words are optional,
except that at least one must be used. The G0 is optional if the current motion mode is G0. This
will produce coordinated linear motion to the destination point at the current traverse rate (or
slower if the machine will not go that fast). It is expected that cutting will not take place
when a G0 command is executing.
**It is an error if:**
* all axis words are omitted.
If cutter radius compensation is active, the motion will differ from the above; see Appendix
B. If G53 is programmed on the same line, the motion will also differ; see Section 3.5.12.
"""
####################################################################################################
class G1:
"""**Linear Motion at Feed Rate — G1**
For linear motion at feed rate (for cutting or not), program G1 X… Y… Z… A… B… C…, where all
the axis words are optional, except that at least one must be used. The G1 is optional if the
current motion mode is G1. This will produce coordinated linear motion to the destination point
at the current feed rate (or slower if the machine will not go that fast).
**It is an error if:**
* all axis words are omitted.
If cutter radius compensation is active, the motion will differ from the above; see Appendix
B. If G53 is programmed on the same line, the motion will also differ; see Section 3.5.12.
"""
####################################################################################################
class G2_G3:
"""**Arc at Feed Rate — G2 and G3**
A circular or helical arc is specified using either G2 (clockwise arc)
or G3 (counterclockwise arc).
The axis of the circle or helix must be parallel to the X, Y, or Z-axis of the machine
coordinate system. The axis (or, equivalently, the plane perpendicular to the axis) is selected
with G17 (Z-axis, XY-plane), G18 (Y-axis, XZ-plane), or G19 (X-axis, YZ-plane). If the arc is
circular, it lies in a plane parallel to the selected plane.
If a line of RS274/NGC code makes an arc and includes rotational axis motion, the rotational
axes turn at a constant rate so that the rotational motion starts and finishes when the XYZ
motion starts and finishes. Lines of this sort are hardly ever programmed.
If cutter radius compensation is active, the motion will differ from what is described here. See
Appendix B.
Two formats are allowed for specifying an arc. We will call these the center format and the
radius format. In both formats the G2 or G3 is optional if it is the current motion mode.
*Radius Format Arc*
In the radius format, the coordinates of the end point of the arc in the selected plane are
specified along with the radius of the arc. Program G2 X… Y… Z… A… B… C… R… (or use G3 instead
of G2). R is the radius. The axis words are all optional except that at least one of the two
words for the axes in the selected plane must be used. The R number is the radius. A positive
radius indicates that the arc turns through 180 degrees or less, while a negative radius
indicates a turn of 180 degrees to 359.999 degrees. If the arc is helical, the value of the end
point of the arc on the coordinate axis parallel to the axis of the helix is also specified.
**It is an error if:**
* both of the axis words for the axes of the selected plane are omitted,
* the end point of the arc is the same as the current point.
It is not good practice to program radius format arcs that are nearly full circles or are
semicircles (or nearly semicircles) because a small change in the location of the end point will
produce a much larger change in the location of the center of the circle (and, hence, the middle
of the arc).
The magnification effect is large enough that rounding error in a number can produce
out-of-tolerance cuts. Nearly full circles are outrageously bad, semicircles (and nearly so) are
only very bad. Other size arcs (in the range tiny to 165 degrees or 195 to 345 degrees) are OK.
Here is an example of a radius format command to mill an arc: G17 G2 x 10 y 15 r 20 z 5.
That means to make a clockwise (as viewed from the positive Z-axis) circular or helical arc
whose axis is parallel to the Z-axis, ending where X=10, Y=15, and Z=5, with a radius of 20. If
the starting value of Z is 5, this is an arc of a circle parallel to the XY-plane; otherwise it
is a helical arc.
*Center Format Arc*
In the center format, the coordinates of the end point of the arc in the selected plane are
specified along with the offsets of the center of the arc from the current location. In this
format, it is OK if the end point of the arc is the same as the current point.
**It is an error if:**
* when the arc is projected on the selected plane, the distance from the current point to the
center differs from the distance from the end point to the center by more than 0.0002 inch (if
inches are being used) or 0.002 millimeter (if millimeters are being used).
When the XY-plane is selected, program G2 X… Y… Z… A… B… C… I… J… (or use G3 instead of G2). The
axis words are all optional except that at least one of X and Y must be used. I and J are the
offsets from the current location (in the X and Y directions, respectively) of the center of the
circle. I and J are optional except that at least one of the two must be used.
**It is an error if:**
* X and Y are both omitted,
* I and J are both omitted.
When the XZ-plane is selected, program G2 X… Y… Z… A… B… C… I… K… (or use G3 instead of G2). The
axis words are all optional except that at least one of X and Z must be used. I and K are the
offsets from the current location (in the X and Z directions, respectively) of the center of the
circle. I and K are optional except that at least one of the two must be used.
**It is an error if:**
* X and Z are both omitted,
* I and K are both omitted.
When the YZ-plane is selected, program G2 X… Y… Z… A… B… C… J… K… (or use G3 instead of G2). The
axis words are all optional except that at least one of Y and Z must be used. J and K are the
offsets from the current location (in the Y and Z directions, respectively) of the center of the
circle. J and K are optional except that at least one of the two must be used.
**It is an error if:**
* Y and Z are both omitted,
* J and K are both omitted.
Here is an example of a center format command to mill an arc: G17 G2 x 10 y 16 i 3 j 4 z 9.
That means to make a clockwise (as viewed from the positive z-axis) circular or helical arc
whose axis is parallel to the Z-axis, ending where X=10, Y=16, and Z=9, with its center offset
in the X direction by 3 units from the current X location and offset in the Y direction by 4
units from the current Y location. If the current location has X=7, Y=7 at the outset, the
center will be at X=10, Y=11. If the starting value of Z is 9, this is a circular arc; otherwise
it is a helical arc. The radius of this arc would be 5.
In the center format, the radius of the arc is not specified, but it may be found easily as the
distance from the center of the circle to either the current point or the end point of the arc.
"""
####################################################################################################
class G4:
"""**Dwell — G4**
For a dwell, program G4 P… . This will keep the axes unmoving for the period of time in seconds
specified by the P number.
**It is an error if:**
* the P number is negative.
"""
####################################################################################################
class G10:
"""**Set Coordinate System Data — G10**
The RS274/NGC language view of coordinate systems is described in Section 3.2.2.
To set the coordinate values for the origin of a coordinate system, program G10 L2 P … X… Y… Z…
A… B… C…, where the P number must evaluate to an integer in the range 1 to 9 (corresponding to
G54 to G59.3) and all axis words are optional. The coordinates of the origin of the coordinate
system specified by the P number are reset to the coordinate values given (in terms of the
absolute coordinate system). Only those coordinates for which an axis word is included on the
line will be reset.
**It is an error if:**
* the P number does not evaluate to an integer in the range 1 to 9. If origin offsets (made by
G92 or G92.3) were in effect before G10 is used, they will continue to be in effect
afterwards.
The coordinate system whose origin is set by a G10 command may be active or inactive at the time
the G10 is executed.
Example: G10 L2 P1 x 3.5 y 17.2 sets the origin of the first coordinate system (the one selected
by G54) to a point where X is 3.5 and Y is 17.2 (in absolute coordinates). The Z coordinate of
the origin (and the coordinates for any rotational axes) are whatever those coordinates of the
origin were before the line was executed.
"""
####################################################################################################
class G17_G18_G19:
"""**Plane Selection — G17, G18, and G19**
Program G17 to select the XY-plane, G18 to select the XZ-plane, or G19 to select the YZ-plane.
The effects of having a plane selected are discussed in Section 3.5.3 and Section 3.5.16.
"""
####################################################################################################
class G20_G21:
"""**Length Units — G20 and G21**
Program G20 to use inches for length units. Program G21 to use millimeters.
It is usually a good idea to program either G20 or G21 near the beginning of a program before
any motion occurs, and not to use either one anywhere else in the program. It is the
responsibility of the user to be sure all numbers are appropriate for use with the current
length units.
"""
####################################################################################################
class G28_G30:
"""**Return to Home — G28 and G30**
Two home positions are defined (by parameters 5161-5166 for G28 and parameters 5181-5186 for
G30). The parameter values are in terms of the absolute coordinate system, but are in
unspecified length units.
To return to home position by way of the programmed position, program G28 X… Y… Z… A… B… C… (or
use G30). All axis words are optional. The path is made by a traverse move from the current
position to the programmed position, followed by a traverse move to the home position. If no
axis words are programmed, the intermediate point is the current point, so only one move is
made.
"""
####################################################################################################
class G38_2:
"""**Straight Probe — G38.2**
*The Straight Probe Command*
Program G38.2 X… Y… Z… A… B… C… to perform a straight probe operation. The rotational axis
words are allowed, but it is better to omit them. If rotational axis words are used, the numbers
must be the same as the current position numbers so that the rotational axes do not move. The
linear axis words are optional, except that at least one of them must be used. The tool in the
spindle must be a probe.
**It is an error if:**
* the current point is less than 0.254 millimeter or 0.01 inch from the programmed point.
* G38.2 is used in inverse time feed rate mode,
* any rotational axis is commanded to move,
* no X, Y, or Z-axis word is used.
In response to this command, the machine moves the controlled point (which should be at the end
of the probe tip) in a straight line at the current feed rate toward the programmed point. If
the probe trips, the probe is retracted slightly from the trip point at the end of command
execution. If the probe does not trip even after overshooting the programmed point slightly, an
error is signalled.
After successful probing, parameters 5061 to 5066 will be set to the coordinates of the location
of the controlled point at the time the probe tripped.
*Using the Straight Probe Command*
Using the straight probe command, if the probe shank is kept nominally parallel to the Z-axis
(i.e., any rotational axes are at zero) and the tool length offset for the probe is used, so
that the controlled point is at the end of the tip of the probe:
* without additional knowledge about the probe, the parallelism of a face of a part to the
XY-plane may, for example, be found.
* if the probe tip radius is known approximately, the parallelism of a face of a part to the YZ
or XZ-plane may, for example, be found.
* if the shank of the probe is known to be well-aligned with the Z-axis and the probe tip radius
is known approximately, the center of a circular hole, may, for example, be found.
* if the shank of the probe is known to be well-aligned with the Z-axis and the probe tip radius
is known precisely, more uses may be made of the straight probe command, such as finding the
diameter of a circular hole.
If the straightness of the probe shank cannot be adjusted to high accuracy, it is desirable to
know the effective radii of the probe tip in at least the +X, -X, +Y, and -Y directions. These
quantities can be stored in parameters either by being included in the parameter file or by
being set in an RS274/NGC program.
Using the probe with rotational axes not set to zero is also feasible. Doing so is more complex
than when rotational axes are at zero, and we do not deal with it here.
*Example Code*
As a usable example, the code for finding the center and diameter of a circular hole is shown in
Table 6. For this code to yield accurate results, the probe shank must be well-aligned with the
Z-axis, the cross section of the probe tip at its widest point must be very circular, and the
probe tip radius (i.e., the radius of the circular cross section) must be known precisely. If
the probe tip radius is known only approximately (but the other conditions hold), the location
of the hole center will still be accurate, but the hole diameter will not.
In Table 6, an entry of the form *description of number* is meant to be replaced by an actual
number that matches the *description of number*. After this section of code has executed, the
X-value of the center will be in parameter 1041, the Y-value of the center in parameter 1022,
and the diameter in parameter 1034. In addition, the diameter parallel to the X-axis will be in
parameter 1024, the diameter parallel to the Y-axis in parameter 1014, and the difference (an
indicator of circularity) in parameter 1035. The probe tip will be in the hole at the XY center
of the hole.
The example does not include a tool change to put a probe in the spindle. Add the tool change
code at the beginning, if needed.
"""
####################################################################################################
class G40_G41_G42:
"""**Cutter Radius Compensation — G40, G41, and G42**
To turn cutter radius compensation off, program G40. It is OK to turn compensation off when it
is already off.
Cutter radius compensation may be performed only if the XY-plane is active.
To turn cutter radius compensation on left (i.e., the cutter stays to the left of the programmed
path
**Table 6. Code to Probe Hole**
.. code::
N010 (probe to find center and diameter of circular hole)
N020 (This program will not run as given here. You have to)
N030 (insert numbers in place of <description of number>.)
N040 (Delete lines N020, N030, and N040 when you do that.)
N050 G0 Z <Z-value of retracted position> F <feed rate>
N060 #1001=<nominal X-value of hole center>
N070 #1002=<nominal Y-value of hole center>
N080 #1003=<some Z-value inside the hole>
N090 #1004=<probe tip radius>
N100 #1005=[<nominal hole diameter>/2.0 - #1004]
N110 G0 X#1001 Y#1002 (move above nominal hole center)
N120 G0 Z#1003 (move into hole - to be cautious, substitute G1 for G0 here)
N130 G38.2 X[#1001 + #1005] (probe +X side of hole)
N140 #1011=#5061 (save results)
N150 G0 X#1001 Y#1002 (back to center of hole)
N160 G38.2 X[#1001 - #1005] (probe -X side of hole)
N170 #1021=[[#1011 + #5061] / 2.0] (find pretty good X-value of hole center)
N180 G0 X#1021 Y#1002 (back to center of hole)
N190 G38.2 Y[#1002 + #1005] (probe +Y side of hole)
N200 #1012=#5062 (save results)
N210 G0 X#1021 Y#1002 (back to center of hole)
N220 G38.2 Y[#1002 - #1005] (probe -Y side of hole)
N230 #1022=[[#1012 + #5062] / 2.0] (find very good Y-value of hole center)
N240 #1014=[#1012 - #5062 + [2 \* #1004]] (find hole diameter in Y-direction)
N250 G0 X#1021 Y#1022 (back to center of hole)
N260 G38.2 X[#1021 + #1005] (probe +X side of hole)
N270 #1031=#5061 (save results)
N280 G0 X#1021 Y#1022 (back to center of hole)
N290 G38.2 X[#1021 - #1005] (probe -X side of hole)
N300 #1041=[[#1031 + #5061] / 2.0] (find very good X-value of hole center)
N310 #1024=[#1031 - #5061 + [2 \* #1004]] (find hole diameter in X-direction)
N320 #1034=[[#1014 + #1024] / 2.0] (find average hole diameter)
N330 #1035=[#1024 - #1014] (find difference in hole diameters)
N340 G0 X#1041 Y#1022 (back to center of hole)
N350 M2 (that’s all, folks)
when the tool radius is positive), program G41 D… . To turn cutter radius compensation on right
(i.e., the cutter stays to the right of the programmed path when the tool radius is positive),
program G42 D… . The D word is optional; if there is no D word, the radius of the tool currently
in the spindle will be used. If used, the D number should normally be the slot number of the
tool in the spindle, although this is not required. It is OK for the D number to be zero; a
radius value of zero will be used.
**It is an error if:**
* the D number is not an integer, is negative or is larger than the number of carousel slots,
* the XY-plane is not active,
* cutter radius compensation is commanded to turn on when it is already on.
The behavior of the machining center when cutter radius compensation is on is described in
Appendix B.
"""
####################################################################################################
class G43_G49:
"""**Tool Length Offsets — G43 and G49**
To use a tool length offset, program G43 H…, where the H number is the desired index in the tool
table. It is expected that all entries in this table will be positive. The H number should be,
but does not have to be, the same as the slot number of the tool currently in the spindle. It is
OK for the H number to be zero; an offset value of zero will be used.
**It is an error if:**
* the H number is not an integer, is negative, or is larger than the number of carousel slots.
To use no tool length offset, program G49.
It is OK to program using the same offset already in use. It is also OK to program using no tool
length offset if none is currently being used.
"""
####################################################################################################
class G53:
"""**Move in Absolute Coordinates — G53**
For linear motion to a point expressed in absolute coordinates, program G1 G53 X… Y… Z… A… B…
C… (or use G0 instead of G1), where all the axis words are optional, except that at least one
must be used. The G0 or G1 is optional if it is the current motion mode. G53 is not modal and
must be programmed on each line on which it is intended to be active. This will produce
coordinated linear motion to the programmed point. If G1 is active, the speed of motion is the
current feed rate (or slower if the machine will not go that fast). If G0 is active, the speed
of motion is the current traverse rate (or slower if the machine will not go that fast).
**It is an error if:**
* G53 is used without G0 or G1 being active,
* G53 is used while cutter radius compensation is on.
See Section 3.2.2 for an overview of coordinate systems.
"""
####################################################################################################
class G54_to_G59_3:
"""**Select Coordinate System — G54 to G59.3**
To select coordinate system 1, program G54, and similarly for other coordinate systems. The
system-number—G-code pairs are: (1—G54), (2—G55), (3—G56), (4—G57), (5—G58), (6—G59), (7—G59.1),
(8—G59.2), and (9—G59.3).
**It is an error if:**
* one of these G-codes is used while cutter radius compensation is on.
See Section 3.2.2 for an overview of coordinate systems.
"""
####################################################################################################
class G61_G61_1_G64:
"""**Set Path Control Mode — G61, G61.1, and G64**
Program G61 to put the machining center into exact path mode, G61.1 for exact stop mode, or G64
for continuous mode. It is OK to program for the mode that is already active. See Section
2.1.2.16 for a discussion of these modes.
"""
####################################################################################################
class G80:
"""**Cancel Modal Motion — G80**
Program G80 to ensure no axis motion will occur.
**It is an error if:**
* Axis words are programmed when G80 is active, unless a modal group 0 G code is programmed
which uses axis words.
"""
####################################################################################################
class G81_to_G89:
"""**Canned Cycles — G81 to G89**
The canned cycles G81 through G89 have been implemented as described in this section. Two
examples are given with the description of G81 below.
All canned cycles are performed with respect to the currently selected plane. Any of the three
planes (XY, YZ, ZX) may be selected. Throughout this section, most of the descriptions assume
the XY-plane has been selected. The behavior is always analogous if the YZ or XZ-plane is
selected.
Rotational axis words are allowed in canned cycles, but it is better to omit them. If rotational
axis words are used, the numbers must be the same as the current position numbers so that the
rotational axes do not move.
All canned cycles use X, Y, R, and Z numbers in the NC code. These numbers are used to determine
X, Y, R, and Z positions. The R (usually meaning retract) position is along the axis
perpendicular to the currently selected plane (Z-axis for XY-plane, X-axis for YZ-plane, Y-axis
for XZ-plane). Some canned cycles use additional arguments.
For canned cycles, we will call a number “sticky” if, when the same cycle is used on several
lines of code in a row, the number must be used the first time, but is optional on the rest of
the lines.
Sticky numbers keep their value on the rest of the lines if they are not explicitly programmed
to be different. The R number is always sticky.
In incremental distance mode: when the XY-plane is selected, X, Y, and R numbers are treated as
increments to the current position and Z as an increment from the Z-axis position before the
move involving Z takes place; when the YZ or XZ-plane is selected, treatment of the axis words
is analogous. In absolute distance mode, the X, Y, R, and Z numbers are absolute positions in
the current coordinate system.
The L number is optional and represents the number of repeats. L=0 is not allowed. If the repeat
feature is used, it is normally used in incremental distance mode, so that the same sequence of
motions is repeated in several equally spaced places along a straight line. In absolute distance
mode, L > 1 means “do the same cycle in the same place several times,” Omitting the L word is
equivalent to specifying L=1. The L number is not sticky.
When L>1 in incremental mode with the XY-plane selected, the X and Y positions are determined by
adding the given X and Y numbers either to the current X and Y positions (on the first go-
around) or to the X and Y positions at the end of the previous go-around (on the
repetitions). The R and Z positions do not change during the repeats.
The height of the retract move at the end of each repeat (called “clear Z” in the descriptions
below) is determined by the setting of the retract mode: either to the original Z position (if
that is above the R position and the retract mode is G98, OLD_Z), or otherwise to the R
position. See Section 3.5.20
**It is an error if:**
* X, Y, and Z words are all missing during a canned cycle,
* a P number is required and a negative P number is used,
* an L number is used that does not evaluate to a positive integer,
* rotational axis motion is used during a canned cycle,
* inverse time feed rate is active during a canned cycle,
* cutter radius compensation is active during a canned cycle.
When the XY plane is active, the Z number is sticky, and **it is an error if:**
* the Z number is missing and the same canned cycle was not already active,
* the R number is less than the Z number.
When the XZ plane is active, the Y number is sticky, and **it is an error if:**
* the Y number is missing and the same canned cycle was not already active,
* the R number is less than the Y number.
When the YZ plane is active, the X number is sticky, and **it is an error if:**
* the X number is missing and the same canned cycle was not already active,
* the R number is less than the X number.
*Preliminary and In-Between Motion*
At the very beginning of the execution of any of the canned cycles, with the XY-plane selected,
if the current Z position is below the R position, the Z-axis is traversed to the R
position. This happens only once, regardless of the value of L.
In addition, at the beginning of the first cycle and each repeat, the following one or two moves
are made:
1. a straight traverse parallel to the XY-plane to the given XY-position,
2. a straight traverse of the Z-axis only to the R position, if it is not already at the R
position.
If the XZ or YZ plane is active, the preliminary and in-between motions are analogous.
*G81 Cycle*
The G81 cycle is intended for drilling. Program G81 X… Y… Z… A… B… C… R… L…
0. Preliminary motion, as described above.
1. Move the Z-axis only at the current feed rate to the Z position.
2. Retract the Z-axis at traverse rate to clear Z.
**Example 1**
Suppose the current position is (1, 2, 3) and the XY-plane has been selected, and the following
line of NC code is interpreted.
G90 G81 G98 X4 Y5 Z1.5 R2.8
This calls for absolute distance mode (G90) and OLD_Z retract mode (G98) and calls for the G81
drilling cycle to be performed once. The X number and X position are 4. The Y number and Y
position are 5. The Z number and Z position are 1.5. The R number and clear Z are 2.8. Old Z is
3.
The following moves take place.
1. a traverse parallel to the XY-plane to (4,5,3)
2. a traverse parallel to the Z-axis to (4,5,2.8)
3. a feed parallel to the Z-axis to (4,5,1.5)
4. a traverse parallel to the Z-axis to (4,5,3)
**Example 2**
Suppose the current position is (1, 2, 3) and the XY-plane has been selected, and the following
line of NC code is interpreted.
G91 G81 G98 X4 Y5 Z-0.6 R1.8 L3
This calls for incremental distance mode (G91) and OLD_Z retract mode (G98) and calls for the
G81 drilling cycle to be repeated three times. The X number is 4, the Y number is 5, the Z
number is -0.6 and the R number is 1.8. The initial X position is 5 (=1+4), the initial Y
position is 7 (=2+5), the clear Z position is 4.8 (=1.8+3), and the Z position is 4.2
(=4.8-0.6). Old Z is 3.
The first move is a traverse along the Z-axis to (1,2,4.8), since old Z < clear Z.
The first repeat consists of 3 moves.
1. a traverse parallel to the XY-plane to (5,7,4.8)
2. a feed parallel to the Z-axis to (5,7, 4.2)
3. a traverse parallel to the Z-axis to (5,7,4.8)
The second repeat consists of 3 moves. The X position is reset to 9 (=5+4) and the Y position to
12 (=7+5).
1. a traverse parallel to the XY-plane to (9,12,4.8)
2. a feed parallel to the Z-axis to (9,12, 4.2)
3. a traverse parallel to the Z-axis to (9,12,4.8)
The third repeat consists of 3 moves. The X position is reset to 13 (=9+4) and the Y position to
17 (=12+5).
1. a traverse parallel to the XY-plane to (13,17,4.8)
2. a feed parallel to the Z-axis to (13,17, 4.2)
3. a traverse parallel to the Z-axis to (13,17,4.8)
*G82 Cycle*
The G82 cycle is intended for drilling. Program G82 X… Y… Z… A… B… C… R… L… P…
0. Preliminary motion, as described above.
1. Move the Z-axis only at the current feed rate to the Z position.
2. Dwell for the P number of seconds.
3. Retract the Z-axis at traverse rate to clear Z.
*G83 Cycle*
The G83 cycle (often called peck drilling) is intended for deep drilling or milling with chip
breaking. The retracts in this cycle clear the hole of chips and cut off any long stringers
(which are common when drilling in aluminum). This cycle takes a Q number which represents a
“delta” increment along the Z-axis. Program G83 X… Y… Z… A… B… C… R… L… Q…
0. Preliminary motion, as described above.
1. Move the Z-axis only at the current feed rate downward by delta or to the Z position,
whichever is less deep.
2. Rapid back out to the clear_z.
3. Rapid back down to the current hole bottom, backed off a bit.
4. Repeat steps 1, 2, and 3 until the Z position is reached at step 1.
5. Retract the Z-axis at traverse rate to clear Z.
**It is an error if:**
* the Q number is negative or zero.
*G84 Cycle*
The G84 cycle is intended for right-hand tapping with a tap tool.
Program G84 X… Y… Z… A… B… C… R… L…
0. Preliminary motion, as described above.
1. Start speed-feed synchronization.
2. Move the Z-axis only at the current feed rate to the Z position.
3. Stop the spindle.
4. Start the spindle counterclockwise.
5. Retract the Z-axis at the current feed rate to clear Z.
6. If speed-feed synch was not on before the cycle started, stop it.
7. Stop the spindle.
8. Start the spindle clockwise.
The spindle must be turning clockwise before this cycle is used. **It is an error if:**
* the spindle is not turning clockwise before this cycle is executed.
With this cycle, the programmer must be sure to program the speed and feed in the correct
proportion to match the pitch of threads being made. The relationship is that the spindle speed
equals the feed rate times the pitch (in threads per length unit). For example, if the pitch is
2 threads per millimeter, the active length units are millimeters, and the feed rate has been
set with the command F150, then the speed should be set with the command S300, since 150 x 2 =
300.
If the feed and speed override switches are enabled and not set at 100%, the one set at the
lower setting will take effect. The speed and feed rates will still be synchronized.
*G85 Cycle*
The G85 cycle is intended for boring or reaming, but could be used for drilling or milling.
Program G85 X… Y… Z… A… B… C… R… L…
0. Preliminary motion, as described above.
1. Move the Z-axis only at the current feed rate to the Z position.
2. Retract the Z-axis at the current feed rate to clear Z.
*G86 Cycle*
The G86 cycle is intended for boring. This cycle uses a P number for the number of seconds to
dwell. Program G86 X… Y… Z… A… B… C… R… L… P…
0. Preliminary motion, as described above.
1. Move the Z-axis only at the current feed rate to the Z position.
2. Dwell for the P number of seconds.
3. Stop the spindle turning.
4. Retract the Z-axis at traverse rate to clear Z.
5. Restart the spindle in the direction it was going.
The spindle must be turning before this cycle is used. **It is an error if:**
* the spindle is not turning before this cycle is executed.
*G87 Cycle*
The G87 cycle is intended for back boring.
Program G87 X… Y… Z… A… B… C… R… L… I… J… K…
The situation, as shown in Figure 1, is that you have a through hole and you want to counterbore
the bottom of hole. To do this you put an L-shaped tool in the spindle with a cutting surface on
the UPPER side of its base. You stick it carefully through the hole when it is not spinning and
is oriented so it fits through the hole, then you move it so the stem of the L is on the axis of
the hole, start the spindle, and feed the tool upward to make the counterbore. Then you stop
the tool, get it out of the hole, and restart it.
This cycle uses I and J numbers to indicate the position for inserting and removing the tool. I
and J will always be increments from the X position and the Y position, regardless of the
distance mode setting. This cycle also uses a K number to specify the position along the Z-axis
of the controlled point top of the counterbore. The K number is a Z-value in the current
coordinate system in absolute distance mode, and an increment (from the Z position) in
incremental distance mode.
0. Preliminary motion, as described above.
1. Move at traverse rate parallel to the XY-plane to the point indicated by I and J.
2. Stop the spindle in a specific orientation.
3. Move the Z-axis only at traverse rate downward to the Z position.
4. Move at traverse rate parallel to the XY-plane to the X,Y location.
5. Start the spindle in the direction it was going before.
6. Move the Z-axis only at the given feed rate upward to the position indicated by K.
7. Move the Z-axis only at the given feed rate back down to the Z position.
8. Stop the spindle in the same orientation as before.
9. Move at traverse rate parallel to the XY-plane to the point indicated by I and J.
10. Move the Z-axis only at traverse rate to the clear Z.
11. Move at traverse rate parallel to the XY-plane to the specified X,Y location.
12. Restart the spindle in the direction it was going before.
When programming this cycle, the I and J numbers must be chosen so that when the tool is stopped
in an oriented position, it will fit through the hole. Because different cutters are made
differently, it may take some analysis and/or experimentation to determine appropriate values
for I and J.
*G88 Cycle*
The G88 cycle is intended for boring. This cycle uses a P word, where P specifies the number of
seconds to dwell. Program G88 X… Y… Z… A… B… C… R… L… P…
0. Preliminary motion, as described above.
1. Move the Z-axis only at the current feed rate to the Z position.
2. Dwell for the P number of seconds.
3. Stop the spindle turning.
**Figure 1. G87 Cycle**
The eight subfigures are labelled with the steps from the description above.
4. Stop the program so the operator can retract the spindle manually.
5. Restart the spindle in the direction it was going.
*G89 Cycle*
The G89 cycle is intended for boring. This cycle uses a P number, where P specifies the number
of seconds to dwell. program G89 X… Y… Z… A… B… C… R… L… P…
0. Preliminary motion, as described above.
1. Move the Z-axis only at the current feed rate to the Z position.
2. Dwell for the P number of seconds.
3. Retract the Z-axis at the current feed rate to clear Z.
"""
####################################################################################################
class G90_G91:
"""**Set Distance Mode — G90 and G91**
Interpretation of RS274/NGC code can be in one of two distance modes: absolute or incremental.
To go into absolute distance mode, program G90. In absolute distance mode, axis numbers (X, Y,
Z, A, B, C) usually represent positions in terms of the currently active coordinate system. Any
exceptions to that rule are described explicitly in this Section 3.5.
To go into incremental distance mode, program G91. In incremental distance mode, axis numbers
(X, Y, Z, A, B, C) usually represent increments from the current values of the numbers.
I and J numbers always represent increments, regardless of the distance mode setting. K numbers
represent increments in all but one usage (see Section 3.5.16.8), where the meaning changes with
distance mode.
"""
####################################################################################################
class G92_G92_1_G92_2_G92_3:
"""**3.5.18 Coordinate System Offsets — G92, G92.1, G92.2, G92.3**
See Section 3.2.2 for an overview of coordinate systems.
To make the current point have the coordinates you want (without motion), program G92 X… Y… Z…
A… B… C… , where the axis words contain the axis numbers you want. All axis words are
optional, except that at least one must be used. If an axis word is not used for a given axis,
the coordinate on that axis of the current point is not changed.
**It is an error if:**
* all axis words are omitted.
When G92 is executed, the origin of the currently active coordinate system moves. To do this,
origin offsets are calculated so that the coordinates of the current point with respect to the
moved origin are as specified on the line containing the G92. In addition, parameters 5211 to
5216 are set to the X, Y, Z, A, B, and C-axis offsets. The offset for an axis is the amount the
origin must be moved so that the coordinate of the controlled point on the axis has the
specified value.
Here is an example. Suppose the current point is at X=4 in the currently specified coordinate
system and the current X-axis offset is zero, then G92 x7 sets the X-axis offset to -3, sets
parameter 5211 to -3, and causes the X-coordinate of the current point to be 7.
The axis offsets are always used when motion is specified in absolute distance mode using any of
the nine coordinate systems (those designated by G54 - G59.3). Thus all nine coordinate systems
are affected by G92.
Being in incremental distance mode has no effect on the action of G92.
Non-zero offsets may be already be in effect when the G92 is called. If this is the case, the
new value of each offset is A+B, where A is what the offset would be if the old offset were
zero, and B is the old offset. For example, after the previous example, the X-value of the
current point is 7. If G92 x9 is then programmed, the new X-axis offset is -5, which is
calculated by [[7-9] + -3].
To reset axis offsets to zero, program G92.1 or G92.2. G92.1 sets parameters 5211 to 5216 to
zero, whereas G92.2 leaves their current values alone.
To set the axis offset values to the values given in parameters 5211 to 5216, program G92.3.
You can set axis offsets in one program and use the same offsets in another program. Program G92
in the first program. This will set parameters 5211 to 5216. Do not use G92.1 in the remainder
of the first program. The parameter values will be saved when the first program exits and
restored when the second one starts up. Use G92.3 near the beginning of the second program.
That will restore the offsets saved in the first program. If other programs are to run between
the the program that sets the offsets and the one that restores them, make a copy of the
parameter file written by the first program and use it as the parameter file for the second
program.
"""
####################################################################################################
class G93_G94:
"""**Set Feed Rate Mode — G93 and G94**
Two feed rate modes are recognized: units per minute and inverse time. Program G94 to start the
units per minute mode. Program G93 to start the inverse time mode.
In units per minute feed rate mode, an F word (no, not *that* F word; we mean * feedrate*) is
interpreted to mean the controlled point should move at a certain number of inches per minute,
millimeters per minute, or degrees per minute, depending upon what length units are being used
and which axis or axes are moving.
In inverse time feed rate mode, an F word means the move should be completed in [one divided by
the F number] minutes. For example, if the F number is 2.0, the move should be completed in half
a minute.
When the inverse time feed rate mode is active, an F word must appear on every line which has a
G1, G2, or G3 motion, and an F word on a line that does not have G1, G2, or G3 is ignored. Being
in inverse time feed rate mode does not affect G0 (rapid traverse) motions.
**It is an error if:**
* inverse time feed rate mode is active and a line with G1, G2, or G3 (explicitly or implicitly)
does not have an F word.
"""
####################################################################################################
class G98_G99:
"""**Set Canned Cycle Return Level — G98 and G99**
When the spindle retracts during canned cycles, there is a choice of how far it retracts: (1)
retract perpendicular to the selected plane to the position indicated by the R word, or (2)
retract perpendicular to the selected plane to the position that axis was in just before the
canned cycle started (unless that position is lower than the position indicated by the R word,
in which case use the R word position).
To use option (1), program G99. To use option (2), program G98. Remember that the R word has
different meanings in absolute distance mode and incremental distance mode.
"""
####################################################################################################
# **Input M Codes**
#
# M codes of the RS274/NGC language are shown in Table 7.
####################################################################################################
class M0_M1_M2_M30_M60:
"""**Program Stopping and Ending — M0, M1, M2, M30, M60**
To stop a running program temporarily (regardless of the setting of the optional stop switch),
program M0.
To stop a running program temporarily (but only if the optional stop switch is on), program M1.
It is OK to program M0 and M1 in MDI mode, but the effect will probably not be noticeable,
because normal behavior in MDI mode is to stop after each line of input, anyway.
To exchange pallet shuttles and then stop a running program temporarily (regardless of the
setting of the optional stop switch), program M60.
If a program is stopped by an M0, M1, or M60, pressing the cycle start button will restart the
program at the following line.
To end a program, program M2. To exchange pallet shuttles and then end a program, program
M30. Both of these commands have the following effects.
1. Axis offsets are set to zero (like G92.2) and origin offsets are set to the default (like G54).
2. Selected plane is set to CANON_PLANE_XY (like G17).
3. Distance mode is set to MODE_ABSOLUTE (like G90).
4. Feed rate mode is set to UNITS_PER_MINUTE (like G94).
5. Feed and speed overrides are set to ON (like M48).
6. Cutter compensation is turned off (like G40).
7. The spindle is stopped (like M5).
8. The current motion mode is set to G_1 (like G1).
9. Coolant is turned off (like M9).
No more lines of code in an RS274/NGC file will be executed after the M2 or M30 command is
executed. Pressing cycle start will start the program back at the beginning of the file.
"""
####################################################################################################
class M3_M4_M5:
"""**Spindle Control — M3, M4, M5**
To start the spindle turning clockwise at the currently programmed speed, program M3.
To start the spindle turning counterclockwise at the currently programmed speed, program M4.
To stop the spindle from turning, program M5.
It is OK to use M3 or M4 if the spindle speed is set to zero. If this is done (or if the speed
override switch is enabled and set to zero), the spindle will not start turning. If, later, the
spindle speed is set above zero (or the override switch is turned up), the spindle will start
turning. It is OK to use
M3 or M4 when the spindle is already turning or to use M5 when the spindle is already stopped.
"""
####################################################################################################
class M6:
"""**Tool Change — M6**
To change a tool in the spindle from the tool currently in the spindle to the tool most recently
selected (using a T word — see Section 3.7.3), program M6. When the tool change is complete:
* The spindle will be stopped.
* The tool that was selected (by a T word on the same line or on any line after the previous
tool change) will be in the spindle. The T number is an integer giving the changer slot of the
tool (not its id).
* If the selected tool was not in the spindle before the tool change, the tool that was in the
spindle (if there was one) will be in its changer slot.
* The coordinate axes will be stopped in the same absolute position they were in before the tool
change (but the spindle may be re-oriented).
* No other changes will be made. For example, coolant will continue to flow during the tool
change unless it has been turned off by an M9.
The tool change may include axis motion while it is in progress. It is OK (but not useful) to
program a change to the tool already in the spindle. It is OK if there is no tool in the
selected slot; in that case, the spindle will be empty after the tool change. If slot zero was
last selected, there will definitely be no tool in the spindle after a tool change.
"""
####################################################################################################
class M7_M8_M9:
"""**Coolant Control — M7, M8, M9**
* To turn mist coolant on, program M7.
* To turn flood coolant on, program M8.
* To turn all coolant off, program M9.
It is always OK to use any of these commands, regardless of what coolant is on or off.
"""
####################################################################################################
class M48_M48:
"""**Override Control — M48 and M49**
To enable the speed and feed override switches, program M48. To disable both switches, program
M49. See Section 2.2.1 for more details. It is OK to enable or disable the switches when they
are already enabled or disabled.
"""
####################################################################################################
# **Other Input Codes**
####################################################################################################
class F:
"""**Set Feed Rate — F**
To set the feed rate, program F… . The application of the feed rate is as described in Section
2.1.2.5, unless inverse time feed rate mode is in effect, in which case the feed rate is as
described in Section 3.5.19.
"""
####################################################################################################
class S:
"""**Set Spindle Speed — S**
To set the speed in revolutions per minute (rpm) of the spindle, program S… . The spindle will
turn at that speed when it has been programmed to start turning. It is OK to program an S word
whether the spindle is turning or not. If the speed override switch is enabled and not set at
100%, the speed will be different from what is programmed. It is OK to program S0; the spindle
will not turn if that is done.
**It is an error if:**
* the S number is negative.
As described in Section 3.5.16.5, if a G84 (tapping) canned cycle is active and the feed and
speed override switches are enabled, the one set at the lower setting will take effect. The
speed and feed rates will still be synchronized. In this case, the speed may differ from what is
programmed, even if the speed override switch is set at 100%.
"""
####################################################################################################
class T:
"""**Select Tool — T**
To select a tool, program T…, where the T number is the carousel slot for the tool. The tool is
not changed until an M6 is programmed (see Section 3.6.3). The T word may appear on the same
line as the M6 or on a previous line. It is OK, but not normally useful, if T words appear on
two or more lines with no tool change. The carousel may move a lot, but only the most recent T
word will take effect at the next tool change. It is OK to program T0; no tool will be
selected. This is useful if you want the spindle to be empty after a tool change.
**It is an error if:**
* a negative T number is used,
* a T number larger than the number of slots in the carousel is used.
On some machines, the carousel will move when a T word is programmed, at the same time machining
is occurring. On such machines, programming the T word several lines before a tool change will
save time. A common programming practice for such machines is to put the T word for the next
tool to be used on the line after a tool change. This maximizes the time available for the
carousel to move.
"""
####################################################################################################
#
# PythonicGcodeMachine - @licence_header_description@
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
......@@ -18,7 +18,16 @@
#
####################################################################################################
__all__ = ['GcodeLexerError', 'GcodeLexer']
"""Module to implement a RS-274 G-code lexer."""
####################################################################################################
__all__ = [
'GcodeLexerError',
'GcodeLexer',
'GcodeLexerMixin',
'GcodeTokenMixin',
]
####################################################################################################
......@@ -36,11 +45,9 @@ class GcodeLexerError(ValueError):
####################################################################################################
class GcodeLexer:
class GcodeTokenMixin:
"""Class to implement a RS-274 G-code lexer.
"""
"""Mixin to define RS-274 G-code tokens. """
# List of token names.
tokens = (
......@@ -196,6 +203,12 @@ class GcodeLexer:
# raise GcodeLexerError("Illegal character @{} '{}'".format(t.lexpos, t.value))
raise GcodeLexerError(t.lexpos)
####################################################################################################
class GcodeLexerMixin:
"""Class to implement a RS-274 G-code lexer."""
##############################################
def __init__(self):
......@@ -209,6 +222,7 @@ class GcodeLexer:
module=self,
reflags=int(re.VERBOSE + re.IGNORECASE),
optimize=1,
lextab='_lextab',
**kwargs,
)
......@@ -226,3 +240,8 @@ class GcodeLexer:
if not token:
break
yield token
####################################################################################################
class GcodeLexer(GcodeLexerMixin, GcodeTokenMixin):
pass
####################################################################################################
#
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
"""Module to implement a basic G-code machine.
"""
####################################################################################################
__all__ = [
'GcodeMachine',
]
####################################################################################################
from pathlib import Path as Path
from .Config import Config
from .Parser import GcodeParser, GcodeParserError
####################################################################################################
class GcodeMachine:
PARSER_CLS = GcodeParser
##############################################
def __init__(self):
self._config = None
self.load_config()
self._parser = None
self.setup_parser()
##############################################
def load_config(self):
data_path = Path(__file__).parent.joinpath('data')
self._config = Config(
execution_order=data_path.joinpath('rs274-execution-order.yaml'),
gcodes=data_path.joinpath('rs274-gcodes.yaml'),
letters=data_path.joinpath('rs274-word-starting-letter.yaml'),
modal_groups=data_path.joinpath('rs274-modal-groups.yaml'),
parameters=data_path.joinpath('rs274-default-parameter-file.yaml'),
)
##############################################
def setup_parser(self):
self._parser = self.PARSER_CLS(machine=self)
##############################################
@property
def config(self):
return self._config
@property
def parser(self):
return self._parser
##############################################
def reset():
pass
####################################################################################################
#
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
"""Module to implement a basic G-code machine.
"""
####################################################################################################
__all__ = [
'MachineState',
]
####################################################################################################
from enum import Enum, auto
from .Coordinate import Coordinate
from .ToolSet import ToolSet
####################################################################################################
class PlaneSelection:
XY = auto()
XZ = auto()
YZ = auto()
class FeedRateMode:
UNITS_PER_MINUTE = auto()
INVERSE_TIME = auto()
####################################################################################################
class MachineState:
NUMBER_OF_COORDINATE_SYSTEMS = 9
##############################################
def __init__(self,
number_of_axes,
is_metric=True,
):
self._number_of_axes = int(number_of_axes)
self._coordinate = Coordinate(dimension=self._number_of_axes)
self._tool_set = ToolSet()
self._tool = None # T
self._is_metric = bool(is_metric)
self._use_metric = self._is_metric # G20 inch / G21 mm
self._use_absolut = True # G90 absolut / G91 incremental
# G17 XY-plane selection
# G18 XZ-plane selection
# G19 YZ-plane selection
self._plane = None
# G54 G55 G56 G57 G58 G59 G59.1 G59.2 G59.3
self._coordinate_system = None
self._feed_rate = 0 # F
# G93 units per minute
# G94 inverse time
self._feed_rate_mode = FeedRateMode.UNITS_PER_MINUTE
self._spindle_rate = 0 # S
### 4 M0 M1 M2 M30 M60 stopping
### 6 M6 tool change
### 7 M3 M4 M5 spindle turning
### 8 M7 M8 M9 coolant (special case: M7 and M8 may be active at the same time)
### 9 M48 M49 enable/disable feed and speed override switches
### 10 G98 G99 return mode in canned cycles
### 13 G61 G61.1 G64 path control mode
##############################################
@property
def number_of_axes(self):
return self._number_of_axes
@property
def coordinate(self):
return self._coordinate
##############################################
@property
def is_metric(self):
return self._is_metric
@property
def use_metric(self):
return self._use_metric
@use_metric.setter
def use_metric(self, value):
self._use_metric = bool(value)
##############################################
@property
def use_absolut(self):
return self._use_absolut
@use_absolut.setter
def use_absolut(self, value):
self._use_absolut = bool(value)
##############################################
@property
def plane(self):
return self._plane
@plane.setter
def plane(self, value):
self._plane = PlaneSelection(value)
##############################################
@property
def coordinate_system(self):
return self._coordinate_system
@coordinate_system.setter
def coordinate_system(self, value):
_value = int(value)
if not(1 <= _value <= self.NUMBER_OF_COORDINATE_SYSTEMS):
raise ValueError('Invalid coordinate system {}'.format(value))
self._coordinate_system = _value
##############################################
@property
def tool_set(self):
return self._tool_set
def load_tool(self, pocket):
"""Load the tool at the given carousel pocket.
Raise ValueError if KeyError.
"""
self._tool.toggle_loaded()
try:
self._tool = self._tool_set[pocket].toggle_loaded()
except KeyError:
raise ValueError('Invalid carousel pocket {}'.format(pocket))
##############################################
@property
def feed_rate(self):
return self._feed_rate
@feed_rate.setter
def feed_rate(self, value):
# negative feedback ?
self._feed_rate = float(value)
@property
def feed_rate_mode(self):
return self._feed_rate_mode
@feed_rate_mode.setter
def feed_rate_mode(self, value):
self._feed_rate_mode = FeedRateMode(value)
##############################################
@property
def spindle_rate(self):
return self._spindle_rate
@spindle_rate.setter
def spindle_rate(self, value):
_value = float(value)
if _value < 0:
raise ValueError('Negative spindle rate {}'.format(value))
self._spindle_rate = _value
####################################################################################################
#
# PythonicGcodeMachine - @licence_header_description@
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
......@@ -54,6 +54,8 @@ __all__ = [
####################################################################################################
from pathlib import Path
# https://rply.readthedocs.io/en/latest/
from ply import yacc
......@@ -186,7 +188,7 @@ class GcodeGrammarMixin:
def p_ordinary_comment(self, p):
'ordinary_comment : INLINE_COMMENT'
p[0] = Ast.Comment(p[1])
p[0] = Ast.Comment(p[1], self._machine)
# def p_message(self, p):
# 'message : left_parenthesis + {white_space} + letter_m + {white_space} + letter_s +
......@@ -197,7 +199,7 @@ class GcodeGrammarMixin:
def p_mid_line_word(self, p):
'mid_line_word : mid_line_letter real_value'
p[0] = Ast.Word(p[1], p[2])
p[0] = Ast.Word(p[1], p[2], self._machine)
def p_mid_line_letter(self, p):
# LETTER
......@@ -226,11 +228,11 @@ class GcodeGrammarMixin:
def p_parameter_setting(self, p):
'parameter_setting : PARAMETER_SIGN parameter_index EQUAL_SIGN real_value'
p[0] = Ast.ParameterSetting(p[2], p[4])
p[0] = Ast.ParameterSetting(p[2], p[4], self._machine)
def p_parameter_value(self, p):
'parameter_value : PARAMETER_SIGN parameter_index'
p[0] = Ast.Parameter(p[2])
p[0] = Ast.Parameter(p[2], self._machine)
def p_parameter_index(self, p):
'parameter_index : real_value'
......@@ -340,12 +342,20 @@ class GcodeParserMixin:
##############################################
def __init__(self):
def __init__(self, machine=None):
self._machine = machine
self._build()
self._reset()
##############################################
@property
def machine(self):
return self._machine
##############################################
def _reset(self):
self._line = None
......@@ -359,8 +369,10 @@ class GcodeParserMixin:
self.tokens = self._lexer.tokens
self._parser = yacc.yacc(
module=self,
# debug=True,
optimize=0,
debug=False,
optimize=1,
tabmodule='_parsetab',
# outputdir=Path(__file__).parent.joinpath('ply'),
)
##############################################
......@@ -374,7 +386,7 @@ class GcodeParserMixin:
line = line.strip()
self._line = Ast.Line()
self._line = Ast.Line(machine=self._machine)
ast = self._parser.parse(
line,
lexer=self._lexer._lexer,
......@@ -395,9 +407,16 @@ class GcodeParserMixin:
Return a :class:`PythonicGcodeMachine.Gcode.Rs274.Ast.Program` instance.
"""
program = Ast.Program()
for line in lines.split('\n'):
program += self.parse(line)
if not isinstance(lines, (list, tuple)):
lines = lines.split('\n')
program = Ast.Program(machine=self._machine)
for line in lines:
try:
program += self.parse(line)
except GcodeParserError as exception:
print('Parse Error:', line)
raise exception
return program
......
####################################################################################################
#
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
"""Module to implement a basic tool set.
"""
####################################################################################################
__all__ = [
'Tool',
'LatheTool',
'ToolSet',
]
####################################################################################################
import yaml
####################################################################################################
class Tool:
"""Class to define a tool"""
##############################################
def __init__(self, tool_id, offset, diameter=None, comment=None):
self._id = tool_id
self._tool_offset = offset
self._tool_diameter = diameter
self._comment = comment
self._tool_set = None
self._pocket = None
self._loaded = False
##############################################
@property
def id(self):
return self._id
@tool_id.setter
def id(self, value):
self._id = str(value)
@property
def offset(self):
return self._offset
@offset.setter
def offset(self, value):
self._offset = value
@property
def diameter(self):
return self._diameter
@diameter.setter
def diameter(self, value):
self._diameter = float(value)
@property
def comment(self):
return self._comment
@comment.setter
def comment(self, value):
self._comment = str(value)
##############################################
@property
def tool_set(self):
return self._tool_set
@tool_set.setter
def tool_set(self, value):
self._tool_set = value
@property
def pocket(self):
return self._pocket
@pocket.setter
def pocket(self, value):
self._pocket = int(value)
##############################################
@property
def loaded(self):
return self._loaded
@loaded.setter
def loaded(self, value):
self._loaded = bool(value)
def toggle_loaded(self):
self._loaded = not self._loaded
return self
##############################################
def _to_dict(self, d, keys):
for key in keys:
d[key] = geattr(self, key)
##############################################
def to_dict(self):
keys = (
'id',
'tool_offset',
'tool_diameter',
'comment',
'pocket',
)
return self._to_dict({}, keys)
####################################################################################################
class LatheTool(Tool):
"""Class to define a lathe tool"""
##############################################
def __init__(self, tool_id, offset, front_angle, back_angle, orientation,
diameter=None, comment=None):
super(). __init__(tool_id, offset, diameter, comment)
self._front_angle = front_angle
self._back_angle = back_angle
self._orientation = orientation
##############################################
@property
def front_angle(self):
return self._front_angle
@front_angle.setter
def front_angle(self, value):
self._front_angle = float(value)
@property
def back_angle(self):
return self._back_angle
@back_angle.setter
def back_angle(self, value):
self._back_angle = float(value)
@property
def orientation(self):
return self._orientation
@orientation.setter
def orientation(self, value):
self._orientation = int(value)
##############################################
def to_dict(self):
d = super().to_dict()
keys = (
'front_angle',
'back_angle',
'orientation',
)
self._to_dict(d, keys)
return d
####################################################################################################
class ToolSet:
"""Class to define a tool set"""
##############################################
def __init__(self):
self._tools = {} # Free pocket implementation
##############################################
def __len__(self):
return len(self._tools)
def __iter__(self):
return iter(self._tools.values())
def __getitem__(self, pocket):
return self._tools[pocket]
##############################################
def remove_tool(self, pocket):
if isinstance(pocket, Tool):
pocket = pocket.pocket
tool = self._tools.pop(pocket)
tool.tool_set = None
tool.pocket = None
return tool
##############################################
def add_tool(self, tool, pocket):
old_tool = self.remove_tool(pocket)
self._tools[pocket] = tool
tool.tool_set = self
tool.pocket = pocket
return old_tool
##############################################
def load_yaml(self, path):
with (open(path, 'r')) as fh:
yaml_data = yaml.load(fh.read())
for pocket, d in yaml_data.items():
if 'front_angle' in d:
cls = LatheTool
else:
cls = Tool
tool = cls(*d)
self.add_tool(tool, pocket)
##############################################
def write_yaml(self, path):
data = {}
for tool in self:
d = tool.to_dict()
del d['pocket']
data[tool.pocket] = d
yaml_data = yaml.dump(data, default_flow_style=False)
with (open(path, 'w')) as fh:
fh.write(yaml_data)
####################################################################################################
#
# PythonicGcodeMachine - @licence_header_description@
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
......@@ -20,370 +20,11 @@
"""Module to implement the G-code language.
.. Note::
Text derived from several sources, like NIST RS-274 paper and Linux CNC project.
cf. supra for references.
History
-------
The G-code language, also called RS-274, is a programming language for numerical control. It was
developed by the EIA in the early 1960s, and finally standardised by ISO in February 1980 as RS274D
/ ISO 6983.
The G-code language has several flavours and historical versions. A list of reference documents
follows :
* `The NIST RS274NGC Interpreter - Version 3, T. Kramer, F. Proctor, E. Messina, National Institute
of Standards and Technology, NISTIR 6556, August 17, 2000
<https://www.nist.gov/publications/nist-rs274ngc-interpreter-version-3>`_
* The documentation of the `Linux CNC <http://linuxcnc.org>`_ project, formerly Enhanced Machine
Controller developed at NIST,
* EIA Standard RS-274-D Interchangeable Variable Block Data Format for Positioning, Contouring, and
Contouring/Positioning Numerically Controlled Machines, 2001 Eye Street, NW, Washington,
D.C. 20006: Electronic Industries Association, February 1979
Overview
--------
The RS274/NGC language is based on lines of code. Each line (also called a “block”) may include
commands to a machining center to do several different things.
A typical line of code consists of an optional line number at the beginning followed by one or more
“words.” A word consists of a letter followed by a number (or something that evaluates to a
number). A word may either give a command or provide an argument to a command. For example,
:code:`G1 X3` is a valid line of code with two words. :code:`G1` is a command meaning “move in a
straight line at the programmed feed rate,” and :code:`X3` provides an argument value (the value of
X should be 3 at the end of the move). Most RS274/NGC commands start with either G or M (for
miscellaneous). The words for these commands are called “G codes” and “M codes.”
Language View of a Machining Center
-----------------------------------
Parameters
~~~~~~~~~~
In the RS274/NGC language view, a machining center maintains an array of 5400 numerical
parameters. Many of them have specific uses. The parameter array should persist over time, even if
the machining center is powered down.
Coordinate Systems
~~~~~~~~~~~~~~~~~~
In the RS274/NGC language view, a machining center has an absolute coordinate system and nine
program coordinate systems.
You can set the offsets of the nine program coordinate systems using G10 L2 Pn (n is the number of
the coordinate system) with values for the axes in terms of the absolute coordinate system.
You can select one of the nine systems by using G54, G55, G56, G57, G58, G59, G59.1, G59.2, or
G59.3. It is not possible to select the absolute coordinate system directly. You can offset the
current coordinate system using G92 or G92.3. This offset will then apply to all nine program
coordinate systems. This offset may be cancelled with G92.1 or G92.2.
You can make straight moves in the absolute machine coordinate system by using G53 with either G0 or
G1.
Data for coordinate systems is stored in parameters.
During initialization, the coordinate system is selected that is specified by parameter 5220. A
value of 1 means the first coordinate system (the one G54 activates), a value of 2 means the second
coordinate system (the one G55 activates), and so on. It is an error for the value of parameter 5220
to be anything but a whole number between one and nine.
Format of a Line
----------------
A permissible line of input RS274/NGC code consists of the following, in order, with the restriction
that there is a maximum (currently 256) to the number of characters allowed on a line.
#. an optional block delete character, which is a slash :code:`/` .
#. an optional line number.
#. any number of words, parameter settings, and comments.
#. an end of line marker (carriage return or line feed or both).
Spaces and tabs are allowed anywhere on a line of code and do not change the meaning of the line,
except inside comments. This makes some strange-looking input legal. The line :code:`g0x +0. 12 34y
7` is equivalent to :code:`g0 x+0.1234 y7`, for example.
Blank lines are allowed in the input. They are to be ignored.
Input is case insensitive, except in comments, i.e., any letter outside a comment may be in upper or
lower case without changing the meaning of a line.
Line Number
~~~~~~~~~~~
A line number is the letter :code:`N` followed by an integer (with no sign) between 0 and 99999
written with no more than five digits (000009 is not OK, for example). Line numbers may be repeated
or used out of order, although normal practice is to avoid such usage. Line numbers may also be
skipped, and that is normal practice. A line number is not required to be used, but must be in the
proper place if used.
Word
~~~~
A word is a letter other than :code:`N` followed by a real value.
Words may begin with any of the letters shown in the following table. The table includes :code:`N`
for completeness, even though, as defined above, line numbers are not words. Several letters
(:code:`I`, :code:`J, K`, :code:`L`, :code:`P`, :code:`R`) may have different meanings in different
contexts.
Table. Linux CNC Words and their meanings Letter
====== =====================================================
Letter Meaning
====== =====================================================
A A axis of machine
B B axis of machine
C C axis of machine
D Tool radius compensation number
F Feed rate
G General function (See table Modal Groups)
H Tool length offset index
I X offset for arcs and G87 canned cycles
J Y offset for arcs and G87 canned cycles
K Z offset for arcs and G87 canned cycles.
Spindle-Motion Ratio for G33 synchronized movements.
L Generic parameter word for G10, M66 and others
M Miscellaneous function (See table Modal Groups)
N Line number
P Dwell time in canned cycles and with G4.
Key used with G10.
Q Feed increment in G73, G83 canned cycles
R Arc radius or canned cycle plane
S Spindle speed
T Tool selection
U U axis of machine
V V axis of machine
W W axis of machine
X X axis of machine
Y Y axis of machine
Z Z axis of machine
====== =====================================================
A real value is some collection of characters that can be processed to come up with a number. A real
value may be an explicit number (such as 341 or -0.8807), a parameter value, an expression, or a
unary operation value.
Number
~~~~~~
The following rules are used for (explicit) numbers. In these rules a digit is a single character
between 0 and 9.
* A number consists of (1) an optional plus or minus sign, followed by (2) zero to many digits,
followed, possibly, by (3) one decimal point, followed by (4) zero to many digits — provided that
there is at least one digit somewhere in the number.
* There are two kinds of numbers: integers and decimals. An integer does not have a decimal point in
it; a decimal does.
* Numbers may have any number of digits, subject to the limitation on line length.
* A non-zero number with no sign as the first character is assumed to be positive. Notice that
initial (before the decimal point and the first non-zero digit) and trailing (after the decimal
point and the last non-zero digit) zeros are allowed but not required. A number written with
initial or trailing zeros will have the same value when it is read as if the extra zeros were not
there.
Parameter Value
~~~~~~~~~~~~~~~
A parameter value is the pound character :code:`#` followed by a real value. The real value must
evaluate to an integer between 1 and 5399. The integer is a parameter number, and the value of the
parameter value is whatever number is stored in the numbered parameter.
The :code:`#` character takes precedence over other operations, so that, for example, :code:`#1+2`
means the number found by adding 2 to the value of parameter 1, not the value found in parameter
3. Of course, :code:`#[1+2]` does mean the value found in parameter 3. The :code:`#` character may
be repeated; for example :code:`##2` means the value of the parameter whose index is the (integer)
value of parameter 2.
Expressions and Binary Operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An expression is a set of characters starting with a left bracket :code:`[` and ending with a
balancing right bracket :code:`]`. In between the brackets are numbers, parameter values,
mathematical operations, and other expressions. An expression may be evaluated to produce a
number. The expressions on a line are evaluated when the line is read, before anything on the line
is executed. An example of an expression is :code:`[ 1 + acos[0] - [#3 ** [4.0/2]]]`.
Binary operations appear only inside expressions. Nine binary operations are defined. There are four
basic mathematical operations: addition :code:`+`, subtraction :code:`-`, multiplication :code:`*`,
and division :code:`/`. There are three logical operations: non-exclusive or :code:`OR`, exclusive
or :code:`XOR`, and logical and :code:`AND`. The eighth operation is the modulus operation
:code:`MOD`. The ninth operation is the “power” operation :code:`**` of raising the number on the
left of the operation to the power on the right. The binary operations are divided into three
groups. The first group is: power. The second group is: multiplication, division, and modulus. The
third group is: addition, subtraction, logical non- exclusive or, logical exclusive or, and logical
and. If operations are strung together (for example in the expression :code:`[2.0 / 3 * 1.5 - 5.5 /
11.0]`), operations in the first group are to be performed before operations in the second group and
operations in the second group before operations in the third group. If an expression contains more
than one operation from the same group (such as the first / and * in the example), the operation on
the left is performed first. Thus, the example is equivalent to: :code:`[((2.0 / 3) * 1.5) - (5.5 /
11.0)]`, which simplifies to :code:`[1.0 - 0.5]`, which is 0.5.
The logical operations and modulus are to be performed on any real numbers, not just on integers.
The number zero is equivalent to logical false, and any non-zero number is equivalent to logical
true.
Unary Operation Value
~~~~~~~~~~~~~~~~~~~~~
A unary operation value is either :code:`ATAN` followed by one expression divided by another
expression (for example :code:`ATAN[2]/[1+3]`) or any other unary operation name followed by an
expression (for example :code:`SIN[90]`). The unary operations are: :code:`ABS` (absolute value),
:code:`ACOS` (arc cosine), :code:`ASIN` (arc sine), :code:`ATAN` (arc tangent), :code:`COS`
(cosine), :code:`EXP` (e raised to the given power), :code:`FIX` (round down), :code:`FUP` (round
up), :code:`LN` (natural logarithm), :code:`ROUND` (round to the nearest whole number), :code:`SIN`
(sine), :code:`SQRT` (square root), and :code:`TAN` (tangent). Arguments to unary operations which
take angle measures (:code:`COS`, :code:`SIN`, and :code:`TAN`) are in degrees. Values returned by
unary operations which return angle measures (:code:`ACOS`, :code:`ASIN`, and :code:`ATAN`) are also
in degrees.
The :code:`FIX` operation rounds towards the left (less positive or more negative) on a number line,
so that :code:`FIX[2.8] = 2` and :code:`FIX[-2.8] = -3`, for example. The :code:`FUP` operation
rounds towards the right (more positive or less negative) on a number line; :code:`FUP[2.8] = 3` and
:code:`FUP[-2.8] = -2`, for example.
Parameter Setting
~~~~~~~~~~~~~~~~~
A parameter setting is the following four items one after the other: (1) a pound character
:code:`#`, (2) a real value which evaluates to an integer between 1 and 5399, (3) an equal sign
:code:`=`, and (4) a real value. For example :code:`#3 = 15` is a parameter setting meaning “set
parameter 3 to 15.”
A parameter setting does not take effect until after all parameter values on the same line have
been found. For example, if parameter 3 has been previously set to 15 and the line :code:`#3=6 G1
x#3` is interpreted, a straight move to a point where x equals 15 will occur and the value of
parameter 3 will be 6.
Comments and Messages
~~~~~~~~~~~~~~~~~~~~~
Printable characters and white space inside parentheses is a comment. A left parenthesis always
starts a comment. The comment ends at the first right parenthesis found thereafter. Once a left
parenthesis is placed on a line, a matching right parenthesis must appear before the end of the
line. Comments may not be nested; it is an error if a left parenthesis is found after the start of
a comment and before the end of the comment. Here is an example of a line containing a comment:
:code:`G80 M5 (stop motion)`. Comments do not cause a machining center to do anything.
.. A comment contains a message if “MSG,” appears after the left parenthesis and before any other
printing characters. Variants of “MSG,” which include white space and lower case characters are
allowed. The rest of the characters before the right parenthesis are considered to be a message.
Messages should be displayed on the message display device. Comments not containing messages need
not be displayed there.
Item Repeats
~~~~~~~~~~~~
A line may have any number of :code:`G` words, but two :code:`G` words from the same modal group may
not appear on the same line.
A line may have zero to four :code:`M` words. Two :code:`M` words from the same modal group may not
appear on the same line.
For all other legal letters, a line may have only one word beginning with that letter.
If a parameter setting of the same parameter is repeated on a line, :code:`#3=15 #3=6`, for example,
only the last setting will take effect. It is silly, but not illegal, to set the same parameter
twice on the same line.
If more than one comment appears on a line, only the last one will be used; each of the other
comments will be read and its format will be checked, but it will be ignored thereafter. It is
expected that putting more than one comment on a line will be very rare.
Item order
~~~~~~~~~~
The three types of item whose order may vary on a line (as given at the beginning of this section)
are word, parameter setting, and comment. Imagine that these three types of item are divided into
three groups by type.
The first group (the words) may be reordered in any way without changing the meaning of the line.
If the second group (the parameter settings) is reordered, there will be no change in the meaning of
the line unless the same parameter is set more than once. In this case, only the last setting of the
parameter will take effect. For example, after the line :code:`#3=15 #3=6` has been interpreted, the
value of parameter 3 will be 6. If the order is reversed to :code:`#3=6 #3=15` and the line is
interpreted, the value of parameter 3 will be 15.
If the third group (the comments) contains more than one comment and is reordered, only the last
comment will be used.
If each group is kept in order or reordered without changing the meaning of the line, then the three
groups may be interleaved in any way without changing the meaning of the line. For example, the line
:code:`g40 g1 #3=15 (foo) #4=-7.0` has five items and means exactly the same thing in any of the 120
possible orders (such as :code:`#4=-7.0 g1 #3=15 g40 (foo)`) for the five items.
Commands and Machine Modes
~~~~~~~~~~~~~~~~~~~~~~~~~~
In RS274/NGC, many commands cause a machining center to change from one mode to another, and the
mode stays active until some other command changes it implicitly or explicitly. Such commands are
called “modal”. For example, if coolant is turned on, it stays on until it is explicitly turned
off. The :code:`G` codes for motion are also modal. If a :code:`G1` (straight move) command is given
on one line, for example, it will be executed again on the next line if one or more axis words is
available on the line, unless an explicit command is given on that next line using the axis words or
cancelling motion.
“Non-modal” codes have effect only on the lines on which they occur. For example, :code:`G4` (dwell)
is non-modal.
Modal Groups
------------
Modal commands are arranged in sets called “modal groups”, and only one member of a modal group may
be in force at any given time. In general, a modal group contains commands for which it is logically
impossible for two members to be in effect at the same time — like measure in inches vs. measure in
millimeters. A machining center may be in many modes at the same time, with one mode from each modal
group being in effect.
.. The modal groups are shown in Table 4.
For several modal groups, when a machining center is ready to accept commands, one member of the
group must be in effect. There are default settings for these modal groups. When the machining
center is turned on or otherwise re-initialized, the default values are automatically in effect.
Group 1, the first group on the table, is a group of :code:`G` codes for motion. One of these is
always in effect. That one is called the current motion mode.
It is an error to put a G-code from group 1 and a G-code from group 0 on the same line if both of
them use axis words. If an axis word-using G-code from group 1 is implicitly in effect on a line (by
having been activated on an earlier line), and a group 0 G-code that uses axis words appears on the
line, the activity of the group 1 G-code is suspended for that line. The axis word-using G-codes
from group 0 are :code:`G10`, :code:`G28`, :code:`G30`, and :code:`G92`.
G and Input Codes
-----------------
See ...
..
G codes of the RS274/NGC language are shown in Table 5 and described following that.
In the command prototypes, three dots (...) stand for a real value. As described earlier, a real
value may be (1) an explicit number, 4, for example, (2) an expression, :code:`[2+2]`, for example,
(3) a parameter value, #88, for example, or (4) a unary function value, :code:`acos[0]`, for
example. In most cases, if axis words (any or all of X..., Y..., Z..., A..., B..., C...) are given,
they specify a destination point. Axis numbers are in the currently active coordinate system, unless
explicitly described as being in the absolute coordinate system. Where axis words are optional, any
omitted axes will have their current value. Any items in the command prototypes not explicitly
described as optional are required. It is an error if a required item is omitted.
In the prototypes, the values following letters are often given as explicit numbers. Unless stated
otherwise, the explicit numbers can be real values. For example, :code:`G10 L2` could equally well
be written :code:`G[2*5] L[1+1]`. If the value of parameter 100 were 2, :code:`G10 L#100` would also
mean the same. Using real values which are not explicit numbers as just shown in the examples is
rarely useful.
If L... is written in a prototype the “...” will often be referred to as the “L number”. Similarly the
“...” in H... may be called the “H number”, and so on for any other letter.
Order of Execution
------------------
See :ref:`rs-274-reference-page` for more details about the RS-274 specification.
"""
The order of execution of items on a line is critical to safe and effective machine operation. Items
are executed in a particular order if they occur on the same line.
####################################################################################################
"""
# from .Config import Config as _Config
# from .Parser import GcodeParser, GcodeParserError
from .Machine import GcodeMachine
#! /usr/bin/env python3
####################################################################################################
#
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
"""Script to generate rST files.
"""
####################################################################################################
import pathlib
from PythonicGcodeMachine.Gcode.Rs274.Machine import GcodeMachine
####################################################################################################
machine = GcodeMachine()
config = machine.config
source_path = pathlib.Path(__file__).absolute().parents[4]
print('Source:', source_path)
rst_path = source_path.joinpath('doc', 'sphinx', 'source', 'gcode-reference', 'rs-274')
print('rST:', rst_path)
config.execution_order.to_rst(rst_path.joinpath('execution_order.rst'))
config.gcodes.to_rst(rst_path.joinpath('gcodes.rst'))
config.letters.to_rst(rst_path.joinpath('letters.rst'))
config.modal_groups.to_rst(rst_path.joinpath('modal_groups.rst'))
config.parameters.to_rst(rst_path.joinpath('parameters.rst'))
#! /usr/bin/env python3
####################################################################################################
#
# PythonicGcodeMachine - A Python G-code Toolkit
# Copyright (C) 2018 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
"""Script to generate YAML files from texts copied from the NIST PDF.
"""
####################################################################################################
import pathlib
......@@ -295,25 +319,18 @@ B-axis of machine
C-axis of machine
tool radius compensation number
feedrate
general function (see Table 5)
general function (See table G codes)
tool length offset index
X-axis offset for arcs
X offset in G87 canned cycle
Y-axis offset for arcs
Y offset in G87 canned cycle
Z-axis offset for arcs
Z offset in G87 canned cycle
number of repetitions in canned cycles
key used with G10
miscellaneous function (see Table 7)
X-axis offset for arcs / X offset in G87 canned cycle
Y-axis offset for arcs / Y offset in G87 canned cycle
Z-axis offset for arcs / Z offset in G87 canned cycle
number of repetitions in canned cycles / key used with G10
miscellaneous function (see Table M codes)
line number
dwell time in canned cycles
dwell time with G4
key used with G10
dwell time in canned cycles / dwell time with G4 / key used with G10
feed increment in G83 canned cycle
arc radius
canned cycle plane
spindle speed
canned cycle plane / spindle speed
tool selection
X-axis of machine
Y-axis of machine
......
# Table 8. Order of Execution
1: COMMENT # (includes message]
2: [G93, G94] # set feed rate mode (inverse time or per minute]
3: F # set feed rate
4: S # set spindle speed
5: T # select tool
6: M6 # change tool
7: [M3, M4, M5] # spindle on or off
8: [M7, M8, M9] # coolant on or off
9: [M48, M49] # enable or disable overrides
10: G4 # dwell
11: [G17, G18, G19] # set active plane
12: [G20, G21] # set length units
13: [G40, G41, G42] # cutter radius compensation on or off
14: [G43, G49] # cutter length compensation on or off
15: [G54, G55, G56, G57, G58, G59, G59.1, G59.2, G59.3] # coordinate system selection
16: [G61, G61.1, G64] # set path control mode
17: [G90, G91] # set distance mode
18: [G98, G99] # set retract mode
19: [G28, G30, G10, G92, G92.1, G92.2, G94] # home or change coordinate system data or set axis offsets
20: ['G0-G3', 'G80-G89', G53] # perform motion, as modified (possibly) by G53
21: [M0, M1, M2, M30, M60] # stop
1:
gcodes: COMMENT
meaning: includes message
2:
gcodes: [G93, G94]
meaning: set feed rate mode (inverse time or per minute)
3:
gcodes: F
meaning: set feed rate
4:
gcodes: S
meaning: set spindle speed
5:
gcodes: T
meaning: select tool
6:
gcodes: M6
meaning: change tool
7:
gcodes: [M3, M4, M5]
meaning: spindle on or off
8:
gcodes: [M7, M8, M9]
meaning: coolant on or off
9:
gcodes: [M48, M49]
meaning: enable or disable overrides
10:
gcodes: G4
meaning: dwell
11:
gcodes: [G17, G18, G19]
meaning: set active plane
12:
gcodes: [G20, G21]
meaning: set length units
13:
gcodes: [G40, G41, G42]
meaning: cutter radius compensation on or off
14:
gcodes: [G43, G49]
meaning: cutter length compensation on or off
15:
gcodes: [G54, G55, G56, G57, G58, G59, G59.1, G59.2, G59.3]
meaning: coordinate system selection
16:
gcodes: [G61, G61.1, G64]
meaning: set path control mode
17:
gcodes: [G90, G91]
meaning: set distance mode
18:
gcodes: [G98, G99]
meaning: set retract mode
19:
gcodes: [G28, G30, G10, G92, G92.1, G92.2, G94]
meaning: home or change coordinate system data or set axis offsets
20:
gcodes: ['G0-G3', 'G80-G89', G53]
meaning: perform motion, as modified (possibly) by G53
21:
gcodes: [M0, M1, M2, M30, M60]
meaning: stop
# Table 4. Modal Groups
# The modal groups for G codes are
1: [G0, G1, G2, G3, G38.2, G80, G81, G82, G83, G84, G85, G86, G87, G88, G89]
2 : [G17, G18, G19] # plane selection
3 : [G90, G91] # distance mode
5 : [G93, G94] # feed rate mode
6 : [G20, G21] # units
7 : [G40, G41, G42] # cutter radius compensation
8 : [G43, G49] # tool length offset
10 : [G98, G99] # return mode in canned cycles
12 : [G54, G55, G56, G57, G58, G59, G59.1, G59.2, G59.3] # coordinate system selection
13 : [G61, G61.1, G64] # path control mode
1:
gcodes: [G0, G1, G2, G3, G38.2, G80, G81, G82, G83, G84, G85, G86, G87, G88, G89]
meaning:
2 :
gcodes: [G17, G18, G19]
meaning: plane selection
3 :
gcodes: [G90, G91]
meaning: distance mode
5 :
gcodes: [G93, G94]
meaning: feed rate mode
6 :
gcodes: [G20, G21]
meaning: units
7 :
gcodes: [G40, G41, G42]
meaning: cutter radius compensation
8 :
gcodes: [G43, G49]
meaning: tool length offset
10 :
gcodes: [G98, G99]
meaning: return mode in canned cycles
12 :
gcodes: [G54, G55, G56, G57, G58, G59, G59.1, G59.2, G59.3]
meaning: coordinate system selection
13 :
gcodes: [G61, G61.1, G64]
meaning: path control mode
# The modal groups for M codes are
4 : [M0, M1, M2, M30, M60] # stopping
6 : [M6] # tool change
7 : [M3, M4, M5] # spindle turning
8 : [M7, M8, M9] # coolant (special case: M7 and M8 may be active at the same time)
9 : [M48, M49] # enable/disable feed and speed override switches
4 :
gcodes: [M0, M1, M2, M30, M60]
meaning: stopping
6 :
gcodes: [M6]
meaning: tool change
7 :
gcodes: [M3, M4, M5]
meaning: spindle turning
8 :
gcodes: [M7, M8, M9]
meaning: 'coolant (special case: M7 and M8 may be active at the same time)'
9 :
gcodes: [M48, M49]
meaning: enable/disable feed and speed override switches
# In addition to the above modal groups, there is a group for non-modal G codes
0 : [G4, G10, G28, G30, G53, G92, G92.1, G92.2, G92.3]
0 :
gcodes: [G4, G10, G28, G30, G53, G92, G92.1, G92.2, G92.3]
meaning: group for non-modal G codes
......@@ -9,34 +9,34 @@ D:
F:
meaning: feedrate
G:
meaning: general function (see Table 5)
meaning: general function (See table G codes)
H:
meaning: tool length offset index
I:
meaning: X-axis offset for arcs
meaning: X-axis offset for arcs / X offset in G87 canned cycle
J:
meaning: X offset in G87 canned cycle
meaning: Y-axis offset for arcs / Y offset in G87 canned cycle
K:
meaning: Y-axis offset for arcs
meaning: Z-axis offset for arcs / Z offset in G87 canned cycle
L:
meaning: Y offset in G87 canned cycle
meaning: number of repetitions in canned cycles / key used with G10
M:
meaning: Z-axis offset for arcs
meaning: miscellaneous function (see Table M codes)
N:
meaning: Z offset in G87 canned cycle
meaning: line number
P:
meaning: number of repetitions in canned cycles
meaning: dwell time in canned cycles / dwell time with G4 / key used with G10
Q:
meaning: key used with G10
meaning: feed increment in G83 canned cycle
R:
meaning: miscellaneous function (see Table 7)
meaning: arc radius
S:
meaning: line number
meaning: canned cycle plane / spindle speed
T:
meaning: dwell time in canned cycles
meaning: tool selection
X:
meaning: dwell time with G4
meaning: X-axis of machine
Y:
meaning: key used with G10
meaning: Y-axis of machine
Z:
meaning: feed increment in G83 canned cycle
meaning: Z-axis of machine
This directory contains PLY code, should be removed in future.
......@@ -4,7 +4,7 @@
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.14: http://docutils.sourceforge.net/" />
<title>The Pythonic Gcode Machine</title>
<title>The Pythonic G-code Machine</title>
<style type="text/css">
/*
......@@ -360,8 +360,8 @@ ul.auto-toc {
</style>
</head>
<body>
<div class="document" id="the-pythonic-gcode-machine">
<h1 class="title">The Pythonic Gcode Machine</h1>
<div class="document" id="the-pythonic-g-code-machine">
<h1 class="title">The Pythonic G-code Machine</h1>
<!-- -*- Mode: rst -*- -->
<!-- -*- Mode: rst -*- -->
......@@ -391,6 +391,23 @@ ul.auto-toc {
<h2>What is PythonicGcodeMachine ?</h2>
<!-- free and open source -->
<p>PythonicGcodeMachine is a Python toolkit to work with RS-274 / ISO G-Code.</p>
<!-- -*- mode: rst -*- -->
<p>PythonicGcodeMachine features:</p>
<ul class="simple">
<li>a compliant RS-274 / ISO G-code parser which is automatically generated from grammar and easy to
derivate to support other flavours,</li>
<li>an abstract syntax tree (AST) API,</li>
<li>some G-code flavour aspects are handled by YAML files for maximum flexibility,</li>
<li>tools to manipulate and validate G-code,</li>
<li>and more ..</li>
</ul>
<p>PythonicGcodeMachine supports these G-code flavours:</p>
<ul class="simple">
<li>RS-274 <strong>(full support)</strong></li>
<li>Fanuc <em>(partially)</em></li>
<li>Heidenhain <em>(partially)</em></li>
<li>LinuxCNC <em>(partially)</em></li>
</ul>
</div>
<div class="section" id="where-is-the-documentation">
<h2>Where is the Documentation ?</h2>
......
......@@ -79,9 +79,9 @@
.. |YAML| replace:: YAML
.. _YAML: https://yaml.org
============================
The Pythonic Gcode Machine
============================
=============================
The Pythonic G-code Machine
=============================
|Pypi License|
|Pypi Python Version|
......@@ -101,6 +101,24 @@ What is PythonicGcodeMachine ?
PythonicGcodeMachine is a Python toolkit to work with RS-274 / ISO G-Code.
.. -*- mode: rst -*-
PythonicGcodeMachine features:
* a compliant RS-274 / ISO G-code parser which is automatically generated from grammar and easy to
derivate to support other flavours,
* an abstract syntax tree (AST) API,
* some G-code flavour aspects are handled by YAML files for maximum flexibility,
* tools to manipulate and validate G-code,
* and more ..
PythonicGcodeMachine supports these G-code flavours:
* RS-274 **(full support)**
* Fanuc *(partially)*
* Heidenhain *(partially)*
* LinuxCNC *(partially)*
Where is the Documentation ?
----------------------------
......
......@@ -3,9 +3,9 @@
.. include:: project-links.txt
.. include:: abbreviation.txt
============================
The Pythonic Gcode Machine
============================
=============================
The Pythonic G-code Machine
=============================
|Pypi License|
|Pypi Python Version|
......@@ -25,6 +25,8 @@ What is PythonicGcodeMachine ?
PythonicGcodeMachine is a Python toolkit to work with RS-274 / ISO G-Code.
.. include:: features.txt
Where is the Documentation ?
----------------------------
......