WIP: tags, print time estimation, gcode parsing

This commit is contained in:
Gina Häußge committed 2018-05-24 18:52:19 +02:00
1 parent 73a16f6075
commit d9c8351025
19 files changed
+759 -714

No files matched your search

+18 -6
View File
@@ -91,17 +91,17 @@ class Protocol(ListenerAware, TransportListener):
self._job.process(self, position=position, tags=tags)
def pause_processing(self, tags=None):
if self._job is None or self.state != ProtocolState.PRINTING:
if self._job is None or self.state != ProtocolState.PROCESSING:
return
self.state = ProtocolState.PAUSED
def resume_processing(self, tags=None):
if self._job is None or self.state != ProtocolState.PAUSED:
return
self.state = ProtocolState.PRINTING
self.state = ProtocolState.PROCESSING
def cancel_processing(self, error=False, tags=None):
if self._job is not None and self.state in (ProtocolState.PRINTING, ProtocolState.PAUSED):
if self._job is not None and self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED):
self._job.cancel(error=error)
self.state = ProtocolState.CONNECTED
@@ -115,7 +115,7 @@ class Protocol(ListenerAware, TransportListener):
pass
def on_job_started(self, job):
self.state = ProtocolState.PRINTING
self.state = ProtocolState.PROCESSING
def on_job_done(self, job):
self._job_processed(job)
@@ -157,7 +157,7 @@ class ProtocolState(object):
CONNECTED = "connected"
DISCONNECTING = "disconnecting"
DISCONNECTED = "disconnected"
PRINTING = "printing"
PROCESSING = "processing"
CANCELLING = "cancelling"
PAUSING = "pausing"
PAUSED = "paused"
@@ -177,11 +177,14 @@ class ThreeAxisProtocolMixin(object):
def home(self, x=False, y=False, z=False):
pass
class MultiToolProtocolMixin(object):
def change_tool(self, tool):
pass
class ThreeDPrinterProtocolMixin(ThreeAxisProtocolMixin):
class ThreeDPrinterProtocolMixin(ThreeAxisProtocolMixin, MultiToolProtocolMixin):
def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False):
pass
@@ -304,3 +307,12 @@ class FileAwareProtocolListener(object):
def on_protocol_file_print_done(self, protocol):
pass
class PositionAwareProtocolListener(object):
def on_protocol_position_all_update(self, protocol, position):
pass
def on_protocol_position_z_update(self, protocol, z):
pass
@@ -1,214 +0,0 @@
# 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 "")
@@ -1,8 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals, print_function, \
division
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
-216
View File
@@ -1,216 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals, print_function, division
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
import Queue as queue
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 GcodeCommand(object):
known_float_attributes = ("x", "y", "z", "e", "s", "p", "r")
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<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>.*?)$")
@staticmethod
def from_line(line, tags=None):
"""
>>> 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
if tags is None:
tags = set()
line = line.strip()
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"):
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 = line[len(match.group(0)):].lstrip()
if param:
args["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["tool"] = match.group("tool")
elif match.group("F"):
code = "F"
args["f"] = match.group("feedrate")
return GcodeCommand(code, subcode=subcode, **args)
def __init__(self, command, subcode=None, **kwargs):
self.code = command
self.subcode = subcode
self.x = None
self.y = None
self.z = None
self.e = None
self.s = None
self.p = None
self.r = None
self.f = None
self.t = None
self.n = None
self.tool = None
self.original = None
self.param = None
self.progress = None
self.callback = None
self.tags = set()
self.unknown = False
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):
return "GcodeCommand(\"{str}\",progress={progress})".format(str=str(self), progress=self.progress)
def __str__(self):
if self.original is not None:
return self.original
else:
attr = []
for key in GcodeCommand.known_attributes:
value = self.__getattribute__(key)
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 "")
class TypedQueue(queue.Queue):
def __init__(self, maxsize=0):
queue.Queue.__init__(self, maxsize=maxsize)
self._lookup = set()
def put(self, item, item_type=None, *args, **kwargs):
queue.Queue.put(self, (item, item_type), *args, **kwargs)
def get(self, *args, **kwargs):
item, _ = queue.Queue.get(self, *args, **kwargs)
return item
def _put(self, item):
_, item_type = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
queue.Queue._put(self, item)
def _get(self):
item = queue.Queue._get(self)
_, item_type = item
if item_type is not None:
self._lookup.discard(item_type)
return item
class TypeAlreadyInQueue(Exception):
def __init__(self, t, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.type = t
def strip_comment(line):
if not ";" in line:
# shortcut
return line
escaped = False
result = []
for c in line:
if c == ";" and not escaped:
break
result += c
escaped = (c == "\\") and not escaped
return "".join(result).strip()
+169 -99
View File
@@ -8,14 +8,13 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
from octoprint.comm.protocol import Protocol, ThreeDPrinterProtocolMixin, FileStreamingProtocolMixin, \
MotorControlProtocolMixin, FanControlProtocolMixin, ProtocolState
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, \
PushingTransportWrapper, PushingTransportWrapperListener
PushingTransportWrapper, PushingTransportWrapperListener, TransportListener
from octoprint.comm.protocol.commands import Command, AtCommand, GcodeCommand
from octoprint.comm.protocol.reprap.commands import Command, to_command
from octoprint.comm.protocol.reprap.commands.atcommand import AtCommand
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.gcode.util import TypedQueue, TypeAlreadyInQueue, \
regexes_parameters
from octoprint.comm.protocol.reprap.util import normalize_command_handler_result
from octoprint.comm.protocol.reprap.util import normalize_command_handler_result, TypedQueue, TypeAlreadyInQueue
from octoprint.job import LocalGcodeFilePrintjob, SDFilePrintjob, \
LocalGcodeStreamjob
@@ -69,16 +68,20 @@ gcode_to_event = {
class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProtocolMixin,
FanControlProtocolMixin, FileStreamingProtocolMixin,
PushingTransportWrapperListener):
PushingTransportWrapperListener, TransportListener):
supported_jobs = [LocalGcodeFilePrintjob,
LocalGcodeStreamjob,
SDFilePrintjob]
@staticmethod
def get_attributes_starting_with(flavor, prefix):
def get_flavor_attributes_starting_with(flavor, prefix):
return [x for x in dir(flavor) if x.startswith(prefix)]
@classmethod
def get_attributes_starting_with(cls, prefix):
return dict((x, getattr(cls, x)) for x in dir(cls) if x.startswith(prefix))
def __init__(self, flavor, connection_timeout=30.0, communication_timeout=5.0,
temperature_interval_idle=5.0, temperature_interval_printing=5.0):
super(ReprapGcodeProtocol, self).__init__()
@@ -95,12 +98,16 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
temperature_printing=temperature_interval_printing
)
comm_attrs = self.get_attributes_starting_with(self.flavor, "comm_")
message_attrs = self.get_attributes_starting_with(self.flavor, "message_")
error_attrs = self.get_attributes_starting_with(self.flavor, "error_")
flavor_comm_attrs = self.get_flavor_attributes_starting_with(self.flavor, "comm_")
flavor_message_attrs = self.get_flavor_attributes_starting_with(self.flavor, "message_")
flavor_error_attrs = self.get_flavor_attributes_starting_with(self.flavor, "error_")
self._registered_messages = comm_attrs + message_attrs
self._error_messages = error_attrs
self._registered_messages = flavor_comm_attrs + flavor_message_attrs
self._error_messages = flavor_error_attrs
self._handlers_gcode = self.get_attributes_starting_with("_gcode_")
self._handlers_atcommand = self.get_attributes_starting_with("_atcommand_")
self._handlers_command_phase = self.get_attributes_starting_with("_command_phase_")
self._transport = None
@@ -160,6 +167,16 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# temperature polling
self._temperature_poller = None
# terminal logging
self._terminal_log = collections.deque([], 20)
# resend logging
self._log_resends = True
self._log_resends_rate_start = None
self._log_resends_rate_count = 0
self._log_resends_rate_frame = 60
self._log_resends_max = 5
# mutexes
self._line_mutex = threading.RLock()
self._send_queue_mutex = threading.RLock()
@@ -181,7 +198,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
transport = PushingTransportWrapper(LineAwareTransportWrapper(transport), timeout=5.0)
self._send_queue_active = True
self._sending_thread = threading.Thread(target=self._send_loop, name="comm.sending_thread")
self._sending_thread = threading.Thread(target=self._send_loop, name=b"comm.sending_thread")
self._sending_thread.daemon = True
self._sending_thread.start()
@@ -292,12 +309,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
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 self.state == ProtocolState.PROCESSING and not self._job.runs_parallel and not force:
if len(commands) > 1:
command_type = None
for command in commands:
if not isinstance(command, Command):
command = Command.from_line(command, type=command_type, tags=tags)
command = to_command(command, type=command_type, tags=tags)
try:
self._command_queue.put((command, on_sent), item_type=command_type)
@@ -314,7 +331,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
return self.state not in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR)
def _is_busy(self):
return self.state in (ProtocolState.PRINTING, ProtocolState.PAUSED)
return self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED)
def _is_streaming(self):
# TODO make more abstract?
@@ -337,7 +354,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._clear_to_send.set()
def poll_temperature_interval():
return self.interval["temperature_printing"] if self.state == ProtocolState.PRINTING else self.interval["temperature_idle"]
return self.interval["temperature_printing"] if self.state == ProtocolState.PROCESSING else self.interval["temperature_idle"]
def poll_temperature():
if self._is_operational() and not self._internal_state["only_from_job"] and self.can_send():
@@ -360,6 +377,20 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._temperature_poller.cancel()
self._temperature_poller = None
##~~ Transport logging
def on_transport_log_message(self, transport, data):
super(ReprapGcodeProtocol, self).on_transport_log_message(transport, data)
self._terminal_log.append("--- " + to_unicode(data.strip(), errors="replace"))
def on_transport_log_received_data(self, transport, data):
super(ReprapGcodeProtocol, self).on_transport_log_received_data(transport, data)
self._terminal_log.append("<<< " + to_unicode(data.strip(), errors="replace"))
def on_transport_log_sent_data(self, transport, data):
super(ReprapGcodeProtocol, self).on_transport_log_sent_data(transport, data)
self._terminal_log.append(">>> " + to_unicode(data.strip(), errors="replace"))
##~~ Receiving
def on_transport_data_pushed(self, transport, data):
@@ -451,7 +482,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._clear_to_send.set()
def _on_comm_timeout(self):
if self.state not in (ProtocolState.PRINTING,
if self.state not in (ProtocolState.PROCESSING,
ProtocolState.PAUSED,
ProtocolState.CONNECTED):
return
@@ -461,7 +492,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# figure out which consecutive timeout maximum we have to use
if self._internal_state["long_running_command"]:
consecutive_max = 5 # TODO take from config
elif self.state in (ProtocolState.PRINTING, ProtocolState.PAUSING, ProtocolState.CANCELLING):
elif self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSING, ProtocolState.CANCELLING):
consecutive_max = 10 # TODO take from config
else:
consecutive_max = 15 # TODO take from config
@@ -492,7 +523,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# long running command active, ignore timeout
self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active")
elif self.state in (ProtocolState.PRINTING, ProtocolState.PAUSED):
elif self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED):
# printing, try to tickle the printer
message = "Communication timeout while printing, trying to trigger response from printer."
self._logger.info(message)
@@ -507,7 +538,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self.notify_listeners("on_protocol_log_message", self, message + " " + general_message)
self._clear_to_send.set()
return self.state != ProtocolState.PRINTING
return self.state != ProtocolState.PROCESSING
def _on_comm_ok(self):
if self._internal_state["ignore_ok"] > 0:
@@ -533,7 +564,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._finish_heatup()
if not self.state in (ProtocolState.PRINTING, ProtocolState.CONNECTED, ProtocolState.PAUSED):
if not self.state in (ProtocolState.PROCESSING, ProtocolState.CONNECTED, ProtocolState.PAUSED):
return
# process ongoing resend requests and queues if we are operational
@@ -549,7 +580,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._logger.info("Ignoring next ok, counter is now at {}".format(self._internal_state["ignore_ok"]))
def _on_comm_wait(self):
if self.state == ProtocolState.PRINTING:
if self.state == ProtocolState.PROCESSING:
self._on_comm_ok()
def _on_comm_resend(self, linenumber):
@@ -594,7 +625,22 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
else:
self._internal_state["resend_delta"] = None
# TODO log resend (with rate limiting)
# if we log resends, make sure we don't log more resends than the set rate within a window
#
# this it to prevent the log from getting flooded for extremely bad communication issues
if self._log_resends:
now = time.time()
new_rate_window = self._log_resends_rate_start is None or self._log_resends_rate_start + self._log_resends_rate_frame < now
in_rate = self._log_resends_rate_count < self._log_resends_max
if new_rate_window or in_rate:
if new_rate_window:
self._log_resends_rate_start = now
self._log_resends_rate_count = 0
self._to_logfile_with_terminal(u"Got a resend request from the printer: requested line = {}, "
u"current line = {}".format(linenumber, self._current_linenumber))
self._log_resends_rate_count += 1
return True
@@ -685,7 +731,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
def _continue_sending(self):
while self._active:
if self.state in (ProtocolState.PRINTING,) and not (self._job is None or not self._job.active or isinstance(self._job, SDFilePrintjob)):
if self.state in (ProtocolState.PROCESSING,) 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
@@ -745,7 +791,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
with self._send_queue_mutex:
while self._active:
# we loop until we've actually enqueued a line for sending
if self.state != ProtocolState.PRINTING:
if self.state != ProtocolState.PROCESSING:
# we are no longer printing, return False
return False
@@ -760,10 +806,13 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# end of job, return False
return False
command = Command.from_line(line, tags={"source:file",})
# TODO filepos & fileline tags
#"filepos:{}".format(pos),
#"fileline:{}".format(lineno)})
pos = self._job.pos
read_lines = self._job.read_lines
actual_lines = self._job.actual_lines
command = to_command(line, tags={"source:file",
"filepos:{}".format(pos),
"fileline:{}".format(read_lines),
"fileactualline:{}".format(actual_lines)})
if self._send_command(command):
return True
@@ -813,7 +862,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
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)
command = to_command(command, type=command_type, tags=tags)
with self._send_queue_mutex:
if self._internal_state["trigger_events"]:
@@ -963,7 +1012,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# transport does not have message integrity, let's see if we'll send a 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)
checksum_enabled = self.flavor.always_send_checksum or (self.state == ProtocolState.PROCESSING and not self.flavor.never_send_checksum)
send_with_checksum = command_requiring_checksum or (command_allowing_checksum and checksum_enabled)
@@ -1014,7 +1063,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._phase_logger.debug("phase: {}, command: {!r}".format(phase, command))
def _process_command_phase(self, phase, command, **kwargs):
command = Command.from_line(command, **kwargs)
command = to_command(command, **kwargs)
results = [command]
self._log_command_phase(phase, command)
@@ -1057,9 +1106,10 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
new_results = []
modified = False
for command in results:
if isinstance(command, GcodeCommand) is not None:
if isinstance(command, GcodeCommand):
gcode_handler = "_gcode_" + command.code + "_" + phase
if hasattr(self, gcode_handler):
if gcode_handler in self._handlers_gcode:
# noinspection PyCallingNonCallable
handler_results = getattr(self, gcode_handler)(command)
new_results += normalize_command_handler_result(command, handler_results)
modified = True
@@ -1077,7 +1127,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# send it through the phase specific command handler if it exists
command_phase_handler = "_command_phase_" + phase
if hasattr(self, command_phase_handler):
if command_phase_handler in self._handlers_command_phase:
new_results = []
for command in results:
handler_results = getattr(self, command_phase_handler)(command)
@@ -1099,10 +1149,10 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._logger.exception("Error while processing hook {} for phase {} and command {}:".format(name, phase, command.atcommand))
# trigger built-in handler if available
handler = getattr(self, "_atcommand_{}_{}".format(command.atcommand, phase), None)
if callable(handler):
atcommand_handler = "_atcommand_{}_{}".format(command.atcommand, phase)
if atcommand_handler in self._handlers_atcommand:
try:
handler(command.atcommand, command.parameters, tags=command.tags)
getattr(self, atcommand_handler)(command)
except:
self._logger.exception("Error in handler for phase {} and command {}".format(phase, command.atcommand))
@@ -1142,31 +1192,30 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
def _add_to_last_lines(self, command):
self._last_lines.append(command)
##~~ command handlers
##~~ gcode command handlers
def _gcode_T_sent(self, cmd, cmd_type=None):
tool_match = regexes_parameters["intT"].search(cmd)
if tool_match:
self._internal_state["current_tool"] = int(tool_match.group("value"))
def _gcode_T_sent(self, command):
if command.tool:
self._internal_state["current_tool"] = int(command.tool)
def _gcode_G0_sent(self, cmd, cmd_type=None):
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)
def _gcode_G0_sent(self, command):
if command.z is not None and self._internal_state["current_z"] != command.z:
self._internal_state["current_z"] = command.z
self.notify_listeners("on_protocol_position_z_update", self, self._internal_state["current_z"])
_gcode_G1_sent = _gcode_G0_sent
def _gcode_M0_queuing(self, cmd, cmd_type=None):
def _gcode_M0_queuing(self, command):
self.pause_file_print()
return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
_gcode_M1_queuing = _gcode_M0_queuing
def _gcode_M25_queuing(self, cmd, cmd_type=None):
def _gcode_M25_queuing(self, command):
# M25 while not printing from SD will be handled as pause. This way it can be used as another marker
# for GCODE induced pausing. Send it to the printer anyway though.
if self.state == ProtocolState.PRINTING and not isinstance(self._job, SDFilePrintjob):
if self.state == ProtocolState.PROCESSING and not isinstance(self._job, SDFilePrintjob):
self.pause_file_print()
def _gcode_M140_queuing(self, cmd, cmd_type=None):
def _gcode_M140_queuing(self, command):
# TODO heated bed handling needs heated bed flag from printer profile
#if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
# self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd))
@@ -1174,72 +1223,67 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
pass
_gcode_M190_queuing = _gcode_M140_queuing
def _gcode_M104_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
def _gcode_M104_sent(self, command, wait=False, support_r=False):
tool_num = self._internal_state["current_tool"]
tool_match = regexes_parameters["intT"].search(cmd)
if tool_match:
tool_num = int(tool_match.group("value"))
if command.t:
tool_num = command.t
if wait:
self._internal_state["former_tool"] = self._internal_state["current_tool"]
self._internal_state["current_tool"] = tool_num
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
target = None
if command.s is not None:
target = float(command.s)
elif command.r is not None and support_r:
target = float(command.r)
if match:
if target:
tool = "tool{}".format(tool_num)
try:
target = float(match.group("value"))
self._set_temperature(tool, None, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_state["temperatures"])
except ValueError:
pass
self._set_temperature(tool, None, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_state["temperatures"])
def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
def _gcode_M140_sent(self, command, wait=False, support_r=False):
target = None
if command.s is not None:
target = float(command.s)
elif command.r is not None and support_r:
target = float(command.r)
if match:
try:
target = float(match.group("value"))
self._set_temperature("bed", None, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_state["temperatures"])
except ValueError:
pass
if target:
self._set_temperature("bed", None, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_state["temperatures"])
def _gcode_M109_sent(self, cmd, cmd_type=None):
def _gcode_M109_sent(self, command):
self._internal_state["heatup_start"] = time.time()
self._internal_state["long_running_command"] = True
self._internal_state["heating"] = True
self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True)
self._gcode_M104_sent(command, wait=True, support_r=True)
def _gcode_M190_sent(self, cmd, cmd_type=None):
def _gcode_M190_sent(self, command):
self._internal_state["heatup_start"] = time.time()
self._internal_state["long_running_command"] = True
self._internal_state["heating"] = True
self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True)
self._gcode_M140_sent(command, wait=True, support_r=True)
def _gcode_M116_sent(self, cmd, cmd_type=None):
def _gcode_M116_sent(self, command):
self._internal_state["heatup_start"] = time.time()
self._internal_state["long_running_command"] = True
self._internal_state["heating"] = True
def _gcode_M110_sending(self, cmd, cmd_type=None):
def _gcode_M110_sending(self, command):
new_line_number = None
match = regexes_parameters["intN"].search(cmd)
if match:
if command.n:
try:
new_line_number = int(match.group("value"))
new_line_number = int(command.n)
except:
pass
else:
new_line_number = 0
with self._line_mutex:
self._logger.info("M110 detected, setting current line number to {}".format(new_line_number))
# send M110 command with new line number
self._current_linenumber = new_line_number
@@ -1247,7 +1291,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._last_lines.clear()
self._internal_state["resend_delta"] = None
def _gcode_M112_queuing(self, cmd, cmd_type=None):
def _gcode_M112_queuing(self, command):
# emergency stop, jump the queue with the M112
self._do_send_with_checksum(str(self.flavor.command_emergency_stop()))
self._do_increment_and_send_with_checksum(str(self.flavor.command_emergency_stop()))
@@ -1282,22 +1326,42 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# I hope it got it the first time because as far as I can tell, there is no way to know
return None,
def _gcode_G4_sent(self, cmd, cmd_type=None):
def _gcode_G4_sent(self, cmd):
# we are intending to dwell for a period of time, increase the timeout to match
p_match = regexes_parameters["floatP"].search(cmd)
s_match = regexes_parameters["floatS"].search(cmd)
timeout = 0
if cmd.p:
timeout = float(cmd.p) / 1000.0
elif cmd.s:
timeout = float(cmd.s)
self._internal_state["timeout"] = self._get_timeout("communication") + timeout
_timeout = 0
if p_match:
_timeout = float(p_match.group("value")) / 1000.0
elif s_match:
_timeout = float(s_match.group("value"))
##~~ atcommand handlers
self._internal_state["timeout"] = self._get_timeout("communication") + _timeout
def _atcommand_pause_queuing(self, command):
tags = command.tags
if tags is None:
tags = set()
if not "script:afterPrintPaused" in tags:
self.pause_processing(tags={"trigger:atcommand_pause"})
def _atcommand_cancel_queuing(self, command):
tags = command.tags
if tags is None:
tags = set()
if not "script:afterPrintCancelled" in tags:
self.cancel_processing(tags={"trigger:atcommand_cancel"})
_atcommand_abort_queuing = _atcommand_cancel_queuing
def _atcommand_resume_queuing(self, command):
tags = command.tags
if tags is None:
tags = set()
if not "script:beforePrintResumed" in tags:
self.resume_processing(tags={"trigger:atcommand_resume"})
##~~ command phase handlers
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None):
def _command_phase_sending(self, cmd, gcode=None):
if gcode is not None and gcode.code in self.flavor.long_running_commands:
self._internal_state["long_running_command"] = True
@@ -1317,6 +1381,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
else:
return time.time()
def _to_logfile_with_terminal(self, message=None, level=logging.INFO):
log = u"Last lines in terminal:\n" + u"\n".join(map(lambda x: u"| {}".format(x), list(self._terminal_log)))
if message is not None:
log = message + u"\n| " + log
self._logger.log(level, log)
if __name__ == "__main__":
from octoprint.comm.transport.serialtransport import VirtualSerialTransport
@@ -0,0 +1,66 @@
# 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
__registry = dict()
def _register_command_class(cls):
__registry[cls.__name__] = cls
def to_command(line, type=None, tags=None, **kwargs):
if isinstance(line, Command):
return line
for cls in __registry.values():
if cls.pattern:
# noinspection PyUnresolvedReferences,PyProtectedMember
if isinstance(cls.pattern, re._pattern_type) and cls.pattern.match(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
elif callable(cls.pattern) and cls.pattern(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
return Command.from_line(line, type=type, tags=tags, **kwargs)
class CommandMetaClass(type):
def __new__(mcs, *args, **kwargs):
c = type.__new__(mcs, *args, **kwargs)
_register_command_class(c)
return c
class Command(object):
__metaclass__ = CommandMetaClass
pattern = None
@classmethod
def from_line(cls, line, type=None, tags=None, **kwargs):
return cls(line, type=type, tags=tags, **kwargs)
def __init__(self, line, type=None, tags=None, **kwargs):
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())
@@ -0,0 +1,39 @@
# 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"
from octoprint.comm.protocol.reprap.commands import Command
class AtCommand(Command):
pattern = staticmethod(lambda x: x.startswith("@"))
@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)
@@ -0,0 +1,132 @@
# 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"
from octoprint.comm.protocol.reprap.commands import Command
import re
import string
class GcodeCommand(Command):
pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x))
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+)))")
parameter_regex = re.compile("(?P<key>[A-Z])((?P<value>[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))")
possible_params = tuple(string.ascii_lowercase) + ("subcode", "param", "tool", "feedrate", "original")
@staticmethod
def from_line(line, **kwargs):
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 = dict(original=line, type=type, tags=tags)
match = GcodeCommand.command_regex.match(line)
if match is None:
raise ValueError("{!r} is not a Gcode line".format(line))
if match.group(b"GM"):
code = match.group(b"GM")
if match.group(b"subcode"):
args[b"subcode"] = int(match.group(b"subcode"))
if match.group(0) != line:
rest = line[len(match.group(0)):]
while True:
matched_param = GcodeCommand.parameter_regex.search(rest)
if not matched_param:
break
key = matched_param.group(b"key").lower()
if matched_param.group(b"value"):
value = matched_param.group(b"value")
if "." in value:
value = float(value)
else:
value = int(value)
else:
value = True
args[key] = value
rest = rest[:matched_param.start()] + rest[matched_param.end():]
rest = rest.lstrip()
if rest:
args[b"param"] = rest
elif match.group(b"T"):
code = "T"
args[b"tool"] = int(match.group(b"tool"))
elif match.group(b"F"):
code = "F"
args[b"feedrate"] = int(match.group(b"feedrate"))
return GcodeCommand(code, **args)
def __init__(self, code, **kwargs):
self.code = code
self.subcode = kwargs.pop(b"subcode", None)
self.tool = kwargs.pop(b"tool", None)
self.feedrate = kwargs.pop(b"feedrate", None)
self.param = kwargs.pop(b"param", None)
self.original = kwargs.pop(b"original", None)
if self.original is None:
line = self._to_line()
else:
line = self.original
type = kwargs.pop(b"type", None)
tags = kwargs.pop(b"tags", None)
self.args = kwargs
super(GcodeCommand, self).__init__(line, type=type, tags=tags)
self._repr = self._to_repr()
def __getattr__(self, item):
if len(item) == 1:
return self.args.get(item, None)
raise AttributeError("'GcodeCommand' object has no attribute '{}'".format(item))
def __repr__(self):
return self._repr
def _to_line(self):
attr = []
for key in string.ascii_lowercase:
value = getattr(self, key, None)
if value is not None:
if value is True:
attr.append(key.upper())
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 "")
def _to_repr(self):
args = [k + "=" + repr(getattr(self, k)) for k in self.possible_params if getattr(self, k, None) is not None]
return "GcodeCommand({!r},{},type={!r},tags={!r})".format(self.code,
",".join(args),
self.type,
self.tags)
@@ -2,18 +2,16 @@
from __future__ import absolute_import, unicode_literals, print_function, \
division
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
import logging
import time
from octoprint.comm.protocol.commands import GcodeCommand
from octoprint.comm.protocol.gcode.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.reprap.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
# TODO needed? move?
from octoprint.util import chunks
@@ -198,7 +196,7 @@ class ReprapGcodeFlavor(object):
line_to_resend = None
match = cls.regex_resend_linenumber.search(line)
if match is not None:
line_to_resend = int(match.group("n"))
line_to_resend = int(match.group(b"n"))
return dict(linenumber=line_to_resend)
@classmethod
@@ -245,7 +243,7 @@ class ReprapGcodeFlavor(object):
def parse_message_position(cls, line, lower_line, state):
position = dict(x=None, y=None, z=None, e=None)
for match in re.finditer(cls.regex_position, line):
position[match.group("axis").lower()] = float(match.group("pos"))
position[match.group(b"axis").lower()] = float(match.group(b"pos"))
return position
@classmethod
@@ -275,7 +273,7 @@ class ReprapGcodeFlavor(object):
match = cls.regex_sd_file_opened.match(lower_line)
if not match:
return
return dict(name=match.group("name"), size=int(match.group("size")))
return dict(name=match.group(b"name"), size=int(match.group(b"size")))
@classmethod
def parse_message_sd_entry(cls, line, lower_line, state):
@@ -310,7 +308,7 @@ class ReprapGcodeFlavor(object):
match = cls.regex_sd_printing_byte.match(lower_line)
if not match:
return None
return dict(current=int(match.group("current")), total=int(match.group("total")))
return dict(current=int(match.group(b"current")), total=int(match.group(b"total")))
##~~ Commands
+69 -4
View File
@@ -7,12 +7,40 @@ __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, GcodeCommand
from octoprint.comm.protocol.commands import Command
from octoprint.comm.protocol.reprap.commands import Command
# noinspection PyCompatibility
from past.builtins import basestring
import copy
try:
# noinspection PyCompatibility
from queue import Queue
except:
# noinspection PyCompatibility
from Queue import Queue
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = "\d+"
def strip_comment(line):
if not ";" in line:
# shortcut
return line
escaped = False
result = []
for c in line:
if c == ";" and not escaped:
break
result += c
escaped = (c == "\\") and not escaped
return "".join(result).strip()
def process_gcode_line(line, offsets=None, current_tool=None):
line = strip_comment(line).strip()
@@ -137,7 +165,7 @@ def normalize_command_handler_result(command, handler_results, tags_to_add=None)
elif isinstance(handler_result, Command):
if handler_result != original:
command = handler_result.copy()
command = copy.copy(handler_result)
command.tags = expand_tags(original.tags, tags_to_add)
result.append(command)
@@ -145,7 +173,6 @@ def normalize_command_handler_result(command, handler_results, tags_to_add=None)
# 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
@@ -177,3 +204,41 @@ def normalize_command_handler_result(command, handler_results, tags_to_add=None)
command, command_type, gcode, subcode, tags = original
return result
class TypedQueue(Queue):
def __init__(self, maxsize=0):
Queue.__init__(self, maxsize=maxsize)
self._lookup = set()
def put(self, item, item_type=None, *args, **kwargs):
Queue.put(self, (item, item_type), *args, **kwargs)
def get(self, *args, **kwargs):
item, _ = Queue.get(self, *args, **kwargs)
return item
def _put(self, item):
_, item_type = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
Queue._put(self, item)
def _get(self):
item = Queue._get(self)
_, item_type = item
if item_type is not None:
self._lookup.discard(item_type)
return item
class TypeAlreadyInQueue(Exception):
def __init__(self, t, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.type = t
+40 -23
View File
@@ -12,6 +12,8 @@ from octoprint.util.listener import ListenerAware
from abc import ABCMeta, abstractmethod, abstractproperty
from monotonic import monotonic
class Printjob(ProtocolListener, ListenerAware):
__metaclass__ = ABCMeta
@@ -48,7 +50,14 @@ class Printjob(ProtocolListener, ListenerAware):
@property
def elapsed(self):
return time.time() - self._start if self._start is not None else None
return monotonic() - self._start if self._start is not None else None
@property
def clean_elapsed(self):
elapsed = self.elapsed
if elapsed is None:
return None
return elapsed - self._lost_time
@property
def progress(self):
@@ -59,19 +68,6 @@ class Printjob(ProtocolListener, ListenerAware):
return float(pos) / float(size)
@property
def estimate(self):
elapsed = self.elapsed
if elapsed is None:
return
progress = self.progress
if progress is None:
return
spent_time = elapsed - self._lost_time
return spent_time / progress
@property
def active(self):
return self._start is not None
@@ -83,7 +79,7 @@ class Printjob(ProtocolListener, ListenerAware):
return False
def process(self, protocol, position=0, tags=None):
self._start = time.time()
self._start = monotonic()
self._protocol = protocol
self._protocol.register_listener(self)
@@ -180,6 +176,10 @@ class LocalFilePrintjob(StoragePrintjob):
self._encoding = encoding
self._size = os.stat(path).st_size
self._pos = 0
self._read_lines = 0
self._actual_lines = 0
self._handle = None
@property
@@ -188,8 +188,15 @@ class LocalFilePrintjob(StoragePrintjob):
@property
def pos(self):
# TODO manual pos tracking
return self._handle.tell() if self._handle is not None else 0
return self._pos
@property
def actual_lines(self):
return self._actual_lines
@property
def read_lines(self):
return self._read_lines
@property
def active(self):
@@ -199,6 +206,11 @@ class LocalFilePrintjob(StoragePrintjob):
def path(self):
return self._path
def event_payload(self):
event_data = StoragePrintjob.event_payload(self)
event_data["size"] = self.size
return event_data
def process(self, protocol, position=0, tags=None):
Printjob.process(self, protocol, position=position)
@@ -207,6 +219,7 @@ class LocalFilePrintjob(StoragePrintjob):
if position > 0:
self._handle.seek(position)
self._pos = position
self.process_job_started()
def get_next(self):
@@ -222,10 +235,19 @@ class LocalFilePrintjob(StoragePrintjob):
# file got closed just now
return None
line = to_unicode(self._handle.readline())
# we need to manually keep track of our pos here since
# codecs' readline will make our handle's tell not
# return the actual number of bytes read, but also the
# already buffered bytes (for detecting the newlines)
self._pos += len(line)
self._actual_lines += 1
if not line:
self.process_job_done()
processed = self.process_line(line)
self._read_lines += 1
self.process_job_progress()
return processed
except Exception as e:
@@ -265,7 +287,7 @@ class LocalGcodeFilePrintjob(LocalFilePrintjob):
def process_line(self, line):
# TODO no dependency on protocol module
from octoprint.comm.protocol.gcode.util import strip_comment
from octoprint.comm.protocol.reprap.util import strip_comment
# strip line
processed = line.strip()
@@ -331,11 +353,6 @@ class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener):
def status_interval(self):
return self._status_interval
def event_payload(self):
event_data = Printjob.event_payload(self)
event_data["size"] = self.size
return event_data
def can_process(self, protocol):
from octoprint.comm.protocol import FileAwareProtocolMixin
return SDFilePrintjob in protocol.supported_jobs and isinstance(protocol, FileAwareProtocolMixin)
+8 -2
View File
@@ -22,15 +22,21 @@ class PrintTimeEstimator(object):
self.force_dumb_from_percent = settings().getFloat(["estimation", "printTime", "forceDumbFromPercent"])
self.force_dumb_after_min = settings().getFloat(["estimation", "printTime", "forceDumbAfterMin"])
self._job_type = job_type
self._data = None
self.reset()
def reset(self):
threshold = None
rolling_window = None
countdown = None
if job_type == "local" or job_type == "sdcard":
if self._job_type == "local" or self._job_type == "sdcard":
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"])
if job_type == "sdcard":
if self._job_type == "sdcard":
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
+152 -132
View File
@@ -30,13 +30,16 @@ from octoprint.util import comm as comm
from octoprint.util import InvariantContainer
from octoprint.util import to_unicode
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, ProtocolState
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, PositionAwareProtocolListener, ProtocolState
from octoprint.job import LocalGcodeFilePrintjob, LocalGcodeStreamjob, SDFilePrintjob, PrintjobListener
from octoprint.job import StoragePrintjob, LocalGcodeFilePrintjob, LocalGcodeStreamjob, SDFilePrintjob, PrintjobListener
from collections import namedtuple
JobData = namedtuple("JobData", ("job", "average_past_total", "analysis_total", "estimator"))
JobData = namedtuple("JobData", ("job",
"average_past_total",
"analysis_total",
"estimator"))
def _serial_factory(port=None, baudrate=None):
import serial
@@ -64,7 +67,7 @@ def _serial_factory(port=None, baudrate=None):
return None
class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, FileAwareProtocolListener, PrintjobListener):
class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, FileAwareProtocolListener, PositionAwareProtocolListener, PrintjobListener):
"""
Default implementation of the :class:`PrinterInterface`. Manages the communication layer object and registers
itself with it as a callback to react to changes on the communication layer.
@@ -96,10 +99,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
self._current_z = None
self._progress = None
self._print_time = None
self._print_time_left = None
# sd handling
self._sdPrinting = False
self._sdStreaming = False
@@ -140,7 +139,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
on_update=self._send_current_data_callbacks,
on_add_temperature=self.send_add_temperature_callbacks,
on_add_log=self._send_add_log_callbacks,
on_add_message=self._send_add_message_callbacks
on_add_message=self._send_add_message_callbacks,
on_get_progress=self._update_progress_data_callback
)
self._state_monitor.reset(
state=self._dict(text=self.get_state_string(), flags=self._get_state_flags()),
@@ -167,7 +167,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated)
def _create_estimator(self, job_type):
self._estimator = self._estimator_factory(job_type)
return self._estimator_factory(job_type)
#~~ handling of PrinterCallbacks
@@ -524,18 +524,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
if self._job is None or self._protocol is None or self._protocol.state not in (ProtocolState.CONNECTED,):
return
# TODO other way to determine job type
if isinstance(self._job.job, SDFilePrintjob):
job_type = "sdcard"
else:
job_type = "local"
self._create_estimator(job_type)
self._fileManager.delete_recovery_data()
self._file_manager.delete_recovery_data()
self._last_progress_report = None
self._update_progress_data()
self._setCurrentZ(None)
self._set_current_z(None)
self._protocol.process(self._job.job,
position=pos,
@@ -547,7 +540,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
"""
if self._protocol is None:
return
if self._protocol.state != ProtocolState.PRINTING:
if self._protocol.state != ProtocolState.PROCESSING:
return
self._protocol.pause_processing()
@@ -565,11 +558,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
"""
Cancel the current job.
"""
if self._protocol is None or not self._protocol.state in (ProtocolState.PRINTING, ProtocolState.PAUSED):
if self._protocol is None or not self._protocol.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED):
return
# reset progress, height, print time
self._setCurrentZ(None)
self._set_current_z(None)
self._reset_progress_data()
# mark print as failure
@@ -608,7 +601,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
return "Connecting"
elif state == ProtocolState.CONNECTED:
return "Operational"
elif state == ProtocolState.PRINTING:
elif state == ProtocolState.PROCESSING:
if self._job is None:
return "Printing unknown job"
if isinstance(self._job.job, SDFilePrintjob):
@@ -637,7 +630,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
return "CONNECTING"
elif state == ProtocolState.CONNECTED:
return "OPERATIONAL"
elif state == ProtocolState.PRINTING:
elif state == ProtocolState.PROCESSING:
return "PRINTING"
elif state == ProtocolState.PAUSED:
return "PAUSED"
@@ -679,7 +672,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
return self.get_state_string(), port, baudrate, printer_profile
def is_connected(self):
return self._protocol is not None and self._protocol.state in (ProtocolState.CONNECTED, ProtocolState.PRINTING, ProtocolState.PAUSED)
return self._protocol is not None and self._protocol.state in (ProtocolState.CONNECTED, ProtocolState.PROCESSING, ProtocolState.PAUSED)
def is_closed_or_error(self, *args, **kwargs):
return self._protocol is None or self._protocol.state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR)
@@ -688,7 +681,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
return not self.is_closed_or_error()
def is_printing(self, *args, **kwargs):
return self._protocol is not None and self._protocol.state == ProtocolState.PRINTING
return self._protocol is not None and self._protocol.state == ProtocolState.PROCESSING
def is_cancelling(self, *args, **kwargs):
return self._comm is not None and self._comm.isCancelling()
@@ -703,7 +696,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
return self._protocol is not None and self._protocol.state == ProtocolState.DISCONNECTED_WITH_ERROR
def is_ready(self, *args, **kwargs):
return self.is_operational() and not self._protocol.state in (ProtocolState.PRINTING, ProtocolState.PAUSED)
return self.is_operational() and not self._protocol.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED)
def is_sd_ready(self, *args, **kwargs):
if not settings().getBoolean(["feature", "sdSupport"]) or self._protocol is None:
@@ -778,10 +771,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
#~~ state monitoring
def _setOffsets(self, offsets):
self._stateMonitor.set_temp_offsets(offsets)
def _set_offsets(self, offsets):
self._state_monitor.set_temp_offsets(offsets)
def _setCurrentZ(self, currentZ):
def _set_current_z(self, currentZ):
self._current_z = currentZ
self._state_monitor.set_current_z(self._current_z)
@@ -809,16 +802,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
self._state_monitor.add_message(message)
def _estimate_total_for_job(self):
if self._job is None or self._job.job is None or self._job.estimator is None or self._job.job.estimate is None:
if self._job is None or self._job.job is None or self._job.estimator is None:
return None
self._job.estimator.update(self._job.job.estimate)
result = None
if self._job.estimator.is_stable():
result = self._job.estimator.average_total_rolling
return result
return self._job.estimator.estimate_total()
def _reset_progress_data(self):
self._state_monitor.set_progress(dict(completion=None,
@@ -827,61 +814,72 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
printTimeLeft=None))
def _set_completion_progress_data(self):
self._progress = 1.0
self._print_time = self._job.job.elapsed if self._job is not None else None
self._print_time_left = 0
progress = 1.0
pos = self._job.job.size if self._job is not None else None
print_time = int(self._job.job.elapsed) if self._job is not None else None
print_time_left = 0
pos = self._job.job.pos if self._job is not None else None
self._update_progress_data(completion=progress,
filepos=pos,
print_time=print_time,
print_time_left=print_time_left)
self._state_monitor.set_progress(dict(completion=self._progress * 100 if self._progress is not None else None,
filepos=pos,
printTime=int(self._print_time) if self._print_time is not None else None,
printTimeLeft=int(self._print_time_left) if self._print_time_left is not None else None))
def _update_progress_data(self, completion=None, filepos=None, print_time=None, print_time_left=None, print_time_left_origin=None):
self._state_monitor.set_progress(self._dict(completion=completion,
filepos=filepos,
printTime=print_time,
printTimeLeft=print_time_left,
printTimeLeftOrigin=print_time_left_origin))
def _update_progress_data(self):
if self._job is None or not self._job.job.active:
self._state_monitor.set_progress(self._dict(completion=None,
filepos=None,
printTime=None,
printTimeLeft=None,
printTimeLeftOrigin=None))
return
def _update_progress_data_callback(self):
if self._job is None or self._job.job is None:
progress = None
print_time = None
cleaned_print_time = None
pos = None
else:
progress = self._job.job.progress
print_time = self._job.job.elapsed
cleaned_print_time = self._job.job.clean_elapsed
pos = self._job.job.pos
estimated_total_print_time = self._estimate_total_for_job()
total_print_time = estimated_total_print_time
print_time_left = print_time_left_origin = None
original_estimate = None
if self._job.average_past_total:
original_estimate = self._job.average_past_total
elif self._job.analysis_total:
original_estimate = self._job.analysis_total
if original_estimate:
if self._job.job.progress and self._job.job.elapsed:
if estimated_total_print_time is None:
total_print_time = original_estimate
else:
if self._job.job.progress < 0.5:
sub_progress = self._job.job.progress * 2
else:
sub_progress = 1.0
total_print_time = (1 - sub_progress) * original_estimate + sub_progress * estimated_total_print_time
self._progress = self._job.job.progress
self._print_time = self._job.job.elapsed
self._print_time_left = total_print_time - self._job.job.elapsed if (total_print_time is not None and self._job.job.elapsed is not None) else None
self._state_monitor.set_progress(dict(completion=self._progress * 100 if self._progress is not None else None,
filepos=self._job.job.pos,
printTime=int(self._print_time) if self._print_time is not None else None,
printTimeLeft=int(self._print_time_left) if self._print_time_left is not None else None))
if self._job.job.progress:
if progress is not None:
progress_int = int(self._job.job.progress * 100)
if self._last_progress_report != progress_int:
self._last_progress_report = progress_int
self._report_print_progress_to_plugins(progress_int)
if progress == 0:
print_time_left = None
print_time_left_origin = None
elif progress == 1.0:
print_time_left = 0
print_time_left_origin = None
else:
original_estimate = None
original_estimate_type = None
if self._job.average_past_total is not None:
original_estimate = self._job.average_past_total
original_estimate_type = "average"
elif self._job.analysis_total is not None:
original_estimate = self._job.analysis_total
original_estimate_type = "analysis"
print_time_left, print_time_left_origin = self._job.estimator.estimate(progress,
print_time,
cleaned_print_time,
original_estimate,
original_estimate_type)
return self._dict(completion=progress * 100 if progress is not None else None,
filepos=pos,
printTime=int(print_time) if print_time is not None else None,
printTimeLeft=int(print_time_left) if print_time_left is not None else None,
printTimeLeftOrigin=print_time_left_origin)
def _add_temperature_data(self, temperatures):
if temperatures is None:
temperatures = dict()
@@ -914,12 +912,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
job = self._job.job
if job is None:
# TODO fix this, this won't work for deselecting jobs
self._remove_job()
return
rolling_window = None
threshold = None
countdown = None
average_past_total = None
analysis_total = None
filament = None
@@ -928,18 +924,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
display_name = job.name
if isinstance(job, SDFilePrintjob):
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
rolling_window = 15 / job.status_interval
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = 60
# we are happy when one rolling window has been stable
countdown = rolling_window
elif isinstance(job, LocalGcodeFilePrintjob):
if isinstance(job, LocalGcodeFilePrintjob):
# local file means we might have some information about the job stored in the file manager!
try:
file_data = self._file_manager.get_metadata(FileDestinations.LOCAL, job.path)
@@ -977,11 +962,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
self._state_monitor.set_job_data(job_data)
# set our internal job data
estimation_helper = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
# TODO other way to determine job type?
if isinstance(job, SDFilePrintjob):
job_type = "sdcard"
elif isinstance(job, LocalGcodeStreamjob):
job_type = "stream"
else:
job_type = "local"
self._job = JobData(job=job,
average_past_total=average_past_total,
analysis_total=analysis_total,
estimator=estimation_helper)
estimator=self._create_estimator(job_type))
job.register_listener(self)
def _send_initial_state_update(self, callback):
@@ -1011,7 +1004,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
return None
job = self._job.job
return FileDestinations.SDCARD if isinstance(job, SDFilePrintjob) else FileDestinations.LOCAL
if not isinstance(job, StoragePrintjob):
return None
return job.storage
#~~ octoprint.comm.protocol.ProtocolListener implementation
@@ -1028,7 +1024,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
self._logger.info("Protocol state changed from {} to {}".format(old_state, new_state))
# forward relevant state changes to file manager
if old_state == ProtocolState.PRINTING:
if old_state == ProtocolState.PROCESSING:
if self._job is not None:
if new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR):
self._file_manager.log_print(self._get_origin_for_job(self._job.job),
@@ -1039,14 +1035,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
self._printer_profile_manager.get_current_or_default()["id"])
self._analysis_queue.resume() # printing done, put those cpu cycles to good use
elif new_state == ProtocolState.PRINTING:
elif new_state == ProtocolState.PROCESSING:
self._analysis_queue.pause() # do not analyse files while printing
elif new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) and old_state != ProtocolState.DISCONNECTING:
self.disconnect()
self._setCurrentZ(None)
self._set_current_z(None)
self._update_progress_data()
self._setOffsets(None)
self._set_offsets(None)
self._addTemperatureData()
self._update_job()
self._printer_profile_manager.deselect()
@@ -1077,19 +1073,30 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
self._sd_filelist_available.set()
#~~ octoprint.comm.protocol.PositionAwareProtocolListener implementation
def on_protocol_position_z_update(self, protocol, z):
if protocol != self._protocol:
return
old_z = self._current_z
if z != old_z:
eventManager().fire(Events.Z_CHANGE, dict(new=z, old=old_z))
self._set_current_z(z)
#~~ octoprint.job.PrintjobListener
def on_job_progress(self, job):
if job != self._job.job:
if self._job is None or job != self._job.job:
return
self._update_progress_data()
self._state_monitor.trigger_progress_update()
def on_job_started(self, job):
if job != self._job.job:
if self._job is None or job != self._job.job:
return
# TODO include position in payload if available
payload = job.event_payload()
if payload:
eventManager().fire(Events.PRINT_STARTED, payload)
@@ -1098,37 +1105,54 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
must_be_set=False)
def on_job_done(self, job):
if job != self._job.job:
if self._job is None or job != self._job.job:
return
if isinstance(self._job.job, LocalGcodeStreamjob):
# streaming job
if self._streamingFinishedCallback is not None:
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
# both parameters
self._streamingFinishedCallback(self._job.job.name, self._job.job.name, FileDestinations.SDCARD)
self._setCurrentZ(None)
self._set_current_z(None)
self._update_job()
self._update_progress_data()
else:
self._set_completion_progress_data()
# TODO include position in payload if available
else:
# all other job types
payload = job.event_payload()
if payload:
payload["time"] = job.elapsed
eventManager().fire(Events.PRINT_DONE, payload)
self._file_manager.log_print(payload["origin"],
payload["path"],
time.time(),
payload["time"],
True,
self._printer_profile_manager.get_current_or_default()["id"])
self._update_progress_data(completion=1.0,
filepos=payload["size"],
print_time=payload["time"],
print_time_left=0)
self._state_monitor.set_state(self._dict(text=self.get_state_string(),
flags=self._get_state_flags()))
eventManager().fire(Events.PRINT_DONE, payload)
self.script("afterPrintDone",
context=dict(event=payload),
must_be_set=False)
def log_print():
self._file_manager.log_print(payload["origin"],
payload["path"],
time.time(),
payload["time"],
True,
self._printer_profile_manager.get_current_or_default()["id"])
thread = threading.Thread(target=log_print)
thread.daemon = True
thread.start()
self._state_monitor.set_state({"text": self.get_state_string(), "flags": self._get_state_flags()})
def on_job_failed(self, job):
if job != self._job.job:
if self._job is None or job != self._job.job:
return
payload = job.event_payload()
@@ -1136,7 +1160,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
eventManager().fire(Events.PRINT_FAILED, payload)
def on_job_cancelling(self, job, firmware_error=None):
if job != self._job.job:
if self._job is None or job != self._job.job:
return
payload = job.event_payload()
@@ -1146,7 +1170,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
eventManager().fire(Events.PRINT_CANCELLING, payload)
def on_job_cancelled(self, job, cancel_position=None):
if job != self._job.job:
if self._job is None or job != self._job.job:
return
self._update_progress_data()
@@ -1176,7 +1200,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
thread.start()
def on_job_paused(self, job, pause_position=None):
if job != self._job.job:
if self._job is None or job != self._job.job:
return
payload = job.event_payload()
@@ -1189,7 +1213,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
must_be_set=False)
def on_job_resumed(self, job):
if job != self._job.job:
if self._job is None or job != self._job.job:
return
payload = job.event_payload()
@@ -1201,10 +1225,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
#~~ comm.MachineComPrintCallback implementation
def on_comm_z_change(self, newZ):
# TODO
pass
def on_comm_force_disconnect(self):
# TODO
self.disconnect()
@@ -1212,7 +1232,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
def on_comm_record_fileposition(self, origin, name, pos):
# TODO
try:
self._fileManager.save_recovery_data(origin, name, pos)
self._file_manager.save_recovery_data(origin, name, pos)
except NoSuchStorage:
pass
except:
+2 -2
View File
@@ -440,7 +440,7 @@ class Timelapse(object):
"""
Override this to perform additional actions upon start of a print job.
"""
self.start_timelapse(payload["file"])
self.start_timelapse(payload["name"])
def on_print_done(self, event, payload):
"""
@@ -484,7 +484,7 @@ class Timelapse(object):
self._capture_errors = 0
self._capture_success = 0
self._in_timelapse = True
self._gcode_file = os.path.basename(gcodeFile)
self._gcode_file = gcodeFile
self._file_prefix = "{}_{}".format(os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S"))
def stop_timelapse(self, do_create_movie=True, success=True):
View File
Whitespace-only changes.
View File
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,9 @@
# coding=utf-8
"""
Unit tests for ``octoprint.comm.protocol.reprap.commands.``.
"""
from __future__ import absolute_import
__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"
@@ -0,0 +1,49 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals, print_function, \
division
"""
Unit tests for ``octoprint.comm.protocol.reprap.commands.gcode.``.
"""
__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 unittest
import ddt
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
@ddt.ddt
class GcodeCommandTest(unittest.TestCase):
@ddt.data(
("M105", dict(code="M105")),
("M30 some_file.gco", dict(code="M30", param="some_file.gco")),
("G28 X0 Y0", dict(code="G28", x=0, y=0)),
("G28X0Y0", dict(code="G28", x=0, y=0)),
("M104 S220.0 T1", dict(code="M104", s=220.0, t=1)),
("M123.456 my parameter is long", dict(code="M123", subcode=456, param="my parameter is long")),
("M123 Hello there", dict(code="M123", param="Hello there")),
("M123 C P1 X0 Y2.3 Z-23.42 E+5", dict(code="M123", c=True, p=1, x=0, y=2.3, z=-23.42, e=5)),
("M123 P1 And a parameter too", dict(code="M123", p=1, param="And a parameter too")),
("T123", dict(code="T", tool=123)),
("F200", dict(code="F", feedrate=200))
)
@ddt.unpack
def test_from_line(self, line, expected_args):
actual = GcodeCommand.from_line(line)
for arg, value in expected_args.items():
self.assertEqual(value, getattr(actual, arg))
@ddt.data(
("G28 X0 Y0", "GcodeCommand(u'G28',x=0,y=0,original=u'G28 X0 Y0',type=None,tags=set([]))"),
("M30 some_file.gco", "GcodeCommand(u'M30',param=u'some_file.gco',original=u'M30 some_file.gco',type=None,tags=set([]))"),
("T1", "GcodeCommand(u'T',tool=1,original=u'T1',type=None,tags=set([]))"),
("F6000", "GcodeCommand(u'F',feedrate=6000,original=u'F6000',type=None,tags=set([]))"),
("M27 C", "GcodeCommand(u'M27',c=True,original=u'M27 C',type=None,tags=set([]))"),
)
@ddt.unpack
def test_repr(self, line, expected):
gcode = GcodeCommand.from_line(line)
self.assertEqual(expected, repr(gcode))