From 47b3f51a3faedecf16c56efdc9e601cadfa40a45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 30 Oct 2019 18:10:52 +0100 Subject: [PATCH 01/19] =?UTF-8?q?=E2=99=BB=20Speed=20up=20the=20analyser?= =?UTF-8?q?=20a=20bit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3318 Thanks at @jmfrank63 for the heads-up! --- src/octoprint/util/gcodeInterpreter.py | 71 ++++++++++++++++---------- 1 file changed, 45 insertions(+), 26 deletions(-) diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index 8d7834c4b..be0b2cfe2 100644 --- a/src/octoprint/util/gcodeInterpreter.py +++ b/src/octoprint/util/gcodeInterpreter.py @@ -62,36 +62,55 @@ class Vector3D(object): return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) def __add__(self, other): - if isinstance(other, Vector3D): + try: + if len(other) == 3: + return Vector3D(self.x + other[0], + self.y + other[1], + self.z + other[2]) + except TypeError: + # doesn't look like a 3-tuple + pass + + try: return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z) - elif isinstance(other, (tuple, list)) and len(other) == 3: - return Vector3D(self.x + other[0], - self.y + other[1], - self.z + other[2]) - else: - raise ValueError("other must be a Vector3D instance or a list or tuple of length 3") + except AttributeError: + # also doesn't look like a Vector3D + pass + + raise TypeError("other must be a Vector3D instance or a list or tuple of length 3") def __sub__(self, other): - if isinstance(other, Vector3D): + try: + if len(other) == 3: + return Vector3D(self.x - other[0], + self.y - other[1], + self.z - other[2]) + except TypeError: + # doesn't look like a 3-tuple + pass + + try: return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z) - elif isinstance(other, (tuple, list)) and len(other) == 3: - return Vector3D(self.x - other[0], - self.y - other[1], - self.z - other[2]) - else: - raise ValueError("other must be a Vector3D instance or a list or tuple") + except AttributeError: + # also doesn't look like a Vector3D + pass + + raise TypeError("other must be a Vector3D instance or a list or tuple of length 3") def __mul__(self, other): - if isinstance(other, (int, float)): + try: return Vector3D(self.x * other, self.y * other, self.z * other) - else: - raise ValueError("other must be a float or int value") + except TypeError: + # doesn't look like a scalar + pass + + raise ValueError("other must be a float or int value") def __rmul__(self, other): return self.__mul__(other) @@ -342,11 +361,11 @@ class gcode(object): totalExtrusion[currentExtruder]) if currentExtruder == 0 and len(currentE) > 1 and duplicationMode: - # Copy first extruder length to other extruders + # Copy first extruder length to other extruders for i in range(1, len(currentE)): - totalExtrusion[i] += e - currentE[i] += e - maxExtrusion[i] = max(maxExtrusion[i], + totalExtrusion[i] += e + currentE[i] += e + maxExtrusion[i] = max(maxExtrusion[i], totalExtrusion[i]) else: e = 0.0 @@ -436,13 +455,13 @@ class gcode(object): else: fwrecoverTime = (fwretractDist + s) / f elif M == 605: #Duplication/Mirroring mode - s = getCodeInt(line, 'S') - if s in [2, 4, 5, 6]: - # Duplication / Mirroring mode selected. Printer firmware copies extrusion commands + s = getCodeInt(line, 'S') + if s in [2, 4, 5, 6]: + # Duplication / Mirroring mode selected. Printer firmware copies extrusion commands # from first extruder to all other extruders duplicationMode = True - else: - duplicationMode = False + else: + duplicationMode = False elif T is not None: if T > max_extruders: From 4bf3445eef82803bd4cbf44f69a57b8270ceafa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 30 Oct 2019 18:23:57 +0100 Subject: [PATCH 02/19] =?UTF-8?q?=F0=9F=92=A1=20Fix=20a=20doc=20bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3233 --- docs/jsclientlib/socket.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/jsclientlib/socket.rst b/docs/jsclientlib/socket.rst index 6da88a1ee..925528490 100644 --- a/docs/jsclientlib/socket.rst +++ b/docs/jsclientlib/socket.rst @@ -42,7 +42,7 @@ To register for all message types, provide ``*`` as the type to register for. ``handler`` is expected to be a function accepting one object parameter ``eventObj``, consisting - of the received message as property ``key`` and the received payload (if any) as property ``data``. + of the received message as property ``event`` and the received payload (if any) as property ``data``. .. code-block:: javascript From 9c775bd899e3f17178fc14a13bf581a72502226f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 30 Oct 2019 18:28:53 +0100 Subject: [PATCH 03/19] =?UTF-8?q?=F0=9F=90=9B=20Fix=20overzealous=20filter?= =?UTF-8?q?ing=20of=20history=20entries?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3309 --- src/octoprint/server/api/printer.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index 39cb89fc2..47737c77b 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -483,17 +483,17 @@ def _get_temperature_data(preprocessor): def _keep_tools(x): - return _delete_from_data(x, lambda k: not k.startswith("tool")) + return _delete_from_data(x, lambda k: not k.startswith("tool") and k != "history") def _keep_bed(x): - return _delete_from_data(x, lambda k: k != "bed") + return _delete_from_data(x, lambda k: k != "bed" and k != "history") def _delete_bed(x): return _delete_from_data(x, lambda k: k == "bed") def _keep_chamber(x): - return _delete_from_data(x, lambda k: k != "chamber") + return _delete_from_data(x, lambda k: k != "chamber" and k != "history") def _delete_chamber(x): return _delete_from_data(x, lambda k: k == "chamber") From 888fb97e66ec3587b05e5f1745550862960d2590 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 31 Oct 2019 09:57:57 +0100 Subject: [PATCH 04/19] =?UTF-8?q?=F0=9F=92=A1=20Clarify=20Error=20event=20?= =?UTF-8?q?in=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3210 --- docs/events/index.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/events/index.rst b/docs/events/index.rst index 791f33d0f..67dca11a5 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -151,6 +151,9 @@ Error An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or on the connection. + Note that this event will not fire for error messages from the firmware that are handled (and as such recovered from) + either by OctoPrint or a plugin. + Payload: * ``error``: the error string From bee82bcde99fb3899113e8d3e5e269b4f4b410d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 31 Oct 2019 11:09:54 +0100 Subject: [PATCH 05/19] =?UTF-8?q?=F0=9F=90=9B=20Treat=20port=3DNone=20as?= =?UTF-8?q?=20port=3DAUTO=20on=20autoconnect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Potential fix for #3267 --- src/octoprint/server/__init__.py | 10 +++++++--- src/octoprint/util/comm.py | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index db4322ce5..b9f3dc0ad 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -732,12 +732,16 @@ class Server(object): # auto connect if self._settings.getBoolean(["serial", "autoconnect"]): + self._logger.info("Autoconnect on startup is configured, trying to connect to the printer...") try: - (port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"]) + (port, baudrate) = self._settings.get(["serial", "port"]).strip(), self._settings.getInt(["serial", "baudrate"]) printer_profile = printerProfileManager.get_default() connectionOptions = printer.__class__.get_connection_options() - if port in connectionOptions["ports"] or port == "AUTO": - printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default") + if port in connectionOptions["ports"] or port == "AUTO" or port is None: + self._logger.info("Trying to connect to configured serial port {}".format(port)) + printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default") + else: + self._logger.info("Could not find configured serial port {} in the system, cannot automatically connect to a non existing printer. Is it plugged in and booted up yet?") except: self._logger.exception("Something went wrong while attempting to automatically connect to the printer") diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 0f2200705..4c4991fd7 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -378,7 +378,7 @@ class MachineCom(object): CAPABILITY_SUPPORT_DETECTED = "detected" CAPABILITY_SUPPORT_DISABLED = "disabled" - def __init__(self, port = None, baudrate=None, callbackObject=None, printerProfileManager=None): + def __init__(self, port=None, baudrate=None, callbackObject=None, printerProfileManager=None): self._logger = logging.getLogger(__name__) self._serialLogger = logging.getLogger("SERIAL") self._phaseLogger = logging.getLogger(__name__ + ".command_phases") From 759f4f8ea2e0274265111387576b75cb164d678b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 31 Oct 2019 12:07:31 +0100 Subject: [PATCH 06/19] =?UTF-8?q?=F0=9F=90=9B=20Default=20checkbox=20shoul?= =?UTF-8?q?d=20always=20be=20enabled?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See #3302 --- src/octoprint/templates/tabs/timelapse.jinja2 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/templates/tabs/timelapse.jinja2 b/src/octoprint/templates/tabs/timelapse.jinja2 index da134c733..6f419b46e 100644 --- a/src/octoprint/templates/tabs/timelapse.jinja2 +++ b/src/octoprint/templates/tabs/timelapse.jinja2 @@ -75,7 +75,7 @@
From 6e6dd2c34e14226a4bdf842caff796e07384305d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 31 Oct 2019 17:09:49 +0100 Subject: [PATCH 07/19] =?UTF-8?q?=F0=9F=90=9B=20port=20can=20be=20None?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/server/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index b9f3dc0ad..19bbdfe16 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -734,7 +734,7 @@ class Server(object): if self._settings.getBoolean(["serial", "autoconnect"]): self._logger.info("Autoconnect on startup is configured, trying to connect to the printer...") try: - (port, baudrate) = self._settings.get(["serial", "port"]).strip(), self._settings.getInt(["serial", "baudrate"]) + (port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"]) printer_profile = printerProfileManager.get_default() connectionOptions = printer.__class__.get_connection_options() if port in connectionOptions["ports"] or port == "AUTO" or port is None: From b031092f07d4e86ffd92a67ee0b2f6181d76f426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 1 Nov 2019 13:03:47 +0100 Subject: [PATCH 08/19] =?UTF-8?q?=E2=9C=A8=20PMGR:=20plugin=20data=20clean?= =?UTF-8?q?up=20functions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plugin data can now be cleaned up * on a plugin's uninstall through the plugin manager * manually through a new action button in the plugin manager Implements #3299 Ideas for further improvement: * Management interface to show "orphaned" plugin data and delete on request. --- .../plugins/pluginmanager/__init__.py | 55 ++++++++++++- .../static/clientjs/pluginmanager.js | 18 ++++- .../pluginmanager/static/js/pluginmanager.js | 77 +++++++++++++++---- .../templates/pluginmanager_settings.jinja2 | 9 +-- src/octoprint/static/js/app/helpers.js | 36 ++++++--- 5 files changed, 157 insertions(+), 38 deletions(-) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index d7f2e0b59..4aed0ce2e 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -169,7 +169,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, notices_ttl=6*60, pip_args=None, pip_force_user=False, - confirm_uninstall=True, confirm_disable=False, dependency_links=False, hidden=[], @@ -270,6 +269,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, "uninstall": ["plugin"], "enable": ["plugin"], "disable": ["plugin"], + "cleanup": ["plugin"], "refresh_repository": [] } @@ -350,7 +350,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return make_response("Unknown plugin: %s" % plugin_name, 404) plugin = self._plugin_manager.plugins[plugin_name] - return self.command_uninstall(plugin) + return self.command_uninstall(plugin, cleanup=data.get("cleanup", False)) + + elif command == "cleanup": + plugin_name = data["plugin"] + if not plugin_name in self._plugin_manager.plugins: + return make_response("Unknown plugin: %s" % plugin_name, 404) + + plugin = self._plugin_manager.plugins[plugin_name] + return self.command_cleanup(plugin) elif command == "enable" or command == "disable": plugin_name = data["plugin"] @@ -531,7 +539,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._send_result_notification("install", result) return jsonify(result) - def command_uninstall(self, plugin): + def command_uninstall(self, plugin, cleanup=False): if plugin.key == "pluginmanager": return make_response("Can't uninstall Plugin Manager", 403) @@ -580,7 +588,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals())) return make_response("Could not uninstall plugin, its origin is unknown") - needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) + needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational() @@ -620,6 +628,45 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_reconnect=needs_reconnect, plugin=self._to_external_plugin(plugin)) self._send_result_notification("uninstall", result) + self._logger.info("Plugin {} uninstalled".format(plugin.key)) + + if cleanup: + self.command_cleanup(plugin) + + return jsonify(result) + + def command_cleanup(self, plugin): + # delete plugin settings + self._settings.global_set(["plugins", plugin.key], None) + self._settings.save() + message = "Cleaned up settings of plugin {}".format(plugin.key) + self._log_stdout(message) + self._logger.info(message) + + # delete plugin data folder + import os + import shutil + + result_data = True + data_folder = os.path.join(self._settings.getBaseFolder("data"), plugin.key) + if os.path.exists(data_folder): + try: + shutil.rmtree(data_folder) + message = "Cleaned up data folder of plugin {}".format(plugin.key) + self._log_stdout(message) + self._logger.info(message) + except: + message = "Could not delete data folder of plugin {} at {}".format(plugin.key, data_folder) + self._log_stderr(message) + self._logger.exception(message) + result_data = False + + result = dict(result=result_data, + needs_restart=True, + plugin=self._to_external_plugin(plugin)) + self._send_result_notification("cleanup", result) + self._logger.info("Plugin {} cleaned up".format(plugin.key)) + return jsonify(result) def command_toggle(self, plugin, command): diff --git a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js index acaaf3590..5a59a2075 100644 --- a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js @@ -52,11 +52,25 @@ return this.base.simpleApiCommand("pluginmanager", "install", data, opts); }; - OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) { + OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, cleanup, opts) { + // backwards compatibility to former argument list (plugin, opts) + if (arguments.length === 2 && typeof cleanup === "object") { + opts = cleanup; + cleanup = false; + } + + var data = { + plugin: plugin, + cleanup: !!cleanup + }; + return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.cleanup = function(plugin, opts) { var data = { plugin: plugin }; - return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts); + return this.base.simpleApiCommand("pluginmanager", "cleanup", data, opts); }; OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) { diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index c1450e5bf..ba209a4ca 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -185,6 +185,12 @@ $(function() { && !data.pending_uninstall; }; + self.enableCleanup = function(data) { + return self.enableManagement() + && data.key !== 'pluginmanager' + && !data.pending_uninstall; + }; + self.enableRepoInstall = function(data) { return self.enableManagement() && self.pipAvailable() && !self.safeMode() && !self.throttled() && self.online() && self.isCompatible(data); }; @@ -565,14 +571,14 @@ $(function() { } if (data.bundled) return; - if (data.key == "pluginmanager") return; + if (data.key === "pluginmanager") return; // defining actual uninstall logic as functor in order to handle // the confirm/no-confirm logic without duplication of logic - var performUninstall = function() { + var performUninstall = function(cleanup) { self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: _.escape(data.name)})); - OctoPrint.plugins.pluginmanager.uninstall(data.key) + OctoPrint.plugins.pluginmanager.uninstall(data.key, cleanup) .done(function() { self.requestData(); }) @@ -589,19 +595,56 @@ $(function() { }); }; - if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_uninstall()) { - // confirmation needed. Show confirmation dialog and call performUninstall if user clicks Yes - showConfirmationDialog({ - message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: _.escape(data.name)}), - cancel: gettext("Keep installed"), - proceed: gettext("Uninstall"), - onproceed: performUninstall, - nofade: true - }); - } else { - // no confirmation needed, just go ahead and uninstall - performUninstall(); + showConfirmationDialog({ + message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: _.escape(data.name)}), + cancel: gettext("Keep installed"), + proceed: [ + gettext("Uninstall"), + gettext("Uninstall & clean up data") + ], + onproceed: function(button) { + // buttons: 0=uninstall, 1=uninstall&cleanup + performUninstall(button === 1) + }, + nofade: true + }); + }; + + self.cleanupPlugin = function(data) { + if (!self.loginState.isAdmin()) { + return; } + + if (!self.enableUninstall(data)) { + return; + } + + if (data.key === "pluginmanager") return; + + var performCleanup = function() { + self._markWorking(gettext("Cleaning up plugin data..."), _.sprintf(gettext("Cleaning up data of plugin \"%(name)s\""), {name: _.escape(data.name)})); + + OctoPrint.plugins.pluginmanager.cleanup(data.key) + .fail(function() { + new PNotify({ + title: gettext("Something went wrong"), + text: gettext("Please consult octoprint.log for details"), + type: "error", + hide: false + }); + }) + .always(function() { + self._markDone(); + }) + }; + + showConfirmationDialog({ + message: _.sprintf(gettext("You are about to cleanup the plugin data of \"%(name)s\". This operation cannot be reversed."), {name: _.escape(data.name)}), + cancel: gettext("Keep data"), + proceed: gettext("Cleanup data"), + onproceed: performCleanup, + nofade: true + }); }; self.refreshRepository = function() { @@ -748,6 +791,10 @@ $(function() { line = gettext("Disable %(plugin)s: %(result)s"); break; } + case "cleanup": { + line = gettext("Cleanup %(plugin)s: %(result)s"); + break; + } default: { return; } diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 6026fdc18..5a9faea0c 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -81,7 +81,7 @@
-  |  +  |  |  @@ -260,13 +260,6 @@
{{ _('Confirmations') }} -
-
- -
-
+
+ +
+ + {{ _('Only modify if told to do so') }} +
+
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 4c4991fd7..80196735c 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -512,7 +512,8 @@ class MachineCom(object): self._pausing_commands = settings().get(["serial", "pausingCommands"]) self._emergency_commands = settings().get(["serial", "emergencyCommands"]) - self._clear_to_send = CountedEvent(name="comm.clear_to_send", minimum=None) + self._ack_max = settings().getInt(["serial", "ackMax"]) + self._clear_to_send = CountedEvent(name="comm.clear_to_send", minimum=None, maximum=self._ack_max) self._send_queue = SendQueue() self._temperature_timer = None self._sd_status_timer = None @@ -3143,6 +3144,19 @@ class MachineCom(object): self._logger.debug("Type already in send queue: " + e.type) return False + def _use_up_clear(self, gcode): + # 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 + eats_clear = self._unknownCommandsNeedAck + if gcode is not None: + eats_clear = True + + if eats_clear: + # if we need to use up a clear, do that now + self._clear_to_send.clear() + + return eats_clear + def _send_loop(self): """ The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for @@ -3189,6 +3203,7 @@ class MachineCom(object): 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!) + self._use_up_clear(gcode) self._do_send_with_checksum(command, linenumber) else: @@ -3239,7 +3254,13 @@ class MachineCom(object): continue # now comes the part where we increase line numbers and send stuff - no turning back now + used_up_clear = self._use_up_clear(gcode) self._do_send(command, gcode=gcode) + if not used_up_clear: + # If we didn't use up a clear we need to tickle the read queue - there might + # not be a reply to this command, so our _monitor loop will stay waiting until + # timeout. We definitely do not want that, so we tickle the queue manually here + self._continue_sending() # trigger "sent" phase and use up one "ok" if on_sent is not None and callable(on_sent): @@ -3247,21 +3268,6 @@ class MachineCom(object): on_sent() self._process_command_phase("sent", command, command_type, gcode=gcode, subcode=subcode, tags=tags) - # 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 - use_up_clear = self._unknownCommandsNeedAck - if gcode is not None: - use_up_clear = True - - if use_up_clear: - # if we need to use up a clear, do that now - self._clear_to_send.clear() - else: - # Otherwise we need to tickle the read queue - there might not be a reply - # to this command, so our _monitor loop will stay waiting until timeout. We - # definitely do not want that, so we tickle the queue manually here - self._continue_sending() - finally: # no matter _how_ we exit this block, we signal that we # are done processing the last fetched queue entry @@ -3788,10 +3794,12 @@ class MachineCom(object): return self._logger.info(message) - self._do_send(cmd, gcode=gcode) # use up an ok since we will get one back for this command and don't want to get out of sync - self._clear_to_send.clear() + used_up_clear = self._use_up_clear(gcode) + self._do_send(cmd, gcode=gcode) + if not used_up_clear: + self._continue_sending() return None, From 9cd597a4671b028eed0c23a616f3c412260d6d87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 5 Nov 2019 13:21:49 +0100 Subject: [PATCH 15/19] =?UTF-8?q?=F0=9F=90=9B=20Fix=20invalid=20use=20of?= =?UTF-8?q?=20401=20response=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Leftovers from fixing #2297. Fixes #3327 --- docs/api/general.rst | 13 +++++++++---- src/octoprint/server/api/__init__.py | 2 +- src/octoprint/server/apps/__init__.py | 6 +++--- .../static/js/app/viewmodels/loginstate.js | 12 ++---------- 4 files changed, 15 insertions(+), 18 deletions(-) diff --git a/docs/api/general.rst b/docs/api/general.rst index 3c404724c..47e46aa32 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -148,8 +148,14 @@ Login via the ``passive`` flag. Will return a :http:statuscode:`200` with a :ref:`login response ` on successful - login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in - case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account. + login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`403` in + case of a username/password mismatch, unknown user or a deactivated account. + + .. warning:: + + Previous versions of this API endpoint did return a :http:statuscode:`401` in case of a username/password + mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of + the :http:statuscode:`401` code and got therefore changed as part of a bug fix. :json passive: If present, performs a passive login only, returning information about the current user that's active either through an existing session or the used API key @@ -157,8 +163,7 @@ Login :json pass: (active login only) Password :json remember: (active login only) Whether to set a "remember me" cookie on the session :status 200: Successful login - :status 401: Username/password mismatch or unknown user - :status 403: Deactivated account + :status 403: Username/password mismatch, unknown user or deactivated account .. _sec-api-general-logout: diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index f9e64940e..a941ab558 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -241,7 +241,7 @@ def login(): r.delete_cookie("active_logout") return r - return make_response(("User unknown or password incorrect", 401, [])) + return make_response(("User unknown or password incorrect", 403, [])) elif "passive" in data: return passive_login() diff --git a/src/octoprint/server/apps/__init__.py b/src/octoprint/server/apps/__init__.py index 04d8edf87..f5fee21bd 100644 --- a/src/octoprint/server/apps/__init__.py +++ b/src/octoprint/server/apps/__init__.py @@ -63,7 +63,7 @@ def verifySessionKey(): apps = _get_registered_apps() if not lookup_key in apps or not apps[lookup_key]["enabled"] or not "pubkey" in apps[lookup_key]: octoprint.server.appSessionManager.remove(key) - return make_response("Invalid app: {lookup_key}".format(lookup_key=lookup_key), 401) + return make_response("Invalid app: {lookup_key}".format(lookup_key=lookup_key), 403) pubkey_string = apps[lookup_key]["pubkey"] pubkey_string = "\n".join([pubkey_string[x:x+64] for x in range(0, len(pubkey_string), 64)]) @@ -78,12 +78,12 @@ def verifySessionKey(): rsa.verify(message, signature, pubkey) except rsa.VerificationError: octoprint.server.appSessionManager.remove(key) - return make_response("Invalid signature", 401) + return make_response("Invalid signature", 403) # generate new session key and return it result = octoprint.server.appSessionManager.verify(key) if not result: - return make_response("Invalid key or already verified", 401) + return make_response("Invalid key or already verified", 403) verified_key, valid_until = result return jsonify(key=verified_key, validUntil=valid_until) diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index 3b90694a3..521c68804 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -173,18 +173,10 @@ $(function() { }) .fail(function(response) { switch(response.status) { - case 401: { - new PNotify({ - title: gettext("Login failed"), - text: gettext("User unknown or wrong password"), - type: "error" - }); - break; - } case 403: { new PNotify({ title: gettext("Login failed"), - text: gettext("Your account is deactivated"), + text: gettext("User unknown, wrong password or account deactivated"), type: "error" }); break; @@ -200,7 +192,7 @@ $(function() { self.fromResponse(response); }) .fail(function(error) { - if (error && error.status === 401) { + if (error && error.status === 403) { self.fromResponse(false); } }); From ef54cbb148c3ce392be7d1f9a4a169dfbadd0294 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 5 Nov 2019 15:41:51 +0100 Subject: [PATCH 16/19] =?UTF-8?q?=E2=98=94=20Set=20close=5Fexec=20flag=20o?= =?UTF-8?q?n=20serial=20handle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Possible fix for #3212 --- src/octoprint/util/comm.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 80196735c..78b76da93 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -39,7 +39,7 @@ 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, PrependableQueue, TypeAlreadyInQueue, chunks, ResettableTimer, \ monotonic_time -from octoprint.util.platform import get_os +from octoprint.util.platform import get_os, set_close_exec try: import _winreg @@ -2669,6 +2669,15 @@ class MachineCom(object): serial_obj.open() + # Set close_exec flag on serial handle, see #3212 + if hasattr(serial_obj, "fd"): + # posix + set_close_exec(serial_obj.fd) + elif hasattr(serial_obj, "_port_handle"): + # win32 + # noinspection PyProtectedMember + set_close_exec(serial_obj._port_handle) + return BufferedReadlineWrapper(serial_obj) serial_factories = self._serial_factory_hooks.items() + [("default", default)] From 96294df71040f6d0647bb9f0f6e9fcdec0b727a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gy=C3=B6rgy=20Bal=C3=A1ssy?= Date: Tue, 5 Nov 2019 22:25:25 +0100 Subject: [PATCH 17/19] Fixed a typo in the restore command name of the Backup plugin --- docs/bundledplugins/backup.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst index 350d40508..8e05c4954 100644 --- a/docs/bundledplugins/backup.rst +++ b/docs/bundledplugins/backup.rst @@ -27,7 +27,7 @@ Command line usage ------------------ The Backup Plugin implements a command line interface that allows creation and restoration of backups. -It adds two new commands, ``backup:backup`` and ``backup_restore``. +It adds two new commands, ``backup:backup`` and ``backup:restore``. .. code-block:: none From 2b60dbc7e142fbaa383d0d71cdd2e361cd0fa4ea Mon Sep 17 00:00:00 2001 From: Daniele Forsi Date: Wed, 6 Nov 2019 22:11:23 +0100 Subject: [PATCH 18/19] Fix typos Those typos were found with codespell which is available from https://github.com/lucasdemarchi/codespell.git --- src/octoprint/plugin/core.py | 2 +- src/octoprint/plugins/discovery/__init__.py | 2 +- src/octoprint/printer/estimation.py | 2 +- src/octoprint/server/__init__.py | 2 +- src/octoprint/server/api/__init__.py | 2 +- src/octoprint/server/util/tornado.py | 2 +- src/octoprint/settings.py | 2 +- src/octoprint/static/js/app/viewmodels/settings.js | 2 +- src/octoprint/templates/tabs/timelapse.jinja2 | 2 +- src/octoprint/util/comm.py | 6 +++--- 10 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index a269c9dc4..da2a4a709 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -387,7 +387,7 @@ class PluginInfo(object): @property def hooks(self): """ - Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defiend in + Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in :attr:`attr_hooks` if available, otherwise an empty dictionary is returned. Returns: diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 50d8fad7b..51ce72ed5 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -211,7 +211,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, def zeroconf_unregister(self, reg_type, port=None): """ - Unregisteres a previously registered Zeroconf/Bonjour/Avahi service identified by service and port. + Unregisters a previously registered Zeroconf/Bonjour/Avahi service identified by service and port. :param reg_type: the type of the service to be unregistered :param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given diff --git a/src/octoprint/printer/estimation.py b/src/octoprint/printer/estimation.py index 537760a8f..7ee17ac0f 100644 --- a/src/octoprint/printer/estimation.py +++ b/src/octoprint/printer/estimation.py @@ -69,7 +69,7 @@ class PrintTimeEstimator(object): but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage in the print we do a percentage based weighing of the statistical data and the intelligent estimate - the closer to the beginning of the print, the more precedence for the statistical - data, the closer to the cut off point, the more precendence for the intelligent estimate. This + data, the closer to the cut off point, the more precedence for the intelligent estimate. This is our preliminary total print time. 3. If the total print time is set, we do a sanity check for it. Based on the total print time estimate and the time we already spent printing, we calculate at what percentage we SHOULD be diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 19bbdfe16..4e8951a42 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -286,7 +286,7 @@ class Server(object): ### open port and prevent us from firing up Tornado later. ### ### The intermediary server's socket should have the CLOSE_EXEC flag (or its equivalent) set where possible, but - ### we can only do that if fcntl is availabel or we are on Windows, so better safe than sorry. + ### we can only do that if fcntl is available or we are on Windows, so better safe than sorry. ### ### See also issues #2035 and #2090 diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index a941ab558..cb6a1c089 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -106,7 +106,7 @@ def pluginCommand(name): return response return NO_CONTENT except Exception: - logging.getLogger(__name__).exception("Error while excuting SimpleApiPlugin {}".format(name), + logging.getLogger(__name__).exception("Error while executing SimpleApiPlugin {}".format(name), extra=dict(plugin=name)) return abort(500) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index d04e403f8..a07c5a6ac 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -71,7 +71,7 @@ class RequestlessExceptionLoggingMixin(tornado.web.RequestHandler): class CorsSupportMixin(tornado.web.RequestHandler): """ `tornado.web.RequestHandler `_ mixin that - makes sure to set CORS headers similarily to the Flask backed API endpoints. + makes sure to set CORS headers similarly to the Flask backed API endpoints. """ ENABLE_CORS = False diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 1dcdcd830..7e6bff899 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1232,7 +1232,7 @@ class Settings(object): self._logger.info("Migrated {} action to server.commands.{}".format(action, migrate_to)) to_delete.append(index) - self._logger.info("Deleting {} action from configured system commands, superseeded by server.commands.{}".format(action, migrate_to)) + self._logger.info("Deleting {} action from configured system commands, superseded by server.commands.{}".format(action, migrate_to)) for index in reversed(to_delete): actions.pop(index) diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 6b2c22262..5b28d3b53 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -655,7 +655,7 @@ $(function() { } } - // handler for any explicitely provided callbacks + // handler for any explicitly provided callbacks var callbackHandler = function() { if (!callback) return; try { diff --git a/src/octoprint/templates/tabs/timelapse.jinja2 b/src/octoprint/templates/tabs/timelapse.jinja2 index 6f419b46e..d80797330 100644 --- a/src/octoprint/templates/tabs/timelapse.jinja2 +++ b/src/octoprint/templates/tabs/timelapse.jinja2 @@ -26,7 +26,7 @@ {{ _('sec') }} - {{ _('OctoPrint will rate limit snapshots to this minimum interval. This is to prevent against performance issues with vase mode/continous z prints.') }} + {{ _('OctoPrint will rate limit snapshots to this minimum interval. This it to prevent against performance issues with vase mode/continuous z prints.') }} diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 78b76da93..d8d708bf3 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -2708,11 +2708,11 @@ class MachineCom(object): _recoverable_communication_errors = ("no line number with checksum", "missing linenumber") - _resend_request_communication_errors = ("line number", # since this error class get's checked after recoverable + _resend_request_communication_errors = ("line number", # since this error class gets checked after recoverable # communication errors, we can use this broad term here - "linenumber", # since this error class get's checked after recoverable + "linenumber", # since this error class gets checked after recoverable # communication errors, we can use this broad term here - "checksum", # since this error class get's checked after recoverable + "checksum", # since this error class gets checked after recoverable # communication errors, we can use this broad term here "format error", "expected line") From 8173f8d0c42a0e90771f53a5ebb56b9cd67b5b35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 8 Nov 2019 09:40:09 +0100 Subject: [PATCH 19/19] =?UTF-8?q?=F0=9F=90=9B=20gcode=20viewer:=20Fix=20sw?= =?UTF-8?q?apped=20G2/G3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3334 --- src/octoprint/static/gcodeviewer/js/Worker.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/static/gcodeviewer/js/Worker.js b/src/octoprint/static/gcodeviewer/js/Worker.js index f5c0f4224..dded4b51c 100644 --- a/src/octoprint/static/gcodeviewer/js/Worker.js +++ b/src/octoprint/static/gcodeviewer/js/Worker.js @@ -410,9 +410,9 @@ var doParse = function () { break; case 'g': if(args[j].charAt(1).toLowerCase() === '2') - direction=1; - if(args[j].charAt(1).toLowerCase() === '3') direction=-1; + if(args[j].charAt(1).toLowerCase() === '3') + direction=1; break; } }