More work on getting to the point where printing might work

Status reporting, timeout handling, parsing etc... lots of work
This commit is contained in:
Gina Häußge committed 2016-01-29 21:16:13 +01:00
1 parent ff9b7de615
commit cf02471db7
14 files changed
+885 -286

No files matched your search

+67 -47
View File
@@ -5,19 +5,25 @@ __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.util import to_unicode
import logging
class Protocol(object):
class Protocol(ListenerAware, TransportListener):
supported_jobs = []
def __init__(self):
super(Protocol, self).__init__()
self._logger = logging.getLogger(__name__)
self._state = ProtocolState.DISCONNECTED
self._listeners = []
self._job = None
self._transport = None
@property
def state(self):
@@ -25,26 +31,33 @@ class Protocol(object):
@state.setter
def state(self, new_state):
old_state = self._state
self._state = new_state
def register_listener(self, listener):
self._listeners.append(listener)
name = "_on_state_{}".format(new_state)
method = getattr(self, name, None)
if method is not None:
method(old_state)
def unregister_listener(self, listener):
self._listeners.remove(listener)
self.notify_listeners("on_protocol_state", self, old_state, new_state)
def connect(self, transport):
pass
self._transport = transport
self._transport.register_listener(self)
if self._transport.state == TransportState.DISCONNECTED:
self._transport.connect()
self.state = ProtocolState.CONNECTING
def disconnect(self):
pass
self._transport.unregister_listener(self)
def process(self, job, position=0):
if not job.can_process(self):
raise ValueError("Job {} cannot be processed with protocol {}".format(job, self))
self._job = job
self._job.register_listener(self)
self._job.process(job, position=position)
self._job.process(self, position=position)
def pause_processing(self):
if self._job is None or self.state != ProtocolState.PRINTING:
@@ -68,51 +81,46 @@ class Protocol(object):
def set_extrusion_multiplier(self, multiplier):
pass
def notify_listeners(self, name, *args, **kwargs):
for listener in self._listeners:
method = getattr(listener, name, None)
if not method:
continue
def can_send(self):
return True
try:
method(*args, **kwargs)
except:
self._logger.exception("Exception while calling {} on protocol listener {}".format(
"{}({})".format(name, ", ".join(list(args) + ["{}={}".format(key, value)
for key, value in kwargs.items()]))
))
def send_commands(self, command_type=None, *commands):
pass
def on_job_started(self, job):
if job != self._job:
return
self.state = ProtocolState.PRINTING
def on_job_done(self, job):
if job != self._job:
return
self._job = None
self.state = ProtocolState.CONNECTED
self._job_processed(job)
def on_job_cancelled(self, job):
if job != self._job:
return
self._job = None
self.state = ProtocolState.CONNECTED
self._job_processed(job)
def on_job_failed(self, job):
if job != self._job:
return
self._job = None
self._job_processed(job)
def _job_processed(self, job):
self._job.unregister_listener(self)
self.state = ProtocolState.CONNECTED
def on_transport_log_received_data(self, transport, data):
self.notify_listeners("on_protocol_log", self, "<<< {}".format(to_unicode(data, errors="replace").strip()))
def on_transport_log_sent_data(self, transport, data):
self.notify_listeners("on_protocol_log", self, ">>> {}".format(to_unicode(data, errors="replace").strip()))
def on_transport_log_message(self, transport, data):
self.notify_listeners("on_protocol_log", self, "--- {}".format(to_unicode(data, errors="replace").strip()))
class ProtocolState(object):
CONNECTING = "connecting"
CONNECTED = "connected"
DISCONNECTED = "disconnected"
PRINTING = "printing"
PAUSED = "paused"
ERROR = "error"
DISCONNECTED_WITH_ERROR = "disconnected with error"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
class FanControlProtocolMixin(object):
@@ -120,30 +128,39 @@ class FanControlProtocolMixin(object):
def set_fan_speed(self, speed):
pass
def get_fan_speed(self, speed):
pass
class MotorControlProtocolMixin(object):
def enable_motors(self):
self.set_motors(True)
self.set_motor_state(True)
def disable_motors(self):
self.set_motors(False)
self.set_motor_state(False)
def set_motors(self, enabled):
def set_motor_state(self, enabled):
pass
def get_motor_state(self):
pass
class PowerControlProtocolMixin(object):
def enable_power(self):
self.set_power(True)
self.set_power_state(True)
def disable_power(self):
self.set_power(False)
self.set_power_state(False)
def set_power(self, enabled):
def set_power_state(self, enabled):
pass
def get_power_state(self):
return None
class FileAwareProtocolMixin(object):
@@ -183,23 +200,26 @@ class FileStreamingProtocolMixin(FileManagementProtocolMixin):
class ProtocolListener(object):
def on_protocol_connection_state(self, state):
def on_protocol_state(self, protocol, old_state, new_state):
pass
def on_protocol_temperature(self, temperatures):
def on_protocol_temperature(self, protocol, temperatures):
pass
def on_protocol_log(self, protocol, message):
pass
class FileAwareProtocolListener(object):
def on_protocol_sd_file_list(self, files):
def on_protocol_sd_file_list(self, protocol, files):
pass
def on_protocol_sd_status(self, name, pos, total):
def on_protocol_sd_status(self, protocol, pos, total):
pass
def on_protocol_file_print_started(self, name, size):
def on_protocol_file_print_started(self, protocol, name, size):
pass
def on_protocol_file_print_done(self):
def on_protocol_file_print_done(self, protocol):
pass
@@ -0,0 +1,8 @@
# coding=utf-8
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"
@@ -1,3 +1,9 @@
# coding=utf-8
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"
import re
import Queue as queue
@@ -9,6 +15,15 @@ regex_int_pattern = "\d+"
regex_float = re.compile(regex_float_pattern)
"""Regex for a float value."""
regexes_parameters = dict(
floatP=re.compile("(^|[^A-Za-z])[Pp](?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),
intT=re.compile("(^|[^A-Za-z])[Tt](?P<value>%s)" % regex_int_pattern)
)
"""Regexes for parsing various GCODE command parameters."""
class GcodeCommand(object):
@@ -180,12 +195,3 @@ def strip_comment(line):
escaped = (c == "\\") and not escaped
return "".join(result)
def process_gcode_line(line, offsets=None, current_tool=None):
line = strip_comment(line).strip()
if not len(line):
return None
#if offsets is not None:
# line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
return line
+399 -61
View File
@@ -1,44 +1,74 @@
# coding=utf-8
from __future__ import absolute_import
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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol import Protocol, FileStreamingProtocolMixin, \
MotorControlProtocolMixin, FanControlProtocolMixin, ProtocolState
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, \
PushingTransportWrapper, PushingTransportWrapperListener
import re
from octoprint.comm.protocol.gcode.util import TypedQueue, TypeAlreadyInQueue, \
GcodeCommand, regexes_parameters
from octoprint.comm.protocol import Protocol, FileStreamingProtocolMixin, MotorControlProtocolMixin, FanControlProtocolMixin, ProtocolState
from octoprint.comm.transport import LineAwareTransportWrapper, TransportListener, PushingTransportWrapper
from octoprint.comm.protocol.util import TypedQueue, TypeAlreadyInQueue, GcodeCommand, process_gcode_line, strip_comment
from octoprint.job import LocalGcodeFilePrintjob, SDFilePrintjob, LocalGcodeStreamjob
from octoprint.job import LocalGcodeFilePrintjob, SDFilePrintjob, \
LocalGcodeStreamjob
from octoprint.util import to_unicode, protectedkeydict, CountedEvent
import Queue as queue
import collections
import threading
import time
class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtocolMixin, FileStreamingProtocolMixin, TransportListener):
supported_jobs = [LocalGcodeFilePrintjob, LocalGcodeStreamjob, SDFilePrintjob]
class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin,
FanControlProtocolMixin, FileStreamingProtocolMixin,
PushingTransportWrapperListener):
supported_jobs = [LocalGcodeFilePrintjob,
LocalGcodeStreamjob,
SDFilePrintjob]
@staticmethod
def get_attributes_starting_with(flavor, prefix):
return [x for x in dir(flavor) if x.startswith(prefix)]
def __init__(self, flavor):
Protocol.__init__(self)
self.flavor = flavor
def __init__(self, flavor, connection_timeout=30.0, communication_timeout=5.0,
temperature_interval_idle=2.0, temperature_interval_printing=5.0):
super(ReprapGcodeProtocol, self).__init__()
self._registered_messages = self.get_attributes_starting_with(self.flavor, "comm_") \
+ self.get_attributes_starting_with(self.flavor, "message_")
self._error_messages = self.get_attributes_starting_with(self.flavor, "error_")
self.flavor = flavor
self.timeouts = dict(
connection=connection_timeout,
communication=communication_timeout
)
self.interval = dict(
temperature_idle=temperature_interval_idle,
temperature_printing=temperature_interval_printing
)
comm_attrs = self.get_attributes_starting_with(self.flavor, "comm_")
message_attrs = self.get_attributes_starting_with(self.flavor, "message_")
error_attrs = self.get_attributes_starting_with(self.flavor, "error_")
self._registered_messages = comm_attrs + message_attrs
self._error_messages = error_attrs
self._transport = None
self._internal_state = dict(
# temperature and heating related
temperatures=dict(),
heating_start=None,
heating=False,
# current stuff
current_tool=0,
current_z=None,
# sd status
sd_available=False,
sd_files=[],
@@ -48,6 +78,16 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
resend_delta=None,
resend_linenumber=None,
resend_count=None,
# protocol status
long_running_command=False,
# misc
only_from_job=False,
trigger_events=True,
# timeout
timeout = None
)
self._protected_state = protectedkeydict(self._internal_state)
@@ -56,7 +96,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
self._send_queue = TypedQueue()
self._current_linenumber = 1
self._last_lines = []
self._last_lines = collections.deque(iterable=[], maxlen=50)
self._last_communication_error = None
self._gcode_hooks = dict(queuing=dict(),
@@ -64,6 +104,9 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
sending=dict(),
sent=dict())
# temperature polling
self._temperature_poller = None
# mutexes
self._line_mutex = threading.RLock()
self._send_queue_mutex = threading.RLock()
@@ -74,21 +117,24 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
self.sending_thread.daemon = True
self.sending_thread.start()
self._only_send_from_job = False
self._trigger_events_while_sending = True
def connect(self, transport):
self._transport = transport
if not isinstance(transport, Transport):
raise ValueError("transport must be a Transport subclass but is a {} instead".format(type(transport)))
self._internal_state["timeout"] = self._get_timeout("connection")
transport = PushingTransportWrapper(LineAwareTransportWrapper(transport), timeout=5.0)
super(ReprapGcodeProtocol, self).connect(transport)
def process(self, job, position=0):
if isinstance(job, LocalGcodeStreamjob):
self._only_send_from_job = True
self._trigger_events_while_sending = False
self._internal_state["only_from_job"] = True
self._internal_state["trigger_events"] = False
else:
self._only_send_from_job = False
self._trigger_events_while_sending = True
self._internal_state["only_from_job"] = False
self._internal_state["trigger_events"] = True
Protocol.process(job, position=position)
super(ReprapGcodeProtocol, self).process(job, position=position)
def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False):
commands = [self.flavor.command_move(x=x, y=y, z=z, e=e, f=feedrate)]
@@ -111,8 +157,8 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
##~~ MotorControlProtocolMixin
def set_motors(self, enabled):
self._send_commands(self.flavor.command.set_motors(enabled))
def set_motor_state(self, enabled):
self._send_commands(self.flavor.command.set_motor_state(enabled))
##~~ FanControlProtocolMixin
@@ -147,14 +193,79 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
def stop_recording_file(self):
self._send_commands(self.flavor.command_sd_end_write())
def get_file_print_status(self):
self._send_commands(self.flavor.command_sd_status())
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):
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)
##~~ State handling
def _is_operational(self):
return self.state not in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR)
def _is_busy(self):
return self.state in (ProtocolState.PRINTING, ProtocolState.PAUSED)
def _on_state_connecting(self, old_state):
hello = self.flavor.command_hello()
if hello:
self._send_command(hello)
self._clear_to_send.set()
def _on_state_connected(self, old_state):
self._internal_state["timeout"] = self._get_timeout("communication")
self._send_command(self.flavor.command_set_line(0))
self._clear_to_send.set()
def poll_temperature_interval():
return self.interval["temperature_printing"] if self.state == ProtocolState.PRINTING else self.interval["temperature_idle"]
def poll_temperature():
if self._is_operational() and not self._internal_state["only_from_job"] and self.can_send():
self._send_command(self.flavor.command_get_temp(), command_type="temperature_poll")
from octoprint.util import RepeatedTimer
self._temperature_poller = RepeatedTimer(poll_temperature_interval,
poll_temperature,
run_first=True,
condition=self._is_operational)
self._temperature_poller.start()
def _on_state_disconnected(self, old_state):
self._handle_disconnected(old_state, False)
def _on_state_disconnected_with_error(self, old_state):
self._handle_disconnected(old_state, True)
def _handle_disconnected(self, old_state, error):
if self._temperature_poller is not None:
self._temperature_poller.cancel()
self._temperature_poller = None
##~~ Receiving
def on_transport_data_received(self, transport, data):
def on_transport_data_pushed(self, transport, data):
if transport != self._transport:
return
self._receive(data)
def _receive(self, data):
if data is None:
# EOF
# TODO handle EOF
pass
line = to_unicode(data, encoding="ascii", errors="replace").strip()
lower_line = line.lower()
@@ -163,26 +274,55 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
if not handler_method:
continue
if getattr(self.flavor, message)(line, lower_line, self._protected_state):
matches = getattr(self.flavor, message)(line, lower_line, self._protected_state)
continue_further = False
if isinstance(matches, tuple) and len(matches) == 2:
matches, continue_further = matches
if matches:
message_args = dict()
parse_method = getattr(self.flavor, "parse_{}".format(message), None)
if parse_method:
parse_result = parse_method(line, lower_line, self._protected_state)
if parse_result is None:
break
if continue_further:
continue
else:
break
message_args.update(parse_result)
if not handler_method(**message_args):
break
if continue_further:
continue
else:
break
else:
# unknown message
pass
def _on_comm_timeout(self):
if self.state == ProtocolState.CONNECTING:
self.disconnect()
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())
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")
def _on_comm_ok(self):
if self.state == ProtocolState.CONNECTING:
self.state = ProtocolState.CONNECTED
return
self._clear_to_send.set()
if self._internal_state["heating"]:
self._internal_state["heating"] = False
if not self.state in (ProtocolState.PRINTING, ProtocolState.CONNECTED, ProtocolState.PAUSED):
return
@@ -207,7 +347,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
if last_communication_error is not None \
and last_communication_error == "linenumber" \
and linenumber == self._internal_state["resend_last_linenumber"] \
and self._resend_delta is not None and self._internal_state["resend_count"] < self._internal_state["resend_delta"]:
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
@@ -220,10 +360,9 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
# TODO error because printer requested lines we don't have
pass
def _on_comm_start(self):
print("!!! start")
self._clear_to_send.set()
if self.state == ProtocolState.CONNECTING:
self.state = ProtocolState.CONNECTED
def _on_comm_error(self, line, lower_line):
for message in self._error_messages:
@@ -248,11 +387,28 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
# unknown error message
pass
def on_error_communication(self, error_type):
def _on_error_communication(self, error_type):
self._last_communication_error = error_type
# TODO multiline error handling
def _on_message_temperature(self, max_tool_num, temperatures, heatup_detected):
if heatup_detected:
self._logger.debug("Externally triggered heatup detected")
self._internal_state["heating"] = True
self._internal_state["heatup_start"] = time.time()
potential_tools = dict(("T{}".format(x), "tool{}".format(x)) for x in range(max_tool_num + 1))
potential_tools.update(dict(B="bed"))
for tool_rep, tool in potential_tools.items():
if not tool_rep in temperatures:
continue
actual, target = temperatures[tool_rep]
self._set_temperature(tool, actual, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_state["temperatures"])
def _on_message_sd_init_ok(self):
self._internal_state["sd_available"] = True
self.list_files()
@@ -266,22 +422,19 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
def _on_message_sd_end_file_list(self):
self._internal_state["sd_files"] = self._internal_state["sd_files_temp"]
self._internal_state["sd_files_temp"] = None
self.notify_listeners("on_protocol_sd_file_list", self._internal_state["sd_files"])
self.notify_listeners("on_protocol_sd_file_list", self, self._internal_state["sd_files"])
def _on_message_sd_entry(self, name, size):
self._internal_state["sd_files_temp"].append((name, size))
def _on_message_sd_file_opened(self, name, size):
pass
def _on_message_sd_file_selected(self):
pass
self.notify_listeners("on_protocol_file_print_started", self, name, size)
def _on_message_sd_done_printing(self):
pass
self.notify_listeners("on_protocol_file_print_done", self)
def _on_message_sd_printing_byte(self, current, total):
self.notify_listeners("on_protocol_sd_status", current, total)
self.notify_listeners("on_protocol_sd_status", self, current, total)
##~~ Sending
@@ -322,7 +475,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
# 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._only_send_from_job:
if self._command_queue.empty() or self._internal_state["only_from_job"]:
# no command queue or irrelevant command queue => return
return False
@@ -342,19 +495,22 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
# return, we are done here
return True
def _send_commands(self, *commands):
def _send_commands(self, *commands, **kwargs):
command_type = kwargs.get("command_type", None)
for command in commands:
self._send_command(command)
if len(commands) > 1:
command_type = None
self._send_command(command, command_type=command_type)
def _send_command(self, command, command_type=None):
if isinstance(command, GcodeCommand):
gcode = command
command = gcode.command
command = str(gcode)
else:
gcode = None
with self._send_queue_mutex:
if self._trigger_events_while_sending:
if self._internal_state["trigger_events"]:
command, command_type, gcode = self._process_command_phase("queuing", command, command_type, gcode=gcode)
if command is None:
@@ -368,7 +524,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
self._enqueue_for_sending(command, command_type=command_type)
if self._trigger_events_while_sending:
if self._internal_state["trigger_events"]:
self._process_command_phase("queued", command, command_type, gcode=gcode)
return True
@@ -484,7 +640,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
self._clear_to_send.wait()
except:
self._logger.exception("Caught an exception in the send loop")
self._log("Closing down send loop")
self.notify_listeners("on_protocol_log", self, "Closing down send loop")
def _process_command_phase(self, phase, command, command_type=None, gcode=None):
if phase not in ("queuing", "queued", "sending", "sent"):
@@ -554,7 +710,7 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
def _do_increment_and_send_with_checksum(self, cmd):
with self._line_mutex:
linenumber = self._current_linenumber
self._add_to_last_line(cmd)
self._add_to_last_lines(cmd)
self._current_linenumber += 1
self._do_send_with_checksum(cmd, linenumber)
@@ -567,32 +723,214 @@ class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtoco
def _do_send_without_checksum(self, data):
self._transport.write(data + b"\n")
def _add_to_last_line(self, command):
def _add_to_last_lines(self, command):
self._last_lines.append(command)
##~~ command handlers
def _gcode_T_sent(self, cmd, cmd_type=None):
tool_match = regexes_parameters["intT"].search(cmd)
if tool_match:
self._internal_state["current_tool"] = int(tool_match.group("value"))
def _gcode_G0_sent(self, cmd, cmd_type=None):
if "Z" in cmd:
match = regexes_parameters["floatZ"].search(cmd)
if match:
try:
z = float(match.group("value"))
if self._internal_state["current_z"] != z:
self._internal_state["current_z"] = z
# TODO self._callback.on_comm_z_change(z)
except ValueError:
pass
_gcode_G1_sent = _gcode_G0_sent
def _gcode_M0_queuing(self, cmd, cmd_type=None):
self.pause_file_print()
return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
_gcode_M1_queuing = _gcode_M0_queuing
def _gcode_M25_queuing(self, cmd, cmd_type=None):
# M25 while not printing from SD will be handled as pause. This way it can be used as another marker
# for GCODE induced pausing. Send it to the printer anyway though.
if self.state == ProtocolState.PRINTING and not isinstance(self._job, SDFilePrintjob):
self.pause_file_print()
def _gcode_M140_queuing(self, cmd, cmd_type=None):
# TODO heated bed handling needs heated bed flag from printer profile
#if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
# self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd))
# return None, # Don't send bed commands if we don't have a heated bed
pass
_gcode_M190_queuing = _gcode_M140_queuing
def _gcode_M104_sent(self, cmd, cmd_type=None):
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)
match = regexes_parameters["floatS"].search(cmd)
if match:
try:
target = float(match.group("value"))
self._set_temperature(tool, None, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_state["temperatures"])
except ValueError:
pass
def _gcode_M140_sent(self, cmd, cmd_type=None):
match = regexes_parameters["floatS"].search(cmd)
if match:
try:
target = float(match.group("value"))
self._set_temperature("bed", None, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_state["temperatures"])
except ValueError:
pass
def _gcode_M109_sent(self, cmd, cmd_type=None):
self._internal_state["heatup_start"] = time.time()
self._internal_state["heating"] = True
self._gcode_M104_sent(cmd, cmd_type)
def _gcode_M190_sent(self, cmd, cmd_type=None):
self._internal_state["heatup_start"] = time.time()
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
match = regexes_parameters["intN"].search(cmd)
if match:
try:
new_line_number = int(match.group("value"))
except:
pass
else:
new_line_number = 0
with self._line_mutex:
# send M110 command with new line number
self._current_linenumber = new_line_number
# after a reset of the line number we have no way to determine what line exactly the printer now wants
self._last_lines.clear()
self._internal_state["resend_delta"] = None
def _gcode_M112_queuing(self, cmd, cmd_type=None):
# emergency stop, jump the queue with the M112
self._do_send_with_checksum(str(self.flavor.command_emergency_stop()))
self._do_increment_and_send_with_checksum(str(self.flavor.command_emergency_stop()))
# No idea if the printer is still listening or if M112 won. Just in case
# we'll now try to also manually make sure all heaters are shut off - better
# safe than sorry. We do this ignoring the queue since at this point it
# is irrelevant whether the printer has sent enough ack's or not, we
# are going to shutdown the connection in a second anyhow.
# TODO needs printer profile
"""
for tool in range(self._printerProfileManager.get_current_or_default()["extruder"]["count"]):
self._do_increment_and_send_with_checksum(self.flavor.set_extruder_temp(s=0, t=tool))
if self._printerProfileManager.get_current_or_default()["heatedBed"]:
self._do_increment_and_send_with_checksum(str(self.flavor.set_bed_temp(s=0)))
"""
# close to reset host state
# TODO needs error and event handling
"""
self._errorValue = "Closing serial port due to emergency stop M112."
self._log(self._errorValue)
self.close(is_error=True)
# fire the M112 event since we sent it and we're going to prevent the caller from seeing it
gcode = "M112"
if gcode in gcodeToEvent:
eventManager().fire(gcodeToEvent[gcode])
"""
# return None 1-tuple to eat the one that is queuing because we don't want to send it twice
# I hope it got it the first time because as far as I can tell, there is no way to know
return None,
def _gcode_G4_sent(self, cmd, cmd_type=None):
# we are intending to dwell for a period of time, increase the timeout to match
p_match = regexes_parameters["floatP"].search(cmd)
s_match = regexes_parameters["floatS"].search(cmd)
_timeout = 0
if p_match:
_timeout = float(p_match.group("value")) / 1000.0
elif s_match:
_timeout = float(s_match.group("value"))
# TODO needs timeout handling
#self._timeout = get_new_timeout("communication") + _timeout
##~~ command phase handlers
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None):
if gcode is not None and gcode.command in self.flavor.long_running_commands:
self._internal_state["long_running_command"] = True
##~~ helpers
def _set_temperature(self, tool, actual, target):
temperatures = self._internal_state["temperatures"]
if actual is None and tool in temperatures:
actual, _ = temperatures[tool]
if target is None and tool in temperatures:
_, target = temperatures[tool]
temperatures[tool] = (actual, target)
def _get_timeout(self, timeout_type):
if timeout_type in self.timeouts:
return time.time() + self.timeouts[timeout_type]
else:
return time.time()
if __name__ == "__main__":
from octoprint.comm.transport.serialtransport import VirtualSerialTransport
from octoprint.comm.protocol.reprap.virtual import VirtualPrinter
from octoprint.comm.protocol.reprap.flavors import ReprapGcodeFlavor
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener
from octoprint.job import PrintjobListener
def virtual_serial_factory():
return VirtualPrinter(virtual_sd="C:/Users/gina/AppData/Roaming/OctoPrint/virtualSd")
class CustomProtocolListener(object):
class CustomProtocolListener(ProtocolListener, FileAwareProtocolListener, PrintjobListener):
def on_protocol_sd_file_list(self, files):
def on_protocol_state(self, protocol, old_state, new_state):
print("State changed from {} to {}".format(old_state, new_state))
def on_protocol_temperature(self, protocol, temperatures):
print("Temperature update: {!r}".format(temperatures))
def on_protocol_sd_file_list(self, protocol, files):
print("Received files from printer:")
for f in files:
print("\t{} (Size {} bytes)".format(*f))
transport = PushingTransportWrapper(
LineAwareTransportWrapper(
VirtualSerialTransport(virtual_serial_factory=virtual_serial_factory)
)
)
filename = "50mm-t~5.gco"
print("Going to print file {} from SD card".format(filename))
from octoprint.job import SDFilePrintjob
job = SDFilePrintjob(filename)
job.register_listener(self)
protocol.process(job)
def on_protocol_log(self, protocol, data):
print(data)
def on_job_progress(self, job, progress, estimation):
print("Job progress: {}% (Total estimated time: {}min)".format(int(progress * 100) if progress is not None else "-",
int(estimation / 60) if estimation is not None else "-"))
transport = VirtualSerialTransport(virtual_serial_factory=virtual_serial_factory)
protocol = ReprapGcodeProtocol(ReprapGcodeFlavor)
transport.register_listener(protocol)
protocol.register_listener(CustomProtocolListener())
transport.connect()
@@ -1,5 +1,6 @@
# coding=utf-8
from __future__ import absolute_import
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'
@@ -7,14 +8,19 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import re
import logging
import time
from octoprint.comm.protocol.util import GcodeCommand, regex_positive_float_pattern
from octoprint.comm.protocol.gcode.util import GcodeCommand, regex_positive_float_pattern
class ReprapGcodeFlavor(object):
key = "generic"
logger = logging.getLogger(__name__)
unknown_requires_ack = False
unknown_with_checksum = False
@@ -22,7 +28,8 @@ class ReprapGcodeFlavor(object):
never_send_checksum = False
checksum_requiring_commands = ["M110"]
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M400", "M226"]
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"]
asynchronous_commands = ["G0", "G1", "G2", "G3"]
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.
@@ -35,9 +42,9 @@ class ReprapGcodeFlavor(object):
* ``target``: target temperature, if provided (float)
"""
regex_sd_file_opened = re.compile("File opened:\s*(?P<name>.*?)(\s+Size:\s*(?P<size>[0-9]+))?")
regex_sd_file_opened = re.compile("file opened:\s*(?P<name>.*?)(\s+size:\s*(?P<size>[0-9]+)|$)")
regex_sd_printing_byte = re.compile("(?P<current>[0-9]*)/(?P<total>[0-9]*)")
regex_sd_printing_byte = re.compile("sd printing byte (?P<current>[0-9]*)/(?P<total>[0-9]*)")
"""Regex matching SD printing status reports.
Groups will be as follows:
@@ -48,9 +55,13 @@ class ReprapGcodeFlavor(object):
##~~ Message matchers
@classmethod
def comm_timeout(cls, line, lower_line, state):
return line == "" and time.time() > state["timeout"]
@classmethod
def comm_ok(cls, line, lower_line, state):
return lower_line.startswith("ok")
return lower_line.startswith("ok"), cls.message_temperature(line, lower_line, state)
@classmethod
def comm_start(cls, line, lower_line, state):
@@ -160,10 +171,143 @@ class ReprapGcodeFlavor(object):
line_to_resend = int(line.split()[1])
return dict(linenumber=line_to_resend)
@classmethod
def parse_message_temperature(cls, line, lower_line, state):
"""
Parses the provided temperature line.
The result will be a dictionary mapping from the extruder or bed key to
a tuple with current and target temperature. The result will be canonicalized
with :func:`canonicalize_temperatures` before returning.
Returns:
tuple: a 2-tuple with the maximum tool number and a dict mapping from
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
"""
current_tool = state["current_tool"]
result = {}
max_tool_num = 0
for match in re.finditer(cls.regex_temp, line):
values = match.groupdict()
tool = values["tool"]
if tool == "T" and "toolnum" in values and values["toolnum"]:
tool_num = int(values["toolnum"])
if tool_num > max_tool_num:
max_tool_num = tool_num
try:
actual = float(values.get("actual", None)) if values.get("actual", None) is not None else None
target = float(values.get("target", None)) if values.get("target", None) is not None else None
result[tool] = actual, target
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
heatup_detected = not lower_line.startswith("ok") and not state["heating"]
return dict(max_tool_num=max(max_tool_num, current_tool),
temperatures=cls._canonicalize_temperatures(result, current_tool),
heatup_detected=heatup_detected)
@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_message_sd_file_opened(cls, line, lower_line, state):
match = cls.regex_sd_file_opened.match(lower_line)
return dict(name=match.group("name"), size=match.group("size"))
if not match:
return
return dict(name=match.group("name"), size=int(match.group("size")))
@classmethod
def parse_message_sd_entry(cls, line, lower_line, state):
@@ -196,25 +340,35 @@ class ReprapGcodeFlavor(object):
@classmethod
def parse_message_sd_printing_byte(cls, line, lower_line, state):
match = cls.regex_sd_printing_byte.match(lower_line)
return dict(current=match.group("current"), total=match.group("total"))
if not match:
return None
return dict(current=int(match.group("current")), total=int(match.group("total")))
##~~ Commands
@classmethod
def command_hello(cls):
return cls.command_set_line(0)
@classmethod
def command_get_temp(cls):
return GcodeCommand("M105")
@classmethod
def command_set_extruder_temp(cls, s, t, w):
return GcodeCommand("M109", s=s, t=t) if w else GcodeCommand("M104", s=s, t=t)
@classmethod
def command_set_line(cls, n):
return GcodeCommand("M110", n=n)
@classmethod
def command_set_bed_temp(cls, s, w):
return GcodeCommand("M190", s=s) if w else GcodeCommand("M140", s=s)
def command_emergency_stop(cls):
return GcodeCommand("M112")
@classmethod
def command_set_extruder_temp(cls, s, t, wait):
return GcodeCommand("M109" if wait else "M104", s=s, t=t)
@classmethod
def command_set_bed_temp(cls, s, wait):
return GcodeCommand("M190" if wait else "M140", s=s)
@classmethod
def command_set_relative_positioning(cls):
@@ -272,23 +426,30 @@ class ReprapGcodeFlavor(object):
def command_sd_select_file(cls, name):
return GcodeCommand("M23", param=name)
@classmethod
def command_sd_start(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_pause(cls):
return GcodeCommand("M25")
@classmethod
def command_sd_set_pos(cls, pos):
return GcodeCommand("M26", s=pos)
@classmethod
def command_sd_status(cls):
return GcodeCommand("M27")
@classmethod
def command_sd_begin_write(cls, name):
return GcodeCommand("M28", param=name)
@classmethod
def command_sd_end_write(cls):
return GcodeCommand("M29")
@classmethod
def command_sd_delete(cls, name):
return GcodeCommand("M30", param=name)
@@ -0,0 +1,14 @@
# coding=utf-8
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"
from octoprint.comm.protocol.reprap.flavors import ReprapGcodeFlavor
class MarlinFlavor(ReprapGcodeFlavor):
key = "marlin"
@@ -1,5 +1,6 @@
# coding=utf-8
from __future__ import absolute_import
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'
@@ -8,7 +9,9 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
from octoprint.comm.protocol.reprap.flavors import ReprapGcodeFlavor
import logging
from octoprint.comm.protocol.gcode.util import regex_positive_float_pattern
import re
class RepetierFlavor(ReprapGcodeFlavor):
@@ -16,10 +19,59 @@ class RepetierFlavor(ReprapGcodeFlavor):
always_send_checksum = True
logger = logging.getLogger(__name__)
identical_resends_countdown = 5
regex_tempextr = re.compile("targetextr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier.
Groups will be as follows:
* ``toolnum``: number of the extruder to which the target temperature
report belongs (int)
* ``target``: new target temperature (float)
"""
regex_tempbed = re.compile("targetbed:(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows:
* ``target``: new target temperature (float)
"""
@classmethod
def message_temperature(cls, line, lower_line, state):
return ReprapGcodeFlavor.message_temperature(line, lower_line, state) or "targetextr" in lower_line or "targetbed" in lower_line
@classmethod
def parse_message_temperature(cls, line, lower_line, state):
if "targetextr" in lower_line:
match = cls.regex_tempextr.match(lower_line)
if match is not None:
tool_num = int(match.group("toolnum"))
target = float(match.group("target"))
tool = "T{}".format(tool_num)
temperatures = dict()
temperatures[tool] = (None, target)
return dict(max_tool_num=max(tool_num, state.get("current_tool", 0)),
temperatures=temperatures,
detected_heatup=False)
elif "targetbed" in lower_line:
match = cls.regex_tempbed.match(lower_line)
if match is not None:
target = float(match.group("target"))
temperatures = dict(bed=(None, target))
return dict(max_tool_num=state.get("current_tool", 0),
temperatures=temperatures,
detected_heatup=False)
else:
# Repetier sends temperature output on it's own line, so we can't use the
# "no ok in temperature output" metric to detected external heatups
result = ReprapGcodeFlavor.parse_message_temperature(line, lower_line, state)
result["heating"] = False
return result
##~~ Preprocessors, returning True stops further processing by the protocol
@classmethod
@@ -0,0 +1,21 @@
# coding=utf-8
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"
from octoprint.comm.protocol.gcode.util import strip_comment
def process_gcode_line(line, offsets=None, current_tool=None):
line = strip_comment(line).strip()
if not len(line):
return None
#if offsets is not None:
# line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
return line
@@ -11,6 +11,8 @@ import threading
import math
import Queue
from octoprint.util import to_unicode
from serial import SerialTimeoutException
class VirtualPrinter(object):
@@ -785,7 +787,7 @@ class VirtualPrinter(object):
try:
self.incoming.put(data, timeout=self._write_timeout)
self._seriallog.info("<<< {}".format(data.strip()))
self._seriallog.info(u"<<< {}".format(to_unicode(data.strip(), errors="replace")))
except Queue.Full:
self._logger.info("Incoming queue is full, raising SerialTimeoutException")
raise SerialTimeoutException()
@@ -797,7 +799,7 @@ class VirtualPrinter(object):
try:
line = self.outgoing.get(timeout=self._read_timeout) + "\n"
time.sleep(self._throttle)
self._seriallog.info(">>> {}".format(line.strip()))
self._seriallog.info(u">>> {}".format(to_unicode(line.strip(), errors="replace")))
return line
except Queue.Empty:
return ""
+70 -51
View File
@@ -7,7 +7,12 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms
from .parameters import get_param_dict
class Transport(object):
import logging
import time
from octoprint.util.listener import ListenerAware
class Transport(ListenerAware):
name = None
key = None
@@ -18,6 +23,9 @@ class Transport(object):
return []
def __init__(self, *args, **kwargs):
super(Transport, self).__init__()
self._logger = logging.getLogger(__name__)
self._state = TransportState.DISCONNECTED
@property
@@ -37,10 +45,19 @@ class Transport(object):
def create_connection(self, *args, **kwargs):
pass
def read(self, size=None):
return b""
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)
return data
def write(self, data):
self.do_write(data)
self.notify_listeners("on_transport_log_sent_data", self, data)
def do_read(self, size=None, timeout=None):
return b""
def do_write(self, data):
pass
@@ -57,60 +74,65 @@ class AlreadyConnectedError(Exception):
pass
class SeparatorAwareTransportWrapper(object):
class SeparatorAwareTransportWrapper(ListenerAware):
def __init__(self, transport, separator, internal_timeout=0.1):
super(SeparatorAwareTransportWrapper, self).__init__()
def __init__(self, transport, separator, chunksize=128):
self.transport = transport
self.separator = separator
self.internal_timeout = internal_timeout
self._buffered = b""
self._chunksize = chunksize
def read(self, size=None):
if size is not None:
return self._internal_read(size)
def read(self, size=None, timeout=None):
data = self._buffered
self._buffered = b""
data = b""
while self.separator not in data:
data += self._internal_read(size=self._chunksize)
rest = timeout
while self.separator not in data and (rest is None or rest > 0):
start = time.time()
read = self.transport.read(1, timeout=self.internal_timeout)
end = time.time()
separator_pos = data.index(self.separator)
separator_end = separator_pos + len(self.separator)
self._buffered += data[separator_end:]
return data[:separator_end]
if rest is not None:
rest -= end - start if end > start else 0
if rest < 0:
rest = 0
def _internal_read(self, size=None):
if self._buffered:
if size is not None and len(self._buffered) > size:
# return first size bytes
data = self._buffered[:size]
self._buffered = self._buffered[size:]
return data
else:
# fetch data from buffer, reset buffer and recalculate size
data = self._buffered
self._buffered = b""
size -= len(data) if size is not None else None
else:
if read is None:
# EOF
break
data += read
if rest is not None and rest <= 0:
# couldn't read a full line within the timeout, returning empty line and
# buffering already read data
self._buffered = data
data = b""
return data + self.transport.read(size)
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)
class LineAwareTransportWrapper(SeparatorAwareTransportWrapper):
def __init__(self, transport, chunksize=512):
SeparatorAwareTransportWrapper.__init__(self, transport, b"\n", chunksize=chunksize)
def __init__(self, transport):
SeparatorAwareTransportWrapper.__init__(self, transport, b"\n")
class PushingTransportWrapper(object):
def __init__(self, transport, name="pushingTransportReceiveLoop"):
def __init__(self, transport, name="pushingTransportReceiveLoop", timeout=None):
self.transport = transport
self.name = name
self.timeout = timeout
self._listeners = set()
self._receiver_active = False
self._receiver_thread = None
@@ -131,30 +153,27 @@ class PushingTransportWrapper(object):
def wait(self):
self._receiver_thread.join()
def register_listener(self, transport_listener):
self._listeners.add(transport_listener)
def unregister_listener(self, transport_listener):
try:
self._listeners.remove(transport_listener)
except KeyError:
# not registered, ah well, we'll ignore that
pass
def _send_on_transport_data_received(self, data):
for listener in self._listeners:
listener.on_transport_data_received(self, data)
def _receiver_loop(self):
while self._receiver_active:
data = self.transport.read()
self._send_on_transport_data_received(data)
data = self.transport.read(timeout=self.timeout)
self.notify_listeners("on_transport_data_pushed", self, data)
def __getattr__(self, item):
return getattr(self.transport, item)
class TransportListener(object):
def on_transport_data_received(self, transport, data):
def on_transport_log_sent_data(self, transport, data):
pass
def on_transport_log_received_data(self, transport, data):
pass
def on_transport_log_message(self, transport, data):
pass
class PushingTransportWrapperListener(object):
def on_transport_data_pushed(self, transport, data):
pass
@@ -81,14 +81,11 @@ class SerialTransport(Transport):
def close(self):
self._serial.close()
def read(self, size=None):
result = self._serial.read(size=size)
print("<<< {!r}".format(result))
return result
def do_read(self, size=None, timeout=None):
return self._serial.read(size=size)
def write(self, data):
def do_write(self, data):
self._serial.write(data)
print(">>> {!r}".format(data))
def close_connection(self):
self._serial.close()
@@ -114,58 +111,3 @@ class VirtualSerialTransport(SerialTransport):
raise ValueError("virtual_serial_factory is not callable")
self._serial = self.virtual_serial_factory()
if __name__ == "__main__":
for option in VirtualSerialTransport.get_connection_options():
print(repr(option))
def create_virtual_serial():
class VirtualSerial():
def __init__(self):
self.active = True
self.lines = [b"one", b"two", b"three", b"four", b"five"]
def read(self, size=None):
if self.active:
if self.lines:
data = self.lines.pop(0)
print("read called: {!r}".format(data))
return data + b"\n"
else:
self.close()
return ""
else:
raise RuntimeError("virtual serial is closed")
def write(self, data):
print("write called: {!r}".format(data))
def close(self):
self.active = False
print("Closed")
return VirtualSerial()
from octoprint.comm.transport import TransportListener
class MyTransportListener(TransportListener):
def on_transport_data_received(self, transport, data):
print(">>> Received: {!r}".format(data))
transport.write(b"echo:" + data)
listener = MyTransportListener()
#pushingvirtual = PushingTransportWrapper(LineAwareTransportWrapper(VirtualSerialTransport(virtual_serial_factory=create_virtual_serial)))
#pushingvirtual.register_listener(listener)
#pushingvirtual.connect()
#pushingvirtual.write(b"Just a test")
#pushingvirtual.wait()
to_send = [b"Send 1", b"Send 2"]
virtual = LineAwareTransportWrapper(VirtualSerialTransport(virtual_serial_factory=create_virtual_serial))
virtual.connect()
for data in to_send:
data += b"\n"
print(">>> {!r}".format(data))
virtual.write(data)
print("<<< {!r}".format(virtual.read()))
virtual.close()
@@ -37,12 +37,12 @@ class TcpTransport(Transport):
self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
self._socket.connect((host, port))
def read(self, size=None):
def do_read(self, size=None, timeout=None):
if size is None:
size = 16
return self._socket.recv(size)
def write(self, data):
def do_write(self, data):
self._socket.sendall(data)
def close(self):
+15 -35
View File
@@ -7,25 +7,20 @@ import time
from octoprint.comm.protocol import FileAwareProtocolListener
from octoprint.util.listener import ListenerAware
from abc import ABCMeta, abstractmethod, abstractproperty
class Printjob(object):
class Printjob(ListenerAware):
__metaclass__ = ABCMeta
def __init__(self):
super(Printjob, self).__init__()
self._logger = logging.getLogger(__name__)
self._start = None
self._protocol = None
self._printer_profile = None
self._listeners = []
def register_listener(self, listener):
self._listeners.append(listener)
def unregister_listener(self, listener):
self._listeners.remove(listener)
def can_process(self, protocol):
return False
@@ -71,20 +66,6 @@ class Printjob(object):
def process_job_failed(self):
self.notify_listeners("on_job_failed")
def notify_listeners(self, name, *args, **kwargs):
for listener in self._listeners:
method = getattr(listener, name, None)
if not method:
continue
try:
method(*args, **kwargs)
except:
self._logger.exception("Exception while calling {} on printjob listener {}".format(
"{}({})".format(name, ", ".join(list(args) + ["{}={}".format(key, value)
for key, value in kwargs.items()]))
))
class LocalFilePrintjob(Printjob):
@@ -214,28 +195,24 @@ class SDFilePrintjob(Printjob, FileAwareProtocolListener):
def get_progress(self):
if self._size is None or self._last_pos is None:
return None
return self._last_pos / self._size
return float(self._last_pos) / float(self._size)
def on_protocol_sd_file_list(self, files):
pass
def on_protocol_sd_status(self, name, pos, total):
if name != self._filename:
return
def on_protocol_sd_status(self, protocol, pos, total):
self._last_pos = pos
self._size = total
self.notify_listeners("on_job_progress", self, self.get_progress(), self.get_time_estimate())
def on_protocol_file_print_started(self, name, size):
if name != self._filename:
return
def on_protocol_file_print_started(self, protocol, name, size):
self._size = size
def on_protocol_file_print_done(self):
def on_protocol_file_print_done(self, protocol):
self._active = False
self._protocol.unregister_listener(self)
self.notify_listeners("on_job_done", self)
def _query_status(self):
self._protocol.get_file_print_status()
if self._protocol.can_send():
self._protocol.get_file_print_status()
def _query_active(self):
return self._active
@@ -254,3 +231,6 @@ class PrintjobListener(object):
def on_job_failed(self, job):
pass
def on_job_progress(self, job, progress, estimation):
pass
+36
View File
@@ -0,0 +1,36 @@
# coding=utf-8
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"
class ListenerAware(object):
def __init__(self):
self._listeners = set()
def register_listener(self, listener):
self._listeners.add(listener)
def unregister_listener(self, listener):
self._listeners.remove(listener)
def notify_listeners(self, name, *args, **kwargs):
from logging import getLogger
logger = getLogger(__name__)
for listener in self._listeners.copy():
method = getattr(listener, name, None)
if not method:
continue
try:
method(*args, **kwargs)
except:
logger.exception("Exception while calling {} on protocol listener {}".format(
"{}(...)".format(name),
listener
))