2018-05-25 18:33:01 +02:00
|
|
|
# Add ability to define custom g-code macros
|
|
|
|
#
|
|
|
|
# Copyright (C) 2018 Kevin O'Connor <kevin@koconnor.net>
|
|
|
|
#
|
|
|
|
# This file may be distributed under the terms of the GNU GPLv3 license.
|
2018-09-30 18:32:13 +02:00
|
|
|
import traceback, logging
|
2018-05-25 18:33:01 +02:00
|
|
|
|
2018-09-27 18:08:01 +02:00
|
|
|
DEFAULT_PREFIX = 'default_parameter_'
|
|
|
|
|
2018-05-25 18:33:01 +02:00
|
|
|
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')
|
2019-02-19 00:04:42 +01:00
|
|
|
self.gcode.register_command(self.alias, self.cmd, desc=self.cmd_desc)
|
2018-05-25 18:33:01 +02:00
|
|
|
self.in_script = False
|
2018-09-27 18:08:01 +02:00
|
|
|
self.kwparams = { o[len(DEFAULT_PREFIX):].upper(): config.get(o)
|
|
|
|
for o in config.get_prefix_options(DEFAULT_PREFIX) }
|
2018-05-25 18:33:01 +02:00
|
|
|
cmd_desc = "G-Code macro"
|
|
|
|
def cmd(self, params):
|
|
|
|
if self.in_script:
|
2018-09-26 07:23:45 +02:00
|
|
|
raise self.gcode.error(
|
|
|
|
"Macro %s called recursively" % (self.alias,))
|
2018-09-26 07:19:54 +02:00
|
|
|
script = ""
|
2018-09-27 18:08:01 +02:00
|
|
|
kwparams = dict(self.kwparams)
|
|
|
|
kwparams.update(params)
|
2018-09-26 07:19:54 +02:00
|
|
|
try:
|
2018-09-27 18:08:01 +02:00
|
|
|
script = self.script.format(**kwparams)
|
2018-09-30 18:32:13 +02:00
|
|
|
except Exception as e:
|
|
|
|
msg = "Error evaluating %s: %s" % (
|
|
|
|
self.alias, traceback.format_exception_only(type(e), e)[-1])
|
2018-09-26 07:19:54 +02:00
|
|
|
logging.exception(msg)
|
|
|
|
raise self.gcode.error(msg)
|
2018-05-25 18:33:01 +02:00
|
|
|
self.in_script = True
|
|
|
|
try:
|
2018-09-26 07:19:54 +02:00
|
|
|
self.gcode.run_script_from_command(script)
|
2018-05-25 18:33:01 +02:00
|
|
|
finally:
|
|
|
|
self.in_script = False
|
|
|
|
|
|
|
|
def load_config_prefix(config):
|
|
|
|
return GCodeMacro(config)
|