Join connection dialog with new comm layer

This commit is contained in:
Gina Häußge committed 2018-06-29 20:55:54 +02:00
1 parent 5d0cb14f71
commit 3173783620
22 files changed
+464 -189

No files matched your search

+57 -3
View File
@@ -5,19 +5,65 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.util.listener import ListenerAware
from octoprint.comm.transport import TransportListener, TransportState
from octoprint.plugin import plugin_manager
from octoprint.util import to_unicode, CountedEvent
from octoprint.util.listener import ListenerAware
import contextlib
import copy
import logging
_registry = dict()
def register_protocols():
from .reprap import ReprapGcodeProtocol
logger = logging.getLogger(__name__)
# stock protocols
register_protocol(ReprapGcodeProtocol)
# more protocols provided by plugins
hooks = plugin_manager().get_hooks(b"octoprint.comm.protocol.register")
for name, hook in hooks.items():
try:
protocols = hook()
for protocol in protocols:
try:
register_protocol(protocol)
except:
logger.exception("Error while registering protocol class {} for plugin {}".format(protocol, name))
except:
logger.exception("Error executing octoprint.comm.protocol.register hook for plugin {}".format(name))
def register_protocol(protocol_class):
if not hasattr(protocol_class, "key"):
raise ValueError("Protocol class {} is missing key".format(protocol_class))
_registry[protocol_class.key] = protocol_class
def lookup_protocol(key):
return _registry.get(key)
def all_protocols():
return _registry.values()
class Protocol(ListenerAware, TransportListener):
name = None
key = None
supported_jobs = []
def __init__(self):
@classmethod
def get_connection_options(cls):
return []
def __init__(self, *args, **kwargs):
super(Protocol, self).__init__()
self._logger = logging.getLogger(__name__)
@@ -29,6 +75,14 @@ class Protocol(ListenerAware, TransportListener):
self._job_on_hold = CountedEvent()
self._args = dict()
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@contextlib.contextmanager
def job_put_on_hold(self, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
+25 -8
View File
@@ -15,11 +15,13 @@ 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
from octoprint.comm.protocol.reprap.flavors import GenericFlavor, all_flavors, lookup_flavor
from octoprint.comm.protocol.reprap.util import normalize_command_handler_result, SendToken, LineHistory, PositionRecord, TemperatureRecord
from octoprint.comm.protocol.reprap.util.queues import ScriptQueue, CommandQueue, SendQueue, QueueMarker, SendQueueMarker
from octoprint.comm.util.parameters import ChoiceType, Value
from octoprint.comm.job import LocalGcodeFilePrintjob, SDFilePrintjob, \
LocalGcodeStreamjob, CopyJobMixin
@@ -33,6 +35,7 @@ except ImportError:
import Queue as queue
import collections
import copy
import logging
import threading
import time
@@ -76,11 +79,19 @@ CAPABILITY_BUSY_PROTOCOL = "BUSY_PROTOCOL"
class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProtocolMixin,
FanControlProtocolMixin, FileStreamingProtocolMixin,
PushingTransportWrapperListener, TransportListener):
name = "Reprap GCODE Protocol"
key = "reprap"
supported_jobs = [LocalGcodeFilePrintjob,
LocalGcodeStreamjob,
SDFilePrintjob]
@classmethod
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")]
@staticmethod
def get_flavor_attributes_starting_with(flavor, prefix):
return [x for x in dir(flavor) if x.startswith(prefix)]
@@ -99,10 +110,19 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
temperature_interval_autoreport=2.0,
sd_status_interval=2.0,
sd_status_interval_autoreport=1.0,
plugin_manager=None):
super(ReprapGcodeProtocol, self).__init__()
plugin_manager=None,
event_bus=None,
*args,
**kwargs):
super(ReprapGcodeProtocol, self).__init__(*args, **kwargs)
self.flavor = lookup_flavor(flavor)
if self.flavor is None:
self.flavor = GenericFlavor
self.set_current_args(flavor=self.flavor.key)
self._plugin_manager = plugin_manager
self._event_bus = event_bus
self._logger = logging.getLogger(__name__)
self._commdebug_logger = logging.getLogger("COMMDEBUG")
@@ -110,7 +130,6 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._terminal_log = collections.deque([], 20)
self.flavor = flavor if flavor is not None else GenericFlavor
self.timeouts = dict(
connection=connection_timeout,
communication=communication_timeout,
@@ -1156,8 +1175,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self.notify_listeners("on_protocol_position_all_update", self, position, reason=reason)
def _on_message_firmware_info(self, firmware_name, data):
# TODO
#self._event_bus.fire(Events.FIRMWARE_DATA, dict(name=firmware_name, data=copy.copy(data)))
self._event_bus.fire(Events.FIRMWARE_DATA, dict(name=firmware_name, data=copy.copy(data)))
if not self._internal_flags["firmware_identified"] and firmware_name:
self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name))
@@ -1424,8 +1442,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._process_command_phase("queued", command)
if self._internal_flags["trigger_events"] and isinstance(command, GcodeCommand) and command.code in GCODE_TO_EVENT:
# TODO inject eventbus
#self._eventbus.fire(gcode_to_event[command.code])
self._event_bus.fire(GCODE_TO_EVENT[command.code])
pass
return True
else:
@@ -8,6 +8,7 @@ from .generic import *
from .marlin import *
from .repetier import *
from .reprapfirmware import *
from .smoothieware import *
from .anet import *
from .malyan import *
@@ -1,9 +1,11 @@
from __future__ import absolute_import, unicode_literals
from .repetier import RepetierFlavor
class AnetA8RepetierFlavor(RepetierFlavor):
key = "aneta8repetier"
name = "Anet A8"
@classmethod
def identifier(cls, firmware_name, firmware_info):
@@ -27,7 +27,7 @@ def all_flavors():
return _flavor_registry.values()
def flavor(key):
def lookup_flavor(key):
return _flavor_registry.get(key)
@@ -42,6 +42,7 @@ class GenericFlavor(object):
__metaclass__ = FlavorMeta
key = "generic"
name = "Generic Flavor"
logger = logging.getLogger(__name__)
@@ -1,9 +1,11 @@
from __future__ import absolute_import, unicode_literals
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MalyanFlavor(GenericFlavor):
key = "malyan"
name = "Malyan"
always_send_checksum = False
block_while_dwelling = True
@@ -2,7 +2,6 @@
from __future__ import absolute_import, unicode_literals, print_function, \
division
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -12,9 +11,16 @@ from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MarlinFlavor(GenericFlavor):
key = "marlin"
name = "Marlin"
class BqMarlinFlavor(MarlinFlavor):
key = "bqmarlin"
name = "Marlin: BQ variant"
long_running_commands = MarlinFlavor.long_running_commands + ["G92", "M800", "M801"]
class PrusaMarlinFlavor(MarlinFlavor):
key = "prusamarlin"
name = "Marlin: Prusa variant"
@@ -16,6 +16,7 @@ import re
class RepetierFlavor(GenericFlavor):
key = "repetier"
name = "Repetier"
always_send_checksum = True
identical_resends_countdown = 5
@@ -1,9 +1,11 @@
from __future__ import absolute_import, unicode_literals
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "reprapfirmware"
name = "RepRapFirmware"
sd_relative_path = True
@@ -0,0 +1,9 @@
from __future__ import absolute_import, unicode_literals
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "smoothieware"
name = "Smoothieware"
+17 -4
View File
@@ -5,8 +5,9 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
from .parameters import get_param_dict
from octoprint.comm.util.parameters import get_param_dict
import copy
import logging
import time
@@ -17,15 +18,15 @@ from octoprint.plugin import plugin_manager
_registry = dict()
def register_transports():
from .serialtransport import SerialTransport, VirtualSerialTransport
from .sockettransport import TcpTransport
from .serialtransport import SerialTransport
from .sockettransport import TcpTransport, SerialOverTcpTransport
logger = logging.getLogger(__name__)
# stock transports
register_transport(SerialTransport)
register_transport(VirtualSerialTransport)
register_transport(TcpTransport)
register_transport(SerialOverTcpTransport)
# more transports provided by plugins
hooks = plugin_manager().get_hooks(b"octoprint.comm.transport.register")
@@ -51,10 +52,15 @@ def lookup_transport(key):
return _registry.get(key)
def all_transports():
return _registry.values()
class Transport(ListenerAware):
name = None
key = None
message_integrity = False
@classmethod
@@ -66,6 +72,13 @@ class Transport(ListenerAware):
self._logger = logging.getLogger(__name__)
self._state = TransportState.DISCONNECTED
self._args = dict()
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@property
def state(self):
+10 -30
View File
@@ -6,7 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, PushingTransportWrapper
from octoprint.comm.transport.parameters import TextType, IntegerType, SuggestionType, ConstantNameType
from octoprint.comm.util.parameters import TextType, IntegerType, SuggestionType, Value
import serial
import logging
@@ -34,8 +34,8 @@ class SerialTransport(Transport):
@classmethod
def get_connection_options(cls):
return [
SuggestionType("port", "Port", TextType, cls.get_available_serial_ports(), default="AUTO"),
SuggestionType("baudrate", "Baudrate", IntegerType, cls.suggested_baudrates, default=0)
SuggestionType("port", "Port", cls.get_available_serial_ports(), lambda value: Value(value)),
SuggestionType("baudrate", "Baudrate", cls.get_available_baudrates(), lambda value: Value(value), default=0)
]
@classmethod
@@ -68,12 +68,15 @@ class SerialTransport(Transport):
from serial.tools import list_ports_common
ports = [list_ports_common.ListPortInfo(d) for d in devices]
return [ConstantNameType(port.device, port.description) for port in ports]
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
return port_values
@classmethod
def get_available_baudrates(cls):
return [ConstantNameType(0, "Auto detect")] + \
[ConstantNameType(baudrate, baudrate) for baudrate in cls.suggested_baudrates]
return [Value(0, title="Auto detect")] + \
sorted([Value(baudrate) for baudrate in cls.suggested_baudrates], key=lambda x: x.title, reverse=True)
def __init__(self, *args, **kwargs):
super(SerialTransport, self).__init__()
@@ -92,6 +95,7 @@ class SerialTransport(Transport):
self._closing = False
self._serial = factory(port=port, baudrate=baudrate)
self.set_current_args(port=port, baudrate=baudrate)
def drop_connection(self):
if self._serial is not None:
@@ -154,30 +158,6 @@ class SerialTransport(Transport):
def __str__(self):
return "SerialTransport"
class VirtualSerialTransport(SerialTransport):
name = "Virtual Serial Connection"
key = "virtual"
@classmethod
def get_connection_options(cls):
return []
def __init__(self, *args, **kwargs):
super(VirtualSerialTransport, self).__init__()
self.virtual_serial_factory = kwargs.get("virtual_serial_factory", None)
def create_connection(self, *args, **kwargs):
if self.virtual_serial_factory is None:
raise ValueError("virtual_serial_factory is unset")
if not callable(self.virtual_serial_factory):
raise ValueError("virtual_serial_factory is not callable")
self._serial = self.virtual_serial_factory()
def __str__(self):
return "VirtualSerialTransport({})".format(self.virtual_serial_factory)
if __name__ == "__main__":
# list ports
ports = SerialTransport.get_available_serial_ports()
@@ -6,13 +6,13 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.transport import Transport, LineAwareTransportWrapper
from octoprint.comm.transport.parameters import TextType, IntegerType
from octoprint.comm.util.parameters import TextType, IntegerType
import socket
class TcpTransport(Transport):
name = "TCP Transport"
name = "TCP Connection"
key = "tcpsocket"
message_integrity = True
@@ -20,7 +20,7 @@ class TcpTransport(Transport):
def get_connection_options(cls):
return [
TextType("host", "Host"),
IntegerType("port", "Port", min=1)
IntegerType("port", "Port", min=1, max=65535)
]
def __init__(self):
@@ -36,6 +36,7 @@ class TcpTransport(Transport):
self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
self._socket.connect((host, port))
self.set_current_args(host=host, port=port)
def drop_connection(self):
self._socket.close()
@@ -53,13 +54,6 @@ class TcpTransport(Transport):
class SerialOverTcpTransport(TcpTransport):
name = "Serial over TCP Transport"
name = "Serial Connection over TCP"
key = "serialovertcpsocket"
message_integrity = False
if __name__ == "__main__":
transport = LineAwareTransportWrapper(TcpTransport())
transport.connect(host="google.de", port=80)
transport.write(b"GET / HTTP/1.1\r\n\r\n")
while(True):
print("<<< {!r}".format(transport.read()))
View File
Whitespace-only changes.
@@ -1,7 +1,6 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -19,11 +18,19 @@ def get_param_dict(data, options):
class ParamType(object):
type = "generic"
def __init__(self, name, title, default=None):
self.name = name
self.title = title
self.default = default
def as_dict(self):
return dict(name=self.name,
title=self.title,
default=self.default,
type=self.type)
def convert(self, value):
return value
@@ -32,17 +39,27 @@ class ParamType(object):
+ ", ".join(["{}={!r}".format(key, value) for key, value in self.__dict__.items() if not key.startswith("_")]) + ")"
class TextType(ParamType):
type = "text"
def convert(self, value):
if isinstance(value, bytes):
value = value.decode("utf-8", "replace")
return value
class IntegerType(ParamType):
type = "integer"
def __init__(self, name, title, min=None, max=None, default=None):
self.min = min
self.max = max
ParamType.__init__(self, name, title, default=default)
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 = int(value)
@@ -57,40 +74,35 @@ class IntegerType(ParamType):
return value
class ChoiceType(ParamType):
def __init__(self, name, title, choice_type, choices, default=None, choice_type_args=None, choice_type_kwargs=None):
self.choice_type = choice_type
self.choice_type_args = choice_type_args if choice_type_args is not None else []
self.choice_type_kwargs = choice_type_kwargs if choice_type_kwargs is not None else dict()
type = "choice"
def __init__(self, name, title, choices, default=None):
self.choices = choices
ParamType.__init__(self, name, title, default=default)
def convert(self, value):
args = [self.name, self.title] + self.choice_type_args
kwargs = self.choice_type_kwargs
value = self.choice_type(*args, **kwargs).convert(value)
if not value in self.choices:
raise ValueError("value {} is not a valid choice")
return value
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(choices=map(lambda x: x.as_dict(), self.choices)))
return result
class SuggestionType(ParamType):
def __init__(self, name, title, suggestion_type, suggestions, default=None, suggestion_type_args=None, suggestion_type_kwargs=None):
self.suggestion_type = suggestion_type
self.suggestion_type_args = suggestion_type_args if suggestion_type_args is not None else []
self.suggestion_type_kwargs = suggestion_type_kwargs if suggestion_type_kwargs is not None else dict()
type = "suggestion"
def __init__(self, name, title, suggestions, factory, default=None):
self.suggestions = suggestions
self.factory = factory
ParamType.__init__(self, name, title, default=default)
def convert(self, value):
args = [self.name, self.title] + self.suggestion_type_args
kwargs = self.suggestion_type_kwargs
value = self.suggestion_type(*args, **kwargs).convert(value)
return value
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(suggestions=map(lambda x: x.as_dict(), self.suggestions)))
return result
class ListType(ParamType):
def __init__(self, name, title, item_type, default=None, item_type_args=None, item_type_kwargs=None):
self.item_type = item_type
self.item_type_args = item_type_args if item_type_args is not None else []
self.item_type_kwargs = item_type_kwargs if item_type_kwargs is not None else dict()
type = "list"
def __init__(self, name, title, factory, default=None):
self.factory = factory
ParamType.__init__(self, name, title, default=default)
def convert(self, value):
@@ -101,19 +113,13 @@ class ListType(ParamType):
else:
raise ValueError("value {!r} must be either a comma-separated string or a list".format(value))
args = [self.name, self.title] + self.item_type_args
kwargs = self.item_type_kwargs
return map(self.item_type(*args, **kwargs).convert, items)
return map(self.factory, items)
class ConstantType(ParamType):
def __init__(self, name, title, constant, default=None):
ParamType.__init__(self, name, title, default=default)
self.constant = constant
self.default = constant
class Value(object):
def __init__(self, value, title=None):
self.value = value
self.title = title if title else value
def convert(self, value):
return self.constant
class ConstantNameType(ConstantType):
def __init__(self, name, title, default=None):
ConstantType.__init__(self, name, title, constant=name, default=default)
def as_dict(self):
return dict(value=self.value,
title=self.title)
@@ -7,31 +7,24 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import octoprint.plugin
from octoprint.comm.transport.serialtransport import SerialTransport
class VirtualSerialTransport(SerialTransport):
name = "Virtual Connection"
key = "virtual"
@classmethod
def get_connection_options(cls):
return []
def create_connection(self, *args, **kwargs):
from . import virtual
self._serial = virtual.VirtualPrinter()
class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin):
def virtual_printer_factory(self, comm_instance, port, baudrate,
read_timeout):
if not port == "VIRTUAL":
return None
if not self._settings.global_get_boolean(
["devel", "virtualPrinter", "enabled"]):
return None
import logging.handlers
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
seriallog_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="serial"),
when="D",
backupCount=3)
seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
seriallog_handler.setLevel(logging.DEBUG)
from . import virtual
serial_obj = virtual.VirtualPrinter(seriallog_handler=seriallog_handler,
read_timeout=float(read_timeout))
return serial_obj
def register_transport_hook(self, *args, **kwargs):
return [VirtualSerialTransport]
__plugin_name__ = "Virtual Printer"
@@ -49,5 +42,5 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory
"octoprint.comm.transport.register": plugin.register_transport_hook
}
+1 -1
View File
@@ -75,7 +75,7 @@ class PrinterInterface(object):
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs):
def connect(self, protocol=None, protocol_options=None, transport=None, transport_options=None, profile=None, *args, **kwargs):
"""
Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a
connection is already established, that connection will be closed prior to connecting anew with the provided
+48 -13
View File
@@ -263,13 +263,25 @@ class Printer(PrinterInterface,
eventManager().fire(Events.CONNECTING)
##~~ Logging
if not logging.getLogger("SERIAL").isEnabledFor(logging.DEBUG):
# if serial.log is not enabled, log a line to explain that to reduce "serial.log is empty" in tickets...
logging.getLogger("SERIAL").info("serial.log is currently not enabled, you can enable it via Settings > Serial Connection > Log communication to serial.log")
from octoprint.logging.handlers import CommunicationLogHandler
CommunicationLogHandler.on_open_connection(u"TRANSPORT")
CommunicationLogHandler.on_open_connection(u"PROTOCOL")
CommunicationLogHandler.on_open_connection(u"COMMDEBUG")
##~~ Printer profile
profile = kwargs.get("profile")
if not profile:
profile = self._printer_profile_manager.get_default()["id"]
self._printer_profile_manager.select(profile)
if not logging.getLogger("SERIAL").isEnabledFor(logging.DEBUG):
# if serial.log is not enabled, log a line to explain that to reduce "serial.log is empty" in tickets...
logging.getLogger("SERIAL").info("serial.log is currently not enabled, you can enable it via Settings > Serial Connection > Log communication to serial.log")
##~~ Transport
selected_transport = kwargs.get("transport")
if not selected_transport:
@@ -286,27 +298,40 @@ class Printer(PrinterInterface,
transport_connect_kwargs = dict(port=port, baudrate=baudrate)
else:
transport_kwargs = kwargs.get("transport_kwargs", dict())
transport_connect_kwargs = kwargs.get("transport_connect_kwargs", dict())
from octoprint.logging.handlers import CommunicationLogHandler
CommunicationLogHandler.on_open_connection(u"TRANSPORT")
CommunicationLogHandler.on_open_connection(u"PROTOCOL")
CommunicationLogHandler.on_open_connection(u"COMMDEBUG")
transport_connect_kwargs = kwargs.get("transport_options", dict())
from octoprint.comm.transport import lookup_transport
transport_class = lookup_transport(selected_transport)
if not transport_class:
raise ValueError("Invalid transport: {}".format(selected_transport))
transport = transport_class(**transport_kwargs)
self._transport = transport
##~~ Protocol
# TODO make this depend on the printer profile
from octoprint.comm.protocol.reprap import ReprapGcodeProtocol
protocol = ReprapGcodeProtocol(plugin_manager=plugin_manager())
protocol.register_listener(self)
selected_protocol = kwargs.get("protocol")
if not selected_protocol:
selected_protocol = "reprap"
protocol_kwargs = dict()
else:
protocol_kwargs = kwargs.get("protocol_options", dict())
self._transport = transport
protocol_kwargs.update(dict(plugin_manager=plugin_manager(),
event_bus=eventManager()))
from octoprint.comm.protocol import lookup_protocol
protocol_class = lookup_protocol(selected_protocol)
if not protocol_class:
raise ValueError("Invalid protocol: {}".format(selected_protocol))
protocol = protocol_class(**protocol_kwargs)
self._protocol = protocol
##~~ Register everything and connect
self._protocol.register_listener(self)
self._protocol.connect(self._transport, transport_kwargs=transport_connect_kwargs)
def disconnect(self, *args, **kwargs):
@@ -709,6 +734,16 @@ class Printer(PrinterInterface,
printer_profile = self._printer_profile_manager.get_current_or_default()
return self.get_state_string(), port, baudrate, printer_profile
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()
def is_connected(self):
return self._protocol is not None and self._protocol.state in (ProtocolState.CONNECTED, ProtocolState.PROCESSING, ProtocolState.PAUSED)
+4
View File
@@ -419,6 +419,10 @@ class Server(object):
from octoprint.comm.transport import register_transports
register_transports()
# register available protocols
from octoprint.comm.protocol import register_protocols
register_protocols()
# create printer instance
printer_factories = pluginManager.get_hooks("octoprint.printer.factory")
for name, factory in printer_factories.items():
+71 -22
View File
@@ -13,16 +13,32 @@ from octoprint.server.api import api
from octoprint.server.util.flask import require_firstrun, get_json_command_from_request
from octoprint.access.permissions import Permissions
from octoprint.comm.transport import all_transports
from octoprint.comm.protocol import all_protocols
def _convert_transport_options(options):
return [option.as_dict() for option in options]
def _convert_protocol_options(options):
return [option.as_dict() for option in options]
@api.route("/connection", methods=["GET"])
@Permissions.STATUS.require(403)
def connectionState():
state, port, baudrate, printer_profile = printer.get_current_connection()
current = {
"state": state,
"port": port,
"baudrate": baudrate,
"printerProfile": printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default"
}
state, protocol, protocol_options, transport, transport_options, printer_profile = 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)
##~~ legacy
# TODO remove in 1.5.0
_, port, baudrate, _ = printer.get_current_connection()
current.update(dict(port=port, baudrate=baudrate))
return jsonify({"current": current, "options": _get_options()})
@@ -42,39 +58,70 @@ def connectionCommand():
return response
if command == "connect":
connection_options = printer.__class__.get_connection_options()
kwargs = dict()
if "protocol" in data:
kwargs["protocol"] = data["protocol"]
if "protocolOptions" in data:
kwargs["protocol_options"] = data["protocolOptions"]
if "transport" in data:
kwargs["transport"] = data["transport"]
if "transportOptions" in data:
kwargs["transport_options"] = data["transportOptions"]
port = None
baudrate = None
printerProfile = None
if "port" in data.keys():
port = data["port"]
if port not in connection_options["ports"] and port != "AUTO":
return make_response("Invalid port: %s" % port, 400)
if "baudrate" in data.keys():
baudrate = data["baudrate"]
if baudrate not in connection_options["baudrates"] and baudrate != 0:
return make_response("Invalid baudrate: %d" % baudrate, 400)
if "printerProfile" in data.keys():
printerProfile = data["printerProfile"]
if not printerProfileManager.exists(printerProfile):
return make_response("Invalid printer profile: %s" % printerProfile, 400)
kwargs["profile"] = printerProfile
if "save" in data.keys() and data["save"]:
"""
settings().set(["serial", "port"], port)
settings().setInt(["serial", "baudrate"], baudrate)
printerProfileManager.set_default(printerProfile)
printerProfileManager.set_default(kwargs.get("profile"))
"""
if "autoconnect" in data.keys():
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
##~~ legacy
# TODO remove in 1.5.0
if "port" in data.keys():
kwargs["port"] = data["port"]
if "baudrate" in data.keys():
kwargs["baudrate"] = data["baudrate"]
settings().save()
printer.connect(port=port, baudrate=baudrate, profile=printerProfile)
printer.connect(**kwargs)
elif command == "disconnect":
printer.disconnect()
elif command == "fake_ack":
printer.fake_ack()
return NO_CONTENT
def _get_options():
transports = []
for transport in all_transports():
transports.append(dict(name=transport.name,
key=transport.key,
options=_convert_transport_options(transport.get_connection_options())))
protocols = []
for protocol in all_protocols():
protocols.append(dict(name=protocol.name,
key=protocol.key,
options=_convert_protocol_options(protocol.get_connection_options())))
connection_options = printer.__class__.get_connection_options()
profile_options = printerProfileManager.get_all()
default_profile = printerProfileManager.get_default()
@@ -85,7 +132,9 @@ def _get_options():
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],
portPreference=connection_options["portPreference"],
baudratePreference=connection_options["baudratePreference"],
printerProfilePreference=default_profile["id"] if "id" in default_profile else None
printerProfilePreference=default_profile["id"] if "id" in default_profile else None,
protocols=protocols,
transports=transports
)
return options
@@ -21,12 +21,39 @@ $(function() {
self.selectedPrinter(self.printerProfiles.currentProfile());
});
self.portOptions = ko.observableArray(undefined);
self.baudrateOptions = ko.observableArray(undefined);
self.printerOptions = ko.observableArray(undefined);
self.selectedPort = ko.observable(undefined);
self.selectedBaudrate = ko.observable(undefined);
self.selectedPrinter = ko.observable(undefined);
// Protocol
self.availableProtocols = ko.observableArray();
self.selectedProtocol = ko.observable(undefined);
self.protocolParameters = ko.observable();
self.selectedProtocol.subscribe(function() {
var protocol = self.selectedProtocol();
if (protocol) {
self.protocolParameters(protocol.options);
} else {
self.protocolParameters([]);
}
});
// Transport
self.availableTransports = ko.observableArray();
self.selectedTransport = ko.observable(undefined);
self.transportParameters = ko.observableArray();
self.selectedTransport.subscribe(function() {
var transport = self.selectedTransport();
if (transport) {
self.transportParameters(transport.options);
} else {
self.transportParameters([]);
}
});
self.adjustConnectionParameters = ko.observable(undefined);
self.updateProfile = ko.observable(undefined);
self.saveSettings = ko.observable(undefined);
self.autoconnect = ko.observable(undefined);
@@ -59,22 +86,52 @@ $(function() {
};
self.fromResponse = function(response) {
var ports = response.options.ports;
var baudrates = response.options.baudrates;
var portPreference = response.options.portPreference;
var baudratePreference = response.options.baudratePreference;
var printerPreference = response.options.printerProfilePreference;
var printerProfiles = response.options.printerProfiles;
var profile = response.current.profile;
var profiles = response.options.printerProfiles;
self.portOptions(ports);
self.baudrateOptions(baudrates);
var protocol = response.current.protocol;
var protocolOptions = response.current.protocolOptions;
if (!protocolOptions) {
protocolOptions = {};
}
var protocols = response.options.protocols;
if (!self.selectedPort() && ports && ports.indexOf(portPreference) >= 0)
self.selectedPort(portPreference);
if (!self.selectedBaudrate() && baudrates && baudrates.indexOf(baudratePreference) >= 0)
self.selectedBaudrate(baudratePreference);
if (!self.selectedPrinter() && printerProfiles && printerProfiles.indexOf(printerPreference) >= 0)
self.selectedPrinter(printerPreference);
var transport = response.current.transport;
var transportOptions = response.current.transportOptions;
if (!transportOptions) {
transportOptions = {};
}
var transports = response.options.transports;
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]);
});
});
self.availableProtocols(protocols);
self.selectedProtocol(protocol);
// transport
_.each(transports, function(transport) {
_.each(transport.options, function(option) {
extendOption(option, transportOptions[option.name]);
});
});
self.availableTransports(transports);
self.selectedTransport(transport);
self.saveSettings(false);
};
@@ -120,9 +177,19 @@ $(function() {
self.connect = function() {
if (self.isErrorOrClosed()) {
var toOptions = function(parameters) {
var result = {};
_.each(parameters, function(parameter) {
result[parameter.name] = parameter.value();
});
return result;
};
var data = {
"port": self.selectedPort() || "AUTO",
"baudrate": self.selectedBaudrate() || 0,
"protocol": self.selectedProtocol().key,
"protocolOptions": toOptions(self.protocolParameters()),
"transport": self.selectedTransport().key,
"transportOptions": toOptions(self.transportParameters()),
"printerProfile": self.selectedPrinter(),
"autoconnect": self.settings.serial_autoconnect()
};
@@ -1,13 +1,52 @@
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Serial Port') }}</label>
<select id="connection_ports" data-bind="options: portOptions, optionsCaption: 'AUTO', value: selectedPort, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Baudrate') }}</label>
<select id="connection_baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label for="connection_printers" data-bind="css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()">{{ _('Printer Profile') }}</label>
<select id="connection_printers" data-bind="options: printerOptions, optionsText: 'name', optionsValue: 'id', value: selectedPrinter, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"></select>
<label class="checkbox">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Save connection settings') }}
</label>
<label class="checkbox">
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Auto-connect on server startup') }}
</label>
<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 class="checkbox">
<input type="checkbox" data-bind="checked: adjustConnectionParameters, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Adjust connection parameters') }}
</label>
<div style="display: none" data-bind="visible: adjustConnectionParameters">
<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 template: { name: 'connection_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /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 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>
</div>
<label class="checkbox">
<input type="checkbox" id="connection_save" data-bind="checked: saveSettings, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Save connection settings') }}
</label>
<label class="checkbox">
<input type="checkbox" id="connection_autoconnect" data-bind="checked: settings.serial_autoconnect, css: {disabled: !isErrorOrClosed()}, enable: isErrorOrClosed()"> {{ _('Auto-connect on server startup') }}
</label>
</form>
<button class="btn btn-block" id="printer_connect" data-bind="click: 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>
<input class="input-block-level" type="text" data-bind="value: $data.value, attr: {placeholder: $data.default}, css: {disabled: !$root.isErrorOrClosed()}, enable: $root.isErrorOrClosed()">
</script>
<script type="text/html" id="connection_template_integer">
<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_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_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>
</script>
<script type="text/html" id="connection_template_list">
<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>