From 8347f182ef7a1747205d54173c2cd74d2a499f40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 7 Jun 2018 14:16:47 +0200 Subject: [PATCH] queue markers, pausing, cancelling --- src/octoprint/comm/__init__.py | 2 +- src/octoprint/{ => comm}/job/__init__.py | 29 +- src/octoprint/comm/protocol/__init__.py | 76 ++++- .../comm/protocol/reprap/__init__.py | 297 ++++++++++++++++-- .../comm/protocol/reprap/flavors/generic.py | 12 +- src/octoprint/comm/protocol/reprap/util.py | 55 ++++ src/octoprint/filemanager/storage/local.py | 2 +- src/octoprint/filemanager/storage/sdcard.py | 2 +- src/octoprint/printer/standard.py | 80 +++-- src/octoprint/util/__init__.py | 4 +- 10 files changed, 485 insertions(+), 74 deletions(-) rename src/octoprint/{ => comm}/job/__init__.py (94%) diff --git a/src/octoprint/comm/__init__.py b/src/octoprint/comm/__init__.py index 915350f13..314566f29 100644 --- a/src/octoprint/comm/__init__.py +++ b/src/octoprint/comm/__init__.py @@ -3,6 +3,6 @@ from __future__ import absolute_import, unicode_literals __author__ = "Gina Häußge " __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" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/job/__init__.py b/src/octoprint/comm/job/__init__.py similarity index 94% rename from src/octoprint/job/__init__.py rename to src/octoprint/comm/job/__init__.py index d3507e99f..8173e0754 100644 --- a/src/octoprint/job/__init__.py +++ b/src/octoprint/comm/job/__init__.py @@ -85,6 +85,12 @@ class Printjob(ProtocolListener, ListenerAware): self._protocol = protocol self._protocol.register_listener(self) + def pause(self): + self.process_job_paused() + + def resume(self): + self.process_job_resumed() + def cancel(self, error=False): if error: self.process_job_failed() @@ -118,15 +124,12 @@ class Printjob(ProtocolListener, ListenerAware): 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) + def process_job_cancelled(self): + self.notify_listeners("on_job_cancelled", self) 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_paused(self): + self.notify_listeners("on_job_paused", self) def process_job_resumed(self): self.notify_listeners("on_job_resumed", self) @@ -137,7 +140,7 @@ class Printjob(ProtocolListener, ListenerAware): def reset_job(self): self._start = None - def on_protocol_state(self, protocol, old_state, new_state): + def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs): if new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) and self.active: self.cancel(error=True) @@ -182,6 +185,8 @@ class LocalFilePrintjob(StoragePrintjob): self._read_lines = 0 self._actual_lines = 0 + self._cancel_pos = None + self._handle = None @property @@ -200,6 +205,10 @@ class LocalFilePrintjob(StoragePrintjob): def read_lines(self): return self._read_lines + @property + def cancel_pos(self): + return self._cancel_pos + @property def active(self): return self._start is not None and self._handle is not None @@ -224,6 +233,10 @@ class LocalFilePrintjob(StoragePrintjob): self._pos = position self.process_job_started() + def cancel(self, error=False): + self._cancel_pos = self.pos + super(LocalFilePrintjob, self).cancel(error=error) + def get_next(self): from octoprint.util import to_unicode diff --git a/src/octoprint/comm/protocol/__init__.py b/src/octoprint/comm/protocol/__init__.py index fd87fae89..bc947628d 100644 --- a/src/octoprint/comm/protocol/__init__.py +++ b/src/octoprint/comm/protocol/__init__.py @@ -93,17 +93,20 @@ class Protocol(ListenerAware, TransportListener): def pause_processing(self, tags=None): if self._job is None or self.state != ProtocolState.PROCESSING: return - self.state = ProtocolState.PAUSED + self.state = ProtocolState.PAUSING + self._job.pause() def resume_processing(self, tags=None): if self._job is None or self.state != ProtocolState.PAUSED: return - self.state = ProtocolState.PROCESSING + self.state = ProtocolState.RESUMING + self._job.resume() def cancel_processing(self, error=False, tags=None): if self._job is not None and self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED): + self.state = ProtocolState.CANCELLING + self.notify_listeners("on_protocol_job_cancelling", self, self._job) self._job.cancel(error=error) - self.state = ProtocolState.CONNECTED def can_send(self): return True @@ -115,15 +118,27 @@ class Protocol(ListenerAware, TransportListener): pass def on_job_started(self, job): + self.notify_listeners("on_protocol_job_started", self, job) + self.state = ProtocolState.PROCESSING + + def on_job_paused(self, job, *args, **kwargs): + self.notify_listeners("on_protocol_job_paused", self, job) + self.state = ProtocolState.PAUSED + + def on_job_resumed(self, job): + self.notify_listeners("on_protocol_job_resumed", self, job) self.state = ProtocolState.PROCESSING def on_job_done(self, job): + self.notify_listeners("on_protocol_job_done", self, job) self._job_processed(job) def on_job_cancelled(self, job): + self.notify_listeners("on_protocol_job_cancelled", self, job) self._job_processed(job) def on_job_failed(self, job): + self.notify_listeners("on_protocol_job_failed", self, job) self._job_processed(job) def _job_processed(self, job): @@ -158,12 +173,17 @@ class ProtocolState(object): DISCONNECTING = "disconnecting" DISCONNECTED = "disconnected" PROCESSING = "processing" + FINISHING = "finishing" CANCELLING = "cancelling" PAUSING = "pausing" + RESUMING = "resuming" PAUSED = "paused" ERROR = "error" DISCONNECTED_WITH_ERROR = "disconnected_with_error" + PROCESSING_STATES = (PROCESSING, CANCELLING, PAUSING, RESUMING, FINISHING) + OPERATIONAL_STATES = (CONNECTED, PAUSED) + PROCESSING_STATES + class ProtocolAlreadyConnectedError(Exception): pass @@ -281,38 +301,68 @@ class FileStreamingProtocolMixin(FileManagementProtocolMixin): class ProtocolListener(object): - def on_protocol_state(self, protocol, old_state, new_state): + def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs): pass - def on_protocol_temperature(self, protocol, temperatures): + def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs): pass - def on_protocol_log(self, protocol, message): + def on_protocol_log(self, protocol, message, *args, **kwargs): + pass + + def on_protocol_job_started(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_pausing(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_paused(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_resuming(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_resumed(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_finishing(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_done(self, protocol, job, *args, **kwargs): + pass + + def on_protocol_job_failed(self, protocol, job, *args, **kwargs): pass class FileAwareProtocolListener(object): - def on_protocol_file_storage_available(self, protocol, available): + def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs): pass - def on_protocol_file_list(self, protocol, files): + def on_protocol_file_list(self, protocol, files, *args, **kwargs): pass - def on_protocol_file_status(self, protocol, pos, total): + def on_protocol_file_status(self, protocol, pos, total, *args, **kwargs): pass - def on_protocol_file_print_started(self, protocol, name, size): + def on_protocol_file_print_started(self, protocol, name, size, *args, **kwargs): pass - def on_protocol_file_print_done(self, protocol): + def on_protocol_file_print_done(self, protocol, *args, **kwargs): pass class PositionAwareProtocolListener(object): - def on_protocol_position_all_update(self, protocol, position): + def on_protocol_position_all_update(self, protocol, position, *args, **kwargs): pass - def on_protocol_position_z_update(self, protocol, z): + def on_protocol_position_z_update(self, protocol, z, *args, **kwargs): pass diff --git a/src/octoprint/comm/protocol/reprap/__init__.py b/src/octoprint/comm/protocol/reprap/__init__.py index d780ef3fb..ed91fed53 100644 --- a/src/octoprint/comm/protocol/reprap/__init__.py +++ b/src/octoprint/comm/protocol/reprap/__init__.py @@ -16,14 +16,12 @@ from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand from octoprint.comm.protocol.reprap.flavors import GenericFlavor, all_flavors -from octoprint.comm.protocol.reprap.util import normalize_command_handler_result, SendQueue, SendToken, LineHistory +from octoprint.comm.protocol.reprap.util import normalize_command_handler_result, SendQueue, SendToken, LineHistory, QueueMarker, SendQueueMarker, PositionRecord -from octoprint.util import TypedQueue, TypeAlreadyInQueue - -from octoprint.job import LocalGcodeFilePrintjob, SDFilePrintjob, \ +from octoprint.comm.job import LocalGcodeFilePrintjob, SDFilePrintjob, \ LocalGcodeStreamjob -from octoprint.util import to_str, to_unicode, protectedkeydict, CountedEvent, monotonic_time +from octoprint.util import TypedQueue, TypeAlreadyInQueue, ResettableTimer, to_str, to_unicode, protectedkeydict, CountedEvent, monotonic_time from octoprint.events import Events @@ -103,6 +101,8 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self._commdebug_logger = logging.getLogger("COMMDEBUG") self._phase_logger = logging.getLogger(__name__ + ".command_phases") + self._terminal_log = collections.deque([], 20) + self.flavor = flavor if flavor is not None else GenericFlavor self.timeouts = dict( connection=connection_timeout, @@ -193,6 +193,16 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self._last_lines = LineHistory(maxlen = 50) self._last_communication_error = None + # last known positions + self.last_position = PositionRecord() + self.pause_position = PositionRecord() + self.cancel_position = PositionRecord() + + # pause and cancel processing + self._record_pause_data = False + self._record_cancel_data = False + + # hooks # TODO GCODE Hooks self._gcode_hooks = dict(queuing=dict(), queued=dict(), @@ -206,11 +216,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt # TODO action hooks self._action_hooks = dict() - # temperature polling + # polling self._temperature_poller = None + self._sd_status_poller = None - # terminal logging - self._terminal_log = collections.deque([], 20) + # script processing + self._suppress_scripts = set() # resend logging self._log_resends = True @@ -222,6 +233,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt # mutexes self._line_mutex = threading.RLock() self._send_queue_mutex = threading.RLock() + self._cancel_mutex = threading.RLock() + self._suppress_scripts_mutex = threading.RLock() + + # timers + self._pause_position_timer = None + self._cancel_position_timer = None # sending thread self._send_queue_active = False @@ -271,6 +288,152 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt super(ReprapGcodeProtocol, self).process(job, position=position, tags=tags) + # cancel handling + + def _cancel_preparation_failed(self): + self.process_protocol_log("Did not receive parseable position data from printer within {}s, " + "continuing without it".format(self.timeouts.get("position_log_wait", 10.0))) + self._cancel_preparation_done() + + def _cancel_preparation_done(self, check_timer=True): + with self._cancel_mutex: + if self._cancel_position_timer is not None: + self._cancel_position_timer.cancel() + self._cancel_position_timer = None + elif check_timer: + return + + # TODO: recovery data + + def finalize(): + self.state = ProtocolState.CONNECTED + self.notify_listeners("on_protocol_job_cancelled", self, self._job) + + self.send_commands(SendQueueMarker(finalize)) + self._continue_sending() + + def cancel_processing(self, error=False, tags=None, log_position=True): + if self.state not in (ProtocolState.PROCESSING, ProtocolState.PAUSED, ProtocolState.PAUSING): + return + + if self._job is None: + return + + # TODO cancel file streaming + + if tags is None: + tags = set() + + def on_move_finish_requested(): + self._record_cancel_data = True + + with self._cancel_mutex: + if self._cancel_position_timer is not None: + self._cancel_position_timer.cancel() + self._cancel_position_timer = ResettableTimer(self.timeouts.get("position_log_wait", 10.0), + self._cancel_preparation_failed) + self._cancel_position_timer.start() + + self.send_commands(self.flavor.command_get_position(), + tags=tags | {"trigger:comm.cancel", + "trigger:record_position"}) + self._continue_sending() + + # cancel the job + self.state = ProtocolState.CANCELLING + self.notify_listeners("on_protocol_job_cancelling", self, self._job) + self._job.cancel(error=error) + + if log_position: + self.send_commands(self.flavor.command_finish_moving(), + on_sent=on_move_finish_requested, + tags=tags | {"trigger:comm.cancel", + "trigger:record_position"}) + self._continue_sending() + else: + self._cancel_preparation_done(check_timer=False) + + # pause handling + + def _pause_preparation_failed(self): + self.process_protocol_log("Did not receive parseable position data from printer within {}s, " + "continuing without it".format(self.timeouts.get("position_log_wait", 10.0))) + self._pause_preparation_done() + + def _pause_preparation_done(self, check_timer=True, suppress_script=None): + # do we need to suppress the script? + if suppress_script is not None: + with self._suppress_scripts_mutex: + suppress_script = "pause" in self._suppress_scripts + try: + self._suppress_scripts.remove("pause") + except KeyError: + pass + + # do we need to stop a timer? + with self._pause_mutex: + if self._pause_position_timer is not None: + self._pause_position_timer.cancel() + self._pause_position_timer = None + elif check_timer: + return + + # wait for current commands to be sent, then switch to paused state + def finalize(): + self.state = ProtocolState.PAUSED + self.notify_listeners("on_protocol_job_paused", self, self._job, suppress_script=suppress_script) + + self.send_commands(SendQueueMarker(finalize)) + self._continue_sending() + + def pause_processing(self, tags=None, log_position=True, suppress_scripts_and_commands=False): + if self._job is None or self.state != ProtocolState.PROCESSING: + return + + if tags is None: + tags = set() + + self.state = ProtocolState.PAUSING + self.notify_listeners("on_protocol_job_pausing", self, self._job) + self._job.pause() + + if suppress_scripts_and_commands: + with self._suppress_scripts_mutex: + self._suppress_scripts.add("pause") + + def on_move_finish_requested(): + self._record_pause_data = True + + with self._pause_mutex: + if self._pause_position_timer is not None: + self._pause_position_timer.cancel() + self._pause_position_timer = None + self._pause_position_timer = ResettableTimer(self.timeouts.get("position_log_wait", 10.0), + self._pause_preparation_failed) + self._pause_position_timer.start() + + self.send_commands(self.flavor.command_get_position(), + tags=tags | {"trigger:comm.set_pause", + "trigger:pause", + "trigger:record_position"}) + self._continue_sending() + + if log_position: + self.send_commands(self.flavor.command_finish_moving(), + on_sent=on_move_finish_requested, + tags=tags | {"trigger:comm.set_pause", + "trigger:pause", + "trigger:record_position"}) + self._continue_sending() + else: + self._pause_preparation_done(check_timer=False, suppress_script=suppress_scripts_and_commands) + + def resume_processing(self, tags=None, only_adjust_state=False): + if only_adjust_state: + self.state = ProtocolState.PROCESSING + else: + super(ReprapGcodeProtocol, self).resume_processing(tags=tags) + def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False): commands = [self.flavor.command_move(x=x, y=y, z=z, e=e, f=feedrate)] @@ -351,24 +514,27 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt tags = kwargs.get(b"tags") force = kwargs.get(b"force", False) + def sanitize_command(c, ct, t): + if isinstance(c, Command): + return c.with_type(ct).with_tags(t) + elif isinstance(c, QueueMarker): + return c + else: + return to_command(c, type=ct, tags=t) + # TODO job on hold - if self.state == ProtocolState.PROCESSING and not self._job.parallel and not force: + if self.state in ProtocolState.PROCESSING_STATES and not self._job.parallel and not force: if len(commands) > 1: command_type = None for command in commands: - if not isinstance(command, Command): - command = to_command(command, type=command_type, tags=tags) - else: - command = command.with_type(command_type).with_tags(tags) - try: - self._command_queue.put((command, on_sent), item_type=command_type) + self._command_queue.put((sanitize_command(command, command_type, tags), 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) + self._send_commands(*commands, on_sent=on_sent, command_type=command_type, tags=tags) ##~~ State handling @@ -426,11 +592,20 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt ##~~ Job handling + def on_job_cancelled(self, job): + pass + + def on_job_paused(self, job, *args, **kwargs): + pass + + def on_job_done(self, job): + pass + def _job_processed(self, job): self._internal_flags["expect_continous_comms"] = False self._internal_flags["only_from_job"] = False self._internal_flags["trigger_events"] = True - super(ReprapGcodeProtocol, self)._job_processed(job) + self._job.unregister_listener(self) ##~~ Transport logging @@ -795,6 +970,45 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"]) + def _on_message_position(self, position): + self.last_position.valid = True + self.last_position.x = position.get("x") + self.last_position.y = position.get("y") + self.last_position.z = position.get("z") + + # TODO determine e, f and t + """ + if "e" in position: + self.last_position.e = position.get("e") + else: + # multiple extruder coordinates provided, find current one + self.last_position.e = position.get("e{}".format(self._currentTool)) if not self.isSdFileSelected() else None + + for key in [key for key in position if key.startswith("e") and len(key) > 1]: + setattr(self.last_position, key, position.get(key)) + + self.last_position.t = self._currentTool if not self.isSdFileSelected() else None + self.last_position.f = self._currentF if not self.isSdFileSelected() else None + """ + + reason = None + + if self._record_pause_data: + reason = "pause" + self._record_pause_data = False + self.pause_position.copy_from(self.last_position) + #self.pause_temperature.copy_from(self.last_temperature) # TODO pause temperature + self._pause_preparation_done() + + if self._record_cancel_data: + reason = "cancel" + self._record_cancel_data = False + self.cancel_position.copy_from(self.last_position) + #self.cancel_temperature.copy_from(self.last_temperature) # TODO cancel temperature + self._cancel_preparation_done() + + self.notify_listeners("on_protocol_position_all_update", self, position, reason=reason) + def _on_message_firmware_info(self, firmware_name, data): # TODO #self._event_bus.fire(Events.FIRMWARE_DATA, dict(name=firmware_name, data=copy.copy(data))) @@ -942,8 +1156,15 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt # return False line = self._job.get_next() - # TODO implement QueueMarker - if line is None: + if isinstance(line, QueueMarker): + self._send_command(line) + # TODO on job progress + + # end of file, return false so that the next round in continue_sending will process + # what we just enqueued (any scripts + marker) + return False + + elif line is None: # end of job, return False return False @@ -993,21 +1214,29 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self._command_queue.task_done() def _send_commands(self, *commands, **kwargs): - command_type = kwargs.get(b"command_type", None) + command_type = kwargs.pop(b"command_type", None) result = False for command in commands: if len(commands) > 1: command_type = None - result = self._send_command(command, command_type=command_type, tags=kwargs.get(b"tags", None)) or result + result = self._send_command(command, command_type=command_type, **kwargs) or result return result def _send_command(self, command, command_type=None, tags=None, on_sent=None): - if not isinstance(command, Command): - command = to_command(command, type=command_type, tags=tags) - elif command_type or tags: - command = command.with_type(command_type).with_tags(tags) - with self._send_queue_mutex: + if isinstance(command, QueueMarker): + if isinstance(command, SendQueueMarker): + self._enqueue_for_sending(command) + return True + else: + return False + + elif isinstance(command, Command) and (command_type or tags): + command = command.with_type(command_type).with_tags(tags) + + else: + command = to_command(command, type=command_type, tags=tags) + if self._internal_flags["trigger_events"]: results = self._process_command_phase("queuing", command) @@ -1067,7 +1296,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt Enqueues a command and optional command_type and linenumber in the send queue. Arguments: - command (Command): The command to send + command (Command or SendQueueMarker): The command to send or the marker to enqueue linenumber (int): An optional line number to use for sending the command. on_sent (callable or None): Callback to call when the command has been sent @@ -1079,7 +1308,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt if resend: target = "resend" - self._send_queue.put((command, linenumber, on_sent, processed), item_type=command.type, target=target) + if isinstance(command, Command): + command_type = command.type + else: + command_type = None + + self._send_queue.put((command, linenumber, on_sent, processed), item_type=command_type, target=target) return True except TypeAlreadyInQueue as e: self._logger.debug("Type already in queue: {}".format(e.type)) @@ -1112,6 +1346,11 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt # fetch command and optional linenumber from queue command, linenumber, on_sent, processed = entry + if isinstance(command, SendQueueMarker): + command.run() + self._continue_sending() + continue + 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!) @@ -1621,7 +1860,7 @@ if __name__ == "__main__": from octoprint.comm.protocol.reprap.virtual import VirtualPrinter from octoprint.comm.protocol.reprap.flavors import GenericFlavor from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener - from octoprint.job import PrintjobListener + from octoprint.comm.job import PrintjobListener import os diff --git a/src/octoprint/comm/protocol/reprap/flavors/generic.py b/src/octoprint/comm/protocol/reprap/flavors/generic.py index 039ab4581..5178d70f3 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/generic.py +++ b/src/octoprint/comm/protocol/reprap/flavors/generic.py @@ -164,7 +164,7 @@ class GenericFlavor(object): @classmethod def message_position(cls, line, lower_line, state, flags): - return "C:" in line or "X:" in line + return 'X:' in line and 'Y:' in line and 'Z:' in line @classmethod def message_firmware_info(cls, line, lower_line, state, flags): @@ -302,7 +302,7 @@ class GenericFlavor(object): position = dict(x=None, y=None, z=None, e=None) for match in re.finditer(cls.regex_position, line): position[match.group(b"axis").lower()] = float(match.group(b"pos")) - return position + return dict(position=position) @classmethod def parse_message_firmware_info(cls, line, lower_line, state, flags): @@ -389,6 +389,14 @@ class GenericFlavor(object): def command_get_firmware_info(cls): return GcodeCommand("M115") + @classmethod + def command_finish_moving(cls): + return GcodeCommand("M400") + + @classmethod + def command_get_position(cls): + return GcodeCommand("M114") + @classmethod def command_get_temp(cls): return GcodeCommand("M105") diff --git a/src/octoprint/comm/protocol/reprap/util.py b/src/octoprint/comm/protocol/reprap/util.py index 54220921b..109d7b84e 100644 --- a/src/octoprint/comm/protocol/reprap/util.py +++ b/src/octoprint/comm/protocol/reprap/util.py @@ -15,6 +15,7 @@ from octoprint.util import PrependableQueue, TypeAlreadyInQueue, CountedEvent from past.builtins import basestring import copy +import logging import threading try: @@ -363,3 +364,57 @@ class LineHistory(object): del self._line_number_lookup[line_number] except KeyError: pass + + +class QueueMarker(object): + + def __init__(self, callback): + self.callback = callback + + def run(self): + if callable(self.callback): + try: + self.callback() + except: + logging.getLogger(__name__).exception("Error while running callback of QueueMarker") + + +class SendQueueMarker(QueueMarker): + pass + + +class PositionRecord(object): + _standard_attrs = {"x", "y", "z", "e", "f", "t"} + + @classmethod + def valid_e(cls, attr): + if not attr.startswith("e"): + return False + + try: + int(attr[1:]) + except: + return False + + return True + + def __init__(self, *args, **kwargs): + attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)]) + for attr in attrs: + setattr(self, attr, kwargs.get(attr)) + + def copy_from(self, other): + # make sure all standard attrs and attrs from other are set + attrs = self._standard_attrs | set([key for key in dir(other) if self.valid_e(key)]) + for attr in attrs: + setattr(self, attr, getattr(other, attr)) + + # delete attrs other doesn't have + attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs + for attr in attrs: + delattr(self, attr) + + def as_dict(self): + attrs = self._standard_attrs | set([key for key in dir(self) if self.valid_e(key)]) + return dict((attr, getattr(self, attr)) for attr in attrs) + diff --git a/src/octoprint/filemanager/storage/local.py b/src/octoprint/filemanager/storage/local.py index 4f1e782d0..cd091d7b6 100644 --- a/src/octoprint/filemanager/storage/local.py +++ b/src/octoprint/filemanager/storage/local.py @@ -440,7 +440,7 @@ class LocalFileStorage(Storage): return "analysis" in metadata def create_print_job(self, path, user=None): - from octoprint.job import LocalGcodeFilePrintjob + from octoprint.comm.job import LocalGcodeFilePrintjob return LocalGcodeFilePrintjob(self.path_on_disk(path), "local", self.path_in_storage(path), diff --git a/src/octoprint/filemanager/storage/sdcard.py b/src/octoprint/filemanager/storage/sdcard.py index 5670b5f84..daa0b5f10 100644 --- a/src/octoprint/filemanager/storage/sdcard.py +++ b/src/octoprint/filemanager/storage/sdcard.py @@ -10,5 +10,5 @@ from . import Storage, StorageError class PrinterSDStorage(Storage): def create_print_job(self, path, user=None): - from octoprint.job import SDFilePrintjob + from octoprint.comm.job import SDFilePrintjob return SDFilePrintjob("/" + path, user=user) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 89317ee76..5180c8982 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -15,6 +15,7 @@ import os import threading import time +# noinspection PyCompatibility from past.builtins import basestring from frozendict import frozendict @@ -26,13 +27,12 @@ from octoprint.plugin import plugin_manager, ProgressPlugin from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation, InvalidFileType from octoprint.printer.estimation import PrintTimeEstimator from octoprint.settings import settings -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, PositionAwareProtocolListener, ProtocolState -from octoprint.job import StoragePrintjob, LocalGcodeFilePrintjob, LocalGcodeStreamjob, SDFilePrintjob, PrintjobListener +from octoprint.comm.job import StoragePrintjob, LocalGcodeFilePrintjob, LocalGcodeStreamjob, SDFilePrintjob from collections import namedtuple @@ -67,7 +67,10 @@ def _serial_factory(port=None, baudrate=None): return None -class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, FileAwareProtocolListener, PositionAwareProtocolListener, PrintjobListener): +class Printer(PrinterInterface, + ProtocolListener, + FileAwareProtocolListener, + PositionAwareProtocolListener): """ 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. @@ -614,6 +617,14 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, return "Sending file to SD" else: return "Printing" + elif state == ProtocolState.PAUSING: + return "Pausing" + elif state == ProtocolState.RESUMING: + return "Resuming" + elif state == ProtocolState.CANCELLING: + return "Cancelling" + elif state == ProtocolState.FINISHING: + return "Finishing" elif state == ProtocolState.PAUSED: return "Paused" elif state == ProtocolState.DISCONNECTED_WITH_ERROR: @@ -1104,15 +1115,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, self._set_current_z(z) - #~~ octoprint.job.PrintjobListener + #~~ octoprint.comm.protocol.JobAwareProtocolListener implementation - def on_job_progress(self, job): - if self._job is None or job != self._job.job: + def on_protocol_job_processing(self, protocol, job, suppress_script=False): + if protocol != self._protocol: return - self._state_monitor.trigger_progress_update() - - def on_job_started(self, job, suppress_script=False): if self._job is None or job != self._job.job: return @@ -1124,7 +1132,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, context=dict(event=payload), must_be_set=False) - def on_job_done(self, job, suppress_script=False): + def on_protocol_job_done(self, protocol, job, suppress_script=False): + if protocol != self._protocol: + return + if self._job is None or job != self._job.job: return @@ -1172,7 +1183,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, thread.start() - def on_job_failed(self, job): + def on_protocol_job_failed(self, protocol, job, *args, **kwargs): + if protocol != self._protocol: + return + if self._job is None or job != self._job.job: return @@ -1180,22 +1194,33 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, if payload: eventManager().fire(Events.PRINT_FAILED, payload) - def on_job_cancelling(self, job, firmware_error=None): + def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs): + if protocol != self._protocol: + return + if self._job is None or job != self._job.job: return + firmware_error = kwargs.get("error", None) + 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, cancel_position=None, suppress_script=False): + def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs): + if protocol != self._protocol: + return + if self._job is None or job != self._job.job: return self._update_progress_data() + cancel_position = kwargs.get("position", None) + suppress_scripts = kwargs.get("suppress_scripts", None) + payload = job.event_payload() if payload: payload["time"] = job.elapsed @@ -1203,7 +1228,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, payload["position"] = cancel_position eventManager().fire(Events.PRINT_CANCELLED, payload) - if not suppress_script: + if not suppress_scripts: self.script("afterPrintCancelled", context=dict(event=payload), must_be_set=False) @@ -1221,32 +1246,51 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, thread.daemon = True thread.start() - def on_job_paused(self, job, pause_position=None, suppress_script=False): + def on_protocol_job_paused(self, protocol, job, *args, **kwargs): + if protocol != self._protocol: + return + if self._job is None or job != self._job.job: return + pause_position = kwargs.get("position", None) + suppress_scripts = kwargs.get("suppress_scripts", None) + payload = job.event_payload() if payload: if pause_position: payload["position"] = pause_position eventManager().fire(Events.PRINT_PAUSED, payload) - if not suppress_script: + if not suppress_scripts: self.script("afterPrintPaused", context=dict(event=payload), must_be_set=False) - def on_job_resumed(self, job, suppress_script=False): + def on_protocol_job_resumed(self, protocol, job, *args, **kwargs): + if protocol != self._protocol: + return + if self._job is None or job != self._job.job: return + suppress_scripts = kwargs.get("suppress_scripts", False) + payload = job.event_payload() if payload: eventManager().fire(Events.PRINT_RESUMED, payload) - if not suppress_script: + if not suppress_scripts: self.script("beforePrintResumed", context=dict(event=payload), must_be_set=False) + # ~~ octoprint.comm.job.PrintjobListener implementation + + def on_job_progress(self, job): + if self._job is None or job != self._job.job: + return + + self._state_monitor.trigger_progress_update() + #~~ comm.MachineComPrintCallback implementation def on_comm_force_disconnect(self): diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 539ca4065..f68911e0b 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1282,7 +1282,7 @@ class ResettableTimer(threading.Thread): on_reset (callable): Callback to call when the timer is reset. """ - def __init__(self, interval, function, args=None, kwargs=None, on_reset=None, on_cancelled=None): + def __init__(self, interval, function, args=None, kwargs=None, on_reset=None, on_cancelled=None, daemon=True): threading.Thread.__init__(self) self._event = threading.Event() self._mutex = threading.Lock() @@ -1300,6 +1300,8 @@ class ResettableTimer(threading.Thread): self.on_cancelled = on_cancelled self.on_reset = on_reset + self.daemon = daemon + def run(self): while self.is_reset: