diff --git a/src/octoprint/comm/protocol/__init__.py b/src/octoprint/comm/protocol/__init__.py index 02bf40a03..abbcaee3d 100644 --- a/src/octoprint/comm/protocol/__init__.py +++ b/src/octoprint/comm/protocol/__init__.py @@ -83,12 +83,12 @@ class Protocol(ListenerAware, TransportListener): else: self.state = ProtocolState.DISCONNECTED - def process(self, job, position=0): + def process(self, job, position=0, tags=None): if not job.can_process(self): raise ValueError("Job {} cannot be processed with protocol {}".format(job, self)) self._job = job self._job.register_listener(self) - self._job.process(self, position=position) + self._job.process(self, position=position, tags=tags) def pause_processing(self): if self._job is None or self.state != ProtocolState.PRINTING: @@ -158,6 +158,8 @@ class ProtocolState(object): DISCONNECTING = "disconnecting" DISCONNECTED = "disconnected" PRINTING = "printing" + CANCELLING = "cancelling" + PAUSING = "pausing" PAUSED = "paused" ERROR = "error" DISCONNECTED_WITH_ERROR = "disconnected_with_error" @@ -246,7 +248,7 @@ class FileAwareProtocolMixin(object): def list_files(self): pass - def start_file_print(self, name, position=0): + def start_file_print(self, name, position=0, tags=None): pass def pause_file_print(self): diff --git a/src/octoprint/comm/protocol/reprap/__init__.py b/src/octoprint/comm/protocol/reprap/__init__.py index cdccd716c..90e23a0a3 100644 --- a/src/octoprint/comm/protocol/reprap/__init__.py +++ b/src/octoprint/comm/protocol/reprap/__init__.py @@ -157,7 +157,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt super(ReprapGcodeProtocol, self).disconnect() - def process(self, job, position=0): + def process(self, job, position=0, tags=None): if isinstance(job, LocalGcodeStreamjob): self._internal_state["only_from_job"] = True self._internal_state["trigger_events"] = False @@ -165,7 +165,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self._internal_state["only_from_job"] = False self._internal_state["trigger_events"] = True - super(ReprapGcodeProtocol, self).process(job, position=position) + super(ReprapGcodeProtocol, self).process(job, position=position, 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)] @@ -213,10 +213,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt def list_files(self): self._send_commands(self.flavor.command_sd_refresh()) - def start_file_print(self, name, position=0): + def start_file_print(self, name, position=0, **kwargs): + tags = kwargs.get("tags", set()) | "trigger:protocol.start_file_print" self._send_commands(self.flavor.command_sd_select_file(name), self.flavor.command_sd_set_pos(position), - self.flavor.command_sd_start()) + self.flavor.command_sd_start(), + tags=tags) def pause_file_print(self): self._send_commands(self.flavor.command_sd_pause()) @@ -398,7 +400,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,): + elif self.state in (ProtocolState.PRINTING, ProtocolState.PAUSING, ProtocolState.CANCELLING): consecutive_max = 10 # TODO take from config else: consecutive_max = 15 # TODO take from config @@ -612,9 +614,10 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self.notify_listeners("on_protocol_sd_status", self, current, total) def _finish_heatup(self): - if self._internal_state["heating_start"]: - self._internal_state["heating_lost"] = self._internal_state["heating_lost"] + (time.time() - self._internal_state["heating_start"]) - self._internal_state["heating_start"] = None + if self._internal_state["heating"]: + if self._internal_state["heating_start"]: + self._internal_state["heating_lost"] = self._internal_state["heating_lost"] + (time.time() - self._internal_state["heating_start"]) + self._internal_state["heating_start"] = None self._internal_state["heating"] = False ##~~ Sending @@ -727,13 +730,13 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt def _send_commands(self, *commands, **kwargs): # TODO return True or False depending on whether something/all? was sent - command_type = kwargs.get("command_type", None) + command_type = kwargs.get(b"command_type", None) for command in commands: if len(commands) > 1: command_type = None - self._send_command(command, command_type=command_type) + self._send_command(command, command_type=command_type, tags=kwargs.get(b"tags", set())) - def _send_command(self, command, command_type=None, on_sent=None): + def _send_command(self, command, command_type=None, on_sent=None, tags=None): if isinstance(command, GcodeCommand): gcode = command command = str(gcode) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 398201609..2effc91cc 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -592,8 +592,8 @@ class FileManager(object): name=dst_name)) eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) - def get_print_job(self, destination, path): - return self._storage(destination).get_print_job(path) + def create_print_job(self, destination, path, user=None): + return self._storage(destination).get_print_job(path, user=user) def has_analysis(self, destination, path): return self._storage(destination).has_analysis(path) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index cd6f76519..2ca0b1cdd 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -261,7 +261,7 @@ class StorageInterface(object): """ raise NotImplementedError() - def get_print_job(self, path): + def get_print_job(self, path, user=None): """ Retrieves the :class:`~octoprint.job.PrintJob` instance to use for printing ``path``. @@ -854,10 +854,13 @@ class LocalFileStorage(StorageInterface): metadata = self.get_metadata(path) return "analysis" in metadata - def get_print_job(self, path): + def get_print_job(self, path, user=None): from octoprint.job import LocalGcodeFilePrintjob return LocalGcodeFilePrintjob(self.path_on_disk(path), + "local", + self.path_in_storage(path), name=path, + user=user, event_data=dict(path=path, name=self.split_path(path)[1], origin="local")) diff --git a/src/octoprint/job/__init__.py b/src/octoprint/job/__init__.py index ca8bf0168..b5af2a274 100644 --- a/src/octoprint/job/__init__.py +++ b/src/octoprint/job/__init__.py @@ -15,13 +15,17 @@ from abc import ABCMeta, abstractmethod, abstractproperty class Printjob(ProtocolListener, ListenerAware): __metaclass__ = ABCMeta - def __init__(self, name=None, event_data=None): + def __init__(self, name=None, user=None, event_data=None): + if event_data is None: + event_data = dict() + super(Printjob, self).__init__() self._logger = logging.getLogger(__name__) self._start = None self._protocol = None self._printer_profile = None self._name = name + self._user = user self._event_data = event_data self._lost_time = 0 @@ -30,6 +34,10 @@ class Printjob(ProtocolListener, ListenerAware): def name(self): return self._name + @property + def user(self): + return self._user + @property def size(self): return None @@ -74,7 +82,7 @@ class Printjob(ProtocolListener, ListenerAware): def can_process(self, protocol): return False - def process(self, protocol, position=0): + def process(self, protocol, position=0, tags=None): self._start = time.time() self._protocol = protocol self._protocol.register_listener(self) @@ -97,7 +105,9 @@ class Printjob(ProtocolListener, ListenerAware): return None def event_payload(self): - return copy.deepcopy(self._event_data) + payload = copy.deepcopy(self._event_data) + payload["user"] = self._user + return payload def process_job_started(self): self.notify_listeners("on_job_started", self) @@ -124,10 +134,38 @@ class Printjob(ProtocolListener, ListenerAware): if new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) and self.active: self.cancel(error=True) -class LocalFilePrintjob(Printjob): - def __init__(self, path, encoding="utf-8", name=None, event_data=None): - Printjob.__init__(self, name=name, event_data=event_data) +class StoragePrintjob(Printjob): + def __init__(self, storage, path_in_storage, *args, **kwargs): + Printjob.__init__(self, *args, **kwargs) + self._storage = storage + self._path_in_storage = path_in_storage + + @property + def storage(self): + return self._storage + + @property + def path_in_storage(self): + return self._path_in_storage + + def event_payload(self): + payload = Printjob.event_payload(self) + payload["name"] = self.name + payload["path"] = self.path_in_storage + payload["origin"] = self.storage + return payload + + +class LocalFilePrintjob(StoragePrintjob): + + def __init__(self, path, *args, **kwargs): + encoding = kwargs.pop("encoding", "utf-8") + + StoragePrintjob.__init__(self, *args, **kwargs) + + if path is None or not os.path.exists(path): + raise ValueError("path must be set to a local file path") self._path = path self._encoding = encoding @@ -151,12 +189,7 @@ class LocalFilePrintjob(Printjob): def path(self): return self._path - def event_payload(self): - event_data = Printjob.event_payload(self) - event_data["size"] = self.size - return event_data - - def process(self, protocol, position=0): + def process(self, protocol, position=0, tags=None): Printjob.process(self, protocol, position=position) from octoprint.util import bom_aware_open @@ -248,18 +281,19 @@ class LocalGcodeStreamjob(LocalGcodeFilePrintjob): return line -class SDFilePrintjob(Printjob, FileAwareProtocolListener): +class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener): def __init__(self, path, status_interval=2.0): name = path if name.startswith("/"): name = name[1:] - Printjob.__init__(self, - name=name, - event_data=dict(name=name, - path=path, - origin="sdcard")) + StoragePrintjob.__init__(self, + name, + name=name, + event_data=dict(name=name, + path=path, + origin="sdcard")) self._filename = path self._status_interval = status_interval @@ -294,11 +328,11 @@ class SDFilePrintjob(Printjob, FileAwareProtocolListener): from octoprint.comm.protocol import FileAwareProtocolMixin return SDFilePrintjob in protocol.supported_jobs and isinstance(protocol, FileAwareProtocolMixin) - def process(self, protocol, position=0): + def process(self, protocol, position=0, tags=None): Printjob.process(self, protocol, position=position) self._protocol.register_listener(self) - self._protocol.start_file_print(self._filename, position=position) + self._protocol.start_file_print(self._filename, position=position, tags=tags) self._active = True self._last_pos = position diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index e8a5b6c95..0a05a0b82 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -161,7 +161,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, if not isinstance(callback, PrinterCallback): self._logger.warn("Registering an object as printer callback which doesn't implement the PrinterCallback interface") self._callbacks.append(callback) - self._sendInitialStateUpdate(callback) def unregister_callback(self, callback, *args, **kwargs): try: @@ -350,8 +349,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, # TODO #result = self._comm.sendGcodeScript(name, - replacements=context, - tags=kwargs.get("tags", set()) | {"trigger:printer.script"}) + # replacements=context, + # tags=kwargs.get("tags", set()) | {"trigger:printer.script"}) #if not result: # if must_be_set: # raise UnknownScript(name) @@ -469,7 +468,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, self._protocol.set_extrusion_multiplier(factor, tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"}) - def select_job(self, job, start_printing=False, user=None, pos=None, *args, **kwargs): + def select_job(self, job, start_printing=False, pos=None, *args, **kwargs): self._update_job(job) self._reset_progress_data() @@ -516,8 +515,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, self._update_progress_data() self._setCurrentZ(None) - self._protocol.process(self._job.job, position=pos, - tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"}) + self._protocol.process(self._job.job, + position=pos, + tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"}) def pause_print(self, *args, **kwargs): """ @@ -539,7 +539,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, return self._protocol.resume_processing() - def cancel_print(self, error=False): + def cancel_print(self, error=False, tags=None, *args, **kwargs): """ Cancel the current job. """ @@ -818,11 +818,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, def _update_progress_data(self): if self._job is None or not self._job.job.active: - self._state_monitor.set_progress(dict(completion=None, - filepos=None, - printTime=None, - printTimeLeft=None, - printTimeLeftOrigin=None)) + self._state_monitor.set_progress(self._dict(completion=None, + filepos=None, + printTime=None, + printTimeLeft=None, + printTimeLeftOrigin=None)) return estimated_total_print_time = self._estimate_total_for_job() @@ -870,14 +870,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, self._state_monitor.add_temperature(entry) def _remove_job(self): - job_data = dict(file=dict(name=None, - origin=None, - size=None, - date=None), - estimatedPrintTime=None, - averagePrintTime=None, - lastPrintTime=None, - filament=None) + job_data = self._dict(file=self._dict(name=None, + path=None, + display=None, + origin=None, + size=None, + date=None), + estimatedPrintTime=None, + averagePrintTime=None, + lastPrintTime=None, + filament=None, + user=None) self._state_monitor.set_job_data(job_data) self._job = None @@ -898,6 +901,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, last_total = None date = None + 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 @@ -916,9 +921,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, except: pass else: - if "display" in fileData: - display_name = fileData["display"] - if "analysis" in file_data: + if "display" in file_data: + display_name = file_data["display"] + + if "analysis" in file_data: if "estimatedPrintTime" in file_data["analysis"]: analysis_total = file_data["analysis"]["estimatedPrintTime"] if "filament" in file_data["analysis"].keys(): @@ -932,14 +938,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, last_total = file_data["statistics"]["lastPrintTime"][printer_profile] # set the job data on the state monitor - job_data = dict(file=dict(name=job.name, - origin=self._get_origin_for_job(job), - size=job.size, - date=date), - estimatedPrintTime=analysis_total, - averagePrintTime=average_past_total, - lastPrintTime=last_total, - filament=filament) + job_data = self._dict(file=self._dict(name=job.name, + path=job.path_in_storage, + display=display_name, + origin=self._get_origin_for_job(job), + size=job.size, + date=date), + estimatedPrintTime=analysis_total, + averagePrintTime=average_past_total, + lastPrintTime=last_total, + filament=filament, + user=job.user) self._state_monitor.set_job_data(job_data) # set our internal job data @@ -1253,13 +1262,11 @@ class StateMonitor(object): self._progress = self._get_current_progress() self._progress_dirty = False - return { - "state": self._state, - "job": self._job_data, - "currentZ": self._current_z, - "progress": self._progress, - "offsets": self._offsets - } + return dict(state=self._state, + job=self._job_data, + currentZ=self._current_z, + progress=self._progress, + offsets=self._offsets) class TemperatureHistory(InvariantContainer): diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index aeadbde97..5a3892643 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -508,12 +508,13 @@ def gcodeFileCommand(filename, target): print_after_loading = False if "print" in data and data["print"] in valid_boolean_trues: - with Permissions.PRINT.require(403):if not printer.is_operational(): - return make_response("Printer is not operational, cannot directly start printing", 409) - print_after_loading = True + with Permissions.PRINT.require(403): + if not printer.is_operational(): + return make_response("Printer is not operational, cannot directly start printing", 409) + print_after_loading = True - job = fileManager.get_print_job(target, filename) - printer.select_job(job, start_printing=print_after_loading, user=user) + job = fileManager.create_print_job(target, filename, user=user) + printer.select_job(job, start_printing=print_after_loading) elif command == "slice": with Permissions.SLICE.require(403):