From 34facfe764b1bd1456cdeaa6f305574368e2f0d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 21 Jan 2016 10:55:29 +0100 Subject: [PATCH] WIP --- src/octoprint/comm/protocol/__init__.py | 45 + .../comm/protocol/reprap/__init__.py | 569 +++++++++++ .../comm/protocol/reprap/flavors/__init__.py | 237 +++++ .../comm/protocol/reprap/flavors/repetier.py | 13 + src/octoprint/comm/protocol/reprap/virtual.py | 880 ++++++++++++++++++ src/octoprint/comm/protocol/reprapgcode.py | 287 ------ src/octoprint/comm/transport/__init__.py | 10 +- src/octoprint/util/__init__.py | 49 + 8 files changed, 1799 insertions(+), 291 deletions(-) create mode 100644 src/octoprint/comm/protocol/reprap/__init__.py create mode 100644 src/octoprint/comm/protocol/reprap/flavors/__init__.py create mode 100644 src/octoprint/comm/protocol/reprap/flavors/repetier.py create mode 100644 src/octoprint/comm/protocol/reprap/virtual.py delete mode 100644 src/octoprint/comm/protocol/reprapgcode.py diff --git a/src/octoprint/comm/protocol/__init__.py b/src/octoprint/comm/protocol/__init__.py index 0102aa9f1..8977cba75 100644 --- a/src/octoprint/comm/protocol/__init__.py +++ b/src/octoprint/comm/protocol/__init__.py @@ -6,8 +6,21 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" +import logging + + class Protocol(object): + def __init__(self): + self._logger = logging.getLogger(__name__) + self._listeners = [] + + def register_listener(self, listener): + self._listeners.append(listener) + + def unregister_listener(self, listener): + self._listeners.remove(listener) + def connect(self, transport): pass @@ -29,6 +42,20 @@ 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 + + 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()])) + )) + class FanControlProtocolMixin(object): @@ -91,3 +118,21 @@ class FileStreamingProtocolMixin(FileManagementProtocolMixin): def stop_recording_file(self): pass + + +class ProtocolListener(object): + + def on_protocol_connection_state(self, state): + pass + + def on_protocol_temperature(self, temperatures): + pass + + +class FileAwareProtocolListener(object): + + def on_protocol_sd_file_list(self, files): + pass + + def on_protocol_sd_status(self, name, pos, total): + pass diff --git a/src/octoprint/comm/protocol/reprap/__init__.py b/src/octoprint/comm/protocol/reprap/__init__.py new file mode 100644 index 000000000..be123af47 --- /dev/null +++ b/src/octoprint/comm/protocol/reprap/__init__.py @@ -0,0 +1,569 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__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" + + +import re + +from octoprint.comm.protocol import Protocol, FileStreamingProtocolMixin, MotorControlProtocolMixin, FanControlProtocolMixin +from octoprint.comm.transport import LineAwareTransportWrapper, TransportListener, PushingTransportWrapper + +from octoprint.util import to_unicode, dictview, CountedEvent + +import Queue as queue +import threading + + +regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+" +regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+" +regex_int_pattern = "\d+" + +regex_float = re.compile(regex_float_pattern) +"""Regex for a float value.""" + + +class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtocolMixin, FileStreamingProtocolMixin, TransportListener): + + def __init__(self, flavor): + Protocol.__init__(self) + self.flavor = flavor + + self._registered_messages = ["comm_ok", "comm_start", "comm_wait", "comm_resend"] \ + + [x for x in dir(self.flavor) if x.startswith("message_")] + + self._transport = None + + self._internal_state = dict( + # sd status + sd_available=False, + sd_files=[], + sd_files_temp=None + ) + self._state_view = dictview(self._internal_state) + + self._command_queue = queue.Queue() + self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send") + self._send_queue = TypedQueue() + + self._current_linenumber = 1 + self._last_lines = [] + + # mutexes + self._line_mutex = threading.RLock() + + # sending thread + self._send_queue_active = True + self.sending_thread = threading.Thread(target=self._send_loop, name="comm.sending_thread") + self.sending_thread.daemon = True + self.sending_thread.start() + + def connect(self, transport): + self._transport = transport + + 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)] + + if relative: + commands = [self.flavor.command_set_relative_positioning()] + commands + [self.flavor.command_set_absolute_positioning()] + + self._send(*commands) + + def home(self, x=False, y=False, z=False): + self._send(self.flavor.command_home(x=x, y=y, z=z)) + + def set_feedrate_multiplier(self, multiplier): + self._send(self.flavor.command_set_feedrate_multiplier(multiplier)) + + def set_extrusion_multiplier(self, multiplier): + self._send(self.flavor.command.set_extrusion_multiplier(multiplier)) + + ##~~ MotorControlProtocolMixin + + def set_motors(self, enabled): + self._send(self.flavor.command.set_motors(enabled)) + + ##~~ FanControlProtocolMixin + + def set_fan_speed(self, speed): + self._send(self.flavor.command.set_fan_speed(speed)) + + ##~~ FileStreamingProtocolMixin + + def init_file_storage(self): + self._send(self.flavor.command_sd_init()) + + def list_files(self): + self._send(self.flavor.command_sd_refresh()) + + def start_file_print(self, name): + self._send(self.flavor.command_sd_select_file(name), + self.flavor.command_sd_set_pos(0), + self.flavor.command_sd_start()) + + def pause_file_print(self): + self._send(self.flavor.command_sd_pause()) + + def resume_file_print(self): + self._send(self.flavor.command_sd_resume()) + + def delete_file(self, name): + self._send(self.flavor.command_sd_delete(name)) + + def record_file(self, name, job): + self._send(self.flavor.command_sd_begin_write(name)) + + def stop_recording_file(self): + self._send(self.flavor.command_sd_end_write()) + + def on_transport_data_received(self, transport, data): + if transport != self._transport: + return + self._receive(data) + + def _send(self, *commands): + for command in commands: + self._send_queue.put(str(command) + b"\n") + + def _receive(self, data): + line = to_unicode(data, encoding="ascii", errors="replace").strip() + lower_line = line.lower() + + for message in self._registered_messages: + handler_method = getattr(self, "_on_{}".format(message), None) + if not handler_method: + continue + + if getattr(self.flavor, message)(line, lower_line, self._state_view): + message_args = dict() + + parse_method = getattr(self.flavor, "parse_{}".format(message), None) + if parse_method: + message_args.update(parse_method(line, lower_line, self._state_view)) + + if not handler_method(**message_args): + break + else: + # unknown message + pass + + def _send_loop(self): + """ + The send loop is reponsible of sending commands in ``self._send_queue`` over the line, if it is cleared for + sending (through received ``ok`` responses from the printer's firmware. + """ + + self._clear_to_send.wait() + + while self._send_queue_active: + try: + # wait until we have something in the queue + entry = self._send_queue.get() + + try: + # make sure we are still active + if not self._send_queue_active: + break + + # fetch command and optional linenumber from queue + command, linenumber, command_type = 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 + # at hand here and only clear our clear_to_send flag later if that's the case + gcode = GcodeCommand.from_line(command) + + if linenumber is not None: + # line number predetermined - this only happens for resends, so we'll use the number and + # send directly without any processing (since that already took place on the first sending!) + self._do_send_with_checksum(command, linenumber) + + else: + # trigger "sending" phase + command, _, gcode = self._process_command_phase("sending", command, command_type, gcode=gcode) + + if command is None: + # No, we are not going to send this, that was a last-minute bail. + # However, since we already are in the send queue, our _monitor + # loop won't be triggered with the reply from this unsent command + # now, so we try to tickle the processing of any active + # command queues manually + self._continue_sending() + + # and now let's fetch the next item from the queue + continue + + if command.strip() == "": + self._logger.info("Refusing to send an empty line to the printer") + + # same here, tickle the queues manually + self._continue_sending() + + # and fetch the next item + continue + + # now comes the part where we increase line numbers and send stuff - no turning back now + command_requiring_checksum = gcode is not None and gcode.command in self.flavor.checksum_requiring_commands + command_allowing_checksum = gcode is not None or self.flavor.unknown_with_checksum + checksum_enabled = self.flavor.always_send_checksum or (self.isPrinting() and not self.flavor.never_send_checksum) + + command_to_send = command.encode("ascii", errors="replace") + if command_requiring_checksum or (command_allowing_checksum and checksum_enabled): + self._do_increment_and_send_with_checksum(command_to_send) + else: + self._do_send_without_checksum(command_to_send) + + # trigger "sent" phase and use up one "ok" + 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 + # require ack's for unknown commands + use_up_clear = self.flavor.unknown_requires_ack + if gcode is not None and not gcode.unknown: + use_up_clear = True + + if use_up_clear: + # if we need to use up a clear, do that now + self._clear_to_send.clear() + else: + # Otherwise we need to tickle the read queue - there might not be a reply + # to this command, so our _monitor loop will stay waiting until timeout. We + # definitely do not want that, so we tickle the queue manually here + self._continue_sending() + + finally: + # no matter _how_ we exit this block, we signal that we + # are done processing the last fetched queue entry + self._send_queue.task_done() + + # now we just wait for the next clear and then start again + self._clear_to_send.wait() + except: + self._logger.exception("Caught an exception in the send loop") + self._log("Closing down send loop") + + def _process_command_phase(self, phase, command, command_type=None, gcode=None): + if phase not in ("queuing", "queued", "sending", "sent"): + return command, command_type, gcode + + if gcode is None: + gcode = GcodeCommand.from_line(command) + + # send it through the phase specific handlers provided by plugins + for name, hook in self._gcode_hooks[phase].items(): + try: + hook_result = hook(self, phase, command, command_type, gcode.command) + except: + self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals())) + else: + command, command_type, gcode = self._handle_command_handler_result(command, command_type, gcode.command, hook_result) + if command is None: + # hook handler return None as command, so we'll stop here and return a full out None result + return None, None, None + + # if it's a gcode command send it through the specific handler if it exists + if gcode is not None: + gcode_handler = "_gcode_" + gcode.command + "_" + phase + if hasattr(self, gcode_handler): + handler_result = getattr(self, gcode_handler)(command, cmd_type=command_type) + command, command_type, gcode = self._handle_command_handler_result(command, command_type, gcode, handler_result) + + # send it through the phase specific command handler if it exists + command_phase_handler = "_command_phase_" + phase + if hasattr(self, command_phase_handler): + handler_result = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode) + command, command_type, gcode = self._handle_command_handler_result(command, command_type, gcode, handler_result) + + # finally return whatever we resulted on + return command, command_type, gcode + + def _handle_command_handler_result(self, command, command_type, gcode, handler_result): + original_tuple = (command, command_type, gcode) + + if handler_result is None: + # handler didn't return anything, we'll just continue + return original_tuple + + if isinstance(handler_result, basestring): + # handler did return just a string, we'll turn that into a 1-tuple now + handler_result = (handler_result,) + elif not isinstance(handler_result, (tuple, list)): + # handler didn't return an expected result format, we'll just ignore it and continue + return original_tuple + + hook_result_length = len(handler_result) + if hook_result_length == 1: + # handler returned just the command + command, = handler_result + elif hook_result_length == 2: + # handler returned command and command_type + command, command_type = handler_result + else: + # handler returned a tuple of an unexpected length + return original_tuple + + gcode = GcodeCommand.from_line(command) + return command, command_type, gcode + + ##~~ actual sending via serial + + def _do_increment_and_send_with_checksum(self, cmd): + with self._line_mutex: + linenumber = self._current_linenumber + self._addToLastLines(cmd) + self._current_linenumber += 1 + self._do_send_with_checksum(cmd, linenumber) + + def _do_send_with_checksum(self, cmd, lineNumber): + command_to_send = "N%d %s" % (lineNumber, cmd) + checksum = reduce(lambda x,y:x^y, map(ord, command_to_send)) + command_to_send = "%s*%d" % (command_to_send, checksum) + self._do_send_without_checksum(command_to_send) + + def _do_send_without_checksum(self, data): + self._transport.write(data + b"\n") + + def _add_to_last_line(self, command): + self._last_lines.append(command) + + def _on_comm_ok(self): + self._clear_to_send.set() + + def _on_comm_wait(self): + print("!!! wait") + + def _on_comm_resend(self): + print("!!! resend") + + def _on_comm_start(self): + print("!!! start") + + def _on_message_sd_init_ok(self): + self._internal_state["sd_available"] = True + self.list_files() + + def _on_message_sd_init_fail(self): + self._internal_state["sd_available"] = False + + def _on_message_sd_begin_file_list(self): + self._internal_state["sd_files_temp"] = [] + + 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"]) + + def _on_message_sd_entry(self, name, size): + self._internal_state["sd_files_temp"].append((name, size)) + +class GcodeCommand(object): + + known_float_attributes = ("x", "y", "z", "e", "s", "p", "r") + known_int_attributes = ("f", "t", "n") + known_attributes = known_float_attributes + known_int_attributes + + command_regex = re.compile("^\s*((?P[GM](?P\d+))|(?PT(?P\d+))|(?PF(?P\d+)))") + + argument_pattern = "\s*([{float_args}]{float}|[{int_args}]{int})".format(float_args="".join(map(lambda x: x.upper(), known_float_attributes)), + int_args="".join(map(lambda x: x.upper(), known_int_attributes)), + float=regex_float_pattern, + int=regex_int_pattern) + argument_regex = re.compile(argument_pattern) + param_regex = re.compile("^[GMT]\d+\s+(.*?)$") + + @staticmethod + def from_line(line): + """ + >>> gcode = GcodeCommand.from_line("M30 some_file.gco") + >>> gcode.command + 'M30' + >>> gcode.param + 'some_file.gco' + >>> gcode = GcodeCommand.from_line("G28 X0 Y0") + >>> gcode.command + 'G28' + >>> gcode.x + 0.0 + >>> gcode.y + 0.0 + >>> gcode = GcodeCommand.from_line("M104 S220.0 T1") + >>> gcode.command + 'M104' + >>> gcode.s + 220.0 + >>> gcode.t + 1 + """ + + line = line.strip() + command = "" + args = {"original": line} + match = GcodeCommand.command_regex.match(line) + if match is None: + args["unknown"] = True + else: + if match.group("GM"): + command = match.group("GM") + + matched_args = GcodeCommand.argument_regex.findall(line) + if not matched_args: + param_match = GcodeCommand.param_regex.match(line) + if param_match is not None: + args["param"] = param_match.group(1) + else: + for arg in matched_args: + key = arg[0].lower() + if key in GcodeCommand.known_int_attributes: + value = int(arg[1:]) + elif key in GcodeCommand.known_float_attributes: + value = float(arg[1:]) + else: + value = str(arg[1:]) + args[key] = value + elif match.group("T"): + command = "T" + args["tool"] = match.group("tool") + elif match.group("F"): + command = "F" + args["f"] = match.group("feedrate") + + return GcodeCommand(command, **args) + + def __init__(self, command, **kwargs): + self.command = command + self.x = None + self.y = None + self.z = None + self.e = None + self.s = None + self.p = None + self.r = None + self.f = None + self.t = None + self.n = None + + self.tool = None + self.original = None + self.param = None + + self.progress = None + self.callback = None + + self.unknown = False + + for key, value in kwargs.iteritems(): + if key in GcodeCommand.known_attributes + ("tool", "original", "param", "progress", "callback", "unknown"): + self.__setattr__(key, value) + + def __repr__(self): + return "GcodeCommand(\"{str}\",progress={progress})".format(str=str(self), progress=self.progress) + + def __str__(self): + if self.original is not None: + return self.original + else: + attr = [] + for key in GcodeCommand.known_attributes: + value = self.__getattribute__(key) + if value is not None: + if key in GcodeCommand.known_int_attributes: + attr.append("%s%d" % (key.upper(), value)) + elif key in GcodeCommand.known_float_attributes: + attr.append("%s%f" % (key.upper(), value)) + else: + attr.append("%s%r" % (key.upper(), value)) + 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 = [] + + 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) + + queue.Queue._put(self, item) + + def _get(self): + item = queue.Queue._get(self) + + 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) + + return item + + +class TypeAlreadyInQueue(Exception): + def __init__(self, t, *args, **kwargs): + Exception.__init__(self, *args, **kwargs) + self.type = t + + +def strip_comment(line): + if not ";" in line: + # shortcut + return line + + escaped = False + result = [] + for c in line: + if c == ";" and not escaped: + break + result += c + 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 + + +""" +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 + + def virtual_serial_factory(): + return VirtualPrinter(virtual_sd="C:/Users/gina/AppData/Roaming/OctoPrint/virtualSd") + + class CustomProtocolListener(object): + + def on_protocol_sd_file_list(self, 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) + ) + ) + protocol = ReprapGcodeProtocol(ReprapGcodeFlavor) + transport.register_listener(protocol) + protocol.register_listener(CustomProtocolListener()) + + transport.connect() + protocol.connect(transport) +""" + +if __name__ == "__main__": + gcode = GcodeCommand.from_line("M104 S220.4 T2") diff --git a/src/octoprint/comm/protocol/reprap/flavors/__init__.py b/src/octoprint/comm/protocol/reprap/flavors/__init__.py new file mode 100644 index 000000000..95c5fb8be --- /dev/null +++ b/src/octoprint/comm/protocol/reprap/flavors/__init__.py @@ -0,0 +1,237 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__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" + + +import re + +from octoprint.comm.protocol.reprap import GcodeCommand, regex_positive_float_pattern + + +class ReprapGcodeFlavor(object): + + key = "generic" + + unknown_requires_ack = False + unknown_with_checksum = False + + always_send_checksum = False + never_send_checksum = False + + checksum_requiring_commands = ["M110"] + long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M400", "M226"] + + regex_temp = re.compile("(?PB|T(?P\d*)):\s*(?P%s)(\s*\/?\s*(?P%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern)) + """Regex matching temperature entries in line. + + Groups will be as follows: + + * ``tool``: whole tool designator, incl. optional ``toolnum`` (str) + * ``toolnum``: tool number, if provided (int) + * ``actual``: actual temperature (float) + * ``target``: target temperature, if provided (float) + """ + + regex_sd_file_opened = re.compile("File opened:\s*(?P.*?)(\s+Size:\s*(?P[0-9]+))?") + + ##~~ Message matchers + + @classmethod + def comm_ok(cls, line, lower_line, state): + return lower_line.startswith("ok") + + @classmethod + def comm_start(cls, line, lower_line, state): + return lower_line.startswith("start") + + @classmethod + def comm_wait(cls, line, lower_line, state): + return lower_line.startswith("wait") + + @classmethod + def comm_resend(cls, line, lower_line, state): + return lower_line.startswith("resend") or lower_line.startswith("rs") + + @classmethod + def comm_error(cls, line, lower_line, state): + return line.startswith("Error:") or line.startswith("!!") + + @classmethod + def comm_error_multiline(cls, line, lower_line, state): + return False + + @classmethod + def comm_error_communication(cls, line, lower_line, state): + return False + + @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:") + + @classmethod + def message_sd_init_ok(cls, line, lower_line, state): + return "sd card ok" in lower_line + + @classmethod + def message_sd_init_fail(cls, line, lower_line, state): + return "sd init fail" in lower_line or "volume.init failed" in lower_line or "openroot failed" in lower_line + + @classmethod + def message_sd_file_opened(cls, line, lower_line, state): + return lower_line.startswith("file opened") + + @classmethod + def message_sd_file_selected(cls, line, lower_line, state): + return lower_line.startswith("file selected") + + @classmethod + def message_sd_begin_file_list(cls, line, lower_line, state): + return lower_line.startswith("begin file list") + + @classmethod + def message_sd_end_file_list(cls, line, lower_line, state): + return lower_line.startswith("end file list") + + @classmethod + def message_sd_printing_byte(cls, line, lower_line, state): + return "sd printing byte" in lower_line + + @classmethod + def message_sd_not_printing(cls, line, lower_line, state): + return "no sd printing" in lower_line + + @classmethod + def message_sd_done_printing(cls, line, lower_line, state): + return "done printing file" in lower_line + + @classmethod + def message_sd_begin_writing(cls, line, lower_line, state): + return "writing to file" in lower_line + + @classmethod + def message_sd_end_writing(cls, line, lower_line, state): + return "done saving file" in lower_line + + @classmethod + def message_sd_entry(cls, line, lower_line, state): + return state["sd_files_temp"] is not None + + ##~~ Message parsers + + @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]) + return dict(linenumber=line_to_resend) + + @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")) + + @classmethod + def parse_message_sd_entry(cls, line, lower_line, state): + name, size = line.split(" ", 2) + return dict(name=name, size=int(size)) + + ##~~ Commands + + @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) + + @classmethod + def command_set_relative_positioning(cls): + return GcodeCommand("G91") + + @classmethod + def command_set_absolute_positioning(cls): + return GcodeCommand("G90") + + @classmethod + def command_move(cls, x=None, y=None, z=None, e=None, f=None): + return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f) + + @classmethod + def command_extrude(cls, e=None, f=None): + return cls.command_move(e=e, f=f) + + @classmethod + def command_home(cls, x=False, y=False, z=False): + return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None) + + @classmethod + def set_tool(cls, tool): + return GcodeCommand("T{}".format(tool)) + + @classmethod + def set_feedrate_multiplier(cls, multiplier): + return GcodeCommand("M220", s=multiplier) + + @classmethod + def set_extrusion_multiplier(cls, multiplier): + return GcodeCommand("M221", s=multiplier) + + @classmethod + def set_fan_speed(cls, speed): + return GcodeCommand("M106", s=speed) + + @classmethod + def set_motors(cls, enable): + return GcodeCommand("M17") if enable else GcodeCommand("M18") + + @classmethod + def command_sd_refresh(cls): + return GcodeCommand("M20") + + @classmethod + def command_sd_init(cls): + return GcodeCommand("M21") + + @classmethod + def command_sd_release(cls): + return GcodeCommand("M22") + + @classmethod + def command_sd_select_file(cls, name): + return GcodeCommand("M23", param=name) + + def command_sd_start(cls): + return GcodeCommand("M24") + + def command_sd_pause(cls): + return GcodeCommand("M25") + + def command_sd_set_pos(cls, pos): + return GcodeCommand("M26", s=pos) + + def command_sd_status(cls): + return GcodeCommand("M27") + + def command_sd_begin_write(cls, name): + return GcodeCommand("M28", param=name) + + def command_sd_end_write(cls): + return GcodeCommand("M29") + + def command_sd_delete(cls, name): + return GcodeCommand("M30", param=name) diff --git a/src/octoprint/comm/protocol/reprap/flavors/repetier.py b/src/octoprint/comm/protocol/reprap/flavors/repetier.py new file mode 100644 index 000000000..6be5a217e --- /dev/null +++ b/src/octoprint/comm/protocol/reprap/flavors/repetier.py @@ -0,0 +1,13 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__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.reprap.flavors import ReprapGcodeFlavor + +class RepetierFlavor(ReprapGcodeFlavor): + + always_send_checksum = True diff --git a/src/octoprint/comm/protocol/reprap/virtual.py b/src/octoprint/comm/protocol/reprap/virtual.py new file mode 100644 index 000000000..9387dc213 --- /dev/null +++ b/src/octoprint/comm/protocol/reprap/virtual.py @@ -0,0 +1,880 @@ +# coding=utf-8 +from __future__ import absolute_import +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' + + +import time +import os +import re +import threading +import math +import Queue + +from serial import SerialTimeoutException + +class VirtualPrinter(object): + command_regex = re.compile("^([GMTF])(\d+)") + sleep_regex = re.compile("sleep (\d+)") + sleep_after_regex = re.compile("sleep_after ([GMTF]\d+) (\d+)") + sleep_after_next_regex = re.compile("sleep_after_next ([GMTF]\d+) (\d+)") + custom_action_regex = re.compile("action_custom ([a-zA-Z0-9_]+)(\s+.*)?") + + def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0, rx_buffer=64, command_buffer=4, extruders=1, + speeds=dict(x=6000, y=6000, z=300, e=200), wait=None, ok_before=False, support_m112=True, support_f=True, + echo_m117=True, virtual_sd=None, throttle=0.1, ok_with_lineno=False, force_checksums=False, repetier_resends=False): + import logging + self._logger = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter") + + self._seriallog = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter.serial") + self._seriallog.setLevel(logging.CRITICAL) + self._seriallog.propagate = False + + if seriallog_handler is not None: + import logging.handlers + self._seriallog.addHandler(seriallog_handler) + self._seriallog.setLevel(logging.INFO) + + self._seriallog.info("-"*78) + + self._read_timeout = read_timeout + self._write_timeout = write_timeout + self._throttle = throttle + self._ok_with_lineno = ok_with_lineno + + self._force_checksums = force_checksums + self._repetier_resends = repetier_resends + self._extruders = extruders + + self.incoming = CharCountingQueue(rx_buffer, name="RxBuffer") + self.outgoing = Queue.Queue() + self.buffered = Queue.Queue(maxsize=command_buffer) + + for item in ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok']: + self._send(item) + + self.currentExtruder = 0 + self.temp = [0.0] * extruders + self.targetTemp = [0.0] * extruders + self.lastTempAt = time.time() + self.bedTemp = 1.0 + self.bedTargetTemp = 1.0 + self.speeds = speeds + + self._relative = True + self._lastX = None + self._lastY = None + self._lastZ = None + self._lastE = None + + self._unitModifier = 1 + + self._virtualSd = virtual_sd + self._sdCardReady = True + self._sdPrinter = None + self._sdPrintingSemaphore = threading.Event() + self._selectedSdFile = None + self._selectedSdFileSize = None + self._selectedSdFilePos = None + self._writingToSd = False + self._newSdFilePos = None + self._heatupThread = None + + self._okBeforeCommandOutput = ok_before + self._supportM112 = support_m112 + self._supportF = support_f + + self._sendWait = bool(wait) + self._waitInterval = wait if wait else 1.0 + + self._echoOnM117 = echo_m117 + + self.currentLine = 0 + self.lastN = 0 + + self._incoming_lock = threading.RLock() + + self._sleepAfterNext = dict() + self._sleepAfter = dict() + + self._dont_answer = False + + self._debug_drop_connection = False + + #self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action") + + self._killed = False + + readThread = threading.Thread(target=self._processIncoming) + readThread.start() + + bufferThread = threading.Thread(target=self._processBuffer) + bufferThread.start() + + def __str__(self): + return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})"\ + .format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options="...") + + def _clearQueue(self, queue): + try: + while queue.get(block=False): + continue + except Queue.Empty: + pass + + def _processIncoming(self): + next_wait_timeout = time.time() + self._waitInterval + while self.incoming is not None and not self._killed: + self._simulateTemps() + + try: + data = self.incoming.get(timeout=0.01) + except Queue.Empty: + if self._sendWait and time.time() > next_wait_timeout: + self._send("wait") + next_wait_timeout = time.time() + self._waitInterval + continue + + next_wait_timeout = time.time() + self._waitInterval + + if data is None: + continue + + if self._dont_answer: + self._dont_answer = False + continue + + data = data.strip() + + # strip checksum + if "*" in data: + data = data[:data.rfind("*")] + self.currentLine += 1 + elif self._force_checksums: + self._send("Error: Missing checksum") + continue + + # track N = N + 1 + if data.startswith("N") and "M110" in data: + linenumber = int(re.search("N([0-9]+)", data).group(1)) + self.lastN = linenumber + self.currentLine = linenumber + self._sendOk() + continue + elif data.startswith("N"): + linenumber = int(re.search("N([0-9]+)", data).group(1)) + expected = self.lastN + 1 + if linenumber != expected: + self._triggerResend(actual=linenumber) + continue + elif self.currentLine == 101: + # simulate a resend at line 100 + self._triggerResend(expected=100) + continue + else: + self.lastN = linenumber + data = data.split(None, 1)[1].strip() + + data += "\n" + + # shortcut for writing to SD + if self._writingToSd and not self._selectedSdFile is None and not "M29" in data: + with open(self._selectedSdFile, "a") as f: + f.write(data) + self._sendOk() + continue + + if data.strip() == "version": + from octoprint._version import get_versions + self._send("OctoPrint VirtualPrinter v" + get_versions()["version"]) + continue + elif data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG": + debug_command = "" + if data.startswith("!!DEBUG:"): + debug_command = data[len("!!DEBUG:"):].strip() + self._debugTrigger(debug_command) + continue + + # if we are sending oks before command output, send it now + if len(data.strip()) > 0 and self._okBeforeCommandOutput: + self._sendOk() + + # actual command handling + command_match = VirtualPrinter.command_regex.match(data) + if command_match is not None: + command = command_match.group(0) + letter = command_match.group(1) + + try: + # if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first + letter_handler = "_gcode_{}".format(letter) + if hasattr(self, letter_handler): + code = command_match.group(2) + handled = getattr(self, letter_handler)(code, data) + if handled: + continue + + # then look for a method _gcode_ and execute that if it exists + command_handler = "_gcode_{}".format(command) + if hasattr(self, command_handler): + handled = getattr(self, command_handler)(data) + if handled: + continue + + finally: + # make sure that the debug sleepAfter and sleepAfterNext stuff works even + # if we continued above + if len(self._sleepAfter) or len(self._sleepAfterNext): + interval = None + if command in self._sleepAfter: + interval = self._sleepAfter[command] + elif command in self._sleepAfterNext: + interval = self._sleepAfterNext[command] + del self._sleepAfterNext[command] + + if interval is not None: + self._send("// sleeping for {interval} seconds".format(interval=interval)) + time.sleep(interval) + + # if we are sending oks after command output, send it now + if len(data.strip()) > 0 and not self._okBeforeCommandOutput: + self._sendOk() + + ##~~ command implementations + + def _gcode_T(self, code, data): + self.currentExtruder = int(code) + self._send("Active Extruder: %d" % self.currentExtruder) + + def _gcode_F(self, code, data): + if self._supportF: + self._send("echo:changed F value") + return False + else: + self._send("Error: Unknown command F") + return True + + def _gcode_M104(self, data): + self._parseHotendCommand(data) + _gcode_M109 = _gcode_M104 + + def _gcode_M140(self, data): + self._parseBedCommand(data) + _gcode_M190 = _gcode_M140 + + def _gcode_M105(self, data): + self._processTemperatureQuery() + return True + + def _gcode_M20(self, data): + if self._sdCardReady: + self._listSd() + + def _gcode_M21(self, data): + self._sdCardReady = True + self._send("SD card ok") + + def _gcode_M22(self, data): + self._sdCardReady = False + + def _gcode_M23(self, data): + if self._sdCardReady: + filename = data.split(None, 1)[1].strip() + self._selectSdFile(filename) + + def _gcode_M24(self, data): + if self._sdCardReady: + self._startSdPrint() + + def _gcode_M25(self, data): + if self._sdCardReady: + self._pauseSdPrint() + + def _gcode_M26(self, data): + if self._sdCardReady: + pos = int(re.search("S([0-9]+)", data).group(1)) + self._setSdPos(pos) + + def _gcode_M27(self, data): + if self._sdCardReady: + self._reportSdStatus() + + def _gcode_M28(self, data): + if self._sdCardReady: + filename = data.split(None, 1)[1].strip() + self._writeSdFile(filename) + + def _gcode_M29(self, data): + if self._sdCardReady: + self._finishSdFile() + + def _gcode_M30(self, data): + if self._sdCardReady: + filename = data.split(None, 1)[1].strip() + self._deleteSdFile(filename) + + def _gcode_M114(self, data): + output = "C: X:{} Y:{} Z:{} E:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE) + if not self._okBeforeCommandOutput: + output = "ok " + output + self._send(output) + return True + + def _gcode_M117(self, data): + # we'll just use this to echo a message, to allow playing around with pause triggers + if self._echoOnM117: + self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1)) + + def _gcode_M400(self, data): + self.buffered.join() + + def _gcode_M999(self, data): + # mirror Marlin behaviour + self._send("Resend: 1") + + def _gcode_G20(self, data): + self._unitModifier = 1.0 / 2.54 + if self._lastX is not None: + self._lastX *= 2.54 + if self._lastY is not None: + self._lastY *= 2.54 + if self._lastZ is not None: + self._lastZ *= 2.54 + if self._lastE is not None: + self._lastE *= 2.54 + + def _gcode_G21(self, data): + self._unitModifier = 1.0 + if self._lastX is not None: + self._lastX /= 2.54 + if self._lastY is not None: + self._lastY /= 2.54 + if self._lastZ is not None: + self._lastZ /= 2.54 + if self._lastE is not None: + self._lastE /= 2.54 + + def _gcode_G90(self, data): + self._relative = False + + def _gcode_G91(self, data): + self._relative = True + + def _gcode_G92(self, data): + self._setPosition(data) + + def _gcode_G28(self, data): + self._performMove(data) + + def _gcode_G0(self, data): + # simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves + self.buffered.put(data) + _gcode_G1 = _gcode_G0 + _gcode_G2 = _gcode_G0 + _gcode_G3 = _gcode_G0 + + ##~~ further helpers + + def _kill(self): + if not self._supportM112: + return + self._killed = True + self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.") + + def _triggerResend(self, expected=None, actual=None): + with self._incoming_lock: + if expected is None: + expected = self.lastN + 1 + else: + self.lastN = expected - 1 + + if actual is None: + self._send("Error: Wrong checksum") + else: + self._send("Error: expected line %d got %d" % (expected, actual)) + + def request_resend(): + self._send("Resend:%d" % expected) + self._send("ok") + + if self._repetier_resends: + request_resend() + request_resend() + + def _debugTrigger(self, data): + if data == "" or data == "help" or data == "?": + usage = """ + OctoPrint Virtual Printer debug commands + + help + ? + | This help. + + # Action Triggers + + action_pause + | Sends a "// action:pause" action trigger to the host. + action_resume + | Sends a "// action:resume" action trigger to the host. + action_disconnect + | Sends a "// action:disconnect" action trigger to the + | host. + action_custom [ ] + | Sends a custom "// action: " + | action trigger to the host. + + # Communication Errors + + dont_answer + | Will not acknowledge the next command. + trigger_resend_lineno + | Triggers a resend error with a line number mismatch + trigger_resend_checksum + | Triggers a resend error with a checksum mismatch + drop_connection + | Drops the serial connection + + # Reply Timing / Sleeping + + sleep + | Sleep s + sleep_after + | Sleeps s after each execution of + sleep_after_next + | Sleeps s after execution of + """ + for line in usage.split("\n"): + self._send("echo: {}".format(line.strip())) + elif data == "action_pause": + self._send("// action:pause") + elif data == "action_resume": + self._send("// action:resume") + elif data == "action_disconnect": + self._send("// action:disconnect") + elif data == "dont_answer": + self._dont_answer = True + elif data == "trigger_resend_lineno": + self._triggerResend(expected=self.lastN, actual=self.lastN+1) + elif data == "trigger_resend_checksum": + self._triggerResend(expected=self.lastN) + elif data == "drop_connection": + self._debug_drop_connection = True + else: + try: + sleep_match = VirtualPrinter.sleep_regex.match(data) + sleep_after_match = VirtualPrinter.sleep_after_regex.match(data) + sleep_after_next_match = VirtualPrinter.sleep_after_next_regex.match(data) + custom_action_match = VirtualPrinter.custom_action_regex.match(data) + + if sleep_match is not None: + interval = int(sleep_match.group(1)) + self._send("// sleeping for {interval} seconds".format(interval=interval)) + time.sleep(interval) + elif sleep_after_match is not None: + command = sleep_after_match.group(1) + interval = int(sleep_after_match.group(2)) + self._sleepAfter[command] = interval + self._send("// going to sleep {interval} seconds after each {command}".format(**locals())) + elif sleep_after_next_match is not None: + command = sleep_after_next_match.group(1) + interval = int(sleep_after_next_match.group(2)) + self._sleepAfterNext[command] = interval + self._send("// going to sleep {interval} seconds after next {command}".format(**locals())) + elif custom_action_match is not None: + action = custom_action_match.group(1) + params = custom_action_match.group(2) + params = params.strip() if params is not None else "" + self._send("// action:{action} {params}".format(**locals()).strip()) + except: + pass + + def _listSd(self): + self._send("Begin file list") + items = map( + lambda x: "%s %d" % (x.upper(), os.stat(os.path.join(self._virtualSd, x)).st_size), + os.listdir(self._virtualSd) + ) + for item in items: + self._send(item) + self._send("End file list") + + def _selectSdFile(self, filename): + if filename.startswith("/"): + filename = filename[1:] + file = os.path.join(self._virtualSd, filename.lower()) + if not os.path.exists(file) or not os.path.isfile(file): + self._send("open failed, File: %s." % filename) + else: + self._selectedSdFile = file + self._selectedSdFileSize = os.stat(file).st_size + self._send("File opened: %s Size: %d" % (filename, self._selectedSdFileSize)) + self._send("File selected") + + def _startSdPrint(self): + if self._selectedSdFile is not None: + if self._sdPrinter is None: + self._sdPrinter = threading.Thread(target=self._sdPrintingWorker) + self._sdPrinter.start() + self._sdPrintingSemaphore.set() + + def _pauseSdPrint(self): + self._sdPrintingSemaphore.clear() + + def _setSdPos(self, pos): + self._newSdFilePos = pos + + def _reportSdStatus(self): + if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set: + self._send("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize)) + else: + self._send("Not SD printing") + + def _processTemperatureQuery(self): + includeTarget = True + includeOk = not self._okBeforeCommandOutput + + # send simulated temperature data + if self._extruders > 1: + allTemps = [] + for i in range(len(self.temp)): + allTemps.append((i, self.temp[i], self.targetTemp[i])) + allTempsString = " ".join(map(lambda x: "T%d:%.2f /%.2f" % x if includeTarget else "T%d:%.2f" % (x[0], x[1]), allTemps)) + + if includeTarget: + allTempsString = "B:%.2f /%.2f %s" % (self.bedTemp, self.bedTargetTemp, allTempsString) + else: + allTempsString = "B:%.2f %s" % (self.bedTemp, allTempsString) + + output = "%s @:64\n" % allTempsString + else: + output = "T:%.2f /%.2f B:%.2f /%.2f @:64\n" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp) + + if includeOk: + output = "ok " + output + self._send(output) + + def _parseHotendCommand(self, line): + tool = 0 + toolMatch = re.search('T([0-9]+)', line) + if toolMatch: + try: + tool = int(toolMatch.group(1)) + except: + pass + + if tool >= self._extruders: + return + + try: + self.targetTemp[tool] = float(re.search('S([0-9]+)', line).group(1)) + except: + pass + + if "M109" in line: + self._waitForHeatup("tool%d" % tool) + + def _parseBedCommand(self, line): + try: + self.bedTargetTemp = float(re.search('S([0-9]+)', line).group(1)) + except: + pass + + if "M190" in line: + self._waitForHeatup("bed") + + def _performMove(self, line): + matchX = re.search("X([0-9.]+)", line) + matchY = re.search("Y([0-9.]+)", line) + matchZ = re.search("Z([0-9.]+)", line) + matchE = re.search("E([0-9.]+)", line) + + duration = 0 + if matchX is not None: + try: + x = float(matchX.group(1)) + if self._relative or self._lastX is None: + duration = max(duration, x * self._unitModifier / float(self.speeds["x"]) * 60.0) + else: + duration = max(duration, (x - self._lastX) * self._unitModifier / float(self.speeds["x"]) * 60.0) + self._lastX = x + except: + pass + if matchY is not None: + try: + y = float(matchY.group(1)) + if self._relative or self._lastY is None: + duration = max(duration, y * self._unitModifier / float(self.speeds["y"]) * 60.0) + else: + duration = max(duration, (y - self._lastY) * self._unitModifier / float(self.speeds["y"]) * 60.0) + self._lastY = y + except: + pass + if matchZ is not None: + try: + z = float(matchZ.group(1)) + if self._relative or self._lastZ is None: + duration = max(duration, z * self._unitModifier / float(self.speeds["z"]) * 60.0) + else: + duration = max(duration, (z - self._lastZ) * self._unitModifier / float(self.speeds["z"]) * 60.0) + self._lastZ = z + except: + pass + if matchE is not None: + try: + e = float(matchE.group(1)) + if self._relative or self._lastE is None: + duration = max(duration, e * self._unitModifier / float(self.speeds["e"]) * 60.0) + else: + duration = max(duration, (e - self._lastE) * self._unitModifier / float(self.speeds["e"]) * 60.0) + self._lastE = e + except: + pass + + if duration: + slept = 0 + while duration - slept > self._read_timeout and not self._killed: + time.sleep(self._read_timeout) + slept += self._read_timeout + + def _setPosition(self, line): + matchX = re.search("X([0-9.]+)", line) + matchY = re.search("Y([0-9.]+)", line) + matchZ = re.search("Z([0-9.]+)", line) + matchE = re.search("E([0-9.]+)", line) + + if matchX is None and matchY is None and matchZ is None and matchE is None: + self._lastX = self._lastY = self._lastZ = self._lastE = 0 + else: + if matchX is not None: + try: + self._lastX = float(matchX.group(1)) + except: + pass + if matchY is not None: + try: + self._lastY = float(matchY.group(1)) + except: + pass + if matchZ is not None: + try: + self._lastZ = float(matchZ.group(1)) + except: + pass + if matchE is not None: + try: + self._lastE = float(matchE.group(1)) + except: + pass + + def _writeSdFile(self, filename): + if filename.startswith("/"): + filename = filename[1:] + file = os.path.join(self._virtualSd, filename).lower() + if os.path.exists(file): + if os.path.isfile(file): + os.remove(file) + else: + self._send("error writing to file") + + self._writingToSd = True + self._selectedSdFile = file + self._send("Writing to file: %s" % filename) + + def _finishSdFile(self): + self._writingToSd = False + self._selectedSdFile = None + + def _sdPrintingWorker(self): + self._selectedSdFilePos = 0 + with open(self._selectedSdFile, "r") as f: + for line in iter(f.readline, ""): + if self._killed: + break + + # reset position if requested by client + if self._newSdFilePos is not None: + f.seek(self._newSdFilePos) + self._newSdFilePos = None + + # read current file position + self._selectedSdFilePos = f.tell() + + # if we are paused, wait for unpausing + self._sdPrintingSemaphore.wait() + + # set target temps + if 'M104' in line or 'M109' in line: + self._parseHotendCommand(line) + if 'M140' in line or 'M190' in line: + self._parseBedCommand(line) + + time.sleep(0.1) + + self._sdPrintingSemaphore.clear() + self._selectedSdFilePos = 0 + self._sdPrinter = None + self._send("Done printing file") + + def _waitForHeatup(self, heater): + delta = 1 + delay = 1 + if heater.startswith("tool"): + toolNum = int(heater[len("tool"):]) + while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta): + self._simulateTemps(delta=delta) + self._send("T:%0.2f" % self.temp[toolNum]) + time.sleep(delay) + elif heater == "bed": + while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta): + self._simulateTemps(delta=delta) + self._send("B:%0.2f" % self.bedTemp) + time.sleep(delay) + + def _deleteSdFile(self, filename): + if filename.startswith("/"): + filename = filename[1:] + f = os.path.join(self._virtualSd, filename) + if os.path.exists(f) and os.path.isfile(f): + os.remove(f) + + def _simulateTemps(self, delta=1): + timeDiff = self.lastTempAt - time.time() + self.lastTempAt = time.time() + for i in range(len(self.temp)): + if abs(self.temp[i] - self.targetTemp[i]) > delta: + oldVal = self.temp[i] + self.temp[i] += math.copysign(timeDiff * 10, self.targetTemp[i] - self.temp[i]) + if math.copysign(1, self.targetTemp[i] - oldVal) != math.copysign(1, self.targetTemp[i] - self.temp[i]): + self.temp[i] = self.targetTemp[i] + if self.temp[i] < 0: + self.temp[i] = 0 + if abs(self.bedTemp - self.bedTargetTemp) > delta: + oldVal = self.bedTemp + self.bedTemp += math.copysign(timeDiff * 10, self.bedTargetTemp - self.bedTemp) + if math.copysign(1, self.bedTargetTemp - oldVal) != math.copysign(1, self.bedTargetTemp - self.bedTemp): + self.bedTemp = self.bedTargetTemp + if self.bedTemp < 0: + self.bedTemp = 0 + + def _processBuffer(self): + while self.buffered is not None: + try: + line = self.buffered.get(timeout=0.5) + except Queue.Empty: + continue + + if line is None: + continue + + self._performMove(line) + self.buffered.task_done() + + def write(self, data): + if self._debug_drop_connection: + self._logger.info("Debug drop of connection requested, raising SerialTimeoutException") + raise SerialTimeoutException() + + with self._incoming_lock: + if self.incoming is None or self.outgoing is None: + return + + if "M112" in data and self._supportM112: + self._seriallog.info("<<< {}".format(data.strip())) + self._kill() + return + + try: + self.incoming.put(data, timeout=self._write_timeout) + self._seriallog.info("<<< {}".format(data.strip())) + except Queue.Full: + self._logger.info("Incoming queue is full, raising SerialTimeoutException") + raise SerialTimeoutException() + + def read(self, size=None): + if self._debug_drop_connection: + raise SerialTimeoutException() + + try: + line = self.outgoing.get(timeout=self._read_timeout) + "\n" + time.sleep(self._throttle) + self._seriallog.info(">>> {}".format(line.strip())) + return line + except Queue.Empty: + return "" + + def readline(self): + return self.read() + + def close(self): + self.incoming = None + self.outgoing = None + self.buffered = None + + def _sendOk(self): + if self.outgoing is None: + return + + if self._ok_with_lineno: + self._send("ok %d" % self.lastN) + else: + self._send("ok") + + def _sendWaitAfterTimeout(self, timeout=5): + time.sleep(timeout) + if self.outgoing is not None: + self._send("wait") + + def _send(self, line): + if self.outgoing is not None: + self.outgoing.put(line) + +class CharCountingQueue(Queue.Queue): + + def __init__(self, maxsize, name=None): + Queue.Queue.__init__(self, maxsize=maxsize) + self._size = 0 + self._name = name + + def put(self, item, block=True, timeout=None): + self.not_full.acquire() + try: + item_size = self._len(item) + + if not block: + if self._qsize() + item_size >= self.maxsize: + raise Queue.Full + elif timeout is None: + while self._qsize() + item_size >= self.maxsize: + self.not_full.wait() + elif timeout < 0: + raise ValueError("'timeout' must be a positive number") + else: + endtime = time.time() + timeout + while self._qsize() + item_size >= self.maxsize: + remaining = endtime - time.time() + if remaining <= 0.0: + raise Queue.Full + self.not_full.wait(remaining) + + self._put(item) + self.unfinished_tasks += 1 + self.not_empty.notify() + finally: + self.not_full.release() + + def _len(self, item): + return len(item) + + def _qsize(self, len=len): + return self._size + + # Put a new item in the queue + def _put(self, item): + self.queue.append(item) + self._size += self._len(item) + + # Get an item from the queue + def _get(self): + item = self.queue.popleft() + self._size -= self._len(item) + return item diff --git a/src/octoprint/comm/protocol/reprapgcode.py b/src/octoprint/comm/protocol/reprapgcode.py deleted file mode 100644 index d68ff3b72..000000000 --- a/src/octoprint/comm/protocol/reprapgcode.py +++ /dev/null @@ -1,287 +0,0 @@ -# coding=utf-8 -from __future__ import absolute_import - -__author__ = "Gina Häußge " -__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 . import Protocol, FileStreamingProtocolMixin, MotorControlProtocolMixin, FanControlProtocolMixin - -import re - -regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+" -regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+" -regex_int_pattern = "\d+" - -regex_float = re.compile(regex_float_pattern) -"""Regex for a float value.""" - -class ReprapGcodeProtocol(Protocol, MotorControlProtocolMixin, FanControlProtocolMixin, FileStreamingProtocolMixin): - - def __init__(self, flavor): - super(Protocol, self).__init__() - self.flavor = flavor - - self._transport = None - - def connect(self, transport): - self._transport = transport - - 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)] - - if relative: - commands = [self.flavor.command_set_relative_positioning()] + commands + [self.flavor.command_set_absolute_positioning()] - - self._send(*commands) - - def home(self, x=False, y=False, z=False): - self._send(self.flavor.command_home(x=x, y=y, z=z)) - - def set_feedrate_multiplier(self, multiplier): - self._send(self.flavor.command_set_feedrate_multiplier(multiplier)) - - def set_extrusion_multiplier(self, multiplier): - self._send(self.flavor.command.set_extrusion_multiplier(multiplier)) - - ##~~ MotorControlProtocolMixin - - def set_motors(self, enabled): - self._send(self.flavor.command.set_motors(enabled)) - - ##~~ FanControlProtocolMixin - - def set_fan_speed(self, speed): - self._send(self.flavor.command.set_fan_speed(speed)) - - ##~~ FileStreamingProtocolMixin - - def init_file_storage(self): - pass - - def list_files(self): - pass - - def start_file_print(self, name): - pass - - def pause_file_print(self): - pass - - def resume_file_print(self): - pass - - def delete_file(self, name): - pass - - def record_file(self, name, job): - pass - - def stop_recording_file(self): - pass - - def _send(self, *commands): - pass - -class ReprapGcodeFlavor(object): - - regex_temp = re.compile("(?PB|T(?P\d*)):\s*(?P%s)(\s*\/?\s*(?P%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern)) - """Regex matching temperature entries in line. - - Groups will be as follows: - - * ``tool``: whole tool designator, incl. optional ``toolnum`` (str) - * ``toolnum``: tool number, if provided (int) - * ``actual``: actual temperature (float) - * ``target``: target temperature, if provided (float) - """ - - @classmethod - def message_ok(cls, line, lower_line): - return lower_line.startswith("ok") - - @classmethod - def message_start(cls, line, lower_line): - return lower_line.startswith("start") - - @classmethod - def message_wait(cls, line, lower_line): - return lower_line.startswith("wait") - - @classmethod - def message_resend(cls, line, lower_line): - return lower_line.startswith("resend") or lower_line.startswith("rs") - - @classmethod - def message_temperature(cls, line, lower_line): - return " T:" in line or line.startswith("T:") or " T0:" in line or line.startswith("T0:") - - @classmethod - def message_error(cls, line, lower_line): - return line.startswith("Error:") or line.startswith("!!") - - @classmethod - def message_error_multiline(cls, line, lower_line): - return False - - @classmethod - def message_error_communication(cls, line, lower_line): - return False - - @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) - - @classmethod - def command_set_relative_positioning(cls): - return GcodeCommand("G91") - - @classmethod - def command_set_absolute_positioning(cls): - return GcodeCommand("G90") - - @classmethod - def command_move(cls, x=None, y=None, z=None, e=None, f=None): - return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f) - - @classmethod - def command_extrude(cls, e=None, f=None): - return cls.command_move(e=e, f=f) - - @classmethod - def command_home(cls, x=False, y=False, z=False): - return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None) - - @classmethod - def set_tool(cls, tool): - return GcodeCommand("T{}".format(tool)) - - @classmethod - def set_feedrate_multiplier(cls, multiplier): - return GcodeCommand("M220", s=multiplier) - - @classmethod - def set_extrusion_multiplier(cls, multiplier): - return GcodeCommand("M221", s=multiplier) - - @classmethod - def set_fan_speed(cls, speed): - return GcodeCommand("M106", s=speed) - - @classmethod - def set_motors(cls, enable): - return GcodeCommand("M17") if enable else GcodeCommand("M18") - - - -class GcodeCommand(object): - - known_float_attributes = ("x", "y", "z", "e", "s", "p", "r") - known_int_attributes = ("f", "t", "n") - known_attributes = known_float_attributes + known_int_attributes - - command_regex = re.compile("^\s*((?P[GM]\d+)|(?PT)\d+|(?PF)\d+)") - argument_regex = re.compile("\s+([%s][-+]?\d*\.?\d+|[%s][-+]?\d+)" % ("".join(map(lambda x: x.upper(), known_float_attributes)), "".join(map(lambda x: x.upper(), known_int_attributes)))) - param_regex = re.compile("^[GMT]\d+\s+(.*?)$") - - @staticmethod - def from_line(line): - line = line.strip() - command = "" - args = {"original": line} - match = GcodeCommand.command_regex.match(line) - if match is None: - args["unknown"] = True - else: - commandType = match.group(1) - commandNumber = int(match.group(2)) - command = "%s%d" % (commandType, commandNumber) - - - if commandType == "T": - args["tool"] = commandNumber - else: - matchedArgs = GcodeCommand.argument_regex.findall(line) - if len(matchedArgs) == 0: - paramMatch = GcodeCommand.param_regex.match(line) - if paramMatch is not None: - args["param"] = paramMatch.group(1) - else: - for arg in matchedArgs: - key = arg[0].lower() - if key in GcodeCommand.known_int_attributes: - value = int(arg[1:]) - elif key in GcodeCommand.known_float_attributes: - value = float(arg[1:]) - else: - value = str(arg[1:]) - args[key] = value - - return GcodeCommand(command, **args) - - def __init__(self, command, **kwargs): - self.command = command - self.x = None - self.y = None - self.z = None - self.e = None - self.s = None - self.p = None - self.r = None - self.f = None - self.t = None - self.n = None - - self.tool = None - self.original = None - self.param = None - - self.progress = None - self.callback = None - - self.unknown = False - - for key, value in kwargs.iteritems(): - if key in GcodeCommand.known_attributes + ("tool", "original", "param", "progress", "callback", "unknown"): - self.__setattr__(key, value) - - def isGetTemperatureCommand(self): - return self.command == "M105" - - def isSetTemperatureCommand(self): - return self.command in ("M104", "M140", "M109", "M190") - - def isSelectToolCommand(self): - return self.command.startswith("T") - - def __repr__(self): - return "GcodeCommand(\"{str}\",progress={progress})".format(str=str(self), progress=self.progress) - - def __str__(self): - if self.original is not None: - return self.original - else: - attr = [] - for key in GcodeCommand.known_attributes: - value = self.__getattribute__(key) - if value is not None: - if key in GcodeCommand.known_int_attributes: - attr.append("%s%d" % (key.upper(), value)) - elif key in GcodeCommand.known_float_attributes: - attr.append("%s%f" % (key.upper(), value)) - else: - attr.append("%s%r" % (key.upper(), value)) - attributeStr = " ".join(attr) - return "%s%s%s" % (self.command.upper(), " " + attributeStr if attributeStr else "", " " + self.param if self.param else "") diff --git a/src/octoprint/comm/transport/__init__.py b/src/octoprint/comm/transport/__init__.py index 0a3c9f882..561ad30a1 100644 --- a/src/octoprint/comm/transport/__init__.py +++ b/src/octoprint/comm/transport/__init__.py @@ -40,7 +40,7 @@ class Transport(object): class SeparatorAwareTransportWrapper(object): - def __init__(self, transport, separator="\n", chunksize=128): + def __init__(self, transport, separator, chunksize=128): self.transport = transport self.separator = separator @@ -83,12 +83,14 @@ class SeparatorAwareTransportWrapper(object): class LineAwareTransportWrapper(SeparatorAwareTransportWrapper): def __init__(self, transport, chunksize=512): - SeparatorAwareTransportWrapper.__init__(self, transport, separator="\n", chunksize=chunksize) + SeparatorAwareTransportWrapper.__init__(self, transport, b"\n", chunksize=chunksize) class PushingTransportWrapper(object): - def __init__(self, transport): + def __init__(self, transport, name="pushingTransportReceiveLoop"): self.transport = transport + self.name = name + self._listeners = set() self._receiver_active = False self._receiver_thread = None @@ -99,7 +101,7 @@ class PushingTransportWrapper(object): import threading self._receiver_active = True - self._receiver_thread = threading.Thread(target=self._receiver_loop) + self._receiver_thread = threading.Thread(target=self._receiver_loop, name=self.name) self._receiver_thread.daemon = True self._receiver_thread.start() diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index c655f9f9c..3167b9f3d 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -18,6 +18,7 @@ import threading from functools import wraps import warnings import contextlib +import collections logger = logging.getLogger(__name__) @@ -937,3 +938,51 @@ class InvariantContainer(object): def __iter__(self): return self._data.__iter__() + + +class dictview(collections.Mapping): + """ + >>> my_dict = dict(a="a", b="b", flag=True, value=23) + >>> view = dictview(my_dict) + >>> view["a"] + 'a' + >>> view["flag"] + True + >>> view["foo"] + Traceback (most recent call last): + ... + KeyError: 'foo' + >>> my_dict["foo"] = "bar" + >>> view["foo"] + 'bar' + >>> view["foo"] = "fnord" + Traceback (most recent call last): + ... + TypeError: 'dictview' object does not support item assignment + """ + + def __init__(self, data, copy=False, deepcopy=False): + self.data = data + self.copy = copy + self.deepcopy = deepcopy + + def __len__(self): + return len(self.data) + + def __iter__(self): + return iter(self.data) + + def __getitem__(self, key): + return self._get_item(key) + + def _get_item(self, key): + import copy + + value = self.data[key] + + if self.deepcopy: + value = copy.deepcopy(value) + elif self.copy: + value = copy.copy(value) + + return value