diff --git a/docs/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst index e8c3675eb..d2a923e85 100644 --- a/docs/bundledplugins/pluginmanager.rst +++ b/docs/bundledplugins/pluginmanager.rst @@ -54,6 +54,12 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: # Time to live for the repository cache repository_ttl: 1440 + # The URL of the plugin notices feed to use + notices: http://plugins.octoprint.org/notices.json + + # Time to live for the notices feed cache + notices_ttl: 360 + # Additional arguments to use with pip. Defaults to unset, # you normally shouldn't need to modify this pip_args: --some --additional --pip --arguments @@ -76,6 +82,36 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: - hidden - plugins +.. _sec-bundledplugins-pluginmanager-hooks: + +Hooks +----- + +.. _sec-bundledplugins-pluginmanager-hooks-reconnect_hooks: + +octoprint.plugin.pluginmanager.reconnect_hooks +++++++++++++++++++++++++++++++++++++++++++++++ + +.. py:function:: reconnect_hooks_hook(*args, **kwargs) + + Returns additional hooks defined by the plugin for which the plugin manager + should display the "You should reconnect to your printer" message on plugin + install/uninstall/enabling/disabling. + + Handlers should return a Python list containing the affected hook names. + + **Example** + + .. code-block:: python + + def reconnect_hooks_hook(*args, **kwargs): + return ["octoprint.plugin.exampleplugin.some_custom_hook", + "octoprint.plugin.exampleplugin.some_other_custom_hook"] + + __plugin_hooks__ = { + "octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook + } + .. _sec-bundledplugins-pluginmanager-sourcecode: Source Code diff --git a/docs/conf.py b/docs/conf.py index 74799d526..3827b54fa 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -33,7 +33,7 @@ needs_sphinx = '1.3' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain', - 'sphinx.ext.napoleon'] + 'sphinx.ext.napoleon', 'sphinxcontrib.mermaid'] todo_include_todos = True # Add any paths that contain templates here, relative to this directory. diff --git a/docs/events/index.rst b/docs/events/index.rst index b471193f5..bc6f1245f 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -477,6 +477,15 @@ PositionUpdate * ``t``: last tool selected *through OctoPrint* * ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint* +ToolChange + A tool change command was sent to the printer. The payload contains the former current tool index and the + new current tool index. + + Payload: + + * ``old``: old tool index + * ``new``: new tool index + Timelapses ---------- diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index ee3136da8..6b14a616b 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -68,7 +68,16 @@ All GCODE scripts have access to the following template variables through the te * ``printer_profile``: The currently selected Printer Profile, including information such as the extruder count, the build volume size, the filament diameter etc. - * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!) + * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!). + Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and + current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no + position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! + * ``last_temperature``: Last actual and target temperature reported for all available tools and if available the + heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``, + ...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped + to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be + present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also + note that ``actual`` and ``target`` might be ``None``. * ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type`` and ``script.name`` respectively. @@ -76,17 +85,18 @@ There are a few additional template variables available for the following specif * ``afterPrintPaused`` and ``beforePrintResumed`` - * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists - of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool - ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no position could be - retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! + * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See + ``last_position`` above for the structure to expect here. + * ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above + for the structure to expect here. * ``afterPrintCancelled`` * ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled. - Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and - current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no - position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! + See ``last_position`` above for the structure to expect here. + * ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above + for the structure to expect here. + .. warning:: diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 93bd3f108..299903bae 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -451,18 +451,21 @@ This describes actually four hooks: should use this option. * A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``. Handlers which wish to rewrite both the command and the command type should use this option. - * **``queuing`` phase only**: A list of any of the above to allow for expanding one command into + * A list of any of the above to allow for expanding one command into many. The following example shows how any queued command could be turned into a sequence of a temperature query, line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example - does not make a lot of sense to be quiet honest): + does not make a lot of sense to be quite honest): .. code-block:: python - def multi_expansion(*args, **kwargs): - return [("M105", "temperature_poll"), - ("M110",), - "M117 GCODE: {}".format(gcode), - (command, command_type)] + def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): + if gcode or not cmd.startswith("@foo"): + return + + return [("M105", "temperature_poll"), + ("M110",), + "M117 echo foo: {}".format(cmd)] + Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type`` to one already in the queue will give an error. diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index f389ce5ce..584b745ba 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -299,6 +299,130 @@ on your view model, taking a list of all bound view models: }); }) +.. _sec-plugins-viewmodels-livecycle: + +Lifecycle diagrams +------------------ + +.. _sec-plugins-viewmodels-startup: + +Web interface startup +~~~~~~~~~~~~~~~~~~~~~ + +.. mermaid:: + + sequenceDiagram + participant Main + participant onServerConnect + participant fetchSettings + participant bindViewModels + participant DataUpdater + participant LoginStateViewModel + + Note right of DataUpdater: connectCallback = undefined + + activate Main + + Main->>+DataUpdater: connect + Note right of DataUpdater: initialized = false + DataUpdater-->>Main: ok + deactivate Main + DataUpdater->>DataUpdater: asynchronous connect to server... + activate DataUpdater + Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...) + DataUpdater-X+Main: done + deactivate DataUpdater + deactivate DataUpdater + + Main->>+DataUpdater: connectCallback = onServerConnect + Note right of DataUpdater: connectCallback = onServerConnect + DataUpdater-->>-Main: ok + Main->>+onServerConnect: call + onServerConnect->>+LoginStateViewModel: passiveLogin + LoginStateViewModel-->>onServerConnect: ok + onServerConnect-->>Main: ok + deactivate onServerConnect + deactivate Main + + LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login + Note over Main,LoginStateViewModel: Session available! + LoginStateViewModel-X+onServerConnect: done + deactivate LoginStateViewModel + deactivate LoginStateViewModel + + onServerConnect->>+DataUpdater: initialized + Note right of DataUpdater: initialized = true + DataUpdater->DataUpdater: trigger stored callbacks + DataUpdater-->>-onServerConnect: ok + onServerConnect-X+Main: done + deactivate onServerConnect + + Main->>+fetchSettings: call + Note right of fetchSettings: trigger onStartup + + fetchSettings-->>Main: ok + deactivate Main + + fetchSettings->>+fetchSettings: asynchronous settings fetch + fetchSettings->>+bindViewModels: call + + loop for each view model + bindViewModels->bindViewModels: trigger onBeforeBinding + bindViewModels->bindViewModels: trigger onBoundTo + bindViewModels->bindViewModels: trigger onAfterBinding + end + + bindViewModels->bindViewModels: trigger onAllBound + opt User is logged in + bindViewModels->>+LoginStateViewModel: onAllBound + LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn + LoginStateViewModel-->>-bindViewModels: ok + end + bindViewModels->bindViewModels: trigger onStartupComplete + bindViewModels-->>-fetchSettings: ok + + deactivate fetchSettings + deactivate fetchSettings + + +.. _sec-plugins-viewmodels-reconnect: + +Web interface reconnect +~~~~~~~~~~~~~~~~~~~~~~~ + +.. mermaid:: + + sequenceDiagram + participant onServerConnect + participant DataUpdater + participant LoginStateViewModel + + activate DataUpdater + DataUpdater->>DataUpdater: call connectCallback + DataUpdater->>+onServerConnect: call + onServerConnect-->>DataUpdater: ok + deactivate DataUpdater + + onServerConnect->>+LoginStateViewModel: passiveLogin + LoginStateViewModel-->>onServerConnect: ok + deactivate onServerConnect + LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login + Note over onServerConnect,LoginStateViewModel: Session available! + opt User is logged in + LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn + end + + activate onServerConnect + LoginStateViewModel-XonServerConnect: done + deactivate LoginStateViewModel + deactivate LoginStateViewModel + + onServerConnect->>+DataUpdater: initialized + DataUpdater->DataUpdater: trigger stored callbacks + DataUpdater-->>onServerConnect: ok + deactivate DataUpdater + deactivate onServerConnect + .. seealso:: `OctoPrint's core viewmodels `_ diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py index 633eeef35..b6d9a1810 100644 --- a/docs/sphinxext/onlineinclude.py +++ b/docs/sphinxext/onlineinclude.py @@ -7,41 +7,99 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the import codecs -import urllib2 +import requests +from contextlib import closing -from sphinx.directives import LiteralInclude, dedent_lines +from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \ + nodes, set_source_info, parselinenos, logger, container_wrapper + +if False: + # For type annotation + from typing import Any, List # NOQA cache = dict() +class OnlineIncludeReader(LiteralIncludeReader): + + def read_file(self, filename, location=None): + # type: (unicode, Any) -> List[unicode] + + global cache + try: + if filename in cache: + lines = cache[filename] + else: + with closing(requests.get(filename, stream=True)) as r: + r.encoding = self.encoding + lines = r.text.splitlines(True) + cache[filename] = lines + + if 'tab-width' in self.options: + lines = [line.expandtabs(self.options['tab-width']) for line in lines] + + return lines + except (IOError, OSError): + raise IOError(_('Include file %r not found or reading it failed') % filename) + except UnicodeError: + raise UnicodeError(_('Encoding %r used for reading included file %r seems to ' + 'be wrong, try giving an :encoding: option') % + (self.encoding, filename)) + + class OnlineIncludeDirective(LiteralInclude): - def read_with_encoding(self, filename, document, codec_info, encoding): - global cache + def run(self): + # type: () -> List[nodes.Node] + document = self.state.document + if not document.settings.file_insertion_enabled: + return [document.reporter.warning('File insertion disabled', + line=self.lineno)] + env = document.settings.env + + # convert options['diff'] to absolute path + if 'diff' in self.options: + _, path = env.relfn2path(self.options['diff']) + self.options['diff'] = path - f = None try: - if not self.arguments[0] in cache: - f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2], - codec_info[3], 'strict') - lines = f.readlines() - cache[self.arguments[0]] = lines - else: - lines = cache[self.arguments[0]] + location = self.state_machine.get_source_and_line(self.lineno) + url = self.arguments[0] + + reader = OnlineIncludeReader(url, self.options, env.config) + text, lines = reader.read(location=location) + + retnode = nodes.literal_block(text, text, source=url) + set_source_info(self, retnode) + if self.options.get('diff'): # if diff is set, set udiff + retnode['language'] = 'udiff' + elif 'language' in self.options: + retnode['language'] = self.options['language'] + retnode['linenos'] = ('linenos' in self.options or + 'lineno-start' in self.options or + 'lineno-match' in self.options) + retnode['classes'] += self.options.get('class', []) + extra_args = retnode['highlight_args'] = {} + if 'emphasize-lines' in self.options: + hl_lines = parselinenos(self.options['emphasize-lines'], lines) + if any(i >= lines for i in hl_lines): + logger.warning('line number spec is out of range(1-%d): %r' % + (lines, self.options['emphasize-lines']), + location=location) + extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines] + extra_args['linenostart'] = reader.lineno_start + + if 'caption' in self.options: + caption = self.options['caption'] or self.arguments[0] + retnode = container_wrapper(self, retnode, caption) + + # retnode will be note_implicit_target that is linked from caption and numref. + # when options['name'] is provided, it should be primary ID. + self.add_name(retnode) + + return [retnode] + except Exception as exc: + return [document.reporter.warning(str(exc), line=self.lineno)] - lines = dedent_lines(lines, self.options.get('dedent')) - return lines - except (IOError, OSError, urllib2.URLError): - return [document.reporter.warning( - 'Include file %r not found or reading it failed' % self.arguments[0], - line=self.lineno)] - except UnicodeError: - return [document.reporter.warning( - 'Encoding %r used for reading included file %r seems to ' - 'be wrong, try giving an :encoding: option' % - (encoding, self.arguments[0]))] - finally: - if f is not None: - f.close() def visit_onlineinclude(translator, node): translator.visit_literal_block(node) @@ -53,4 +111,4 @@ def setup(app): app.add_directive("onlineinclude", OnlineIncludeDirective) handler = (visit_onlineinclude, depart_onlineinclude) - app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler) \ No newline at end of file + app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler) diff --git a/setup.py b/setup.py index 029ac10c4..c2e41193c 100644 --- a/setup.py +++ b/setup.py @@ -45,7 +45,8 @@ INSTALL_REQUIRES = [ "future>=0.15,<0.16", "scandir>=1.3,<1.4", "websocket-client>=0.40,<0.41", - "python-dateutil>=2.6,<2.7" + "python-dateutil>=2.6,<2.7", + "wrapt>=1.10.10,<1.11" ] if sys.platform == "darwin": @@ -61,9 +62,10 @@ EXTRA_REQUIRES = dict( "ddt", # Documentation dependencies - "sphinx>=1.3,<1.4", + "sphinx>=1.6,<1.7", "sphinxcontrib-httpdomain", - "sphinx_rtd_theme", + "sphinxcontrib-mermaid", + "sphinx_bootstrap_theme", # PyPi upload related "pypandoc" diff --git a/src/octoprint/events.py b/src/octoprint/events.py index c8630e59a..78d5f0ab0 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -84,6 +84,7 @@ class Events(object): EJECT = "Eject" E_STOP = "EStop" POSITION_UPDATE = "PositionUpdate" + TOOL_CHANGE = "ToolChange" REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" # Timelapse diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index a774cc378..33a7a2e8f 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -19,8 +19,6 @@ import time from octoprint.events import Events, eventManager from octoprint.settings import settings -import octoprint.util.gcodeInterpreter as gcodeInterpreter - class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")): """ @@ -305,39 +303,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): * The extruded volume in cm³ """ - def _do_analysis(self, high_priority=False): - try: - throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) - throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) - if throttle > 0: - def throttle_callback(filePos, readBytes): - if filePos % throttle_lines == 0: - # only apply throttle every 100 lines - time.sleep(throttle) - else: - throttle_callback = None + def __init__(self, finished_callback): + AbstractAnalysisQueue.__init__(self, finished_callback) - self._gcode = gcodeInterpreter.gcode() - self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback) + self._aborted = False + self._reenqueue = False + + def _do_analysis(self, high_priority=False): + import sarge + import sys + import yaml + + try: + throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \ + else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) + throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) + max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"]) + g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"]) + speedx = self._current.printer_profile["axes"]["x"]["speed"] + speedy = self._current.printer_profile["axes"]["y"]["speed"] + offsets = self._current.printer_profile["extruder"]["offsets"] + + interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py")) + command = [sys.executable, interpreter, "--speed-x={}".format(speedx), "--speed-y={}".format(speedy), + "--max-t={}".format(max_extruders), "--throttle={}".format(throttle), + "--throttle-lines={}".format(throttle_lines)] + for offset in offsets[1:]: + command += ["--offset", str(offset[0]), str(offset[1])] + if g90_extruder: + command += ["--g90-extruder"] + command.append(self._current.absolute_path) + + self._logger.info("Invoking analysis command: {}".format(" ".join(command))) + + self._aborted = False + p = sarge.run(command, async=True, stdout=sarge.Capture()) + + while len(p.commands) == 0: + # somewhat ugly... we can't use wait_events because + # the events might not be all set if an exception + # by sarge is triggered within the async process + # thread + time.sleep(0.01) + + # by now we should have a command, let's wait for its + # process to have been prepared + p.commands[0].process_ready.wait() + + if not p.commands[0].process: + # the process might have been set to None in case of any exception + raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command))) + + try: + # let's wait for stuff to finish + while p.returncode is None: + if self._aborted: + # oh, we shall abort, let's do so! + p.commands[0].terminate() + raise AnalysisAborted(reenqueue=self._reenqueue) + + # else continue + p.commands[0].poll() + finally: + p.close() + + output = p.stdout.text + self._logger.debug("Got output: {!r}".format(output)) + + if not "RESULTS:" in output: + raise RuntimeError("No analysis result found") + + _, output = output.split("RESULTS:") + analysis = yaml.safe_load(output) result = dict() - result["printingArea"] = self._gcode.printing_area - result["dimensions"] = self._gcode.dimensions - if self._gcode.totalMoveTimeMinute: - result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60 - if self._gcode.extrusionAmount: + result["printingArea"] = analysis["printing_area"] + result["dimensions"] = analysis["dimensions"] + if analysis["total_time"]: + result["estimatedPrintTime"] = analysis["total_time"] * 60 + if analysis["extrusion_length"]: result["filament"] = dict() - for i in range(len(self._gcode.extrusionAmount)): + for i in range(len(analysis["extrusion_length"])): result["filament"]["tool%d" % i] = { - "length": self._gcode.extrusionAmount[i], - "volume": self._gcode.extrusionVolume[i] + "length": analysis["extrusion_length"][i], + "volume": analysis["extrusion_volume"][i] } return result - except gcodeInterpreter.AnalysisAborted as ex: - raise AnalysisAborted(reenqueue=ex.reenqueue) finally: self._gcode = None def _do_abort(self, reenqueue=True): - if self._gcode: - self._gcode.abort(reenqueue=reenqueue) + self._aborted = True + self._reenqueue = reenqueue diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 57adfb2ed..d6214d626 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -104,7 +104,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en UiPlugin] if plugin_restart_needing_hooks is None: - plugin_restart_needing_hooks = ["octoprint.server.http"] + plugin_restart_needing_hooks = ["octoprint.server.http.*", + "octoprint.printer.factory"] if plugin_obsolete_hooks is None: plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] @@ -263,13 +264,17 @@ class PluginSettings(object): :returns: The retrieved settings value. :rtype: object - .. method:: get_int(path) + .. method:: get_int(path, min=None, max=None) - Like :func:`get` but tries to convert the retrieved value to ``int``. + Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if + the value is greater than it. - .. method:: get_float(path) + .. method:: get_float(path, min=None, max=None) - Like :func:`get` but tries to convert the retrieved value to ``float``. + Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if + the value is greater than it. .. method:: get_boolean(path) @@ -285,13 +290,19 @@ class PluginSettings(object): :param boolean force: If set to True, the modified configuration will even be written back to disk if the value didn't change. - .. method:: set_int(path, value, force=False) + .. method:: set_int(path, value, force=False, min=None, max=None) Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it. + If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal + to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than + that, ``max`` if greater than that) will be set instead. - .. method:: set_float(path, value, force=False) + .. method:: set_float(path, value, force=False, min=None, max=None) Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it. + If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal + to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than + that, ``max`` if greater than that) will be set instead. .. method:: set_boolean(path, value, force=False) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 4f98a29ab..76d092e78 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -31,6 +31,7 @@ import os import imp from collections import defaultdict, namedtuple, OrderedDict import logging +import fnmatch import pkg_resources import pkginfo @@ -946,45 +947,107 @@ class PluginManager(object): return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin) def has_restart_needing_implementation(self, plugin): - if not plugin.implementation: - return False - - return isinstance(plugin.implementation, RestartNeedingPlugin) + return self.has_any_of_mixins(plugin, RestartNeedingPlugin) def has_restart_needing_hooks(self, plugin): - if not plugin.hooks: - return False - - hooks = plugin.hooks.keys() - for hook in hooks: - if self.is_restart_needing_hook(hook): - return True - return False + return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks) def has_obsolete_hooks(self, plugin): - if not plugin.hooks: - return False - - hooks = plugin.hooks.keys() - for hook in hooks: - if self.is_obsolete_hook(hook): - return True - return False + return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks) def is_restart_needing_hook(self, hook): - if self.plugin_restart_needing_hooks is None: - return False - - for h in self.plugin_restart_needing_hooks: - if hook.startswith(h): - return True - - return False + return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks) def is_obsolete_hook(self, hook): - if self.plugin_obsolete_hooks is None: + return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks) + + @staticmethod + def has_any_of_hooks(plugin, *hooks): + """ + Tests if the ``plugin`` contains any of the provided ``hooks``. + + Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`. + + Args: + plugin: plugin to test hooks for + *hooks: hooks to test against + + Returns: + (bool): True if any of the plugin's hooks match the provided hooks, + False otherwise. + """ + + if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): + hooks = hooks[0] + + hooks = filter(lambda hook: hook is not None, hooks) + if not hooks: return False - return hook in self.plugin_obsolete_hooks + if not plugin or not plugin.hooks: + return False + + plugin_hooks = plugin.hooks.keys() + + return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks), + plugin_hooks)) + + @staticmethod + def hook_matches_hooks(hook, *hooks): + """ + Tests if ``hook`` matches any of the provided ``hooks`` to test for. + + ``hook`` is expected to be an exact hook name. + + ``hooks`` is expected to be a list containing one or more hook names or + patterns. That can be either an exact hook name or an + :func:`fnmatch.fnmatch` pattern. + + Args: + hook: the hook to test + hooks: the hook name patterns to test against + + Returns: + (bool): True if the ``hook`` matches any of the ``hooks``, False otherwise. + + """ + + if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): + hooks = hooks[0] + + hooks = filter(lambda hook: hook is not None, hooks) + if not hooks: + return False + if not hook: + return False + + return any(map(lambda h: fnmatch.fnmatch(hook, h), + hooks)) + + @staticmethod + def has_any_of_mixins(plugin, *mixins): + """ + Tests if the ``plugin`` has an implementation implementing any + of the provided ``mixins``. + + Args: + plugin: plugin for which to check the implementation + *mixins: mixins to test against + + Returns: + (bool): True if the plugin's implementation implements any of the + provided mixins, False otherwise. + """ + + if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): + mixins = mixins[0] + + mixins = filter(lambda mixin: mixin is not None, mixins) + if not mixins: + return False + if not plugin or not plugin.implementation: + return False + + return isinstance(plugin.implementation, tuple(mixins)) def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): for name, plugin in self.enabled_plugins.items(): diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 8edfdf20c..735b30dc7 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -743,7 +743,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value). Returns: - basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). + str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). """ return None diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 03b81a40c..9e5755802 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -5,6 +5,7 @@ __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" +from past.builtins import basestring import octoprint.plugin import octoprint.plugin.core @@ -44,7 +45,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, macos=["darwin"], freebsd=lambda x: x.startswith("freebsd")) - pip_inapplicable_arguments = dict(uninstall=["--user"]) + PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"]) + + RECONNECT_HOOKS = ["octoprint.comm.protocol.*",] def __init__(self): self._pending_enable = set() @@ -415,6 +418,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, source_type=source_type, needs_restart=True, needs_refresh=True, + needs_reconnect=True, was_reinstalled=False, plugin="unknown") self._send_result_notification("install", result) @@ -426,6 +430,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, or reinstall is not None needs_refresh = new_plugin.implementation \ and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational() is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled") self._plugin_manager.mark_plugin(new_plugin.key, @@ -440,6 +445,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, source_type=source_type, needs_restart=needs_restart, needs_refresh=needs_refresh, + needs_reconnect=needs_reconnect, was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None, plugin=self._to_external_plugin(new_plugin)) self._send_result_notification("install", result) @@ -496,6 +502,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) 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() was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed") self._plugin_manager.mark_plugin(plugin.key, @@ -521,7 +528,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.reload_plugins() - result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_plugin(plugin)) + result = dict(result=True, + needs_restart=needs_restart, + needs_refresh=needs_refresh, + needs_reconnect=needs_reconnect, + plugin=self._to_external_plugin(plugin)) self._send_result_notification("uninstall", result) return jsonify(result) @@ -531,11 +542,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) 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() pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable)) safe_mode_victim = getattr(plugin, "safe_mode_victim", False) needs_restart_api = (needs_restart or safe_mode_victim) and not pending needs_refresh_api = needs_refresh and not pending + needs_reconnect_api = needs_reconnect and not pending try: if command == "disable": @@ -549,11 +562,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, result = dict(result=True, needs_restart=True, needs_refresh=True, + needs_reconnect=True, plugin=self._to_external_plugin(plugin)) else: result = dict(result=True, needs_restart=needs_restart_api, needs_refresh=needs_refresh_api, + needs_reconnect=needs_reconnect_api, plugin=self._to_external_plugin(plugin)) self._send_result_notification(command, result) @@ -605,7 +620,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if additional_args is not None: - inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list()) + inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list()) for inapplicable_argument in inapplicable_arguments: additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args) @@ -881,6 +896,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint_version = pkg_resources.parse_version(octoprint_version.base_version) return octoprint_version + @property + def _reconnect_hooks(self): + reconnect_hooks = self.__class__.RECONNECT_HOOKS + + reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks") + for name, hook in reconnect_hook_provider_hooks.items(): + try: + result = hook() + if isinstance(result, (list, tuple)): + reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result)) + except: + self._logger.exception("Error while retrieving additional hooks for which a " + "reconnect is required from plugin {name}".format(**locals())) + + return reconnect_hooks + def _get_plugins(self): plugins = self._plugin_manager.plugins diff --git a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css index 65ae4796c..91383181e 100644 --- a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css +++ b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css @@ -1 +1 @@ -table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output span{display:block}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file +table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index d234e2ad3..5fb046186 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -663,7 +663,7 @@ $(function() { return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible")); }; - self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) { + self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) { var notification; var beforeClose = function(notification) { @@ -747,6 +747,15 @@ $(function() { }, hide: false }) + } else if (response.needs_reconnect) { + notification = new PNotify({ + title: titleSuccess, + text: textReconnect, + callbacks: { + before_close: beforeClose + }, + hide: false + }) } else { notification = new PNotify({ title: titleSuccess, @@ -1060,7 +1069,7 @@ $(function() { }); self._scrollWorkingOutputToEnd(); } else if (messageType == "result") { - var titleSuccess, textSuccess, textRestart, textReload, titleError, textError; + var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError; var action = data.action; var name = "Unknown"; @@ -1080,16 +1089,19 @@ $(function() { textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly"); textRestart = textSuccess; textReload = textSuccess; + textReconnect = textSuccess; } else if (data.was_reinstalled) { titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name}); textSuccess = gettext("The plugin was reinstalled successfully"); textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect."); } else { titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name}); textSuccess = gettext("The plugin was installed successfully"); textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect."); } titleError = gettext("Something went wrong"); @@ -1141,6 +1153,7 @@ $(function() { textSuccess = gettext("The plugin was uninstalled successfully"); textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1158,6 +1171,7 @@ $(function() { textSuccess = gettext("The plugin was enabled successfully."); textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1175,6 +1189,7 @@ $(function() { textSuccess = gettext("The plugin was disabled successfully."); textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1187,7 +1202,7 @@ $(function() { return; } - self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError); + self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError); self.requestData(); } }; diff --git a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less index cd49e51db..2b591e9cb 100644 --- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less +++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less @@ -85,10 +85,6 @@ table { } #settings_plugin_pluginmanager_workingdialog_output { - span { - display: block; - } - .message { font-weight: bold; } diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 61323ddeb..4931e698f 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -108,7 +108,7 @@

