Allow tagging of GCODE commands throughout their lifecycle

Commands injected/extended/rewritten through one of the phase hooks or
sent by a plugin through self._printer.commands will also be tagged with
"plugin:<plugin identifier>", allowing other code to detect these tags
and handle such commands differently.

That will be interesting for plugins that need to differentiate between
commands originating from the printed file vs the user vs the system vs
other plugins.
This commit is contained in:
Gina Häußge committed 2018-02-16 18:41:17 +01:00
1 parent 1587ee6402
commit 00e6a3856f
8 files changed
+491 -251

No files matched your search

+38 -3
View File
@@ -420,7 +420,7 @@ This describes actually four hooks:
* ``octoprint.comm.protocol.gcode.sending``
* ``octoprint.comm.protocol.gcode.sent``
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs)
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs)
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
are the following:
@@ -443,7 +443,39 @@ This describes actually four hooks:
the communication layer or before they are actually sent over the serial port, or to react to the queuing or sending
of commands after the fact. The hook handler will be called with the processing ``phase``, the ``cmd`` to be sent to
the printer as well as the ``cmd_type`` parameter used for enqueuing (OctoPrint will make sure that the send queue
will never contain more than one line with the same ``cmd_type``) and the detected gcode command (if it is one).
will never contain more than one line with the same ``cmd_type``) and the detected ``gcode`` command (if it is one)
as well as its ``subcode`` (if it has one). OctoPrint will also provide any ``tags`` attached to the command throughout
its lifecycle.
Tags are arbitrary strings that can be attached to a command as it moves through the various phases and can be used to e.g.
distinguish between commands that originated in a printed file (``source:file``) vs. a configured GCODE script
(``source:script``) vs. an API call (``source:api``) vs. a plugin (``source:plugin`` or ``source:rewrite`` and
``plugin:<plugin identifier>``). If during development you want to get an idea of the various possible tags, set
the logger ``octoprint.util.comm.command_phases`` to ``DEBUG``, connect to a printer (real or virtual) and take a
look at your ``octoprint.log`` during serial traffic:
.. code-block:: plain
2018-02-16 18:20:31,213 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
2018-02-16 18:20:31,216 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
2018-02-16 18:20:31,217 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
2018-02-16 18:20:31,217 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
2018-02-16 18:20:31,219 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
2018-02-16 18:20:31,220 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
2018-02-16 18:20:31,230 - tornado.access - INFO - 204 POST /api/printer/command (127.0.0.1) 23.00ms
2018-02-16 18:20:31,232 - tornado.access - INFO - 200 POST /api/printer/command (127.0.0.1) 25.00ms
2018-02-16 18:20:31,232 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
2018-02-16 18:20:31,234 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
2018-02-16 18:20:31,242 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
2018-02-16 18:20:31,243 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
2018-02-16 18:20:38,552 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
2018-02-16 18:20:38,552 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
2018-02-16 18:20:38,553 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
2018-02-16 18:20:38,553 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G1 X10 F6000 | gcode: G1 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
2018-02-16 18:20:38,555 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G1 X10 F6000 | gcode: G1 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
2018-02-16 18:20:38,556 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
2018-02-16 18:20:38,556 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G90 | gcode: G90 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
2018-02-16 18:20:38,558 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G90 | gcode: G90 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
Defining a ``cmd_type`` other than None will make sure OctoPrint takes care of only having one command of that type
in its sending queue. Predefined types are ``temperature_poll`` for temperature polling via ``M105`` and
@@ -482,6 +514,8 @@ This describes actually four hooks:
should use this option.
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
Handlers which wish to rewrite both the command and the command type should use this option.
* A 3-tuple consisting of a rewritten version of the ``cmd``, the ``cmd_type`` and any additional ``tags`` you might
want to attach to the lifecycle of the command, e.g. ``return "M105", "temperature_poll", "my_custom_tag"
* **"queuing" phase only**: A list of any of the above to allow for expanding one command into
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
@@ -489,7 +523,7 @@ This describes actually four hooks:
.. code-block:: python
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None *args, **kwargs):
if gcode or not cmd.startswith("@foo"):
return
@@ -524,6 +558,7 @@ This describes actually four hooks:
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
:param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided
or no command could be parsed.
:param set tags: Tags attached to the
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
.. _sec-plugins-hook-comm-protocol-gcode-received:
+67 -41
View File
@@ -51,7 +51,7 @@ class PrinterInterface(object):
"""Regex for valid heater identifiers."""
@classmethod
def get_connection_options(cls):
def get_connection_options(cls, *args, **kwargs):
"""
Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer.
@@ -75,7 +75,7 @@ class PrinterInterface(object):
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
def connect(self, port=None, baudrate=None, profile=None):
def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs):
"""
Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a
connection is already established, that connection will be closed prior to connecting anew with the provided
@@ -89,13 +89,13 @@ class PrinterInterface(object):
"""
pass
def disconnect(self):
def disconnect(self, *args, **kwargs):
"""
Disconnects from the printer. Does nothing if no connection is currently established.
"""
raise NotImplementedError()
def get_transport(self):
def get_transport(self, *args, **kwargs):
"""
Returns the communication layer's transport object, if a connection is currently established.
@@ -107,7 +107,7 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def fake_ack(self):
def fake_ack(self, *args, **kwargs):
"""
Fakes an acknowledgment for the communication layer. If the communication between OctoPrint and the printer
gets stuck due to lost "ok" responses from the server due to communication issues, this can be used to get
@@ -115,17 +115,18 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def commands(self, commands):
def commands(self, commands, tags=None, *args, **kwargs):
"""
Sends the provided ``commands`` to the printer.
Arguments:
commands (str, list): The commands to send. Might be a single command provided just as a string or a list
of multiple commands to send in order.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def script(self, name, context=None):
def script(self, name, context=None, tags=None, *args, **kwargs):
"""
Sends the GCODE script ``name`` to the printer.
@@ -137,13 +138,14 @@ class PrinterInterface(object):
Arguments:
name (str): The name of the GCODE script to render.
context (dict): An optional context of additional template variables to provide to the renderer.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
Raises:
UnknownScriptException: There is no GCODE script with name ``name``
"""
raise NotImplementedError()
def jog(self, axes, relative=True, speed=None, *args, **kwargs):
def jog(self, axes, relative=True, speed=None, tags=None, *args, **kwargs):
"""
Jogs the specified printer ``axis`` by the specified ``amount`` in mm.
@@ -154,38 +156,42 @@ class PrinterInterface(object):
speed (int, bool or None): Speed at which to jog (F parameter). If set to ``False`` no speed will be set
specifically. If set to ``None`` (or left out) the minimum of all involved axes speeds from the printer
profile will be used.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def home(self, axes):
def home(self, axes, tags=None, *args, **kwargs):
"""
Homes the specified printer ``axes``.
Arguments:
axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of
"x", "y", "z" and "e"
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def extrude(self, amount):
def extrude(self, amount, tags=None, *args, **kwargs):
"""
Extrude ``amount`` millimeters of material from the tool.
Arguments:
amount (int, float): The amount of material to extrude in mm
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def change_tool(self, tool):
def change_tool(self, tool, tags=None, *args, **kwargs):
"""
Switch the currently active ``tool`` (for which extrude commands will apply).
Arguments:
tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...)
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def set_temperature(self, heater, value):
def set_temperature(self, heater, value, tags=None, *args, **kwargs):
"""
Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius.
@@ -194,10 +200,11 @@ class PrinterInterface(object):
temperature or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for
the hotends of the printer
value (int, float): The temperature in celsius to set the target temperature to.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def set_temperature_offset(self, offsets=None):
def set_temperature_offset(self, offsets=None, tags=None, *args, **kwargs):
"""
Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing.
@@ -205,30 +212,33 @@ class PrinterInterface(object):
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and
"tool[0-9]+" for the offsets to the hotend target temperatures.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def feed_rate(self, factor):
def feed_rate(self, factor, tags=None, *args, **kwargs):
"""
Sets the ``factor`` for the printer's feed rate.
Arguments:
factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an
int between 0 and 100 or a float between 0 and 1.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def flow_rate(self, factor):
def flow_rate(self, factor, tags=None, *args, **kwargs):
"""
Sets the ``factor`` for the printer's flow rate.
Arguments:
factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an
int between 0 and 100 or a float between 0 and 1.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def can_modify_file(self, path, sd):
def can_modify_file(self, path, sd, *args, **kwargs):
"""
Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted)
or not.
@@ -254,7 +264,7 @@ class PrinterInterface(object):
"""
return not (self.is_current_file(path, sd) and (self.is_printing() or self.is_paused()))
def is_current_file(self, path, sd):
def is_current_file(self, path, sd, *args, **kwargs):
"""
Returns whether the provided ``path`` (on the printer's SD if ``sd`` is True) is the currently selected
file for printing.
@@ -286,7 +296,7 @@ class PrinterInterface(object):
return False
def select_file(self, path, sd, printAfterSelect=False, pos=None):
def select_file(self, path, sd, printAfterSelect=False, pos=None, tags=None, *args, **kwargs):
"""
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
Optionally can also directly start the print after selecting the file.
@@ -297,6 +307,7 @@ class PrinterInterface(object):
sd (boolean): Indicates whether the file is on the printer's SD card or not.
printAfterSelect (boolean): Indicates whether a print should be started
after the file is selected.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
Raises:
InvalidFileType: if the file is not a machinecode file and hence cannot be printed
@@ -305,53 +316,68 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def unselect_file(self):
def unselect_file(self, *args, **kwargs):
"""
Unselects and currently selected file.
"""
raise NotImplementedError()
def start_print(self):
def start_print(self, tags=None, *args, **kwargs):
"""
Starts printing the currently selected file. If no file is currently selected, does nothing.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def pause_print(self):
def pause_print(self, tags=None, *args, **kwargs):
"""
Pauses the current print job if it is currently running, does nothing otherwise.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def resume_print(self):
def resume_print(self, tags=None, *args, **kwargs):
"""
Resumes the current print job if it is currently paused, does nothing otherwise.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def toggle_pause_print(self):
def toggle_pause_print(self, tags=None, *args, **kwargs):
"""
Pauses the current print job if it is currently running or resumes it if it is currently paused.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
if self.is_printing():
self.pause_print()
self.pause_print(tags=tags)
elif self.is_paused():
self.resume_print()
self.resume_print(tags=tags)
def cancel_print(self):
def cancel_print(self, tags=None, *args, **kwargs):
"""
Cancels the current print job.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def get_state_string(self):
def get_state_string(self, *args, **kwargs):
"""
Returns:
(str) A human readable string corresponding to the current communication state.
"""
raise NotImplementedError()
def get_state_id(self):
def get_state_id(self, *args, **kwargs):
"""
Identifier of the current communication state.
@@ -376,35 +402,35 @@ class PrinterInterface(object):
(str) A unique identifier corresponding to the current communication state.
"""
def get_current_data(self):
def get_current_data(self, *args, **kwargs):
"""
Returns:
(dict) The current state data.
"""
raise NotImplementedError()
def get_current_job(self):
def get_current_job(self, *args, **kwargs):
"""
Returns:
(dict) The data of the current job.
"""
raise NotImplementedError()
def get_current_temperatures(self):
def get_current_temperatures(self, *args, **kwargs):
"""
Returns:
(dict) The current temperatures.
"""
raise NotImplementedError()
def get_temperature_history(self):
def get_temperature_history(self, *args, **kwargs):
"""
Returns:
(list) The temperature history.
"""
raise NotImplementedError()
def get_current_connection(self):
def get_current_connection(self, *args, **kwargs):
"""
Returns:
(tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``.
@@ -412,49 +438,49 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def is_closed_or_error(self):
def is_closed_or_error(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently disconnected and/or in an error state.
"""
raise NotImplementedError()
def is_operational(self):
def is_operational(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently connected and available.
"""
raise NotImplementedError()
def is_printing(self):
def is_printing(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently printing.
"""
raise NotImplementedError()
def is_paused(self):
def is_paused(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently paused.
"""
raise NotImplementedError()
def is_error(self):
def is_error(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently in an error state.
"""
raise NotImplementedError()
def is_ready(self):
def is_ready(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently operational and ready for new print jobs (not printing).
"""
raise NotImplementedError()
def register_callback(self, callback):
def register_callback(self, callback, *args, **kwargs):
"""
Registers a :class:`PrinterCallback` with the instance.
@@ -463,7 +489,7 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def unregister_callback(self, callback):
def unregister_callback(self, callback, *args, **kwargs):
"""
Unregisters a :class:`PrinterCallback` from the instance.
+76 -63
View File
@@ -126,14 +126,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#~~ handling of PrinterCallbacks
def register_callback(self, callback):
def register_callback(self, callback, *args, **kwargs):
if not isinstance(callback, PrinterCallback):
self._logger.warn("Registering an object as printer callback which doesn't implement the PrinterCallback interface")
self._callbacks.append(callback)
self._sendInitialStateUpdate(callback)
def unregister_callback(self, callback):
def unregister_callback(self, callback, *args, **kwargs):
if callback in self._callbacks:
self._callbacks.remove(callback)
@@ -196,7 +196,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#~~ PrinterInterface implementation
def connect(self, port=None, baudrate=None, profile=None):
def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs):
"""
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
will be attempted.
@@ -215,7 +215,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
def disconnect(self):
def disconnect(self, *args, **kwargs):
"""
Closes the connection to the printer.
"""
@@ -225,7 +225,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
eventManager().fire(Events.DISCONNECTED)
def get_transport(self):
def get_transport(self, *args, **kwargs):
if self._comm is None:
return None
@@ -233,13 +233,13 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm.getTransport()
getTransport = util.deprecated("getTransport has been renamed to get_transport", since="1.2.0-dev-590", includedoc="Replaced by :func:`get_transport`")
def fake_ack(self):
def fake_ack(self, *args, **kwargs):
if self._comm is None:
return
self._comm.fakeOk()
def commands(self, commands):
def commands(self, commands, *args, **kwargs):
"""
Sends one or more gcode commands to the printer.
"""
@@ -250,16 +250,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
commands = [commands]
for command in commands:
self._comm.sendCommand(command)
self._comm.sendCommand(command, tags=kwargs.get("tags", set()) | {"trigger:printer.commands"})
def script(self, name, context=None, must_be_set=True):
def script(self, name, context=None, must_be_set=True, *args, **kwargs):
if self._comm is None:
return
if name is None or not name:
raise ValueError("name must be set")
result = self._comm.sendGcodeScript(name, replacements=context)
result = self._comm.sendGcodeScript(name,
replacements=context,
tags=kwargs.get("tags", set()) | {"trigger:printer.script"})
if not result and must_be_set:
raise UnknownScript(name)
@@ -298,9 +300,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
commands = ["G90", command]
self.commands(commands)
self.commands(commands, tags=kwargs.get("tags", set()) | {"trigger:printer.jog"})
def home(self, axes):
def home(self, axes, *args, **kwargs):
if not isinstance(axes, (list, tuple)):
if isinstance(axes, (str, unicode)):
axes = [axes]
@@ -311,24 +313,26 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if len(axes) != len(validated_axes):
raise ValueError("axes contains invalid axes: {axes}".format(axes=axes))
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"])
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"],
tags=kwargs.get("tags", set) | {"trigger:printer.home"})
def extrude(self, amount):
def extrude(self, amount, *args, **kwargs):
if not isinstance(amount, (int, long, float)):
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
printer_profile = self._printerProfileManager.get_current_or_default()
extrusion_speed = printer_profile["axes"]["e"]["speed"]
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"])
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"],
tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"})
def change_tool(self, tool):
def change_tool(self, tool, *args, **kwargs):
if not PrinterInterface.valid_tool_regex.match(tool):
raise ValueError("tool must match \"tool[0-9]+\": {tool}".format(tool=tool))
tool_num = int(tool[len("tool"):])
self.commands("T%d" % tool_num)
self.commands("T%d" % tool_num, tags=kwargs.get("tags", set()) | {"trigger:printer.change_tool"})
def set_temperature(self, heater, value):
def set_temperature(self, heater, value, *args, **kwargs):
if not PrinterInterface.valid_heater_regex.match(heater):
raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(heater=heater))
@@ -341,14 +345,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
shared_nozzle = printer_profile["extruder"]["sharedNozzle"]
if extruder_count > 1 and not shared_nozzle:
toolNum = int(heater[len("tool"):])
self.commands("M104 T{} S{}".format(toolNum, value))
self.commands("M104 T{} S{}".format(toolNum, value),
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
else:
self.commands("M104 S{}".format(value))
self.commands("M104 S{}".format(value),
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
elif heater == "bed":
self.commands("M140 S{}".format(value))
self.commands("M140 S{}".format(value),
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
def set_temperature_offset(self, offsets=None):
def set_temperature_offset(self, offsets=None, *args, **kwargs):
if offsets is None:
offsets = dict()
@@ -381,15 +388,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return factor
def feed_rate(self, factor):
def feed_rate(self, factor, *args, **kwargs):
factor = self._convert_rate_value(factor, min=50, max=200)
self.commands("M220 S%d" % factor)
self.commands("M220 S%d" % factor,
tags=kwargs.get("tags", set()) | {"trigger:printer.feed_rate"})
def flow_rate(self, factor):
def flow_rate(self, factor, *args, **kwargs):
factor = self._convert_rate_value(factor, min=75, max=125)
self.commands("M221 S%d" % factor)
self.commands("M221 S%d" % factor,
tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"})
def select_file(self, path, sd, printAfterSelect=False, pos=None):
def select_file(self, path, sd, printAfterSelect=False, pos=None, *args, **kwargs):
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
self._logger.info("Cannot load file: printer not connected or currently busy")
return
@@ -408,11 +417,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd else path, sd)
self._comm.selectFile("/" + path if sd else path, sd,
tags=kwargs.get("tags", set()) | {"trigger:printer.select_file"})
self._updateProgressData()
self._setCurrentZ(None)
def unselect_file(self):
def unselect_file(self, *args, **kwargs):
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
return
@@ -430,7 +440,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm.getFilePosition()
def start_print(self, pos=None):
def start_print(self, pos=None, *args, **kwargs):
"""
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
@@ -463,9 +473,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._lastProgressReport = None
self._updateProgressData()
self._setCurrentZ(None)
self._comm.startPrint(pos=pos)
self._comm.startPrint(pos=pos,
tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"})
def pause_print(self):
def pause_print(self, *args, **kwargs):
"""
Pause the current printjob.
"""
@@ -475,9 +486,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm.isPaused():
return
self._comm.setPause(True)
self._comm.setPause(True, tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"})
def resume_print(self):
def resume_print(self, *args, **kwargs):
"""
Resume the current printjob.
"""
@@ -487,9 +498,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not self._comm.isPaused():
return
self._comm.setPause(False)
self._comm.setPause(False, tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"})
def cancel_print(self):
def cancel_print(self, *args, **kwargs):
"""
Cancel the current printjob.
"""
@@ -498,28 +509,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# tell comm layer to cancel - will also trigger our cancelled handler
# for further processing
self._comm.cancelPrint()
self._comm.cancelPrint(tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"})
def get_state_string(self, state=None):
def get_state_string(self, state=None, *args, **kwargs):
if self._comm is None:
return "Offline"
else:
return self._comm.getStateString(state=state)
def get_state_id(self, state=None):
def get_state_id(self, state=None, *args, **kwargs):
if self._comm is None:
return "OFFLINE"
else:
return self._comm.getStateId(state=state)
def get_current_data(self):
def get_current_data(self, *args, **kwargs):
return self._stateMonitor.get_current_data()
def get_current_job(self):
def get_current_job(self, *args, **kwargs):
currentData = self._stateMonitor.get_current_data()
return currentData["job"]
def get_current_temperatures(self):
def get_current_temperatures(self, *args, **kwargs):
if self._comm is not None:
offsets = self._comm.getOffsets()
else:
@@ -542,10 +553,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return result
def get_temperature_history(self):
def get_temperature_history(self, *args, **kwargs):
return self._temps
def get_current_connection(self):
def get_current_connection(self, *args, **kwargs):
if self._comm is None:
return "Closed", None, None, None
@@ -553,25 +564,25 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printer_profile = self._printerProfileManager.get_current_or_default()
return self._comm.getStateString(), port, baudrate, printer_profile
def is_closed_or_error(self):
def is_closed_or_error(self, *args, **kwargs):
return self._comm is None or self._comm.isClosedOrError()
def is_operational(self):
def is_operational(self, *args, **kwargs):
return self._comm is not None and self._comm.isOperational()
def is_printing(self):
def is_printing(self, *args, **kwargs):
return self._comm is not None and self._comm.isPrinting()
def is_paused(self):
def is_paused(self, *args, **kwargs):
return self._comm is not None and self._comm.isPaused()
def is_error(self):
def is_error(self, *args, **kwargs):
return self._comm is not None and self._comm.isError()
def is_ready(self):
def is_ready(self, *args, **kwargs):
return self.is_operational() and not self.is_printing() and not self._comm.isStreaming()
def is_sd_ready(self):
def is_sd_ready(self, *args, **kwargs):
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
return False
else:
@@ -579,12 +590,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#~~ sd file handling
def get_sd_files(self):
def get_sd_files(self, *args, **kwargs):
if self._comm is None or not self._comm.isSdReady():
return []
return map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles())
def add_sd_file(self, filename, absolutePath, on_success=None, on_failure=None):
def add_sd_file(self, filename, absolutePath, on_success=None, on_failure=None, *args, **kwargs):
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
self._logger.error("No connection to printer or printer is busy")
return
@@ -604,26 +615,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# probably something else added through a plugin, use it's basename as-is
remoteName = os.path.basename(filename)
self._timeEstimationData = TimeEstimationHelper()
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName, special=not valid_file_type(filename, "gcode"))
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName,
special=not valid_file_type(filename, "gcode"),
tags=kwargs.get("tags", set()) | {"trigger:printer.add_sd_file"})
return remoteName
def delete_sd_file(self, filename):
def delete_sd_file(self, filename, *args, **kwargs):
if not self._comm or not self._comm.isSdReady():
return
self._comm.deleteSdFile("/" + filename)
self._comm.deleteSdFile("/" + filename, tags=kwargs.get("tags", set()) | {"trigger:printer.delete_sd_file"})
def init_sd_card(self):
def init_sd_card(self, *args, **kwargs):
if not self._comm or self._comm.isSdReady():
return
self._comm.initSdCard()
self._comm.initSdCard(tags=kwargs.get("tags", set()) | {"trigger:printer.init_sd_card"})
def release_sd_card(self):
def release_sd_card(self, *args, **kwargs):
if not self._comm or not self._comm.isSdReady():
return
self._comm.releaseSdCard()
self._comm.releaseSdCard(tags=kwargs.get("tags", set()) | {"trigger:printer.release_sd_card"})
def refresh_sd_files(self, blocking=False):
def refresh_sd_files(self, blocking=False, *args, **kwargs):
"""
Refreshes the list of file stored on the SD card attached to printer (if available and printer communication
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
@@ -632,9 +645,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not self._comm or not self._comm.isSdReady():
return
self._sdFilelistAvailable.clear()
self._comm.refreshSdFiles()
self._comm.refreshSdFiles(tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"})
if blocking:
self._sdFilelistAvailable.wait(10000)
self._sdFilelistAvailable.wait(kwargs.get("timeout", 10000))
#~~ state monitoring
+30 -1
View File
@@ -350,8 +350,37 @@ class Server(object):
"""Factory for injections for all OctoPrintPlugins"""
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
return None
components_copy = dict(components)
if "printer" in components:
import wrapt
import functools
def tagwrap(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
tags = kwargs.get("tags", set()) | {"source:plugin",
"plugin:{}".format(name)}
kwargs["tags"] = tags
return f(*args, **kwargs)
setattr(wrapper, "__tagwrapped__", True)
return wrapper
class TaggedFuncsPrinter(wrapt.ObjectProxy):
def __getattribute__(self, attr):
__wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__("__wrapped__")
item = getattr(__wrapped__, attr)
if callable(item) \
and ("tags" in item.__code__.co_varnames or "kwargs" in item.__code__.co_varnames) \
and not getattr(item, "__tagwrapped__", False):
return tagwrap(item)
else:
return item
components_copy["printer"] = TaggedFuncsPrinter(components["printer"])
props = dict()
props.update(components)
props.update(components_copy)
props.update(dict(
data_folder=os.path.join(self._settings.getBaseFolder("data"), name)
))
+2 -2
View File
@@ -325,7 +325,7 @@ def uploadGcodeFile(target):
"""
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode"):
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint)
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint, tags={"source:api", "api:files.sd"})
else:
selectAndOrPrint(filename, absFilename, destination)
return filename
@@ -743,7 +743,7 @@ def deleteGcodeFile(filename, target):
# delete it
if target == FileDestinations.SDCARD:
printer.delete_sd_file(filename)
printer.delete_sd_file(filename, tags={"source:api", "api:files.sd"})
else:
fileManager.remove_file(target, filename)
+8 -6
View File
@@ -32,30 +32,32 @@ def controlJob():
activePrintjob = printer.is_printing() or printer.is_paused()
tags = {"source:api", "api:job"}
if command == "start":
if activePrintjob:
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
printer.start_print()
printer.start_print(tags=tags)
elif command == "restart":
if not printer.is_paused():
return make_response("Printer does not have an active print job or is not paused", 409)
printer.start_print()
printer.start_print(tags=tags)
elif command == "pause":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
action = data.get("action", "toggle")
if action == "toggle":
printer.toggle_pause_print()
printer.toggle_pause_print(tags=tags)
elif action == "pause":
printer.pause_print()
printer.pause_print(tags=tags)
elif action == "resume":
printer.resume_print()
printer.resume_print(tags=tags)
else:
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
elif command == "cancel":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
printer.cancel_print()
printer.cancel_print(tags=tags)
return NO_CONTENT
+23 -13
View File
@@ -75,6 +75,8 @@ def printerToolCommand():
validation_regex = re.compile("tool\d+")
tags = {"source:api", "api:printer.tool"}
##~~ tool selection
if command == "select":
tool = data["tool"]
@@ -83,7 +85,7 @@ def printerToolCommand():
if not tool.startswith("tool"):
return make_response("Invalid tool for selection: %s" % tool, 400)
printer.change_tool(tool)
printer.change_tool(tool, tags=tags)
##~~ temperature
elif command == "target":
@@ -100,7 +102,7 @@ def printerToolCommand():
# perform the actual temperature commands
for tool in validated_values.keys():
printer.set_temperature(tool, validated_values[tool])
printer.set_temperature(tool, validated_values[tool], tags=tags)
##~~ temperature offset
elif command == "offset":
@@ -129,14 +131,14 @@ def printerToolCommand():
amount = data["amount"]
if not isinstance(amount, (int, long, float)):
return make_response("Not a number for extrusion amount: %r" % amount, 400)
printer.extrude(amount)
printer.extrude(amount, tags=tags)
elif command == "flowrate":
factor = data["factor"]
if not isinstance(factor, (int, long, float)):
return make_response("Not a number for flow rate: %r" % factor, 400)
try:
printer.flow_rate(factor)
printer.flow_rate(factor, tags=tags)
except ValueError as e:
return make_response("Invalid value for flow rate: %s" % str(e), 400)
@@ -171,6 +173,8 @@ def printerBedCommand():
if response is not None:
return response
tags = {"source:api", "api:printer.bed"}
##~~ temperature
if command == "target":
target = data["target"]
@@ -180,7 +184,7 @@ def printerBedCommand():
return make_response("Not a number: %r" % target, 400)
# perform the actual temperature command
printer.set_temperature("bed", target)
printer.set_temperature("bed", target, tags=tags)
##~~ temperature offset
elif command == "offset":
@@ -232,6 +236,8 @@ def printerPrintheadCommand():
# do not jog when a print job is running or we don't have a connection
return make_response("Printer is not operational or currently printing", 409)
tags = {"source:api", "api:printer.printhead"}
valid_axes = ["x", "y", "z"]
##~~ jog command
if command == "jog":
@@ -248,7 +254,7 @@ def printerPrintheadCommand():
speed = data.get("speed", None)
# execute the jog commands
printer.jog(validated_values, relative=not absolute, speed=speed)
printer.jog(validated_values, relative=not absolute, speed=speed, tags=tags)
##~~ home command
elif command == "home":
@@ -260,14 +266,14 @@ def printerPrintheadCommand():
validated_values.append(axis)
# execute the home command
printer.home(validated_values)
printer.home(validated_values, tags=tags)
elif command == "feedrate":
factor = data["factor"]
if not isinstance(factor, (int, long, float)):
return make_response("Not a number for feed rate: %r" % factor, 400)
try:
printer.feed_rate(factor)
printer.feed_rate(factor, tags=tags)
except ValueError as e:
return make_response("Invalid value for feed rate: %s" % str(e), 400)
@@ -295,12 +301,14 @@ def printerSdCommand():
if response is not None:
return response
tags = {"source:api", "api:printer.sd"}
if command == "init":
printer.init_sd_card()
printer.init_sd_card(tags=tags)
elif command == "refresh":
printer.refresh_sd_files()
printer.refresh_sd_files(tags=tags)
elif command == "release":
printer.release_sd_card()
printer.release_sd_card(tags=tags)
return NO_CONTENT
@@ -341,6 +349,8 @@ def printerCommand():
if "parameters" in data:
parameters = data["parameters"]
tags = {"source:api", "api:printer.command"}
if "command" in data or "commands" in data:
if "command" in data:
commands = [data["command"]]
@@ -356,7 +366,7 @@ def printerCommand():
commandToSend = command % parameters
commandsToSend.append(commandToSend)
printer.commands(commandsToSend)
printer.commands(commandsToSend, tags=tags)
elif "script" in data:
script_name = data["script"]
@@ -365,7 +375,7 @@ def printerCommand():
context["context"] = data["context"]
try:
printer.script(script_name, context=context)
printer.script(script_name, context=context, tags=tags)
except UnknownScript:
return make_response("Unknown script: {script_name}".format(**locals()), 404)
+247 -122
View File
@@ -342,6 +342,7 @@ class MachineCom(object):
def __init__(self, port = None, baudrate=None, callbackObject=None, printerProfileManager=None):
self._logger = logging.getLogger(__name__)
self._serialLogger = logging.getLogger("SERIAL")
self._phaseLogger = logging.getLogger(__name__ + ".command_phases")
if port == None:
port = settings().get(["serial", "port"])
@@ -787,7 +788,7 @@ class MachineCom(object):
def fakeOk(self):
self._handle_ok()
def sendCommand(self, cmd, cmd_type=None, processed=False, force=False, on_sent=None):
def sendCommand(self, cmd, cmd_type=None, processed=False, force=False, on_sent=None, tags=None):
cmd = to_unicode(cmd, errors="replace")
if not processed:
cmd = process_gcode_line(cmd)
@@ -796,13 +797,13 @@ class MachineCom(object):
if self.isPrinting() and not self.isSdFileSelected():
try:
self._command_queue.put((cmd, cmd_type, on_sent), item_type=cmd_type)
self._command_queue.put((cmd, cmd_type, on_sent, tags), item_type=cmd_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in command queue: " + e.type)
return False
elif self.isOperational() or force:
return self._sendCommand(cmd, cmd_type=cmd_type, on_sent=on_sent)
return self._sendCommand(cmd, cmd_type=cmd_type, on_sent=on_sent, tags=tags)
def _getGcodeScript(self, scriptName, replacements=None):
context = dict()
@@ -870,13 +871,16 @@ class MachineCom(object):
scriptLines))
def sendGcodeScript(self, scriptName, replacements=None):
def sendGcodeScript(self, scriptName, replacements=None, tags=None):
if tags is None:
tags = set()
scriptLines = self._getGcodeScript(scriptName, replacements=replacements)
for line in scriptLines:
self.sendCommand(line)
self.sendCommand(line, tags=tags | {"trigger:comm.send_gcode_script", "source:script", "script:{}".format(scriptName)})
return "\n".join(scriptLines)
def startPrint(self, pos=None):
def startPrint(self, pos=None, tags=None):
if not self.isOperational() or self.isPrinting():
return
@@ -888,13 +892,16 @@ class MachineCom(object):
self._pauseWaitStartTime = 0
self._pauseWaitTimeLost = 0.0
if tags is None:
tags = set()
try:
with self._jobLock:
self._currentFile.start()
self._changeState(self.STATE_PRINTING)
self.resetLineNumbers()
self.resetLineNumbers(tags={"trigger:comm.start_print"})
self._callback.on_comm_print_job_started()
@@ -904,14 +911,15 @@ class MachineCom(object):
# make sure to ignore the "file selected" later on, otherwise we'll reset our progress data
self._ignore_select = True
self.sendCommand("M23 {filename}".format(filename=self._currentFile.getFilename()))
self.sendCommand("M23 {filename}".format(filename=self._currentFile.getFilename()),
tags=tags | {"trigger:comm.start_print",})
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.setFilepos(pos)
self.sendCommand("M26 S{}".format(pos))
self.sendCommand("M26 S{}".format(pos), tags=tags | {"trigger:comm.start_print",})
else:
self._currentFile.setFilepos(0)
self.sendCommand("M24")
self.sendCommand("M24", tags=tags | {"trigger:comm.start_print",})
self._sd_status_timer = RepeatedTimer(self._timeout_intervals.get("sdStatus", 1.0), self._poll_sd_status, run_first=True)
self._sd_status_timer.start()
@@ -921,7 +929,7 @@ class MachineCom(object):
line = self._getNext()
if line is not None:
self.sendCommand(line)
self.sendCommand(line, tags={"trigger:comm.start_print", "source:file"})
# now make sure we actually do something, up until now we only filled up the queue
self._sendFromQueue()
@@ -931,13 +939,16 @@ class MachineCom(object):
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
def startFileTransfer(self, filename, localFilename, remoteFilename, special=False):
def startFileTransfer(self, filename, localFilename, remoteFilename, special=False, tags=None):
if not self.isOperational() or self.isBusy():
self._logger.info("Printer is not operational or busy")
return
if tags is None:
tags = set()
with self._jobLock:
self.resetLineNumbers()
self.resetLineNumbers(tags={"trigger:comm.start_file_transfer"})
if special:
self._currentFile = SpecialStreamingGcodeFileInformation(filename, localFilename, remoteFilename)
@@ -945,22 +956,25 @@ class MachineCom(object):
self._currentFile = StreamingGcodeFileInformation(filename, localFilename, remoteFilename)
self._currentFile.start()
self.sendCommand("M28 %s" % remoteFilename)
self.sendCommand("M28 %s" % remoteFilename, tags=tags | {"trigger:comm.start_file_transfer",})
eventManager().fire(Events.TRANSFER_STARTED, {"local": localFilename, "remote": remoteFilename})
self._callback.on_comm_file_transfer_started(remoteFilename, self._currentFile.getFilesize())
def cancelFileTransfer(self):
def cancelFileTransfer(self, tags=None):
if not self.isOperational() or not self.isStreaming():
self._logger.info("Printer is not operational or not streaming")
return
self._finishFileTransfer(failed=True)
self._finishFileTransfer(failed=True, tags=tags)
def _finishFileTransfer(self, failed=False, tags=None):
if tags is None:
tags = set()
def _finishFileTransfer(self, failed=False):
with self._jobLock:
remote = self._currentFile.getRemoteFilename()
self._sendCommand("M29")
self._sendCommand("M29", tags=tags | {"trigger:comm.finish_file_transfer",})
if failed:
self.deleteSdFile(remote)
@@ -980,12 +994,15 @@ class MachineCom(object):
self._callback.on_comm_file_transfer_done(remote)
eventManager().fire(Events.TRANSFER_DONE, payload)
self.refreshSdFiles()
self.refreshSdFiles(tags={"trigger:comm.finish_file_transfer",})
def selectFile(self, filename, sd):
def selectFile(self, filename, sd, tags=None):
if self.isBusy():
return
if tags is None:
tags = set()
if sd:
if not self.isOperational():
# printer is not connected, can't use SD
@@ -995,7 +1012,7 @@ class MachineCom(object):
filename = filename[1:]
self._sdFileToSelect = filename
self.sendCommand("M23 %s" % filename)
self.sendCommand("M23 %s" % filename, tags=tags | {"trigger:comm.select_file",})
else:
self._currentFile = PrintingGcodeFileInformation(filename, offsets_callback=self.getOffsets, current_tool_callback=self.getCurrentTool)
self._callback.on_comm_file_selected(filename, self._currentFile.getFilesize(), False)
@@ -1011,7 +1028,7 @@ class MachineCom(object):
self._recordFilePosition()
self._callback.on_comm_print_job_cancelled()
def cancelPrint(self, firmware_error=None, disable_log_position=False):
def cancelPrint(self, firmware_error=None, disable_log_position=False, tags=None):
if not self.isOperational():
return
@@ -1024,20 +1041,23 @@ class MachineCom(object):
self.cancelFileTransfer()
return
if tags is None:
tags = set()
def _on_M400_sent():
# we don't call on_print_job_cancelled on our callback here
# because we do this only after our M114 has been answered
# by the firmware
self._record_cancel_data = True
self.sendCommand("M114")
self.sendCommand("M114", tags=tags | {"trigger:comm.cancel", "trigger:record_position"})
with self._jobLock:
self._changeState(self.STATE_OPERATIONAL)
if self.isSdFileSelected():
self.sendCommand("M25") # pause print
self.sendCommand("M27") # get current byte position in file
self.sendCommand("M26 S0") # reset position in file to byte 0
self.sendCommand("M25", tags=tags | {"trigger:comm.cancel",}) # pause print
self.sendCommand("M27", tags=tags | {"trigger:comm.cancel",}) # get current byte position in file
self.sendCommand("M26 S0", tags=tags | {"trigger:comm.cancel",}) # reset position in file to byte 0
if self._sd_status_timer is not None:
try:
self._sd_status_timer.cancel()
@@ -1045,20 +1065,23 @@ class MachineCom(object):
pass
if self._log_position_on_cancel and not disable_log_position:
self.sendCommand("M400", on_sent=_on_M400_sent)
self.sendCommand("M400", on_sent=_on_M400_sent, tags=tags | {"trigger:comm.cancel", "trigger:record_position"})
else:
self._cancel_preparation_done()
def _pause_preparation_done(self):
self._callback.on_comm_print_job_paused()
def setPause(self, pause):
def setPause(self, pause, tags=None):
if self.isStreaming():
return
if not self._currentFile:
return
if tags is None:
tags = set()
with self._jobLock:
if not pause and self.isPaused():
if self._pauseWaitStartTime:
@@ -1069,12 +1092,17 @@ class MachineCom(object):
self._callback.on_comm_print_job_resumed()
if self.isSdFileSelected():
self.sendCommand("M24")
self.sendCommand("M27")
self.sendCommand("M24", tags=tags | {"trigger:comm.set_pause","trigger:resume"})
self.sendCommand("M27", tags=tags | {"trigger:comm.set_pause", "trigger:resume"})
else:
line = self._getNext()
if line is not None:
self.sendCommand(line)
if not tags:
tags_to_use = set()
else:
tags_to_use = set(tags)
tags_to_use.add("file")
self.sendCommand(line, tags=tags | {"trigger:comm.set_pause", "trigger:resume", "source:file"})
# now make sure we actually do something, up until now we only filled up the queue
self._sendFromQueue()
@@ -1085,59 +1113,68 @@ class MachineCom(object):
self._changeState(self.STATE_PAUSED)
if self.isSdFileSelected():
self.sendCommand("M25") # pause print
self.sendCommand("M25", tags=tags | {"trigger:comm.set_pause", "trigger:pause"}) # pause print
def _on_M400_sent():
# we don't call on_print_job_paused on our callback here
# because we do this only after our M114 has been answered
# by the firmware
self._record_pause_data = True
self.sendCommand("M114")
self.sendCommand("M114", tags=tags | {"trigger:comm.set_pause", "trigger:pause", "trigger:record_position"})
if self._log_position_on_pause:
self.sendCommand("M400", on_sent=_on_M400_sent)
self.sendCommand("M400", on_sent=_on_M400_sent, tags=tags | {"trigger:comm.set_pause", "trigger:pause", "trigger:record_position"})
else:
self._pause_preparation_done()
def getSdFiles(self):
return self._sdFiles
def deleteSdFile(self, filename):
def deleteSdFile(self, filename, tags=None):
if not self._sdEnabled:
return
if tags is None:
tags = set()
if not self.isOperational() or (self.isBusy() and
isinstance(self._currentFile, PrintingSdFileInformation) and
self._currentFile.getFilename() == filename):
# do not delete a file from sd we are currently printing from
return
self.sendCommand("M30 %s" % filename.lower())
self.sendCommand("M30 %s" % filename.lower(), tags=tags | {"trigger:comm.delete_sd_file",})
self.refreshSdFiles()
def refreshSdFiles(self):
def refreshSdFiles(self, tags=None):
if not self._sdEnabled:
return
if not self.isOperational() or self.isBusy():
return
self.sendCommand("M20")
if tags is None:
tags = set()
def initSdCard(self):
self.sendCommand("M20", tags=tags | {"trigger:comm.refresh_sd_files",})
def initSdCard(self, tags=None):
if not self._sdEnabled:
return
if not self.isOperational():
return
self.sendCommand("M21")
if tags is None:
tags = set()
self.sendCommand("M21", tags=tags | {"trigger:comm.init_sd_card"})
if self._sdAlwaysAvailable:
self._sdAvailable = True
self.refreshSdFiles()
self._callback.on_comm_sd_state_change(self._sdAvailable)
def releaseSdCard(self):
def releaseSdCard(self, tags=None):
if not self._sdEnabled:
return
@@ -1145,22 +1182,31 @@ class MachineCom(object):
# do not release the sd card if we are currently printing from it
return
self.sendCommand("M22")
if tags is None:
tags = set()
self.sendCommand("M22", tags=tags | {"trigger:comm.release_sd_card",})
self._sdAvailable = False
self._sdFiles = []
self._callback.on_comm_sd_state_change(self._sdAvailable)
self._callback.on_comm_sd_files(self._sdFiles)
def sayHello(self):
self.sendCommand(self._hello_command, force=True)
def sayHello(self, tags=None):
if tags is None:
tags = set()
self.sendCommand(self._hello_command, force=True, tags=tags | {"trigger:comm.say_hello",})
self._clear_to_send.set()
def resetLineNumbers(self, number=0):
def resetLineNumbers(self, number=0, tags=None):
if not self.isOperational():
return
self.sendCommand("M110 N%d" % number)
if tags is None:
tags = set()
self.sendCommand("M110 N%d" % number, tags=tags | {"trigger:comm.reset_line_numbers",})
##~~ record aborted file positions
@@ -1640,7 +1686,7 @@ class MachineCom(object):
self._baudrateDetectRetry -= 1
self._serial.write('\n')
self._log("Baudrate test retry: %d" % (self._baudrateDetectRetry))
self.sayHello()
self.sayHello(tags="trigger:baudrate_detection")
elif len(self._baudrateDetectList) > 0:
baudrate = self._baudrateDetectList.pop(0)
try:
@@ -1651,7 +1697,7 @@ class MachineCom(object):
self._baudrateDetectRetry = 5
self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals)
self._serial.write('\n')
self.sayHello()
self.sayHello(tags="trigger:baudrate_detection")
except:
self._log("Unexpected error while setting baudrate {}: {}".format(baudrate, get_exception_string()))
self._logger.exception("Unexpceted error while setting baudrate {}".format(baudrate))
@@ -1792,7 +1838,7 @@ class MachineCom(object):
message = "Communication timeout while printing, trying to trigger response from printer."
self._logger.info(message)
self._log(message + " " + general_message)
if self._sendCommand("M105", cmd_type="temperature"):
if self._sendCommand("M105", cmd_type="temperature", tags={"trigger:comm.handle_timeout"}):
self._clear_to_send.set()
elif self._clear_to_send.blocked():
@@ -1873,7 +1919,7 @@ class MachineCom(object):
"""
if self.isOperational() and not self._temperature_autoreporting and not self._connection_closing and not self.isStreaming() and not self._long_running_command and not self._heating and not self._dwelling_until and not self._manualStreaming:
self.sendCommand("M105", cmd_type="temperature_poll")
self.sendCommand("M105", cmd_type="temperature_poll", tags={"trigger:comm.poll_temperature"})
def _poll_sd_status(self):
"""
@@ -1884,7 +1930,7 @@ class MachineCom(object):
"""
if self.isOperational() and not self._connection_closing and self.isSdPrinting() and not self._long_running_command and not self._dwelling_until and not self._heating:
self.sendCommand("M27", cmd_type="sd_status_poll")
self.sendCommand("M27", cmd_type="sd_status_poll", tags={"trigger:comm.poll_sd_status"})
def _set_autoreport_temperature_interval(self, interval=None):
if interval is None:
@@ -1892,7 +1938,7 @@ class MachineCom(object):
interval = int(self._timeout_intervals.get("temperatureAutoreport", 2))
except:
interval = 2
self.sendCommand("M155 S{}".format(interval))
self.sendCommand("M155 S{}".format(interval), tags={"trigger:comm.set_autoreport_temperature_interval"})
def _set_busy_protocol_interval(self, interval=None):
if interval is None:
@@ -1900,7 +1946,7 @@ class MachineCom(object):
interval = max(int(self._timeout_intervals.get("communicationBusy", 3)) - 1, 1)
except:
interval = 2
self.sendCommand("M113 S{}".format(interval))
self.sendCommand("M113 S{}".format(interval), tags={"trigger:comm.set_busy_protocol_interval"})
def _onConnected(self):
self._serial.timeout = settings().getFloat(["serial", "timeout", "communication"])
@@ -1909,21 +1955,20 @@ class MachineCom(object):
self._changeState(self.STATE_OPERATIONAL)
self.resetLineNumbers()
if self._firmware_detection:
self.sendCommand("M115")
self.resetLineNumbers(tags={"trigger:comm.on_connected",})
self.sendCommand("M115", tags={"trigger:comm.on_connected",})
if self._sdAvailable:
self.refreshSdFiles()
self.refreshSdFiles(tags={"trigger:comm.on_connected",})
else:
self.initSdCard()
self.initSdCard(tags={"trigger:comm.on_connected"})
payload = dict(port=self._port, baudrate=self._baudrate)
eventManager().fire(Events.CONNECTED, payload)
self.sendGcodeScript("afterPrinterConnected", replacements=dict(event=payload))
def _onExternalReset(self):
self.resetLineNumbers()
self.resetLineNumbers(tags={"trigger:comm.on_external_reset"})
if self._temperature_autoreporting:
self._set_autoreport_temperature_interval()
@@ -1965,17 +2010,18 @@ class MachineCom(object):
try:
if isinstance(entry, tuple):
if not len(entry) == 3:
if not len(entry) == 4:
# something with that entry is broken, ignore it and fetch
# the next one
continue
cmd, cmd_type, callback = entry
cmd, cmd_type, callback, tags = entry
else:
cmd = entry
cmd_type = None
callback = None
tags = None
if self._sendCommand(cmd, cmd_type=cmd_type, on_sent=callback):
if self._sendCommand(cmd, cmd_type=cmd_type, on_sent=callback, tags=tags):
# we actually did add this cmd to the send queue, so let's
# return, we are done here
return True
@@ -2202,7 +2248,7 @@ class MachineCom(object):
# end of file, return false
return False
result = self._sendCommand(line)
result = self._sendCommand(line, tags={"source:file"})
self._callback.on_comm_progress()
if result:
# line sent, return true
@@ -2327,7 +2373,7 @@ class MachineCom(object):
return result
def _sendCommand(self, cmd, cmd_type=None, on_sent=None):
def _sendCommand(self, cmd, cmd_type=None, on_sent=None, tags=None):
# Make sure we are only handling one sending job at a time
with self._sendingLock:
if self._serial is None:
@@ -2337,16 +2383,16 @@ class MachineCom(object):
if not self.isStreaming():
# trigger the "queuing" phase only if we are not streaming to sd right now
results = self._process_command_phase("queuing", cmd, command_type=cmd_type, gcode=gcode, subcode=subcode)
results = self._process_command_phase("queuing", cmd, command_type=cmd_type, gcode=gcode, subcode=subcode, tags=tags)
if not results:
# command is no more, return
return False
else:
results = [(cmd, cmd_type, gcode, subcode)]
results = [(cmd, cmd_type, gcode, subcode, tags)]
# process helper
def process(cmd, cmd_type, gcode, subcode, on_sent=None):
def process(cmd, cmd_type, gcode, subcode, on_sent=None, tags=None):
if cmd is None:
# no command, next entry
return False
@@ -2356,10 +2402,10 @@ class MachineCom(object):
eventManager().fire(gcodeToEvent[gcode])
# actually enqueue the command for sending
if self._enqueue_for_sending(cmd, command_type=cmd_type, on_sent=on_sent):
if self._enqueue_for_sending(cmd, command_type=cmd_type, on_sent=on_sent, tags=tags):
if not self.isStreaming():
# trigger the "queued" phase only if we are not streaming to sd right now
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode, subcode=subcode)
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode, subcode=subcode, tags=tags)
return True
else:
return False
@@ -2376,18 +2422,18 @@ class MachineCom(object):
enqueued_something = False
# process all but the last ...
for (cmd, cmd_type, gcode, subcode) in results:
enqueued_something = process(cmd, cmd_type, gcode, subcode) or enqueued_something
for (cmd, cmd_type, gcode, subcode, tags) in results:
enqueued_something = process(cmd, cmd_type, gcode, subcode, tags=tags) or enqueued_something
# ... and then process the last one with the on_sent callback attached
cmd, cmd_type, gcode, subcode = last_command
enqueued_something = process(cmd, cmd_type, gcode, subcode, on_sent=on_sent) or enqueued_something
cmd, cmd_type, gcode, subcode, tags = last_command
enqueued_something = process(cmd, cmd_type, gcode, subcode, on_sent=on_sent, tags=tags) or enqueued_something
return enqueued_something
##~~ send loop handling
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None, resend=False):
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None, resend=False, tags=None):
"""
Enqueues a command and optional linenumber to use for it in the send queue.
@@ -2398,6 +2444,8 @@ class MachineCom(object):
command_type (str): Optional command type, if set and command type is already in the queue the
command won't be enqueued
on_sent (callable): Optional callable to call after command has been sent to printer.
resend (bool): Whether this is a resent command
tags (set of str or None): Tags to attach to this command
"""
try:
@@ -2405,7 +2453,7 @@ class MachineCom(object):
if resend:
target = "resend"
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type, target=target)
self._send_queue.put((command, linenumber, command_type, on_sent, False, tags), item_type=command_type, target=target)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in send queue: " + e.type)
@@ -2436,7 +2484,7 @@ class MachineCom(object):
self._dwelling_until = False
# fetch command, command type and optional linenumber and sent callback from queue
command, linenumber, command_type, on_sent, processed = entry
command, linenumber, command_type, on_sent, processed, tags = entry
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
@@ -2451,7 +2499,10 @@ class MachineCom(object):
else:
if not processed:
# trigger "sending" phase if we didn't so far
results = self._process_command_phase("sending", command, command_type, gcode=gcode, subcode=subcode)
results = self._process_command_phase("sending", command, command_type,
gcode=gcode,
subcode=subcode,
tags=tags)
if not results:
# No, we are not going to send this, that was a last-minute bail.
@@ -2471,7 +2522,7 @@ class MachineCom(object):
assert len(results) == 1
# we only use the first (and only!) entry here
command, _, gcode, subcode = results[0]
command, _, gcode, subcode, tags = results[0]
if command.strip() == "":
self._logger.info("Refusing to send an empty line to the printer")
@@ -2499,7 +2550,7 @@ class MachineCom(object):
if on_sent is not None and callable(on_sent):
# we have a sent callback for this specific command, let's execute it now
on_sent()
self._process_command_phase("sent", command, command_type, gcode=gcode, subcode=subcode)
self._process_command_phase("sent", command, command_type, gcode=gcode, subcode=subcode, tags=tags)
# we only need to use up a clear if the command we just sent was either a gcode command or if we also
# require ack's for unknown commands
@@ -2527,10 +2578,28 @@ class MachineCom(object):
self._logger.exception("Caught an exception in the send loop")
self._log("Closing down send loop")
def _process_command_phase(self, phase, command, command_type=None, gcode=None, subcode=None):
def _log_command_phase(self, phase, command, *args, **kwargs):
if self._phaseLogger.isEnabledFor(logging.DEBUG):
output_parts = [u"phase: {}".format(phase),
u"command: {}".format(command)]
if kwargs.get("command_type"):
output_parts.append(u"command_type: {}".format(kwargs["command_type"]))
if kwargs.get("gcode"):
output_parts.append(u"gcode: {}".format(kwargs["gcode"]))
if kwargs.get("subcode"):
output_parts.append(u"subcode: {}".format(kwargs["subcode"]))
if kwargs.get("tags"):
output_parts.append(u"tags: [ {} ]".format(", ".join(sorted(kwargs["tags"]))))
self._phaseLogger.debug(" | ".join(output_parts))
def _process_command_phase(self, phase, command, command_type=None, gcode=None, subcode=None, tags=None):
if gcode is None:
gcode, subcode = gcode_and_subcode_for_cmd(command)
results = [(command, command_type, gcode, subcode)]
results = [(command, command_type, gcode, subcode, tags)]
self._log_command_phase(phase, command, command_type=command_type, gcode=gcode, subcode=subcode, tags=tags)
if (self.isStreaming() and self.isPrinting()) or phase not in ("queuing", "queued", "sending", "sent"):
return results
@@ -2538,18 +2607,22 @@ class MachineCom(object):
# send it through the phase specific handlers provided by plugins
for name, hook in self._gcode_hooks[phase].items():
new_results = []
for command, command_type, gcode, subcode in results:
for command, command_type, gcode, subcode, tags in results:
try:
hook_results = hook(self, phase, command, command_type, gcode, subcode=subcode)
hook_results = hook(self, phase, command, command_type, gcode, subcode=subcode, tags=tags)
except:
self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals()))
else:
normalized = _normalize_command_handler_result(command, command_type, gcode, subcode, hook_results)
normalized = _normalize_command_handler_result(command, command_type, gcode, subcode, tags,
hook_results,
tags_to_add={"source:rewrite",
"phase:{}".format(phase),
"plugin:{}".format(name)})
# make sure we don't allow multi entry results in anything but the queuing phase
if not phase in ("queuing",) and len(normalized) > 1:
self._logger.error("Error while processing hook {name} for phase {phase} and command {command}: Hook returned multi-entry result for phase {phase} and command {command}. That's not supported, if you need to do multi expansion of commands you need to do this in the queuing phase. Ignoring hook result and sending command as-is.".format(**locals()))
new_results.append((command, command_type, gcode, subcode))
new_results.append((command, command_type, gcode, subcode, tags))
else:
new_results += normalized
if not new_results:
@@ -2560,15 +2633,19 @@ class MachineCom(object):
# if it's a gcode command send it through the specific handler if it exists
new_results = []
modified = False
for command, command_type, gcode, subcode in results:
for command, command_type, gcode, subcode, tags in results:
if gcode is not None:
gcode_handler = "_gcode_" + gcode + "_" + phase
if hasattr(self, gcode_handler):
handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type, subcode=subcode)
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
handler_results = getattr(self, gcode_handler)(command,
cmd_type=command_type,
subcode=subcode,
tags=tags)
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, tags,
handler_results)
modified = True
else:
new_results.append((command, command_type, gcode, subcode))
new_results.append((command, command_type, gcode, subcode, tags))
modified = True
if modified:
if not new_results:
@@ -2581,9 +2658,14 @@ class MachineCom(object):
command_phase_handler = "_command_phase_" + phase
if hasattr(self, command_phase_handler):
new_results = []
for command, command_type, gcode, subcode in results:
handler_results = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode, subcode=subcode)
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
for command, command_type, gcode, subcode, tags in results:
handler_results = getattr(self, command_phase_handler)(command,
cmd_type=command_type,
gcode=gcode,
subcode=subcode,
tags=tags)
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, tags,
handler_results)
results = new_results
# finally return whatever we resulted on
@@ -3670,7 +3752,7 @@ def gcode_and_subcode_for_cmd(cmd):
return gcode, values.get("subcode", None)
def _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results):
def _normalize_command_handler_result(command, command_type, gcode, subcode, tags, handler_results, tags_to_add=None):
"""
Normalizes a command handler result.
@@ -3678,14 +3760,15 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
entries.
``None`` results are ignored, the provided ``command``, ``command_type``,
``gcode`` and ``subcode`` are returned in that case (as single-entry list with
one 4-tuple as entry).
``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with
one 5-tuple as entry).
Single result entries are either:
* a single string defining a replacement ``command``
* a 1-tuple defining a replacement ``command``
* a 2-tuple defining a replacement ``command`` and ``command_type``
* a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set
A ``command`` that is ``None`` will lead to the entry being ignored for
the normalized result.
@@ -3696,26 +3779,32 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
be empty in which case the command is to be suppressed.
Examples:
>>> _normalize_command_handler_result("M105", None, "M105", None, None)
[('M105', None, 'M105', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, "M110")
[('M110', None, 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110"])
[('M110', None, 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", "M117 Foobar"])
[('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), "M117 Foobar"])
[('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110", "lineno_reset"), "M117 Foobar"])
[('M110', 'lineno_reset', 'M110', None), ('M117 Foobar', None, 'M117', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, [])
>>> _normalize_command_handler_result("M105", None, "M105", None, None, None)
[('M105', None, 'M105', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, "M110")
[('M110', None, 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110"])
[('M110', None, 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", "M117 Foobar"])
[('M110', None, 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), "M117 Foobar"])
[('M110', None, 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110", "lineno_reset"), "M117 Foobar"])
[('M110', 'lineno_reset', 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [])
[]
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", None])
[('M110', None, 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), (None, "ignored")])
[('M110', None, 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")])
[('M110', None, 'M110', None), ('M117 Foobar', 'display_message', 'M117', None), ('M110', 'lineno_reset', 'M110', None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", None])
[('M110', None, 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), (None, "ignored")])
[('M110', None, 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")])
[('M110', None, 'M110', None, None), ('M117 Foobar', 'display_message', 'M117', None, None), ('M110', 'lineno_reset', 'M110', None, None)]
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M117 Foobar"])
[('M110', None, 'M110', None, set(['tag1', 'tag2'])), ('M117 Foobar', None, 'M117', None, set(['tag1', 'tag2']))]
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M105", "M117 Foobar"], tags_to_add={"tag3"})
[('M110', None, 'M110', None, set(['tag1', 'tag2', 'tag3'])), ('M105', None, 'M105', None, set(['tag1', 'tag2'])), ('M117 Foobar', None, 'M117', None, set(['tag1', 'tag2', 'tag3']))]
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", ("M105", "temperature_poll"), "M117 Foobar"], tags_to_add={"tag3"})
[('M110', None, 'M110', None, set(['tag1', 'tag2', 'tag3'])), ('M105', 'temperature_poll', 'M105', None, set(['tag1', 'tag2', 'tag3'])), ('M117 Foobar', None, 'M117', None, set(['tag1', 'tag2', 'tag3']))]
Arguments:
command (str or None): The command for which the handler result was
@@ -3726,16 +3815,20 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
generated
subcode (str or None): The GCODE subcode for which the handler result
was generated
tags (set of str or None): The tags associated with the GCODE for which
the handler result was generated
handler_results: The handler result(s) to normalized. Can be either
a single result entry or a list of result entries.
tags_to_add (set of str or None): List of tags to add to expanded result
entries
Returns:
(list) - A list of normalized handler result entries, which are
4-tuples consisting of ``command``, ``command_type``, ``gcode``
and ``subcode``, the latter three of which may be ``None``.
5-tuples consisting of ``command``, ``command_type``, ``gcode``
``subcode`` and ``tags``, the latter three of which may be ``None``.
"""
original = (command, command_type, gcode, subcode)
original = (command, command_type, gcode, subcode, tags)
if handler_results is None:
# handler didn't return anything, we'll just continue
@@ -3753,21 +3846,39 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
# entry is None, we'll ignore that entry and continue
continue
if tags:
# copy the tags
tags = set(tags)
if isinstance(handler_result, basestring):
# entry is just a string, replace command with it
command = handler_result
gcode, subcode = gcode_and_subcode_for_cmd(command)
result.append((command, command_type, gcode, subcode))
if command != original[0]:
# command changed, re-extract gcode and subcode and add tags if necessary
gcode, subcode = gcode_and_subcode_for_cmd(command)
if tags_to_add and isinstance(tags_to_add, set) and command != original[0]:
if tags is None:
tags = set()
tags |= tags_to_add
result.append((command, command_type, gcode, subcode, tags))
elif isinstance(handler_result, tuple):
# entry is a tuple, extract command and command_type
hook_result_length = len(handler_result)
handler_tags = None
if hook_result_length == 1:
# handler returned just the command
command, = handler_result
elif hook_result_length == 2:
# handler returned command and command_type
command, command_type = handler_result
elif hook_result_length == 3:
# handler returned command, command type and additional tags
command, command_type, handler_tags = handler_result
else:
# handler returned a tuple of an unexpected length, ignore
# and continue
@@ -3777,11 +3888,25 @@ def _normalize_command_handler_result(command, command_type, gcode, subcode, han
# command is None, ignore it and continue
continue
gcode, subcode = gcode_and_subcode_for_cmd(command)
result.append((command, command_type, gcode, subcode))
if command != original[0] or command_type != original[2]:
# command or command_type changed, re-extract gcode and subcode and add tags if necessary
gcode, subcode = gcode_and_subcode_for_cmd(command)
if tags_to_add and isinstance(tags_to_add, set):
if tags is None:
tags = set()
tags |= tags_to_add
if handler_tags and isinstance(handler_tags, set):
# handler provided additional tags, add them
if tags is None:
tags = set()
tags |= handler_tags
result.append((command, command_type, gcode, subcode, tags))
# reset to original
command, command_type, gcode, subcode = original
command, command_type, gcode, subcode, tags = original
return result