WIP: Add tags & atcommands
This commit is contained in:
1 parent
4b64fb7f47
commit
4967d19b6a
13 files changed
+1271
-640
No files matched your search
@@ -90,17 +90,17 @@ class Protocol(ListenerAware, TransportListener):
|
||||
self._job.register_listener(self)
|
||||
self._job.process(self, position=position, tags=tags)
|
||||
|
||||
def pause_processing(self):
|
||||
def pause_processing(self, tags=None):
|
||||
if self._job is None or self.state != ProtocolState.PRINTING:
|
||||
return
|
||||
self.state = ProtocolState.PAUSED
|
||||
|
||||
def resume_processing(self):
|
||||
def resume_processing(self, tags=None):
|
||||
if self._job is None or self.state != ProtocolState.PAUSED:
|
||||
return
|
||||
self.state = ProtocolState.PRINTING
|
||||
|
||||
def cancel_processing(self, error=False):
|
||||
def cancel_processing(self, error=False, tags=None):
|
||||
if self._job is not None and self.state in (ProtocolState.PRINTING, ProtocolState.PAUSED):
|
||||
self._job.cancel(error=error)
|
||||
self.state = ProtocolState.CONNECTED
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, unicode_literals, print_function, \
|
||||
division
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import re
|
||||
|
||||
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
|
||||
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
|
||||
regex_int_pattern = "\d+"
|
||||
|
||||
regex_float = re.compile(regex_float_pattern)
|
||||
"""Regex for a float value."""
|
||||
|
||||
regexes_parameters = dict(
|
||||
floatP=re.compile("(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
|
||||
floatR=re.compile("(^|[^A-Za-z])[Rr](?P<value>%s)" % regex_float_pattern),
|
||||
floatS=re.compile("(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
|
||||
floatZ=re.compile("(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
|
||||
intN=re.compile("(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
|
||||
intT=re.compile("(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern)
|
||||
)
|
||||
"""Regexes for parsing various GCODE command parameters."""
|
||||
|
||||
class Command(object):
|
||||
@staticmethod
|
||||
def from_line(line, type=None, tags=None, **kwargs):
|
||||
if isinstance(line, Command):
|
||||
return line
|
||||
|
||||
line = line.strip()
|
||||
if GcodeCommand.command_regex.match(line):
|
||||
return GcodeCommand.from_line(line, type=type, tags=tags, **kwargs)
|
||||
elif line.startswith("@"):
|
||||
return AtCommand.from_line(line, type=type, tags=tags, **kwargs)
|
||||
else:
|
||||
return Command(line, type=type, tags=tags)
|
||||
|
||||
def __init__(self, line, type=None, tags=None):
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
self.line = line
|
||||
self.type = type
|
||||
self.tags = tags
|
||||
|
||||
def __repr__(self):
|
||||
return "{}({!r},type={!r},tags={!r})".format(self.__class__.__name__, self.line, self.type, self.tags)
|
||||
|
||||
def __str__(self):
|
||||
return self.line
|
||||
|
||||
def __key(self):
|
||||
return self.line, self.type
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__key() == other.__key()
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.__key())
|
||||
|
||||
class AtCommand(Command):
|
||||
@staticmethod
|
||||
def from_line(line, **kwargs):
|
||||
split = line.split(None, 1)
|
||||
if len(split) == 2:
|
||||
atcommand = split[0]
|
||||
parameters = split[1]
|
||||
else:
|
||||
atcommand = split[0]
|
||||
parameters = ""
|
||||
|
||||
atcommand = atcommand[1:]
|
||||
|
||||
return AtCommand(line, atcommand, parameters, **kwargs)
|
||||
|
||||
def __init__(self, line, atcommand, parameters, **kwargs):
|
||||
self.atcommand = atcommand
|
||||
self.parameters = parameters
|
||||
super(AtCommand, self).__init__(line, **kwargs)
|
||||
|
||||
def __repr__(self):
|
||||
return "AtCommand({!r},{!r},{!r},type={!r},tags={!r}".format(self.line,
|
||||
self.atcommand,
|
||||
self.parameters,
|
||||
self.type,
|
||||
self.tags)
|
||||
|
||||
class GcodeCommand(Command):
|
||||
|
||||
known_float_attributes = (b"x", b"y", b"z", b"e", b"s", b"p", b"r")
|
||||
known_int_attributes = (b"f", b"t", b"n")
|
||||
known_attributes = known_float_attributes + known_int_attributes
|
||||
|
||||
command_regex = re.compile("^\s*((?P<GM>[GM](?P<number>\d+))(\\.(?P<subcode>\d+))?|(?P<T>T(?P<tool>\d+))|(?P<F>F(?P<feedrate>\d+)))")
|
||||
|
||||
argument_pattern = "\s*([{float_args}]{float}|[{int_args}]{int})".format(float_args="".join(map(lambda x: x.upper(), known_float_attributes)),
|
||||
int_args="".join(map(lambda x: x.upper(), known_int_attributes)),
|
||||
float=regex_float_pattern,
|
||||
int=regex_int_pattern)
|
||||
argument_regex = re.compile(argument_pattern)
|
||||
param_regex = re.compile("^[GMTF]\d+(\\.\d+)?\s+(?P<param>.*?)$")
|
||||
|
||||
command_parameters = known_attributes + (b"subcode", b"tool", b"param")
|
||||
|
||||
@staticmethod
|
||||
def from_line(line, **kwargs):
|
||||
"""
|
||||
>>> gcode = GcodeCommand.from_line("M30 some_file.gco")
|
||||
>>> gcode.code
|
||||
u'M30'
|
||||
>>> gcode.param
|
||||
u'some_file.gco'
|
||||
>>> gcode = GcodeCommand.from_line("G28 X0 Y0")
|
||||
>>> gcode.code
|
||||
u'G28'
|
||||
>>> gcode.x
|
||||
0.0
|
||||
>>> gcode.y
|
||||
0.0
|
||||
>>> gcode = GcodeCommand.from_line("M104 S220.0 T1")
|
||||
>>> gcode.code
|
||||
u'M104'
|
||||
>>> gcode.s
|
||||
220.0
|
||||
>>> gcode.t
|
||||
1
|
||||
>>> gcode = GcodeCommand.from_line("M123.456 my parameter is long")
|
||||
>>> gcode.code
|
||||
u'M123'
|
||||
>>> gcode.subcode
|
||||
456
|
||||
>>> gcode.param
|
||||
u'my parameter is long'
|
||||
"""
|
||||
|
||||
if isinstance(line, GcodeCommand):
|
||||
return line
|
||||
|
||||
tags = kwargs.get(b"tags")
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
type = kwargs.get(b"type")
|
||||
|
||||
line = line.strip()
|
||||
code = ""
|
||||
args = {"original": line, "type": type, "tags": tags}
|
||||
match = GcodeCommand.command_regex.match(line)
|
||||
if match is None:
|
||||
args["unknown"] = True
|
||||
else:
|
||||
if match.group("GM"):
|
||||
code = match.group("GM")
|
||||
|
||||
if match.group("subcode"):
|
||||
args[b"subcode"] = int(match.group("subcode"))
|
||||
|
||||
matched_args = GcodeCommand.argument_regex.findall(line)
|
||||
if not matched_args:
|
||||
param = line[len(match.group(0)):].lstrip()
|
||||
if param:
|
||||
args[b"param"] = param
|
||||
else:
|
||||
for arg in matched_args:
|
||||
key = arg[0].lower()
|
||||
if key in GcodeCommand.known_int_attributes:
|
||||
value = int(arg[1:])
|
||||
elif key in GcodeCommand.known_float_attributes:
|
||||
value = float(arg[1:])
|
||||
else:
|
||||
value = str(arg[1:])
|
||||
args[key] = value
|
||||
elif match.group("T"):
|
||||
code = "T"
|
||||
args[b"tool"] = match.group("tool")
|
||||
elif match.group("F"):
|
||||
code = "F"
|
||||
args[b"f"] = match.group("feedrate")
|
||||
|
||||
return GcodeCommand(code, **args)
|
||||
|
||||
def __init__(self, code, **kwargs):
|
||||
self.code = code
|
||||
|
||||
for key in GcodeCommand.command_parameters:
|
||||
try:
|
||||
setattr(self, key, kwargs[key])
|
||||
except KeyError:
|
||||
setattr(self, key, None)
|
||||
|
||||
original = kwargs.get(b"original")
|
||||
if original is None:
|
||||
line = self._to_line()
|
||||
else:
|
||||
line = original
|
||||
|
||||
super(GcodeCommand, self).__init__(line, type=kwargs.get(b"type", None), tags=kwargs.get(b"tags", None))
|
||||
|
||||
def __str__(self):
|
||||
kwargs = dict((k, self.getattr(k)) for k in GcodeCommand.command_parameters if self.getattr(k) is not None)
|
||||
return "GcodeCommand({},original={},type={},tags={})".format(self.code, self.line, ["{}={!r}".format(key, value) for key, value in kwargs.items()], self.type, self.tags)
|
||||
|
||||
def _to_line(self):
|
||||
attr = []
|
||||
for key in GcodeCommand.known_attributes:
|
||||
value = getattr(self, key, None)
|
||||
if value is not None:
|
||||
attr.append("{}{!r}".format(key.upper(), value))
|
||||
attribute_str = " ".join(attr)
|
||||
return "{}{}{}".format(self.code.upper(), " " + attribute_str if attribute_str else "",
|
||||
" " + self.param if self.param else "")
|
||||
@@ -32,57 +32,71 @@ class GcodeCommand(object):
|
||||
known_int_attributes = ("f", "t", "n")
|
||||
known_attributes = known_float_attributes + known_int_attributes
|
||||
|
||||
command_regex = re.compile("^\s*((?P<GM>[GM](?P<number>\d+))|(?P<T>T(?P<tool>\d+))|(?P<F>F(?P<feedrate>\d+)))")
|
||||
command_regex = re.compile("^\s*((?P<GM>[GM](?P<number>\d+))(\\.(?P<subcode>\d+))?|(?P<T>T(?P<tool>\d+))|(?P<F>F(?P<feedrate>\d+)))")
|
||||
|
||||
argument_pattern = "\s*([{float_args}]{float}|[{int_args}]{int})".format(float_args="".join(map(lambda x: x.upper(), known_float_attributes)),
|
||||
int_args="".join(map(lambda x: x.upper(), known_int_attributes)),
|
||||
float=regex_float_pattern,
|
||||
int=regex_int_pattern)
|
||||
argument_regex = re.compile(argument_pattern)
|
||||
param_regex = re.compile("^[GMT]\d+\s+(.*?)$")
|
||||
param_regex = re.compile("^[GMTF]\d+(\\.\d+)?\s+(?P<param>.*?)$")
|
||||
|
||||
@staticmethod
|
||||
def from_line(line):
|
||||
def from_line(line, tags=None):
|
||||
"""
|
||||
>>> gcode = GcodeCommand.from_line("M30 some_file.gco")
|
||||
>>> gcode.command
|
||||
'M30'
|
||||
>>> gcode.code
|
||||
u'M30'
|
||||
>>> gcode.param
|
||||
'some_file.gco'
|
||||
u'some_file.gco'
|
||||
>>> gcode = GcodeCommand.from_line("G28 X0 Y0")
|
||||
>>> gcode.command
|
||||
'G28'
|
||||
>>> gcode.code
|
||||
u'G28'
|
||||
>>> gcode.x
|
||||
0.0
|
||||
>>> gcode.y
|
||||
0.0
|
||||
>>> gcode = GcodeCommand.from_line("M104 S220.0 T1")
|
||||
>>> gcode.command
|
||||
'M104'
|
||||
>>> gcode.code
|
||||
u'M104'
|
||||
>>> gcode.s
|
||||
220.0
|
||||
>>> gcode.t
|
||||
1
|
||||
>>> gcode = GcodeCommand.from_line("M123.456 my parameter is long")
|
||||
>>> gcode.code
|
||||
u'M123'
|
||||
>>> gcode.subcode
|
||||
456
|
||||
>>> gcode.param
|
||||
u'my parameter is long'
|
||||
"""
|
||||
|
||||
if isinstance(line, GcodeCommand):
|
||||
return line
|
||||
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
line = line.strip()
|
||||
command = ""
|
||||
args = {"original": line}
|
||||
code = ""
|
||||
subcode = None
|
||||
args = {"original": line, "tags": tags}
|
||||
match = GcodeCommand.command_regex.match(line)
|
||||
if match is None:
|
||||
args["unknown"] = True
|
||||
else:
|
||||
if match.group("GM"):
|
||||
command = match.group("GM")
|
||||
code = match.group("GM")
|
||||
|
||||
if match.group("subcode"):
|
||||
subcode = int(match.group("subcode"))
|
||||
|
||||
matched_args = GcodeCommand.argument_regex.findall(line)
|
||||
if not matched_args:
|
||||
param_match = GcodeCommand.param_regex.match(line)
|
||||
if param_match is not None:
|
||||
args["param"] = param_match.group(1)
|
||||
param = line[len(match.group(0)):].lstrip()
|
||||
if param:
|
||||
args["param"] = param
|
||||
else:
|
||||
for arg in matched_args:
|
||||
key = arg[0].lower()
|
||||
@@ -94,16 +108,18 @@ class GcodeCommand(object):
|
||||
value = str(arg[1:])
|
||||
args[key] = value
|
||||
elif match.group("T"):
|
||||
command = "T"
|
||||
code = "T"
|
||||
args["tool"] = match.group("tool")
|
||||
elif match.group("F"):
|
||||
command = "F"
|
||||
code = "F"
|
||||
args["f"] = match.group("feedrate")
|
||||
|
||||
return GcodeCommand(command, **args)
|
||||
return GcodeCommand(code, subcode=subcode, **args)
|
||||
|
||||
def __init__(self, command, subcode=None, **kwargs):
|
||||
self.code = command
|
||||
self.subcode = subcode
|
||||
|
||||
def __init__(self, command, **kwargs):
|
||||
self.command = command
|
||||
self.x = None
|
||||
self.y = None
|
||||
self.z = None
|
||||
@@ -121,11 +137,12 @@ class GcodeCommand(object):
|
||||
|
||||
self.progress = None
|
||||
self.callback = None
|
||||
self.tags = set()
|
||||
|
||||
self.unknown = False
|
||||
|
||||
for key, value in kwargs.iteritems():
|
||||
if key in GcodeCommand.known_attributes + ("tool", "original", "param", "progress", "callback", "unknown"):
|
||||
for key, value in kwargs.items():
|
||||
if key in GcodeCommand.known_attributes + ("tool", "original", "param", "progress", "callback", "tags", "unknown"):
|
||||
self.__setattr__(key, value)
|
||||
|
||||
def __repr__(self):
|
||||
@@ -139,14 +156,9 @@ class GcodeCommand(object):
|
||||
for key in GcodeCommand.known_attributes:
|
||||
value = self.__getattribute__(key)
|
||||
if value is not None:
|
||||
if key in GcodeCommand.known_int_attributes:
|
||||
attr.append("%s%d" % (key.upper(), value))
|
||||
elif key in GcodeCommand.known_float_attributes:
|
||||
attr.append("%s%f" % (key.upper(), value))
|
||||
else:
|
||||
attr.append("%s%r" % (key.upper(), value))
|
||||
attributeStr = " ".join(attr)
|
||||
return "%s%s%s" % (self.command.upper(), " " + attributeStr if attributeStr else "", " " + self.param if self.param else "")
|
||||
attr.append("{}{!r}".format(key.upper(), value))
|
||||
attribute_str = " ".join(attr)
|
||||
return "{}{}{}".format(self.code.upper(), " " + attribute_str if attribute_str else "", " " + self.param if self.param else "")
|
||||
|
||||
|
||||
class TypedQueue(queue.Queue):
|
||||
|
||||
@@ -10,13 +10,19 @@ from octoprint.comm.protocol import Protocol, ThreeDPrinterProtocolMixin, FileSt
|
||||
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, \
|
||||
PushingTransportWrapper, PushingTransportWrapperListener
|
||||
|
||||
from octoprint.comm.protocol.commands import Command, AtCommand, GcodeCommand
|
||||
|
||||
from octoprint.comm.protocol.gcode.util import TypedQueue, TypeAlreadyInQueue, \
|
||||
GcodeCommand, regexes_parameters
|
||||
regexes_parameters
|
||||
|
||||
from octoprint.comm.protocol.reprap.util import normalize_command_handler_result
|
||||
|
||||
from octoprint.job import LocalGcodeFilePrintjob, SDFilePrintjob, \
|
||||
LocalGcodeStreamjob
|
||||
|
||||
from octoprint.util import to_unicode, protectedkeydict, CountedEvent
|
||||
from octoprint.util import to_str, to_unicode, protectedkeydict, CountedEvent
|
||||
|
||||
from octoprint.events import Events
|
||||
|
||||
try:
|
||||
import queue
|
||||
@@ -24,10 +30,43 @@ except ImportError:
|
||||
import Queue as queue
|
||||
|
||||
import collections
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
gcode_to_event = {
|
||||
# pause for user input
|
||||
"M226": Events.WAITING,
|
||||
"M0": Events.WAITING,
|
||||
"M1": Events.WAITING,
|
||||
# dwell command
|
||||
"G4": Events.DWELL,
|
||||
|
||||
# part cooler
|
||||
"M245": Events.COOLING,
|
||||
|
||||
# part conveyor
|
||||
"M240": Events.CONVEYOR,
|
||||
|
||||
# part ejector
|
||||
"M40": Events.EJECT,
|
||||
|
||||
# user alert
|
||||
"M300": Events.ALERT,
|
||||
|
||||
# home print head
|
||||
"G28": Events.HOME,
|
||||
|
||||
# emergency stop
|
||||
"M112": Events.E_STOP,
|
||||
|
||||
# motors on/off
|
||||
"M80": Events.POWER_ON,
|
||||
"M81": Events.POWER_OFF,
|
||||
}
|
||||
|
||||
|
||||
class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProtocolMixin,
|
||||
FanControlProtocolMixin, FileStreamingProtocolMixin,
|
||||
PushingTransportWrapperListener):
|
||||
@@ -44,6 +83,8 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
temperature_interval_idle=5.0, temperature_interval_printing=5.0):
|
||||
super(ReprapGcodeProtocol, self).__init__()
|
||||
|
||||
self._phase_logger = logging.getLogger(__name__ + ".command_phases")
|
||||
|
||||
self.flavor = flavor
|
||||
self.timeouts = dict(
|
||||
connection=connection_timeout,
|
||||
@@ -100,7 +141,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
)
|
||||
self._protected_state = protectedkeydict(self._internal_state)
|
||||
|
||||
self._command_queue = queue.Queue()
|
||||
self._command_queue = TypedQueue()
|
||||
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
|
||||
self._send_queue = TypedQueue()
|
||||
|
||||
@@ -113,6 +154,9 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
sending=dict(),
|
||||
sent=dict())
|
||||
|
||||
self._atcommand_hooks = dict(queuing=dict(),
|
||||
sending=dict())
|
||||
|
||||
# temperature polling
|
||||
self._temperature_poller = None
|
||||
|
||||
@@ -214,7 +258,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
self._send_commands(self.flavor.command_sd_refresh())
|
||||
|
||||
def start_file_print(self, name, position=0, **kwargs):
|
||||
tags = kwargs.get("tags", set()) | "trigger:protocol.start_file_print"
|
||||
tags = kwargs.get(b"tags", set()) | {"trigger:protocol.start_file_print"}
|
||||
self._send_commands(self.flavor.command_sd_select_file(name),
|
||||
self.flavor.command_sd_set_pos(position),
|
||||
self.flavor.command_sd_start(),
|
||||
@@ -242,14 +286,27 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
return not self._internal_state["long_running_command"] and not self._internal_state["heating"]
|
||||
|
||||
def send_commands(self, *commands, **kwargs):
|
||||
command_type = kwargs.get("command_type")
|
||||
if self.state == ProtocolState.PRINTING and not self._job.runs_parallel:
|
||||
command_type = kwargs.get(b"command_type")
|
||||
on_sent = kwargs.get(b"on_sent")
|
||||
tags = kwargs.get(b"tags")
|
||||
force = kwargs.get(b"force", False)
|
||||
|
||||
# TODO job on hold
|
||||
if self.state == ProtocolState.PRINTING and not self._job.runs_parallel and not force:
|
||||
if len(commands) > 1:
|
||||
command_type = None
|
||||
for command in commands:
|
||||
self._command_queue.put((command, command_type))
|
||||
elif self._is_operational():
|
||||
self._send_commands(*commands, command_type=command_type)
|
||||
if not isinstance(command, Command):
|
||||
command = Command.from_line(command, type=command_type, tags=tags)
|
||||
|
||||
try:
|
||||
self._command_queue.put((command, on_sent), item_type=command_type)
|
||||
return True
|
||||
except TypeAlreadyInQueue as e:
|
||||
self._logger.debug("Type already in queue: " + e.type)
|
||||
return False
|
||||
elif self._is_operational() or force:
|
||||
self._send_commands(*commands, command_type=command_type, tags=tags)
|
||||
|
||||
##~~ State handling
|
||||
|
||||
@@ -259,6 +316,10 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
def _is_busy(self):
|
||||
return self.state in (ProtocolState.PRINTING, ProtocolState.PAUSED)
|
||||
|
||||
def _is_streaming(self):
|
||||
# TODO make more abstract?
|
||||
return self._is_busy() and self._job and isinstance(self._job, LocalGcodeStreamjob)
|
||||
|
||||
def _on_state_connecting(self, old_state):
|
||||
if old_state is not ProtocolState.DISCONNECTED:
|
||||
return
|
||||
@@ -624,10 +685,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
|
||||
def _continue_sending(self):
|
||||
while self._active:
|
||||
if self.state in (ProtocolState.CONNECTED, ProtocolState.PAUSED):
|
||||
return self._send_from_queue()
|
||||
|
||||
elif self.state in (ProtocolState.PRINTING,):
|
||||
if self.state in (ProtocolState.PRINTING,) and not (self._job is None or not self._job.active or isinstance(self._job, SDFilePrintjob)):
|
||||
# we are printing, we really want to send either something from the command
|
||||
# queue or the next line from our file, so we only return here if we actually DO
|
||||
# send something
|
||||
@@ -635,11 +693,18 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
# we found something in the queue to send
|
||||
return True
|
||||
|
||||
# TODO job on hold
|
||||
#elif self.job_on_hold:
|
||||
# return False
|
||||
|
||||
elif self._send_next_from_job():
|
||||
# we sent the next line from the file
|
||||
return True
|
||||
|
||||
self._logger.debug("No command sent on ok while printing, doing another iteration")
|
||||
else:
|
||||
# just send stuff from the command queue and be done with it
|
||||
return self._send_from_queue()
|
||||
|
||||
def _send_same_from_resend(self):
|
||||
return self._send_next_from_resend(again=True)
|
||||
@@ -665,7 +730,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
command = self._last_lines[-resend_delta]
|
||||
linenumber = self._current_linenumber - resend_delta
|
||||
|
||||
result = self._enqueue_for_sending(command, linenumber=linenumber)
|
||||
result = self._enqueue_for_sending(Command(command), linenumber=linenumber, processed=True)
|
||||
|
||||
self._internal_state["resend_delta"] -= 1
|
||||
if self._internal_state["resend_delta"] <= 0:
|
||||
@@ -684,12 +749,22 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
# we are no longer printing, return False
|
||||
return False
|
||||
|
||||
# TODO job on hold
|
||||
#elif self.job_on_hold:
|
||||
# # job is on hold, return false
|
||||
# return False
|
||||
|
||||
line = self._job.get_next()
|
||||
# TODO implement QueueMarker
|
||||
if line is None:
|
||||
# end of job, return False
|
||||
return False
|
||||
|
||||
if self._send_command(line):
|
||||
command = Command.from_line(line, tags={"source:file",})
|
||||
# TODO filepos & fileline tags
|
||||
#"filepos:{}".format(pos),
|
||||
#"fileline:{}".format(lineno)})
|
||||
if self._send_command(command):
|
||||
return True
|
||||
|
||||
self._logger.debug("Command \"{}\" from job not enqueued, doing another iteration".format(line))
|
||||
@@ -715,13 +790,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
# something with that entry is broken, ignore it and fetch
|
||||
# the next one
|
||||
continue
|
||||
cmd, cmd_type, callback = entry
|
||||
cmd, callback = entry
|
||||
else:
|
||||
cmd = entry
|
||||
cmd_type = None
|
||||
callback = None
|
||||
|
||||
if self._send_command(cmd, command_type=cmd_type, on_sent=callback):
|
||||
if self._send_command(cmd, on_sent=callback):
|
||||
# we actually did add this cmd to the send queue, so let's
|
||||
# return, we are done here
|
||||
return True
|
||||
@@ -729,55 +803,87 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
self._command_queue.task_done()
|
||||
|
||||
def _send_commands(self, *commands, **kwargs):
|
||||
# TODO return True or False depending on whether something/all? was sent
|
||||
command_type = kwargs.get(b"command_type", None)
|
||||
result = False
|
||||
for command in commands:
|
||||
if len(commands) > 1:
|
||||
command_type = None
|
||||
self._send_command(command, command_type=command_type, tags=kwargs.get(b"tags", set()))
|
||||
result = self._send_command(command, command_type=command_type, tags=kwargs.get(b"tags", None)) or result
|
||||
return result
|
||||
|
||||
def _send_command(self, command, command_type=None, on_sent=None, tags=None):
|
||||
if isinstance(command, GcodeCommand):
|
||||
gcode = command
|
||||
command = str(gcode)
|
||||
else:
|
||||
gcode = None
|
||||
def _send_command(self, command, command_type=None, tags=None, on_sent=None):
|
||||
if not isinstance(command, Command):
|
||||
command = Command.from_line(command, type=command_type, tags=tags)
|
||||
|
||||
with self._send_queue_mutex:
|
||||
if self._internal_state["trigger_events"]:
|
||||
command, command_type, gcode = self._process_command_phase("queuing", command, command_type, gcode=gcode)
|
||||
results = self._process_command_phase("queuing", command)
|
||||
|
||||
if command is None:
|
||||
if not results:
|
||||
# command is no more, return
|
||||
return False
|
||||
|
||||
# TODO gcode to event mapping
|
||||
#if gcode and gcode.command in gcode_to_event:
|
||||
# # if this is a gcode bound to an event, trigger that now
|
||||
# self._eventbus.fire(gcode_to_event[gcode.command])
|
||||
|
||||
if self._enqueue_for_sending(command, command_type=command_type, on_sent=on_sent):
|
||||
if self._internal_state["trigger_events"]:
|
||||
self._process_command_phase("queued", command, command_type, gcode=gcode)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
results = [command]
|
||||
|
||||
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None):
|
||||
# process helper
|
||||
def process(command, on_sent=None):
|
||||
if command is None:
|
||||
# no command, next entry
|
||||
return False
|
||||
|
||||
# process @ commands
|
||||
if isinstance(command, AtCommand):
|
||||
self._process_atcommand_phase("queuing", command)
|
||||
|
||||
# actually enqueue the command for sending
|
||||
if self._enqueue_for_sending(command, on_sent=on_sent):
|
||||
if not self._is_streaming():
|
||||
# trigger the "queued" phase only if we are not streaming to sd right now
|
||||
self._process_command_phase("queued", command)
|
||||
|
||||
if self._internal_state["trigger_events"] and isinstance(command, GcodeCommand) and command.code in gcode_to_event:
|
||||
# TODO inject eventbus
|
||||
#self._eventbus.fire(gcode_to_event[command.code])
|
||||
pass
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
# split off the final command, because that needs special treatment
|
||||
if len(results) > 1:
|
||||
last_command = results[-1]
|
||||
results = results[:-1]
|
||||
else:
|
||||
last_command = results[0]
|
||||
results = []
|
||||
|
||||
# track if we enqueued anything at all
|
||||
enqueued_something = False
|
||||
|
||||
# process all but the last ...
|
||||
for command in results:
|
||||
enqueued_something = process(command) or enqueued_something
|
||||
|
||||
# ... and then process the last one with the on_sent callback attached
|
||||
command = last_command
|
||||
enqueued_something = process(command, on_sent=on_sent) or enqueued_something
|
||||
|
||||
return enqueued_something
|
||||
|
||||
def _enqueue_for_sending(self, command, linenumber=None, on_sent=None, processed=False):
|
||||
"""
|
||||
Enqueues a command and optional command_type and linenumber in the send queue.
|
||||
|
||||
Arguments:
|
||||
command (unicode): The command to send
|
||||
command (Command): The command to send
|
||||
linenumber (int): An optional line number to use for sending the
|
||||
command.
|
||||
command_type (unicode): An optional command type. There can only be
|
||||
one command of a specified command type in the queue at any
|
||||
given time.
|
||||
on_sent (callable or None): Callback to call when the command has been sent
|
||||
processed (bool): Whether this line has already been processed or not
|
||||
"""
|
||||
|
||||
try:
|
||||
self._send_queue.put((command, linenumber, command_type, on_sent), item_type=command_type)
|
||||
self._send_queue.put((command, linenumber, on_sent, processed), item_type=command.type)
|
||||
return True
|
||||
except TypeAlreadyInQueue as e:
|
||||
self._logger.debug("Type already in queue: {}".format(e.type))
|
||||
@@ -802,34 +908,38 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
break
|
||||
|
||||
# fetch command and optional linenumber from queue
|
||||
command, linenumber, command_type, on_sent = 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
|
||||
# at hand here and only clear our clear_to_send flag later if that's the case
|
||||
gcode = GcodeCommand.from_line(command)
|
||||
command, linenumber, on_sent, processed = entry
|
||||
|
||||
if linenumber is not None:
|
||||
# line number predetermined - this only happens for resends, so we'll use the number and
|
||||
# send directly without any processing (since that already took place on the first sending!)
|
||||
self._do_send_with_checksum(command, linenumber)
|
||||
self._do_send_with_checksum(to_str(command.line), linenumber)
|
||||
|
||||
else:
|
||||
# trigger "sending" phase
|
||||
command, _, gcode = self._process_command_phase("sending", command, command_type, gcode=gcode)
|
||||
if not processed:
|
||||
results = self._process_command_phase("sending", command)
|
||||
|
||||
if command is None:
|
||||
# No, we are not going to send this, that was a last-minute bail.
|
||||
# However, since we already are in the send queue, our _monitor
|
||||
# loop won't be triggered with the reply from this unsent command
|
||||
# now, so we try to tickle the processing of any active
|
||||
# command queues manually
|
||||
self._continue_sending()
|
||||
if not results:
|
||||
# No, we are not going to send this, that was a last-minute bail.
|
||||
# However, since we already are in the send queue, our _monitor
|
||||
# loop won't be triggered with the reply from this unsent command
|
||||
# now, so we try to tickle the processing of any active
|
||||
# command queues manually
|
||||
self._continue_sending()
|
||||
|
||||
# and now let's fetch the next item from the queue
|
||||
continue
|
||||
# and now let's fetch the next item from the queue
|
||||
continue
|
||||
|
||||
if command.strip() == "":
|
||||
# we explicitly throw away plugin hook results that try
|
||||
# to perform command expansion in the sending/sent phase,
|
||||
# so "results" really should only have more than one entry
|
||||
# at this point if our core code contains a bug
|
||||
assert len(results) == 1
|
||||
|
||||
# we only use the first (and only!) entry here
|
||||
command = results[0]
|
||||
|
||||
if command.line.strip() == "":
|
||||
self._logger.info("Refusing to send an empty line to the printer")
|
||||
|
||||
# same here, tickle the queues manually
|
||||
@@ -838,11 +948,21 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
# and fetch the next item
|
||||
continue
|
||||
|
||||
# handle @ commands
|
||||
if isinstance(command, AtCommand):
|
||||
self._process_command_phase("sending", command)
|
||||
|
||||
# tickle...
|
||||
self._continue_sending()
|
||||
|
||||
# ... and fetch the next item
|
||||
continue
|
||||
|
||||
# now comes the part where we increase line numbers and send stuff - no turning back now
|
||||
if not self._transport.message_integrity:
|
||||
# transport does not have message integrity, let's see if we'll send a checksum
|
||||
command_requiring_checksum = gcode is not None and gcode.command in self.flavor.checksum_requiring_commands
|
||||
command_allowing_checksum = gcode is not None or self.flavor.unknown_with_checksum
|
||||
command_requiring_checksum = isinstance(command, GcodeCommand) and command.code in self.flavor.checksum_requiring_commands
|
||||
command_allowing_checksum = isinstance(command, GcodeCommand) or self.flavor.unknown_with_checksum
|
||||
checksum_enabled = self.flavor.always_send_checksum or (self.state == ProtocolState.PRINTING and not self.flavor.never_send_checksum)
|
||||
|
||||
send_with_checksum = command_requiring_checksum or (command_allowing_checksum and checksum_enabled)
|
||||
@@ -851,22 +971,22 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
# transport has message integrity, no checksum
|
||||
send_with_checksum = False
|
||||
|
||||
command_to_send = command.encode("ascii", errors="replace")
|
||||
command_to_send = command.line.encode("ascii", errors="replace")
|
||||
if send_with_checksum:
|
||||
self._do_increment_and_send_with_checksum(command_to_send)
|
||||
self._do_increment_and_send_with_checksum(to_str(command_to_send))
|
||||
else:
|
||||
self._do_send_without_checksum(command_to_send)
|
||||
self._do_send_without_checksum(to_str(command_to_send))
|
||||
|
||||
# trigger "sent" phase and use up one "ok"
|
||||
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)
|
||||
self._process_command_phase("sent", command)
|
||||
|
||||
# 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
|
||||
use_up_clear = self.flavor.unknown_requires_ack
|
||||
if gcode is not None and not gcode.unknown:
|
||||
if isinstance(command, GcodeCommand):
|
||||
use_up_clear = True
|
||||
|
||||
if use_up_clear:
|
||||
@@ -889,87 +1009,134 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
self._logger.exception("Caught an exception in the send loop")
|
||||
self.notify_listeners("on_protocol_log", self, "Closing down send loop")
|
||||
|
||||
def _process_command_phase(self, phase, command, command_type=None, gcode=None):
|
||||
if phase not in ("queuing", "queued", "sending", "sent"):
|
||||
return command, command_type, gcode
|
||||
def _log_command_phase(self, phase, command):
|
||||
if self._phase_logger.isEnabledFor(logging.DEBUG):
|
||||
self._phase_logger.debug("phase: {}, command: {!r}".format(phase, command))
|
||||
|
||||
if gcode is None:
|
||||
gcode = GcodeCommand.from_line(command)
|
||||
def _process_command_phase(self, phase, command, **kwargs):
|
||||
command = Command.from_line(command, **kwargs)
|
||||
results = [command]
|
||||
|
||||
self._log_command_phase(phase, command)
|
||||
|
||||
if phase not in ("queueing", "queued", "sending", "sent"):
|
||||
return results
|
||||
|
||||
# send it through the phase specific handlers provided by plugins
|
||||
for name, hook in self._gcode_hooks[phase].items():
|
||||
try:
|
||||
hook_result = hook(self, phase, command, command_type, gcode.command)
|
||||
except:
|
||||
self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals()))
|
||||
else:
|
||||
command, command_type, gcode = self._handle_command_handler_result(command, command_type, gcode.command, hook_result)
|
||||
if command is None:
|
||||
# hook handler return None as command, so we'll stop here and return a full out None result
|
||||
return None, None, None
|
||||
new_results = []
|
||||
for command in results:
|
||||
try:
|
||||
hook_results = hook(self,
|
||||
phase,
|
||||
str(command),
|
||||
command.type,
|
||||
command.code if isinstance(command, GcodeCommand) else None,
|
||||
subcode=command.subcode if isinstance(command, GcodeCommand) else None,
|
||||
tags=command.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, 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)
|
||||
else:
|
||||
new_results += normalized
|
||||
if not new_results:
|
||||
# hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
|
||||
return []
|
||||
results = new_results
|
||||
|
||||
# if it's a gcode command send it through the specific handler if it exists
|
||||
if gcode is not None:
|
||||
gcode_handler = "_gcode_" + gcode.command + "_" + phase
|
||||
if hasattr(self, gcode_handler):
|
||||
handler_result = getattr(self, gcode_handler)(command, cmd_type=command_type)
|
||||
command, command_type, gcode = self._handle_command_handler_result(command, command_type, gcode, handler_result)
|
||||
new_results = []
|
||||
modified = False
|
||||
for command in results:
|
||||
if isinstance(command, GcodeCommand) is not None:
|
||||
gcode_handler = "_gcode_" + command.code + "_" + phase
|
||||
if hasattr(self, gcode_handler):
|
||||
handler_results = getattr(self, gcode_handler)(command)
|
||||
new_results += normalize_command_handler_result(command, handler_results)
|
||||
modified = True
|
||||
else:
|
||||
new_results.append(command)
|
||||
else:
|
||||
new_results.append(command)
|
||||
|
||||
if modified:
|
||||
if not new_results:
|
||||
# gcode handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
|
||||
return []
|
||||
else:
|
||||
results = new_results
|
||||
|
||||
# send it through the phase specific command handler if it exists
|
||||
command_phase_handler = "_command_phase_" + phase
|
||||
if hasattr(self, command_phase_handler):
|
||||
handler_result = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode)
|
||||
command, command_type, gcode = self._handle_command_handler_result(command, command_type, gcode, handler_result)
|
||||
new_results = []
|
||||
for command in results:
|
||||
handler_results = getattr(self, command_phase_handler)(command)
|
||||
new_results += normalize_command_handler_result(command, handler_results)
|
||||
results = new_results
|
||||
|
||||
# finally return whatever we resulted on
|
||||
return command, command_type, gcode
|
||||
return results
|
||||
|
||||
def _handle_command_handler_result(self, command, command_type, gcode, handler_result):
|
||||
original_tuple = (command, command_type, gcode)
|
||||
def _process_atcommand_phase(self, phase, command):
|
||||
if (self._is_streaming()) or phase not in ("queuing", "sending"):
|
||||
return
|
||||
|
||||
if handler_result is None:
|
||||
# handler didn't return anything, we'll just continue
|
||||
return original_tuple
|
||||
# send it through the phase specific handlers provided by plugins
|
||||
for name, hook in self._atcommand_hooks[phase].items():
|
||||
try:
|
||||
hook(self, phase, command.atcommand, command.parameters, tags=command.tags)
|
||||
except:
|
||||
self._logger.exception("Error while processing hook {} for phase {} and command {}:".format(name, phase, command.atcommand))
|
||||
|
||||
if isinstance(handler_result, basestring):
|
||||
# handler did return just a string, we'll turn that into a 1-tuple now
|
||||
handler_result = (handler_result,)
|
||||
elif not isinstance(handler_result, (tuple, list)):
|
||||
# handler didn't return an expected result format, we'll just ignore it and continue
|
||||
return original_tuple
|
||||
|
||||
hook_result_length = len(handler_result)
|
||||
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
|
||||
else:
|
||||
# handler returned a tuple of an unexpected length
|
||||
return original_tuple
|
||||
|
||||
gcode = GcodeCommand.from_line(command)
|
||||
return command, command_type, gcode
|
||||
# trigger built-in handler if available
|
||||
handler = getattr(self, "_atcommand_{}_{}".format(command.atcommand, phase), None)
|
||||
if callable(handler):
|
||||
try:
|
||||
handler(command.atcommand, command.parameters, tags=command.tags)
|
||||
except:
|
||||
self._logger.exception("Error in handler for phase {} and command {}".format(phase, command.atcommand))
|
||||
|
||||
##~~ actual sending via serial
|
||||
|
||||
def _do_increment_and_send_with_checksum(self, cmd):
|
||||
def _do_increment_and_send_with_checksum(self, line):
|
||||
"""
|
||||
Args:
|
||||
line (str): the line to send
|
||||
"""
|
||||
with self._line_mutex:
|
||||
linenumber = self._current_linenumber
|
||||
self._add_to_last_lines(cmd)
|
||||
self._add_to_last_lines(line)
|
||||
self._current_linenumber += 1
|
||||
self._do_send_with_checksum(cmd, linenumber)
|
||||
self._do_send_with_checksum(line, linenumber)
|
||||
|
||||
def _do_send_with_checksum(self, cmd, lineNumber):
|
||||
command_to_send = b"N%d %s" % (lineNumber, cmd)
|
||||
def _do_send_with_checksum(self, line, line_number):
|
||||
"""
|
||||
Args:
|
||||
line (str): the line to send
|
||||
line_number (int): the line number to send
|
||||
"""
|
||||
command_to_send = b"N" + str(line_number) + b" " + line
|
||||
checksum = 0
|
||||
for c in command_to_send:
|
||||
checksum ^= ord(c)
|
||||
command_to_send = b"%s*%d" % (command_to_send, checksum)
|
||||
for c in bytearray(command_to_send):
|
||||
checksum ^= c
|
||||
command_to_send = command_to_send + b"*" + str(checksum)
|
||||
self._do_send_without_checksum(command_to_send)
|
||||
|
||||
def _do_send_without_checksum(self, data):
|
||||
"""
|
||||
Args:
|
||||
data (str): the data to send
|
||||
"""
|
||||
self._transport.write(data + b"\n")
|
||||
|
||||
def _add_to_last_lines(self, command):
|
||||
@@ -983,16 +1150,9 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
self._internal_state["current_tool"] = int(tool_match.group("value"))
|
||||
|
||||
def _gcode_G0_sent(self, cmd, cmd_type=None):
|
||||
if "Z" in cmd:
|
||||
match = regexes_parameters["floatZ"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
z = float(match.group("value"))
|
||||
if self._internal_state["current_z"] != z:
|
||||
self._internal_state["current_z"] = z
|
||||
# TODO self._callback.on_comm_z_change(z)
|
||||
except ValueError:
|
||||
pass
|
||||
if cmd.z is not None and self._internal_state["current_z"] != cmd.z:
|
||||
self._internal_state["current_z"] = cmd.z
|
||||
# TODO self._callback.on_comm_z_change(z)
|
||||
_gcode_G1_sent = _gcode_G0_sent
|
||||
|
||||
def _gcode_M0_queuing(self, cmd, cmd_type=None):
|
||||
@@ -1138,7 +1298,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
##~~ command phase handlers
|
||||
|
||||
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None):
|
||||
if gcode is not None and gcode.command in self.flavor.long_running_commands:
|
||||
if gcode is not None and gcode.code in self.flavor.long_running_commands:
|
||||
self._internal_state["long_running_command"] = True
|
||||
|
||||
##~~ helpers
|
||||
|
||||
@@ -12,7 +12,8 @@ import logging
|
||||
import time
|
||||
|
||||
|
||||
from octoprint.comm.protocol.gcode.util import GcodeCommand, regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
|
||||
from octoprint.comm.protocol.commands import GcodeCommand
|
||||
from octoprint.comm.protocol.gcode.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
|
||||
|
||||
# TODO needed? move?
|
||||
from octoprint.util import chunks
|
||||
|
||||
@@ -7,7 +7,11 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from octoprint.comm.protocol.gcode.util import strip_comment
|
||||
from octoprint.comm.protocol.gcode.util import strip_comment, GcodeCommand
|
||||
from octoprint.comm.protocol.commands import Command
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
|
||||
def process_gcode_line(line, offsets=None, current_tool=None):
|
||||
@@ -19,3 +23,157 @@ def process_gcode_line(line, offsets=None, current_tool=None):
|
||||
# line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
|
||||
|
||||
return line
|
||||
|
||||
def normalize_command_handler_result(command, handler_results, tags_to_add=None):
|
||||
"""
|
||||
Normalizes a command handler result.
|
||||
|
||||
Handler results can be either ``None``, a single result entry or a list of result
|
||||
entries.
|
||||
|
||||
``None`` results are ignored, the provided ``command``, ``command_type``,
|
||||
``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.
|
||||
|
||||
The method returns a list of normalized result entries. Normalized result
|
||||
entries always are a 4-tuple consisting of ``command``, ``command_type``,
|
||||
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
|
||||
be empty in which case the command is to be suppressed.
|
||||
|
||||
Examples:
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, None)
|
||||
[(u'M105', None, u'M105', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, "M110")
|
||||
[(u'M110', None, u'M110', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, ["M110"])
|
||||
[(u'M110', None, u'M110', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, ["M110", "M117 Foobar"])
|
||||
[(u'M110', None, u'M110', None, None), (u'M117 Foobar', None, u'M117', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), "M117 Foobar"])
|
||||
[(u'M110', None, u'M110', None, None), (u'M117 Foobar', None, u'M117', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, [("M110", "lineno_reset"), "M117 Foobar"])
|
||||
[(u'M110', u'lineno_reset', u'M110', None, None), (u'M117 Foobar', None, u'M117', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, [])
|
||||
[]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, ["M110", None])
|
||||
[(u'M110', None, u'M110', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), (None, "ignored")])
|
||||
[(u'M110', None, u'M110', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")])
|
||||
[(u'M110', None, u'M110', None, None), (u'M117 Foobar', u'display_message', u'M117', None, None), (u'M110', u'lineno_reset', u'M110', None, None)]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M117 Foobar"])
|
||||
[(u'M110', None, u'M110', None, set([u'tag1', u'tag2'])), (u'M117 Foobar', None, u'M117', None, set([u'tag1', u'tag2']))]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M105", "M117 Foobar"], tags_to_add={"tag3"})
|
||||
[(u'M110', None, u'M110', None, set([u'tag1', u'tag2', u'tag3'])), (u'M105', None, u'M105', None, set([u'tag1', u'tag2'])), (u'M117 Foobar', None, u'M117', None, set([u'tag1', u'tag2', u'tag3']))]
|
||||
>>> normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", ("M105", "temperature_poll"), "M117 Foobar"], tags_to_add={"tag3"})
|
||||
[(u'M110', None, u'M110', None, set([u'tag1', u'tag2', u'tag3'])), (u'M105', u'temperature_poll', u'M105', None, set([u'tag1', u'tag2', u'tag3'])), (u'M117 Foobar', None, u'M117', None, set([u'tag1', u'tag2', u'tag3']))]
|
||||
|
||||
Arguments:
|
||||
command (unicode or Command or None): The command for which the handler result was
|
||||
generated
|
||||
command_type (unicode or None): The command type for which the handler
|
||||
result was generated
|
||||
gcode (unicode or None): The GCODE for which the handler result was
|
||||
generated
|
||||
subcode (unicode or None): The GCODE subcode for which the handler result
|
||||
was generated
|
||||
tags (set of unicode 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 unicode or None): List of tags to add to expanded result
|
||||
entries
|
||||
|
||||
Returns:
|
||||
(list) - A list of normalized handler result entries, which are
|
||||
5-tuples consisting of ``command``, ``command_type``, ``gcode``
|
||||
``subcode`` and ``tags``, the latter three of which may be ``None``.
|
||||
"""
|
||||
|
||||
original = command
|
||||
|
||||
if handler_results is None:
|
||||
# handler didn't return anything, we'll just continue
|
||||
return [original]
|
||||
|
||||
if not isinstance(handler_results, list):
|
||||
handler_results = [handler_results,]
|
||||
|
||||
result = []
|
||||
for handler_result in handler_results:
|
||||
# we iterate over all handler result entries and process each one
|
||||
# individually here
|
||||
|
||||
if handler_result is None:
|
||||
# entry is None, we'll ignore that entry and continue
|
||||
continue
|
||||
|
||||
if command.tags:
|
||||
# copy the tags
|
||||
tags = set(command.tags)
|
||||
|
||||
def expand_tags(tags, tags_to_add):
|
||||
tags = tags.copy()
|
||||
if tags_to_add and isinstance(tags_to_add, set):
|
||||
tags |= tags_to_add
|
||||
return tags
|
||||
|
||||
if isinstance(handler_result, basestring):
|
||||
# entry is just a string, replace command with it
|
||||
if handler_result != original.line:
|
||||
# command changed, swap it
|
||||
command = Command.from_line(handler_result, type=original.type, tags=expand_tags(original.tags, tags_to_add))
|
||||
result.append(command)
|
||||
|
||||
elif isinstance(handler_result, Command):
|
||||
if handler_result != original:
|
||||
command = handler_result.copy()
|
||||
command.tags = expand_tags(original.tags, tags_to_add)
|
||||
result.append(command)
|
||||
|
||||
elif isinstance(handler_result, tuple):
|
||||
# entry is a tuple, extract command and command_type
|
||||
hook_result_length = len(handler_result)
|
||||
|
||||
command_line = original.line
|
||||
command_type = original.type
|
||||
command_tags = original.tags
|
||||
|
||||
if hook_result_length == 1:
|
||||
# handler returned just the command
|
||||
command_line, = handler_result
|
||||
elif hook_result_length == 2:
|
||||
# handler returned command and command_type
|
||||
command_line, command_type = handler_result
|
||||
elif hook_result_length == 3:
|
||||
# handler returned command, command type and additional tags
|
||||
command_line, command_type, command_tags = handler_result
|
||||
else:
|
||||
# handler returned a tuple of an unexpected length, ignore
|
||||
# and continue
|
||||
continue
|
||||
|
||||
if command_line is None:
|
||||
# command is None, ignore it and continue
|
||||
continue
|
||||
|
||||
if command_line != original.line or command_type != original.type:
|
||||
# command or command_type changed, tags need to be rewritten
|
||||
command_tags = expand_tags(command_tags, tags_to_add)
|
||||
|
||||
result.append(Command.from_line(command_line, type=command_type, tags=command_tags))
|
||||
|
||||
# reset to original
|
||||
command, command_type, gcode, subcode, tags = original
|
||||
|
||||
return result
|
||||
@@ -15,11 +15,11 @@ from octoprint.events import eventManager, Events
|
||||
|
||||
from .destinations import FileDestinations
|
||||
from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
@@ -593,7 +593,7 @@ class FileManager(object):
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def create_print_job(self, destination, path, user=None):
|
||||
return self._storage(destination).get_print_job(path, user=user)
|
||||
return self._storage(destination).create_print_job(path, user=user)
|
||||
|
||||
def has_analysis(self, destination, path):
|
||||
return self._storage(destination).has_analysis(path)
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
try:
|
||||
from os import scandir, walk
|
||||
except ImportError:
|
||||
from scandir import scandir, walk
|
||||
|
||||
|
||||
class Storage(object):
|
||||
"""
|
||||
Interface of storage adapters for OctoPrint.
|
||||
"""
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
"""
|
||||
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
|
||||
|
||||
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
|
||||
to recurse into folders if your storage adapter supports those.
|
||||
|
||||
:return: an iterator yielding all un-analysed files in the storage
|
||||
"""
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
# noinspection PyUnreachableCode
|
||||
yield
|
||||
|
||||
def analysis_backlog_for_path(self, path=None):
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
# noinspection PyUnreachableCode
|
||||
yield
|
||||
|
||||
def last_modified(self, path=None, recursive=False):
|
||||
"""
|
||||
Get the last modification date of the specified ``path`` or ``path``'s subtree.
|
||||
|
||||
Args:
|
||||
path (str or None): Path for which to determine the subtree's last modification date. If left out or
|
||||
set to None, defatuls to storage root.
|
||||
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
|
||||
the whole ``path``'s subtree (True).
|
||||
|
||||
Returns: (float) The last modification date of the indicated subtree
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def file_in_path(self, path, filepath):
|
||||
"""
|
||||
Returns whether the file indicated by ``file`` is inside ``path`` or not.
|
||||
:param string path: the path to check
|
||||
:param string filepath: path to the file
|
||||
:return: ``True`` if the file is inside the path, ``False`` otherwise
|
||||
"""
|
||||
return NotImplementedError()
|
||||
|
||||
def file_exists(self, path):
|
||||
"""
|
||||
Returns whether the file indicated by ``path`` exists or not.
|
||||
:param string path: the path to check for existence
|
||||
:return: ``True`` if the file exists, ``False`` otherwise
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def folder_exists(self, path):
|
||||
"""
|
||||
Returns whether the folder indicated by ``path`` exists or not.
|
||||
:param string path: the path to check for existence
|
||||
:return: ``True`` if the folder exists, ``False`` otherwise
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def list_files(self, path=None, filter=None, recursive=True):
|
||||
"""
|
||||
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
|
||||
subfolders.
|
||||
|
||||
An optional filter function can be supplied which will be called with a file name and file data and which has
|
||||
to return True if the file is to be included in the result or False if not.
|
||||
|
||||
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
|
||||
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
|
||||
|
||||
{
|
||||
"some_folder": {
|
||||
"name": "some_folder",
|
||||
"path": "some_folder",
|
||||
"type": "folder",
|
||||
"children": {
|
||||
"some_sub_folder": {
|
||||
"name": "some_sub_folder",
|
||||
"path": "some_folder/some_sub_folder",
|
||||
"type": "folder",
|
||||
"typePath": ["folder"],
|
||||
"children": { ... }
|
||||
},
|
||||
"some_file.gcode": {
|
||||
"name": "some_file.gcode",
|
||||
"path": "some_folder/some_file.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [ ... ],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
"test.gcode": {
|
||||
"name": "test.gcode",
|
||||
"path": "test.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
"test.stl": {
|
||||
"name": "test.stl",
|
||||
"path": "test.stl",
|
||||
"type": "model",
|
||||
"typePath": ["model", "stl"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
|
||||
from root of base folder
|
||||
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
|
||||
filtering will take place
|
||||
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
|
||||
do one step down into sub folders to be able to populate the ``children``.
|
||||
:return: a dictionary mapping entry names to entry data that represents the whole file list
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
"""
|
||||
Adds a folder as ``path``
|
||||
|
||||
The ``path`` will be sanitized.
|
||||
|
||||
:param string path: the path of the new folder
|
||||
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
|
||||
:param unicode display: display name of the folder
|
||||
:return: the sanitized name of the new folder to be used for future references to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
"""
|
||||
Removes the folder at ``path``
|
||||
|
||||
:param string path: the path of the folder to remove
|
||||
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
|
||||
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_folder(self, source, destination):
|
||||
"""
|
||||
Copies the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the path in the storage to the copy of the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def move_folder(self, source, destination):
|
||||
"""
|
||||
Moves the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the new path in the storage to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
"""
|
||||
Adds the file ``file_object`` as ``path``
|
||||
|
||||
:param string path: the file's new path, will be sanitized
|
||||
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
|
||||
where the object should then store its contents
|
||||
:param object printer_profile: the printer profile associated with this file (if any)
|
||||
:param list links: any links to add with the file
|
||||
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
|
||||
and its metadata will just be silently overwritten
|
||||
:param unicode display: display name of the file
|
||||
:return: the sanitized name of the file to be used for future references to it
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_file(self, path):
|
||||
"""
|
||||
Removes the file at ``path``
|
||||
|
||||
Will also take care of deleting the corresponding entries
|
||||
in the metadata and deleting all links pointing to the file.
|
||||
|
||||
:param string path: path of the file to remove
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_file(self, source, destination):
|
||||
"""
|
||||
Copies the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the path in the storage to the copy of the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def move_file(self, source, destination):
|
||||
"""
|
||||
Moves the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the new path in the storage to the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def has_analysis(self, path):
|
||||
"""
|
||||
Returns whether the file at path has been analysed yet
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def create_print_job(self, path, user=None):
|
||||
"""
|
||||
Retrieves the :class:`~octoprint.job.PrintJob` instance
|
||||
to use for printing ``path``.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_metadata(self, path):
|
||||
"""
|
||||
Retrieves the metadata for the file ``path``.
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
:return: the metadata associated with the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_link(self, path, rel, data):
|
||||
"""
|
||||
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
|
||||
|
||||
The following relation types are currently supported:
|
||||
|
||||
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
|
||||
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
|
||||
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
|
||||
referring to ``name`` and its hash will also be added to the linked ``model`` file
|
||||
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
|
||||
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
|
||||
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
|
||||
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
|
||||
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
|
||||
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
|
||||
attribute describing when the content was retrieved
|
||||
|
||||
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
|
||||
as machine code will be refused.
|
||||
|
||||
:param path: path of the file for which to add a link
|
||||
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to add
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_link(self, path, rel, data):
|
||||
"""
|
||||
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
|
||||
|
||||
:param path: path of the file from which to remove the link
|
||||
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to remove, must match existing link
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
|
||||
"""
|
||||
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
|
||||
|
||||
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
|
||||
|
||||
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
|
||||
the two dictionaries will be merged recursively.
|
||||
|
||||
:param path: the virtual path to the file for which to add additional metadata
|
||||
:param key: key of metadata to add
|
||||
:param data: metadata to add
|
||||
:param overwrite: if True and ``key`` already exists, it will be overwritten
|
||||
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
|
||||
will be merged
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_additional_metadata(self, path, key):
|
||||
"""
|
||||
Removes additional metadata under ``key`` for ``name`` on ``path``
|
||||
|
||||
:param path: the virtual path to the file for which to remove the metadata under ``key``
|
||||
:param key: the key to remove
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def canonicalize(self, path):
|
||||
"""
|
||||
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
|
||||
implementation must separate those if necessary.
|
||||
|
||||
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
|
||||
of stripping any invalid characters.
|
||||
|
||||
Args:
|
||||
path: the path to canonicalize
|
||||
|
||||
Returns:
|
||||
a 2-tuple containing the canonicalized path and file name
|
||||
|
||||
"""
|
||||
return self.sanitize(path)
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
|
||||
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
|
||||
|
||||
:param string path: the path to sanitize
|
||||
:return: a 2-tuple containing the sanitized path and file name
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_path(self, path):
|
||||
"""
|
||||
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
|
||||
:param string path: the path to sanitize
|
||||
:return: the sanitized path
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Sanitizes the given file ``name``, stripping it of all invalid characters.
|
||||
:param string name: the file name to sanitize
|
||||
:return: the sanitized name
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def split_path(self, path):
|
||||
"""
|
||||
Split ``path`` into base directory and file name.
|
||||
:param path: the path to split
|
||||
:return: a tuple (base directory, file name)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def join_path(self, *path):
|
||||
"""
|
||||
Join path elements together
|
||||
:param path: path elements to join
|
||||
:return: joined representation of the path to be usable as fully qualified path for further operations
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def path_on_disk(self, path):
|
||||
"""
|
||||
Retrieves the path on disk for ``path``.
|
||||
|
||||
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
|
||||
raise an :class:`io.UnsupportedOperation`
|
||||
|
||||
Opposite of :func:`path_in_storage`.
|
||||
|
||||
:param string path: the virtual path for which to retrieve the path on disk
|
||||
:return: the path on disk to ``path``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def path_in_storage(self, path):
|
||||
"""
|
||||
Retrieves the equivalent in the storage adapter for ``path``.
|
||||
|
||||
Opposite of :func:`path_on_disk`.
|
||||
|
||||
:param string path: the path for which to retrieve the storage path
|
||||
:return: the path in storage to ``path``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
UNKNOWN = "unknown"
|
||||
INVALID_DIRECTORY = "invalid_directory"
|
||||
INVALID_FILE = "invalid_file"
|
||||
INVALID_SOURCE = "invalid_source"
|
||||
INVALID_DESTINATION = "invalid_destination"
|
||||
DOES_NOT_EXIST = "does_not_exist"
|
||||
ALREADY_EXISTS = "already_exists"
|
||||
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
|
||||
NOT_EMPTY = "not_empty"
|
||||
|
||||
def __init__(self, message, code=None, cause=None):
|
||||
BaseException.__init__(self)
|
||||
self.message = message
|
||||
self.cause = cause
|
||||
|
||||
if code is None:
|
||||
code = StorageError.UNKNOWN
|
||||
self.code = code
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import logging
|
||||
import os
|
||||
import pylru
|
||||
@@ -21,6 +19,7 @@ from octoprint.util import atomic_write
|
||||
from contextlib import contextmanager
|
||||
from copy import deepcopy
|
||||
|
||||
# noinspection PyCompatibility
|
||||
from past.builtins import basestring
|
||||
|
||||
from emoji import demojize
|
||||
@@ -30,424 +29,10 @@ import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path, to_unicode
|
||||
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
Interface of storage adapters for OctoPrint.
|
||||
"""
|
||||
from . import Storage, StorageError
|
||||
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
"""
|
||||
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
|
||||
|
||||
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
|
||||
to recurse into folders if your storage adapter supports those.
|
||||
|
||||
:return: an iterator yielding all un-analysed files in the storage
|
||||
"""
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
yield
|
||||
|
||||
def analysis_backlog_for_path(self, path=None):
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
yield
|
||||
|
||||
def last_modified(self, path=None, recursive=False):
|
||||
"""
|
||||
Get the last modification date of the specified ``path`` or ``path``'s subtree.
|
||||
|
||||
Args:
|
||||
path (str or None): Path for which to determine the subtree's last modification date. If left out or
|
||||
set to None, defatuls to storage root.
|
||||
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
|
||||
the whole ``path``'s subtree (True).
|
||||
|
||||
Returns: (float) The last modification date of the indicated subtree
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def file_in_path(self, path, filepath):
|
||||
"""
|
||||
Returns whether the file indicated by ``file`` is inside ``path`` or not.
|
||||
:param string path: the path to check
|
||||
:param string filepath: path to the file
|
||||
:return: ``True`` if the file is inside the path, ``False`` otherwise
|
||||
"""
|
||||
return NotImplementedError()
|
||||
|
||||
def file_exists(self, path):
|
||||
"""
|
||||
Returns whether the file indicated by ``path`` exists or not.
|
||||
:param string path: the path to check for existence
|
||||
:return: ``True`` if the file exists, ``False`` otherwise
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def folder_exists(self, path):
|
||||
"""
|
||||
Returns whether the folder indicated by ``path`` exists or not.
|
||||
:param string path: the path to check for existence
|
||||
:return: ``True`` if the folder exists, ``False`` otherwise
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def list_files(self, path=None, filter=None, recursive=True):
|
||||
"""
|
||||
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
|
||||
subfolders.
|
||||
|
||||
An optional filter function can be supplied which will be called with a file name and file data and which has
|
||||
to return True if the file is to be included in the result or False if not.
|
||||
|
||||
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
|
||||
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
|
||||
|
||||
{
|
||||
"some_folder": {
|
||||
"name": "some_folder",
|
||||
"path": "some_folder",
|
||||
"type": "folder",
|
||||
"children": {
|
||||
"some_sub_folder": {
|
||||
"name": "some_sub_folder",
|
||||
"path": "some_folder/some_sub_folder",
|
||||
"type": "folder",
|
||||
"typePath": ["folder"],
|
||||
"children": { ... }
|
||||
},
|
||||
"some_file.gcode": {
|
||||
"name": "some_file.gcode",
|
||||
"path": "some_folder/some_file.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [ ... ],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
"test.gcode": {
|
||||
"name": "test.gcode",
|
||||
"path": "test.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
"test.stl": {
|
||||
"name": "test.stl",
|
||||
"path": "test.stl",
|
||||
"type": "model",
|
||||
"typePath": ["model", "stl"],
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
|
||||
from root of base folder
|
||||
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
|
||||
filtering will take place
|
||||
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
|
||||
do one step down into sub folders to be able to populate the ``children``.
|
||||
:return: a dictionary mapping entry names to entry data that represents the whole file list
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_folder(self, path, ignore_existing=True, display=None):
|
||||
"""
|
||||
Adds a folder as ``path``
|
||||
|
||||
The ``path`` will be sanitized.
|
||||
|
||||
:param string path: the path of the new folder
|
||||
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
|
||||
:param unicode display: display name of the folder
|
||||
:return: the sanitized name of the new folder to be used for future references to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
"""
|
||||
Removes the folder at ``path``
|
||||
|
||||
:param string path: the path of the folder to remove
|
||||
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
|
||||
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_folder(self, source, destination):
|
||||
"""
|
||||
Copies the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the path in the storage to the copy of the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def move_folder(self, source, destination):
|
||||
"""
|
||||
Moves the folder ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source folder
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the new path in the storage to the folder
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
|
||||
"""
|
||||
Adds the file ``file_object`` as ``path``
|
||||
|
||||
:param string path: the file's new path, will be sanitized
|
||||
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
|
||||
where the object should then store its contents
|
||||
:param object printer_profile: the printer profile associated with this file (if any)
|
||||
:param list links: any links to add with the file
|
||||
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
|
||||
and its metadata will just be silently overwritten
|
||||
:param unicode display: display name of the file
|
||||
:return: the sanitized name of the file to be used for future references to it
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_file(self, path):
|
||||
"""
|
||||
Removes the file at ``path``
|
||||
|
||||
Will also take care of deleting the corresponding entries
|
||||
in the metadata and deleting all links pointing to the file.
|
||||
|
||||
:param string path: path of the file to remove
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def copy_file(self, source, destination):
|
||||
"""
|
||||
Copies the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the path in the storage to the copy of the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def move_file(self, source, destination):
|
||||
"""
|
||||
Moves the file ``source`` to ``destination``
|
||||
|
||||
:param string source: path to the source file
|
||||
:param string destination: path to destination
|
||||
|
||||
:return: the new path in the storage to the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def has_analysis(self, path):
|
||||
"""
|
||||
Returns whether the file at path has been analysed yet
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_print_job(self, path, user=None):
|
||||
"""
|
||||
Retrieves the :class:`~octoprint.job.PrintJob` instance
|
||||
to use for printing ``path``.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_metadata(self, path):
|
||||
"""
|
||||
Retrieves the metadata for the file ``path``.
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
:return: the metadata associated with the file
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_link(self, path, rel, data):
|
||||
"""
|
||||
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
|
||||
|
||||
The following relation types are currently supported:
|
||||
|
||||
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
|
||||
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
|
||||
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
|
||||
referring to ``name`` and its hash will also be added to the linked ``model`` file
|
||||
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
|
||||
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
|
||||
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
|
||||
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
|
||||
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
|
||||
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
|
||||
attribute describing when the content was retrieved
|
||||
|
||||
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
|
||||
as machine code will be refused.
|
||||
|
||||
:param path: path of the file for which to add a link
|
||||
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to add
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_link(self, path, rel, data):
|
||||
"""
|
||||
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
|
||||
|
||||
:param path: path of the file from which to remove the link
|
||||
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to remove, must match existing link
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
|
||||
"""
|
||||
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
|
||||
|
||||
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
|
||||
|
||||
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
|
||||
the two dictionaries will be merged recursively.
|
||||
|
||||
:param path: the virtual path to the file for which to add additional metadata
|
||||
:param key: key of metadata to add
|
||||
:param data: metadata to add
|
||||
:param overwrite: if True and ``key`` already exists, it will be overwritten
|
||||
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
|
||||
will be merged
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_additional_metadata(self, path, key):
|
||||
"""
|
||||
Removes additional metadata under ``key`` for ``name`` on ``path``
|
||||
|
||||
:param path: the virtual path to the file for which to remove the metadata under ``key``
|
||||
:param key: the key to remove
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def canonicalize(self, path):
|
||||
"""
|
||||
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
|
||||
implementation must separate those if necessary.
|
||||
|
||||
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
|
||||
of stripping any invalid characters.
|
||||
|
||||
Args:
|
||||
path: the path to canonicalize
|
||||
|
||||
Returns:
|
||||
a 2-tuple containing the canonicalized path and file name
|
||||
|
||||
"""
|
||||
return self.sanitize(path)
|
||||
|
||||
def sanitize(self, path):
|
||||
"""
|
||||
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
|
||||
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
|
||||
|
||||
:param string path: the path to sanitize
|
||||
:return: a 2-tuple containing the sanitized path and file name
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_path(self, path):
|
||||
"""
|
||||
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
|
||||
:param string path: the path to sanitize
|
||||
:return: the sanitized path
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Sanitizes the given file ``name``, stripping it of all invalid characters.
|
||||
:param string name: the file name to sanitize
|
||||
:return: the sanitized name
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def split_path(self, path):
|
||||
"""
|
||||
Split ``path`` into base directory and file name.
|
||||
:param path: the path to split
|
||||
:return: a tuple (base directory, file name)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def join_path(self, *path):
|
||||
"""
|
||||
Join path elements together
|
||||
:param path: path elements to join
|
||||
:return: joined representation of the path to be usable as fully qualified path for further operations
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def path_on_disk(self, path):
|
||||
"""
|
||||
Retrieves the path on disk for ``path``.
|
||||
|
||||
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
|
||||
raise an :class:`io.UnsupportedOperation`
|
||||
|
||||
Opposite of :func:`path_in_storage`.
|
||||
|
||||
:param string path: the virtual path for which to retrieve the path on disk
|
||||
:return: the path on disk to ``path``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def path_in_storage(self, path):
|
||||
"""
|
||||
Retrieves the equivalent in the storage adapter for ``path``.
|
||||
|
||||
Opposite of :func:`path_on_disk`.
|
||||
|
||||
:param string path: the path for which to retrieve the storage path
|
||||
:return: the path in storage to ``path``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
UNKNOWN = "unknown"
|
||||
INVALID_DIRECTORY = "invalid_directory"
|
||||
INVALID_FILE = "invalid_file"
|
||||
INVALID_SOURCE = "invalid_source"
|
||||
INVALID_DESTINATION = "invalid_destination"
|
||||
DOES_NOT_EXIST = "does_not_exist"
|
||||
ALREADY_EXISTS = "already_exists"
|
||||
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
|
||||
NOT_EMPTY = "not_empty"
|
||||
|
||||
def __init__(self, message, code=None, cause=None):
|
||||
BaseException.__init__(self)
|
||||
self.message = message
|
||||
self.cause = cause
|
||||
|
||||
if code is None:
|
||||
code = StorageError.UNKNOWN
|
||||
self.code = code
|
||||
|
||||
|
||||
class LocalFileStorage(StorageInterface):
|
||||
class LocalFileStorage(Storage):
|
||||
"""
|
||||
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
|
||||
|
||||
@@ -473,7 +58,7 @@ class LocalFileStorage(StorageInterface):
|
||||
text = demojize(text, delimiters=(u"", u""))
|
||||
return cls._SLUGIFY(text)
|
||||
|
||||
def __init__(self, basefolder, create=False):
|
||||
def __init__(self, basefolder, create=False, key="local"):
|
||||
"""
|
||||
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
|
||||
if necessary and ``create`` is set to ``True``.
|
||||
@@ -854,7 +439,7 @@ class LocalFileStorage(StorageInterface):
|
||||
metadata = self.get_metadata(path)
|
||||
return "analysis" in metadata
|
||||
|
||||
def get_print_job(self, path, user=None):
|
||||
def create_print_job(self, path, user=None):
|
||||
from octoprint.job import LocalGcodeFilePrintjob
|
||||
return LocalGcodeFilePrintjob(self.path_on_disk(path),
|
||||
"local",
|
||||
@@ -1632,9 +1217,3 @@ class LocalFileStorage(StorageInterface):
|
||||
else:
|
||||
self._metadata_locks[path] = (counter, lock)
|
||||
|
||||
|
||||
class PrinterSDStorage(StorageInterface):
|
||||
|
||||
def get_print_job(self, path):
|
||||
from octoprint.job import SDFilePrintjob
|
||||
return SDFilePrintjob("/" + path)
|
||||
@@ -0,0 +1,14 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from . import Storage, StorageError
|
||||
|
||||
|
||||
class PrinterSDStorage(Storage):
|
||||
def create_print_job(self, path, user=None):
|
||||
from octoprint.job import SDFilePrintjob
|
||||
return SDFilePrintjob("/" + path, user=user)
|
||||
@@ -116,14 +116,23 @@ class Printjob(ProtocolListener, ListenerAware):
|
||||
self.notify_listeners("on_job_done", self)
|
||||
self.reset_job()
|
||||
|
||||
def process_job_cancelled(self):
|
||||
self.notify_listeners("on_job_cancelled", self)
|
||||
self.reset_job()
|
||||
|
||||
def process_job_failed(self):
|
||||
self.notify_listeners("on_job_failed", self)
|
||||
self.reset_job()
|
||||
|
||||
def process_job_cancelling(self, firmware_error=None):
|
||||
self.notify_listeners("on_job_cancelling", self, firmware_error=firmware_error)
|
||||
|
||||
def process_job_cancelled(self, cancel_position=None):
|
||||
self.notify_listeners("on_job_cancelled", self, cancel_position=cancel_position)
|
||||
self.reset_job()
|
||||
|
||||
def process_job_paused(self, pause_position=None):
|
||||
self.notify_listeners("on_job_paused", self, pause_position=pause_position)
|
||||
|
||||
def process_job_resumed(self):
|
||||
self.notify_listeners("on_job_resumed", self)
|
||||
|
||||
def process_job_progress(self):
|
||||
self.notify_listeners("on_job_progress", self)
|
||||
|
||||
@@ -179,6 +188,7 @@ class LocalFilePrintjob(StoragePrintjob):
|
||||
|
||||
@property
|
||||
def pos(self):
|
||||
# TODO manual pos tracking
|
||||
return self._handle.tell() if self._handle is not None else 0
|
||||
|
||||
@property
|
||||
@@ -246,6 +256,7 @@ class LocalFilePrintjob(StoragePrintjob):
|
||||
def reset_job(self):
|
||||
super(LocalFilePrintjob, self).reset_job()
|
||||
self.close()
|
||||
self._pos = self._read_lines = 0
|
||||
|
||||
class LocalGcodeFilePrintjob(LocalFilePrintjob):
|
||||
|
||||
@@ -283,12 +294,13 @@ class LocalGcodeStreamjob(LocalGcodeFilePrintjob):
|
||||
|
||||
class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener):
|
||||
|
||||
def __init__(self, path, status_interval=2.0):
|
||||
def __init__(self, path, status_interval=2.0, *args, **kwargs):
|
||||
name = path
|
||||
if name.startswith("/"):
|
||||
name = name[1:]
|
||||
|
||||
StoragePrintjob.__init__(self,
|
||||
"sdcard",
|
||||
name,
|
||||
name=name,
|
||||
event_data=dict(name=name,
|
||||
@@ -373,10 +385,19 @@ class PrintjobListener(object):
|
||||
def on_job_done(self, job):
|
||||
pass
|
||||
|
||||
def on_job_cancelled(self, job):
|
||||
def on_job_failed(self, job):
|
||||
pass
|
||||
|
||||
def on_job_failed(self, job):
|
||||
def on_job_cancelling(self, job, firmware_error=None):
|
||||
pass
|
||||
|
||||
def on_job_cancelled(self, job, cancel_position=None):
|
||||
pass
|
||||
|
||||
def on_job_paused(self, job, pause_position=None):
|
||||
pass
|
||||
|
||||
def on_job_resumed(self, job):
|
||||
pass
|
||||
|
||||
def on_job_progress(self, job):
|
||||
|
||||
@@ -461,12 +461,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
|
||||
def feed_rate(self, factor, *args, **kwargs):
|
||||
factor = self._convert_rate_value(factor, min=50, max=200)
|
||||
self._protocol.set_feedrate_multiplier(factor,
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.feed_rate"})
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.feed_rate"})
|
||||
|
||||
def flow_rate(self, factor, *args, **kwargs):
|
||||
factor = self._convert_rate_value(factor, min=75, max=125)
|
||||
self._protocol.set_extrusion_multiplier(factor,
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"})
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"})
|
||||
|
||||
def select_job(self, job, start_printing=False, pos=None, *args, **kwargs):
|
||||
self._update_job(job)
|
||||
@@ -477,7 +477,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
|
||||
eventManager().fire(Events.FILE_SELECTED, event_payload)
|
||||
|
||||
if start_printing and self.is_ready():
|
||||
self.start_print(pos=pos)
|
||||
self.start_print(pos=pos,
|
||||
tags=kwargs.get("tags", set()))
|
||||
|
||||
def unselect_job(self):
|
||||
self._remove_job()
|
||||
@@ -485,23 +486,21 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
|
||||
|
||||
eventManager().fire(Events.FILE_DESELECTED)
|
||||
|
||||
# TODO add a since to the deprecation message as soon as the version this stuff will be included in is defined
|
||||
@util.deprecated("select_file has been deprecated, use select_job instead", includedoc="Replaced by :func:`select_job`")
|
||||
def select_file(self, path, sd, printAfterSelect=False, pos=None):
|
||||
@util.deprecated("select_file has been deprecated, use select_job instead",
|
||||
includedoc="Replaced by :func:`select_job`",
|
||||
since="1.4.0")
|
||||
def select_file(self, path, sd, printAfterSelect=False, pos=None, user=None):
|
||||
if sd:
|
||||
job = SDFilePrintjob("/" + path)
|
||||
storage = "sdcard"
|
||||
else:
|
||||
full_path = os.path.join(settings().getBaseFolder("uploads"), path)
|
||||
job = LocalGcodeFilePrintjob(full_path,
|
||||
name=path,
|
||||
event_data=dict(name=os.path.basename(full_path),
|
||||
path=path,
|
||||
origin="local"))
|
||||
storage = "local"
|
||||
|
||||
job = self._file_manager.create_print_job(storage, path, user=user)
|
||||
self.select_job(job, start_printing=printAfterSelect, pos=pos)
|
||||
|
||||
# TODO add a since to the deprecation message as soon as the version this stuff will be included in is defined
|
||||
unselect_file = util.deprecated("unselect_file has been deprecated, use unselect_job instead", includedoc="Replaced by :func:`unselect_job`")(unselect_job)
|
||||
unselect_file = util.deprecated("unselect_file has been deprecated, use unselect_job instead",
|
||||
includedoc="Replaced by :func:`unselect_job`",
|
||||
since="1.4.0")(unselect_job)
|
||||
|
||||
def start_print(self, pos=None, user=None, *args, **kwargs):
|
||||
"""
|
||||
@@ -1106,40 +1105,73 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
|
||||
if job != self._job.job:
|
||||
return
|
||||
|
||||
# TODO include position in payload if available
|
||||
payload = job.event_payload()
|
||||
if payload:
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def on_comm_print_job_cancelling(self, firmware_error=None):
|
||||
payload = self._payload_for_print_job_event()
|
||||
def on_job_cancelling(self, job, firmware_error=None):
|
||||
if job != self._job.job:
|
||||
return
|
||||
|
||||
payload = job.event_payload()
|
||||
if payload:
|
||||
if firmware_error:
|
||||
payload["firmwareError"] = firmware_error
|
||||
eventManager().fire(Events.PRINT_CANCELLING, payload)
|
||||
|
||||
def on_job_cancelled(self, job):
|
||||
def on_job_cancelled(self, job, cancel_position=None):
|
||||
if job != self._job.job:
|
||||
return
|
||||
|
||||
self._update_progress_data()
|
||||
|
||||
# TODO include position in payload if available
|
||||
payload = job.event_payload()
|
||||
if payload:
|
||||
payload["time"] = job.elapsed
|
||||
if cancel_position:
|
||||
payload["position"] = cancel_position
|
||||
|
||||
eventManager().fire(Events.PRINT_CANCELLED, payload)
|
||||
self.script("afterPrintCancelled",
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
def finalize():self._file_manager.log_print(self._get_origin_for_job(),
|
||||
self._job.job.name,
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printer_profile_manager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
def finalize():
|
||||
self._file_manager.log_print(job.storage,
|
||||
job.name,
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printer_profile_manager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
thread = threading.Thread(target=finalize)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def on_job_paused(self, job, pause_position=None):
|
||||
if job != self._job.job:
|
||||
return
|
||||
|
||||
payload = job.event_payload()
|
||||
if payload:
|
||||
if pause_position:
|
||||
payload["position"] = pause_position
|
||||
eventManager().fire(Events.PRINT_PAUSED, payload)
|
||||
self.script("afterPrintPaused",
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
def on_job_resumed(self, job):
|
||||
if job != self._job.job:
|
||||
return
|
||||
|
||||
payload = job.event_payload()
|
||||
if payload:
|
||||
eventManager().fire(Events.PRINT_RESUMED, payload)
|
||||
self.script("beforePrintResumed",
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
#~~ comm.MachineComPrintCallback implementation
|
||||
|
||||
|
||||
@@ -93,7 +93,6 @@ import octoprint.events as events
|
||||
import octoprint.plugin
|
||||
import octoprint.timelapse
|
||||
import octoprint._version
|
||||
import octoprint.filemanager.storage
|
||||
import octoprint.filemanager.analysis
|
||||
import octoprint.slicing
|
||||
from octoprint.server.util import enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, \
|
||||
@@ -296,10 +295,12 @@ class Server(object):
|
||||
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
|
||||
slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager)
|
||||
|
||||
storage_managers = dict()
|
||||
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(self._settings.getBaseFolder("uploads"))
|
||||
storage_managers[octoprint.filemanager.FileDestinations.SDCARD] = octoprint.filemanager.storage.PrinterSDStorage()
|
||||
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
|
||||
storage_managers = self._collect_initial_storage_managers()
|
||||
fileManager = octoprint.filemanager.FileManager(analysisQueue,
|
||||
slicingManager,
|
||||
printerProfileManager,
|
||||
initial_storage_managers=storage_managers)
|
||||
|
||||
appSessionManager = util.flask.AppSessionManager()
|
||||
pluginLifecycleManager = LifecycleManager(pluginManager)
|
||||
preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml"))
|
||||
@@ -858,6 +859,15 @@ class Server(object):
|
||||
|
||||
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
|
||||
|
||||
def _collect_initial_storage_managers(self):
|
||||
from octoprint.filemanager.storage.local import LocalFileStorage
|
||||
from octoprint.filemanager.storage.sdcard import PrinterSDStorage
|
||||
|
||||
storage_managers = dict()
|
||||
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = LocalFileStorage(self._settings.getBaseFolder("uploads"))
|
||||
storage_managers[octoprint.filemanager.FileDestinations.SDCARD] = PrinterSDStorage()
|
||||
return storage_managers
|
||||
|
||||
def _setup_heartbeat_logging(self):
|
||||
logger = logging.getLogger(__name__ + ".heartbeat")
|
||||
|
||||
|
||||
Reference in new issue
Block a user