+
+ +
+ +
+
+
+ +
+ +
+
@@ -39,7 +51,7 @@
+ {{ _('This will only be executed when closing the connection actively. If the connection to the printer is suddenly lost nothing will be sent.') }}
- {{ _('This will only be executed when closing the connection actively. If the connection to the printer is suddenly lost nothing will be sent.') }}
diff --git a/src/octoprint/templates/dialogs/settings/temperatures.jinja2 b/src/octoprint/templates/dialogs/settings/temperatures.jinja2 index 5f4411a64..727eb0ed9 100644 --- a/src/octoprint/templates/dialogs/settings/temperatures.jinja2 +++ b/src/octoprint/templates/dialogs/settings/temperatures.jinja2 @@ -1,5 +1,5 @@
-

{{ _('Temperature Graph') }}

+

{{ _('Graph') }}

@@ -10,7 +10,26 @@ {{ _('Needs a restart of OctoPrint to become active.') }}
-

{{ _('Temperature Presets') }}

+

{{ _('Fine adjustments') }}

+
+
+ + {{ _('Enable this to have temperature fine adjustments you do via the + or - button be sent to the printer automatically.') }} +
+
+
+ +
+
+ + sec +
+ {{ _('OctoPrint will use this delay to limit the number of sent temperature commands should you perform multiple fine adjustments in a short time.') }} +
+
+

