From 3bb06a1a33f43f16fc2d0cbe2f6c1451acc45c6a Mon Sep 17 00:00:00 2001 From: Andy Werner Date: Mon, 3 Jul 2017 16:26:58 +0200 Subject: [PATCH 01/15] SW Update check type 'bitbucket_commit' now supports API credentials for private repos --- .../version_checks/bitbucket_commit.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py index 969473d05..81d5277aa 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py @@ -6,6 +6,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms import requests import logging +import base64 from ..exceptions import ConfigurationInvalid @@ -13,8 +14,14 @@ BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/comm logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit") -def _get_latest_commit(user, repo, branch): - r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)) + +def _get_latest_commit(user, repo, branch, api_user=None, api_password=None): + url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch) + headers = {} + if api_user is not None and api_password is not None: + headers['authorization'] = 'Basic {}'.format( + base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password))) + r = requests.get(url, headers=headers) if not r.status_code == requests.codes.ok: return None @@ -34,11 +41,14 @@ def get_latest(target, check): if "branch" in check: branch = check["branch"] + api_user = check["api_user"] if 'api_user' in check else None + api_password = check["api_password"] if 'api_password' in check else None + current = None if "current" in check: current = check["current"] - remote_commit = _get_latest_commit(check["user"], check["repo"], branch) + remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password) information = dict( local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current), From c81c93896b1afe12fbb5e2ddb8751ec4e52d5e09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 5 Jul 2017 09:28:22 +0200 Subject: [PATCH 02/15] Apply tool offsets immediately and only once Less tracking of offsets and also more similar to how firmware does this. We rewrite our current position on tool change to current position plus tool offset instead of applying it for every single position change. --- src/octoprint/util/gcodeInterpreter.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index ea6d291a6..2e8f62dff 100644 --- a/src/octoprint/util/gcodeInterpreter.py +++ b/src/octoprint/util/gcodeInterpreter.py @@ -222,7 +222,6 @@ class gcode(object): lineNo = 0 readBytes = 0 pos = Vector3D(0.0, 0.0, 0.0) - toolOffset = Vector3D(0.0, 0.0, 0.0) currentE = [0.0] totalExtrusion = [0.0] maxExtrusion = [0.0] @@ -320,16 +319,16 @@ class gcode(object): # Use new coordinates if provided. If not provided, use prior coordinates (minus tool offset) # in absolute and 0.0 in relative mode. - newPos = Vector3D(x if x is not None else (0.0 if relativeMode else pos.x - toolOffset.x), - y if y is not None else (0.0 if relativeMode else pos.y - toolOffset.y), - z if z is not None else (0.0 if relativeMode else pos.z - toolOffset.z)) + newPos = Vector3D(x if x is not None else (0.0 if relativeMode else pos.x), + y if y is not None else (0.0 if relativeMode else pos.y), + z if z is not None else (0.0 if relativeMode else pos.z)) if relativeMode: # Relative mode: scale and add to current position pos += newPos * scale else: # Absolute mode: scale coordinates and apply tool offsets - pos = newPos * scale + toolOffset + pos = newPos * scale if f is not None and f != 0: feedrate = f @@ -442,14 +441,16 @@ class gcode(object): elif T is not None: if T > max_extruders: self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T) + elif T == currentExtruder: + pass else: - toolOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0 - toolOffset.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0 + pos.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0 + pos.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0 currentExtruder = T - toolOffset.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0 - toolOffset.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0 + pos.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0 + pos.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0 if len(currentE) <= currentExtruder: for i in range(len(currentE), currentExtruder + 1): From cc3d34635ef56a88653e940c97832a48766bf45f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 5 Jul 2017 16:37:03 +0200 Subject: [PATCH 03/15] Add API function to (re)analyse files --- src/octoprint/filemanager/__init__.py | 20 ++++++++++++++++++++ src/octoprint/server/api/files.py | 12 ++++++++++++ src/octoprint/static/js/app/client/files.js | 4 ++++ src/octoprint/templates/sidebar/files.jinja2 | 1 + 4 files changed, 37 insertions(+) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index de78ecad9..a5b1bf6af 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -253,6 +253,26 @@ class FileManager(object): def default_slicer(self): return self._slicing_manager.default_slicer + def analyse(self, destination, path, printer_profile_id=None): + if not self.file_exists(destination, path): + return + + if printer_profile_id is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + else: + printer_profile = self._printer_profile_manager.get(printer_profile_id) + if printer_profile is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + + queue_entry = self._analysis_queue_entry(destination, path) + self._analysis_queue.dequeue(queue_entry) + + queue_entry = self._analysis_queue_entry(destination, path, printer_profile=printer_profile) + if queue_entry: + return self._analysis_queue.enqueue(queue_entry, high_priority=True) + + return False + def slice(self, slicer_name, source_location, source_path, dest_location, dest_path, position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None): absolute_source_path = self.path_on_disk(source_location, source_path) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 4895760eb..91fcaaa53 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -464,6 +464,7 @@ def gcodeFileCommand(filename, target): valid_commands = { "select": [], "slice": [], + "analyse": [], "copy": ["destination"], "move": ["destination"] } @@ -616,6 +617,17 @@ def gcodeFileCommand(filename, target): r.headers["Location"] = location return r + elif command == "analyse": + if not _verifyFileExists(target, filename): + return make_response("File not found on '%s': %s" % (target, filename), 404) + + printer_profile = None + if "printerProfile" in data and data["printerProfile"]: + printer_profile = data["printerProfile"] + + if not fileManager.analyse(target, filename, printer_profile_id=printer_profile): + return make_response("No analysis possible for {} on {}".format(filename, target), 400) + elif command == "copy" or command == "move": # Copy and move are only possible on local storage if not target in [FileDestinations.LOCAL]: diff --git a/src/octoprint/static/js/app/client/files.js b/src/octoprint/static/js/app/client/files.js index 726949c84..dc5d6c7e7 100644 --- a/src/octoprint/static/js/app/client/files.js +++ b/src/octoprint/static/js/app/client/files.js @@ -89,6 +89,10 @@ return this.issueEntryCommand(location, path, "select", data, opts); }; + OctoPrintFilesClient.prototype.analyse = function (location, path, parameters, opts) { + return this.issueEntryCommand(location, path, "analyse", parameters || {}, opts); + }; + OctoPrintFilesClient.prototype.slice = function (location, path, parameters, opts) { return this.issueEntryCommand(location, path, "slice", parameters || {}, opts); diff --git a/src/octoprint/templates/sidebar/files.jinja2 b/src/octoprint/templates/sidebar/files.jinja2 index 80a8e46b6..14281950d 100644 --- a/src/octoprint/templates/sidebar/files.jinja2 +++ b/src/octoprint/templates/sidebar/files.jinja2 @@ -18,6 +18,7 @@
+
From 4c3f4c2a8bbc072ea506084deb6becf37a0e261b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 5 Jul 2017 16:37:39 +0200 Subject: [PATCH 04/15] Fix "additional data" toggle in file list --- src/octoprint/static/js/app/viewmodels/files.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 8f3634976..f74b93f47 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -581,7 +581,7 @@ $(function() { var additionalInfo = $(".additionalInfo", entryElement); additionalInfo.slideToggle("fast", function() { - $(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up"); + $(".toggleAdditionalData i", entryElement).toggleClass("fa-chevron-down fa-chevron-up"); }); }; From f8d225a768954eb4d10f87473581eb71c887addc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 5 Jul 2017 17:56:46 +0200 Subject: [PATCH 05/15] Support for parsing GCODE subcodes Hook handlers will get any parsed subcode as optional keyword argument "subcode". --- docs/plugins/hooks.rst | 4 +- src/octoprint/util/comm.py | 192 +++++++++++++++++--------------- tests/util/test_comm_helpers.py | 18 +++ 3 files changed, 122 insertions(+), 92 deletions(-) diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 8811bbf8b..bc444a05b 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -389,7 +389,7 @@ This describes actually four hooks: * ``octoprint.comm.protocol.gcode.sending`` * ``octoprint.comm.protocol.gcode.sent`` -.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs) +.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs) Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases are the following: @@ -488,6 +488,8 @@ This describes actually four hooks: :param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD printing status polling. :param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed + :param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided + or no command could be parsed. :return: None, 1-tuple, 2-tuple or string, see the description above for details. .. _sec-plugins-hook-comm-protocol-gcode-received: diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 088c58692..1ed32665f 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -47,7 +47,7 @@ regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+" regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+" regex_int_pattern = "\d+" -regex_command = re.compile("^\s*((?P[GM]\d+)|(?PT)\d+|(?PF)\d+)") +regex_command = re.compile("^\s*((?P[GM]\d+)(\\.(?P\d+))?|(?PT)\d+|(?PF)\d+)") """Regex for a GCODE command.""" regex_float = re.compile(regex_float_pattern) @@ -2112,20 +2112,20 @@ class MachineCom(object): if self._serial is None: return False - gcode = None + gcode, subcode = gcode_and_subcode_for_cmd(cmd) if not self.isStreaming(): # trigger the "queuing" phase only if we are not streaming to sd right now - results = self._process_command_phase("queuing", cmd, cmd_type, gcode=gcode) + results = self._process_command_phase("queuing", cmd, command_type=cmd_type, gcode=gcode, subcode=subcode) if not results: # command is no more, return return False else: - results = [(cmd, cmd_type, gcode)] + results = [(cmd, cmd_type, gcode, subcode)] # process helper - def process(cmd, cmd_type, gcode, on_sent=None): + def process(cmd, cmd_type, gcode, subcode, on_sent=None): if cmd is None: # no command, next entry return False @@ -2138,7 +2138,7 @@ class MachineCom(object): if self._enqueue_for_sending(cmd, command_type=cmd_type, on_sent=on_sent): if not self.isStreaming(): # trigger the "queued" phase only if we are not streaming to sd right now - self._process_command_phase("queued", cmd, cmd_type, gcode=gcode) + self._process_command_phase("queued", cmd, cmd_type, gcode=gcode, subcode=subcode) return True else: return False @@ -2155,12 +2155,12 @@ class MachineCom(object): enqueued_something = False # process all but the last ... - for (cmd, cmd_type, gcode) in results: - enqueued_something = process(cmd, cmd_type, gcode) or enqueued_something + for (cmd, cmd_type, gcode, subcode) in results: + enqueued_something = process(cmd, cmd_type, gcode, subcode) or enqueued_something # ... and then process the last one with the on_sent callback attached - cmd, cmd_type, gcode = last_command - enqueued_something = process(cmd, cmd_type, gcode, on_sent=on_sent) or enqueued_something + cmd, cmd_type, gcode, subcode = last_command + enqueued_something = process(cmd, cmd_type, gcode, subcode, on_sent=on_sent) or enqueued_something return enqueued_something @@ -2216,7 +2216,7 @@ class MachineCom(object): # some firmwares (e.g. Smoothie) might support additional in-band communication that will not # stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command # at hand here and only clear our clear_to_send flag later if that's the case - gcode = gcode_command_for_cmd(command) + gcode, subcode = gcode_and_subcode_for_cmd(command) if linenumber is not None: # line number predetermined - this only happens for resends, so we'll use the number and @@ -2226,7 +2226,7 @@ class MachineCom(object): else: if not processed: # trigger "sending" phase if we didn't so far - results = self._process_command_phase("sending", command, command_type, gcode=gcode) + results = self._process_command_phase("sending", command, command_type, gcode=gcode, subcode=subcode) if not results: # No, we are not going to send this, that was a last-minute bail. @@ -2252,7 +2252,7 @@ class MachineCom(object): self._send_queue.prepend((m[0], None, None, None, True)) # we only actually send the first entry here - command, _, gcode = results[0] + command, _, gcode, subcode = results[0] if command.strip() == "": self._logger.info("Refusing to send an empty line to the printer") @@ -2280,7 +2280,7 @@ class MachineCom(object): if on_sent is not None and callable(on_sent): # we have a sent callback for this specific command, let's execute it now on_sent() - self._process_command_phase("sent", command, command_type, gcode=gcode) + self._process_command_phase("sent", command, command_type, gcode=gcode, subcode=subcode) # we only need to use up a clear if the command we just sent was either a gcode command or if we also # require ack's for unknown commands @@ -2308,10 +2308,10 @@ class MachineCom(object): self._logger.exception("Caught an exception in the send loop") self._log("Closing down send loop") - def _process_command_phase(self, phase, command, command_type=None, gcode=None): + def _process_command_phase(self, phase, command, command_type=None, gcode=None, subcode=None): if gcode is None: - gcode = gcode_command_for_cmd(command) - results = [(command, command_type, gcode)] + gcode, subcode = gcode_and_subcode_for_cmd(command) + results = [(command, command_type, gcode, subcode)] if (self.isStreaming() and self.isPrinting()) or phase not in ("queuing", "queued", "sending", "sent"): return results @@ -2319,13 +2319,13 @@ class MachineCom(object): # send it through the phase specific handlers provided by plugins for name, hook in self._gcode_hooks[phase].items(): new_results = [] - for command, command_type, gcode in results: + for command, command_type, gcode, subcode in results: try: - hook_results = hook(self, phase, command, command_type, gcode) + hook_results = hook(self, phase, command, command_type, gcode, subcode=subcode) except: self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals())) else: - normalized = _normalize_command_handler_result(command, command_type, gcode, hook_results) + normalized = _normalize_command_handler_result(command, command_type, gcode, subcode, hook_results) new_results += normalized if not new_results: # hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result @@ -2335,15 +2335,15 @@ class MachineCom(object): # if it's a gcode command send it through the specific handler if it exists new_results = [] modified = False - for command, command_type, gcode in results: + for command, command_type, gcode, subcode in results: if gcode is not None: gcode_handler = "_gcode_" + gcode + "_" + phase if hasattr(self, gcode_handler): - handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type) - new_results += _normalize_command_handler_result(command, command_type, gcode, handler_results) + handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type, subcode=subcode) + new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results) modified = True else: - new_results.append((command, command_type, gcode)) + new_results.append((command, command_type, gcode, subcode)) modified = True if modified: if not new_results: @@ -2356,9 +2356,9 @@ class MachineCom(object): command_phase_handler = "_command_phase_" + phase if hasattr(self, command_phase_handler): new_results = [] - for command, command_type, gcode in results: - handler_results = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode) - new_results += _normalize_command_handler_result(command, command_type, gcode, handler_results) + for command, command_type, gcode, subcode in results: + handler_results = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode, subcode=subcode) + new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results) results = new_results # finally return whatever we resulted on @@ -2444,7 +2444,7 @@ class MachineCom(object): ##~~ command handlers - def _gcode_T_queuing(self, cmd, cmd_type=None): + def _gcode_T_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): toolMatch = regexes_parameters["intT"].search(cmd) if toolMatch: current_tool = self._currentTool @@ -2455,14 +2455,14 @@ class MachineCom(object): return before + [cmd] + after - def _gcode_T_sent(self, cmd, cmd_type=None): + def _gcode_T_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): toolMatch = regexes_parameters["intT"].search(cmd) if toolMatch: old = self._currentTool self._currentTool = int(toolMatch.group("value")) eventManager().fire(Events.TOOL_CHANGE, dict(old=old, new=self._currentTool)) - def _gcode_G0_sent(self, cmd, cmd_type=None): + def _gcode_G0_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): if "Z" in cmd or "F" in cmd: # track Z match = regexes_parameters["floatZ"].search(cmd) @@ -2485,7 +2485,7 @@ class MachineCom(object): pass _gcode_G1_sent = _gcode_G0_sent - def _gcode_G28_sent(self, cmd, cmd_type=None): + def _gcode_G28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): if "F" in cmd: match = regexes_parameters["floatF"].search(cmd) if match: @@ -2495,34 +2495,34 @@ class MachineCom(object): except ValueError: pass - def _gcode_M0_queuing(self, cmd, cmd_type=None): + def _gcode_M0_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): self.setPause(True) 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, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): # 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.isPrinting() and not self.isSdPrinting(): self.setPause(True) - def _gcode_M28_sent(self, cmd, cmd_type=None): + def _gcode_M28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): if not self.isStreaming(): self._log("Detected manual streaming. Disabling temperature polling. Finish writing with M29. Do NOT attempt to print while manually streaming!") self._manualStreaming = True - def _gcode_M29_sent(self, cmd, cmd_type=None): + def _gcode_M29_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): if self._manualStreaming: self._log("Manual streaming done. Re-enabling temperature polling. All is well.") self._manualStreaming = False - def _gcode_M140_queuing(self, cmd, cmd_type=None): + def _gcode_M140_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): if not self._printerProfileManager.get_current_or_default()["heatedBed"]: self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd)) return None, # Don't send bed commands if we don't have a heated bed _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, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs): toolNum = self._currentTool toolMatch = regexes_parameters["intT"].search(cmd) @@ -2545,7 +2545,7 @@ class MachineCom(object): except ValueError: pass - def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False, support_r=False): + def _gcode_M140_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs): match = regexes_parameters["floatS"].search(cmd) if not match and support_r: match = regexes_parameters["floatR"].search(cmd) @@ -2558,24 +2558,24 @@ class MachineCom(object): except ValueError: pass - def _gcode_M109_sent(self, cmd, cmd_type=None): + def _gcode_M109_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): self._heatupWaitStartTime = time.time() self._long_running_command = True self._heating = True self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True) - def _gcode_M190_sent(self, cmd, cmd_type=None): + def _gcode_M190_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): self._heatupWaitStartTime = time.time() self._long_running_command = True self._heating = True self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True) - def _gcode_M116_sent(self, cmd, cmd_type=None): + def _gcode_M116_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): self._heatupWaitStartTime = time.time() self._long_running_command = True self._heating = True - def _gcode_M155_sending(self, cmd, cmd_type=None): + def _gcode_M155_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): match = regexes_parameters["intS"].search(cmd) if match: try: @@ -2585,7 +2585,7 @@ class MachineCom(object): except: pass - def _gcode_M110_sending(self, cmd, cmd_type=None): + def _gcode_M110_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): newLineNumber = 0 match = regexes_parameters["intN"].search(cmd) if match: @@ -2604,7 +2604,7 @@ class MachineCom(object): self._lastLines.clear() self._resendDelta = None - def _gcode_M112_queuing(self, cmd, cmd_type=None): + def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): # emergency stop, jump the queue with the M112 self._do_send_without_checksum("M112") self._do_increment_and_send_with_checksum("M112") @@ -2633,7 +2633,7 @@ class MachineCom(object): # 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, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): # 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) @@ -2649,7 +2649,7 @@ class MachineCom(object): ##~~ command phase handlers - def _command_phase_sending(self, cmd, cmd_type=None, gcode=None): + def _command_phase_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs): if gcode is not None and gcode in self._long_running_commands: self._long_running_command = True @@ -3277,35 +3277,43 @@ def gcode_command_for_cmd(cmd): Returns: str or None: The GCODE command identifier if it could be parsed, or None if not. """ + + gcode, _ = gcode_and_subcode_for_cmd(cmd) + return gcode + + +def gcode_and_subcode_for_cmd(cmd): if not cmd: - return None + return None, None - gcode = regex_command.search(cmd) - if not gcode: - return None + match = regex_command.search(cmd) + if not match: + return None, None - values = gcode.groupdict() - if "commandGM" in values and values["commandGM"]: - return values["commandGM"] - elif "commandT" in values and values["commandT"]: - return values["commandT"] - elif settings().getBoolean(["feature", "supportFAsCommand"]) and "commandF" in values and values["commandF"]: - return values["commandF"] + values = match.groupdict() + if "codeGM" in values and values["codeGM"]: + gcode = values["codeGM"] + elif "codeT" in values and values["codeT"]: + gcode = values["codeT"] + elif settings().getBoolean(["feature", "supportFAsCommand"]) and "codeF" in values and values["codeF"]: + gcode = values["codeF"] else: # this should never happen - return None + return None, None + + return gcode, values.get("subcode", None) -def _normalize_command_handler_result(command, command_type, gcode, handler_results): +def _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results): """ Normalizes a command handler result. Handler results can be either ``None``, a single result entry or a list of result entries. - ``None`` results are ignored, the provided ``command``, ``command_type`` - and ``gcode`` are returned in that case (as single-entry list with one - 3-tuple as entry). + ``None`` results are ignored, the provided ``command``, ``command_type``, + ``gcode`` and ``subcode`` are returned in that case (as single-entry list with + one 4-tuple as entry). Single result entries are either: @@ -3317,31 +3325,31 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu the normalized result. The method returns a list of normalized result entries. Normalized result - entries always are a 3-tuple consisting of ``command``, ``command_type`` - and ``gcode``, the latter two being allowed to be ``None``. The list may + entries always are a 4-tuple consisting of ``command``, ``command_type``, + ``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may be empty in which case the command is to be suppressed. Examples: - >>> _normalize_command_handler_result("M105", None, "M105", None) - [('M105', None, 'M105')] - >>> _normalize_command_handler_result("M105", None, "M105", "M110") - [('M110', None, 'M110')] - >>> _normalize_command_handler_result("M105", None, "M105", ["M110"]) - [('M110', None, 'M110')] - >>> _normalize_command_handler_result("M105", None, "M105", ["M110", "M117 Foobar"]) - [('M110', None, 'M110'), ('M117 Foobar', None, 'M117')] - >>> _normalize_command_handler_result("M105", None, "M105", [("M110",), "M117 Foobar"]) - [('M110', None, 'M110'), ('M117 Foobar', None, 'M117')] - >>> _normalize_command_handler_result("M105", None, "M105", [("M110", "lineno_reset"), "M117 Foobar"]) - [('M110', 'lineno_reset', 'M110'), ('M117 Foobar', None, 'M117')] - >>> _normalize_command_handler_result("M105", None, "M105", []) + >>> _normalize_command_handler_result("M105", None, "M105", None, None) + [('M105', None, 'M105', None)] + >>> _normalize_command_handler_result("M105", None, "M105", None, "M110") + [('M110', None, 'M110', None)] + >>> _normalize_command_handler_result("M105", None, "M105", None, ["M110"]) + [('M110', None, 'M110', None)] + >>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", "M117 Foobar"]) + [('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)] + >>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), "M117 Foobar"]) + [('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)] + >>> _normalize_command_handler_result("M105", None, "M105", None, [("M110", "lineno_reset"), "M117 Foobar"]) + [('M110', 'lineno_reset', 'M110', None), ('M117 Foobar', None, 'M117', None)] + >>> _normalize_command_handler_result("M105", None, "M105", None, []) [] - >>> _normalize_command_handler_result("M105", None, "M105", ["M110", None]) - [('M110', None, 'M110')] - >>> _normalize_command_handler_result("M105", None, "M105", [("M110",), (None, "ignored")]) - [('M110', None, 'M110')] - >>> _normalize_command_handler_result("M105", None, "M105", [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")]) - [('M110', None, 'M110'), ('M117 Foobar', 'display_message', 'M117'), ('M110', 'lineno_reset', 'M110')] + >>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", None]) + [('M110', None, 'M110', None)] + >>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), (None, "ignored")]) + [('M110', None, 'M110', None)] + >>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")]) + [('M110', None, 'M110', None), ('M117 Foobar', 'display_message', 'M117', None), ('M110', 'lineno_reset', 'M110', None)] Arguments: command (str or None): The command for which the handler result was @@ -3350,16 +3358,18 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu result was generated gcode (str or None): The GCODE for which the handler result was generated + subcode (str or None): The GCODE subcode for which the handler result + was generated handler_results: The handler result(s) to normalized. Can be either a single result entry or a list of result entries. Returns: (list) - A list of normalized handler result entries, which are - 3-tuples consisting of ``command``, ``command_type`` and - ``gcode``, the latter two of which may be ``None``. + 4-tuples consisting of ``command``, ``command_type``, ``gcode`` + and ``subcode``, the latter three of which may be ``None``. """ - original = (command, command_type, gcode) + original = (command, command_type, gcode, subcode) if handler_results is None: # handler didn't return anything, we'll just continue @@ -3380,8 +3390,8 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu if isinstance(handler_result, basestring): # entry is just a string, replace command with it command = handler_result - gcode = gcode_command_for_cmd(command) - result.append((command, command_type, gcode)) + gcode, subcode = gcode_and_subcode_for_cmd(command) + result.append((command, command_type, gcode, subcode)) elif isinstance(handler_result, tuple): # entry is a tuple, extract command and command_type @@ -3401,11 +3411,11 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu # command is None, ignore it and continue continue - gcode = gcode_command_for_cmd(command) - result.append((command, command_type, gcode)) + gcode, subcode = gcode_and_subcode_for_cmd(command) + result.append((command, command_type, gcode, subcode)) # reset to original - command, command_type, gcode = original + command, command_type, gcode, subcode = original return result diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py index 3042bfe52..5ac6998e2 100644 --- a/tests/util/test_comm_helpers.py +++ b/tests/util/test_comm_helpers.py @@ -198,6 +198,24 @@ class TestCommHelpers(unittest.TestCase): result = gcode_command_for_cmd(cmd) self.assertEqual(expected, result) + @data( + ("G0 X0", "G0", None), + ("M105", "M105", None), + ("T2", "T", None), + ("M80.1", "M80", "1"), + ("G28.2", "G28", "2"), + ("T0.3", "T", None), + ("M80.nosubcode", "M80", None), + (None, None, None), + ("No match", None, None) + ) + @unpack + def test_gcode_and_subcode_for_cmd(self, cmd, expected_gcode, expected_subcode): + from octoprint.util.comm import gcode_and_subcode_for_cmd + actual_gcode, actual_subcode = gcode_and_subcode_for_cmd(cmd) + self.assertEqual(expected_gcode, actual_gcode) + self.assertEqual(expected_subcode, actual_subcode) + @data( ("T:23.0 B:60.0", 0, dict(T0=(23.0, None), B=(60.0, None)), 0), ("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1), From c1c09d417d9eaaccb5a62028e8f6265af41a7db7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 5 Jul 2017 17:58:33 +0200 Subject: [PATCH 06/15] Removed a line that was accidentally committed --- src/octoprint/templates/sidebar/files.jinja2 | 1 - 1 file changed, 1 deletion(-) diff --git a/src/octoprint/templates/sidebar/files.jinja2 b/src/octoprint/templates/sidebar/files.jinja2 index 14281950d..80a8e46b6 100644 --- a/src/octoprint/templates/sidebar/files.jinja2 +++ b/src/octoprint/templates/sidebar/files.jinja2 @@ -18,7 +18,6 @@
-
From 4c6c764c5c15bdfa2c0f7fc5ee3a33c7bd43a368 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 6 Jul 2017 16:18:55 +0200 Subject: [PATCH 07/15] Small simplifications and clarifications --- .../version_checks/bitbucket_commit.py | 18 ++++++++---------- .../version_checks/github_commit.py | 8 +++----- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py index 81d5277aa..ddce43c1c 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py @@ -8,8 +8,6 @@ import requests import logging import base64 -from ..exceptions import ConfigurationInvalid - BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}" logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit") @@ -19,8 +17,8 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None): url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch) headers = {} if api_user is not None and api_password is not None: - headers['authorization'] = 'Basic {}'.format( - base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password))) + auth_value = base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password)) + headers["authorization"] = "Basic {}".format(auth_value) r = requests.get(url, headers=headers) if not r.status_code == requests.codes.ok: @@ -34,19 +32,19 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None): def get_latest(target, check): + from ..exceptions import ConfigurationInvalid + if "user" not in check or "repo" not in check: raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target) branch = "master" - if "branch" in check: + if "branch" in check and check["branch"] is not None: branch = check["branch"] - api_user = check["api_user"] if 'api_user' in check else None - api_password = check["api_password"] if 'api_password' in check else None + api_user = check.get("api_user") + api_password = check.get("api_password") - current = None - if "current" in check: - current = check["current"] + current = check.get("current") remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py index cc1529438..9df59833c 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py @@ -8,8 +8,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import requests import logging -from ..exceptions import ConfigurationInvalid - BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}" logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit") @@ -31,6 +29,8 @@ def _get_latest_commit(user, repo, branch): def get_latest(target, check): + from ..exceptions import ConfigurationInvalid + user = check.get("user") repo = check.get("repo") @@ -41,9 +41,7 @@ def get_latest(target, check): if "branch" in check and check["branch"] is not None: branch = check["branch"] - current = None - if "current" in check: - current = check["current"] + current = check.get("current") remote_commit = _get_latest_commit(check["user"], check["repo"], branch) From 16e96743c5663b811a7e9453818dcf268e874895 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 6 Jul 2017 16:30:44 +0200 Subject: [PATCH 08/15] Docs for api_user/api_password on bitbucket_commit --- docs/bundledplugins/softwareupdate.rst | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index 17efc535c..763a0de5e 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -198,6 +198,13 @@ Version checks * ``branch``: Branch of the Bitbucket repository to check, defaults to ``master`` if not set. * ``current``: Current commit hash. Will be updated automatically. + * ``api_user``: (mandatory only for private repositories) Bitbucket user name (not email address). + Requires ``api_password`` to be set. Hint: This is used for the check only. For the actual + download you might register your public SSH key as access key for the according repo and + configure this as pip URL in ``config.yaml``: ``git+ssh://git@bitbucket.org/my_user/my_repo.git@{target_version}`` + * ``api_password``: (mandatory only for private repositories) App password. Requires + ``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate + a new app password. App passwords are user specific on Bitbucket. * ``git_commit``: Checks a local git repository for new commits on its configured remote. Additional config parameters: From 2e897f19accef98deaefdf0d09bf93005576d7e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 7 Jul 2017 15:56:22 +0200 Subject: [PATCH 09/15] Synchronize all writing access to the send queue --- src/octoprint/util/comm.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 1ed32665f..3517b9709 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -2240,16 +2240,17 @@ class MachineCom(object): continue if len(results) > 1: - # last command gets on_sent attached - last = results[-1] - self._send_queue.prepend((last[0], None, None, on_sent, True)) - on_sent = None + with self._sendingLock: + # last command gets on_sent attached + last = results[-1] + self._send_queue.prepend((last[0], None, None, on_sent, True)) + on_sent = None - # middle gets prepended reversed (so order gets restored) - if len(results) > 2: - to_prepend = reversed(results[1:-1]) - for m in to_prepend: - self._send_queue.prepend((m[0], None, None, None, True)) + # middle gets prepended reversed (so order gets restored) + if len(results) > 2: + to_prepend = reversed(results[1:-1]) + for m in to_prepend: + self._send_queue.prepend((m[0], None, None, None, True)) # we only actually send the first entry here command, _, gcode, subcode = results[0] From 23e58d2fc18c77c4e34a54debac51b41a60ae4b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 11 Jul 2017 14:04:38 +0200 Subject: [PATCH 10/15] Make sure resent lines always win before regular ones Introduced a custom send queue type that actually contains two queues, one for resends, one for regular lines. A flag indicates whether lines should be returned from both or only resends. That way we ensure that as soon as we have an active resend request we ignore what was already in the queue and only send the lines we need to resend. Also: PrependQueue => PrependableQueue --- src/octoprint/util/__init__.py | 18 ++--- src/octoprint/util/comm.py | 119 ++++++++++++++++++++++++++++----- 2 files changed, 112 insertions(+), 25 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index d43733ce2..c62fe8ed0 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1046,7 +1046,7 @@ class InvariantContainer(object): return self._data.__iter__() -class PrependQueue(queue.Queue): +class PrependableQueue(queue.Queue): def __init__(self, maxsize=0): queue.Queue.__init__(self, maxsize=maxsize) @@ -1082,21 +1082,21 @@ class PrependQueue(queue.Queue): self.queue.appendleft(item) -class TypedQueue(PrependQueue): +class TypedQueue(PrependableQueue): def __init__(self, maxsize=0): - PrependQueue.__init__(self, maxsize=maxsize) + PrependableQueue.__init__(self, maxsize=maxsize) self._lookup = set() def put(self, item, item_type=None, *args, **kwargs): - PrependQueue.put(self, (item, item_type), *args, **kwargs) + PrependableQueue.put(self, (item, item_type), *args, **kwargs) def get(self, *args, **kwargs): - item, _ = PrependQueue.get(self, *args, **kwargs) + item, _ = PrependableQueue.get(self, *args, **kwargs) return item def prepend(self, item, item_type=None, *args, **kwargs): - PrependQueue.prepend(self, (item, item_type), *args, **kwargs) + PrependableQueue.prepend(self, (item, item_type), *args, **kwargs) def _put(self, item): _, item_type = item @@ -1106,10 +1106,10 @@ class TypedQueue(PrependQueue): else: self._lookup.add(item_type) - queue.Queue._put(self, item) + PrependableQueue._put(self, item) def _get(self): - item = PrependQueue._get(self) + item = PrependableQueue._get(self) _, item_type = item if item_type is not None: @@ -1125,7 +1125,7 @@ class TypedQueue(PrependQueue): else: self._lookup.add(item_type) - PrependQueue._prepend(self, item) + PrependableQueue._prepend(self, item) class TypeAlreadyInQueue(Exception): def __init__(self, t, *args, **kwargs): diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 3517b9709..aa71a9ac6 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -32,7 +32,7 @@ from octoprint.events import eventManager, Events from octoprint.filemanager import valid_file_type from octoprint.filemanager.destinations import FileDestinations from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \ - to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue, chunks + to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks try: import _winreg @@ -422,7 +422,7 @@ class MachineCom(object): self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"]) self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send") - self._send_queue = TypedQueue() + self._send_queue = SendQueue() self._temperature_timer = None self._sd_status_timer = None @@ -2068,6 +2068,7 @@ class MachineCom(object): self._to_logfile_with_terminal("Got a resend request from the printer: requested line = {}, current line = {}".format(lineToResend, self._currentLine)) self._log_resends_rate_count += 1 + self._send_queue.resend_active = True return True finally: if self._supportResendsWithoutOk: @@ -2096,7 +2097,7 @@ class MachineCom(object): cmd = self._lastLines[-self._resendDelta] lineNumber = self._currentLine - self._resendDelta - result = self._enqueue_for_sending(cmd, linenumber=lineNumber) + result = self._enqueue_for_sending(cmd, linenumber=lineNumber, resend=True) self._resendDelta -= 1 if self._resendDelta <= 0: @@ -2104,6 +2105,8 @@ class MachineCom(object): self._lastResendNumber = None self._currentResendCount = 0 + self._send_queue.resend_active = False + return result def _sendCommand(self, cmd, cmd_type=None, on_sent=None): @@ -2166,7 +2169,7 @@ class MachineCom(object): ##~~ send loop handling - def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None): + def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None, resend=False): """ Enqueues a command and optional linenumber to use for it in the send queue. @@ -2180,7 +2183,11 @@ class MachineCom(object): """ try: - self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type) + target = "send" + if resend: + target = "resend" + + self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type, target=target) return True except TypeAlreadyInQueue as e: self._logger.debug("Type already in send queue: " + e.type) @@ -2188,7 +2195,7 @@ class MachineCom(object): def _send_loop(self): """ - The send loop is reponsible of sending commands in ``self._send_queue`` over the line, if it is cleared for + The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for sending (through received ``ok`` responses from the printer's firmware. """ @@ -2241,16 +2248,14 @@ class MachineCom(object): if len(results) > 1: with self._sendingLock: - # last command gets on_sent attached - last = results[-1] - self._send_queue.prepend((last[0], None, None, on_sent, True)) - on_sent = None - - # middle gets prepended reversed (so order gets restored) - if len(results) > 2: - to_prepend = reversed(results[1:-1]) - for m in to_prepend: - self._send_queue.prepend((m[0], None, None, None, True)) + # prepend reversed (so order gets restored) + to_prepend = reversed(results[1:-1]) + for m in to_prepend: + try: + self._send_queue.prepend((m[0], None, m[1], on_sent, True), item_type=m[1]) + on_sent = None + except TypeAlreadyInQueue: + pass # we only actually send the first entry here command, _, gcode, subcode = results[0] @@ -2926,6 +2931,88 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation): duration=duration) self._logger.info("Finished in {duration:.3f} s. Approx. transfer rate of {rate:.3f} lines/s or {time_per_line:.3f} ms per line".format(**stats)) + +class SendQueue(PrependableQueue): + + def __init__(self, maxsize=0): + PrependableQueue.__init__(self, maxsize=maxsize) + + self._resend_queue = PrependableQueue() + self._send_queue = PrependableQueue() + self._lookup = set() + + self._resend_active = False + + @property + def resend_active(self): + return self._resend_active + + @resend_active.setter + def resend_active(self, resend_active): + with self.mutex: + self._resend_active = resend_active + + def prepend(self, item, item_type=None, target=None, block=True, timeout=None): + PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout) + + def put(self, item, item_type=None, target=None, block=True, timeout=None): + PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout) + + def get(self, block=True, timeout=None): + item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout) + return item + + def _put(self, item): + _, item_type, target = 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) + + if target == "resend": + self._resend_queue.put(item) + else: + self._send_queue.put(item) + + pass + + def _prepend(self, item): + _, item_type, target = 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) + + if target == "resend": + self._resend_queue.prepend(item) + else: + self._send_queue.prepend(item) + + def _get(self): + if self.resend_active: + item = self._resend_queue.get(block=False) + else: + try: + item = self._resend_queue.get(block=False) + except queue.Empty: + item = self._send_queue.get(block=False) + + _, item_type, _ = item + if item_type is not None: + if item_type in self._lookup: + self._lookup.remove(item_type) + + return item + + def _qsize(self): + if self.resend_active: + return self._resend_queue.qsize() + else: + return self._resend_queue.qsize() + self._send_queue.qsize() + + def get_new_timeout(type, intervals): now = time.time() return now + intervals.get(type, 0.0) From a33f44ea2508aaa5591eb86ff24ffe57d3aa2e7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 12 Jul 2017 16:13:51 +0200 Subject: [PATCH 11/15] Fix File(Added|Removed) and Folder(Added|Removed) events Were defined as 1-tuple instead of a string thanks to a syntax error. --- src/octoprint/events.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 78d5f0ab0..3c39c71b3 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -53,10 +53,10 @@ class Events(object): METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished" METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated" - FILE_ADDED = "FileAdded", - FILE_REMOVED = "FileRemoved", - FOLDER_ADDED = "FolderAdded", - FOLDER_REMOVED = "FolderRemoved", + FILE_ADDED = "FileAdded" + FILE_REMOVED = "FileRemoved" + FOLDER_ADDED = "FolderAdded" + FOLDER_REMOVED = "FolderRemoved" # SD Upload TRANSFER_STARTED = "TransferStarted" From 142a1b0dcbab544e6aafb9e10e0cd1d9c64c6ef9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 13 Jul 2017 15:48:22 +0200 Subject: [PATCH 12/15] Progress might be 0, don't divide by it then --- src/octoprint/printer/standard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 527f502a1..d36e55538 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -763,7 +763,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): (2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation """ - if progress is None or printTime is None or cleanedPrintTime is None: + if progress is None or progress == 0 or printTime is None or cleanedPrintTime is None: return None, None dumbTotalPrintTime = printTime / progress From 3a9d5814238757379d3e017763b58d00ac4420c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 13 Jul 2017 20:00:45 +0200 Subject: [PATCH 13/15] Decouple writing of print log from everything else Fixes delay in cancel processing as observed by @capnbry with regards to #1946. More tests necessary to ensure this was the only cause. --- src/octoprint/printer/standard.py | 49 ++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index d36e55538..6f2cddab0 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -1000,7 +1000,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): with self._selectedFileMutex: if self._selectedFile is not None: if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR: - self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"]) + def log_print(): + self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, + self._selectedFile["filename"], + time.time(), + self._comm.getPrintTime(), + False, + self._printerProfileManager.get_current_or_default()["id"]) + + thread = threading.Thread(target=log_print) + thread.daemon = True + thread.start() self._analysisQueue.resume() # printing done, put those cpu cycles to good use elif state == comm.MachineCom.STATE_PRINTING: self._analysisQueue.pause() # do not analyse files while printing @@ -1091,12 +1101,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): context=dict(event=payload), must_be_set=False) - self._fileManager.log_print(payload["origin"], - payload["path"], - time.time(), - payload["time"], - True, - self._printerProfileManager.get_current_or_default()["id"]) + def log_print(): + self._fileManager.log_print(payload["origin"], + payload["path"], + time.time(), + payload["time"], + True, + self._printerProfileManager.get_current_or_default()["id"]) + + thread = threading.Thread(target=log_print) + thread.daemon = True + thread.start() + else: self._updateProgressData() self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()}) @@ -1119,13 +1135,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): context=dict(event=payload), must_be_set=False) - self._fileManager.log_print(payload["origin"], - payload["path"], - time.time(), - payload["time"], - False, - self._printerProfileManager.get_current_or_default()["id"]) - eventManager().fire(Events.PRINT_FAILED, payload) + def finalize(): + self._fileManager.log_print(payload["origin"], + payload["path"], + time.time(), + payload["time"], + False, + self._printerProfileManager.get_current_or_default()["id"]) + eventManager().fire(Events.PRINT_FAILED, payload) + + thread = threading.Thread(target=finalize) + thread.daemon = True + thread.start() def on_comm_print_job_paused(self): payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None) From b1101f5150bf3b075ab7cd93df51828d3c34de7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 14 Jul 2017 11:07:25 +0200 Subject: [PATCH 14/15] Virtual printer: support pinning of temperatures Helpful for simulating disconnected thermistors, preparation for debugging #2007 --- src/octoprint/plugins/virtual_printer/virtual.py | 7 +++++++ src/octoprint/settings.py | 1 + 2 files changed, 8 insertions(+) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 632cddf4d..a87e16a07 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -65,6 +65,9 @@ class VirtualPrinter(object): self.currentExtruder = 0 self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"]) + self.pinnedExtruders = settings().get(["devel", "virtualPrinter", "pinnedExtruders"]) + if self.pinnedExtruders is None: + self.pinnedExtruders = dict() self.sharedNozzle = settings().getBoolean(["devel", "virtualPrinter", "sharedNozzle"]) self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount) @@ -1001,6 +1004,10 @@ class VirtualPrinter(object): timeDiff = self.lastTempAt - time.time() self.lastTempAt = time.time() for i in range(len(self.temp)): + if i in self.pinnedExtruders: + self.temp[i] = self.pinnedExtruders[i] + continue + if abs(self.temp[i] - self.targetTemp[i]) > delta: oldVal = self.temp[i] self.temp[i] += math.copysign(timeDiff * 10, self.targetTemp[i] - self.temp[i]) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 221d35e72..269fa3de0 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -342,6 +342,7 @@ default_settings = { "okAfterResend": False, "forceChecksum": False, "numExtruders": 1, + "pinnedExtruders": None, "includeCurrentToolInTemps": True, "includeFilenameInOpened": True, "hasBed": True, From cf053ddbed07fe20905f6e5f040432fa77112c79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 14 Jul 2017 11:18:04 +0200 Subject: [PATCH 15/15] Temperatures may in fact be negative E.g. in case of a disconnected thermistor, or when it is really really cold. Make sure our parsing doesn't get confuse by this and thinks that ok T:150.0/210.0 T0:-55.7/0 T1:150.0/210.0 is actually only T and T1 being reported by the firmware, causing stuff to be wrongly canonicalized thanks to T/T1 being Smoothie's way of reporting dual extruder setups. Fixes #2007 --- src/octoprint/util/comm.py | 6 +++--- tests/util/test_comm_helpers.py | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index aa71a9ac6..0cbaf9fe5 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -89,7 +89,7 @@ Groups will be as follows: * ``size``: size of the file in bytes (int) """ -regex_temp = re.compile("(?PB|T(?P\d*)):\s*(?P%s)(\s*\/?\s*(?P%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern)) +regex_temp = re.compile("(?PB|T(?P\d*)):\s*(?P%s)(\s*\/?\s*(?P%s))?" % (regex_float_pattern, regex_float_pattern)) """Regex matching temperature entries in line. Groups will be as follows: @@ -100,7 +100,7 @@ Groups will be as follows: * ``target``: target temperature, if provided (float) """ -regex_repetierTempExtr = re.compile("TargetExtr(?P\d+):(?P%s)" % regex_positive_float_pattern) +regex_repetierTempExtr = re.compile("TargetExtr(?P\d+):(?P%s)" % regex_float_pattern) """Regex for matching target temp reporting from Repetier. Groups will be as follows: @@ -110,7 +110,7 @@ Groups will be as follows: * ``target``: new target temperature (float) """ -regex_repetierTempBed = re.compile("TargetBed:(?P%s)" % regex_positive_float_pattern) +regex_repetierTempBed = re.compile("TargetBed:(?P%s)" % regex_float_pattern) """Regex for matching target temp reporting from Repetier for beds. Groups will be as follows: diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py index 5ac6998e2..0da2cf609 100644 --- a/tests/util/test_comm_helpers.py +++ b/tests/util/test_comm_helpers.py @@ -221,7 +221,9 @@ class TestCommHelpers(unittest.TestCase): ("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1), ("T:23.0/220.0 B:60.0/70.0", 0, dict(T0=(23.0, 220.0), B=(60.0, 70.0)), 0), ("ok T:23.0/220.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 0, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2), - ("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2) + ("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2), + ("ok T:-55.7/0 T0:-55.7/0 T1:150.0/210.0", 0, dict(T0=(-55.7, 0), T1=(150.0, 210.0)), 1), + ("ok T:150.0/210.0 T0:-55.7/0 T1:150.0/210.0", 1, dict(T0=(-55.7, 0), T1=(150.0, 210.0)), 1) ) @unpack def test_process_temperature_line(self, line, current, expected_result, expected_max):