🚧 Introduce connection profiles

This commit is contained in:
Gina Häußge committed 2019-05-24 16:30:22 +02:00
1 parent 0d6d0f7256
commit 13995e30b7
26 files changed
+1225 -132

No files matched your search

+193
View File
@@ -0,0 +1,193 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import io
try:
from os import scandir
except ImportError:
from scandir import scandir
from octoprint.settings import settings
from octoprint.util import is_hidden_path
class ConnectionProfile(object):
def __init__(self, id, name=None, printer_profile=None, protocol=None, protocol_parameters=None, transport=None, transport_parameters=None, **kwargs):
self.id = id
self.name = name if name is not None else id
self.printer_profile = printer_profile
self.protocol = protocol
self.protocol_parameters = protocol_parameters
self.transport = transport
self.transport_parameters = transport_parameters
@classmethod
def from_dict(cls, data):
identifier = data.pop("id")
return ConnectionProfile(identifier, **data)
def as_dict(self):
return dict(id=self.id,
name=self.name,
printer_profile=self.printer_profile,
protocol=self.protocol,
protocol_parameters=self.protocol_parameters,
transport=self.transport,
transport_parameters=self.transport_parameters)
class ConnectionProfileManager(object):
@classmethod
def to_profile(cls, data):
return ConnectionProfile.from_dict(data)
def __init__(self):
self._current = None
self._folder = settings().getBaseFolder("connectionProfiles")
self._logger = logging.getLogger(__name__)
def select(self, identifier):
self._current = self.get(identifier)
if self._current is None:
self._logger.error("Profile {} is invalid, cannot select".format(identifier))
return False
return True
def deselect(self):
self._current = None
@property
def current(self):
return self._current
def get_all(self):
return self._load_all()
def get(self, identifier):
try:
if self.exists(identifier):
return self._load_from_path(self._get_profile_path(identifier))
else:
return None
except InvalidProfileError:
return None
def remove(self, identifier):
return self._remove_from_path(self._get_profile_path(identifier))
def save(self, profile, allow_overwrite=False, make_default=False):
self._save_to_path(self._get_profile_path(profile.id),
profile,
allow_overwrite=allow_overwrite)
if make_default:
self.set_default(profile.id)
return self.get(profile.id)
@property
def profile_count(self):
return len(self._load_all_identifiers())
@property
def last_modified(self):
dates = [os.stat(self._folder).st_mtime]
dates += [entry.stat().st_mtime for entry in scandir(self._folder) if entry.name.endswith(".profile")]
return max(dates)
def get_default(self):
pass
def set_default(self, idenitifier):
pass
def exists(self, identifier):
if identifier is None:
return False
path = self._get_profile_path(identifier)
return os.path.exists(path) and os.path.isfile(path)
def _load_all(self):
all_identifiers = self._load_all_identifiers()
results = dict()
for identifier, path in all_identifiers.items():
try:
profile = self._load_from_path(path)
except InvalidProfileError:
self._logger.warning("Profile {} is invalid, skipping".format(identifier))
continue
if profile is None:
continue
results[identifier] = profile
return results
def _load_all_identifiers(self):
results = dict()
for entry in scandir(self._folder):
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
continue
if not entry.is_file():
continue
identifier = entry.name[:-len(".profile")]
results[identifier] = entry.path
return results
def _load_from_path(self, path):
if not os.path.exists(path) or not os.path.isfile(path):
return None
import yaml
with io.open(path, 'rt', encoding='utf-8') as f:
data = yaml.safe_load(f)
if data is None or not isinstance(data, dict):
raise InvalidProfileError("Profile is None or not a dict")
return ConnectionProfile.from_dict(data)
def _save_to_path(self, path, profile, allow_overwrite=False):
if os.path.exists(path) and not allow_overwrite:
raise SaveError("Profile {} already exists and overwriting is not allowed".format(profile["id"]))
from octoprint.util import atomic_write
import yaml
try:
with atomic_write(path, mode="wt", max_permissions=0o666) as f:
yaml.safe_dump(profile.as_dict(), f,
default_flow_style=False,
indent=2,
allow_unicode=True)
except Exception as e:
self._logger.exception("Error while trying to save profile {}".format(profile["id"]))
raise SaveError("Cannot save profile {}: {}".format(profile["id"], e))
def _remove_from_path(self, path):
try:
os.remove(path)
return True
except Exception:
return False
def _get_profile_path(self, identifier):
return os.path.join(self._folder, "{}.profile".format(identifier))
class InvalidProfileError(Exception):
pass
class SaveError(Exception):
pass
+22 -6
View File
@@ -14,7 +14,7 @@ from octoprint.comm.protocol.reprap.commands import Command, to_command
from octoprint.comm.protocol.reprap.commands.atcommand import AtCommand
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.reprap.flavors import GenericFlavor, all_flavors, lookup_flavor
from octoprint.comm.protocol.reprap.flavors import FlavorOverride, GenericFlavor, all_flavors, lookup_flavor
from octoprint.comm.protocol.reprap.scripts import GcodeScript
@@ -23,7 +23,7 @@ from octoprint.comm.protocol.reprap.util.queues import ScriptQueue, JobQueue, Co
from octoprint.comm.scripts import InvalidScript, UnknownScript
from octoprint.comm.util.parameters import ChoiceType, Value
from octoprint.comm.util.parameters import ChoiceType, Value, ParamGroup, BooleanType, SmallChoiceType
from octoprint.comm.job import LocalGcodeFilePrintjob, SDFilePrintjob, \
LocalGcodeStreamjob, CopyJobMixin
@@ -127,7 +127,18 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
def get_connection_options(cls):
return [ChoiceType("flavor", "Firmware Flavor",
sorted([Value(f.key, title=f.name) for f in all_flavors()], key=lambda x: x.title),
default="generic")]
default="generic"),
ParamGroup("flavor_overrides",
"Flavor Overrides",
[BooleanType("always_send_checksum", "Always send checksum", help="Check this to always send checksums", default=False),
SmallChoiceType("trigger_ok_after_resend",
"Trigger ok after resend",
[Value("detect", title="As detected"),
Value("always", title="Always"),
Value("never", title="Never")],
default="detect")],
help="Just a test",
advanced=True)]
@staticmethod
def get_flavor_attributes_starting_with(flavor, prefix):
@@ -155,7 +166,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self.flavor = lookup_flavor(flavor)
if self.flavor is None:
self.flavor = GenericFlavor
self.set_current_args(flavor=self.flavor.key)
self.flavor_overrides = kwargs.get("flavor_overrides", dict())
self.flavor = self.flavor.with_overrides(self.flavor_overrides)
self.set_current_args(flavor=self.flavor.key,
flavor_overrides=self.flavor_overrides)
self._logger = logging.getLogger(__name__)
self._commdebug_logger = logging.getLogger("COMMDEBUG")
@@ -1479,7 +1495,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._current_linenumber = 0
self._last_lines.clear()
self.flavor = GenericFlavor
self.flavor = GenericFlavor.with_overrides(self.flavor_overrides)
self.send_commands(self.flavor.command_hello(),
self.flavor.command_set_line(0))
@@ -2337,7 +2353,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._logger.log(level, log)
def _switch_flavor(self, new_flavor):
self.flavor = new_flavor
self.flavor = new_flavor.with_overrides(self.flavor_overrides)
self._trigger_ok_after_resend = FallbackValue(self._trigger_ok_after_resend.value, fallback=self.flavor.trigger_ok_after_resend)
@@ -13,3 +13,32 @@ from .smoothieware import * # noqa: F403
from .anet import * # noqa: F403
from .malyan import * # noqa: F403
class FlavorOverride(object):
def __init__(self, flavor, overrides):
self._flavor = flavor
self._overrides = overrides
@property
def flavor(self):
return self._flavor
@flavor.setter
def flavor(self, value):
self._flavor = value
@property
def overrides(self):
return self._overrides
@overrides.setter
def overrides(self, value):
self._overrides = value
def __getattr__(self, item):
try:
return self._overrides[item]
except KeyError:
return getattr(self._flavor, item)
@@ -106,6 +106,14 @@ class GenericFlavor(with_metaclass(FlavorMeta, object)):
* ``total``: total size of file being printed
"""
##~~ Overrides
_overrides = dict()
@classmethod
def with_overrides(cls, overrides):
return type(b"{}WithOverrides".format(cls.__name__), (cls,), overrides)
##~~ Identifier
@classmethod
@@ -73,9 +73,7 @@ class SerialTransport(Transport):
from serial.tools import list_ports_common
ports = [list_ports_common.ListPortInfo(d) for d in devices]
port_values = sorted([Value(port.device, title=port.description) for port in ports], key=lambda x: x.title)
if len(port_values) > 1:
port_values = [Value(None, title="Auto detect")] + port_values
port_values = [Value(None, title="Auto detect")] + sorted([Value(port.device, title=port.description) for port in ports], key=lambda x: x.title)
return port_values
@classmethod
+75 -11
View File
@@ -21,15 +21,19 @@ def get_param_dict(data, options):
class ParamType(object):
type = "generic"
def __init__(self, name, title, default=None):
def __init__(self, name, title, default=None, advanced=False, help=None):
self.name = name
self.title = title
self.default = default
self.advanced = advanced
self.help = help
def as_dict(self):
return dict(name=self.name,
title=self.title,
default=self.default,
advanced=self.advanced,
help=self.help,
type=self.type)
def convert(self, value):
@@ -50,10 +54,10 @@ class TextType(ParamType):
class IntegerType(ParamType):
type = "integer"
def __init__(self, name, title, min=None, max=None, default=None):
def __init__(self, name, title, min=None, max=None, **kwargs):
self.min = min
self.max = max
ParamType.__init__(self, name, title, default=default)
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
@@ -74,25 +78,66 @@ class IntegerType(ParamType):
return value
class FloatType(ParamType):
type = "float"
def __init__(self, name, title, min=None, max=None, **kwargs):
self.min = min
self.max = max
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(min=self.min,
max=self.max))
return result
def convert(self, value):
try:
value = float(value)
except ValueError:
raise ValueError("value {!r} is not a valid float".format(value))
if self.min is not None and value < self.min:
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
if self.max is not None and value > self.max:
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
return value
class BooleanType(ParamType):
type = "boolean"
def convert(self, value):
try:
value = bool(value)
except ValueError:
raise ValueError("value {!r} is not a valid boolean".format(value))
return value
class ChoiceType(ParamType):
type = "choice"
def __init__(self, name, title, choices, default=None):
def __init__(self, name, title, choices, **kwargs):
self.choices = choices
ParamType.__init__(self, name, title, default=default)
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(choices=list(map(lambda x: x.as_dict(), self.choices))))
return result
class SmallChoiceType(ChoiceType):
type = "smallchoice"
class SuggestionType(ParamType):
type = "suggestion"
def __init__(self, name, title, suggestions, factory, default=None):
def __init__(self, name, title, suggestions, factory, **kwargs):
self.suggestions = suggestions
self.factory = factory
ParamType.__init__(self, name, title, default=default)
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
@@ -102,9 +147,9 @@ class SuggestionType(ParamType):
class ListType(ParamType):
type = "list"
def __init__(self, name, title, factory, default=None):
def __init__(self, name, title, factory, **kwargs):
self.factory = factory
ParamType.__init__(self, name, title, default=default)
ParamType.__init__(self, name, title, **kwargs)
def convert(self, value):
if isinstance(value, unicode):
@@ -116,11 +161,30 @@ class ListType(ParamType):
return list(map(self.factory, items))
class ParamGroup(ParamType):
type = "group"
def __init__(self, name, title, params, help=None, advanced=False):
ParamType.__init__(self, name, title, help=help, advanced=advanced)
self.params = params
def as_dict(self):
result = ParamType.as_dict(self)
result["params"] = [x.as_dict() for x in self.params]
return result
def convert(self, value):
if not isinstance(value, dict):
raise ValueError("value {!r} must be a dict".format(value))
return dict((k, v.convert()) for k, v in value.items())
class Value(object):
def __init__(self, value, title=None):
def __init__(self, value, title=None, help=None):
self.value = value
self.title = title if title else value
self.help = help
def as_dict(self):
return dict(value=self.value,
title=self.title)
title=self.title,
help=self.help)
@@ -1 +1 @@
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
+102 -46
View File
@@ -78,7 +78,7 @@ class Printer(PrinterInterface,
itself with it as a callback to react to changes on the communication layer.
"""
def __init__(self, fileManager, analysisQueue, printerProfileManager):
def __init__(self, fileManager, analysisQueue, connectionProfileManager, printerProfileManager):
from collections import deque
self._logger = logging.getLogger(__name__)
@@ -88,6 +88,7 @@ class Printer(PrinterInterface,
self._analysis_queue = analysisQueue
self._file_manager = fileManager
self._connection_profile_manager = connectionProfileManager
self._printer_profile_manager = printerProfileManager
# state
@@ -133,6 +134,7 @@ class Printer(PrinterInterface,
self.sd_card_upload_hooks = plugin_manager().get_hooks("octoprint.printer.sdcardupload")
# comm
self._connection = None
self._protocol = None
self._transport = None
self._job = None
@@ -293,37 +295,95 @@ class Printer(PrinterInterface,
CommunicationLogHandler.on_open_connection(u"PROTOCOL")
CommunicationLogHandler.on_open_connection(u"COMMDEBUG")
##~~ Printer profile
connection_id = kwargs.get("connection")
connection = None
if connection_id is not None:
connection = self._connection_profile_manager.get(connection_id)
profile_id = kwargs.get("profile")
if not profile_id:
profile_id = self._printer_profile_manager.get_default()["id"]
self._printer_profile_manager.select(profile_id)
profile = self._printer_profile_manager.get_current_or_default()
if connection is not None:
# we have a connection profile
self._connection = connection
##~~ Transport
##~~ Printer profile
profile_id = connection.printer_profile
self._printer_profile_manager.select(profile_id)
profile = self._printer_profile_manager.get_current_or_default()
selected_transport = kwargs.get("transport")
if not selected_transport:
port = kwargs.get("port")
baudrate = kwargs.get("baudrate")
##~~ Transport
if not port:
port = "AUTO"
if not baudrate:
baudrate = 0
selected_transport = connection.transport
transport_connect_kwargs = connection.transport_parameters
transport_connect_kwargs.update(kwargs.get("transport_options", dict()))
transport_kwargs = dict()
transport_kwargs.update(dict(settings=settings(),
plugin_manager=plugin_manager(),
event_bus=eventManager(),
printer_profile=profile))
##~~ Protocol
selected_protocol = connection.protocol
protocol_kwargs = connection.protocol_parameters
protocol_kwargs.update(kwargs.get("protocol_options", dict()))
protocol_kwargs.update(dict(settings=settings(),
plugin_manager=plugin_manager(),
event_bus=eventManager(),
printer_profile=profile))
selected_transport = "serial"
transport_kwargs = dict(serial_factory=_serial_factory)
transport_connect_kwargs = dict(port=port, baudrate=baudrate)
else:
transport_kwargs = kwargs.get("transport_kwargs", dict())
transport_connect_kwargs = kwargs.get("transport_options", dict())
self._connection = None
transport_kwargs.update(dict(settings=settings(),
plugin_manager=plugin_manager(),
event_bus=eventManager(),
printer_profile=profile))
##~~ Printer profile
profile_id = kwargs.get("profile")
if not profile_id:
profile_id = self._printer_profile_manager.get_default()["id"]
self._printer_profile_manager.select(profile_id)
profile = self._printer_profile_manager.get_current_or_default()
##~~ Transport
selected_transport = kwargs.get("transport")
if not selected_transport:
port = kwargs.get("port")
baudrate = kwargs.get("baudrate")
if not port:
port = "AUTO"
if not baudrate:
baudrate = 0
selected_transport = "serial"
transport_kwargs = dict(serial_factory=_serial_factory)
transport_connect_kwargs = dict(port=port, baudrate=baudrate)
else:
transport_kwargs = kwargs.get("transport_kwargs", dict())
transport_connect_kwargs = kwargs.get("transport_options", dict())
transport_kwargs.update(dict(settings=settings(),
plugin_manager=plugin_manager(),
event_bus=eventManager(),
printer_profile=profile))
##~~ Protocol
# TODO make this depend on the printer profile
selected_protocol = kwargs.get("protocol")
if not selected_protocol:
selected_protocol = "reprap"
protocol_kwargs = dict()
else:
protocol_kwargs = kwargs.get("protocol_options", dict())
protocol_kwargs.update(dict(settings=settings(),
plugin_manager=plugin_manager(),
event_bus=eventManager(),
printer_profile=profile))
##~~ Lookup and create transport instances
from octoprint.comm.transport import lookup_transport
transport_class = lookup_transport(selected_transport)
@@ -333,20 +393,7 @@ class Printer(PrinterInterface,
transport = transport_class(**transport_kwargs)
self._transport = transport
##~~ Protocol
# TODO make this depend on the printer profile
selected_protocol = kwargs.get("protocol")
if not selected_protocol:
selected_protocol = "reprap"
protocol_kwargs = dict()
else:
protocol_kwargs = kwargs.get("protocol_options", dict())
protocol_kwargs.update(dict(settings=settings(),
plugin_manager=plugin_manager(),
event_bus=eventManager(),
printer_profile=profile))
##~~ Lookup and create protocol instance
from octoprint.comm.protocol import lookup_protocol
protocol_class = lookup_protocol(selected_protocol)
@@ -775,13 +822,22 @@ class Printer(PrinterInterface,
def get_current_connection_parameters(self, *args, **kwargs):
if self._transport is None or self._protocol is None:
return "Closed", None, None, None, None, None
return self.get_state_string(), \
self._transport.key, \
self._transport.args(), \
self._protocol.key, \
self._protocol.args(), \
self._printer_profile_manager.get_current_or_default()
return dict(state="Closed",
connection=None,
protocol=None,
protocol_args=None,
transport=None,
transport_args=None,
printer_profile=None)
printer_profile = self._printer_profile_manager.get_current_or_default()
return dict(state=self.get_state_string(),
connection=self._connection.id if self._connection is not None else None,
protocol=self._protocol.key,
protocol_args=self._protocol.args(),
transport=self._transport.key,
transport_args=self._transport.args(),
printer_profile=printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default")
def is_connected(self):
return self._protocol is not None and self._protocol.state in (ProtocolState.CONNECTED, ProtocolState.PROCESSING, ProtocolState.PAUSED)
+6 -1
View File
@@ -52,6 +52,7 @@ debug = False
safe_mode = False
printer = None
connectionProfileManager = None
printerProfileManager = None
fileManager = None
slicingManager = None
@@ -85,6 +86,7 @@ user_permission = octoprint.util.variable_deprecated("user_permission has been d
# only import further octoprint stuff down here, as it might depend on things defined above to be initialized already
from octoprint import __version__, __branch__, __display_version__, __revision__
from octoprint.comm.connectionprofile import ConnectionProfileManager
from octoprint.printer.profile import PrinterProfileManager
from octoprint.printer.standard import Printer
from octoprint.settings import settings
@@ -228,6 +230,7 @@ class Server(object):
global babel
global printer
global connectionProfileManager
global printerProfileManager
global fileManager
global slicingManager
@@ -308,6 +311,7 @@ class Server(object):
# then initialize the plugin manager
pluginManager.reload_plugins(startup=True, initialize_implementations=False)
connectionProfileManager = ConnectionProfileManager()
printerProfileManager = PrinterProfileManager()
eventManager = self._event_manager
@@ -369,6 +373,7 @@ class Server(object):
components = dict(
plugin_manager=pluginManager,
connection_profile_manager=connectionProfileManager,
printer_profile_manager=printerProfileManager,
event_bus=eventManager,
analysis_queue=analysisQueue,
@@ -453,7 +458,7 @@ class Server(object):
self._logger.exception("Error while creating printer instance from factory {}".format(name),
extra=dict(plugin=name))
else:
printer = Printer(fileManager, analysisQueue, printerProfileManager)
printer = Printer(fileManager, analysisQueue, connectionProfileManager, printerProfileManager)
components.update(dict(printer=printer))
def octoprint_plugin_inject_factory(name, implementation):
+1
View File
@@ -30,6 +30,7 @@ api = Blueprint("api", __name__)
from . import printer as api_printer
from . import job as api_job
from . import connection as api_connection
from . import connection_profiles as api_connection_profiles
from . import files as api_files
from . import settings as api_settings
from . import timelapse as api_timelapse
+15 -8
View File
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from flask import request, jsonify, make_response
from octoprint.settings import settings
from octoprint.server import printer, printerProfileManager, NO_CONTENT
from octoprint.server import printer, connectionProfileManager, printerProfileManager, NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request
from octoprint.access.permissions import Permissions
@@ -25,14 +25,15 @@ def _convert_protocol_options(options):
@api.route("/connection", methods=["GET"])
@Permissions.STATUS.require(403)
def connectionState():
state, protocol, protocol_options, transport, transport_options, printer_profile = printer.get_current_connection_parameters()
params = printer.get_current_connection_parameters()
current = dict(state=state,
profile=printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default",
protocol=protocol,
protocolOptions=protocol_options,
transport=transport,
transportOptions=transport_options)
current = dict(state=params["state"],
connection=params["connection"],
profile=params["printer_profile"],
protocol=params["protocol"],
protocolOptions=params["protocol_args"],
transport=params["transport"],
transportOptions=params["transport_args"])
##~~ legacy
@@ -60,6 +61,9 @@ def connectionCommand():
if command == "connect":
kwargs = dict()
if "connection" in data:
kwargs["connection"] = data["connection"]
if "protocol" in data:
kwargs["protocol"] = data["protocol"]
@@ -126,10 +130,13 @@ def _get_options():
profile_options = printerProfileManager.get_all()
default_profile = printerProfileManager.get_default()
connection_profiles = connectionProfileManager.get_all()
options = dict(
ports=connection_options["ports"],
baudrates=connection_options["baudrates"],
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
connectionProfiles=[connection_profile.as_dict() for connection_profile in connection_profiles.values()],
portPreference=connection_options["portPreference"],
baudratePreference=connection_options["baudratePreference"],
printerProfilePreference=default_profile["id"] if "id" in default_profile else None,
@@ -0,0 +1,160 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import jsonify, make_response, request, url_for
from werkzeug.exceptions import BadRequest
from octoprint.server import connectionProfileManager
from octoprint.server.api import api, NO_CONTENT, valid_boolean_trues
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking
from octoprint.util import dict_merge
from octoprint.comm.connectionprofile import InvalidProfileError, SaveError
from octoprint.access.permissions import Permissions
def _lastmodified():
return connectionProfileManager.last_modified
def _etag(lm=None):
if lm is None:
lm = _lastmodified()
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode('utf-8')
hash.update(value)
hash_update(str(lm))
return hash.hexdigest()
@api.route("/connectionprofiles", methods=["GET"])
@with_revalidation_checking(etag_factory=_etag,
lastmodified_factory=_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def connectionProfilesList():
all_profiles = connectionProfileManager.get_all()
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
@api.route("/connectionprofiles", methods=["POST"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def connectionProfilesAdd():
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if not "profile" in json_data:
return make_response("No profile included in request", 400)
new_profile = json_data["profile"]
if not "id" in new_profile:
return make_response("Profile does not contain mandatory 'id' field", 400)
if not "name" in new_profile:
return make_response("Profile does not contain mandatory 'name' field", 400)
make_default = False
if "default" in new_profile:
make_default = True
del new_profile["default"]
profile = connectionProfileManager.to_profile(new_profile)
try:
connectionProfileManager.save(profile, allow_overwrite=False, make_default=make_default)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except SaveError:
return make_response("Profile {} could not be saved".format(profile["id"]), 400)
except Exception as e:
return make_response("Could not save profile: {}".format(e), 500)
else:
return jsonify(dict(profile=profile.as_dict()))
@api.route("/connectionprofiles/<string:identifier>", methods=["GET"])
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def connectionProfilesGet(identifier):
profile = connectionProfileManager.get(identifier)
if profile is None:
return make_response("Unknown profile: {}".format(identifier), 404)
else:
return jsonify(dict(profile=profile.as_dict()))
@api.route("/connectionprofiles/<string:identifier>", methods=["DELETE"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def connectionProfilesDelete(identifier):
#current_profile = connectionProfileManager.get_current()
#if current_profile and current_profile["id"] == identifier:
# return make_response("Cannot delete currently selected profile: {}".format(identifier), 409)
#default_profile = connectionProfileManager.get_default()
#if default_profile and default_profile["id"] == identifier:
# return make_response("Cannot delete default profile: {}".format(identifier), 409)
connectionProfileManager.remove(identifier)
return NO_CONTENT
#@api.route("/connectionprofiles/<string:identifier>", methods=["PATCH"])
#@no_firstrun_access
#@Permissions.SETTINGS.require(403)
#def printerProfilesUpdate(identifier):
# if not "application/json" in request.headers["Content-Type"]:
# return make_response("Expected content-type JSON", 400)
#
# try:
# json_data = request.get_json()
# except BadRequest:
# return make_response("Malformed JSON body in request", 400)
#
# if json_data is None:
# return make_response("Malformed JSON body in request", 400)
#
# if not "profile" in json_data:
# return make_response("No profile included in request", 400)
#
# profile = printerProfileManager.get(identifier)
# if profile is None:
# profile = printerProfileManager.get_default()
#
# new_profile = json_data["profile"]
# merged_profile = dict_merge(profile, new_profile)
#
# make_default = False
# if "default" in merged_profile:
# make_default = True
# del new_profile["default"]
#
# merged_profile["id"] = identifier
#
# try:
# saved_profile = printerProfileManager.save(merged_profile, allow_overwrite=True, make_default=make_default)
# except InvalidProfileError:
# return make_response("Profile is invalid", 400)
# except CouldNotOverwriteError:
# return make_response("Profile already exists and overwriting was not allowed", 400)
# except Exception as e:
# return make_response("Could not save profile: %s" % str(e), 500)
# else:
# return jsonify(dict(profile=_convert_profile(saved_profile)))
def _convert_profiles(profiles):
result = dict()
for identifier, profile in profiles.items():
result[identifier] = profile.as_dict()
return result
+2
View File
@@ -1394,6 +1394,7 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
'js/app/viewmodels/access.js',
'js/app/viewmodels/appearance.js',
'js/app/viewmodels/connection.js',
'js/app/viewmodels/connectionprofiles.js',
'js/app/viewmodels/control.js',
'js/app/viewmodels/files.js',
'js/app/viewmodels/loginstate.js',
@@ -1426,6 +1427,7 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
"js/app/client/access.js",
"js/app/client/browser.js",
"js/app/client/connection.js",
"js/app/client/connectionprofiles.js",
"js/app/client/control.js",
"js/app/client/files.js",
"js/app/client/job.js",
+1
View File
@@ -588,6 +588,7 @@ def fetch_template_data(refresh=False):
section_printer=(gettext("Printer"), None),
serial=(gettext("Serial Connection"), dict(template="dialogs/settings/serialconnection.jinja2", _div="settings_serialConnection", custom_bindings=False)),
connectionprofiles=(gettext("Connection Profiles"), dict(template="dialogs/settings/connectionprofiles.jinja2", _div="settings_connectionProfiles", custom_bindings=False)),
printerprofiles=(gettext("Printer Profiles"), dict(template="dialogs/settings/printerprofiles.jinja2", _div="settings_printerProfiles", custom_bindings=False)),
temperatures=(gettext("Temperatures"), dict(template="dialogs/settings/temperatures.jinja2", _div="settings_temperature", custom_bindings=False)),
terminalfilters=(gettext("Terminal Filters"), dict(template="dialogs/settings/terminalfilters.jinja2", _div="settings_terminalFilters", custom_bindings=False)),
+1
View File
@@ -275,6 +275,7 @@ default_settings = {
"plugins": None,
"slicingProfiles": None,
"printerProfiles": None,
"connectionProfiles": None,
"scripts": None,
"translations": None,
"generated": None,
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -0,0 +1,48 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient", "jquery"], factory);
} else {
factory(global.OctoPrintClient, global.$);
}
})(this, function(OctoPrintClient, $) {
var url = "api/connectionprofiles";
var profileUrl = function(profile) {
return url + "/" + profile;
};
var OctoPrintConnectionProfileClient = function(base) {
this.base = base;
};
OctoPrintConnectionProfileClient.prototype.list = function (opts) {
return this.base.get(url, opts);
};
OctoPrintConnectionProfileClient.prototype.add = function (profile, opts) {
profile = profile || {};
var data = {profile: profile};
return this.base.postJson(url, data, opts);
};
OctoPrintConnectionProfileClient.prototype.get = function (id, opts) {
return this.base.get(profileUrl(id), opts);
};
OctoPrintConnectionProfileClient.prototype. update = function (id, profile, opts) {
profile = profile || {};
var data = {profile: profile};
return this.base.patchJson(profileUrl(id), data, opts);
};
OctoPrintConnectionProfileClient.prototype.delete = function (id, opts) {
return this.base.delete(profileUrl(id), opts);
};
OctoPrintClient.registerComponent("connectionprofiles", OctoPrintConnectionProfileClient);
return OctoPrintConnectionProfileClient;
});
@@ -4,8 +4,30 @@ $(function() {
self.loginState = parameters[0];
self.settings = parameters[1];
self.printerProfiles = parameters[2];
self.access = parameters[3];
self.connectionProfiles = parameters[2];
self.printerProfiles = parameters[3];
self.access = parameters[4];
var extendOption = function(option, value) {
if (option.type === "group") {
if (value === undefined) {
value = {};
}
_.each(option.params, function(option) {
extendOption(option, value[option.name]);
});
} else {
if (value === undefined && option.default !== undefined) {
value = option.default;
}
if (option.value) {
option.value(value);
} else {
option.value = ko.observable(value);
}
}
};
self.printerProfiles.profiles.items.subscribe(function() {
var allProfiles = self.printerProfiles.profiles.items();
@@ -24,10 +46,58 @@ $(function() {
self.printerOptions = ko.observableArray(undefined);
self.selectedPrinter = ko.observable(undefined);
// Connection profiles
self.availableConnectionProfiles = ko.observableArray();
self.selectedConnectionProfile = ko.observable(undefined);
self.selectedConnectionProfile.subscribe(function() {
var protocolParameters, transportParameters;
var profile = self.selectedConnectionProfile();
if (profile) {
self.selectedPrinter(profile.printer_profile);
self.selectedProtocol(_.find(self.availableProtocols(), function(p) { return p.key === profile.protocol }));
self.selectedTransport(_.find(self.availableTransports(), function(t) { return t.key === profile.transport }));
protocolParameters = self.protocolParameters();
_.each(protocolParameters, function(option) {
extendOption(option, profile.protocol_parameters[option.name]);
});
self.protocolParameters(protocolParameters);
transportParameters = self.transportParameters();
_.each(transportParameters, function(option) {
extendOption(option, profile.transport_parameters[option.name]);
});
self.transportParameters(transportParameters);
} else {
self.selectedPrinter(undefined);
self.selectedProtocol(undefined);
self.selectedTransport(undefined);
protocolParameters = self.protocolParameters();
_.each(protocolParameters, function(option) {
extendOption(option);
});
self.protocolParameters(protocolParameters);
transportParameters = self.transportParameters();
_.each(transportParameters, function(option) {
extendOption(option);
});
self.transportParameters(transportParameters);
}
});
// Protocol
self.availableProtocols = ko.observableArray();
self.selectedProtocol = ko.observable(undefined);
self.protocolParameters = ko.observable();
self.advancedProtocolParameters = ko.observable();
self.showAdvancedProtocolOptions = function() {
$("#connection_protocol_dialog").modal("show");
};
self.selectedProtocol.subscribe(function() {
var protocol = self.selectedProtocol();
@@ -36,12 +106,18 @@ $(function() {
} else {
self.protocolParameters([]);
}
self.advancedProtocolParameters(_.any(self.protocolParameters(), function(p) { return p.advanced }));
});
// Transport
self.availableTransports = ko.observableArray();
self.selectedTransport = ko.observable(undefined);
self.transportParameters = ko.observableArray();
self.advancedTransportParameters = ko.observable();
self.showAdvancedTransportOptions = function() {
};
self.selectedTransport.subscribe(function() {
var transport = self.selectedTransport();
@@ -50,9 +126,11 @@ $(function() {
} else {
self.transportParameters([]);
}
self.advancedTransportParameters(_.any(self.transportParameters(), function(p) { return p.advanced }));
});
self.adjustConnectionParameters = ko.observable(undefined);
self.adjustConnectionParameters = ko.observable();
self.updateProfile = ko.observable(undefined);
self.saveSettings = ko.observable(undefined);
self.autoconnect = ko.observable(undefined);
@@ -86,36 +164,17 @@ $(function() {
};
self.fromResponse = function(response) {
var profile = response.current.profile;
var connections = response.options.connectionProfiles;
var profiles = response.options.printerProfiles;
var protocolKey = response.current.protocol;
// protocol
var protocols = response.options.protocols;
var protocolOptions = response.current.protocolOptions;
if (!protocolOptions) {
protocolOptions = {};
}
var protocols = response.options.protocols;
var protocol = _.find(protocols, function(p) { return p.key === protocolKey });
var transportKey = response.current.transport;
var transportOptions = response.current.transportOptions;
if (!transportOptions) {
transportOptions = {};
}
var transports = response.options.transports;
var transport = _.find(transports, function(t) { return t.key === transportKey });
if (!self.selectedPrinter() && profiles && profiles.indexOf(profile) >= 0)
self.selectedPrinter(profile);
var extendOption = function(option, value) {
if (value === undefined && option.default !== undefined) {
value = option.default;
}
option.value = ko.observable(value);
};
// protocol
_.each(protocols, function(protocol) {
_.each(protocol.options, function(option) {
extendOption(option, protocolOptions[option.name]);
@@ -123,9 +182,14 @@ $(function() {
});
self.availableProtocols(protocols);
self.selectedProtocol(protocol);
// transport
var transports = response.options.transports;
var transportOptions = response.current.transportOptions;
if (!transportOptions) {
transportOptions = {};
}
_.each(transports, function(transport) {
_.each(transport.options, function(option) {
extendOption(option, transportOptions[option.name]);
@@ -133,7 +197,31 @@ $(function() {
});
self.availableTransports(transports);
self.selectedTransport(transport);
self.availableConnectionProfiles(connections);
//~~ Connection profile or not?
var connectionKey = response.current.connection;
if (connectionKey) {
var connection = _.find(connections, function(c) { return c.id === connectionKey });
self.selectedConnectionProfile(connection);
} else if (self.selectedConnectionProfile() === undefined) {
var profile = response.current.profile;
var protocolKey = response.current.protocol;
var protocol = _.find(protocols, function(p) { return p.key === protocolKey });
var transportKey = response.current.transport;
var transport = _.find(transports, function(t) { return t.key === transportKey });
if (!self.selectedPrinter() && profiles && profiles.indexOf(profile) >= 0)
self.selectedPrinter(profile);
self.selectedProtocol(protocol);
self.selectedTransport(transport);
self.adjustConnectionParameters(true);
}
self.saveSettings(false);
};
@@ -177,33 +265,67 @@ $(function() {
}
};
self.connect = function() {
self.connect = function(save) {
if (self.isErrorOrClosed()) {
var toOptions = function(parameters) {
var result = {};
_.each(parameters, function(parameter) {
result[parameter.name] = parameter.value();
if (parameter.type === "group") {
result[parameter.name] = toOptions(parameter.params);
} else {
result[parameter.name] = parameter.value();
}
});
return result;
};
var data = {
"protocol": self.selectedProtocol().key,
"protocolOptions": toOptions(self.protocolParameters()),
"transport": self.selectedTransport().key,
"transportOptions": toOptions(self.transportParameters()),
"printerProfile": self.selectedPrinter(),
"autoconnect": self.settings.serial_autoconnect()
};
if (self.saveSettings())
data["save"] = true;
var connectionProfile = self.selectedConnectionProfile();
if (connectionProfile) {
data.connection = connectionProfile.id;
}
if (self.adjustConnectionParameters() || connectionProfile === undefined) {
data.printerProfile = self.selectedPrinter();
data.protocol = self.selectedProtocol().key;
data.protocolOptions = toOptions(self.protocolParameters());
data.transport = self.selectedTransport().key;
data.transportOptions = toOptions(self.transportParameters());
}
var finalize = function() {
self.settings.requestData();
self.settings.connectionProfiles.requestData();
self.settings.printerProfiles.requestData();
};
if (save) {
var profile = {
printer_profile: data.printerProfile,
protocol: data.protocol,
protocol_parameters: data.protocolOptions,
transport: data.transport,
transport_parameters: data.transportOptions
};
if (connectionProfile) {
profile.id = connectionProfile.id;
profile.name = connectionProfile.name;
}
self.connectionProfiles.editor.showDialog(profile, gettext("Save & Connect"))
.done(function(profile) {
OctoPrint.connection.connect({connection: profile.id})
.done(finalize);
});
} else {
OctoPrint.connection.connect(data)
.done(finalize);
}
OctoPrint.connection.connect(data)
.done(function() {
self.settings.requestData();
self.settings.printerProfiles.requestData();
});
} else {
if (!self.isPrinting() && !self.isPaused()) {
self.requestData();
@@ -258,11 +380,15 @@ $(function() {
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
self.requestData();
};
self._sanitize = function(name) {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
}
OCTOPRINT_VIEWMODELS.push({
construct: ConnectionViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel", "printerProfilesViewModel", "accessViewModel"],
elements: ["#connection_wrapper"]
dependencies: ["loginStateViewModel", "settingsViewModel", "connectionProfilesViewModel", "printerProfilesViewModel", "accessViewModel"],
elements: ["#connection_wrapper", "#connection_protocol_dialog", "#connection_transport_dialog"]
});
});
@@ -0,0 +1,135 @@
$(function() {
function ConnectionProfileEditorViewModel() {
var self = this;
self.active = ko.observable(false);
self.deferred = undefined;
self.buttonText = ko.observable(gettext("Save"));
self.profile = undefined;
self.name = ko.observable();
self.identifier = ko.observable();
self.identifierPlaceholder = ko.observable();
self.name.subscribe(function() {
self.identifierPlaceholder(self._sanitize(self.name()).toLowerCase());
});
self.showDialog = function(profile, button) {
if (button) {
self.buttonText(button);
} else {
self.buttonText(gettext("Save"));
}
self.profile = profile;
self.name(profile.name);
self.identifier(profile.identifier);
self.deferred = $.Deferred();
$("#connectionprofiles_save_dialog").modal("show");
return self.deferred.promise();
};
self.confirm = function() {
self.profile.id = self.identifier();
if (self.profile.id === undefined) {
self.profile.id = self.identifierPlaceholder();
}
self.profile.name = self.name();
OctoPrint.connectionprofiles.add(self.profile)
.done(function(response) {
if (self.deferred) {
self.deferred.resolve(response.profile);
}
})
};
self._sanitize = function(name) {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
}
function ConnectionProfilesViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.access = parameters[1];
self.requestInProgress = ko.observable(false);
self.editor = new ConnectionProfileEditorViewModel();
self.profiles = new ItemListHelper(
"connectionProfiles",
{
"name": function(a, b) {
// sorts ascending
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
return 0;
}
},
{},
"name",
[],
[],
10
);
self.makeDefault = function(data) {
/*
var profile = {
id: data.id,
default: true
};
self.updateProfile(profile);
*/
};
self.canMakeDefault = function(data) {
//return !data.isdefault();
return true;
};
self.canRemove = function(data) {
//return !data.iscurrent() && !data.isdefault();
return true;
};
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.CONNECTION)) {
return;
}
return OctoPrint.connectionprofiles.list()
.done(self.fromResponse);
};
self.fromResponse = function(data) {
var items = [];
_.each(data.profiles, function(profile) {
items.push(profile);
});
self.profiles.updateItems(items);
};
self.onSettingsShown = self.requestData;
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
self.requestData();
}
}
OCTOPRINT_VIEWMODELS.push({
construct: ConnectionProfilesViewModel,
dependencies: ["loginStateViewModel", "accessViewModel"],
elements: ["#connectionprofiles_save_dialog"]
});
});
@@ -4,11 +4,12 @@ $(function() {
self.loginState = parameters[0];
self.access = parameters[1];
self.printerProfiles = parameters[2];
self.about = parameters[3];
self.connectionProfiles = parameters[2];
self.printerProfiles = parameters[3];
self.about = parameters[4];
// TODO: remove in upcoming version, this is only for backwards compatibility
self.users = parameters[4];
self.users = parameters[5];
// use this promise to do certain things once the SettingsViewModel has processed
// its first request
@@ -1109,7 +1110,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: SettingsViewModel,
dependencies: ["loginStateViewModel", "accessViewModel", "printerProfilesViewModel", "aboutViewModel", "usersViewModel"],
dependencies: ["loginStateViewModel", "accessViewModel", "connectionProfilesViewModel", "printerProfilesViewModel", "aboutViewModel", "usersViewModel"],
elements: ["#settings_dialog", "#navbar_settings"]
});
});
+11
View File
@@ -438,6 +438,17 @@ table {
.actioncol;
}
// Connection profiles
&.settings_connectionProfiles_profiles_name {
text-overflow: ellipsis;
text-align: left;
}
&.settings_connectionProfiles_profiles_action {
width: 80px;
.actioncol;
}
}
}
@@ -0,0 +1,120 @@
<div id="connection_protocol_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Protocol Parameters') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="javascript:void(0)">
<!-- ko foreach: protocolParameters -->
<!-- ko template: { name: 'connection_dialog_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /ko -->
</form>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</a>
</div>
</div>
<div id="connection_transport_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Protocol Parameters') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="javascript:void(0)">
<!-- ko foreach: transportParameters -->
<!-- ko template: { name: 'connection_dialog_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /ko -->
</form>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</a>
</div>
</div>
<script type="text/html" id="connection_dialog_template_text">
<div class="control-group">
<label class="control-label" data-bind="text: $data.title"></label>
<div class="controls">
<input class="input-block-level" type="text" data-bind="value: $data.value, attr: {placeholder: $data.default}, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()">
<span class="help-block" data-bind="visible: $data.help, text: $data.help"></span>
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_integer">
<div class="control-group">
<label class="control-label" data-bind="text: $data.title"></label>
<div class="controls">
<input class="input-block-level" type="number" step="1" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()">
<span class="help-block" data-bind="visible: $data.help, text: $data.help"></span>
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_float">
<div class="control-group">
<label class="control-label" data-bind="text: $data.title"></label>
<div class="controls">
<input class="input-block-level" type="number" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()">
<span class="help-block" data-bind="visible: $data.help, text: $data.help"></span>
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_choice">
<div class="control-group">
<label class="control-label" data-bind="text: $data.title"></label>
<div class="controls">
<select class="input-block-level" data-bind="options: $data.choices, optionsText: 'title', optionsValue: 'value', value: $data.value, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></select>
<span class="help-block" data-bind="visible: $data.help, text: $data.help"></span>
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_smallchoice">
<div class="control-group">
<label class="control-label" data-bind="text: $data.title"></label>
<div class="controls">
<!-- ko foreach: choices -->
<label class="radio">
<input type="radio" data-bind="attr: { name: 'connection_dialog_' + $parent.name + '_group' }, value: $data.value, checked: $parent.value"> <span data-bind="text: $data.title"></span>
<span class="help-block" data-bind="visible: $data.help, text: $data.help"></span>
</label>
<!-- /ko -->
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_boolean">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: $data.value, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"> <span data-bind="text: $data.title"></span>
</label>
<span class="help-block" data-bind="visible: $data.help, text: $data.help"></span>
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_suggestion">
<div class="control-group">
<label class="control-label" data-bind="text: $data.title"></label>
<div class="controls">
<select class="input-block-level" data-bind="options: $data.suggestions, optionsText: 'title', optionsValue: 'value', value: $data.value, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></select>
<span class="help-block" data-bind="visible: $data.help, text: $data.help"></span>
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_list">
<div class="control-group">
<label class="control-label" data-bind="text: $data.title"></label>
<div class="controls">
<textarea data-bind="value: $data.value, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></textarea>
<span class="help-block" data-bind="visible: $data.help, text: $data.help"></span>
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_group">
<fieldset>
<legend data-bind="text: $data.title"></legend>
<p data-bind="visible: $data.help, text: $data.help"></p>
<!-- ko foreach: params -->
<!-- ko template: { name: 'connection_dialog_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /ko -->
</fieldset>
</script>
@@ -0,0 +1,43 @@
<div id="connectionprofiles_save_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Save connection profile') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="javascript:void(0)">
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input class="input-block-level" type="text" data-bind="value: editor.name, valueUpdate: 'afterkeydown'">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input class="input-block-level" type="text" data-bind="value: editor.identifier, attr: {placeholder: editor.identifierPlaceholder}">
</div>
</div>
<!--
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox"> {{ _('Make default') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox"> {{ _('Attempt auto connect on server start') }}
</label>
</div>
</div>
-->
</form>
</div>
<div class="modal-footer">
<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</a>
<a href="javascript:void(0)" class="btn" aria-hidden="true" data-bind="text: editor.buttonText, click: editor.confirm">{{ _('Save') }}</a>
</div>
</div>
@@ -0,0 +1,30 @@
<h3>{{ _('Connection Profiles') }}</h3>
<table class="table table-striped table-hover table-condensed table-hover" id="settings_connectionProfiles_profiles" data-bind="visible: connectionProfiles.profiles.items().length > 0" style="display: none">
<thead>
<tr>
<th class="settings_connectionProfiles_profiles_name">{{ _('Name') }}</th>
<th class="settings_connectionProfiles_profiles_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: connectionProfiles.profiles.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_connectionProfiles_profiles_name"><span data-bind="text: name"></span></td>
<td class="settings_connectionProfiles_profiles_action">
<a href="#" class="fa fa-trash-o" title="{{ _('Delete Profile') }}" data-bind="click: function() { if ($root.connectionProfiles.canRemove($data) && !$root.connectionProfiles.requestInProgress()) { $root.connectionProfiles.removeProfile($data); } }, css: {disabled: !$root.connectionProfiles.canRemove($data) || $root.connectionProfiles.requestInProgress()}, enabled: $root.connectionProfiles.canRemove($data) && !$root.connectionProfiles.requestInProgress()"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: connectionProfiles.profiles.currentPage() === 0}"><a href="#" data-bind="click: connectionProfiles.profiles.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: connectionProfiles.profiles.pages">
<li data-bind="css: { active: $data.number === $root.connectionProfiles.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.connectionProfiles.profiles.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: connectionProfiles.profiles.currentPage() === connectionProfiles.profiles.lastPage()}"><a href="#" data-bind="click: connectionProfiles.profiles.nextPage">»</a></li>
</ul>
</div>
+2
View File
@@ -134,6 +134,8 @@
{% include 'dialogs/about.jinja2' %}
{% include 'dialogs/files.jinja2' %}
{% include 'dialogs/temperature.jinja2' %}
{% include 'dialogs/connection.jinja2' %}
{% include 'dialogs/connectionprofiles.jinja2' %}
<!-- End of dialogs -->
<!-- Overlays -->
@@ -1,24 +1,36 @@
<form>
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Printer Profile') }}</label>
<select class="input-block-level" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Connection Profile') }}</label>
<select class="input-block-level" data-bind="options: availableConnectionProfiles, optionsText: 'name', value: selectedConnectionProfile, optionsCaption: 'New...', css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label class="checkbox">
<input type="checkbox" data-bind="checked: adjustConnectionParameters, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Adjust connection parameters') }}
<input type="checkbox" data-bind="checked: adjustConnectionParameters"> {{ _('Adjust connection parameters') }}
</label>
<div style="display: none" data-bind="visible: adjustConnectionParameters">
<hr style="margin: 0">
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Printer Profile') }}</label>
<select class="input-block-level" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<hr style="margin: 0">
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Protocol') }}</label>
<select class="input-block-level" data-bind="options: availableProtocols, optionsText: 'name', value: selectedProtocol, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<!-- ko foreach: protocolParameters -->
<!-- ko if: !advanced -->
<!-- ko template: { name: 'connection_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
<!-- ko if: advancedProtocolParameters -->
<small class="text-block text-right"><a href="javascript:void(0)" data-bind="click: showAdvancedProtocolOptions">{{ _('Advanced...') }}</a></small>
<!-- /ko -->
<hr style="margin: 0">
<label data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Transport') }}</label>
<select class="input-block-level" data-bind="options: availableTransports, optionsText: 'name', value: selectedTransport, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<!-- ko foreach: transportParameters -->
<!-- ko if: !advanced -->
<!-- ko template: { name: 'connection_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /ko -->
<label class="checkbox">
<input type="checkbox" id="connection_update_profile" data-bind="checked: updateProfile, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Update printer profile on connect') }}
</label>
<!-- /ko -->
<!-- ko if: advancedTransportParameters -->
<small class="text-block text-right"><a href="javascript:void(0)">{{ _('Advanced...') }}</a></small>
<!-- /ko -->
<hr style="margin: 0">
</div>
<label class="checkbox">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Save connection settings') }}
@@ -28,7 +40,8 @@
</label>
</form>
<button class="btn btn-block" id="printer_connect" data-bind="click: connect, text: buttonText">{{ _('Connect') }}</button>
<button class="btn btn-block" id="printer_connect_and_save" data-bind="click: function() { connect(true) }, visible: isErrorOrClosed() && adjustConnectionParameters()">{{ _('Save & Connect') }}</button>
<button class="btn btn-primary btn-block" id="printer_connect" data-bind="click: function() { connect() }, text: buttonText">{{ _('Connect') }}</button>
<script type="text/html" id="connection_template_text">
<label data-bind="text: $data.title, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></label>
@@ -38,10 +51,27 @@
<label data-bind="text: $data.title, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></label>
<input class="input-block-level" type="number" step="1" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()">
</script>
<script type="text/html" id="connection_template_float">
<label data-bind="text: $data.title, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></label>
<input class="input-block-level" type="number" data-bind="value: $data.value, attr: {placeholder: $data.default, min: $data.min, max: $data.max}, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()">
</script>
<script type="text/html" id="connection_template_choice">
<label data-bind="text: $data.title, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></label>
<select class="input-block-level" data-bind="options: $data.choices, optionsText: 'title', optionsValue: 'value', value: $data.value, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></select>
</script>
<script type="text/html" id="connection_template_smallchoice">
<label data-bind="text: $data.title, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></label>
<!-- ko foreach: choices -->
<label class="radio">
<input type="radio" data-bind="attr: { name: 'connection_dialog_' + $parent.name + '_group' }, value: $data.value, checked: $parent.value"> <span data-bind="text: $data.title"></span>
</label>
<!-- /ko -->
</script>
<script type="text/html" id="connection_template_boolean">
<label class="checkbox">
<input type="checkbox" data-bind="checked: $data.value, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"> <span data-bind="text: $data.title"></span>
</label>
</script>
<script type="text/html" id="connection_template_suggestion">
<label data-bind="text: $data.title, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></label>
<select class="input-block-level" data-bind="options: $data.suggestions, optionsText: 'title', optionsValue: 'value', value: $data.value, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></select>
@@ -50,3 +80,9 @@
<label data-bind="text: $data.title, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></label>
<textarea data-bind="value: $data.value, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()"></textarea>
</script>
<script type="text/html" id="connection_template_group">
<label data-bind="text: $data.title"></label>
<!-- ko foreach: params -->
<!-- ko template: { name: 'connection_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /ko -->
</script>