✨ Implement serial port auto detection
This commit is contained in:
1 parent
7ffa3595db
commit
b5a7586926
6 files changed
+269
-71
No files matched your search
@@ -4,7 +4,9 @@
|
||||
* UI for connection profiles
|
||||
* UI for transport/protocol settings
|
||||
* SerialTransport:
|
||||
* Auto detection (relies on protocol, which makes this somewhat tricky)
|
||||
* RepRapProtocol:
|
||||
* Anything missing from settings migration to profile?
|
||||
* Disconnect after incomplete connect/reset states
|
||||
* Disconnect after autodetection failure
|
||||
|
||||
TBC
|
||||
@@ -7,7 +7,12 @@ import logging
|
||||
|
||||
import frozendict
|
||||
|
||||
from octoprint.comm.transport import TransportListener, TransportState
|
||||
from octoprint.comm.transport import (
|
||||
TransportListener,
|
||||
TransportOutOfAutodetectionCandidates,
|
||||
TransportRequiresAutodetection,
|
||||
TransportState,
|
||||
)
|
||||
from octoprint.comm.util.parameters import register_settings_overlay
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.settings import SubSettings
|
||||
@@ -367,8 +372,11 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener):
|
||||
self._transport.register_listener(self)
|
||||
|
||||
if self._transport.state == TransportState.DISCONNECTED:
|
||||
self._transport.connect(*transport_args, **transport_kwargs)
|
||||
self.state = ProtocolState.CONNECTING
|
||||
try:
|
||||
self._transport.connect(*transport_args, **transport_kwargs)
|
||||
except TransportRequiresAutodetection:
|
||||
self._transport.start_autodetection(*transport_args, **transport_kwargs)
|
||||
self.state = ProtocolState.CONNECTING
|
||||
|
||||
def disconnect(self, error=False, wait=True, timeout=10.0):
|
||||
if self.state in (
|
||||
@@ -533,6 +541,13 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener):
|
||||
message = f"--- {message}"
|
||||
self.process_protocol_log(message)
|
||||
|
||||
def on_transport_validate_connection(self, transport):
|
||||
try:
|
||||
self._transport.autodetection_step()
|
||||
except TransportOutOfAutodetectionCandidates:
|
||||
# TODO: handle out of candidates situation gracefully
|
||||
raise
|
||||
|
||||
def process_protocol_log(self, message):
|
||||
self._connection_logger.debug(message)
|
||||
self.notify_listeners("on_protocol_log", self, message)
|
||||
|
||||
@@ -189,6 +189,8 @@ class ReprapGcodeProtocol(
|
||||
LOG_PREFIX_MSG = "--- "
|
||||
LOG_PREFIX_WARN = "!!! "
|
||||
|
||||
VALIDATION_RETRIES = 3
|
||||
|
||||
@classmethod
|
||||
def get_connection_options(cls):
|
||||
return [
|
||||
@@ -583,6 +585,25 @@ class ReprapGcodeProtocol(
|
||||
default=10,
|
||||
unit="sec",
|
||||
),
|
||||
FloatType(
|
||||
"first_validation",
|
||||
gettext("Initial validation timeout"),
|
||||
min=1,
|
||||
unit="sec",
|
||||
default=10,
|
||||
advanced=True,
|
||||
expert=True,
|
||||
),
|
||||
FloatType(
|
||||
"consecutive_validation",
|
||||
gettext("Consecutive validation timeout"),
|
||||
min=1,
|
||||
unit="sec",
|
||||
default=2,
|
||||
advanced=True,
|
||||
expert=True,
|
||||
),
|
||||
# TODO This needs to go into transport
|
||||
FloatType(
|
||||
"baudrate_detection_pause",
|
||||
gettext("Initial baudrate detection pause"),
|
||||
@@ -733,6 +754,10 @@ class ReprapGcodeProtocol(
|
||||
"communication_busy": kwargs.get("timeouts", {}).get(
|
||||
"communication_timeout_busy", 2.0
|
||||
),
|
||||
"first_validation": kwargs.get("timeouts", {}).get("first_validation", 10.0),
|
||||
"consecutive_validation": kwargs.get("timeouts", {}).get(
|
||||
"consecutive_validation", 2.0
|
||||
),
|
||||
}
|
||||
self.interval = {
|
||||
"temperature_idle": kwargs.get("intervals", {}).get(
|
||||
@@ -798,6 +823,7 @@ class ReprapGcodeProtocol(
|
||||
}
|
||||
|
||||
self._transport = None
|
||||
self._validation_retry = self.VALIDATION_RETRIES
|
||||
|
||||
self.internal_state = InternalState(self)
|
||||
|
||||
@@ -1722,6 +1748,38 @@ class ReprapGcodeProtocol(
|
||||
def _job_on_hold_cleared(self):
|
||||
self._continue_sending()
|
||||
|
||||
##~~ Connection validation
|
||||
|
||||
def on_transport_validate_connection(self, transport):
|
||||
self._validation_retry = 0
|
||||
self._attempt_validation()
|
||||
|
||||
def _handle_autodetection_timeout(self):
|
||||
if self._validation_retry < self.VALIDATION_RETRIES:
|
||||
self._attempt_validation()
|
||||
else:
|
||||
# still no dice, try next combo
|
||||
self._transport.autodetection_step()
|
||||
|
||||
def _attempt_validation(self):
|
||||
self._validation_retry += 1
|
||||
timeout = (
|
||||
self.timeouts.get("first_validation", 10)
|
||||
if self._validation_retry == 1
|
||||
else self.timeouts.get("consecutive_validation", 2)
|
||||
)
|
||||
self.internal_state.timeout = self.internal_state.ok_timeout = (
|
||||
time.monotonic() + timeout
|
||||
)
|
||||
|
||||
self.process_protocol_log(
|
||||
f"Handshake attempt #{self._validation_retry} with timeout {timeout}s"
|
||||
)
|
||||
|
||||
hello = self.flavor.command_hello()
|
||||
if hello:
|
||||
self._tickle(hello)
|
||||
|
||||
##~~ Transport logging
|
||||
|
||||
def on_transport_log_message(self, transport, data):
|
||||
@@ -1844,6 +1902,12 @@ class ReprapGcodeProtocol(
|
||||
pass
|
||||
|
||||
def _on_comm_any(self, line, lower_line):
|
||||
if self.state == ProtocolState.CONNECTING and (
|
||||
not len(line) or time.monotonic() > self.internal_state.ok_timeout
|
||||
):
|
||||
self._handle_autodetection_timeout()
|
||||
return
|
||||
|
||||
timeout, _ = self.flavor.comm_timeout(line, lower_line)
|
||||
if not timeout:
|
||||
self.internal_state.timeout_consecutive = 0
|
||||
@@ -1867,11 +1931,6 @@ class ReprapGcodeProtocol(
|
||||
):
|
||||
self.internal_state.dwelling_until = False
|
||||
|
||||
if self.state == ProtocolState.CONNECTING and len(line):
|
||||
hello = self.flavor.command_hello()
|
||||
if hello:
|
||||
self._tickle(hello)
|
||||
|
||||
if (
|
||||
self._resend_ok_timer
|
||||
and line
|
||||
|
||||
@@ -177,6 +177,7 @@ class Transport(ListenerAware):
|
||||
options = self.get_connection_options()
|
||||
param_dict = get_param_dict(params, options)
|
||||
|
||||
self.state = TransportState.CONNECTING
|
||||
self.create_connection(**param_dict)
|
||||
|
||||
self.state = TransportState.CONNECTED
|
||||
@@ -207,6 +208,14 @@ class Transport(ListenerAware):
|
||||
def check_connection(self, *args, **kwargs):
|
||||
return True
|
||||
|
||||
def start_autodetection(self, *args, **kwargs):
|
||||
self.do_init_autodetection(*args, **kwargs)
|
||||
self.autodetection_step()
|
||||
|
||||
def autodetection_step(self):
|
||||
self.do_autodetection_step()
|
||||
self.notify_listeners("on_transport_validate_connection", self)
|
||||
|
||||
def read(self, size=None, timeout=None):
|
||||
data = self.do_read(size=size, timeout=timeout)
|
||||
self.notify_listeners("on_transport_log_received_data", self, data)
|
||||
@@ -226,11 +235,22 @@ class Transport(ListenerAware):
|
||||
def do_write(self, data):
|
||||
pass
|
||||
|
||||
def do_init_autodetection(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def do_autodetection_step(self):
|
||||
pass
|
||||
|
||||
def process_transport_log(self, message):
|
||||
self._logger.info(message)
|
||||
self.notify_listeners("on_transport_log_message", self, message)
|
||||
|
||||
def __str__(self):
|
||||
return self.__class__.__name__
|
||||
|
||||
|
||||
class TransportState:
|
||||
CONNECTING = "connecting"
|
||||
CONNECTED = "connected"
|
||||
DISCONNECTED = "disconnected"
|
||||
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
|
||||
@@ -367,7 +387,10 @@ class PushingTransportWrapper(TransportWrapper):
|
||||
return self._receiver_active
|
||||
|
||||
def connect(self, **kwargs):
|
||||
self.transport.connect(**kwargs)
|
||||
try:
|
||||
self.transport.connect(**kwargs)
|
||||
except TransportRequiresAutodetection:
|
||||
self.transport.start_autodetection(**kwargs)
|
||||
|
||||
import threading
|
||||
|
||||
@@ -382,8 +405,8 @@ class PushingTransportWrapper(TransportWrapper):
|
||||
self._receiver_active = False
|
||||
self.transport.disconnect(*args, **kwargs)
|
||||
|
||||
def wait(self):
|
||||
self._receiver_thread.join()
|
||||
def wait(self, timeout=None):
|
||||
self._receiver_thread.join(timeout)
|
||||
|
||||
def _receiver_loop(self):
|
||||
while self._receiver_active:
|
||||
@@ -407,6 +430,12 @@ class TransportListener:
|
||||
def on_transport_disconnected(self, transport, error=None):
|
||||
pass
|
||||
|
||||
def on_transport_autodetecting(self, transport):
|
||||
pass
|
||||
|
||||
def on_transport_validate_connection(self, transport):
|
||||
pass
|
||||
|
||||
def on_transport_log_sent_data(self, transport, data):
|
||||
pass
|
||||
|
||||
@@ -435,3 +464,11 @@ class TimeoutTransportException(TransportException):
|
||||
|
||||
class EofTransportException(TransportException):
|
||||
pass
|
||||
|
||||
|
||||
class TransportRequiresAutodetection(TransportException):
|
||||
pass
|
||||
|
||||
|
||||
class TransportOutOfAutodetectionCandidates(TransportException):
|
||||
pass
|
||||
@@ -5,8 +5,13 @@ import logging
|
||||
import os
|
||||
|
||||
import serial
|
||||
from serial.tools.list_ports import comports
|
||||
|
||||
from octoprint.comm.transport import Transport
|
||||
from octoprint.comm.transport import (
|
||||
Transport,
|
||||
TransportRequiresAutodetection,
|
||||
TransportState,
|
||||
)
|
||||
from octoprint.comm.util.parameters import (
|
||||
BooleanType,
|
||||
ChoiceType,
|
||||
@@ -30,6 +35,7 @@ class SerialTransport(Transport):
|
||||
max_write_passes = 5
|
||||
|
||||
baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
|
||||
autodetection_baudrates = [115200, 250000]
|
||||
ignored_ports = [
|
||||
"/dev/ttyAMA0",
|
||||
"/dev/ttyS*",
|
||||
@@ -43,6 +49,13 @@ class SerialTransport(Transport):
|
||||
factory=int,
|
||||
default=baudrates,
|
||||
),
|
||||
ListType(
|
||||
"autodetection_baudrates",
|
||||
gettext("Autodetection baudrates"),
|
||||
sep="\n",
|
||||
factory=int,
|
||||
default=autodetection_baudrates,
|
||||
),
|
||||
ListType(
|
||||
"ignored_ports",
|
||||
gettext("Ignored ports"),
|
||||
@@ -143,6 +156,14 @@ class SerialTransport(Transport):
|
||||
@classmethod
|
||||
def _get_common_options(cls):
|
||||
return [
|
||||
IntegerType(
|
||||
"read_timeout",
|
||||
gettext("Read Timeout"),
|
||||
min=1,
|
||||
unit="sec",
|
||||
default=2,
|
||||
advanced=True,
|
||||
),
|
||||
IntegerType(
|
||||
"write_timeout",
|
||||
gettext("Write Timeout"),
|
||||
@@ -207,8 +228,6 @@ class SerialTransport(Transport):
|
||||
|
||||
@classmethod
|
||||
def get_available_serial_ports(cls, focus):
|
||||
from serial.tools.list_ports import comports
|
||||
|
||||
matcher = lambda x: True
|
||||
if focus == "usbid":
|
||||
matcher = lambda x: x.vid and x.pid
|
||||
@@ -258,6 +277,10 @@ class SerialTransport(Transport):
|
||||
|
||||
self._closing = False
|
||||
|
||||
self._autodetect_candidates = None
|
||||
self._autodetect_kwargs = None
|
||||
self._autodetect_timer = None
|
||||
|
||||
def create_connection(self, **kwargs):
|
||||
factory = self.serial_factory
|
||||
if self.serial_factory is None:
|
||||
@@ -309,6 +332,8 @@ class SerialTransport(Transport):
|
||||
return False
|
||||
|
||||
def do_read(self, size=None, timeout=None):
|
||||
if timeout is not None:
|
||||
self._serial.timeout = timeout
|
||||
return self._serial.read(size=size)
|
||||
|
||||
def do_write(self, data):
|
||||
@@ -366,6 +391,67 @@ class SerialTransport(Transport):
|
||||
def in_waiting(self):
|
||||
return getattr(self._serial, "in_waiting", 0)
|
||||
|
||||
def do_init_autodetection(self, *args, **kwargs):
|
||||
self._autodetect_kwargs = {
|
||||
k: v
|
||||
for k, v in kwargs.items()
|
||||
if k not in ("connect_via", "port", "baudrate")
|
||||
}
|
||||
port = self._find_serial_port(focus=kwargs.get("connect_via"))
|
||||
baudrate = kwargs.get("baudrate")
|
||||
|
||||
if port:
|
||||
port_candidates = [
|
||||
port.device,
|
||||
]
|
||||
else:
|
||||
port_candidates = [port.device for port in comports()]
|
||||
|
||||
if baudrate:
|
||||
baudrate_candidates = [
|
||||
baudrate,
|
||||
]
|
||||
else:
|
||||
baudrate_candidates = [*self.autodetection_baudrates]
|
||||
|
||||
self._autodetect_candidates = [
|
||||
(p, b) for b in baudrate_candidates for p in port_candidates
|
||||
]
|
||||
|
||||
self.process_transport_log(
|
||||
"Performing autodetection with {} port/baudrate candidates: {}".format(
|
||||
len(self._autodetect_candidates),
|
||||
", ".join(map(lambda x: "{}@{}".format(*x), self._autodetect_candidates)),
|
||||
)
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def do_autodetection_step(self):
|
||||
while (
|
||||
len(self._autodetect_candidates) > 0
|
||||
and self.state == TransportState.CONNECTING
|
||||
):
|
||||
(p, b) = self._autodetect_candidates.pop(0)
|
||||
|
||||
try:
|
||||
self.process_transport_log(f"Trying port {p}@{b}")
|
||||
if self._serial is None or self._serial.port != p:
|
||||
if not self.create_connection(
|
||||
connect_via="port",
|
||||
port=p,
|
||||
baudrate=b,
|
||||
**self._autodetect_kwargs,
|
||||
):
|
||||
self.process_transport_log(f"Could not open {p}@{b}, skipping")
|
||||
continue
|
||||
else:
|
||||
self._serial.baudrate = b
|
||||
|
||||
return
|
||||
except Exception:
|
||||
self._logger.exception(f"Unexpected error while setting baudrate {b}")
|
||||
|
||||
def _default_serial_factory(self, **kwargs):
|
||||
serial_obj = self._create_serial(**kwargs)
|
||||
self._apply_parity_workaround(serial_obj, **kwargs)
|
||||
@@ -376,75 +462,62 @@ class SerialTransport(Transport):
|
||||
return serial_obj
|
||||
|
||||
@classmethod
|
||||
def _create_serial(cls, **kwargs):
|
||||
focus = kwargs["connect_via"]
|
||||
|
||||
def match_port(matcher):
|
||||
from serial.tools.list_ports import comports
|
||||
|
||||
for port in comports():
|
||||
if matcher(port):
|
||||
return port
|
||||
else:
|
||||
raise ValueError()
|
||||
def _find_serial_port(cls, focus="port", **kwargs):
|
||||
value = kwargs.get(focus)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
if focus == "port":
|
||||
port = kwargs.pop("port")
|
||||
baudrate = kwargs.pop("baudrate")
|
||||
return cls._create_serial_for_port_and_baudrate(port, baudrate, **kwargs)
|
||||
|
||||
matcher = lambda p: p.device == value
|
||||
elif focus == "usbid":
|
||||
usbid = kwargs.pop("usbid")
|
||||
baudrate = kwargs.pop("baudrate")
|
||||
vid, pid = usbid.split(":")
|
||||
try:
|
||||
port = match_port(
|
||||
lambda p: f"{p.vid:04x}" == vid and f"{p.pid:04x}" == pid
|
||||
)
|
||||
return cls._create_serial_for_port_and_baudrate(
|
||||
port.device, baudrate, **kwargs
|
||||
)
|
||||
except ValueError:
|
||||
raise ValueError(f"Can't find USB ID to connect to: {usbid}")
|
||||
|
||||
vid, pid = value.split(":")
|
||||
matcher = lambda p: f"{p.vid:04x}" == vid and f"{p.pid:04x}" == pid
|
||||
elif focus == "usbserial":
|
||||
usbserial = kwargs.pop("usbserial")
|
||||
baudrate = kwargs.pop("baudrate")
|
||||
try:
|
||||
port = match_port(lambda p: p.serial_number == usbserial)
|
||||
return cls._create_serial_for_port_and_baudrate(
|
||||
port.device, baudrate, **kwargs
|
||||
)
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
f"Can't find USB serial number to connect to: {usbserial}"
|
||||
)
|
||||
|
||||
matcher = lambda p: p.serial_number == value
|
||||
elif focus == "usbloc":
|
||||
usbloc = kwargs.pop("usbloc")
|
||||
baudrate = kwargs.pop("baudrate")
|
||||
try:
|
||||
port = match_port(lambda p: p.location == usbloc)
|
||||
return cls._create_serial_for_port_and_baudrate(
|
||||
port.device, baudrate, **kwargs
|
||||
)
|
||||
except ValueError:
|
||||
raise ValueError(f"Can't find USB port to connect to: {usbloc}")
|
||||
matcher = lambda p: p.location == value
|
||||
else:
|
||||
return None
|
||||
|
||||
try:
|
||||
return match_port(matcher)
|
||||
except PortNotFound:
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _create_serial(cls, **kwargs):
|
||||
focus = kwargs.pop("connect_via")
|
||||
|
||||
port_based = ("port", "usbid", "usbserial", "usbloc")
|
||||
if focus in port_based:
|
||||
port = cls._find_serial_port(focus=focus, **kwargs)
|
||||
for k in port_based:
|
||||
if k in kwargs:
|
||||
kwargs.pop(k)
|
||||
|
||||
baudrate = kwargs.pop("baudrate", 0)
|
||||
|
||||
if port is None or baudrate == 0:
|
||||
raise TransportRequiresAutodetection()
|
||||
|
||||
return cls._create_serial_for_port_and_baudrate(
|
||||
port.device, baudrate, **kwargs
|
||||
)
|
||||
|
||||
elif focus == "url":
|
||||
serial_obj = serial.serial_for_url(kwargs.get("url"), do_not_open=True)
|
||||
return serial_obj
|
||||
return serial.serial_for_url(kwargs.get("url"), do_not_open=True)
|
||||
|
||||
else:
|
||||
raise ValueError(f"Invalid connect_via: {focus}")
|
||||
raise ValueError(f"Invalid focus: {focus}")
|
||||
|
||||
@classmethod
|
||||
def _create_serial_for_port_and_baudrate(cls, port, baudrate, **kwargs):
|
||||
serial_obj = serial.Serial(
|
||||
baudrate=baudrate,
|
||||
exclusive=kwargs.get("exclusive"),
|
||||
parity=kwargs.get("parity"),
|
||||
write_timeout=kwargs.get("write_timeout", 10) * 1000,
|
||||
exclusive=kwargs.get("exclusive", True),
|
||||
parity=kwargs.get("parity", serial.PARITY_NONE),
|
||||
timeout=kwargs.get("read_timeout", 2),
|
||||
write_timeout=kwargs.get("write_timeout", 10),
|
||||
)
|
||||
serial_obj.port = port # set port only now to prevent auto open
|
||||
return serial_obj
|
||||
@@ -499,6 +572,18 @@ class SerialTransport(Transport):
|
||||
return "SerialTransport"
|
||||
|
||||
|
||||
class PortNotFound(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def match_port(matcher):
|
||||
for port in comports():
|
||||
if matcher(port):
|
||||
return port
|
||||
else:
|
||||
raise PortNotFound()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# list ports
|
||||
ports = SerialTransport.get_available_serial_ports()
|
||||
|
||||
@@ -34,7 +34,7 @@ def get_param_defaults(options):
|
||||
def get_param_dict(data, options):
|
||||
options_by_name = {option.name: option for option in options}
|
||||
|
||||
result = {}
|
||||
result = get_param_defaults(options)
|
||||
for key, value in data.items():
|
||||
if key not in options_by_name:
|
||||
continue
|
||||
|
||||
Reference in new issue
Block a user