{{ _('Presets') }}

{{ _('Extruder') }}

{{ _('Bed') }}

diff --git a/src/octoprint/templates/dialogs/temperature.jinja2 b/src/octoprint/templates/dialogs/temperature.jinja2 new file mode 100644 index 000000000..78911009c --- /dev/null +++ b/src/octoprint/templates/dialogs/temperature.jinja2 @@ -0,0 +1,34 @@ + diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index d21075988..2065b505e 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -92,7 +92,7 @@ {% endfor %} -
+
{% for key in templates.tab.order %} {% set entry, data = templates.tab.entries[key] %} {% if "custom_bindings" not in data or data["custom_bindings"] %}{% endif %} @@ -131,6 +131,7 @@ {% include 'dialogs/wizard.jinja2' %} {% include 'dialogs/about.jinja2' %} {% include 'dialogs/files.jinja2' %} + {% include 'dialogs/temperature.jinja2' %} diff --git a/src/octoprint/templates/tabs/temperature.jinja2 b/src/octoprint/templates/tabs/temperature.jinja2 index 63b4a56f6..e6ee0ddb9 100644 --- a/src/octoprint/templates/tabs/temperature.jinja2 +++ b/src/octoprint/templates/tabs/temperature.jinja2 @@ -5,12 +5,12 @@ {% endif %}
- +
- - - - + + + + @@ -19,37 +19,45 @@
{{ _('Actual') }}{{ _('Target') }}{{ _('Offset') }}{{ _('Actual') }}{{ _('Target') }}{{ _('Offset') }}
+ diff --git a/src/octoprint/templates/tabs/terminal.jinja2 b/src/octoprint/templates/tabs/terminal.jinja2 index 4200d5cff..b1fd588f3 100644 --- a/src/octoprint/templates/tabs/terminal.jinja2 +++ b/src/octoprint/templates/tabs/terminal.jinja2 @@ -1,5 +1,5 @@
-
+
{{ _("Scroll to end") }} | {{ _("Select all") }} diff --git a/src/octoprint/users.py b/src/octoprint/users.py index 9630b750c..f2d3736b0 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -13,12 +13,14 @@ import os import yaml import uuid +import wrapt + import logging from builtins import range, bytes from octoprint.settings import settings -from octoprint.util import atomic_write, to_str +from octoprint.util import atomic_write, to_str, deprecated class UserManager(object): valid_roles = ["user", "admin"] @@ -58,13 +60,13 @@ class UserManager(object): if not isinstance(user, SessionUser): user = SessionUser(user) - self._session_users_by_session[user.get_session()] = user + self._session_users_by_session[user.session] = user userid = user.get_id() if not userid in self._sessionids_by_userid: self._sessionids_by_userid[userid] = set() - self._sessionids_by_userid[userid].add(user.get_session()) + self._sessionids_by_userid[userid].add(user.session) self._logger.debug("Logged in user: %r" % user) @@ -81,7 +83,7 @@ class UserManager(object): return userid = user.get_id() - sessionid = user.get_session() + sessionid = user.session if userid in self._sessionids_by_userid: try: @@ -99,7 +101,7 @@ class UserManager(object): for session, user in self._session_users_by_session.items(): if not isinstance(user, SessionUser): continue - if user._created + (24 * 60 * 60) < time.time(): + if user.created + (24 * 60 * 60) < time.time(): self.logout_user(user) @staticmethod @@ -591,37 +593,34 @@ class AnonymousUser(AnonymousUserMixin): return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: False) -class SessionUser(User): +class SessionUser(wrapt.ObjectProxy): def __init__(self, user): - self._user = user + wrapt.ObjectProxy.__init__(self, user) import string import random import time chars = string.ascii_uppercase + string.ascii_lowercase + string.digits - self._session = "".join(random.choice(chars) for _ in range(10)) - self._created = time.time() + self._self_session = "".join(random.choice(chars) for _ in range(10)) + self._self_created = time.time() - def __getattribute__(self, item): - if item in ("get_session", "update_user", "_user", "_session", "_created"): - return object.__getattribute__(self, item) - else: - return getattr(object.__getattribute__(self, "_user"), item) + @property + def session(self): + return self._self_session - def __setattr__(self, item, value): - if item in ("_user", "_session", "_created"): - return object.__setattr__(self, item, value) - else: - return setattr(self._user, item, value) + @property + def created(self): + return self._self_created + @deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5") def get_session(self): - return self._session + return self.session def update_user(self, user): - self._user = user + self.__wrapped__ = user def __repr__(self): - return "SessionUser(id=%s,name=%s,active=%r,user=%r,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), bool(self.is_user), bool(self.is_admin), self._session, self._created) + return "SessionUser({!r},session={},created={})".format(self.__wrapped__, self.session, self.created) ##~~ DummyUser object to use when accessControl is disabled diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index b2459a421..d43733ce2 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -174,8 +174,6 @@ def get_class(name): """ Retrieves the class object for a given fully qualified class name. - Taken from http://stackoverflow.com/a/452981/2028598. - Arguments: name (string): The fully qualified class name, including all modules separated by ``.`` @@ -183,15 +181,17 @@ def get_class(name): type: The class if it could be found. Raises: - AttributeError: The class could not be found. + ImportError """ - parts = name.split(".") - module = ".".join(parts[:-1]) - m = __import__(module) - for comp in parts[1:]: - m = getattr(m, comp) - return m + import importlib + + mod_name, cls_name = name.rsplit(".", 1) + m = importlib.import_module(mod_name) + try: + return getattr(m, cls_name) + except AttributeError: + raise ImportError("No module named " + name) def get_exception_string(): @@ -1046,19 +1046,58 @@ class InvariantContainer(object): return self._data.__iter__() -class TypedQueue(queue.Queue): +class PrependQueue(queue.Queue): def __init__(self, maxsize=0): queue.Queue.__init__(self, maxsize=maxsize) + + def prepend(self, item, block=True, timeout=True): + from time import time as _time + + self.not_full.acquire() + try: + if self.maxsize > 0: + if not block: + if self._qsize() == self.maxsize: + raise queue.Full + elif timeout is None: + while self._qsize() >= self.maxsize: + self.not_full.wait() + elif timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + else: + endtime = _time() + timeout + while self._qsize() == self.maxsize: + remaining = endtime - _time() + if remaining <= 0.0: + raise queue.Full + self.not_full.wait(remaining) + self._prepend(item) + self.unfinished_tasks += 1 + self.not_empty.notify() + finally: + self.not_full.release() + + def _prepend(self, item): + self.queue.appendleft(item) + + +class TypedQueue(PrependQueue): + + def __init__(self, maxsize=0): + PrependQueue.__init__(self, maxsize=maxsize) self._lookup = set() def put(self, item, item_type=None, *args, **kwargs): - queue.Queue.put(self, (item, item_type), *args, **kwargs) + PrependQueue.put(self, (item, item_type), *args, **kwargs) def get(self, *args, **kwargs): - item, _ = queue.Queue.get(self, *args, **kwargs) + item, _ = PrependQueue.get(self, *args, **kwargs) return item + def prepend(self, item, item_type=None, *args, **kwargs): + PrependQueue.prepend(self, (item, item_type), *args, **kwargs) + def _put(self, item): _, item_type = item if item_type is not None: @@ -1070,7 +1109,7 @@ class TypedQueue(queue.Queue): queue.Queue._put(self, item) def _get(self): - item = queue.Queue._get(self) + item = PrependQueue._get(self) _, item_type = item if item_type is not None: @@ -1078,6 +1117,15 @@ class TypedQueue(queue.Queue): return item + def _prepend(self, item): + _, item_type = 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) + + PrependQueue._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 84ed4a9b6..0c2288fec 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -19,6 +19,7 @@ from past.builtins import basestring import logging import serial + import octoprint.plugin from collections import deque @@ -242,6 +243,62 @@ class PositionRecord(object): t=self.t, f=self.f) +class TemperatureRecord(object): + def __init__(self): + self._tools = dict() + self._bed = (None, None) + + def copy_from(self, other): + self._tools = other.tools + self._bed = other.bed + + def set_tool(self, tool, actual=None, target=None): + current = self._tools.get(tool, (None, None)) + self._tools[tool] = self._to_new_tuple(current, actual, target) + + def set_bed(self, actual=None, target=None): + current = self._bed + self._bed = self._to_new_tuple(current, actual, target) + + @property + def tools(self): + return dict(self._tools) + + @property + def bed(self): + return self._bed + + def as_script_dict(self): + result = dict() + + tools = self.tools + for tool, data in tools.items(): + result[tool] = dict(actual=data[0], + target=data[1]) + + bed = self.bed + result["b"] = dict(actual=bed[0], + target=bed[1]) + + return result + + @classmethod + def _to_new_tuple(cls, current, actual, target): + if current is None or not isinstance(current, tuple) or len(current) != 2: + current = (None, None) + + if actual is None and target is None: + return current + + old_actual, old_target = current + + if actual is None: + return old_actual, target + elif target is None: + return actual, old_target + else: + return actual, target + class MachineCom(object): STATE_NONE = 0 STATE_OPEN_SERIAL = 1 @@ -281,8 +338,6 @@ class MachineCom(object): self._serial = None self._baudrateDetectList = baudrateList() self._baudrateDetectRetry = 0 - self._temp = {} - self._bedTemp = None self._temperatureTargetSetThreshold = 25 self._tempOffsets = dict() self._command_queue = TypedQueue() @@ -396,11 +451,16 @@ class MachineCom(object): self._ignore_select = False self._manualStreaming = False + self.last_temperature = TemperatureRecord() + self.pause_temperature = TemperatureRecord() + self.cancel_temperature = TemperatureRecord() + self.last_position = PositionRecord() self.pause_position = PositionRecord() - self._record_pause_position = False self.cancel_position = PositionRecord() - self._record_cancel_position = False + + self._record_pause_data = False + self._record_cancel_data = False # print job self._currentFile = None @@ -579,10 +639,10 @@ class MachineCom(object): return cleanedPrintTime def getTemp(self): - return self._temp + return self.last_temperature.tools def getBedTemp(self): - return self._bedTemp + return self.last_temperature.bed def getOffsets(self): return dict(self._tempOffsets) @@ -695,31 +755,29 @@ class MachineCom(object): elif self.isOperational() or force: return self._sendCommand(cmd, cmd_type=cmd_type, on_sent=on_sent) - def sendGcodeScript(self, scriptName, replacements=None): + def _getGcodeScript(self, scriptName, replacements=None): context = dict() if replacements is not None and isinstance(replacements, dict): context.update(replacements) + context.update(dict( printer_profile=self._printerProfileManager.get_current_or_default(), - last_position=self.last_position + last_position=self.last_position, + last_temperature=self.last_temperature.as_script_dict() )) if scriptName == "afterPrintPaused" or scriptName == "beforePrintResumed": - context.update(dict(pause_position=self.pause_position)) + context.update(dict(pause_position=self.pause_position, + pause_temperature=self.pause_temperature.as_script_dict())) elif scriptName == "afterPrintCancelled": - context.update(dict(cancel_position=self.cancel_position)) + context.update(dict(cancel_position=self.cancel_position, + cancel_temperature=self.cancel_temperature.as_script_dict())) template = settings().loadScript("gcode", scriptName, context=context) if template is None: scriptLines = [] else: - scriptLines = filter( - lambda x: x is not None and x.strip() != "", - map( - lambda x: process_gcode_line(x, offsets=self._tempOffsets, current_tool=self._currentTool), - template.split("\n") - ) - ) + scriptLines = template.split("\n") for hook in self._gcodescript_hooks: try: @@ -749,6 +807,13 @@ class MachineCom(object): if suffix: scriptLines += list(suffix) + return filter(lambda x: x is not None and x.strip() != "", + map(lambda x: process_gcode_line(x, offsets=self._tempOffsets, current_tool=self._currentTool), + scriptLines)) + + + def sendGcodeScript(self, scriptName, replacements=None): + scriptLines = self._getGcodeScript(scriptName, replacements=replacements) for line in scriptLines: self.sendCommand(line) return "\n".join(scriptLines) @@ -864,7 +929,7 @@ class MachineCom(object): # we don't call on_print_job_cancelled on our callback here # because we do this only after our M114 has been answered # by the firmware - self._record_cancel_position = True + self._record_cancel_data = True self.sendCommand("M114") with self._jobLock: @@ -924,7 +989,7 @@ class MachineCom(object): # we don't call on_print_job_paused on our callback here # because we do this only after our M114 has been answered # by the firmware - self._record_pause_position = True + self._record_pause_data = True self.sendCommand("M114") self.sendCommand("M400", on_sent=_on_M400_sent) @@ -1025,24 +1090,12 @@ class MachineCom(object): continue actual, target = parsedTemps[tool] - if target is not None: - self._temp[n] = (actual, target) - elif n in self._temp and self._temp[n] is not None and isinstance(self._temp[n], tuple): - (oldActual, oldTarget) = self._temp[n] - self._temp[n] = (actual, oldTarget) - else: - self._temp[n] = (actual, None) + self.last_temperature.set_tool(n, actual=actual, target=target) # bed temperature if "B" in parsedTemps.keys(): actual, target = parsedTemps["B"] - if target is not None: - self._bedTemp = (actual, target) - elif self._bedTemp is not None and isinstance(self._bedTemp, tuple): - (oldActual, oldTarget) = self._bedTemp - self._bedTemp = (actual, oldTarget) - else: - self._bedTemp = (actual, None) + self.last_temperature.set_bed(actual=actual, target=target) ##~~ Serial monitor processing received messages @@ -1205,16 +1258,18 @@ class MachineCom(object): reason = None - if self._record_pause_position: + if self._record_pause_data: reason = "pause" - self._record_pause_position = False + self._record_pause_data = False self.pause_position.copy_from(self.last_position) + self.pause_temperature.copy_from(self.last_temperature) self._pause_preparation_done() - if self._record_cancel_position: + if self._record_cancel_data: reason = "cancel" - self._record_cancel_position = False + self._record_cancel_data = False self.cancel_position.copy_from(self.last_position) + self.cancel_temperature.copy_from(self.last_temperature) self._cancel_preparation_done() self._callback.on_comm_position_update(self.last_position.as_dict(), reason=reason) @@ -1231,7 +1286,7 @@ class MachineCom(object): self._heatupWaitStartTime = time.time() self._processTemperatures(line) - self._callback.on_comm_temperature_update(self._temp, self._bedTemp) + self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed) elif supportRepetierTargetTemp and ('TargetExtr' in line or 'TargetBed' in line): matchExtr = regex_repetierTempExtr.match(line) @@ -1241,23 +1296,15 @@ class MachineCom(object): toolNum = int(matchExtr.group(1)) try: target = float(matchExtr.group(2)) - if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple): - (actual, oldTarget) = self._temp[toolNum] - self._temp[toolNum] = (actual, target) - else: - self._temp[toolNum] = (None, target) - self._callback.on_comm_temperature_update(self._temp, self._bedTemp) + self.last_temperature.set_tool(toolNum, target=target) + self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed) except ValueError: pass elif matchBed is not None: try: target = float(matchBed.group(1)) - if self._bedTemp is not None and isinstance(self._bedTemp, tuple): - (actual, oldTarget) = self._bedTemp - self._bedTemp = (actual, target) - else: - self._bedTemp = (None, target) - self._callback.on_comm_temperature_update(self._temp, self._bedTemp) + self.last_temperature.set_bed(target=target) + self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed) except ValueError: pass @@ -1285,7 +1332,7 @@ class MachineCom(object): firmware_name = firmware_name.strip() self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name)) - if "repetier" in firmware_name.lower(): + if "repetier" in firmware_name.lower() or "anet_a8" in firmware_name.lower(): self._logger.info("Detected Repetier firmware, enabling relevant features for issue free communication") self._alwaysSendChecksum = True @@ -1692,11 +1739,13 @@ class MachineCom(object): if self.isBusy(): return self._timeout_intervals.get("temperature", busy_default) - for temp in [self._temp[k][1] for k in self._temp.keys()]: + tools = self.last_temperature.tools + for temp in [tools[k][1] for k in tools.keys()]: if temp > self._temperatureTargetSetThreshold: return self._timeout_intervals.get("temperatureTargetSet", target_default) - if self._bedTemp and len(self._bedTemp) > 0 and self._bedTemp[1] > self._temperatureTargetSetThreshold: + bed = self.last_temperature.bed + if bed and len(bed) > 0 and bed[1] > self._temperatureTargetSetThreshold: return self._timeout_intervals.get("temperatureTargetSet", target_default) return self._timeout_intervals.get("temperature", busy_default) @@ -2120,16 +2169,19 @@ class MachineCom(object): def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None): """ - Enqueues a command an optional linenumber to use for it in the send queue. + Enqueues a command and optional linenumber to use for it in the send queue. Arguments: command (str): The command to send. linenumber (int): The line number with which to send the command. May be ``None`` in which case the command will be sent without a line number and checksum. + command_type (str): Optional command type, if set and command type is already in the queue the + command won't be enqueued + on_sent (callable): Optional callable to call after command has been sent to printer. """ try: - self._send_queue.put((command, linenumber, command_type, on_sent), item_type=command_type) + self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type) return True except TypeAlreadyInQueue as e: self._logger.debug("Type already in send queue: " + e.type) @@ -2160,7 +2212,7 @@ class MachineCom(object): self._dwelling_until = False # fetch command, command type and optional linenumber and sent callback from queue - command, linenumber, command_type, on_sent = entry + command, linenumber, command_type, on_sent, processed = entry # 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 @@ -2173,28 +2225,35 @@ class MachineCom(object): self._do_send_with_checksum(command, linenumber) else: - # trigger "sending" phase - results = self._process_command_phase("sending", command, command_type, gcode=gcode) + if not processed: + # trigger "sending" phase if we didn't so far + results = self._process_command_phase("sending", command, command_type, gcode=gcode) - if not results: - # No, we are not going to send this, that was a last-minute bail. - # However, since we already are in the send queue, our _monitor - # loop won't be triggered with the reply from this unsent command - # now, so we try to tickle the processing of any active - # command queues manually - self._continue_sending() + if not results: + # No, we are not going to send this, that was a last-minute bail. + # However, since we already are in the send queue, our _monitor + # loop won't be triggered with the reply from this unsent command + # now, so we try to tickle the processing of any active + # command queues manually + self._continue_sending() - # and now let's fetch the next item from the queue - continue + # and now let's fetch the next item from the queue + continue - # we explicitly throw away plugin hook results that try - # to perform command expansion in the sending/sent phase, - # so "results" really should only have more than one entry - # at this point if our core code contains a bug - assert len(results) == 1 + 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 - # we only use the first (and only!) entry here - command, _, gcode = results[0] + # 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 = results[0] if command.strip() == "": self._logger.info("Refusing to send an empty line to the printer") @@ -2268,13 +2327,7 @@ class MachineCom(object): 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) - - # make sure we don't allow multi entry results in anything but the queuing phase - if not phase in ("queuing",) and len(normalized) > 1: - self._logger.error("Error while processing hook {name} for phase {phase} and command {command}: Hook returned multi-entry result for phase {phase} and command {command}. That's not supported, if you need to do multi expansion of commands you need to do this in the queuing phase. Ignoring hook result and sending command as-is.".format(**locals())) - new_results.append((command, command_type, gcode)) - else: - new_results += normalized + 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 return [] @@ -2392,10 +2445,23 @@ class MachineCom(object): ##~~ command handlers + def _gcode_T_queuing(self, cmd, cmd_type=None): + toolMatch = regexes_parameters["intT"].search(cmd) + if toolMatch: + current_tool = self._currentTool + new_tool = int(toolMatch.group("value")) + + before = self._getGcodeScript("beforeToolChange", replacements=dict(tool=dict(old=current_tool, new=new_tool))) + after = self._getGcodeScript("afterToolChange", replacements=dict(tool=dict(old=current_tool, new=new_tool))) + + return before + [cmd] + after + def _gcode_T_sent(self, cmd, cmd_type=None): 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): if "Z" in cmd or "F" in cmd: @@ -2475,12 +2541,8 @@ class MachineCom(object): if match: try: target = float(match.group("value")) - if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple): - (actual, oldTarget) = self._temp[toolNum] - self._temp[toolNum] = (actual, target) - else: - self._temp[toolNum] = (None, target) - self._callback.on_comm_temperature_update(self._temp, self._bedTemp) + self.last_temperature.set_tool(toolNum, target=target) + self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed) except ValueError: pass @@ -2492,12 +2554,8 @@ class MachineCom(object): if match: try: target = float(match.group("value")) - if self._bedTemp is not None and isinstance(self._bedTemp, tuple): - (actual, oldTarget) = self._bedTemp - self._bedTemp = (actual, target) - else: - self._bedTemp = (None, target) - self._callback.on_comm_temperature_update(self._temp, self._bedTemp) + self.last_temperature.set_bed(target=target) + self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed) except ValueError: pass diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index 8f2a26b5d..ea6d291a6 100644 --- a/src/octoprint/util/gcodeInterpreter.py +++ b/src/octoprint/util/gcodeInterpreter.py @@ -10,8 +10,7 @@ import os import base64 import zlib import logging - -from octoprint.settings import settings +import codecs class Vector3D(object): @@ -178,18 +177,18 @@ class AnalysisAborted(Exception): class gcode(object): - def __init__(self): + def __init__(self, progress_callback=None): self._logger = logging.getLogger(__name__) self.layerList = None self.extrusionAmount = [0] self.extrusionVolume = [0] self.totalMoveTimeMinute = 0 self.filename = None - self.progressCallback = None self._abort = False self._reenqueue = True self._filamentDiameter = 0 self._minMax = MinMax3D() + self._progress_callback = progress_callback @property def dimensions(self): @@ -207,20 +206,19 @@ class gcode(object): maxY=self._minMax.max.y, maxZ=self._minMax.max.z) - def load(self, filename, printer_profile, throttle=None): + def load(self, filename, throttle=None, speedx=6000, speedy=6000, offsets=None, max_extruders=10, g90_extruder=False): if os.path.isfile(filename): self.filename = filename self._fileSize = os.stat(filename).st_size - import codecs with codecs.open(filename, encoding="utf-8", errors="replace") as f: - self._load(f, printer_profile, throttle=throttle) + self._load(f, throttle=throttle, speedx=speedx, speedy=speedy, offsets=offsets, max_extruders=max_extruders, g90_extruder=g90_extruder) def abort(self, reenqueue=True): self._abort = True self._reenqueue = reenqueue - def _load(self, gcodeFile, printer_profile, throttle=None): + def _load(self, gcodeFile, throttle=None, speedx=6000, speedy=6000, offsets=None, max_extruders=10, g90_extruder=False): lineNo = 0 readBytes = 0 pos = Vector3D(0.0, 0.0, 0.0) @@ -236,21 +234,23 @@ class gcode(object): fwretractTime = 0 fwretractDist = 0 fwrecoverTime = 0 - feedrate = min(printer_profile["axes"]["x"]["speed"], printer_profile["axes"]["y"]["speed"]) + feedrate = min(speedx, speedy) if feedrate == 0: # some somewhat sane default if axes speeds are insane... feedrate = 2000 - offsets = printer_profile["extruder"]["offsets"] - g90InfluencesExtruder = settings().getBoolean(["feature", "g90InfluencesExtruder"]) + if offsets is None or not isinstance(offsets, (list, tuple)): + offsets = [] + if len(offsets) < max_extruders: + offsets += [(0, 0)] * (max_extruders - len(offsets)) for line in gcodeFile: if self._abort: raise AnalysisAborted(reenqueue=self._reenqueue) lineNo += 1 - readBytes += len(line) + readBytes += len(line.encode("utf-8")) - if isinstance(gcodeFile, (file)): + if isinstance(gcodeFile, (file, codecs.StreamReaderWriter)): percentage = float(readBytes) / float(self._fileSize) elif isinstance(gcodeFile, (list)): percentage = float(lineNo) / float(len(gcodeFile)) @@ -258,8 +258,8 @@ class gcode(object): percentage = None try: - if self.progressCallback is not None and (lineNo % 1000 == 0) and percentage is not None: - self.progressCallback(percentage) + if self._progress_callback is not None and (lineNo % 1000 == 0) and percentage is not None: + self._progress_callback(percentage) except: pass @@ -395,11 +395,11 @@ class gcode(object): pos.z = center.z elif G == 90: #Absolute position relativeMode = False - if g90InfluencesExtruder: + if g90_extruder: relativeE = False elif G == 91: #Relative position relativeMode = True - if g90InfluencesExtruder: + if g90_extruder: relativeE = True elif G == 92: x = getCodeFloat(line, 'X') @@ -440,7 +440,7 @@ class gcode(object): fwrecoverTime = (fwretractDist + s) / f elif T is not None: - if T > settings().getInt(["gcodeAnalysis", "maxExtruders"]): + if T > max_extruders: self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T) else: toolOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0 @@ -463,8 +463,8 @@ class gcode(object): if throttle is not None: throttle(lineNo, readBytes) - if self.progressCallback is not None: - self.progressCallback(100.0) + if self._progress_callback is not None: + self._progress_callback(100.0) self.extrusionAmount = maxExtrusion self.extrusionVolume = [0] * len(maxExtrusion) @@ -476,6 +476,13 @@ class gcode(object): def _parseCuraProfileString(self, comment, prefix): return {key: value for (key, value) in map(lambda x: x.split("=", 1), zlib.decompress(base64.b64decode(comment[len(prefix):])).split("\b"))} + def get_result(self): + return dict(total_time=self.totalMoveTimeMinute, + extrusion_length=self.extrusionAmount, + extrusion_volume=self.extrusionVolume, + dimensions=self.dimensions, + printing_area=self.printing_area) + def getCodeInt(line, code): n = line.find(code) + 1 if n < 1: @@ -503,3 +510,86 @@ def getCodeFloat(line, code): return val if not (math.isnan(val) or math.isinf(val)) else None except: return None + +if __name__ == "__main__": + import click + import time + import yaml + import sys + + @click.command() + @click.option("--throttle", "throttle", type=float, default=None) + @click.option("--throttle-lines", "throttle_lines", type=int, default=None) + @click.option("--speed-x", "speedx", type=float, default=6000) + @click.option("--speed-y", "speedy", type=float, default=6000) + @click.option("--speed-z", "speedz", type=float, default=300) + @click.option("--offset", "offset", type=(float, float), multiple=True) + @click.option("--max-t", "maxt", type=int, default=10) + @click.option("--g90-extruder", "g90_extruder", is_flag=True) + @click.option("--progress", "progress", is_flag=True) + @click.argument("path", type=click.Path()) + def main(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress): + throttle_callback = None + if throttle: + def throttle_callback(filePos, readBytes): + if filePos % throttle_lines == 0: + # only apply throttle every $throttle_lines lines + time.sleep(throttle) + + offsets = offset + if offsets is None: + offsets = [] + elif isinstance(offset, tuple): + offsets = list(offsets) + offsets = [(0, 0)] + offsets + if len(offsets) < maxt: + offsets += [(0, 0)] * (maxt - len(offsets)) + + start_time = time.time() + + progress_callback = None + if progress: + def progress_callback(percentage): + print("PROGRESS:{}".format(percentage)) + interpreter = gcode(progress_callback=progress_callback) + + interpreter.load(path, + speedx=speedx, + speedy=speedy, + offsets=offsets, + throttle=throttle_callback, + max_extruders=maxt, + g90_extruder=g90_extruder) + + print("DONE:{}s".format(time.time() - start_time)) + print("RESULTS:") + print(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True)) + + # os args are gained differently on win32 + try: + from click.utils import get_os_args + args = get_os_args() + except ImportError: + # for whatever reason we are running an older Click version? + args = sys.argv[1:] + + if len(args) >= len(sys.argv): + # Now some ugly preprocessing of our arguments starts. We have a somewhat difficult situation on our hands + # here if we are running under Windows and want to be able to handle utf-8 command line parameters (think + # plugin parameters such as names or something, e.g. for the "dev plugin:new" command) while at the same + # time also supporting sys.argv rewriting for debuggers etc (e.g. PyCharm). + # + # So what we try to do here is solve this... Generally speaking, sys.argv and whatever Windows returns + # for its CommandLineToArgvW win32 function should have the same length. If it doesn't however and + # sys.argv is shorter than the win32 specific command line arguments, obviously stuff was cut off from + # sys.argv which also needs to be cut off of the win32 command line arguments. + # + # So this is what we do here. + + # -1 because first entry is the script that was called + sys_args_length = len(sys.argv) - 1 + + # cut off stuff from the beginning + args = args[-1 * sys_args_length:] if sys_args_length else [] + + main(args=args, prog_name="octoprint-gcode-analysis") diff --git a/tests/plugin/test_core.py b/tests/plugin/test_core.py index 07da519ba..cb25a4bdd 100644 --- a/tests/plugin/test_core.py +++ b/tests/plugin/test_core.py @@ -1,10 +1,11 @@ import unittest import mock +import ddt import octoprint.plugin import octoprint.plugin.core - +@ddt.ddt class PluginTestCase(unittest.TestCase): def setUp(self): @@ -191,3 +192,85 @@ class PluginTestCase(unittest.TestCase): plugin = self.plugin_manager.enabled_plugins["deprecated_plugin"] self.assertTrue(hasattr(plugin.instance, plugin.__class__.attr_implementation)) self.assertFalse(hasattr(plugin.instance, plugin.__class__.attr_implementations)) + + @ddt.data( + (["octoprint.some_hook"], ["octoprint.some_hook", "octoprint.another_hook"], True), + (["octoprint.*"], ["octoprint.some_hook", "octoprint.another_hook"], True), + (["octoprint.some_hook"], ["octoprint.another_hook"], False), + (["octoprint.some_hook"], [], False), + ([], ["octoprint.some_hook"], False) + ) + @ddt.unpack + def test_has_any_of_hooks(self, hooks_to_test_for, plugin_hooks, expected): + plugin = mock.MagicMock() + plugin.hooks = dict((hook, hook) for hook in plugin_hooks) + + actual = octoprint.plugin.core.PluginManager.has_any_of_hooks(plugin, hooks_to_test_for) + self.assertEqual(actual, expected) + + def test_has_any_of_hooks_varargs(self): + plugin = mock.MagicMock() + plugin.hooks = dict((hook, hook) for hook in ["octoprint.some_hook", "octoprint.another_hook"]) + + result = octoprint.plugin.core.PluginManager.has_any_of_hooks(plugin, "octoprint.some_hook", "octoprint.some_other_hook") + self.assertTrue(result) + + def test_has_any_of_hooks_nohooks(self): + plugin = mock.MagicMock() + + result = octoprint.plugin.core.PluginManager.has_any_of_hooks(plugin, "octoprint.some_hook", "octoprint.some_other_hook") + self.assertFalse(result) + + @ddt.data( + ("octoprint.some_hook", ["octoprint.another_hook", "octoprint.some_hook"], True), + ("octoprint.some_hook", ["octoprint.*"], True), + ("octoprint.some_hook", ["octoprint.some_hook*"], True), + ("octoprint.some_hook", ["octoprint.*_hook"], True), + ("octoprint.some_hook", ["octoprint.another_hook.*"], False), + ("", ["octoprint.some_hook"], False), + (None, ["octoprint.some_hook"], False), + ("octoprint.some_hook", [], False), + ("octoprint.some_hook", None, False), + ("octoprint.some_hook", [None], False) + ) + @ddt.unpack + def test_hook_matches_hooks(self, hook, hooks, expected): + actual = octoprint.plugin.core.PluginManager.hook_matches_hooks(hook, hooks) + self.assertEqual(actual, expected) + + def test_hook_matches_hooks_varargs(self): + result = octoprint.plugin.core.PluginManager.hook_matches_hooks("octoprint.some_hook", + "octoprint.another_hook", "octoprint.some_hook") + self.assertTrue(result) + + @ddt.data( + ([octoprint.plugin.RestartNeedingPlugin], [octoprint.plugin.Plugin, octoprint.plugin.RestartNeedingPlugin], True), + ([octoprint.plugin.RestartNeedingPlugin], [octoprint.plugin.Plugin], False), + ([], [octoprint.plugin.Plugin], False), + ([octoprint.plugin.RestartNeedingPlugin], [], False) + ) + @ddt.unpack + def test_has_any_of_mixins(self, mixins_to_test_for, plugin_mixins, expected): + plugin = mock.MagicMock() + plugin.implementation = mock.MagicMock() + + for mixin in plugin_mixins: + plugin.implementation.mock_add_spec(mixin) + + actual = octoprint.plugin.core.PluginManager.has_any_of_mixins(plugin, mixins_to_test_for) + self.assertEqual(actual, expected) + + def test_has_any_of_mixins_varargs(self): + plugin = mock.MagicMock() + plugin.implementation = mock.MagicMock() + plugin.implementation.mock_add_spec(octoprint.plugin.Plugin) + plugin.implementation.mock_add_spec(octoprint.plugin.RestartNeedingPlugin) + + result = octoprint.plugin.core.PluginManager.has_any_of_mixins(plugin, octoprint.plugin.RestartNeedingPlugin) + self.assertTrue(result) + + def test_has_any_of_mixins_noimplementation(self): + plugin = mock.MagicMock() + + result = octoprint.plugin.core.PluginManager.has_any_of_mixins(plugin, octoprint.plugin.RestartNeedingPlugin) + self.assertFalse(result) diff --git a/tests/users/test_sessionuser.py b/tests/users/test_sessionuser.py index 1096476e4..e5f0f81ca 100644 --- a/tests/users/test_sessionuser.py +++ b/tests/users/test_sessionuser.py @@ -21,17 +21,36 @@ class SessionUserTestCase(unittest.TestCase): session1 = octoprint.users.SessionUser(self.user) session2 = octoprint.users.SessionUser(self.user) - self.assertNotEqual(session1.get_session(), session2.get_session()) - self.assertEqual(session1._user, session2._user) - self.assertEqual(session1._username, session2._username) + # session should be different, wrapped object should be identical + self.assertNotEqual(session1.session, session2.session) + self.assertEqual(session1.__wrapped__, session2.__wrapped__) + self.assertEqual(session1.get_name(), session2.get_name()) def test_settings_change_propagates(self): - user = octoprint.users.SessionUser(self.user) - self.user.set_setting("otherkey", "othervalue") + session1 = octoprint.users.SessionUser(self.user) + session2 = octoprint.users.SessionUser(self.user) - self.assertDictEqual(dict(key="value", otherkey="othervalue"), user.get_all_settings()) + # change should propagate from User to SessionUser + self.user.set_setting("otherkey", "othervalue") + self.assertDictEqual(dict(key="value", otherkey="othervalue"), session1.get_all_settings()) + + # change should propagate from SessionUser to SessionUser + session2.set_setting("otherkey", "yetanothervalue") + self.assertDictEqual(dict(key="value", otherkey="yetanothervalue"), session1.get_all_settings()) def test_repr(self): user = octoprint.users.SessionUser(self.user) - expected = "SessionUser(id=username,name=username,active=True,user=True,admin=False,session={},created={})".format(user._session, user._created) + expected = "SessionUser({!r},session={},created={})".format(self.user, user.session, user.created) self.assertEqual(expected, repr(user)) + + def test_isinstance(self): + session = octoprint.users.SessionUser(self.user) + + # needs to be detected as User instance + self.assertTrue(isinstance(session, octoprint.users.User)) + + # also needs to be detected as SessionUser instance + self.assertTrue(isinstance(session, octoprint.users.SessionUser)) + + # but wrapped user should NOT be detected as SessionUser instance of course + self.assertFalse(isinstance(self.user, octoprint.users.SessionUser)) diff --git a/tests/util/test_misc.py b/tests/util/test_misc.py new file mode 100644 index 000000000..644654b76 --- /dev/null +++ b/tests/util/test_misc.py @@ -0,0 +1,31 @@ +# coding=utf-8 +from __future__ import absolute_import + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import unittest + +import octoprint.util + +class MiscTestCase(unittest.TestCase): + + def test_get_class(self): + octoprint.util.get_class("octoprint.users.FilebasedUserManager") + + def test_get_class_wrongmodule(self): + try: + octoprint.util.get_class("octoprint2.users.FilebasedUserManager") + self.fail("This should have thrown an ImportError") + except ImportError: + # success + pass + + def test_get_class_wrongclass(self): + try: + octoprint.util.get_class("octoprint.users.FilebasedUserManagerBzzztWrong") + self.fail("This should have thrown an ImportError") + except ImportError: + # success + pass