More migrations from stable comm layer to new layer

Also fixed:
  * comment stripping
  * resends (? maybe ?)
  * transport error detection
This commit is contained in:
Gina Häußge committed 2017-04-21 23:05:58 +02:00
1 parent c28fb4164b
commit babc581c5d
7 files changed
+603 -233

No files matched your search

+37 -23
View File
@@ -65,7 +65,7 @@ class Protocol(ListenerAware, TransportListener):
self._transport.connect(*transport_args, **transport_kwargs)
self.state = ProtocolState.CONNECTING
def disconnect(self):
def disconnect(self, error=False):
if self.state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR, ProtocolState.DISCONNECTING):
raise ProtocolNotConnectedError("Already disconnecting or disconnected")
@@ -77,7 +77,11 @@ class Protocol(ListenerAware, TransportListener):
self._transport.unregister_listener(self)
if self._transport.state == TransportState.CONNECTED:
self._transport.disconnect()
self.state = ProtocolState.DISCONNECTED
if error:
self.state = ProtocolState.DISCONNECTED_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTED
def process(self, job, position=0):
if not job.can_process(self):
@@ -101,27 +105,6 @@ class Protocol(ListenerAware, TransportListener):
self._job.cancel(error=error)
self.state = ProtocolState.CONNECTED
def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False):
pass
def home(self, x=False, y=False, z=False):
pass
def change_tool(self, tool):
pass
def set_feedrate_multiplier(self, multiplier):
pass
def set_extrusion_multiplier(self, multiplier):
pass
def set_extruder_temperature(self, temperature, tool=None, wait=False):
pass
def set_bed_temperature(self, temperature, wait=False):
pass
def can_send(self):
return True
@@ -147,6 +130,9 @@ class Protocol(ListenerAware, TransportListener):
self._job.unregister_listener(self)
self.state = ProtocolState.CONNECTED
def on_transport_disconnected(self, transport, error=None):
self.disconnect(error=error is not None)
def on_transport_log_received_data(self, transport, data):
message = "<<< {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
@@ -182,6 +168,34 @@ class ProtocolAlreadyConnectedError(Exception):
class ProtocolNotConnectedError(Exception):
pass
class ThreeAxisProtocolMixin(object):
def move(self, x=None, y=None, z=None, feedrate=None, relative=False):
pass
def home(self, x=False, y=False, z=False):
pass
def change_tool(self, tool):
pass
class ThreeDPrinterProtocolMixin(ThreeAxisProtocolMixin):
def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False):
pass
def set_feedrate_multiplier(self, multiplier):
pass
def set_extrusion_multiplier(self, multiplier):
pass
def set_extruder_temperature(self, temperature, tool=None, wait=False):
pass
def set_bed_temperature(self, temperature, wait=False):
pass
class FanControlProtocolMixin(object):
def set_fan_speed(self, speed):
+19 -12
View File
@@ -17,6 +17,7 @@ regex_float = re.compile(regex_float_pattern)
regexes_parameters = dict(
floatP=re.compile("(^|[^A-Za-z])[Pp](?P<value>%s)" % regex_float_pattern),
floatR=re.compile("(^|[^A-Za-z])[Rr](?P<value>%s)" % regex_float_pattern),
floatS=re.compile("(^|[^A-Za-z])[Ss](?P<value>%s)" % regex_float_pattern),
floatZ=re.compile("(^|[^A-Za-z])[Zz](?P<value>%s)" % regex_float_pattern),
intN=re.compile("(^|[^A-Za-z])[Nn](?P<value>%s)" % regex_int_pattern),
@@ -147,30 +148,36 @@ class GcodeCommand(object):
attributeStr = " ".join(attr)
return "%s%s%s" % (self.command.upper(), " " + attributeStr if attributeStr else "", " " + self.param if self.param else "")
class TypedQueue(queue.Queue):
def __init__(self, maxsize=0):
queue.Queue.__init__(self, maxsize=maxsize)
self._lookup = []
self._lookup = set()
def put(self, item, item_type=None, *args, **kwargs):
queue.Queue.put(self, (item, item_type), *args, **kwargs)
def get(self, *args, **kwargs):
item, _ = queue.Queue.get(self, *args, **kwargs)
return item
def _put(self, item):
if isinstance(item, tuple) and len(item) == 3:
cmd, line, cmd_type = item
if cmd_type is not None:
if cmd_type in self._lookup:
raise TypeAlreadyInQueue(cmd_type, "Type {cmd_type} is already in queue".format(**locals()))
else:
self._lookup.append(cmd_type)
_, item_type = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
queue.Queue._put(self, item)
def _get(self):
item = queue.Queue._get(self)
_, item_type = item
if isinstance(item, tuple) and len(item) == 3:
cmd, line, cmd_type = item
if cmd_type is not None and cmd_type in self._lookup:
self._lookup.remove(cmd_type)
if item_type is not None:
self._lookup.discard(item_type)
return item
+264 -77
View File
@@ -5,7 +5,7 @@ __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.comm.protocol import Protocol, FileStreamingProtocolMixin, \
from octoprint.comm.protocol import Protocol, ThreeDPrinterProtocolMixin, FileStreamingProtocolMixin, \
MotorControlProtocolMixin, FanControlProtocolMixin, ProtocolState
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, \
PushingTransportWrapper, PushingTransportWrapperListener
@@ -28,7 +28,7 @@ import threading
import time
class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProtocolMixin,
FanControlProtocolMixin, FileStreamingProtocolMixin,
PushingTransportWrapperListener):
@@ -67,10 +67,12 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
# temperature and heating related
temperatures=dict(),
heating_start=None,
heating_lost=0,
heating=False,
# current stuff
current_tool=0,
former_tool=0,
current_z=None,
# sd status
@@ -79,6 +81,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
sd_files_temp=None,
# resend status
resend_active=False,
resend_delta=None,
resend_linenumber=None,
resend_count=None,
@@ -93,6 +96,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
# timeout
timeout = None,
timeout_consecutive=0,
)
self._protected_state = protectedkeydict(self._internal_state)
@@ -120,6 +124,10 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
self._send_queue_active = False
self._sending_thread = None
@property
def _active(self):
return self._transport is not None and self._transport.active and self._send_queue_active
def connect(self, transport, transport_args=None, transport_kwargs=None):
if not isinstance(transport, Transport):
raise ValueError("transport must be a Transport subclass but is a {} instead".format(type(transport)))
@@ -138,7 +146,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
transport_kwargs=transport_kwargs)
def disconnect(self):
def disconnect(self, error=False):
# TODO either clear send queue, or wait until everything has been sent...
self._send_queue_active = False
self._sending_thread = None
@@ -231,14 +239,15 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
def can_send(self):
return not self._internal_state["long_running_command"] and not self._internal_state["heating"]
def send_commands(self, command_type=None, *commands):
def send_commands(self, *commands, **kwargs):
command_type = kwargs.get("command_type")
if self.state == ProtocolState.PRINTING and not self._job.runs_parallel:
if len(commands) > 1:
command_type = None
for command in commands:
self._command_queue.put((command, command_type))
elif self._is_operational():
self._send_commands(commands, command_type=command_type)
self._send_commands(*commands, command_type=command_type)
##~~ State handling
@@ -301,16 +310,28 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
# TODO handle EOF
pass
line = to_unicode(data, encoding="ascii", errors="replace").strip()
lower_line = line.lower()
def convert_line(line):
if line is None:
return None, None
stripped_line = line.strip().strip("\0")
return stripped_line, stripped_line.lower()
orig_line = to_unicode(data, encoding="ascii", errors="replace").strip()
line, lower_line = convert_line(orig_line)
if len(line):
# TODO handle dwelling
pass
any_processed = False
for message in self._registered_messages:
for message in self._registered_messages: # flavor.comm_* + flavor.message_*
handler_method = getattr(self, "_on_{}".format(message), None)
if not handler_method:
# no handler, nothing to do
continue
# match line against flavor specific matcher
matches = getattr(self.flavor, message)(line, lower_line, self._protected_state)
continue_further = False
if isinstance(matches, tuple) and len(matches) == 2:
@@ -325,6 +346,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
parse_method = getattr(self.flavor, "parse_{}".format(message), None)
if parse_method:
# flavor specific parser? run it
parse_result = parse_method(line, lower_line, self._protected_state)
if parse_result is None:
if continue_further:
@@ -332,9 +354,24 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
else:
break
# add parser result to kwargs
message_args.update(parse_result)
if not handler_method(**message_args):
# before handler: flavor.before_comm_* or flavor.before_message_*
before_handler = getattr(self.flavor, "before_{}".format(message), None)
if before_handler:
before_handler(**message_args)
# run handler
result = handler_method(**message_args)
# after handler: flavor.after_comm_* or flavor.after_message_*
after_handler = getattr(self.flavor, "after_{}".format(message), None)
if after_handler:
after_handler(result, **message_args)
if not result:
# nothing returned? handled -> only continue further if instructed
if continue_further:
continue
else:
@@ -351,15 +388,63 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
self._clear_to_send.set()
def _on_comm_timeout(self):
if self.state == ProtocolState.CONNECTING:
self.disconnect()
if self.state not in (ProtocolState.PRINTING,
ProtocolState.PAUSED,
ProtocolState.CONNECTED):
return
general_message = "Configure long running commands or increase communication timeout if that happens regularly on specific commands or long moves."
# figure out which consecutive timeout maximum we have to use
if self._internal_state["long_running_command"]:
consecutive_max = 5 # TODO take from config
elif self.state in (ProtocolState.PRINTING,):
consecutive_max = 10 # TODO take from config
else:
if not self._internal_state["long_running_command"]:
self.notify_listeners("on_protocol_log_message", self, "Communication timeout, forcing a line")
self._send_command(self.flavor.command_get_temp())
consecutive_max = 15 # TODO take from config
# now increment the timeout counter
self._internal_state["timeout_consecutive"] += 1
self._logger.debug("Now at {} consecutive timeouts".format(self._internal_state["timeout_consecutive"]))
if 0 < consecutive_max < self._internal_state["timeout_consecutive"]:
# too many consecutive timeouts, we give up
# TODO implement
pass
elif self._internal_state["resend_active"]:
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._clear_to_send.set()
else:
self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active")
elif self._internal_state["heating"]:
# blocking heatup active, consider that finished
message = "Timeout while in an active heatup, considering heatup to be over"
self._logger.info(message)
self._finish_heatup()
elif self._internal_state["long_running_command"]:
# long running command active, ignore timeout
self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active")
elif self.state in (ProtocolState.PRINTING, ProtocolState.PAUSED):
# printing, try to tickle the printer
message = "Communication timeout while printing, trying to trigger response from printer."
self._logger.info(message)
self.notify_listeners("on_protocol_log_message", self, message + " " + general_message)
if self._send_command("M105", command_type="temperature"):
self._clear_to_send.set()
elif self._clear_to_send.blocked():
# timeout while idle and no oks left, let's try to tickle the printer
message = "Communication timeout while idle, trying to trigger response from printer."
self._logger.info(message)
self.notify_listeners("on_protocol_log_message", self, message + " " + general_message)
self._clear_to_send.set()
return self.state != ProtocolState.PRINTING
def _on_comm_ok(self):
if self._internal_state["ignore_ok"] > 0:
@@ -375,17 +460,25 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
self._clear_to_send.set()
if self._internal_state["heating"]:
self._internal_state["heating"] = False
if self._internal_state["long_running_command"]:
self._internal_state["long_running_command"] = False
# reset long running commands, persisted current tools and heatup counters on ok
self._internal_state["long_running_command"] = False
if self._internal_state["former_tool"]:
self._internal_state["current_tool"] = self._internal_state["former_tool"]
self._internal_state["former_tool"] = None
self._finish_heatup()
if not self.state in (ProtocolState.PRINTING, ProtocolState.CONNECTED, ProtocolState.PAUSED):
return
# process ongoing resend requests and queues if we are operational
if self._internal_state["resend_delta"] is not None:
self._send_next_from_resend()
else:
self._internal_state["resend_active"] = False
self._continue_sending()
def _on_comm_ignore_ok(self):
@@ -398,7 +491,19 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
def _on_comm_resend(self, linenumber):
if linenumber is None:
return
return False
if self._internal_state["resend_delta"] is None and linenumber == self._current_linenumber:
# We don't expect to have an active resend request and the printer is requesting a resend of
# a line we haven't yet sent.
#
# This means the printer got a line from us with N = self._current_linenumber - 1 but had already
# acknowledged that. This can happen if the last line was resent due to a timeout during an active
# (prior) resend request.
#
# We will ignore this resend request and just continue normally.
self._logger.debug("Ignoring resend request for line {} == current line, we haven't sent that yet so the printer got N-1 twice from us, probably due to a timeout".format(linenumber))
return False
last_communication_error = self._last_communication_error
self._last_communication_error = None
@@ -411,12 +516,25 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
and self._internal_state["resend_delta"] is not None and self._internal_state["resend_count"] < self._internal_state["resend_delta"]:
self._logger.debug("Ignoring resend request for line {}, that still originates from lines we sent before we got the first resend request".format(linenumber))
self._internal_state["resend_count"] += 1
return
return True
self._internal_state["resend_active"] = True
self._internal_state["resend_delta"] = resend_delta
self._internal_state["resend_linenumber"] = linenumber
self._internal_state["resend_count"] = 0
if resend_delta > len(self._last_lines) or len(self._last_lines) == 0 or resend_delta < 0:
self._logger.error("Printer requested to resend a line further back than we have")
if self._is_busy():
# TODO set error state & log
self.cancel_processing(error=True)
else:
self._internal_state["resend_delta"] = None
# TODO log resend (with rate limiting)
return True
def _on_comm_start(self):
if self.state == ProtocolState.CONNECTING:
self.state = ProtocolState.CONNECTED
@@ -493,85 +611,129 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
def _on_message_sd_printing_byte(self, current, total):
self.notify_listeners("on_protocol_sd_status", self, current, total)
def _finish_heatup(self):
if self._internal_state["heating_start"]:
self._internal_state["heating_lost"] = self._internal_state["heating_lost"] + (time.time() - self._internal_state["heating_start"])
self._internal_state["heating_start"] = None
self._internal_state["heating"] = False
##~~ Sending
def _continue_sending(self):
if self._internal_state["resend_delta"] is not None:
self._send_next_from_resend()
else:
if self.state == ProtocolState.PRINTING and self._job is not None:
if not self._send_from_queue():
self._send_next_from_job()
elif self.state == ProtocolState.CONNECTED or self.state == ProtocolState.PAUSED:
self._send_from_queue()
while self._active:
if self.state in (ProtocolState.CONNECTED, ProtocolState.PAUSED):
return self._send_from_queue()
def _send_next_from_resend(self):
elif self.state in (ProtocolState.PRINTING,):
# we are printing, we really want to send either something from the command
# queue or the next line from our file, so we only return here if we actually DO
# send something
if self._send_from_queue():
# we found something in the queue to send
return True
elif self._send_next_from_job():
# we sent the next line from the file
return True
self._logger.debug("No command sent on ok while printing, doing another iteration")
def _send_same_from_resend(self):
return self._send_next_from_resend(again=True)
def _send_next_from_resend(self, again=False):
self._last_communication_error = None
# Make sure we are only handling one sending job at a time
with self._send_queue_mutex:
def reset_resend_data():
self._internal_state["resend_delta"] = None
self._internal_state["resend_linenumber"] = None
self._internal_state["resend_count"] = 0
if again:
# If we are about to send the last line from the active resend request
# again, we first need to increment resend delta. It might already
# be set to None if the last resend line was already sent, so
# if that's the case we set it to 0. It will then be incremented,
# the last line will be sent again, and then the delta will be
# decremented and set to None again, completing the cycle.
if self._internal_state["resend_delta"] is None:
self._internal_state["resend_delta"] = 0
self._internal_state["resend_delta"] += 1
resend_delta = self._internal_state["resend_delta"]
if resend_delta > len(self._last_lines) or len(self._last_lines) == 0 or resend_delta < 0:
self._logger.error("Printer requested to resend a line further back than we have")
reset_resend_data()
if self._is_busy():
self.cancel_processing(error=True)
return
command = self._last_lines[-resend_delta]
linenumber = self._current_linenumber - resend_delta
self._enqueue_for_sending(command, linenumber=linenumber)
result = self._enqueue_for_sending(command, linenumber=linenumber)
self._internal_state["resend_delta"] -= 1
if self._internal_state["resend_delta"] <= 0:
reset_resend_data()
self._internal_state["resend_active"] = False
self._internal_state["resend_delta"] = None
self._internal_state["resend_linenumber"] = None
self._internal_state["resend_count"] = 0
return result
def _send_next_from_job(self):
with self._send_queue_mutex:
line = self._job.get_next()
if line is not None:
self._send_command(line)
def _send_from_queue(self):
with self._send_queue_mutex:
# We loop here to make sure that if we do NOT send the first command
# from the queue, we'll send the second (if there is one). We do not
# want to get stuck here by throwing away commands.
while True:
if self._command_queue.empty() or self._internal_state["only_from_job"]:
# no command queue or irrelevant command queue => return
while self._active:
# we loop until we've actually enqueued a line for sending
if self.state != ProtocolState.PRINTING:
# we are no longer printing, return False
return False
entry = self._command_queue.get()
line = self._job.get_next()
if line is None:
# end of job, return False
return False
if self._send_command(line):
return True
self._logger.debug("Command \"{}\" from job not enqueued, doing another iteration".format(line))
def _send_from_queue(self):
# We loop here to make sure that if we do NOT send the first command
# from the queue, we'll send the second (if there is one). We do not
# want to get stuck here by throwing away commands.
while True:
if self._internal_state["only_from_job"]:
# irrelevant command queue => return
return False
try:
entry = self._command_queue.get(block=False)
except queue.Empty:
# nothing in command queue
return False
try:
if isinstance(entry, tuple):
if not len(entry) == 2:
if not len(entry) == 3:
# something with that entry is broken, ignore it and fetch
# the next one
continue
cmd, cmd_type = entry
cmd, cmd_type, callback = entry
else:
cmd = entry
cmd_type = None
callback = None
if self._send_command(cmd, command_type=cmd_type):
if self._send_command(cmd, command_type=cmd_type, on_sent=callback):
# we actually did add this cmd to the send queue, so let's
# return, we are done here
return True
finally:
self._command_queue.task_done()
def _send_commands(self, *commands, **kwargs):
# TODO return True or False depending on whether something/all? was sent
command_type = kwargs.get("command_type", None)
for command in commands:
if len(commands) > 1:
command_type = None
self._send_command(command, command_type=command_type)
def _send_command(self, command, command_type=None):
def _send_command(self, command, command_type=None, on_sent=None):
if isinstance(command, GcodeCommand):
gcode = command
command = str(gcode)
@@ -591,30 +753,32 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
# # if this is a gcode bound to an event, trigger that now
# self._eventbus.fire(gcode_to_event[gcode.command])
self._enqueue_for_sending(command, command_type=command_type)
if self._enqueue_for_sending(command, command_type=command_type, on_sent=on_sent):
if self._internal_state["trigger_events"]:
self._process_command_phase("queued", command, command_type, gcode=gcode)
return True
else:
return False
if self._internal_state["trigger_events"]:
self._process_command_phase("queued", command, command_type, gcode=gcode)
return True
def _enqueue_for_sending(self, command, command_type=None, linenumber=None):
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None):
"""
Enqueues a command and optional command_type and linenumber in the send queue.
Arguments:
command (unicode): The command to send
linenumber (int): An optional line number to use for sending the
command.
command_type (unicode): An optional command type. There can only be
one command of a specified command type in the queue at any
given time.
linenumber (int): An optional line number to use for sending the
command.
"""
try:
self._send_queue.put((command, linenumber, command_type))
self._send_queue.put((command, linenumber, command_type, on_sent), item_type=command_type)
return True
except TypeAlreadyInQueue as e:
self._logger.debug("Type already in queue: {}".format(e.type))
return False
def _send_loop(self):
"""
@@ -635,7 +799,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
break
# fetch command and optional linenumber from queue
command, linenumber, command_type = entry
command, linenumber, command_type, on_sent = entry
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
@@ -683,6 +847,9 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
self._do_send_without_checksum(command_to_send)
# trigger "sent" phase and use up one "ok"
if on_sent is not None and callable(on_sent):
# we have a sent callback for this specific command, let's execute it now
on_sent()
self._process_command_phase("sent", command, command_type, gcode=gcode)
# we only need to use up a clear if the command we just sent was either a gcode command or if we also
@@ -785,7 +952,9 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
def _do_send_with_checksum(self, cmd, lineNumber):
command_to_send = b"N%d %s" % (lineNumber, cmd)
checksum = reduce(lambda x,y:x^y, map(ord, command_to_send))
checksum = 0
for c in command_to_send:
checksum ^= ord(c)
command_to_send = b"%s*%d" % (command_to_send, checksum)
self._do_send_without_checksum(command_to_send)
@@ -834,15 +1003,23 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
pass
_gcode_M190_queuing = _gcode_M140_queuing
def _gcode_M104_sent(self, cmd, cmd_type=None):
def _gcode_M104_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
tool_num = self._internal_state["current_tool"]
tool_match = regexes_parameters["intT"].search(cmd)
if tool_match:
tool_num = int(tool_match.group("value"))
tool = "tool{}".format(tool_num)
if wait:
self._internal_state["former_tool"] = self._internal_state["current_tool"]
self._internal_state["current_tool"] = tool_num
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
if match:
tool = "tool{}".format(tool_num)
try:
target = float(match.group("value"))
self._set_temperature(tool, None, target)
@@ -850,8 +1027,11 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
except ValueError:
pass
def _gcode_M140_sent(self, cmd, cmd_type=None):
def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
match = regexes_parameters["floatS"].search(cmd)
if not match and support_r:
match = regexes_parameters["floatR"].search(cmd)
if match:
try:
target = float(match.group("value"))
@@ -862,13 +1042,20 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
def _gcode_M109_sent(self, cmd, cmd_type=None):
self._internal_state["heatup_start"] = time.time()
self._internal_state["long_running_command"] = True
self._internal_state["heating"] = True
self._gcode_M104_sent(cmd, cmd_type)
self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M190_sent(self, cmd, cmd_type=None):
self._internal_state["heatup_start"] = time.time()
self._internal_state["long_running_command"] = True
self._internal_state["heating"] = True
self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True)
def _gcode_M116_sent(self, cmd, cmd_type=None):
self._internal_state["heatup_start"] = time.time()
self._internal_state["long_running_command"] = True
self._internal_state["heating"] = True
self._gcode_M140_sent(cmd, cmd_type)
def _gcode_M110_sending(self, cmd, cmd_type=None):
new_line_number = None
@@ -12,8 +12,10 @@ import logging
import time
from octoprint.comm.protocol.gcode.util import GcodeCommand, regex_positive_float_pattern
from octoprint.comm.protocol.gcode.util import GcodeCommand, regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
# TODO needed? move?
from octoprint.util import chunks
class ReprapGcodeFlavor(object):
@@ -31,6 +33,9 @@ class ReprapGcodeFlavor(object):
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"]
asynchronous_commands = ["G0", "G1", "G2", "G3"]
regex_resend_linenumber = re.compile("(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern))
"""Regex matching temperature entries in line.
@@ -42,6 +47,18 @@ class ReprapGcodeFlavor(object):
* ``target``: target temperature, if provided (float)
"""
regex_position = re.compile("(?P<axis>X|Y|Z|E):(?P<pos>{float})\s*".format(float=regex_float_pattern))
"""Regex for matching position entries in line.
Groups will be as follows:
* ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str)
* ``pos``: axis position (float)
"""
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):")
"""Regex to use for splitting M115 responses."""
regex_sd_file_opened = re.compile("file opened:\s*(?P<name>.*?)(\s+size:\s*(?P<size>[0-9]+)|$)")
regex_sd_printing_byte = re.compile("sd printing byte (?P<current>[0-9]*)/(?P<total>[0-9]*)")
@@ -61,7 +78,9 @@ class ReprapGcodeFlavor(object):
@classmethod
def comm_ok(cls, line, lower_line, state):
return lower_line.startswith("ok"), cls.message_temperature(line, lower_line, state)
return lower_line.startswith("ok"), cls.message_temperature(line, lower_line, state) \
or cls.message_position(line, lower_line, state) \
or cls.message_firmware_info(line, lower_line, state)
@classmethod
def comm_start(cls, line, lower_line, state):
@@ -97,7 +116,15 @@ class ReprapGcodeFlavor(object):
@classmethod
def message_temperature(cls, line, lower_line, state):
return " T:" in line or line.startswith("T:") or " T0:" in line or line.startswith("T0:")
return "T:" in line or "T0:" in line or "B:" in line
@classmethod
def message_position(cls, line, lower_line, state):
return "C:" in line or "X:" in line
@classmethod
def message_firmware_info(cls, line, lower_line, state):
return "NAME:" in line
@classmethod
def message_sd_init_ok(cls, line, lower_line, state):
@@ -168,11 +195,9 @@ class ReprapGcodeFlavor(object):
@classmethod
def parse_comm_resend(cls, line, lower_line, state):
line_to_resend = None
try:
line_to_resend = int(line.replace("N:", " ").replace("N", " ").replace(":", " ").split()[-1])
except:
if "rs" in line:
line_to_resend = int(line.split()[1])
match = cls.regex_resend_linenumber.search(line)
if match is not None:
line_to_resend = int(match.group("n"))
return dict(linenumber=line_to_resend)
@classmethod
@@ -216,95 +241,33 @@ class ReprapGcodeFlavor(object):
heatup_detected=heatup_detected)
@classmethod
def _canonicalize_temperatures(cls, parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
def parse_message_position(cls, line, lower_line, state):
position = dict(x=None, y=None, z=None, e=None)
for match in re.finditer(cls.regex_position, line):
position[match.group("axis").lower()] = float(match.group("pos"))
return position
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
@classmethod
def parse_message_firmware_info(cls, line, lower_line, state):
data = cls._parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
``T`` from the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = filter(lambda x: x.startswith("T"), parsed.keys())
if not "T" in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, so T contains the current
# extruder's temperature, e.g. for current_tool == 1:
#
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
#
# Same goes if Tc is already present, it will be overwritten:
#
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result[current_tool_key] = result["T"]
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
if firmware_name is None:
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
# report its firmware name properly in response to M115. Wonderful - why stick to established
# protocol when you can do your own thing, right?
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
#
# In both cases it is however safe to just move our T over
# to T<current> in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
name = data.get("NAME")
ver = data.get("VER")
if "malyan" in name.lower() and ver:
firmware_name = name.strip() + " " + ver.strip()
result[current_tool_key] = result["T"]
del result["T"]
return result
return dict(firmware_name=firmware_name,
data=data)
@classmethod
def parse_message_sd_file_opened(cls, line, lower_line, state):
@@ -457,3 +420,114 @@ class ReprapGcodeFlavor(object):
@classmethod
def command_sd_delete(cls, name):
return GcodeCommand("M30", param=name)
##~~ Helpers
@classmethod
def _canonicalize_temperatures(cls, parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
``T`` from the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = filter(lambda x: x.startswith("T"), parsed.keys())
if not "T" in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, so T contains the current
# extruder's temperature, e.g. for current_tool == 1:
#
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
#
# Same goes if Tc is already present, it will be overwritten:
#
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result[current_tool_key] = result["T"]
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
#
# In both cases it is however safe to just move our T over
# to T<current> in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
result[current_tool_key] = result["T"]
del result["T"]
return result
@classmethod
def _parse_firmware_line(cls, line):
"""
Parses the provided firmware info line.
The result will be a dictionary mapping from the contained keys to the contained
values.
Arguments:
line (str): the line to parse
Returns:
dict: a dictionary with the parsed data
"""
result = dict()
split_line = cls.regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
for key, value in chunks(split_line, 2):
result[key] = value
return result
+56 -18
View File
@@ -27,7 +27,7 @@ def register_transports():
register_transport(TcpTransport)
# more transports provided by plugins
hooks = plugin_manager().get_hooks("octoprint.comm.transport.register")
hooks = plugin_manager().get_hooks(b"octoprint.comm.transport.register")
for name, hook in hooks.items():
try:
transports = hook()
@@ -83,12 +83,20 @@ class Transport(ListenerAware):
param_dict = get_param_dict(params, options)
self.create_connection(**param_dict)
self.state = TransportState.CONNECTED
self.notify_listeners("on_transport_connected", self)
def disconnect(self):
def disconnect(self, error=None):
if self.state == TransportState.DISCONNECTED:
raise TransportNotConnectedError("Already disconnected")
self.drop_connection()
self.state = TransportState.DISCONNECTED
if error:
self.state = TransportState.DISCONNECTED_WITH_ERROR
self.notify_listeners("on_transport_log_message", self, error)
else:
self.state = TransportState.DISCONNECTED
self.notify_listeners("on_transport_disconnected", self, error=error)
def create_connection(self, *args, **kwargs):
pass
@@ -118,6 +126,7 @@ class Transport(ListenerAware):
class TransportState(object):
CONNECTED = "connected"
DISCONNECTED = "disconnected"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
class TransportNotConnectedError(Exception):
@@ -128,12 +137,41 @@ class TransportAlreadyConnectedError(Exception):
pass
class SeparatorAwareTransportWrapper(ListenerAware):
class TransportWrapper(ListenerAware):
unforwarded_handlers = []
def __init__(self, transport):
ListenerAware.__init__(self)
self.transport = transport
self.transport.register_listener(self)
def forward_handler(name):
def f(*args, **kwargs):
# replace references to self.transport with self
args = [self if arg == self.transport else arg for arg in args]
kwargs = dict((key, self if value == self.transport else value) for key, value in kwargs.items())
# forward
self.notify_listeners(name, *args, **kwargs)
return f
for handler in filter(lambda x: x.startswith("on_transport_"), dir(TransportListener)):
if handler not in self.__class__.unforwarded_handlers:
setattr(self, handler, forward_handler(handler))
def __getattr__(self, item):
return getattr(self.transport, item)
class SeparatorAwareTransportWrapper(TransportWrapper):
unforwarded_handlers = ["on_transport_log_received_data"]
"""We have read overwritten and hence send our own received_data notification."""
def __init__(self, transport, separator, internal_timeout=0.1):
super(SeparatorAwareTransportWrapper, self).__init__()
TransportWrapper.__init__(self, transport)
self.transport = transport
self.separator = separator
self.internal_timeout = internal_timeout
@@ -168,13 +206,6 @@ class SeparatorAwareTransportWrapper(ListenerAware):
self.notify_listeners("on_transport_log_received_data", self, data)
return data
def write(self, data):
self.transport.write(data)
self.notify_listeners("on_transport_log_sent_data", self, data)
def __getattr__(self, item):
return getattr(self.transport, item)
def __str__(self):
return "SeparatorAwareTransportWrapper({}, separator={})".format(self.transport, self.separator)
@@ -186,16 +217,20 @@ class LineAwareTransportWrapper(SeparatorAwareTransportWrapper):
def __str__(self):
return "LineAwareTransportWrapper({})".format(self.transport)
class PushingTransportWrapper(object):
class PushingTransportWrapper(TransportWrapper):
def __init__(self, transport, name="pushingTransportReceiveLoop", timeout=None):
self.transport = transport
super(PushingTransportWrapper, self).__init__(transport)
self.name = name
self.timeout = timeout
self._receiver_active = False
self._receiver_thread = None
@property
def active(self):
return self._receiver_active
def connect(self, **kwargs):
self.transport.connect(**kwargs)
@@ -222,14 +257,17 @@ class PushingTransportWrapper(object):
if self._receiver_active:
raise
def __getattr__(self, item):
return getattr(self.transport, item)
def __str__(self):
return "PushingTransportWrapper({})".format(self.transport)
class TransportListener(object):
def on_transport_connected(self, transport):
pass
def on_transport_disconnected(self, transport, error=None):
pass
def on_transport_log_sent_data(self, transport, data):
pass
+58 -10
View File
@@ -16,10 +16,12 @@ class SerialTransport(Transport):
key = "serial"
message_integrity = False
suggested_baudrates = [0, 250000, 230400, 115200, 57600, 38400, 19200, 9600]
suggested_baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
unix_port_patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/tty.usb*",
"/dev/cu.*", "/dev/cuaU*", "/dev/rfcomm*"]
max_write_passes = 5
@classmethod
def for_additional_ports_and_baudrates(cls, additional_ports, additional_baudrates):
patterns = SerialTransport.unix_port_patterns + additional_ports
@@ -66,12 +68,12 @@ class SerialTransport(Transport):
from serial.tools import list_ports_common
ports = [list_ports_common.ListPortInfo(d) for d in devices]
return [ConstantNameType("AUTO", "Autodetect")] \
+ [ConstantNameType(port.device, port.description) for port in ports]
return [ConstantNameType(port.device, port.description) for port in ports]
@classmethod
def get_available_baudrates(cls):
return cls.suggested_baudrates
return [ConstantNameType(0, "Auto detect")] + \
[ConstantNameType(baudrate, baudrate) for baudrate in cls.suggested_baudrates]
def __init__(self, *args, **kwargs):
super(SerialTransport, self).__init__()
@@ -81,29 +83,69 @@ class SerialTransport(Transport):
self._logger = logging.getLogger(__name__)
self._serial = None
self._closing = False
def create_connection(self, port="AUTO", baudrate=0):
factory = self.serial_factory
if self.serial_factory is None:
factory = serial.Serial
self._closing = False
self._serial = factory(port=port, baudrate=baudrate)
def drop_connection(self):
if self._serial is not None:
self._closing = True
self._serial.close()
self._serial = None
def close(self):
self._serial.close()
def do_read(self, size=None, timeout=None):
return self._serial.read(size=size)
def do_write(self, data):
self._serial.write(data)
written = 0
passes = 0
def close_connection(self):
self._serial.close()
def try_to_write(d):
result = self._serial.write(d)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
return len(data)
else:
return result
while written < len(data):
to_send = data[written:]
old_written = written
try:
written += try_to_write(to_send)
except serial.SerialTimeoutException:
self._logger.warn("Serial timeout while writing to serial port, trying again.")
try:
# second try
written += try_to_write(to_send)
except:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
except:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
if old_written == written:
passes += 1
if passes > self.__class__.max_write_passes:
message = "Could not write anything to the serial port in {} tries, something appears to be " \
"wrong with the printer communication".format(self.__class__.max_write_passes)
self._logger.error(message)
self.disconnect(error=message)
break
def __str__(self):
return "SerialTransport"
@@ -131,3 +173,9 @@ class VirtualSerialTransport(SerialTransport):
def __str__(self):
return "VirtualSerialTransport({})".format(self.virtual_serial_factory)
if __name__ == "__main__":
# list ports
ports = SerialTransport.get_available_serial_ports()
for port in ports:
print(port.title + ": " + port.name)
+3 -1
View File
@@ -111,7 +111,7 @@ class Printjob(ProtocolListener, ListenerAware):
self.reset_job()
def process_job_failed(self):
self.notify_listeners("on_job_failed")
self.notify_listeners("on_job_failed", self)
self.reset_job()
def process_job_progress(self):
@@ -223,6 +223,8 @@ class LocalGcodeFilePrintjob(LocalFilePrintjob):
# strip comments
processed = strip_comment(processed)
if not len(processed):
return None
# TODO apply offsets