diff --git a/config/example-extras.cfg b/config/example-extras.cfg index dd2c3b3f..b849b4c2 100644 --- a/config/example-extras.cfg +++ b/config/example-extras.cfg @@ -582,6 +582,14 @@ # measurements must be provided. +# G-Code macros (one may define any number of sections with a +# "gcode_macro" prefix). +#[gcode_macro my_cmd] +#gcode: +# A list of G-Code commands (one per line) to execute in place of +# "my_cmd". This parameter must be provided. + + # Replicape support - see the generic-replicape.cfg file for further # details. #[replicape] diff --git a/klippy/extras/gcode_macro.py b/klippy/extras/gcode_macro.py new file mode 100644 index 00000000..08ad3b74 --- /dev/null +++ b/klippy/extras/gcode_macro.py @@ -0,0 +1,29 @@ +# Add ability to define custom g-code macros +# +# Copyright (C) 2018 Kevin O'Connor +# +# This file may be distributed under the terms of the GNU GPLv3 license. + +class GCodeMacro: + def __init__(self, config): + self.alias = config.get_name().split()[1].upper() + self.script = config.get('gcode') + printer = config.get_printer() + self.gcode = printer.lookup_object('gcode') + try: + self.gcode.register_command(self.alias, self.cmd, desc=self.cmd_desc) + except self.gcode.error as e: + raise config.error(str(e)) + self.in_script = False + cmd_desc = "G-Code macro" + def cmd(self, params): + if self.in_script: + raise self.gcode.error("Macro %s called recursively" % (self.alias,)) + self.in_script = True + try: + self.gcode.run_script(self.script) + finally: + self.in_script = False + +def load_config_prefix(config): + return GCodeMacro(config)