🚧 WIP: adding new conditionalgroup parameter type

Needs to be wired up to frontend. Supposed to be used to distinguish
between connect via port/usbid/url for SerialTransport. Should make
save&connect and autoconnect easier.
This commit is contained in:
Gina Häußge committed 2021-03-17 17:59:33 +01:00
1 parent 236cb56b49
commit 35c3acf610
7 files changed
+133 -60

No files matched your search

@@ -56,9 +56,9 @@ from octoprint.comm.transport import (
from octoprint.comm.util.parameters import (
BooleanType,
FloatType,
GroupChoiceType,
IntegerType,
ParamGroup,
PresetChoiceType,
SmallChoiceType,
SmallListType,
Value,
@@ -192,7 +192,7 @@ class ReprapGcodeProtocol(
@classmethod
def get_connection_options(cls):
return [
GroupChoiceType(
PresetChoiceType(
"flavor",
"Firmware Flavor",
sorted(
+1 -2
View File
@@ -17,13 +17,12 @@ _registry = {}
def register_transports(settings):
from .serialtransport import SerialTransport, SerialUrlTransport
from .serialtransport import SerialTransport
from .sockettransport import SerialOverTcpTransport, TcpTransport
# stock transports
for transport in (
SerialTransport,
SerialUrlTransport,
TcpTransport,
SerialOverTcpTransport,
):
+93 -47
View File
@@ -10,6 +10,7 @@ from octoprint.comm.transport import Transport
from octoprint.comm.util.parameters import (
BooleanType,
ChoiceType,
ConditionalGroup,
IntegerType,
ListType,
SmallChoiceType,
@@ -54,18 +55,56 @@ class SerialTransport(Transport):
@classmethod
def get_connection_options(cls):
return [
SuggestionType(
"port",
gettext("Port"),
cls.get_available_serial_ports(),
lambda value: Value(value),
),
SuggestionType(
"baudrate",
gettext("Baudrate"),
cls.get_available_baudrates(),
lambda value: Value(value),
default=0,
ConditionalGroup(
"connect_via",
gettext("Connect via"),
[
Value("port", title=gettext("Port & baudrate")),
Value("usbid", title=gettext("USB ID & baudrate")),
Value("url", title=gettext("URL")),
],
{
"port": [
SuggestionType(
"port",
gettext("Port"),
cls.get_available_serial_ports("port"),
lambda value: Value(value),
),
SuggestionType(
"baudrate",
gettext("Baudrate"),
cls.get_available_baudrates(),
lambda value: Value(value),
default=0,
),
],
"usbid": [
SuggestionType(
"usbid",
gettext("USB ID"),
cls.get_available_serial_ports("usbid"),
lambda value: Value(value),
),
SuggestionType(
"baudrate",
gettext("Baudrate"),
cls.get_available_baudrates(),
lambda value: Value(value),
default=0,
),
],
"url": [
UrlType(
"url",
"URL",
help=gettext(
"See [here](https://pythonhosted.org/pyserial/url_handlers.html#urls) for supported URL schemes"
),
)
],
},
default="port",
),
] + cls._get_common_options()
@@ -128,23 +167,25 @@ class SerialTransport(Transport):
]
@classmethod
def get_available_serial_ports(cls):
def get_available_serial_ports(cls, focus):
from serial.tools.list_ports import comports
def port_title(port):
if port.vid and port.pid:
# usb
return "{desc} [{vid:04x}:{pid:04x}]".format(
desc=port.description, vid=port.vid, pid=port.pid
)
matcher = lambda x: True
if focus == "usbid":
matcher = lambda x: x.vid and x.pid
def port_value(port):
if focus == "usbid":
vidpid = f"{port.vid:04x}:{port.pid:04x}"
return Value(vidpid, title=f"{port.description} [{vidpid}]")
else:
return port.description
return Value(port.device, title=f"{port.description} [{port.device}]")
port_values = [Value(None, title="Auto detect")] + sorted(
[
Value(port.device, title=port_title(port))
port_value(port)
for port in comports()
if port.device not in cls.ignored_ports
if port.device not in cls.ignored_ports and matcher(port)
],
key=lambda x: x.title,
)
@@ -279,13 +320,41 @@ class SerialTransport(Transport):
@classmethod
def _create_serial(cls, **kwargs):
focus = kwargs["connect_via"]
if focus == "port":
return cls._create_serial_for_port_and_baudrate(
kwargs.get("port"), kwargs.get("baudrate")
)
elif focus == "usbid":
from serial.tools.list_ports import comports
usbid = kwargs.get("usbid")
vid, pid = usbid.split(":")
for port in comports():
if f"{port.vid:04x}" == vid and f"{port.pid:04x}" == pid:
return cls._create_serial_for_port_and_baudrate(
port.device, kwargs.get("baudrate")
)
else:
raise ValueError(f"Can't find USB ID to connect to: {usbid}")
elif focus == "url":
serial_obj = serial.serial_for_url(kwargs.get("url"), do_not_open=True)
return serial_obj
else:
raise ValueError(f"Invalid connect_via: {focus}")
@classmethod
def _create_serial_for_port_and_baudrate(cls, port, baudrate, **kwargs):
serial_obj = serial.Serial(
baudrate=kwargs.get("baudrate"),
baudrate=baudrate,
exclusive=kwargs.get("exclusive"),
parity=kwargs.get("parity"),
write_timeout=kwargs.get("write_timeout", 10) * 1000,
)
serial_obj.port = kwargs.get("port") # set port only now to prevent auto open
serial_obj.port = port # set port only now to prevent auto open
return serial_obj
@classmethod
@@ -321,29 +390,6 @@ class SerialTransport(Transport):
return "SerialTransport"
class SerialUrlTransport(SerialTransport):
name = "Serial URL Connection"
key = "serialurl"
message_integrity = False
@classmethod
def get_connection_options(cls):
return [
UrlType(
"url",
"URL",
help=gettext(
"See [here](https://pythonhosted.org/pyserial/url_handlers.html#urls) for supported URL schemes"
),
)
] + cls._get_common_options()
@classmethod
def _create_serial(cls, **kwargs):
serial_obj = serial.serial_for_url(kwargs.get("url"), do_not_open=True)
return serial_obj
if __name__ == "__main__":
# list ports
ports = SerialTransport.get_available_serial_ports()
+22 -3
View File
@@ -20,9 +20,12 @@ def get_param_defaults(options):
for option in options:
if option.type == "group":
result[option.name] = get_param_defaults(option.params)
elif option.type == "groupchoice":
elif option.type == "presetchoice":
result[option.name] = option.default
result[option.group.name] = option.defaults
elif option.type == "conditionalgroup":
result[option.name] = option.default
result.update(get_param_defaults(option.groups.get(option.default, [])))
else:
result[option.name] = option.default
return result
@@ -198,8 +201,8 @@ class SmallChoiceType(ChoiceType):
type = "smallchoice"
class GroupChoiceType(ChoiceType):
type = "groupchoice"
class PresetChoiceType(ChoiceType):
type = "presetchoice"
def __init__(self, name, title, choices, group, defaults=None, **kwargs):
if defaults is None:
@@ -217,6 +220,22 @@ class GroupChoiceType(ChoiceType):
return result
class ConditionalGroup(ChoiceType):
type = "conditionalgroup"
def __init__(self, name, title, choices, groups, **kwargs):
ChoiceType.__init__(self, name, title, choices, **kwargs)
self.groups = groups
def as_dict(self):
result = ChoiceType.as_dict(self)
result["groups"] = {
key: list(map(lambda x: x.as_dict(), value))
for key, value in self.groups.items()
}
return result
class SuggestionType(ParamType):
type = "suggestion"
@@ -12,7 +12,7 @@ $(function () {
return _.any(params, function (p) {
if (p.type === "group") {
return check(p) || checkRecursively(p.params, check);
} else if (p.type === "groupchoice" && p.group) {
} else if (p.type === "presetchoice" && p.group) {
return (
check(p) ||
check(p.group) ||
@@ -60,7 +60,7 @@ $(function () {
return p.expert;
});
} else {
if (option.type === "groupchoice") {
if (option.type === "presetchoice") {
value = convertValue(value, option);
_.each(option.group.params, function (p) {
extendOption(
@@ -87,7 +87,7 @@ $(function () {
return option.value() != option.defaultValue();
});
if (option.type === "groupchoice" && option.defaults) {
if (option.type === "presetchoice" && option.defaults) {
option.group.advancedParameters =
option.group.advanced ||
_.any(option.group.params, function (p) {
@@ -456,7 +456,7 @@ $(function () {
_.each(parameters, function (parameter) {
if (parameter.type === "group") {
result[parameter.name] = toOptions(parameter.params);
} else if (parameter.type === "groupchoice") {
} else if (parameter.type === "presetchoice") {
result[parameter.name] = parameter.value();
result[parameter.group.name] = toOptions(
parameter.group.params
@@ -114,7 +114,7 @@
</div>
</div>
</script>
<script type="text/html" id="connection_dialog_template_groupchoice">
<script type="text/html" id="connection_dialog_template_presetchoice">
<div class="control-group" data-bind="css: { 'control-changed': $data.modified }">
<a href="javascript:void(0)" class="fa fa-undo control-undo" title="Reset to default" data-bind="click: reset, visible: $data.modified() && $root.isErrorOrClosed()"></a>
<label class="control-label" data-bind="markdownInline: $data.title, css: { 'control-changed': $data.modified }"></label>
@@ -112,7 +112,7 @@
<!-- ko template: { name: 'connection_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /ko -->
</script>
<script type="text/html" id="connection_template_groupchoice">
<script type="text/html" id="connection_template_presetchoice">
<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>
<!-- ko if: !$data.group.advanced -->
@@ -124,3 +124,12 @@
<!-- /ko -->
<!-- /ko -->
</script>
<script type="text/html" id="connection_template_conditionalgroup">
<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>
<!-- ko foreach: $data.groups[$data.value] -->
<!-- ko if: !advanced -->
<!-- ko template: { name: 'connection_template_' + $data.type, data: $data } --><!-- /ko -->
<!-- /ko -->
<!-- /ko -->
</script>