From 13e5cf45ec949dc0e15d4f61c0e5284349b1eb85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 23 Mar 2018 14:52:38 +0100 Subject: [PATCH] Fix reset handling while printing Could get stuck in cancelling due to resend issues. Should fix #2509 --- .../plugins/virtual_printer/virtual.py | 105 +++++++------- src/octoprint/static/js/app/dataupdater.js | 31 ++++- src/octoprint/util/comm.py | 131 +++++++++++++++--- 3 files changed, 190 insertions(+), 77 deletions(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 8895a5625..7531df71e 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -168,72 +168,73 @@ class VirtualPrinter(object): .format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=settings().get(["devel", "virtualPrinter"])) def _reset(self): - self._clearQueue(self.incoming) - self._clearQueue(self.outgoing) - self._clearQueue(self.buffered) + with self._incoming_lock: + self._relative = True + self._lastX = 0.0 + self._lastY = 0.0 + self._lastZ = 0.0 + self._lastE = [0.0] * self.extruderCount + self._lastF = 200 - self._relative = True - self._lastX = 0.0 - self._lastY = 0.0 - self._lastZ = 0.0 - self._lastE = [0.0] * self.extruderCount - self._lastF = 200 + self._unitModifier = 1 + self._feedrate_multiplier = 100 + self._flowrate_multiplier = 100 - self._unitModifier = 1 - self._feedrate_multiplier = 100 - self._flowrate_multiplier = 100 - - self._sdCardReady = True - self._sdPrinting = False - if self._sdPrinter: + self._sdCardReady = True self._sdPrinting = False - self._sdPrintingSemaphore.set() - self._sdPrinter = None - self._selectedSdFile = None - self._selectedSdFileSize = None - self._selectedSdFilePos = None + if self._sdPrinter: + self._sdPrinting = False + self._sdPrintingSemaphore.set() + self._sdPrinter = None + self._selectedSdFile = None + self._selectedSdFileSize = None + self._selectedSdFilePos = None - if self._writingToSdHandle: - try: - self._writingToSdHandle.close() - except: - pass - self._writingToSd = False - self._writingToSdHandle = None - self._newSdFilePos = None + if self._writingToSdHandle: + try: + self._writingToSdHandle.close() + except: + pass + self._writingToSd = False + self._writingToSdHandle = None + self._newSdFilePos = None - self._heatingUp = False + self._heatingUp = False - self.currentLine = 0 - self.lastN = 0 + self.currentLine = 0 + self.lastN = 0 - self._debug_awol = False - self._debug_sleep = None - self._sleepAfterNext.clear() - self._sleepAfter.clear() + self._debug_awol = False + self._debug_sleep = None + self._sleepAfterNext.clear() + self._sleepAfter.clear() - self._dont_answer = False + self._dont_answer = False - self._debug_drop_connection = False + self._debug_drop_connection = False - self._killed = False + self._killed = False - self._triggerResendAt100 = True - self._triggerResendWithTimeoutAt105 = True - self._triggerResendWithMissingLinenoAt110 = True - self._triggerResendWithChecksumMismatchAt115 = True + self._triggerResendAt100 = True + self._triggerResendWithTimeoutAt105 = True + self._triggerResendWithMissingLinenoAt110 = True + self._triggerResendWithChecksumMismatchAt115 = True - if self._temperature_reporter is not None: - self._temperature_reporter.cancel() - self._temperature_reporter = None + if self._temperature_reporter is not None: + self._temperature_reporter.cancel() + self._temperature_reporter = None - if self._sdstatus_reporter is not None: - self._sdstatus_reporter.cancel() - self._sdstatus_reporter = None + if self._sdstatus_reporter is not None: + self._sdstatus_reporter.cancel() + self._sdstatus_reporter = None - if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]): - for item in settings().get(["devel", "virtualPrinter", "resetLines"]): - self._send(item + "\n") + self._clearQueue(self.incoming) + self._clearQueue(self.outgoing) + self._clearQueue(self.buffered) + + if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]): + for item in settings().get(["devel", "virtualPrinter", "resetLines"]): + self._send(item + "\n") @property def timeout(self): diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index 54074ac8f..e33367740 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -218,6 +218,9 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { }); }; + self._printerErrorCancelNotification = undefined; + self._printerErrorDisconnectNotification = undefined; + self._printerResetNotification = undefined; self._onEvent = function(event) { self._ifInitialized(function() { var type = event.data["type"]; @@ -226,7 +229,10 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { log.debug("Got event " + type + " with payload: " + JSON.stringify(payload)); if (type === "PrintCancelling" && payload.firmwareError) { - new PNotify({ + if (self._printerErrorCancelNotification !== undefined) { + self._printerErrorCancelNotification.remove(); + } + self._printerErrorCancelNotification = new PNotify({ title: gettext("Error reported by printer"), text: _.sprintf(gettext("Your printer's firmware reported an error. Due to that the ongoing print job will be cancelled. Reported error: %(firmwareError)s"), payload), type: "error", @@ -271,7 +277,10 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { } if (title && text) { - new PNotify({ + if (self._printerErrorDisconnectNotification !== undefined) { + self._printerErrorDisconnectNotification.remove(); + } + self._printerErrorDisconnectNotification = new PNotify({ title: title, text: text, type: "error", @@ -279,9 +288,23 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { }); } } else if (type === "PrinterReset") { - new PNotify({ + var severity = undefined, + text = undefined; + if (payload.idle) { + text = gettext("It looks like your printer reset while a connection was active. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD."); + severity = "alert"; + } else { + text = gettext("It looks like your printer reset while a connection was active. Due to this the ongoing job was aborted. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD."); + severity = "error"; + } + + if (self._printerResetNotification !== undefined) { + self._printerResetNotification.remove(); + } + self._printerResetNotification = new PNotify({ title: gettext("Printer reset detected"), - text: gettext("It looks like your printer reset while a connection was active. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD."), + text: text, + type: severity, hide: false }); } diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index ffc3efbda..7ca2027dd 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -382,7 +382,7 @@ class MachineCom(object): self._baudrateDetectRetry = 0 self._temperatureTargetSetThreshold = 25 self._tempOffsets = dict() - self._command_queue = TypedQueue() + self._command_queue = CommandQueue() self._currentZ = None self._currentF = None self._heatupWaitStartTime = None @@ -1622,7 +1622,7 @@ class MachineCom(object): # process resends elif lower_line.startswith("resend") or lower_line.startswith("rs"): - self._handleResendRequest(line) + self._handle_resend_request(line) handled = True # process timeouts @@ -2002,23 +2002,27 @@ class MachineCom(object): self.STATE_PAUSED, self.STATE_TRANSFERING_FILE): if line == "start": # exact match, to be on the safe side - if self._state in (self.STATE_OPERATIONAL,): - message = "Printer sent 'start' while already operational. External reset? " \ - "Resetting line numbers to be on the safe side" - self._log(message) - self._logger.warn(message) - self._onExternalReset() + with self.job_put_on_hold(): + idle = self._state in (self.STATE_OPERATIONAL,) + if idle: + message = "Printer sent 'start' while already operational. External reset? " \ + "Resetting line numbers to be on the safe side" + self._log(message) + self._logger.warn(message) - else: - verb = "streaming to SD" if self.isStreaming() else "printing" - message = "Printer sent 'start' while {}. External reset? " \ - "Aborting job since printer lost state.".format(verb) - self._log(message) - self._logger.warn(message) - self.cancelPrint(disable_log_position=True) - self._onExternalReset() + self._on_external_reset() - eventManager().fire(Events.PRINTER_RESET) + else: + verb = "streaming to SD" if self.isStreaming() else "printing" + message = "Printer sent 'start' while {}. External reset? " \ + "Aborting job since printer lost state.".format(verb) + self._log(message) + self._logger.warn(message) + + self._on_external_reset() + self.cancelPrint(disable_log_position=True) + + eventManager().fire(Events.PRINTER_RESET, payload=dict(idle=idle)) except: self._logger.exception("Something crashed inside the serial connection loop, please report this in OctoPrint's bug tracker:") @@ -2291,7 +2295,19 @@ class MachineCom(object): eventManager().fire(Events.CONNECTED, payload) self.sendGcodeScript("afterPrinterConnected", replacements=dict(event=payload)) - def _onExternalReset(self): + def _on_external_reset(self): + # hold queue processing, clear queues and acknowledgements, reset line number and last lines + with self._send_queue.blocked(): + self._clear_to_send.clear(completely=True) + with self._command_queue.blocked(): + self._command_queue.clear() + self._send_queue.clear() + + with self._line_mutex: + self._currentLine = 0 + self._lastLines.clear() + + self.sayHello(tags={"trigger:comm.on_external_reset"}) self.resetLineNumbers(tags={"trigger:comm.on_external_reset"}) if self._temperature_autoreporting: @@ -2620,13 +2636,19 @@ class MachineCom(object): self._logger.debug("Command \"{}\" from file not enqueued, doing another iteration".format(line)) - def _handleResendRequest(self, line): + def _handle_resend_request(self, line): try: lineToResend = parse_resend_line(line) if lineToResend is None: return False - if self._resendDelta is None and lineToResend == self._currentLine: + if self._resendDelta is None and lineToResend == self._currentLine == 1: + # We probably just handled a resend and this request originates from lines sent before that + self._logger.info("Got a resend request for line 1 which is also our current line. It looks " + "like we just handled a reset and this is a left over of this") + return False + + elif self._resendDelta is None and lineToResend == self._currentLine: # We don't expect to have an active resend request and the printer is requesting a resend of # a line we haven't yet sent. # @@ -2647,7 +2669,7 @@ class MachineCom(object): if lastCommError is not None \ and ("line number" in lastCommError.lower() or "expected line" in lastCommError.lower()) \ and lineToResend == self._lastResendNumber \ - and self._resendDelta is not None and self._currentResendCount < self._resendDelta: + and self._resendDelta is not None and self._currentResendCount < resendDelta: self._logger.info("Ignoring resend request for line %d, that still originates from lines we sent " "before we got the first resend request" % lineToResend) self._currentResendCount += 1 @@ -3782,12 +3804,52 @@ class SpecialStreamingGcodeFileInformation(StreamingGcodeFileInformation): return None return line +class CommandQueue(TypedQueue): + def __init__(self, *args, **kwargs): + TypedQueue.__init__(self, *args, **kwargs) + self._unblocked = threading.Event() + self._unblocked.set() + + def block(self): + self._unblocked.clear() + + def unblock(self): + self._unblocked.set() + + @contextlib.contextmanager + def blocked(self): + self.block() + try: + yield + finally: + self.unblock() + + def get(self, *args, **kwargs): + self._unblocked.wait() + return TypedQueue.get(self, *args, **kwargs) + + def put(self, *args, **kwargs): + self._unblocked.wait() + return TypedQueue.put(self, *args, **kwargs) + + def clear(self): + cleared = [] + while True: + try: + cleared.append(TypedQueue.get(self, False)) + TypedQueue.task_done(self) + except queue.Empty: + break + return cleared class SendQueue(PrependableQueue): def __init__(self, maxsize=0): PrependableQueue.__init__(self, maxsize=maxsize) + self._unblocked = threading.Event() + self._unblocked.set() + self._resend_queue = PrependableQueue() self._send_queue = PrependableQueue() self._lookup = set() @@ -3803,16 +3865,43 @@ class SendQueue(PrependableQueue): with self.mutex: self._resend_active = resend_active + def block(self): + self._unblocked.clear() + + def unblock(self): + self._unblocked.set() + + @contextlib.contextmanager + def blocked(self): + self.block() + try: + yield + finally: + self.unblock() + def prepend(self, item, item_type=None, target=None, block=True, timeout=None): + self._unblocked.wait() PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout) def put(self, item, item_type=None, target=None, block=True, timeout=None): + self._unblocked.wait() PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout) def get(self, block=True, timeout=None): + self._unblocked.wait() item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout) return item + def clear(self): + cleared = [] + while True: + try: + cleared.append(PrependableQueue.get(self, False)) + PrependableQueue.task_done(self) + except queue.Empty: + break + return cleared + def _put(self, item): _, item_type, target = item if item_type is not None: