🚧 WIP: Fixing/implementing things left and right

This commit is contained in:
Gina Häußge committed 2021-06-10 16:51:54 +02:00
1 parent c2cec4e11c
commit 786203b7ac
6 files changed
+184 -85

No files matched your search

-1
View File
@@ -7,6 +7,5 @@
* RepRapProtocol:
* Anything missing from settings migration to profile?
* Disconnect after incomplete connect/reset states
* Disconnect after autodetection failure
TBC
+43 -12
View File
@@ -374,12 +374,33 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener):
self._transport = transport
self._transport.register_listener(self)
if self._transport.state == TransportState.DISCONNECTED:
try:
self._transport.connect(*transport_args, **transport_kwargs)
except TransportRequiresAutodetection:
self._transport.start_autodetection(*transport_args, **transport_kwargs)
self.state = ProtocolState.CONNECTING
try:
if self._transport.state == TransportState.DISCONNECTED:
try:
self._transport.connect(*transport_args, **transport_kwargs)
except TransportRequiresAutodetection:
self.log_message(
"Attempting to auto detect correct transport configuration",
level=logging.INFO,
)
self._transport.start_autodetection(
*transport_args, **transport_kwargs
)
self.state = ProtocolState.CONNECTING
except TransportOutOfAutodetectionCandidates:
self.log_warning(
"Auto detection of transport configuration failed, no more candidates to test"
)
self._disconnect_transport(wait=False)
self.state = ProtocolState.DISCONNECTED
raise
except Exception as ex:
self.log_warning(f"There was an error while connecting: {str(ex)}")
self._disconnect_transport(wait=False)
self.state = ProtocolState.DISCONNECTED
raise
def disconnect(self, error=False, wait=True, timeout=10.0):
if self.state in (
@@ -402,6 +423,16 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener):
if wait:
self.join(timeout=timeout)
error = self._disconnect_transport(wait=wait) or error
if error:
self.state = ProtocolState.DISCONNECTED_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTED
def _disconnect_transport(self, wait=True):
error = False
self._transport.unregister_listener(self)
if self._transport.state == TransportState.CONNECTED:
try:
@@ -411,11 +442,9 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener):
f"Error while disconnecting from transport {self._transport}"
)
error = True
self._transport = None
if error:
self.state = ProtocolState.DISCONNECTED_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTED
return error
def process(self, job, position=0, user=None, tags=None, **kwargs):
if not job.can_process(self):
@@ -540,8 +569,10 @@ class Protocol(ListenerAware, TransportListener, ProtocolErrorStatsListener):
try:
self._transport.autodetection_step()
except TransportOutOfAutodetectionCandidates:
# TODO: handle out of candidates situation gracefully
raise
self.log_warning(
"Auto detection of transport configuration failed, no more candidates to test"
)
self.state = ProtocolState.DISCONNECTED
def process_protocol_log(self, message: str):
self._connection_logger.debug(message)
+86 -36
View File
@@ -52,6 +52,7 @@ from octoprint.comm.transport import (
TimeoutTransportException,
Transport,
TransportListener,
TransportState,
)
from octoprint.events import Events
from octoprint.settings.parameters import (
@@ -123,6 +124,8 @@ class InternalState:
self.resend_requested = None
self.resend_linenumber = None
self.resend_count = None
self.resend_consecutive_linenumber = None
self.resend_consecutive_count = None
self.long_running_command = False
@@ -399,6 +402,17 @@ class ReprapGcodeProtocol(
"in order to disable heaters and motors."
),
),
IntegerType(
"max_identical_resends",
gettext("Max number of identical requests"),
default=10,
warning=False,
help=gettext(
"After how many resend requests for the same line OctoPrint "
"should consider the firmware to be stuck in a resend loop "
"and abort and disconnect."
),
),
],
advanced=True,
),
@@ -793,6 +807,9 @@ class ReprapGcodeProtocol(
self.send_emergency_stop = kwargs.get("error_handling", {}).get(
"send_emergency_stop", True
)
self.max_identical_resends = kwargs.get("error_handling", {}).get(
"max_identical_resends", 10
)
self.sanity_check_tools = kwargs.get("sanity_checking", {}).get(
"sanity_check_tools", True
@@ -1759,15 +1776,24 @@ class ReprapGcodeProtocol(
##~~ Connection validation
def on_transport_validate_connection(self, transport):
if transport != self._transport:
return
if transport.state != TransportState.CONNECTING:
return
self._validation_retry = 0
self._attempt_validation()
def _handle_autodetection_timeout(self):
if not self.transport or self.transport.state != TransportState.CONNECTING:
return
if self._validation_retry < self.VALIDATION_RETRIES:
self._attempt_validation()
else:
# still no dice, try next combo
self._transport.autodetection_step()
self.transport.autodetection_step()
def _attempt_validation(self):
self._validation_retry += 1
@@ -1839,8 +1865,8 @@ class ReprapGcodeProtocol(
if data is None:
# EOF
# TODO handle EOF
pass
self._trigger_error("Transport signalled EOF, disconnecting!", "eof")
return
def convert_line(line):
if line is None:
@@ -1910,11 +1936,15 @@ class ReprapGcodeProtocol(
pass
def _on_comm_any(self, line, lower_line):
if self.state == ProtocolState.CONNECTING and (
not len(line)
or (
self.internal_state.ok_timeout
and time.monotonic() > self.internal_state.ok_timeout
if (
self.state == ProtocolState.CONNECTING
and self.transport.state == TransportState.CONNECTING
and (
not len(line)
or (
self.internal_state.ok_timeout
and time.monotonic() > self.internal_state.ok_timeout
)
)
):
self._handle_autodetection_timeout()
@@ -1973,35 +2003,34 @@ class ReprapGcodeProtocol(
# now increment the timeout counter
self.internal_state.timeout_consecutive += 1
self._logger.debug(
"Now at {} consecutive timeouts".format(
self.internal_state.timeout_consecutive
)
f"Now at {self.internal_state.timeout_consecutive} consecutive timeouts"
)
if 0 < consecutive_max < self.internal_state.timeout_consecutive:
# too many consecutive timeouts, we give up
self.log_message(
f"No response from printer after {consecutive_max + 1} consecutive communication timeouts. "
f"Have to consider it dead.",
self.log_warning(
f"No response from printer after {consecutive_max + 1} "
f"consecutive communication timeouts. "
f"Have to consider it dead. {general_message}.",
level=logging.INFO,
)
# TODO error handling
self.error = "Too many consecutive timeouts"
self.disconnect(error=True)
elif self.internal_state.resend_requested is not None:
message = "Communication timeout during an active resend, resending same line again to trigger response from printer."
message = (
"Communication timeout during an active resend, resending same "
"line again to trigger response from printer."
)
self._logger.info(message)
self.notify_listeners(
"on_protocol_log", self, message + " " + general_message
)
if self._send_same_from_resend():
self._commdebug_logger.debug(
"on_comm_timeout => clear_to_send.set: timeout during active resend (counter: {})".format(
self._clear_to_send.counter
)
f"on_comm_timeout => clear_to_send.set: timeout during active resend "
f"(counter: {self._clear_to_send.counter})"
)
self._clear_to_send.set()
@@ -2026,9 +2055,8 @@ class ReprapGcodeProtocol(
)
if self._send_command(GcodeCommand("M105", type="temperature")):
self._commdebug_logger.debug(
"on_comm_timeout => clear_to_send.set: timeout while printing (counter: {})".format(
self._clear_to_send.counter
)
f"on_comm_timeout => clear_to_send.set: timeout while printing "
f"(counter: {self._clear_to_send.counter})"
)
self._clear_to_send.set()
@@ -2040,9 +2068,8 @@ class ReprapGcodeProtocol(
"on_protocol_log_message", self, message + " " + general_message
)
self._commdebug_logger.debug(
"on_comm_timeout => clear_to_send.set: timeout while idle (counter: {})".format(
self._clear_to_send.counter
)
f"on_comm_timeout => clear_to_send.set: timeout while idle "
f"(counter: {self._clear_to_send.counter})"
)
self._clear_to_send.set()
@@ -2145,24 +2172,36 @@ class ReprapGcodeProtocol(
and self.internal_state.resend_count
< self._current_linenumber - linenumber - 1
):
self.log_message(
self._logger.info(
f"Ignoring resend request for line {linenumber}, originates from lines sent earlier"
)
self.internal_state.resend_count += 1
return
if linenumber not in self._last_lines:
self._logger.error(
"Printer requested to resend a line we don't have: {}".format(
linenumber
)
)
error = f"Printer requested to resend a line we don't have: {linenumber}"
self.log_warning(error)
if self._is_busy():
# TODO set error state & log
self.cancel_processing(error=True)
self._trigger_error(error, "resend")
else:
return
if self.internal_state.resend_consecutive_linenumber == linenumber:
self.internal_state.resend_consecutive_count += 1
if (
self.internal_state.resend_consecutive_count
>= self.max_identical_resends
):
error_text = (
f"Printer keep requesting line {linenumber} again and "
f"again, communication stuck"
)
self.log_warning(error_text)
self._trigger_error(error_text, "resend_loop")
else:
self.internal_state.resend_consecutive_linenumber = linenumber
self.internal_state.resend_consecutive_count = 0
self.internal_state.resend_requested = linenumber
self.internal_state.resend_linenumber = linenumber
self.internal_state.resend_count = 0
@@ -2330,8 +2369,16 @@ class ReprapGcodeProtocol(
self.resume_processing(local_handling=False)
elif action == "disconnect":
self.log_message("Disconnecting on request of the printer...", prefix="")
# TODO inform printer about forced disconnect
self.disconnect()
elif action == "sd_inserted":
self.log_message("Printer reported SD card as inserted")
self._on_message_sd_init_ok()
elif action == "sd_ejected":
self.log_message("Printer reported SD card as ejected")
self._on_message_sd_init_fail()
elif action == "sd_updated":
self.log_message("Printer reported a change on the SD card")
self.list_files()
else:
for hook in self._action_hooks:
try:
@@ -2522,6 +2569,7 @@ class ReprapGcodeProtocol(
def _on_message_sd_init_fail(self):
self.internal_state.sd_available = False
self.internal_state.sd_files = []
self.notify_listeners(
"on_protocol_file_storage_available",
self,
@@ -2698,7 +2746,9 @@ class ReprapGcodeProtocol(
try:
command = self._last_lines[linenumber]
except KeyError:
# TODO what to do?
# This should actually never happen, but if it does, all hope is lost
error_text = f"Should resend {linenumber}, but can't find it"
self._trigger_error(error_text, "resend")
return False
result = self._enqueue_for_sending(
+19 -20
View File
@@ -3,9 +3,10 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import copy
import logging
import time
from typing import Union
import serial
from octoprint.plugin import plugin_manager
from octoprint.settings import SubSettings
from octoprint.settings.parameters import get_param_dict, register_settings_overlay
@@ -183,6 +184,8 @@ class Transport(ListenerAware):
self.signal_connected()
def signal_connected(self):
if self.state != TransportState.CONNECTING:
return
self.state = TransportState.CONNECTED
self.notify_listeners("on_transport_connected", self)
@@ -216,8 +219,12 @@ class Transport(ListenerAware):
self.autodetection_step()
def autodetection_step(self):
self.do_autodetection_step()
self.notify_listeners("on_transport_validate_connection", self)
try:
self.do_autodetection_step()
self.notify_listeners("on_transport_validate_connection", self)
except TransportOutOfAutodetectionCandidates:
self.state = TransportState.DISCONNECTED
raise
def read(self, size=None, timeout=None):
data = self.do_read(size=size, timeout=timeout)
@@ -326,29 +333,23 @@ class SeparatorAwareTransportWrapper(TransportWrapper):
self._buffered = bytearray()
def read(self, size=None, timeout=None):
start = time.monotonic()
termlen = len(self.terminator)
data = self._buffered
timeout = serial.Timeout(timeout)
while True:
# make sure we always read everything that is waiting
data += bytearray(self.transport.read(self.transport.in_waiting))
while not timeout.expired():
self._buffered += self.transport.read(self.transport.in_waiting)
# check for terminator, if it's there we have found our line
termpos = data.find(self.terminator)
termpos = self._buffered.find(self.terminator)
if termpos >= 0:
# line: everything up to and incl. the terminator
line = data[: termpos + termlen]
# buffered: everything after the terminator
self._buffered = data[termpos + termlen :]
# line: everything up to and incl. the terminator, buffered: rest
line = self._buffered[: termpos + termlen]
del self._buffered[: termpos + termlen]
received = bytes(line)
self.notify_listeners("on_transport_log_received_data", self, received)
return received
# check if timeout expired
if timeout and time.monotonic() > start + timeout:
if timeout.expired():
break
# if we arrive here we so far couldn't read a full line, wait for more data
@@ -358,9 +359,7 @@ class SeparatorAwareTransportWrapper(TransportWrapper):
break
# add to data and loop
data += c
self._buffered = data
self._buffered += c
raise TimeoutTransportException()
@@ -10,6 +10,7 @@ from serial.tools.list_ports import comports
from octoprint.comm.transport import (
Transport,
TransportOutOfAutodetectionCandidates,
TransportRequiresAutodetection,
TransportState,
)
@@ -473,6 +474,9 @@ class SerialTransport(Transport):
self._logger.exception(message)
self.log_message(message, level=None)
if not self._autodetect_candidates:
raise TransportOutOfAutodetectionCandidates()
def _default_serial_factory(self, **kwargs):
serial_obj = self._create_serial(**kwargs)
self._apply_parity_workaround(serial_obj, **kwargs)
+32 -16
View File
@@ -25,9 +25,11 @@ from octoprint.comm.protocol import (
FileAwareProtocolListener,
MultiToolAwareProtocolListener,
PositionAwareProtocolListener,
ProtocolAlreadyConnectedError,
ProtocolListener,
ProtocolState,
)
from octoprint.comm.transport import TransportOutOfAutodetectionCandidates
from octoprint.events import Events, eventManager
from octoprint.filemanager import FileDestinations, NoSuchStorage, valid_file_type
from octoprint.plugin import ProgressPlugin, plugin_manager
@@ -563,17 +565,37 @@ class Printer(
##~~ Register everything and connect
self._protocol.register_listener(self)
self._protocol.connect(self._transport, transport_kwargs=transport_connect_kwargs)
##~~ Remember last connection
self._last_connection = {
"connection": connection_id,
"protocol": selected_protocol,
"protocol_args": protocol_kwargs,
"transport": selected_transport,
"transport_args": transport_connect_kwargs,
"printer_profile": profile_id,
}
try:
self._protocol.connect(
self._transport, transport_kwargs=transport_connect_kwargs
)
# Remember last connection
self._last_connection = {
"connection": connection_id,
"protocol": selected_protocol,
"protocol_args": protocol_kwargs,
"transport": selected_transport,
"transport_args": transport_connect_kwargs,
"printer_profile": profile_id,
}
except ProtocolAlreadyConnectedError:
self._logger.error(
f"Already connected via protocol {self._protocol} and transport {self._transport}"
)
except TransportOutOfAutodetectionCandidates:
self._transport = None
self._protocol.unregister_listener(self)
self._protocol = None
except Exception:
self._transport = None
self._protocol.unregister_listener(self)
self._protocol = None
raise
def disconnect(self, *args, **kwargs):
"""
@@ -600,12 +622,6 @@ class Printer(
return None
return self._protocol.transport
getTransport = util.deprecated(
"getTransport has been renamed to get_transport",
since="1.2.0-dev-590",
includedoc="Replaced by :func:`get_transport`",
)
def job_on_hold(self, blocking=True, *args, **kwargs):
if self._protocol is None:
raise RuntimeError("No connection to the printer")