Merge branch 'devel' into commRefactoring
This commit is contained in:
commit
a47740ae28
46 files changed
+4597
-188
No files matched your search
@@ -1,30 +1,47 @@
|
||||
# OctoPrint Release Notes
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.2.0 (In Development)
|
||||
## 1.2.0 (Unreleased)
|
||||
|
||||
### New Features
|
||||
|
||||
* Added internationalization of UI. Translations of OctoPrint are being crowd sourced via [Transifex](https://www.transifex.com/projects/p/octoprint/).
|
||||
The following translations are already available with more in the works:
|
||||
- Dutch (nl)
|
||||
- German (de)
|
||||
- French (fr)
|
||||
- Hebrew (he)
|
||||
- Norwegian (no)
|
||||
- Romanian (ro)
|
||||
* New file list: Pagination is gone, no more (mobile incompatible) pop overs, instead scrollable and with instant
|
||||
search
|
||||
* You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing
|
||||
support is enabled -- STL) files to automatically add.
|
||||
* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its
|
||||
core functionality.
|
||||
|
||||
### Improvements
|
||||
|
||||
* Logging is now configurable via config file
|
||||
* Added last print time to additional GCODE file information
|
||||
* Better error handling for capture issues during timelapse creation & more robust handling of missing images during
|
||||
timelapse creation
|
||||
* Start counting the layers at 1 instead of 0 in the GCODE viewer
|
||||
* Upgraded [Font Awesome](https://fortawesome.github.io/Font-Awesome/) to version 3.2.1
|
||||
* Better error reporting for timelapse rendering and system commands
|
||||
* Supports
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#435](https://github.com/foosel/OctoPrint/issues/435) - Always interpret negative duration (e.g. for print time left)
|
||||
as 0
|
||||
|
||||
## 1.1.1 (Unreleased)
|
||||
|
||||
## 1.1.0
|
||||
### Bug Fixes
|
||||
|
||||
* [#580](https://github.com/foosel/OctoPrint/issues/580) - Properly unset job data when instructed so by callers
|
||||
|
||||
## 1.1.0 (2014-09-03)
|
||||
|
||||
### New Features
|
||||
|
||||
@@ -52,7 +69,9 @@
|
||||
* Support for circular beds in the GCODE viewer ([#407](https://github.com/foosel/OctoPrint/pull/407))
|
||||
* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396))
|
||||
* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360))
|
||||
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/).
|
||||
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/). Version number,
|
||||
git commit and branch get reported in the format `<version tag>-<commits since then>-g<commit hash> (<branch> branch)`,
|
||||
e.g. `1.2.0-dev-172-ga48b5de (devel branch)`.
|
||||
* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if
|
||||
viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398))
|
||||
* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431))
|
||||
@@ -92,6 +111,6 @@
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0))
|
||||
|
||||
## 1.0.0
|
||||
## 1.0.0 (2014-06-22)
|
||||
|
||||
First release with new versioning scheme.
|
||||
@@ -18,4 +18,5 @@ Contents
|
||||
|
||||
api/index.rst
|
||||
events/index.rst
|
||||
plugins/index.rst
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
.. _sec-plugins:
|
||||
|
||||
#####################
|
||||
Plugins Documentation
|
||||
#####################
|
||||
|
||||
.. contents::
|
||||
|
||||
Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually
|
||||
extend OctoPrint's functionality.
|
||||
|
||||
Right now plugins can be used to extend OctoPrint's settings dialog, to execute specific tasks on server startup and
|
||||
shutdown or to provide custom (API) endpoints with special functionality. More plugin types are planned for the future.
|
||||
|
||||
.. _sec-plugins-installation:
|
||||
|
||||
Installing Plugins
|
||||
==================
|
||||
|
||||
Plugins can be installed either by unpacking them into one of the configured plugin folders (regularly those are
|
||||
``<octoprint-root>/plugins`` and ``~/.octoprint/plugins`` or by installing them as regular python modules via ``pip``.
|
||||
Please refer to the documentation of the plugin for installations instructions.
|
||||
|
||||
The latter is the more common case since all currently published plugins not bundled with OctoPrint can and should be installed
|
||||
this way.
|
||||
|
||||
For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install <plugin_name>
|
||||
|
||||
For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to
|
||||
a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip
|
||||
|
||||
See `the pip install documentation <http://pip.readthedocs.org/en/latest/reference/pip_install.html>`_ for what URL
|
||||
types are possible.
|
||||
|
||||
.. _sec-plugins-available:
|
||||
|
||||
Available Plugins
|
||||
=================
|
||||
|
||||
Currently there's no such thing as a centralized plugin repository for available plugins.
|
||||
|
||||
Plugins may be found in the lists provided in `the OctoPrint wiki <https://github.com/foosel/OctoPrint/wiki#plugins>`_
|
||||
and on the `OctoPrint organization Github page <https://github.com/OctoPrint>`_.
|
||||
|
||||
.. _sec-plugins-developing:
|
||||
|
||||
Developing Plugins
|
||||
==================
|
||||
|
||||
.. todo::
|
||||
|
||||
A section on how to develop plugins yourself, including a tutorial creating an exemplatory plugin as well as
|
||||
a documentation of the plugin API, will be added in the near future.
|
||||
@@ -10,3 +10,4 @@ pyserial
|
||||
netaddr
|
||||
watchdog
|
||||
sarge
|
||||
netifaces
|
||||
@@ -220,7 +220,7 @@ def params():
|
||||
|
||||
packages = find_packages(where="src")
|
||||
package_dir = {"octoprint": "src/octoprint"}
|
||||
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates'])}
|
||||
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates', 'plugins'])}
|
||||
|
||||
include_package_data = True
|
||||
zip_safe = False
|
||||
|
||||
+16
-16
@@ -1,21 +1,28 @@
|
||||
# coding=utf-8
|
||||
from __future__ import (print_function, absolute_import)
|
||||
|
||||
__author__ = "Lars Norpchen"
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import subprocess
|
||||
import Queue
|
||||
import threading
|
||||
import collections
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.plugin
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
|
||||
|
||||
def all_events():
|
||||
return [name for name in Events.__dict__ if not name.startswith("__")]
|
||||
|
||||
|
||||
class Events(object):
|
||||
# application startup
|
||||
STARTUP = "Startup"
|
||||
@@ -87,7 +94,7 @@ class EventManager(object):
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._registeredListeners = {}
|
||||
self._registeredListeners = collections.defaultdict(list)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._queue = Queue.PriorityQueue()
|
||||
@@ -99,9 +106,7 @@ class EventManager(object):
|
||||
while True:
|
||||
(event, payload) = self._queue.get(True)
|
||||
|
||||
eventListeners = self._registeredListeners.get(event, None)
|
||||
if eventListeners is None:
|
||||
return
|
||||
eventListeners = self._registeredListeners[event]
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
|
||||
for listener in eventListeners:
|
||||
@@ -111,6 +116,10 @@ class EventManager(object):
|
||||
except:
|
||||
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=[event, payload])
|
||||
|
||||
def fire(self, event, payload=None):
|
||||
"""
|
||||
Fire an event to anyone subscribed to it
|
||||
@@ -122,8 +131,6 @@ class EventManager(object):
|
||||
payload being a payload object specific to the event.
|
||||
"""
|
||||
|
||||
if not event in self._registeredListeners.keys():
|
||||
return
|
||||
self._queue.put((event, payload), 0)
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
@@ -131,9 +138,6 @@ class EventManager(object):
|
||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||
"""
|
||||
|
||||
if not event in self._registeredListeners.keys():
|
||||
self._registeredListeners[event] = []
|
||||
|
||||
if callback in self._registeredListeners[event]:
|
||||
# callback is already subscribed to the event
|
||||
return
|
||||
@@ -146,10 +150,6 @@ class EventManager(object):
|
||||
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
|
||||
"""
|
||||
|
||||
if not event in self._registeredListeners:
|
||||
# no callback registered for callback, just return
|
||||
return
|
||||
|
||||
if not callback in self._registeredListeners[event]:
|
||||
# callback not subscribed to event, just return
|
||||
return
|
||||
@@ -293,7 +293,7 @@ class CommandTrigger(GenericEventListener):
|
||||
def _executeGcodeCommand(self, command):
|
||||
commands = [command]
|
||||
if isinstance(command, (list, tuple, set)):
|
||||
self._logger.debug("Executing GCode commands: %r" % command)
|
||||
self.logger.debug("Executing GCode commands: %r" % command)
|
||||
commands = list(command)
|
||||
else:
|
||||
self._logger.debug("Executing GCode command: %s" % command)
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
from octoprint.plugin.types import *
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None):
|
||||
global _instance
|
||||
if _instance is None:
|
||||
if init:
|
||||
if plugin_folders is None:
|
||||
plugin_folders = (settings().getBaseFolder("plugins"), os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")))
|
||||
if plugin_types is None:
|
||||
plugin_types = [StartupPlugin,
|
||||
ShutdownPlugin,
|
||||
TemplatePlugin,
|
||||
SettingsPlugin,
|
||||
SimpleApiPlugin,
|
||||
AssetPlugin,
|
||||
BlueprintPlugin,
|
||||
EventHandlerPlugin]
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = "octoprint.plugin"
|
||||
|
||||
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points)
|
||||
else:
|
||||
raise ValueError("Plugin Manager not initialized yet")
|
||||
return _instance
|
||||
|
||||
|
||||
def plugin_settings(plugin_key, defaults=None):
|
||||
return PluginSettings(settings(), plugin_key, defaults=defaults)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None):
|
||||
if not isinstance(types, (list, tuple)):
|
||||
types = [types]
|
||||
if args is None:
|
||||
args = []
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types)
|
||||
for name, plugin in plugins.items():
|
||||
if hasattr(plugin, method):
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(name, plugin, result)
|
||||
|
||||
|
||||
class PluginSettings(object):
|
||||
def __init__(self, settings, plugin_key, defaults=None):
|
||||
self.settings = settings
|
||||
self.plugin_key = plugin_key
|
||||
|
||||
if defaults is None:
|
||||
defaults = dict()
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
|
||||
def prefix_path(path):
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def prefix_path_in_args(args, index=0):
|
||||
result = []
|
||||
if index == 0:
|
||||
result.append(prefix_path(args[0]))
|
||||
result.extend(args[1:])
|
||||
else:
|
||||
args_before = args[:index - 1]
|
||||
args_after = args[index + 1:]
|
||||
result.extend(args_before)
|
||||
result.append(prefix_path(args[index]))
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
def add_defaults_to_kwargs(kwargs):
|
||||
kwargs.update(dict(defaults=self.defaults))
|
||||
return kwargs
|
||||
|
||||
self.access_methods = {
|
||||
'get': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getInt': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getFloat': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getBoolean': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'set': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setInt': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setFloat': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setBoolean': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs))
|
||||
}
|
||||
|
||||
def globalGet(self, path):
|
||||
return self.settings.get(path)
|
||||
|
||||
def globalGetInt(self, path):
|
||||
return self.settings.getInt(path)
|
||||
|
||||
def globalGetFloat(self, path):
|
||||
return self.settings.getFloat(path)
|
||||
|
||||
def globalGetBoolean(self, path):
|
||||
return self.settings.getBoolean(path)
|
||||
|
||||
def __getattr__(self, item):
|
||||
if item in self.access_methods and hasattr(self.settings, item) and callable(getattr(self.settings, item)):
|
||||
orig_item = getattr(self.settings, item)
|
||||
args_mapper, kwargs_mapper = self.access_methods[item]
|
||||
|
||||
return lambda *args, **kwargs: orig_item(*args_mapper(args), **kwargs_mapper(kwargs))
|
||||
else:
|
||||
return getattr(self.settings, item)
|
||||
@@ -0,0 +1,268 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
import imp
|
||||
from collections import defaultdict
|
||||
import logging
|
||||
|
||||
|
||||
class PluginInfo(object):
|
||||
|
||||
attr_name = '__plugin_name__'
|
||||
|
||||
attr_description = '__plugin_description__'
|
||||
|
||||
attr_version = '__plugin_version__'
|
||||
|
||||
attr_hooks = '__plugin_hooks__'
|
||||
|
||||
attr_implementations = '__plugin_implementations__'
|
||||
|
||||
attr_helpers = '__plugin_helpers__'
|
||||
|
||||
attr_check = '__plugin_check__'
|
||||
|
||||
attr_init = '__plugin_init__'
|
||||
|
||||
def __init__(self, key, location, instance, version=None):
|
||||
self.key = key
|
||||
self.location = location
|
||||
self.instance = instance
|
||||
|
||||
self._version = version
|
||||
|
||||
def __str__(self):
|
||||
return "{name} ({version})".format(name=self.name, version=self.version if self.version else "unknown")
|
||||
|
||||
def get_hook(self, hook):
|
||||
if not hook in self.hooks:
|
||||
return None
|
||||
return self.hooks[hook]
|
||||
|
||||
def get_implementations(self, *types):
|
||||
result = set()
|
||||
for implementation in self.implementations:
|
||||
matches_all = True
|
||||
for type in types:
|
||||
if not isinstance(implementation, type):
|
||||
matches_all = False
|
||||
if matches_all:
|
||||
result.add(implementation)
|
||||
return result
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_name, default=None)
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=None)
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=None)
|
||||
|
||||
@property
|
||||
def hooks(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_hooks, default={})
|
||||
|
||||
@property
|
||||
def implementations(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_implementations, default=[])
|
||||
|
||||
@property
|
||||
def helpers(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_helpers, default={})
|
||||
|
||||
@property
|
||||
def check(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_check, default=lambda: True)
|
||||
|
||||
@property
|
||||
def init(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_init, default=lambda: True)
|
||||
|
||||
def _get_instance_attribute(self, attr, default=None):
|
||||
if not hasattr(self.instance, attr):
|
||||
return default
|
||||
return getattr(self.instance, attr)
|
||||
|
||||
|
||||
class PluginManager(object):
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if plugin_disabled_list is None:
|
||||
plugin_disabled_list = []
|
||||
|
||||
self.plugin_folders = plugin_folders
|
||||
self.plugin_types = plugin_types
|
||||
self.plugin_entry_points = plugin_entry_points
|
||||
self.plugin_disabled_list = plugin_disabled_list
|
||||
|
||||
self.plugins = dict()
|
||||
self.plugin_hooks = defaultdict(list)
|
||||
self.plugin_implementations = defaultdict(list)
|
||||
|
||||
self.reload_plugins()
|
||||
|
||||
def _find_plugins(self):
|
||||
plugins = dict()
|
||||
if self.plugin_folders:
|
||||
self._add_plugins_from_folders(self.plugin_folders, plugins)
|
||||
if self.plugin_entry_points:
|
||||
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins)
|
||||
return plugins
|
||||
|
||||
def _add_plugins_from_folders(self, folders, plugins):
|
||||
for folder in folders:
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
entries = os.listdir(folder)
|
||||
for entry in entries:
|
||||
path = os.path.join(folder, entry)
|
||||
if os.path.isdir(path) and os.path.isfile(os.path.join(path, "__init__.py")):
|
||||
key = entry
|
||||
elif os.path.isfile(path) and entry.endswith(".py"):
|
||||
key = entry[:-3] # strip off the .py extension
|
||||
else:
|
||||
continue
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
# plugin is disabled, ignore it
|
||||
continue
|
||||
|
||||
if key in plugins:
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._load_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugins[key] = plugin
|
||||
|
||||
return plugins
|
||||
|
||||
def _add_plugins_from_entry_points(self, groups, plugins):
|
||||
import pkg_resources
|
||||
|
||||
if not isinstance(groups, (list, tuple)):
|
||||
groups = [groups]
|
||||
|
||||
for group in groups:
|
||||
for entry_point in pkg_resources.iter_entry_points(group=group, name=None):
|
||||
key = entry_point.name
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
# plugin is disabled, ignore it
|
||||
continue
|
||||
|
||||
if key in plugins:
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._load_plugin_from_module(key, module_name=module_name, version=version)
|
||||
if plugin:
|
||||
plugins[key] = plugin
|
||||
|
||||
return plugins
|
||||
|
||||
def _load_plugin_from_module(self, key, folder=None, module_name=None, version=None):
|
||||
# TODO error handling
|
||||
if folder:
|
||||
module = imp.find_module(key, [folder])
|
||||
elif module_name:
|
||||
module = imp.find_module(module_name)
|
||||
else:
|
||||
return None
|
||||
|
||||
plugin = self._load_plugin(key, *module, version=version)
|
||||
if plugin:
|
||||
if plugin.check():
|
||||
return plugin
|
||||
else:
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check, disabling it".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
|
||||
def _load_plugin(self, key, f, filename, description, version=None):
|
||||
try:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
return PluginInfo(key, filename, instance, version=version)
|
||||
except:
|
||||
self.logger.exception("Error loading plugin {key}, disabling it".format(key=key))
|
||||
return None
|
||||
|
||||
def _is_plugin_disabled(self, key):
|
||||
return key in self.plugin_disabled_list or key.endswith('disabled')
|
||||
|
||||
def reload_plugins(self):
|
||||
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(folders=", ".join(self.plugin_folders)))
|
||||
self.plugins = self._find_plugins()
|
||||
|
||||
for name, plugin in self.plugins.items():
|
||||
# initialize the plugin
|
||||
plugin.init()
|
||||
|
||||
# evaluate registered hooks
|
||||
for hook, callback in plugin.hooks.items():
|
||||
self.plugin_hooks[hook].append((name, callback))
|
||||
|
||||
# evaluate registered implementations
|
||||
for plugin_type in self.plugin_types:
|
||||
implementations = plugin.get_implementations(plugin_type)
|
||||
self.plugin_implementations[plugin_type] += ( (name, implementation) for implementation in implementations )
|
||||
|
||||
if len(self.plugins) <= 0:
|
||||
self.logger.info("No plugins found")
|
||||
else:
|
||||
self.logger.info("Found {count} plugin(s): {plugins}".format(count=len(self.plugins), plugins=", ".join(map(lambda x: str(x), self.plugins.values()))))
|
||||
|
||||
def get_plugin(self, name):
|
||||
if not name in self.plugins:
|
||||
return None
|
||||
return self.plugins[name].instance
|
||||
|
||||
def get_hooks(self, hook):
|
||||
if not hook in self.plugin_hooks:
|
||||
return []
|
||||
return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]}
|
||||
|
||||
def get_implementations(self, *types):
|
||||
result = None
|
||||
|
||||
for t in types:
|
||||
implementations = self.plugin_implementations[t]
|
||||
if result is None:
|
||||
result = set(implementations)
|
||||
else:
|
||||
result = result.intersection(implementations)
|
||||
|
||||
if result is None:
|
||||
return set()
|
||||
return {impl[0]: impl[1] for impl in result}
|
||||
|
||||
def get_helpers(self, name, *helpers):
|
||||
if not name in self.plugins:
|
||||
return None
|
||||
plugin = self.plugins[name]
|
||||
|
||||
all_helpers = plugin.helpers
|
||||
if len(helpers):
|
||||
return dict((k, v) for (k, v) in all_helpers.items() if k in helpers)
|
||||
else:
|
||||
return all_helpers
|
||||
|
||||
|
||||
class Plugin(object):
|
||||
pass
|
||||
@@ -0,0 +1,69 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from .core import Plugin
|
||||
|
||||
|
||||
class StartupPlugin(Plugin):
|
||||
def on_startup(self, host, port):
|
||||
pass
|
||||
|
||||
def on_after_startup(self):
|
||||
pass
|
||||
|
||||
|
||||
class ShutdownPlugin(Plugin):
|
||||
def on_shutdown(self):
|
||||
pass
|
||||
|
||||
|
||||
class AssetPlugin(Plugin):
|
||||
def get_asset_folder(self):
|
||||
return None
|
||||
|
||||
def get_assets(self):
|
||||
return []
|
||||
|
||||
|
||||
class TemplatePlugin(Plugin):
|
||||
def get_template_vars(self):
|
||||
return dict()
|
||||
|
||||
def get_template_folder(self):
|
||||
return None
|
||||
|
||||
|
||||
class SimpleApiPlugin(Plugin):
|
||||
def get_api_commands(self):
|
||||
return None
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
return None
|
||||
|
||||
def on_api_get(self, request):
|
||||
return None
|
||||
|
||||
|
||||
class BlueprintPlugin(Plugin):
|
||||
def get_blueprint(self):
|
||||
return None
|
||||
|
||||
|
||||
class SettingsPlugin(Plugin):
|
||||
def on_settings_load(self):
|
||||
return None
|
||||
|
||||
def on_settings_save(self, data):
|
||||
pass
|
||||
|
||||
|
||||
class EventHandlerPlugin(Plugin):
|
||||
def on_event(self, event, payload):
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,690 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
"""
|
||||
The SSDP/UPNP implementations has been largely inspired by https://gist.github.com/schlamar/2428250
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import flask
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util
|
||||
|
||||
try:
|
||||
import pybonjour
|
||||
except:
|
||||
pybonjour = False
|
||||
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
__plugin_version__ = "0.1"
|
||||
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
|
||||
|
||||
def __plugin_init__():
|
||||
if not pybonjour:
|
||||
# no pybonjour available, we can't use that
|
||||
logging.getLogger("octoprint.plugins." + __name__).info("pybonjour is not installed, Zeroconf Discovery won't be available")
|
||||
|
||||
discovery_plugin = DiscoveryPlugin()
|
||||
|
||||
global __plugin_implementations__
|
||||
__plugin_implementations__ = [discovery_plugin]
|
||||
|
||||
global __plugin_helpers__
|
||||
__plugin_helpers__ = dict(
|
||||
ssdp_browse=discovery_plugin.ssdp_browse
|
||||
)
|
||||
if pybonjour:
|
||||
__plugin_helpers__.update(dict(
|
||||
zeroconf_browse=discovery_plugin.zeroconf_browse,
|
||||
zeroconf_register=discovery_plugin.zeroconf_register,
|
||||
zeroconf_unregister=discovery_plugin.zeroconf_unregister
|
||||
))
|
||||
|
||||
|
||||
default_settings = {
|
||||
"publicHost": None,
|
||||
"publicPort": None,
|
||||
"pathPrefix": None,
|
||||
"httpUsername": None,
|
||||
"httpPassword": None,
|
||||
"upnpUuid": None,
|
||||
"zeroConf": [],
|
||||
"model": {
|
||||
"name": None,
|
||||
"description": None,
|
||||
"number": None,
|
||||
"url": None,
|
||||
"serial": None,
|
||||
"vendor": None,
|
||||
"vendorUrl": None
|
||||
}
|
||||
}
|
||||
s = octoprint.plugin.plugin_settings("discovery", defaults=default_settings)
|
||||
|
||||
def get_uuid():
|
||||
upnpUuid = s.get(["upnpUuid"])
|
||||
if upnpUuid is None:
|
||||
import uuid
|
||||
upnpUuid = str(uuid.uuid4())
|
||||
s.set(["upnpUuid"], upnpUuid)
|
||||
s.save()
|
||||
return upnpUuid
|
||||
UUID = get_uuid()
|
||||
del get_uuid
|
||||
|
||||
|
||||
def get_instance_name():
|
||||
name = s.globalGet(["appearance", "name"])
|
||||
if name:
|
||||
return "OctoPrint instance \"{}\"".format(name)
|
||||
else:
|
||||
import socket
|
||||
return "OctoPrint instance on {}".format(socket.gethostname())
|
||||
|
||||
|
||||
#~~ custom blueprint for providing discovery.xml
|
||||
|
||||
blueprint = flask.Blueprint("plugin.discovery", __name__, template_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates"))
|
||||
|
||||
@blueprint.route("/discovery.xml")
|
||||
def discovery():
|
||||
logging.getLogger("octoprint.plugins." + __name__).debug("Rendering discovery.xml")
|
||||
|
||||
modelName = s.get(["model", "name"])
|
||||
if not modelName:
|
||||
import octoprint.server
|
||||
modelName = octoprint.server.DISPLAY_VERSION
|
||||
|
||||
vendor = s.get(["model", "vendor"])
|
||||
vendorUrl = s.get(["model", "vendorUrl"])
|
||||
if not vendor:
|
||||
vendor = "The OctoPrint Project"
|
||||
vendorUrl = "http://www.octoprint.org/"
|
||||
|
||||
response = flask.make_response(flask.render_template("discovery.jinja2",
|
||||
friendlyName=get_instance_name(),
|
||||
manufacturer=vendor,
|
||||
manufacturerUrl=vendorUrl,
|
||||
modelName=modelName,
|
||||
modelDescription=s.get(["model", "description"]),
|
||||
modelNumber=s.get(["model", "number"]),
|
||||
modelUrl=s.get(["model", "url"]),
|
||||
serialNumber=s.get(["model", "serial"]),
|
||||
uuid=UUID,
|
||||
presentationUrl=flask.url_for("index", _external=True)))
|
||||
response.headers['Content-Type'] = 'application/xml'
|
||||
return response
|
||||
|
||||
|
||||
class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.ShutdownPlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
|
||||
ssdp_multicast_addr = "239.255.255.250"
|
||||
|
||||
ssdp_multicast_port = 1900
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger("octoprint.plugins." + __name__)
|
||||
|
||||
self.host = None
|
||||
self.port = None
|
||||
|
||||
# zeroconf
|
||||
self._sd_refs = dict()
|
||||
self._cnames = dict()
|
||||
|
||||
# upnp/ssdp
|
||||
self._ssdp_monitor_active = False
|
||||
self._ssdp_monitor_thread = None
|
||||
self._ssdp_notify_timeout = 10
|
||||
self._ssdp_last_notify = 0
|
||||
|
||||
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
|
||||
|
||||
def get_blueprint(self):
|
||||
return blueprint
|
||||
|
||||
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
|
||||
|
||||
def on_startup(self, host, port):
|
||||
public_host = s.get(["publicHost"])
|
||||
if public_host:
|
||||
host = public_host
|
||||
public_port = s.get(["publicPort"])
|
||||
if public_port:
|
||||
port = public_port
|
||||
|
||||
self.host = host
|
||||
self.port = port
|
||||
|
||||
# Zeroconf
|
||||
self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_http_txt_record_dict())
|
||||
self.zeroconf_register("_octoprint._tcp", get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
|
||||
for zeroconf in s.get(["zeroConf"]):
|
||||
if "service" in zeroconf:
|
||||
self.zeroconf_register(
|
||||
zeroconf["service"],
|
||||
zeroconf["name"] if "name" in zeroconf else get_instance_name(),
|
||||
port=zeroconf["port"] if "port" in zeroconf else None,
|
||||
txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None
|
||||
)
|
||||
|
||||
# SSDP
|
||||
self._ssdp_register()
|
||||
|
||||
##~~ ShutdownPlugin API -- used for unregistering OctoPrint's Zeroconf and SSDP service upon application shutdown
|
||||
|
||||
def on_shutdown(self):
|
||||
for key in self._sd_refs:
|
||||
reg_type, port = key
|
||||
self.zeroconf_unregister(reg_type, port)
|
||||
|
||||
self._ssdp_unregister()
|
||||
|
||||
##~~ helpers
|
||||
|
||||
# ZeroConf
|
||||
|
||||
def zeroconf_register(self, reg_type, name=None, port=None, txt_record=None):
|
||||
"""
|
||||
Registers a new service with Zeroconf/Bonjour/Avahi.
|
||||
|
||||
:param reg_type: type of service to register, e.g. "_gntp._tcp"
|
||||
:param name: displayable name of the service, if not given defaults to the OctoPrint instance name
|
||||
:param port: port to register for the service, if not given defaults to OctoPrint's (public) port
|
||||
:param txt_record: optional txt record to attach to the service, dictionary of key-value-pairs
|
||||
"""
|
||||
|
||||
if not pybonjour:
|
||||
return
|
||||
|
||||
if not name:
|
||||
name = get_instance_name()
|
||||
if not port:
|
||||
port = self.port
|
||||
|
||||
params = dict(
|
||||
name=name,
|
||||
regtype=reg_type,
|
||||
port=port
|
||||
)
|
||||
if txt_record:
|
||||
params["txtRecord"] = pybonjour.TXTRecord(txt_record)
|
||||
|
||||
key = (reg_type, port)
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self.logger.info("Registered {name} for {reg_type}".format(**locals()))
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
Unregisteres 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
|
||||
:return:
|
||||
"""
|
||||
|
||||
if not pybonjour:
|
||||
return
|
||||
|
||||
if not port:
|
||||
port = self.port
|
||||
|
||||
key = (reg_type, port)
|
||||
if not key in self._sd_refs:
|
||||
return
|
||||
|
||||
sd_ref = self._sd_refs[key]
|
||||
try:
|
||||
sd_ref.close()
|
||||
self.logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
except:
|
||||
self.logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
|
||||
def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5):
|
||||
"""
|
||||
Browses for services on the local network providing the specified service type. Can be used either blocking or
|
||||
non-blocking.
|
||||
|
||||
The non-blocking version (default behaviour) will not return until the lookup has completed and
|
||||
return all results that were found.
|
||||
|
||||
For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes.
|
||||
If no callback is provided in non-blocking mode, a ValueError will be raised.
|
||||
|
||||
The results are provided as a list of discovered services, with each service being described by a dictionary
|
||||
with the following keys:
|
||||
|
||||
* `name`: display name of the service
|
||||
* `host`: host name of the service
|
||||
* `post`: port the service is listening on
|
||||
* `txt_record`: TXT record of the service as a dictionary, exact contents depend on the service
|
||||
|
||||
Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an
|
||||
example for a valid callback:
|
||||
|
||||
def browse_callback(results):
|
||||
for result in results:
|
||||
print "Name: {name}, Host: {host}, Port: {port}, TXT: {txt_record!r}".format(**result)
|
||||
|
||||
:param service_type: the service type to browse for
|
||||
:param block: whether to block, defaults to True
|
||||
:param callback: callback to call once lookup has completed, must be set when `block` is set to `False`
|
||||
:param browse_timeout: timeout for browsing operation
|
||||
:param resolve_timeout: timeout for resolving operations for discovered records
|
||||
:return: if `block` is `True` a list of the discovered services, an empty list otherwise (results will then be
|
||||
supplied to the callback instead)
|
||||
"""
|
||||
|
||||
if not pybonjour:
|
||||
return None
|
||||
|
||||
import threading
|
||||
import select
|
||||
|
||||
if not block and not callback:
|
||||
raise ValueError("Non-blocking mode but no callback given")
|
||||
|
||||
result = []
|
||||
result_available = threading.Event()
|
||||
result_available.clear()
|
||||
|
||||
resolved = []
|
||||
|
||||
def resolve_callback(sd_ref, flags, interface_index, error_code, fullname, hosttarget, port, txt_record):
|
||||
if error_code == pybonjour.kDNSServiceErr_NoError:
|
||||
txt_record_dict = None
|
||||
if txt_record:
|
||||
record = pybonjour.TXTRecord.parse(txt_record)
|
||||
txt_record_dict = dict()
|
||||
for key, value in record:
|
||||
txt_record_dict[key] = value
|
||||
|
||||
name = fullname[:fullname.find(service_type) - 1].replace("\\032", " ")
|
||||
host = hosttarget[:-1]
|
||||
|
||||
self.logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
|
||||
result.append(dict(
|
||||
name=name,
|
||||
host=host,
|
||||
port=port,
|
||||
txt_record=txt_record_dict
|
||||
))
|
||||
resolved.append(True)
|
||||
|
||||
def browse_callback(sd_ref, flags, interface_index, error_code, service_name, regtype, reply_domain):
|
||||
if error_code != pybonjour.kDNSServiceErr_NoError:
|
||||
return
|
||||
|
||||
if not (flags & pybonjour.kDNSServiceFlagsAdd):
|
||||
return
|
||||
|
||||
self.logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
|
||||
resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback)
|
||||
|
||||
try:
|
||||
while not resolved:
|
||||
ready = select.select([resolve_ref], [], [], resolve_timeout)
|
||||
if resolve_ref not in ready[0]:
|
||||
break
|
||||
|
||||
pybonjour.DNSServiceProcessResult(resolve_ref)
|
||||
else:
|
||||
resolved.pop()
|
||||
finally:
|
||||
resolve_ref.close()
|
||||
|
||||
self.logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
|
||||
|
||||
def browse():
|
||||
sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback)
|
||||
try:
|
||||
while True:
|
||||
ready = select.select([sd_ref], [], [], browse_timeout)
|
||||
|
||||
if not ready[0]:
|
||||
break
|
||||
|
||||
if sd_ref in ready[0]:
|
||||
pybonjour.DNSServiceProcessResult(sd_ref)
|
||||
finally:
|
||||
sd_ref.close()
|
||||
|
||||
if callback:
|
||||
callback(result)
|
||||
result_available.set()
|
||||
|
||||
browse_thread = threading.Thread(target=browse)
|
||||
browse_thread.daemon = True
|
||||
browse_thread.start()
|
||||
|
||||
if block:
|
||||
result_available.wait()
|
||||
return result
|
||||
else:
|
||||
return []
|
||||
|
||||
# SSDP/UPNP
|
||||
|
||||
def ssdp_browse(self, query, block=True, callback=None, timeout=1, retries=5):
|
||||
"""
|
||||
Browses for UPNP services matching the supplied query. Can be used either blocking or
|
||||
non-blocking.
|
||||
|
||||
The non-blocking version (default behaviour) will not return until the lookup has completed and
|
||||
return all results that were found.
|
||||
|
||||
For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes.
|
||||
If no callback is provided in non-blocking mode, a ValueError will be raised.
|
||||
|
||||
The results are provided as a list of discovered locations of device descriptor files.
|
||||
|
||||
Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an
|
||||
example for a valid callback:
|
||||
|
||||
def browse_callback(results):
|
||||
for result in results:
|
||||
print "Location: {}".format(result)
|
||||
|
||||
:param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices
|
||||
:param block: whether to block, defaults to True
|
||||
:param callback: callback to call in non-blocking mode when lookup has finished, must be set if block is False
|
||||
:param timeout: timeout in seconds to wait for replies to the M-SEARCH query per interface, defaults to 1
|
||||
:param retries: number of retries to perform the lookup on all interfaces, defaults to 5
|
||||
:return: if `block` is `True` a list of the discovered devices, an empty list otherwise (results will then be
|
||||
supplied to the callback instead)
|
||||
"""
|
||||
|
||||
import threading
|
||||
|
||||
import httplib
|
||||
import io
|
||||
class Response(httplib.HTTPResponse):
|
||||
def __init__(self, response_text):
|
||||
self.fp = io.BytesIO(response_text)
|
||||
self.debuglevel = 0
|
||||
self.strict = 0
|
||||
self.msg = None
|
||||
self._method = None
|
||||
self.begin()
|
||||
|
||||
result = []
|
||||
result_available = threading.Event()
|
||||
result_available.clear()
|
||||
|
||||
def browse():
|
||||
import socket
|
||||
|
||||
socket.setdefaulttimeout(timeout)
|
||||
|
||||
search_message = "".join([
|
||||
"M-SEARCH * HTTP/1.1\r\n",
|
||||
"ST: {query}\r\n",
|
||||
"MX: 3\r\n",
|
||||
"MAN: \"ssdp:discovery\"\r\n",
|
||||
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
|
||||
])
|
||||
|
||||
for _ in xrange(retries):
|
||||
for addr in octoprint.util.interface_addresses():
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
||||
sock.bind((addr, 0))
|
||||
|
||||
message = search_message.format(query=query,
|
||||
mcast_addr=self.__class__.ssdp_multicast_addr,
|
||||
mcast_port=self.__class__.ssdp_multicast_port)
|
||||
for _ in xrange(2):
|
||||
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
|
||||
|
||||
try:
|
||||
data = sock.recv(1024)
|
||||
except socket.timeout:
|
||||
pass
|
||||
else:
|
||||
response = Response(data)
|
||||
|
||||
result.append(response.getheader("Location"))
|
||||
except:
|
||||
pass
|
||||
|
||||
if callback:
|
||||
callback(result)
|
||||
result_available.set()
|
||||
|
||||
browse_thread = threading.Thread(target=browse)
|
||||
browse_thread.daemon = True
|
||||
browse_thread.start()
|
||||
|
||||
if block:
|
||||
result_available.wait()
|
||||
return result
|
||||
else:
|
||||
return []
|
||||
|
||||
##~~ internals
|
||||
|
||||
# Zeroconf
|
||||
|
||||
def _create_http_txt_record_dict(self):
|
||||
"""
|
||||
Creates a TXT record for the _http._tcp Zeroconf service supplied by this OctoPrint instance.
|
||||
|
||||
Defines the keys for _http._tcp as defined in http://www.dns-sd.org/txtrecords.html
|
||||
|
||||
:return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record
|
||||
"""
|
||||
|
||||
# determine path entry
|
||||
path = "/"
|
||||
if s.get(["pathPrefix"]):
|
||||
path = s.get(["pathPrefix"])
|
||||
else:
|
||||
prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"])
|
||||
if prefix:
|
||||
path = prefix
|
||||
|
||||
# fetch username and password (if set)
|
||||
username = s.get(["httpUsername"])
|
||||
password = s.get(["httpPassword"])
|
||||
|
||||
entries = dict(
|
||||
path=path
|
||||
)
|
||||
|
||||
if username and password:
|
||||
entries.update(dict(u=username, p=password))
|
||||
|
||||
return entries
|
||||
|
||||
def _create_octoprint_txt_record_dict(self):
|
||||
"""
|
||||
Creates a TXT record for the _octoprint._tcp Zeroconf service supplied by this OctoPrint instance.
|
||||
|
||||
The following keys are defined:
|
||||
|
||||
* `path`: path prefix to actual OctoPrint instance, inherited from _http._tcp
|
||||
* `u`: username if HTTP Basic Auth is used, optional, inherited from _http._tcp
|
||||
* `p`: password if HTTP Basic Auth is used, optional, inherited from _http._tcp
|
||||
* `version`: OctoPrint software version
|
||||
* `api`: OctoPrint API version
|
||||
* `model`: Model of the device that is running OctoPrint
|
||||
* `vendor`: Vendor of the device that is running OctoPrint
|
||||
|
||||
:return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record
|
||||
"""
|
||||
|
||||
entries = self._create_http_txt_record_dict()
|
||||
|
||||
import octoprint.server
|
||||
import octoprint.server.api
|
||||
|
||||
entries.update(dict(
|
||||
version=octoprint.server.VERSION,
|
||||
api=octoprint.server.api.VERSION,
|
||||
))
|
||||
|
||||
modelName = s.get(["model", "name"])
|
||||
if modelName:
|
||||
entries.update(dict(model=modelName))
|
||||
vendor = s.get(["model", "vendor"])
|
||||
if vendor:
|
||||
entries.update(dict(vendor=vendor))
|
||||
|
||||
return entries
|
||||
|
||||
# SSDP/UPNP
|
||||
|
||||
def _ssdp_register(self):
|
||||
"""
|
||||
Registers the OctoPrint instance as basic service with a presentation URL pointing to the web interface
|
||||
"""
|
||||
|
||||
import threading
|
||||
|
||||
self._ssdp_monitor_active = True
|
||||
|
||||
self._ssdp_monitor_thread = threading.Thread(target=self._ssdp_monitor, kwargs=dict(timeout=self._ssdp_notify_timeout))
|
||||
self._ssdp_monitor_thread.daemon = True
|
||||
self._ssdp_monitor_thread.start()
|
||||
|
||||
def _ssdp_unregister(self):
|
||||
"""
|
||||
Unregisters the OctoPrint instance again
|
||||
"""
|
||||
|
||||
self._ssdp_monitor_active = False
|
||||
if self.host and self.port:
|
||||
for _ in xrange(2):
|
||||
self._ssdp_notify(alive=False)
|
||||
|
||||
def _ssdp_notify(self, alive=True):
|
||||
"""
|
||||
Sends an SSDP notify message across the connected networks.
|
||||
|
||||
:param alive: True to send an "ssdp:alive" message, False to send an "ssdp:byebye" message
|
||||
"""
|
||||
|
||||
import socket
|
||||
import time
|
||||
|
||||
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > time.time():
|
||||
# we just sent an alive, no need to send another one now
|
||||
return
|
||||
|
||||
if alive and not self._ssdp_monitor_active:
|
||||
# the monitor already shut down, alive messages don't make sense anymore as byebye will shortly follow
|
||||
return
|
||||
|
||||
for addr in octoprint.util.interface_addresses():
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
||||
sock.bind((addr, 0))
|
||||
|
||||
location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(addr=addr, port=self.port)
|
||||
|
||||
self.logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
|
||||
notify_message = "".join([
|
||||
"NOTIFY * HTTP/1.1\r\n",
|
||||
"Server: Python/2.7\r\n",
|
||||
"Cache-Control: max-age=900\r\n",
|
||||
"Location: {location}\r\n",
|
||||
"NTS: {nts}\r\n",
|
||||
"NT: upnp:rootdevice\r\n",
|
||||
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
|
||||
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
|
||||
])
|
||||
message = notify_message.format(uuid=UUID,
|
||||
location=location,
|
||||
nts="ssdp:alive" if alive else "ssdp:byebye",
|
||||
mcast_addr=self.__class__.ssdp_multicast_addr,
|
||||
mcast_port=self.__class__.ssdp_multicast_port)
|
||||
for _ in xrange(2):
|
||||
# send twice, stuff might get lost, it's only UDP
|
||||
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
|
||||
except:
|
||||
pass
|
||||
|
||||
self._ssdp_last_notify = time.time()
|
||||
|
||||
def _ssdp_monitor(self, timeout=5):
|
||||
"""
|
||||
Monitor thread that listens on the multicast address for M-SEARCH requests and answers them if they are relevant
|
||||
|
||||
:param timeout: timeout after which to stop waiting for M-SEARCHs for a short while in order to put out an
|
||||
alive message
|
||||
"""
|
||||
|
||||
from BaseHTTPServer import BaseHTTPRequestHandler
|
||||
from StringIO import StringIO
|
||||
import socket
|
||||
|
||||
socket.setdefaulttimeout(timeout)
|
||||
|
||||
location_message = "".join([
|
||||
"HTTP/1.1 200 OK\r\n",
|
||||
"ST: upnp:rootdevice\r\n",
|
||||
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
|
||||
"Location: {location}\r\n",
|
||||
"Cache-Control: max-age=60\r\n\r\n"
|
||||
])
|
||||
|
||||
class Request(BaseHTTPRequestHandler):
|
||||
|
||||
def __init__(self, request_text):
|
||||
self.rfile = StringIO(request_text)
|
||||
self.raw_requestline = self.rfile.readline()
|
||||
self.error_code = self.error_message = None
|
||||
self.parse_request()
|
||||
|
||||
def send_error(self, code, message=None):
|
||||
self.error_code = code
|
||||
self.error_message = message
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
||||
sock.bind(('', self.__class__.ssdp_multicast_port))
|
||||
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0'))
|
||||
|
||||
self.logger.info("Registered {} for SSDP".format(get_instance_name()))
|
||||
|
||||
self._ssdp_notify(alive=True)
|
||||
|
||||
try:
|
||||
while (self._ssdp_monitor_active):
|
||||
try:
|
||||
data, address = sock.recvfrom(4096)
|
||||
request = Request(data)
|
||||
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
|
||||
interface_address = octoprint.util.address_for_client(*address)
|
||||
if not interface_address:
|
||||
self.logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
continue
|
||||
message = location_message.format(uuid=UUID, location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
sock.sendto(message, address)
|
||||
self.logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
|
||||
except socket.timeout:
|
||||
pass
|
||||
finally:
|
||||
self._ssdp_notify(alive=True)
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0"?>
|
||||
<root xmlns="urn:schemas-upnp-org:device-1-0">
|
||||
<specVersion>
|
||||
<major>1</major>
|
||||
<minor>0</minor>
|
||||
</specVersion>
|
||||
<device>
|
||||
<deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType>
|
||||
<friendlyName>{{ friendlyName }}</friendlyName>
|
||||
<manufacturer>{{ manufacturer }}</manufacturer>
|
||||
{% if manufacturerUrl %}<manufacturerURL>{{ manufacturerUrl }}</manufacturerURL>{% endif %}
|
||||
<modelName>{{ modelName }}</modelName>
|
||||
{% if modelDescription %}<modelDescription>{{ modelDescription }}</modelDescription>{% endif %}
|
||||
{% if modelNumber %}<modelNumber>{{ modelNumber }}</modelNumber>{% endif %}
|
||||
{% if modelUrl %}<modelURL>{{ modelUrl }}</modelURL>{% endif %}
|
||||
{% if serialNumber %}<serialNumber>{{ serialNumber }}</serialNumber>{% endif %}
|
||||
<UDN>uuid:{{ uuid }}</UDN>
|
||||
<serviceList>
|
||||
</serviceList>
|
||||
<presentationURL>{{ presentationUrl }}</presentationURL>
|
||||
</device>
|
||||
</root>
|
||||
@@ -503,6 +503,17 @@ class Printer():
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
self._stateMonitor.setJobData({
|
||||
"file": {
|
||||
"name": None,
|
||||
"origin": None,
|
||||
"size": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"filament": None,
|
||||
})
|
||||
return
|
||||
|
||||
estimatedPrintTime = None
|
||||
lastPrintTime = None
|
||||
|
||||
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import uuid
|
||||
from sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, render_template, send_from_directory, g, request
|
||||
from flask import Flask, render_template, send_from_directory, g, request, make_response
|
||||
from flask.ext.login import LoginManager
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
|
||||
from flask.ext.babel import Babel
|
||||
@@ -17,6 +17,7 @@ from watchdog.observers import Observer
|
||||
import os
|
||||
import logging
|
||||
import logging.config
|
||||
import atexit
|
||||
|
||||
SUCCESS = {}
|
||||
NO_CONTENT = ("", 204)
|
||||
@@ -30,6 +31,7 @@ gcodeManager = None
|
||||
userManager = None
|
||||
eventManager = None
|
||||
loginManager = None
|
||||
pluginManager = None
|
||||
|
||||
principals = Principal(app)
|
||||
admin_permission = Permission(RoleNeed("admin"))
|
||||
@@ -41,6 +43,7 @@ from octoprint.settings import settings
|
||||
import octoprint.gcodefiles as gcodefiles
|
||||
import octoprint.users as users
|
||||
import octoprint.events as events
|
||||
import octoprint.plugin
|
||||
import octoprint.timelapse
|
||||
import octoprint._version
|
||||
import octoprint.util
|
||||
@@ -88,6 +91,16 @@ def get_locale():
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
settings_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin, octoprint.plugin.SettingsPlugin)
|
||||
settings_plugin_template_vars = dict()
|
||||
for name, implementation in settings_plugins.items():
|
||||
settings_plugin_template_vars[name] = implementation.get_template_vars()
|
||||
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
asset_plugin_urls = dict()
|
||||
for name, implementation in asset_plugins.items():
|
||||
asset_plugin_urls[name] = implementation.get_assets()
|
||||
|
||||
return render_template(
|
||||
"index.jinja2",
|
||||
webcamStream=settings().get(["webcam", "stream"]),
|
||||
@@ -104,7 +117,9 @@ def index():
|
||||
stylesheet=settings().get(["devel", "stylesheet"]),
|
||||
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
|
||||
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
|
||||
uiApiKey=UI_API_KEY
|
||||
uiApiKey=UI_API_KEY,
|
||||
settingsPlugins=settings_plugin_template_vars,
|
||||
assetPlugins=asset_plugin_urls
|
||||
)
|
||||
|
||||
|
||||
@@ -113,6 +128,20 @@ def robotsTxt():
|
||||
return send_from_directory(app.static_folder, "robots.txt")
|
||||
|
||||
|
||||
@app.route("/plugin_assets/<string:name>/<path:filename>")
|
||||
def plugin_assets(name, filename):
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
|
||||
if not name in asset_plugins:
|
||||
return make_response("Asset not found", 404)
|
||||
asset_plugin = asset_plugins[name]
|
||||
asset_folder = asset_plugin.get_asset_folder()
|
||||
if asset_folder is None:
|
||||
return make_response("Asset not found", 404)
|
||||
|
||||
return send_from_directory(asset_folder, filename)
|
||||
|
||||
|
||||
@identity_loaded.connect_via(app)
|
||||
def on_identity_loaded(sender, identity):
|
||||
user = load_user(identity.id)
|
||||
@@ -155,6 +184,7 @@ class Server():
|
||||
global userManager
|
||||
global eventManager
|
||||
global loginManager
|
||||
global pluginManager
|
||||
global debug
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
@@ -174,6 +204,23 @@ class Server():
|
||||
eventManager = events.eventManager()
|
||||
gcodeManager = gcodefiles.GcodeManager()
|
||||
printer = Printer(gcodeManager)
|
||||
pluginManager = octoprint.plugin.plugin_manager(init=True)
|
||||
|
||||
# configure additional template folders for jinja2
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
additional_template_folders = []
|
||||
for plugin in template_plugins.values():
|
||||
folder = plugin.get_template_folder()
|
||||
if folder is not None:
|
||||
additional_template_folders.append(plugin.get_template_folder())
|
||||
|
||||
import jinja2
|
||||
jinja_loader = jinja2.ChoiceLoader([
|
||||
app.jinja_loader,
|
||||
jinja2.FileSystemLoader(additional_template_folders)
|
||||
])
|
||||
app.jinja_loader = jinja_loader
|
||||
del jinja2
|
||||
|
||||
# configure timelapse
|
||||
octoprint.timelapse.configureTimelapse()
|
||||
@@ -213,13 +260,18 @@ class Server():
|
||||
if self._port is None:
|
||||
self._port = settings().getInt(["server", "port"])
|
||||
|
||||
logger.info("Listening on http://%s:%d" % (self._host, self._port))
|
||||
app.debug = self._debug
|
||||
|
||||
from octoprint.server.api import api
|
||||
|
||||
# register API blueprint
|
||||
app.register_blueprint(api, url_prefix="/api")
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.BlueprintPlugin,
|
||||
"get_blueprint",
|
||||
callback=lambda name, _, blueprint: app.register_blueprint(blueprint, url_prefix="/plugin/{name}".format(name=name)))
|
||||
|
||||
self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
|
||||
|
||||
upload_suffixes = dict(name=settings().get(["server", "uploads", "nameSuffix"]), path=settings().get(["server", "uploads", "pathSuffix"]))
|
||||
@@ -249,16 +301,45 @@ class Server():
|
||||
observer.schedule(util.watchdog.UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads"))
|
||||
observer.start()
|
||||
|
||||
try:
|
||||
IOLoop.instance().start()
|
||||
except KeyboardInterrupt:
|
||||
ioloop = IOLoop.instance()
|
||||
|
||||
# run our startup plugins
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
|
||||
"on_startup",
|
||||
args=(self._host, self._port))
|
||||
|
||||
# prepare our after startup function
|
||||
def on_after_startup():
|
||||
logger.info("Listening on http://%s:%d" % (self._host, self._port))
|
||||
|
||||
# now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
|
||||
# which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
|
||||
# or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
|
||||
# create a single use thread in which to perform our after-startup-tasks, start that and hand back
|
||||
# control to the ioloop
|
||||
def work():
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
|
||||
"on_after_startup")
|
||||
import threading
|
||||
threading.Thread(target=work).start()
|
||||
ioloop.add_callback(on_after_startup)
|
||||
|
||||
# prepare our shutdown function
|
||||
def on_shutdown():
|
||||
logger.info("Goodbye!")
|
||||
observer.stop()
|
||||
observer.join()
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
|
||||
"on_shutdown")
|
||||
atexit.register(on_shutdown)
|
||||
|
||||
try:
|
||||
ioloop.start()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except:
|
||||
logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!")
|
||||
logger.exception("Stacktrace follows:")
|
||||
finally:
|
||||
observer.stop()
|
||||
observer.join()
|
||||
|
||||
def _createSocketConnection(self, session):
|
||||
global printer, gcodeManager, userManager, eventManager
|
||||
|
||||
@@ -16,6 +16,7 @@ from flask.ext.principal import Identity, identity_changed, AnonymousIdentity
|
||||
import octoprint.util as util
|
||||
import octoprint.users
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT, UI_API_KEY
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import get_api_key, get_user_for_apikey
|
||||
@@ -107,6 +108,44 @@ def afterApiRequests(resp):
|
||||
return resp
|
||||
|
||||
|
||||
#~~ data from plugins
|
||||
|
||||
@api.route("/plugin/<string:name>", methods=["GET"])
|
||||
def pluginData(name):
|
||||
api_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SimpleApiPlugin)
|
||||
if not name in api_plugins:
|
||||
return make_response("Not found", 404)
|
||||
|
||||
api_plugin = api_plugins[name]
|
||||
response = api_plugin.on_api_get(request)
|
||||
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
|
||||
#~~ commands for plugins
|
||||
|
||||
@api.route("/plugin/<string:name>", methods=["POST"])
|
||||
@restricted_access
|
||||
def pluginCommand(name):
|
||||
api_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SimpleApiPlugin)
|
||||
if not name in api_plugins:
|
||||
return make_response("Not found", 404)
|
||||
|
||||
api_plugin = api_plugins[name]
|
||||
valid_commands = api_plugin.get_api_commands()
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
response = api_plugin.on_api_command(command, data)
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
|
||||
#~~ first run setup
|
||||
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ from octoprint.server import admin_permission
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
|
||||
#~~ settings
|
||||
|
||||
@@ -29,7 +31,7 @@ def getSettings():
|
||||
|
||||
connectionOptions = getConnectionOptions()
|
||||
|
||||
return jsonify({
|
||||
data = {
|
||||
"api": {
|
||||
"enabled": s.getBoolean(["api", "enabled"]),
|
||||
"key": s.get(["api", "key"]),
|
||||
@@ -102,7 +104,21 @@ def getSettings():
|
||||
"path": s.get(["cura", "path"]),
|
||||
"config": s.get(["cura", "config"])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
def process_plugin_result(name, plugin, result):
|
||||
if result:
|
||||
if not "plugins" in data:
|
||||
data["plugins"] = dict()
|
||||
if "__enabled" in result:
|
||||
del result["__enabled"]
|
||||
data["plugins"][name] = result
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.SettingsPlugin,
|
||||
"on_settings_load",
|
||||
callback=process_plugin_result)
|
||||
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
@api.route("/settings", methods=["POST"])
|
||||
@@ -204,6 +220,12 @@ def setSettings():
|
||||
enabled = cura.get("enabled")
|
||||
s.setBoolean(["cura", "enabled"], enabled)
|
||||
|
||||
if "plugins" in data:
|
||||
for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items():
|
||||
if name in data["plugins"]:
|
||||
plugin.on_settings_save(data["plugins"][name])
|
||||
|
||||
|
||||
s.save()
|
||||
|
||||
return getSettings()
|
||||
|
||||
@@ -15,10 +15,6 @@ from octoprint.events import Events
|
||||
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
EVENTS = [Events.UPDATED_FILES, Events.METADATA_ANALYSIS_FINISHED, Events.MOVIE_RENDERING, Events.MOVIE_DONE,
|
||||
Events.MOVIE_FAILED, Events.SLICING_STARTED, Events.SLICING_DONE, Events.SLICING_FAILED,
|
||||
Events.TRANSFER_STARTED, Events.TRANSFER_DONE]
|
||||
|
||||
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
|
||||
sockjs.tornado.SockJSConnection.__init__(self, session)
|
||||
|
||||
@@ -54,7 +50,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
octoprint.timelapse.registerCallback(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
|
||||
for event in PrinterStateConnection.EVENTS:
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.subscribe(event, self._onEvent)
|
||||
|
||||
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
|
||||
@@ -66,7 +62,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
octoprint.timelapse.unregisterCallback(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED)
|
||||
for event in PrinterStateConnection.EVENTS:
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.unsubscribe(event, self._onEvent)
|
||||
|
||||
def on_message(self, message):
|
||||
|
||||
@@ -710,7 +710,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
CHUNK_SIZE = 16 * 1024
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None):
|
||||
tornado.web.StaticFileHandler.initialize(self, path, default_filename)
|
||||
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
self._access_validation = access_validation
|
||||
|
||||
|
||||
+105
-23
@@ -110,7 +110,8 @@ default_settings = {
|
||||
"timelapse_tmp": None,
|
||||
"logs": None,
|
||||
"virtualSd": None,
|
||||
"watched": None
|
||||
"watched": None,
|
||||
"plugins": None
|
||||
},
|
||||
"temperature": {
|
||||
"profiles":
|
||||
@@ -171,6 +172,7 @@ default_settings = {
|
||||
{ "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T\d*:)" },
|
||||
{ "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" }
|
||||
],
|
||||
"plugins": {},
|
||||
"devel": {
|
||||
"stylesheet": "css",
|
||||
"virtualPrinter": {
|
||||
@@ -244,11 +246,89 @@ class Settings(object):
|
||||
if not self._config:
|
||||
return
|
||||
|
||||
dirty = False
|
||||
for migrate in (self._migrate_event_config, self._migrate_reverse_proxy_config):
|
||||
dirty = migrate() or dirty
|
||||
if dirty:
|
||||
if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]):
|
||||
self._logger.info("Migrating config (event subscriptions)...")
|
||||
|
||||
# migrate event hooks to new format
|
||||
placeholderRe = re.compile("%\((.*?)\)s")
|
||||
|
||||
eventNameReplacements = {
|
||||
"ClientOpen": "ClientOpened",
|
||||
"TransferStart": "TransferStarted"
|
||||
}
|
||||
payloadDataReplacements = {
|
||||
"Upload": {"data": "{file}", "filename": "{file}"},
|
||||
"Connected": {"data": "{port} at {baudrate} baud"},
|
||||
"FileSelected": {"data": "{file}", "filename": "{file}"},
|
||||
"TransferStarted": {"data": "{remote}", "filename": "{remote}"},
|
||||
"TransferDone": {"data": "{remote}", "filename": "{remote}"},
|
||||
"ZChange": {"data": "{new}"},
|
||||
"CaptureStart": {"data": "{file}"},
|
||||
"CaptureDone": {"data": "{file}"},
|
||||
"MovieDone": {"data": "{movie}", "filename": "{gcode}"},
|
||||
"Error": {"data": "{error}"},
|
||||
"PrintStarted": {"data": "{file}", "filename": "{file}"},
|
||||
"PrintDone": {"data": "{file}", "filename": "{file}"},
|
||||
}
|
||||
|
||||
def migrateEventHook(event, command):
|
||||
# migrate placeholders
|
||||
command = placeholderRe.sub("{__\\1}", command)
|
||||
|
||||
# migrate event names
|
||||
if event in eventNameReplacements:
|
||||
event = eventNameReplacements["event"]
|
||||
|
||||
# migrate payloads to more specific placeholders
|
||||
if event in payloadDataReplacements:
|
||||
for key in payloadDataReplacements[event]:
|
||||
command = command.replace("{__%s}" % key, payloadDataReplacements[event][key])
|
||||
|
||||
# return processed tuple
|
||||
return event, command
|
||||
|
||||
disableSystemCommands = False
|
||||
if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]:
|
||||
disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"]
|
||||
|
||||
disableGcodeCommands = False
|
||||
if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]:
|
||||
disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"]
|
||||
|
||||
disableAllCommands = disableSystemCommands and disableGcodeCommands
|
||||
newEvents = {
|
||||
"enabled": not disableAllCommands,
|
||||
"subscriptions": []
|
||||
}
|
||||
|
||||
if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]:
|
||||
for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]:
|
||||
if not ("event" in trigger and "command" in trigger):
|
||||
continue
|
||||
|
||||
newTrigger = {"type": "system"}
|
||||
if disableSystemCommands and not disableAllCommands:
|
||||
newTrigger["enabled"] = False
|
||||
|
||||
newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"])
|
||||
newEvents["subscriptions"].append(newTrigger)
|
||||
|
||||
if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]:
|
||||
for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]:
|
||||
if not ("event" in trigger and "command" in trigger):
|
||||
continue
|
||||
|
||||
newTrigger = {"type": "gcode"}
|
||||
if disableGcodeCommands and not disableAllCommands:
|
||||
newTrigger["enabled"] = False
|
||||
|
||||
newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"])
|
||||
newTrigger["command"] = newTrigger["command"].split(",")
|
||||
newEvents["subscriptions"].append(newTrigger)
|
||||
|
||||
self._config["events"] = newEvents
|
||||
self.save(force=True)
|
||||
self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"]))
|
||||
|
||||
def _migrate_reverse_proxy_config(self):
|
||||
if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]):
|
||||
@@ -371,12 +451,13 @@ class Settings(object):
|
||||
|
||||
#~~ getter
|
||||
|
||||
def get(self, path, asdict=False):
|
||||
def get(self, path, asdict=False, defaults=None):
|
||||
if len(path) == 0:
|
||||
return None
|
||||
|
||||
config = self._config
|
||||
defaults = default_settings
|
||||
if defaults is None:
|
||||
defaults = default_settings
|
||||
|
||||
while len(path) > 1:
|
||||
key = path.pop(0)
|
||||
@@ -420,8 +501,8 @@ class Settings(object):
|
||||
else:
|
||||
return results
|
||||
|
||||
def getInt(self, path):
|
||||
value = self.get(path)
|
||||
def getInt(self, path, defaults=None):
|
||||
value = self.get(path, defaults=defaults)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -431,8 +512,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getFloat(self, path):
|
||||
value = self.get(path)
|
||||
def getFloat(self, path, defaults=None):
|
||||
value = self.get(path, defaults=defaults)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -442,8 +523,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getBoolean(self, path):
|
||||
value = self.get(path)
|
||||
def getBoolean(self, path, defaults=None):
|
||||
value = self.get(path, defaults=defaults)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
@@ -517,12 +598,13 @@ class Settings(object):
|
||||
|
||||
#~~ setter
|
||||
|
||||
def set(self, path, value, force=False):
|
||||
def set(self, path, value, force=False, defaults=None):
|
||||
if len(path) == 0:
|
||||
return
|
||||
|
||||
config = self._config
|
||||
defaults = default_settings
|
||||
if defaults is None:
|
||||
defaults = default_settings
|
||||
|
||||
while len(path) > 1:
|
||||
key = path.pop(0)
|
||||
@@ -547,9 +629,9 @@ class Settings(object):
|
||||
config[key] = value
|
||||
self._dirty = True
|
||||
|
||||
def setInt(self, path, value, force=False):
|
||||
def setInt(self, path, value, force=False, defaults=None):
|
||||
if value is None:
|
||||
self.set(path, None, force)
|
||||
self.set(path, None, force=force, defaults=defaults)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -560,9 +642,9 @@ class Settings(object):
|
||||
|
||||
self.set(path, intValue, force)
|
||||
|
||||
def setFloat(self, path, value, force=False):
|
||||
def setFloat(self, path, value, force=False, defaults=None):
|
||||
if value is None:
|
||||
self.set(path, None, force)
|
||||
self.set(path, None, force=force, defaults=defaults)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -573,13 +655,13 @@ class Settings(object):
|
||||
|
||||
self.set(path, floatValue, force)
|
||||
|
||||
def setBoolean(self, path, value, force=False):
|
||||
def setBoolean(self, path, value, force=False, defaults=None):
|
||||
if value is None or isinstance(value, bool):
|
||||
self.set(path, value, force)
|
||||
self.set(path, value, force=force, defaults=defaults)
|
||||
elif value.lower() in valid_boolean_trues:
|
||||
self.set(path, True, force)
|
||||
self.set(path, True, force=force, defaults=defaults)
|
||||
else:
|
||||
self.set(path, False, force)
|
||||
self.set(path, False, force=force, defaults=defaults)
|
||||
|
||||
def setBaseFolder(self, type, path, force=False):
|
||||
if type not in default_settings["folder"].keys():
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewModel, temperatureViewModel, controlViewModel, terminalViewModel, gcodeFilesViewModel, timelapseViewModel, gcodeViewModel, logViewModel) {
|
||||
function DataUpdater(allViewModels) {
|
||||
var self = this;
|
||||
|
||||
self.loginStateViewModel = loginStateViewModel;
|
||||
self.connectionViewModel = connectionViewModel;
|
||||
self.printerStateViewModel = printerStateViewModel;
|
||||
self.temperatureViewModel = temperatureViewModel;
|
||||
self.controlViewModel = controlViewModel;
|
||||
self.terminalViewModel = terminalViewModel;
|
||||
self.gcodeFilesViewModel = gcodeFilesViewModel;
|
||||
self.timelapseViewModel = timelapseViewModel;
|
||||
self.gcodeViewModel = gcodeViewModel;
|
||||
self.logViewModel = logViewModel;
|
||||
self.allViewModels = allViewModels;
|
||||
|
||||
self._socket = undefined;
|
||||
self._autoReconnecting = false;
|
||||
@@ -40,9 +31,28 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
|
||||
};
|
||||
|
||||
self._onclose = function() {
|
||||
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."));
|
||||
if (!$("#offline_overlay").is(":visible"))
|
||||
$("#offline_overlay").show();
|
||||
var handled = false;
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (handled == true) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (viewModel.hasOwnProperty("onServerDisconnect")) {
|
||||
if (!viewModel.onServerDisconnect()) {
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (handled) {
|
||||
return;
|
||||
}
|
||||
|
||||
showOfflineOverlay(
|
||||
gettext("Server is offline"),
|
||||
gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."),
|
||||
self.reconnect
|
||||
);
|
||||
|
||||
if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) {
|
||||
var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial];
|
||||
@@ -55,11 +65,33 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
|
||||
};
|
||||
|
||||
self._onreconnectfailed = function() {
|
||||
var handled = false;
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (handled == true) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (viewModel.hasOwnProperty("onServerDisconnect")) {
|
||||
if (!viewModel.onServerDisconnect()) {
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (handled) {
|
||||
return;
|
||||
}
|
||||
|
||||
$("#offline_overlay_title").text(gettext("Server is offline"));
|
||||
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, but you may try a manual reconnect using the button below."));
|
||||
};
|
||||
|
||||
self._onmessage = function(e) {
|
||||
for (var prop in e.data) {
|
||||
if (!e.data.hasOwnProperty(prop)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var data = e.data[prop];
|
||||
|
||||
switch (prop) {
|
||||
@@ -75,13 +107,12 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
|
||||
$("span.version").text(DISPLAY_VERSION);
|
||||
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
$("#offline_overlay").hide();
|
||||
self.logViewModel.requestData();
|
||||
self.timelapseViewModel.requestData();
|
||||
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||
self.loginStateViewModel.requestData();
|
||||
self.gcodeFilesViewModel.requestData();
|
||||
self.gcodeViewModel.reset();
|
||||
hideOfflineOverlay();
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
|
||||
viewModel.onDataUpdaterReconnect();
|
||||
}
|
||||
});
|
||||
|
||||
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
|
||||
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||
@@ -91,25 +122,19 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
|
||||
break;
|
||||
}
|
||||
case "history": {
|
||||
self.connectionViewModel.fromHistoryData(data);
|
||||
self.printerStateViewModel.fromHistoryData(data);
|
||||
self.temperatureViewModel.fromHistoryData(data);
|
||||
self.controlViewModel.fromHistoryData(data);
|
||||
self.terminalViewModel.fromHistoryData(data);
|
||||
self.timelapseViewModel.fromHistoryData(data);
|
||||
self.gcodeViewModel.fromHistoryData(data);
|
||||
self.gcodeFilesViewModel.fromCurrentData(data);
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("fromHistoryData")) {
|
||||
viewModel.fromHistoryData(data);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "current": {
|
||||
self.connectionViewModel.fromCurrentData(data);
|
||||
self.printerStateViewModel.fromCurrentData(data);
|
||||
self.temperatureViewModel.fromCurrentData(data);
|
||||
self.controlViewModel.fromCurrentData(data);
|
||||
self.terminalViewModel.fromCurrentData(data);
|
||||
self.timelapseViewModel.fromCurrentData(data);
|
||||
self.gcodeViewModel.fromCurrentData(data);
|
||||
self.gcodeFilesViewModel.fromCurrentData(data);
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("fromCurrentData")) {
|
||||
viewModel.fromCurrentData(data);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "event": {
|
||||
@@ -120,8 +145,18 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
|
||||
var gcodeUploadProgress = $("#gcode_upload_progress");
|
||||
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
|
||||
|
||||
if ((type == "UpdatedFiles" && payload.type == "gcode") || type == "MetadataAnalysisFinished") {
|
||||
gcodeFilesViewModel.requestData();
|
||||
if (type == "UpdatedFiles") {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onUpdatedFiles")) {
|
||||
viewModel.onUpdatedFiles(payload);
|
||||
}
|
||||
});
|
||||
} else if (type == "MetadataAnalysisFinished") {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onMetadataAnalysisFinished")) {
|
||||
viewModel.onMetadataAnalysisFinished(payload);
|
||||
}
|
||||
});
|
||||
} else if (type == "MovieRendering") {
|
||||
new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
|
||||
} else if (type == "MovieDone") {
|
||||
@@ -162,11 +197,19 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
|
||||
break;
|
||||
}
|
||||
case "feedbackCommandOutput": {
|
||||
self.controlViewModel.fromFeedbackCommandData(data);
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("fromFeedbackCommandData")) {
|
||||
viewModel.fromFeedbackCommandData(data);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "timelapse": {
|
||||
self.printerStateViewModel.fromTimelapseData(data);
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("fromTimelapseData")) {
|
||||
viewModel.fromTimelapseData(data);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
self.searchFunction = undefined;
|
||||
|
||||
self.allItems = [];
|
||||
0
|
||||
|
||||
self.items = ko.observableArray([]);
|
||||
self.pageSize = ko.observable(filesPerPage);
|
||||
self.currentPage = ko.observable(0);
|
||||
@@ -359,3 +359,42 @@ function pnotifyAdditionalInfo(inner) {
|
||||
+ '<div class="pnotify_more_container hide">' + inner + '</div>'
|
||||
+ '</div>';
|
||||
}
|
||||
|
||||
function ping(url, callback) {
|
||||
var img = new Image();
|
||||
var calledBack = false;
|
||||
|
||||
img.onload = function() {
|
||||
callback(true);
|
||||
calledBack = true;
|
||||
};
|
||||
img.onerror = function() {
|
||||
if (!calledBack) {
|
||||
callback(true);
|
||||
calledBack = true;
|
||||
}
|
||||
};
|
||||
img.src = url;
|
||||
setTimeout(function() {
|
||||
if (!calledBack) {
|
||||
callback(false);
|
||||
calledBack = true;
|
||||
}
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
function showOfflineOverlay(title, message, reconnectCallback) {
|
||||
if (title == undefined) {
|
||||
title = gettext("Server is offline");
|
||||
}
|
||||
|
||||
$("#offline_overlay_title").text(title);
|
||||
$("#offline_overlay_message").html(message);
|
||||
$("#offline_overlay_reconnect").click(reconnectCallback);
|
||||
if (!$("#offline_overlay").is(":visible"))
|
||||
$("#offline_overlay").show();
|
||||
}
|
||||
|
||||
function hideOfflineOverlay() {
|
||||
$("#offline_overlay").hide();
|
||||
}
|
||||
@@ -25,6 +25,46 @@ $(function() {
|
||||
gettext("Transfering file to SD")
|
||||
];
|
||||
|
||||
PNotify.prototype.options.styling = "bootstrap2";
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
// http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results
|
||||
$.ajaxSetup({
|
||||
type: 'POST',
|
||||
headers: { "cache-control": "no-cache" }
|
||||
});
|
||||
|
||||
// send the current UI API key with any request
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
//~~ Show settings - to ensure centered
|
||||
var settingsDialog = $('#settings_dialog');
|
||||
settingsDialog.on('show', function() {
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSettingsShown")) {
|
||||
viewModel.onSettingsShown();
|
||||
}
|
||||
});
|
||||
});
|
||||
settingsDialog.on('hidden', function() {
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSettingsHidden")) {
|
||||
viewModel.onSettingsHidden();
|
||||
}
|
||||
});
|
||||
});
|
||||
$('#navbar_show_settings').click(function() {
|
||||
settingsDialog.modal()
|
||||
.css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
//~~ Initialize view models
|
||||
var loginStateViewModel = new LoginStateViewModel();
|
||||
var usersViewModel = new UsersViewModel(loginStateViewModel);
|
||||
@@ -41,42 +81,46 @@ $(function() {
|
||||
var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel);
|
||||
var logViewModel = new LogViewModel(loginStateViewModel);
|
||||
|
||||
var dataUpdater = new DataUpdater(
|
||||
loginStateViewModel,
|
||||
connectionViewModel,
|
||||
printerStateViewModel,
|
||||
temperatureViewModel,
|
||||
controlViewModel,
|
||||
terminalViewModel,
|
||||
gcodeFilesViewModel,
|
||||
timelapseViewModel,
|
||||
gcodeViewModel,
|
||||
logViewModel
|
||||
);
|
||||
var viewModelMap = {
|
||||
loginStateViewModel: loginStateViewModel,
|
||||
usersViewModel: usersViewModel,
|
||||
settingsViewModel: settingsViewModel,
|
||||
connectionViewModel: connectionViewModel,
|
||||
timelapseViewModel: timelapseViewModel,
|
||||
printerStateViewModel: printerStateViewModel,
|
||||
appearanceViewModel: appearanceViewModel,
|
||||
temperatureViewModel: temperatureViewModel,
|
||||
controlViewModel: controlViewModel,
|
||||
terminalViewModel: terminalViewModel,
|
||||
gcodeFilesViewModel: gcodeFilesViewModel,
|
||||
gcodeViewModel: gcodeViewModel,
|
||||
navigationViewModel: navigationViewModel,
|
||||
logViewModel: logViewModel
|
||||
};
|
||||
|
||||
PNotify.prototype.options.styling = "bootstrap2";
|
||||
var allViewModels = _.values(viewModelMap);
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
// http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results
|
||||
$.ajaxSetup({
|
||||
type: 'POST',
|
||||
headers: { "cache-control": "no-cache" }
|
||||
var additionalViewModels = [];
|
||||
_.each(ADDITIONAL_VIEWMODELS, function(viewModel) {
|
||||
var viewModelClass = viewModel[0];
|
||||
var viewModelParameters = viewModel[1];
|
||||
var viewModelBindTarget = viewModel[2];
|
||||
|
||||
var constructorParameters = [];
|
||||
_.each(viewModelParameters, function(parameter) {
|
||||
if (_.has(viewModelMap, parameter)) {
|
||||
constructorParameters.push(viewModelMap[parameter]);
|
||||
} else {
|
||||
constructorParameters.push(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
var viewModelInstance = new viewModelClass(constructorParameters);
|
||||
additionalViewModels.push([viewModelInstance, viewModelBindTarget]);
|
||||
allViewModels.push(viewModelInstance);
|
||||
});
|
||||
|
||||
// send the current UI API key with any request
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
//~~ Show settings - to ensure centered
|
||||
$('#navbar_show_settings').click(function() {
|
||||
$('#settings_dialog').modal()
|
||||
.css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
return false;
|
||||
});
|
||||
var dataUpdater = new DataUpdater(allViewModels);
|
||||
|
||||
//~~ Temperature
|
||||
|
||||
@@ -287,9 +331,6 @@ $(function() {
|
||||
}, 100);
|
||||
});
|
||||
|
||||
//~~ Offline overlay
|
||||
$("#offline_overlay_reconnect").click(function() {dataUpdater.reconnect()});
|
||||
|
||||
//~~ Underscore setup
|
||||
|
||||
_.mixin(_.str.exports());
|
||||
@@ -331,37 +372,62 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
ko.applyBindings(connectionViewModel, document.getElementById("connection_accordion"));
|
||||
ko.applyBindings(printerStateViewModel, document.getElementById("state_accordion"));
|
||||
ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_accordion"));
|
||||
ko.applyBindings(temperatureViewModel, document.getElementById("temp"));
|
||||
ko.applyBindings(controlViewModel, document.getElementById("control"));
|
||||
ko.applyBindings(terminalViewModel, document.getElementById("term"));
|
||||
var gcode = document.getElementById("gcode");
|
||||
if (gcode) {
|
||||
gcodeViewModel.initialize();
|
||||
ko.applyBindings(gcodeViewModel, gcode);
|
||||
}
|
||||
ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
|
||||
ko.applyBindings(navigationViewModel, document.getElementById("navbar"));
|
||||
ko.applyBindings(appearanceViewModel, document.getElementsByTagName("head")[0]);
|
||||
ko.applyBindings(printerStateViewModel, document.getElementById("drop_overlay"));
|
||||
ko.applyBindings(logViewModel, document.getElementById("logs"));
|
||||
ko.bindingHandlers.invisible = {
|
||||
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
if (!valueAccessor()) return;
|
||||
ko.bindingHandlers.style.update(element, function() {
|
||||
return { visibility: 'hidden' };
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
var timelapseElement = document.getElementById("timelapse");
|
||||
if (timelapseElement) {
|
||||
ko.applyBindings(timelapseViewModel, timelapseElement);
|
||||
}
|
||||
settingsViewModel.requestData(function() {
|
||||
ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
|
||||
|
||||
ko.applyBindings(connectionViewModel, document.getElementById("connection_accordion"));
|
||||
ko.applyBindings(printerStateViewModel, document.getElementById("state_accordion"));
|
||||
ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_accordion"));
|
||||
ko.applyBindings(temperatureViewModel, document.getElementById("temp"));
|
||||
ko.applyBindings(controlViewModel, document.getElementById("control"));
|
||||
ko.applyBindings(terminalViewModel, document.getElementById("term"));
|
||||
var gcode = document.getElementById("gcode");
|
||||
if (gcode) {
|
||||
gcodeViewModel.initialize();
|
||||
ko.applyBindings(gcodeViewModel, gcode);
|
||||
}
|
||||
//ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
|
||||
ko.applyBindings(navigationViewModel, document.getElementById("navbar"));
|
||||
ko.applyBindings(appearanceViewModel, document.getElementsByTagName("head")[0]);
|
||||
ko.applyBindings(printerStateViewModel, document.getElementById("drop_overlay"));
|
||||
ko.applyBindings(logViewModel, document.getElementById("logs"));
|
||||
|
||||
var timelapseElement = document.getElementById("timelapse");
|
||||
if (timelapseElement) {
|
||||
ko.applyBindings(timelapseViewModel, timelapseElement);
|
||||
}
|
||||
|
||||
// apply bindings and signal startup
|
||||
_.each(additionalViewModels, function(additionalViewModel) {
|
||||
if (additionalViewModel[0].hasOwnProperty("onBeforeBinding")) {
|
||||
additionalViewModel[0].onBeforeBinding();
|
||||
}
|
||||
|
||||
// model instance, target container
|
||||
ko.applyBindings(additionalViewModel[0], additionalViewModel[1]);
|
||||
|
||||
if (additionalViewModel[0].hasOwnProperty("onAfterBinding")) {
|
||||
additionalViewModel[0].onAfterBinding();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
//~~ startup commands
|
||||
|
||||
loginStateViewModel.requestData();
|
||||
connectionViewModel.requestData();
|
||||
controlViewModel.requestData();
|
||||
gcodeFilesViewModel.requestData();
|
||||
timelapseViewModel.requestData();
|
||||
settingsViewModel.requestData();
|
||||
logViewModel.requestData();
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onStartup")) {
|
||||
viewModel.onStartup();
|
||||
}
|
||||
});
|
||||
|
||||
loginStateViewModel.subscribe(function(change, data) {
|
||||
if ("login" == change) {
|
||||
|
||||
@@ -120,4 +120,8 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
@@ -236,6 +236,9 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
|
||||
default:
|
||||
return "customControls_emptyTemplate";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
@@ -304,5 +304,22 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
|
||||
}
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUpdatedFiles = function(payload) {
|
||||
if (payload.type == "gcode") {
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
self.onMetadataAnalysisFinished = function(payload) {
|
||||
self.requestData();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +332,7 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
|
||||
}
|
||||
output.push(gettext("Estimated print time") + ": " + formatDuration(model.printTime));
|
||||
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
|
||||
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext(printed) + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
|
||||
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
|
||||
|
||||
self.ui_modelInfo(output.join("<br>"));
|
||||
|
||||
@@ -405,4 +405,8 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
|
||||
GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.reset();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -49,7 +49,7 @@ function LogViewModel(loginStateViewModel) {
|
||||
return;
|
||||
|
||||
self.listHelper.updateItems(files);
|
||||
}
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
$.ajax({
|
||||
@@ -58,5 +58,13 @@ function LogViewModel(loginStateViewModel) {
|
||||
dataType: "json",
|
||||
success: self.requestData
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
@@ -29,7 +29,7 @@ function LoginStateViewModel() {
|
||||
data: {"passive": true},
|
||||
success: self.fromResponse
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
if (response && response.name) {
|
||||
@@ -85,5 +85,13 @@ function LoginStateViewModel() {
|
||||
self.fromResponse(response);
|
||||
}
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
@@ -19,8 +19,9 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
|
||||
{key: "green", name: gettext("green")},
|
||||
{key: "blue", name: gettext("blue")},
|
||||
{key: "violet", name: gettext("violet")},
|
||||
{key: "black", name: gettext("black")},
|
||||
{key: "black", name: gettext("black")}
|
||||
]);
|
||||
|
||||
self.appearance_colorName = function(color) {
|
||||
switch (color) {
|
||||
case "red":
|
||||
@@ -166,6 +167,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
|
||||
|
||||
self.terminalFilters = ko.observableArray([]);
|
||||
|
||||
self.settings = undefined;
|
||||
|
||||
self.addTemperatureProfile = function() {
|
||||
self.temperature_profiles.push({name: "New", extruder:0, bed:0});
|
||||
};
|
||||
@@ -220,6 +223,12 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
if (self.settings === undefined) {
|
||||
self.settings = ko.mapping.fromJS(response);
|
||||
} else {
|
||||
ko.mapping.fromJS(response, self.settings);
|
||||
}
|
||||
|
||||
self.api_enabled(response.api.enabled);
|
||||
self.api_key(response.api.key);
|
||||
self.api_allowCrossOrigin(response.api.allowCrossOrigin);
|
||||
@@ -284,7 +293,9 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
|
||||
};
|
||||
|
||||
self.saveData = function() {
|
||||
var data = {
|
||||
var data = ko.mapping.toJS(self.settings);
|
||||
|
||||
data = _.extend(data, {
|
||||
"api" : {
|
||||
"enabled": self.api_enabled(),
|
||||
"key": self.api_key(),
|
||||
@@ -354,7 +365,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
|
||||
"config": self.cura_config()
|
||||
},
|
||||
"terminalFilters": self.terminalFilters()
|
||||
};
|
||||
});
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "settings",
|
||||
@@ -367,6 +378,6 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) {
|
||||
$("#settings_dialog").modal("hide");
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
@@ -94,15 +94,15 @@ function TimelapseViewModel(loginStateViewModel) {
|
||||
|
||||
self.persist(false);
|
||||
self.isDirty(false);
|
||||
}
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
}
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
}
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
@@ -112,7 +112,7 @@ function TimelapseViewModel(loginStateViewModel) {
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
}
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
$.ajax({
|
||||
@@ -121,25 +121,33 @@ function TimelapseViewModel(loginStateViewModel) {
|
||||
dataType: "json",
|
||||
success: self.requestData
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.save = function(data, event) {
|
||||
var data = {
|
||||
var payload = {
|
||||
"type": self.timelapseType(),
|
||||
"postRoll": self.timelapsePostRoll(),
|
||||
"save": self.persist()
|
||||
}
|
||||
};
|
||||
|
||||
if (self.timelapseType() == "timed") {
|
||||
data["interval"] = self.timelapseTimedInterval();
|
||||
payload["interval"] = self.timelapseTimedInterval();
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: data,
|
||||
data: payload,
|
||||
success: self.fromResponse
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
window.BABEL_TO_LOAD_nl = {"locale": "nl", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-09-01 20:11+0000\nLast-Translator: leon.bek <leon.bek@gmail.com>\nLanguage-Team: Dutch (http://www.transifex.com/projects/p/octoprint/language/nl/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Resterende print tijd", "Proceed": "Verder", "Timelapse Temp Folder": "Tijdelijke timelapse map", "Title": "Titel", "Only show files stored locally": "Laat alleen lokale bestanden zien", "yellow": "geel", "Path to Cura": "Lokatie van Cura", "Action": "Actie", "Passwords do not match": "Wachtwoorden komen niet overeen", "Sort by name": "Sorteer op naam", "Save connection settings": "Verbindings instellingen opslaan", "Rendering timelapse": "Renderen van timelapse", "Cura": "Cura", "Files": "Bestanden", "Bed Size": "Platform grootte", "Always assume SD card is present": "Neem aan dat SD kaart altijd aanwezig is", "Load and Print": "Laad en print", "Sending file to SD": "Verstuur bestand naar SD", "Number of Extruders": "Aantal Extruders", "black": "zwart", "Last Printed": "Laats geprint", "Sourcecode": "Broncode", "Estimated layer height": "Geschatte laag hooge", "You are now logged out": "Je bent nu uitgelogd", "Uploaded": "Geupload", "Opening serial port": "Openen van seri\u00eble poort", "New timelapse %(movie_basename)s is done rendering.": "Nieuwe timelapse %(movie_basename)s is gereed", "Invert control": "Bedieining spiegelen", "Webcam": "Webcam", "Remember me": "Onthoud me", "Enable GCode Visualizer": "Schakel GCode Visualizer in", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "De server lijkt offline te zijn, dat wil zeggen dat ik er geen reactie van krijg. Ik zal proberen om <strong>gedurende een paar minuten</strong> opnieuw te verbinden. Maar je bent op elk moment vrij om handmatig proberen te verbinden met onderstaande knop.", "Rendering failed": "Renderen mislukt", "Upload Folder": "Lokatie voor Uploads", "descending": "Aflopend", "X": "X", "Add user": "Gebruiker toevoegen", "GCODE commands in layer": "GCODE commando's in laag", "Estimated print time": "Geschatte print tijd", "Serial Connection": "Seri\u00eble verbinding", "Control": "Controle", "Password": "Wachtwoord", "Also show next layer": "Laat ook volgende laag zien", "Print Time": "Print tijd", "Sort by file size": "Sorteer op bestands grootte", "Machine State": "Machine status", "default": "Standaard", "API": "API", "Printing from SD": "Printen vanaf SD", "Terminal filters": "Terminal filters", "Change password for user \"%(user)s\"": "Verander wachtwoord voor gebruiker \"%(user)s\"", "Enable Temperature Graph": "Schakel temperatuur grafiek in", "Delete user": "Gebruiker verwijderen", "Confirm Password": "Bevestig wachtwoord", "Disconnect": "Verbreken", "Slicing done": "Slicing klaar", "Initialize SD card": "Formateer SD kaart", "System": "Systeem", "Send": "Verstuur", "State": "Status", "Version": "Versie", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Probeer opnieuw te verbinden", "Streaming done": "Streaming klaar", "violet": "violet", "Print": "Print", "Layer count": "Aantal lagen", "OctoPrint Settings": "OctoPrint instellingen", "Are you sure?": "Weet je het zeker?", "blue": "blauw", "Printer": "Printer", "Tool": "Gereedschap", "Settings": "Instellingen", "Path to FFMPEG": "Lokatie van FFMPEG", "Upload to SD": "Uploaden naar SD", "The command \"%(command)s\" could not be executed.": "Het commando \"%(command)s\" kon niet uitgevoerd worden.", "Printed": "Geprint", "Layer number": "Laag nummer", "Sync with job progress": "Synchroniseer met taak voortgang", "Circular": "Cirkelvormig", "Total filament used": "Totaal gebruikte filament", "red": "rood", "Save as default": "Stel in als standaard", "Slicing ...": "Slicing ...", "Last Print Time": "Laatste print tijd", "Target": "Doel", "Streaming ...": "Streaming ...", "Logout successful": "Uitloggen succesvol", "Now rendering timelapse %(movie_basename)s": "Aan het renderen van timelapse %(movie_basename)s", "Documentation": "Documentatie", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "Oplopend", "Model size": "Model grootte", "Temperatures": "Temperaturen", "visited": "bezocht", "Timed": "Getimed", "Edit user \"%(user)s\"": "Bewerk gebruiker \"%(user)s\"", "Snapshot URL": "Snapshot URL", "Release SD card": "Geef SD kaart vrij", "Server is offline": "Server is offline", "Log communication to serial.log (might negatively impact
Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
window.BABEL_TO_LOAD_no = {"locale": "nb_NO", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-09-03 16:07+0000\nLast-Translator: lobster2b <ch.eikefjord@gmail.com>\nLanguage-Team: Norwegian (http://www.transifex.com/projects/p/octoprint/language/no/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Gjenst\u00e5ende utskriftstid", "Proceed": "Fortsett", "Timelapse Temp Folder": "Timelapse midlertidig mappe", "Title": "Tittel", "Only show files stored locally": "Bare vis filer lagret lokalt", "yellow": "gul", "Path to Cura": "Sti til Cura", "Action": "Handling", "Passwords do not match": "Passordet er ikke likt", "Sort by name": "Sorter ved navn", "Save connection settings": "Lagre tilkoblingsinnstillinger", "Rendering timelapse": "Sammensetter timelapse", "Cura": "Cura", "Files": "Filer", "Bed Size": "Plattformst\u00f8rrelse", "Always assume SD card is present": "Alltid anta at minnekort er p\u00e5 plass", "Load and Print": "Last og skriv ut", "Sending file to SD": "Sender fil til minnekort", "Number of Extruders": "Antall dyser", "black": "svart", "Last Printed": "Sist utskrevet", "Sourcecode": "Kildekode", "Estimated layer height": "Estimert lagh\u00f8yde", "You are now logged out": "Du er n\u00e5 logget ut", "Uploaded": "Opplastet", "Opening serial port": "\u00c5pner serialport", "New timelapse %(movie_basename)s is done rendering.": "Ny timelapse for %(movie_basename)s er ferdig sammensatt", "Invert control": "Inverter kontroller", "Webcam": "Nettkamera", "Remember me": "Husk meg", "Enable GCode Visualizer": "Aktiver GCode framviser", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Serveren er tilsynelatende frakoblet, i det minste f\u00e5r jeg ikke noen respons fra den. Jeg pr\u00f8ver \u00e5 koble til automatisk <strong>over de neste minuttene</strong>, du kan pr\u00f8ve en manuell oppkobling n\u00e5r du \u00f8nsker det ved \u00e5 bruke knappen nedenfor.", "Rendering failed": "Sammensetting feilet", "Upload Folder": "Opplastningsmappe", "descending": "synkende", "X": "X", "Add user": "Legg til bruker", "GCODE commands in layer": "GCODE kommandoer i lag", "Estimated print time": "Beregnet printtid", "Serial Connection": "Seriell kontakt", "Control": "Kontroll", "Password": "Passord", "Also show next layer": "Ogs\u00e5 vis neste lag", "Print Time": "Utskriftstid", "Sort by file size": "Sorter filer etter st\u00f8rrelse", "Machine State": "Maskintilstand", "default": "standard", "API": "API", "Printing from SD": "Utskrift fra minnekort", "Terminal filters": "Terminal filtre", "Change password for user \"%(user)s\"": "Endre passord for bruker \"%(user)s\"", "Enable Temperature Graph": "Aktiver temperaturgraf", "Delete user": "Slett bruker", "Confirm Password": "Bekreft passord", "Disconnect": "Koble fra", "Slicing done": "Slicing ferdig", "Initialize SD card": "Start minnekortet", "System": "System", "Send": "Send", "State": "Tilstand", "Version": "Versjon", "YYYY-MM-DD HH:mm": "YYYY-MM-DD HH:mm", "Attempt to reconnect": "Fors\u00f8k \u00e5 koble til p\u00e5 nytt", "Streaming done": "Streaming ferdig", "violet": "fiolett", "Print": "Utskriv", "Layer count": "Antall lag", "OctoPrint Settings": "OctoPrint innstillinger", "Are you sure?": "Er du sikker?", "blue": "bl\u00e5", "Printer": "Printer", "Tool": "Verkt\u00f8y", "Settings": "Innstillinger", "Path to FFMPEG": "Sti til FFMPEG", "Upload to SD": "Last opp til minnekort", "The command \"%(command)s\" could not be executed.": "Kommando \"%(command)s\" mislykkes", "Printed": "Utskrevet", "Layer number": "Lag nummer", "Sync with job progress": "Synkroniser med jobbprogresjon", "Circular": "Sirkul\u00e6r", "Total filament used": "Totalt tr\u00e5dforbruk", "red": "r\u00f8d", "Save as default": "Lagre som standard", "Slicing ...": "Slicing ...", "Last Print Time": "Siste utskriftstid", "Target": "M\u00e5l", "Streaming ...": "Streaming ...", "Logout successful": "Logg ut vellykket", "Now rendering timelapse %(movie_basename)s": "Sammensetter timelapse %(movie_basename)s", "Documentation": "Dokumentasjon", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Last opp", "ascending": "stigende", "Model size": "Modellst\u00f8rrelse", "Temperatures": "Temperaturer", "visited": "bes\u00f8kt", "Timed": "Tidtakes", "Edit user \"%(user)s\"": "Endre bruker \"%(user)s\"", "Snapshot URL": "Hurtigbilde URL", "Release SD card": "L\u00f8s ut minnekort", "Server is offline": "Server er frakoblet", "Log communication to serial.log (might negatively imLine truncated
|
||||
@@ -0,0 +1,22 @@
|
||||
/// Knockout Mapping plugin v2.4.1
|
||||
/// (c) 2013 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/
|
||||
/// License: MIT (http://www.opensource.org/licenses/mit-license.php)
|
||||
(function(e){"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?e(require("knockout"),exports):"function"===typeof define&&define.amd?define(["knockout","exports"],e):e(ko,ko.mapping={})})(function(e,f){function y(b,c){var a,d;for(d in c)if(c.hasOwnProperty(d)&&c[d])if(a=f.getType(b[d]),d&&b[d]&&"array"!==a&&"string"!==a)y(b[d],c[d]);else if("array"===f.getType(b[d])&&"array"===f.getType(c[d])){a=b;for(var e=d,l=b[d],n=c[d],t={},g=l.length-1;0<=g;--g)t[l[g]]=l[g];for(g=
|
||||
n.length-1;0<=g;--g)t[n[g]]=n[g];l=[];n=void 0;for(n in t)l.push(t[n]);a[e]=l}else b[d]=c[d]}function E(b,c){var a={};y(a,b);y(a,c);return a}function z(b,c){for(var a=E({},b),e=L.length-1;0<=e;e--){var f=L[e];a[f]&&(a[""]instanceof Object||(a[""]={}),a[""][f]=a[f],delete a[f])}c&&(a.ignore=h(c.ignore,a.ignore),a.include=h(c.include,a.include),a.copy=h(c.copy,a.copy),a.observe=h(c.observe,a.observe));a.ignore=h(a.ignore,j.ignore);a.include=h(a.include,j.include);a.copy=h(a.copy,j.copy);a.observe=h(a.observe,
|
||||
j.observe);a.mappedProperties=a.mappedProperties||{};a.copiedProperties=a.copiedProperties||{};return a}function h(b,c){"array"!==f.getType(b)&&(b="undefined"===f.getType(b)?[]:[b]);"array"!==f.getType(c)&&(c="undefined"===f.getType(c)?[]:[c]);return e.utils.arrayGetDistinctValues(b.concat(c))}function F(b,c,a,d,k,l,n){var t="array"===f.getType(e.utils.unwrapObservable(c));l=l||"";if(f.isMapped(b)){var g=e.utils.unwrapObservable(b)[p];a=E(g,a)}var j=n||k,h=function(){return a[d]&&a[d].create instanceof
|
||||
Function},x=function(b){var f=G,g=e.dependentObservable;e.dependentObservable=function(a,b,c){c=c||{};a&&"object"==typeof a&&(c=a);var d=c.deferEvaluation,M=!1;c.deferEvaluation=!0;a=new H(a,b,c);if(!d){var g=a,d=e.dependentObservable;e.dependentObservable=H;a=e.isWriteableObservable(g);e.dependentObservable=d;d=H({read:function(){M||(e.utils.arrayRemoveItem(f,g),M=!0);return g.apply(g,arguments)},write:a&&function(a){return g(a)},deferEvaluation:!0});d.__DO=g;a=d;f.push(a)}return a};e.dependentObservable.fn=
|
||||
H.fn;e.computed=e.dependentObservable;b=e.utils.unwrapObservable(k)instanceof Array?a[d].create({data:b||c,parent:j,skip:N}):a[d].create({data:b||c,parent:j});e.dependentObservable=g;e.computed=e.dependentObservable;return b},u=function(){return a[d]&&a[d].update instanceof Function},v=function(b,f){var g={data:f||c,parent:j,target:e.utils.unwrapObservable(b)};e.isWriteableObservable(b)&&(g.observable=b);return a[d].update(g)};if(n=I.get(c))return n;d=d||"";if(t){var t=[],s=!1,m=function(a){return a};
|
||||
a[d]&&a[d].key&&(m=a[d].key,s=!0);e.isObservable(b)||(b=e.observableArray([]),b.mappedRemove=function(a){var c="function"==typeof a?a:function(b){return b===m(a)};return b.remove(function(a){return c(m(a))})},b.mappedRemoveAll=function(a){var c=C(a,m);return b.remove(function(a){return-1!=e.utils.arrayIndexOf(c,m(a))})},b.mappedDestroy=function(a){var c="function"==typeof a?a:function(b){return b===m(a)};return b.destroy(function(a){return c(m(a))})},b.mappedDestroyAll=function(a){var c=C(a,m);return b.destroy(function(a){return-1!=
|
||||
e.utils.arrayIndexOf(c,m(a))})},b.mappedIndexOf=function(a){var c=C(b(),m);a=m(a);return e.utils.arrayIndexOf(c,a)},b.mappedGet=function(a){return b()[b.mappedIndexOf(a)]},b.mappedCreate=function(a){if(-1!==b.mappedIndexOf(a))throw Error("There already is an object with the key that you specified.");var c=h()?x(a):a;u()&&(a=v(c,a),e.isWriteableObservable(c)?c(a):c=a);b.push(c);return c});n=C(e.utils.unwrapObservable(b),m).sort();g=C(c,m);s&&g.sort();s=e.utils.compareArrays(n,g);n={};var J,A=e.utils.unwrapObservable(c),
|
||||
y={},z=!0,g=0;for(J=A.length;g<J;g++){var r=m(A[g]);if(void 0===r||r instanceof Object){z=!1;break}y[r]=A[g]}var A=[],B=0,g=0;for(J=s.length;g<J;g++){var r=s[g],q,w=l+"["+g+"]";switch(r.status){case "added":var D=z?y[r.value]:K(e.utils.unwrapObservable(c),r.value,m);q=F(void 0,D,a,d,b,w,k);h()||(q=e.utils.unwrapObservable(q));w=O(e.utils.unwrapObservable(c),D,n);q===N?B++:A[w-B]=q;n[w]=!0;break;case "retained":D=z?y[r.value]:K(e.utils.unwrapObservable(c),r.value,m);q=K(b,r.value,m);F(q,D,a,d,b,w,
|
||||
k);w=O(e.utils.unwrapObservable(c),D,n);A[w]=q;n[w]=!0;break;case "deleted":q=K(b,r.value,m)}t.push({event:r.status,item:q})}b(A);a[d]&&a[d].arrayChanged&&e.utils.arrayForEach(t,function(b){a[d].arrayChanged(b.event,b.item)})}else if(P(c)){b=e.utils.unwrapObservable(b);if(!b){if(h())return s=x(),u()&&(s=v(s)),s;if(u())return v(s);b={}}u()&&(b=v(b));I.save(c,b);if(u())return b;Q(c,function(d){var f=l.length?l+"."+d:d;if(-1==e.utils.arrayIndexOf(a.ignore,f))if(-1!=e.utils.arrayIndexOf(a.copy,f))b[d]=
|
||||
c[d];else if("object"!=typeof c[d]&&"array"!=typeof c[d]&&0<a.observe.length&&-1==e.utils.arrayIndexOf(a.observe,f))b[d]=c[d],a.copiedProperties[f]=!0;else{var g=I.get(c[d]),k=F(b[d],c[d],a,d,b,f,b),g=g||k;if(0<a.observe.length&&-1==e.utils.arrayIndexOf(a.observe,f))b[d]=g(),a.copiedProperties[f]=!0;else{if(e.isWriteableObservable(b[d])){if(g=e.utils.unwrapObservable(g),b[d]()!==g)b[d](g)}else g=void 0===b[d]?g:e.utils.unwrapObservable(g),b[d]=g;a.mappedProperties[f]=!0}}})}else switch(f.getType(c)){case "function":u()?
|
||||
e.isWriteableObservable(c)?(c(v(c)),b=c):b=v(c):b=c;break;default:if(e.isWriteableObservable(b))return q=u()?v(b):e.utils.unwrapObservable(c),b(q),q;h()||u();b=h()?x():e.observable(e.utils.unwrapObservable(c));u()&&b(v(b))}return b}function O(b,c,a){for(var d=0,e=b.length;d<e;d++)if(!0!==a[d]&&b[d]===c)return d;return null}function R(b,c){var a;c&&(a=c(b));"undefined"===f.getType(a)&&(a=b);return e.utils.unwrapObservable(a)}function K(b,c,a){b=e.utils.unwrapObservable(b);for(var d=0,f=b.length;d<
|
||||
f;d++){var l=b[d];if(R(l,a)===c)return l}throw Error("When calling ko.update*, the key '"+c+"' was not found!");}function C(b,c){return e.utils.arrayMap(e.utils.unwrapObservable(b),function(a){return c?R(a,c):a})}function Q(b,c){if("array"===f.getType(b))for(var a=0;a<b.length;a++)c(a);else for(a in b)c(a)}function P(b){var c=f.getType(b);return("object"===c||"array"===c)&&null!==b}function T(){var b=[],c=[];this.save=function(a,d){var f=e.utils.arrayIndexOf(b,a);0<=f?c[f]=d:(b.push(a),c.push(d))};
|
||||
this.get=function(a){a=e.utils.arrayIndexOf(b,a);return 0<=a?c[a]:void 0}}function S(){var b={},c=function(a){var c;try{c=a}catch(e){c="$$$"}a=b[c];void 0===a&&(a=new T,b[c]=a);return a};this.save=function(a,b){c(a).save(a,b)};this.get=function(a){return c(a).get(a)}}var p="__ko_mapping__",H=e.dependentObservable,B=0,G,I,L=["create","update","key","arrayChanged"],N={},x={include:["_destroy"],ignore:[],copy:[],observe:[]},j=x;f.isMapped=function(b){return(b=e.utils.unwrapObservable(b))&&b[p]};f.fromJS=
|
||||
function(b){if(0==arguments.length)throw Error("When calling ko.fromJS, pass the object you want to convert.");try{B++||(G=[],I=new S);var c,a;2==arguments.length&&(arguments[1][p]?a=arguments[1]:c=arguments[1]);3==arguments.length&&(c=arguments[1],a=arguments[2]);a&&(c=E(c,a[p]));c=z(c);var d=F(a,b,c);a&&(d=a);if(!--B)for(;G.length;){var e=G.pop();e&&(e(),e.__DO.throttleEvaluation=e.throttleEvaluation)}d[p]=E(d[p],c);return d}catch(f){throw B=0,f;}};f.fromJSON=function(b){var c=e.utils.parseJson(b);
|
||||
arguments[0]=c;return f.fromJS.apply(this,arguments)};f.updateFromJS=function(){throw Error("ko.mapping.updateFromJS, use ko.mapping.fromJS instead. Please note that the order of parameters is different!");};f.updateFromJSON=function(){throw Error("ko.mapping.updateFromJSON, use ko.mapping.fromJSON instead. Please note that the order of parameters is different!");};f.toJS=function(b,c){j||f.resetDefaultOptions();if(0==arguments.length)throw Error("When calling ko.mapping.toJS, pass the object you want to convert.");
|
||||
if("array"!==f.getType(j.ignore))throw Error("ko.mapping.defaultOptions().ignore should be an array.");if("array"!==f.getType(j.include))throw Error("ko.mapping.defaultOptions().include should be an array.");if("array"!==f.getType(j.copy))throw Error("ko.mapping.defaultOptions().copy should be an array.");c=z(c,b[p]);return f.visitModel(b,function(a){return e.utils.unwrapObservable(a)},c)};f.toJSON=function(b,c){var a=f.toJS(b,c);return e.utils.stringifyJson(a)};f.defaultOptions=function(){if(0<arguments.length)j=
|
||||
arguments[0];else return j};f.resetDefaultOptions=function(){j={include:x.include.slice(0),ignore:x.ignore.slice(0),copy:x.copy.slice(0)}};f.getType=function(b){if(b&&"object"===typeof b){if(b.constructor===Date)return"date";if(b.constructor===Array)return"array"}return typeof b};f.visitModel=function(b,c,a){a=a||{};a.visitedObjects=a.visitedObjects||new S;var d,k=e.utils.unwrapObservable(b);if(P(k))a=z(a,k[p]),c(b,a.parentName),d="array"===f.getType(k)?[]:{};else return c(b,a.parentName);a.visitedObjects.save(b,
|
||||
d);var l=a.parentName;Q(k,function(b){if(!(a.ignore&&-1!=e.utils.arrayIndexOf(a.ignore,b))){var j=k[b],g=a,h=l||"";"array"===f.getType(k)?l&&(h+="["+b+"]"):(l&&(h+="."),h+=b);g.parentName=h;if(!(-1===e.utils.arrayIndexOf(a.copy,b)&&-1===e.utils.arrayIndexOf(a.include,b)&&k[p]&&k[p].mappedProperties&&!k[p].mappedProperties[b]&&k[p].copiedProperties&&!k[p].copiedProperties[b]&&"array"!==f.getType(k)))switch(f.getType(e.utils.unwrapObservable(j))){case "object":case "array":case "undefined":g=a.visitedObjects.get(j);
|
||||
d[b]="undefined"!==f.getType(g)?g:f.visitModel(j,c,a);break;default:d[b]=c(j,a.parentName)}}});return d}});
|
||||
@@ -3,7 +3,7 @@
|
||||
<div id="offline_overlay_wrapper">
|
||||
<div class="container">
|
||||
<div class="hero-unit">
|
||||
<h1>{{ _('Server is offline') }}</h1>
|
||||
<h1 id="offline_overlay_title">{{ _('Server is offline') }}</h1>
|
||||
<p id="offline_overlay_message"></p>
|
||||
<p>
|
||||
<a class="btn btn-primary btn-large" id="offline_overlay_reconnect">{{ _('Attempt to reconnect') }}</a>
|
||||
|
||||
@@ -13,11 +13,32 @@
|
||||
<link href="{{ url_for('static', filename='css/font-awesome.min.css') }}" rel="stylesheet" media="screen">
|
||||
<link href="{{ url_for('static', filename='css/jquery.fileupload-ui.css') }}" rel="stylesheet" media="screen">
|
||||
<link href="{{ url_for('static', filename='css/pnotify.min.css') }}" rel="stylesheet" media="screen">
|
||||
|
||||
{% if stylesheet == "less" %}
|
||||
<link href="{{ url_for('static', filename='less/octoprint.less') }}" rel="stylesheet/less" type="text/css" media="screen">
|
||||
|
||||
<!-- Plugin files -->
|
||||
{% for name, assets in assetPlugins.items() %}
|
||||
{% if "less" in assets %}
|
||||
{% for asset in assets["less"] %}
|
||||
<link href="{{ url_for('plugin_assets', name=name, filename=asset) }}" rel="stylesheet/less" type="text/css" media="screen">
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<!-- /Plugin files -->
|
||||
|
||||
<script src="{{ url_for('static', filename='js/lib/less.min.js') }}" type="text/javascript"></script>
|
||||
{% else %}
|
||||
<link href="{{ url_for('static', filename='css/octoprint.css') }}" rel="stylesheet" type="text/css" media="screen">
|
||||
<!-- Plugin files -->
|
||||
{% for name, assets in assetPlugins.items() %}
|
||||
{% if "css" in assets %}
|
||||
{% for asset in assets["css"] %}
|
||||
<link href="{{ url_for('plugin_assets', name=name, filename=asset) }}" rel="stylesheet" type="text/css" media="screen">
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<!-- /Plugin files -->
|
||||
{% endif %}
|
||||
|
||||
<script lang="javascript">
|
||||
@@ -44,6 +65,8 @@
|
||||
var VERSION = "{{ version }}";
|
||||
var DISPLAY_VERSION = "{{ display_version }}";
|
||||
var LOCALE = "{{ g.locale }}";
|
||||
|
||||
var ADDITIONAL_VIEWMODELS = [];
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
@@ -609,6 +632,7 @@
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/underscore-min.js') }}"></script>
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/underscore.string.min.js') }}"></script>
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/knockout.js') }}"></script>
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/knockout.mapping-latest.js') }}"></script>
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/babel.js') }}"></script>
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/avltree.js') }}"></script>
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/lib/bootstrap/bootstrap.js') }}"></script>
|
||||
@@ -647,6 +671,16 @@
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/users.js') }}"></script>
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/log.js') }}"></script>
|
||||
|
||||
<!-- Plugin files -->
|
||||
{% for name, assets in assetPlugins.items() %}
|
||||
{% if "js" in assets %}
|
||||
{% for asset in assets["js"] %}
|
||||
<script type="text/javascript" src="{{ url_for('plugin_assets', name=name, filename=asset) }}"></script>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<!-- /Plugin files -->
|
||||
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/app/dataupdater.js') }}"></script>
|
||||
<script type="text/javascript" src="{{ url_for('static', filename='js/app/helpers.js') }}"></script>
|
||||
|
||||
|
||||
@@ -21,6 +21,14 @@
|
||||
<li><a href="#settings_folder" data-toggle="tab">{{ _('Folders') }}</a></li>
|
||||
<li><a href="#settings_appearance" data-toggle="tab">{{ _('Appearance') }}</a></li>
|
||||
<li><a href="#settings_logs" data-toggle="tab">{{ _('Logs') }}</a></li>
|
||||
{% if settingsPlugins %}
|
||||
<li class="nav-header">Plugins</li>
|
||||
{% for plugin_name, vars in settingsPlugins.items() %}
|
||||
{% if vars._settings_menu_entry %}
|
||||
<li><a href="#settings_plugin_{{ plugin_name }}" data-toggle="tab">{{ vars._settings_menu_entry }}</a></li>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
</ul>
|
||||
|
||||
<div class="tab-content span8">
|
||||
@@ -621,6 +629,12 @@
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% for plugin_name, vars in settingsPlugins.items() %}
|
||||
<div class="tab-pane" id="settings_plugin_{{ plugin_name }}" data-bind="allowBindings: false">
|
||||
{% include plugin_name+"_settings_dialog.jinja2" ignore missing %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
<div class="tab-pane" id="settings_logs" data-bind="allowBindings: false">
|
||||
<div id="logs">
|
||||
<h1>{{ _('Logs') }}</h1>
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -252,3 +252,32 @@ def dict_merge(a, b):
|
||||
|
||||
class Object(object):
|
||||
pass
|
||||
|
||||
def interface_addresses(family=None):
|
||||
import netifaces
|
||||
if not family:
|
||||
family = netifaces.AF_INET
|
||||
|
||||
for interface in netifaces.interfaces():
|
||||
try:
|
||||
ifaddresses = netifaces.ifaddresses(interface)
|
||||
except:
|
||||
continue
|
||||
if family in ifaddresses:
|
||||
for ifaddress in ifaddresses[family]:
|
||||
if not ifaddress["addr"].startswith("169.254."):
|
||||
yield ifaddress["addr"]
|
||||
|
||||
def address_for_client(host, port):
|
||||
import socket
|
||||
|
||||
for address in interface_addresses():
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.bind((address, 0))
|
||||
sock.connect((host, port))
|
||||
return address
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import threading
|
||||
import Queue as queue
|
||||
import logging
|
||||
import serial
|
||||
import octoprint.plugin
|
||||
|
||||
from collections import deque
|
||||
|
||||
@@ -151,6 +152,10 @@ class MachineCom(object):
|
||||
self._resendDelta = None
|
||||
self._lastLines = deque([], 50)
|
||||
|
||||
# hooks
|
||||
self._pluginManager = octoprint.plugin.plugin_manager()
|
||||
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode")
|
||||
|
||||
# SD status data
|
||||
self._sdAvailable = False
|
||||
self._sdFileList = False
|
||||
@@ -1074,6 +1079,10 @@ class MachineCom(object):
|
||||
return
|
||||
|
||||
if not self.isStreaming():
|
||||
for hook in self._gcode_hooks:
|
||||
hook_cmd = self._gcode_hooks[hook](self, cmd)
|
||||
if hook_cmd and isinstance(hook_cmd, basestring):
|
||||
cmd = hook_cmd
|
||||
gcode = self._regex_command.search(cmd)
|
||||
if gcode:
|
||||
gcode = gcode.group(1)
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import unittest
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
|
||||
|
||||
class PluginTestCase(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
import logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# TODO mock pkg_resources to return some defined entry_points
|
||||
|
||||
import os
|
||||
plugin_folders = [os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_plugins")]
|
||||
plugin_types = [octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin]
|
||||
plugin_entry_points = None
|
||||
self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders, plugin_types, plugin_entry_points)
|
||||
|
||||
def test_plugin_loading(self):
|
||||
self.assertEquals(4, len(self.plugin_manager.plugins))
|
||||
self.assertEquals(1, len(self.plugin_manager.plugin_hooks))
|
||||
self.assertEquals(2, len(self.plugin_manager.plugin_implementations))
|
||||
|
||||
self.assertTrue("octoprint.core.startup" in self.plugin_manager.plugin_hooks)
|
||||
self.assertEquals(1, len(self.plugin_manager.plugin_hooks["octoprint.core.startup"]))
|
||||
|
||||
self.assertTrue(octoprint.plugin.StartupPlugin in self.plugin_manager.plugin_implementations)
|
||||
self.assertEquals(2, len(self.plugin_manager.plugin_implementations[octoprint.plugin.StartupPlugin]))
|
||||
|
||||
self.assertTrue(octoprint.plugin.SettingsPlugin in self.plugin_manager.plugin_implementations)
|
||||
self.assertEquals(2, len(self.plugin_manager.plugin_implementations[octoprint.plugin.SettingsPlugin]))
|
||||
|
||||
def test_get_plugin(self):
|
||||
plugin = self.plugin_manager.get_plugin("hook_plugin")
|
||||
self.assertIsNotNone(plugin)
|
||||
self.assertEquals("Hook Plugin", plugin.__plugin_name__)
|
||||
|
||||
plugin = self.plugin_manager.get_plugin("mixed_plugin")
|
||||
self.assertIsNotNone(plugin)
|
||||
self.assertEquals("Mixed Plugin", plugin.__plugin_name__)
|
||||
|
||||
plugin = self.plugin_manager.get_plugin("unknown_plugin")
|
||||
self.assertIsNone(plugin)
|
||||
|
||||
def test_get_hooks(self):
|
||||
hooks = self.plugin_manager.get_hooks("octoprint.core.startup")
|
||||
self.assertEquals(1, len(hooks))
|
||||
self.assertTrue("hook_plugin" in hooks)
|
||||
self.assertEquals("success", hooks["hook_plugin"]())
|
||||
|
||||
hooks = self.plugin_manager.get_hooks("octoprint.printing.print")
|
||||
self.assertEquals(0, len(hooks))
|
||||
|
||||
def test_get_implementation(self):
|
||||
implementations = self.plugin_manager.get_implementations(octoprint.plugin.StartupPlugin)
|
||||
self.assertEquals(2, len(implementations))
|
||||
self.assertTrue('startup_plugin' in implementations)
|
||||
self.assertTrue('mixed_plugin' in implementations)
|
||||
|
||||
implementations = self.plugin_manager.get_implementations(octoprint.plugin.SettingsPlugin)
|
||||
self.assertEquals(2, len(implementations))
|
||||
self.assertTrue('settings_plugin' in implementations)
|
||||
self.assertTrue('mixed_plugin' in implementations)
|
||||
|
||||
implementations = self.plugin_manager.get_implementations(octoprint.plugin.StartupPlugin, octoprint.plugin.SettingsPlugin)
|
||||
self.assertEquals(1, len(implementations))
|
||||
self.assertTrue('mixed_plugin' in implementations)
|
||||
@@ -0,0 +1,10 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
|
||||
def hook_startup():
|
||||
return "success"
|
||||
|
||||
|
||||
__plugin_name__ = "Hook Plugin"
|
||||
__plugin_description__ = "Test hook plugin"
|
||||
__plugin_hooks__ = {'octoprint.core.startup': hook_startup}
|
||||
@@ -0,0 +1,17 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
|
||||
class TestMixedPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.SettingsPlugin):
|
||||
pass
|
||||
|
||||
|
||||
__plugin_name__ = "Mixed Plugin"
|
||||
__plugin_description__ = "Test mixed plugin"
|
||||
__plugin_implementations__ = (TestMixedPlugin(),)
|
||||
@@ -0,0 +1,12 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
|
||||
class TestSettingsPlugin(octoprint.plugin.SettingsPlugin):
|
||||
pass
|
||||
|
||||
|
||||
__plugin_name__ = "Settings Plugin"
|
||||
__plugin_description__ = "Test settings plugin"
|
||||
__plugin_implementations__ = (TestSettingsPlugin(),)
|
||||
@@ -0,0 +1,12 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
|
||||
class TestStartupPlugin(octoprint.plugin.StartupPlugin):
|
||||
pass
|
||||
|
||||
|
||||
__plugin_name__ = "Startup Plugin"
|
||||
__plugin_description__ = "Test startup plugin"
|
||||
__plugin_implementations__ = (TestStartupPlugin(),)
|
||||
Reference in new issue
Block a user