From 0c4f4383e3c3a0106fd4175206570a0551b9bf26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 21 Feb 2019 15:29:20 +0100 Subject: [PATCH 1/5] =?UTF-8?q?=E2=99=BB=20Introduce=20type=20hints?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For now we'll only use them to have our IDEs scream at us... --- setup.py | 3 +- src/octoprint/util/__init__.py | 55 +++++++++++++++++++++------------- 2 files changed, 36 insertions(+), 22 deletions(-) diff --git a/setup.py b/setup.py index 625a9f515..3bbc8570c 100644 --- a/setup.py +++ b/setup.py @@ -60,7 +60,8 @@ INSTALL_REQUIRES = [ "emoji>=0.5.1,<0.6", "monotonic>=1.5,<1.6", "frozendict>=1.2,<1.3", - "sentry-sdk==0.6.6" + "sentry-sdk==0.6.6", + "typing>=3.6.4,<4" ] if sys.platform == "darwin": diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 1f384acc2..89aca7342 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1,4 +1,4 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function """ @@ -24,15 +24,45 @@ import collections import frozendict import copy +from typing import Union + try: import queue except ImportError: import Queue as queue -from past.builtins import basestring +from past.builtins import basestring, unicode logger = logging.getLogger(__name__) + +def to_bytes(s_or_u, encoding="utf-8", errors="strict"): + # type: (Union[str, bytes], str, str) -> bytes + """Make sure ``s_or_u`` is a bytestring.""" + if isinstance(s_or_u, unicode): + return s_or_u.encode(encoding, errors=errors) + else: + return s_or_u + + +def to_unicode(s_or_u, encoding="utf-8", errors="strict"): + # type: (Union[str, bytes], str, str) -> str + """Make sure ``s_or_u`` is a unicode string.""" + if isinstance(s_or_u, bytes): + return s_or_u.decode(encoding, errors=errors) + else: + return s_or_u + + +def to_native_str(s_or_u): + # type: (Union[str, bytes]) -> Union[str, bytes] + """Make sure ``s_or_u`` is a 'str'.""" + if sys.version_info[0] == 2: + return to_bytes(s_or_u) + else: + return to_unicode(s_or_u) + + def warning_decorator_factory(warning_type): def specific_warning(message, stacklevel=1, since=None, includedoc=None, extenddoc=False): def decorator(func): @@ -100,6 +130,8 @@ Returns: function: The wrapped function with the deprecation warnings in place. """ +to_str = deprecated("to_str has been renamed to to_bytes", since="1.3.11")(to_bytes) + def get_formatted_size(num): """ Formats the given byte count as a human readable rounded size expressed in the most pressing unit among B(ytes), @@ -433,25 +465,6 @@ def filter_non_ascii(line): return True -def to_bytes(s_or_u, encoding="utf-8", errors="strict"): - """Make sure ``s_or_u`` is a bytestring.""" - if isinstance(s_or_u, unicode): - return s_or_u.encode(encoding, errors=errors) - else: - return s_or_u - -to_str = deprecated("to_str has been renamed to to_bytes", since="1.3.11")(to_bytes) - - - -def to_unicode(s_or_u, encoding="utf-8", errors="strict"): - """Make sure ``s_or_u`` is a unicode string.""" - if isinstance(s_or_u, bytes): - return s_or_u.decode(encoding, errors=errors) - else: - return s_or_u - - def chunks(l, n): """ Yield successive n-sized chunks from l. From 295b96f25949fdf0027346ffb361938f226ee0ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 21 Feb 2019 15:29:20 +0100 Subject: [PATCH 2/5] =?UTF-8?q?=F0=9F=8E=A8=20Remove=20unnecessary=20impor?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Already included in the next line --- src/octoprint/users.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/octoprint/users.py b/src/octoprint/users.py index 5316fff97..0db900213 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms # Wrapper to the new access.users location -from octoprint.access.users import User, deprecated from octoprint.access.users import * # noqa: F403 ## possibly used by other modules AccessUser = User From 1025f0be43982a55f11519a348b62296245872b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 22 Feb 2019 13:30:42 +0100 Subject: [PATCH 3/5] =?UTF-8?q?=F0=9F=92=9A=20Revert=20"=F0=9F=8E=A8=20Rem?= =?UTF-8?q?ove=20unnecessary=20import"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 295b96f25949fdf0027346ffb361938f226ee0ca. --- src/octoprint/users.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/octoprint/users.py b/src/octoprint/users.py index 0db900213..5316fff97 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms # Wrapper to the new access.users location +from octoprint.access.users import User, deprecated from octoprint.access.users import * # noqa: F403 ## possibly used by other modules AccessUser = User From 54c89230870db5089495731ccf04d28dbee4b482 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 22 Feb 2019 18:29:36 +0100 Subject: [PATCH 4/5] =?UTF-8?q?=F0=9F=90=9B=20virtual:=20fix=20some=20str/?= =?UTF-8?q?bytes=20issues?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Threw some type annotations into it while at it. Should make the IDE become angry at such problems in the future. --- .../plugins/virtual_printer/virtual.py | 194 ++++++++++++------ 1 file changed, 135 insertions(+), 59 deletions(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 3b19376c9..a9134b505 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -16,6 +16,7 @@ try: except ImportError: import Queue as queue +# noinspection PyCompatibility from past.builtins import basestring from serial import SerialTimeoutException @@ -24,17 +25,21 @@ from octoprint.settings import settings from octoprint.plugin import plugin_manager from octoprint.util import RepeatedTimer, to_bytes +from typing import Any + + +# noinspection PyBroadException class VirtualPrinter(object): - command_regex = re.compile(b"^([GMTF])(\\d+)") - sleep_regex = re.compile(b"sleep (\\d+)") - sleep_after_regex = re.compile(b"sleep_after ([GMTF]\\d+) (\\d+)") - sleep_after_next_regex = re.compile(b"sleep_after_next ([GMTF]\\d+) (\\d+)") - custom_action_regex = re.compile(b"action_custom ([a-zA-Z0-9_]+)(\\s+.*)?") - prepare_ok_regex = re.compile(b"prepare_ok (.*)") - send_regex = re.compile(b"send (.*)") - set_ambient_regex = re.compile(b"set_ambient ([-+]?[0-9]*\\.?[0-9]+)") - start_sd_regex = re.compile(b"start_sd (.*)") - select_sd_regex = re.compile(b"select_sd (.*)") + command_regex = re.compile(r"^([GMTF])(\\d+)") + sleep_regex = re.compile(r"sleep (\\d+)") + sleep_after_regex = re.compile(r"sleep_after ([GMTF]\\d+) (\\d+)") + sleep_after_next_regex = re.compile(r"sleep_after_next ([GMTF]\\d+) (\\d+)") + custom_action_regex = re.compile(r"action_custom ([a-zA-Z0-9_]+)(\\s+.*)?") + prepare_ok_regex = re.compile(r"prepare_ok (.*)") + send_regex = re.compile(r"send (.*)") + set_ambient_regex = re.compile(r"set_ambient ([-+]?[0-9]*\\.?[0-9]+)") + start_sd_regex = re.compile(r"start_sd (.*)") + select_sd_regex = re.compile(r"select_sd (.*)") def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0): import logging @@ -259,6 +264,7 @@ class VirtualPrinter(object): self._logger.debug("Setting write timeout to {}s".format(value)) self._write_timeout = value + # noinspection PyMethodMayBeStatic def _clearQueue(self, q): try: while q.get(block=False): @@ -358,6 +364,7 @@ class VirtualPrinter(object): continue elif len(self._prepared_errors): prepared = self._prepared_errors.pop(0) + # noinspection PyCompatibility if callable(prepared): prepared(linenumber, self.lastN, data) continue @@ -370,20 +377,22 @@ class VirtualPrinter(object): data += b"\n" - if data.startswith(b"!!DEBUG:") or data.strip() == b"!!DEBUG": + data = data.decode("ascii") + + if data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG": debug_command = "" - if data.startswith(b"!!DEBUG:"): - debug_command = data[len("!!DEBUG:"):].strip().decode("ascii") + if data.startswith("!!DEBUG:"): + debug_command = data[len("!!DEBUG:"):].strip() self._debugTrigger(debug_command) continue # shortcut for writing to SD - if self._writingToSd and self._writingToSdHandle is not None and not b"M29" in data: + if self._writingToSd and self._writingToSdHandle is not None and not "M29" in data: self._writingToSdHandle.write(data) self._sendOk() continue - if data.strip() == b"version": + if data.strip() == "version": from octoprint import __version__ self._send("OctoPrint VirtualPrinter v" + __version__) continue @@ -400,7 +409,7 @@ class VirtualPrinter(object): try: # if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first - letter_handler = "_gcode_{}".format(letter.decode("ascii")) + letter_handler = "_gcode_{}".format(letter) if hasattr(self, letter_handler): code = command_match.group(2) handled = getattr(self, letter_handler)(code, data) @@ -408,7 +417,7 @@ class VirtualPrinter(object): continue # then look for a method _gcode_ and execute that if it exists - command_handler = "_gcode_{}".format(command.decode("ascii")) + command_handler = "_gcode_{}".format(command) if hasattr(self, command_handler): handled = getattr(self, command_handler)(data) if handled: @@ -437,7 +446,9 @@ class VirtualPrinter(object): ##~~ command implementations + # noinspection PyUnusedLocal def _gcode_T(self, code, data): + # type: (str, str) -> None t = int(code) if 0 <= t < self.extruderCount: self.currentExtruder = t @@ -445,7 +456,9 @@ class VirtualPrinter(object): else: self._send("echo:T{} Invalid extruder ".format(t)) + # noinspection PyUnusedLocal def _gcode_F(self, code, data): + # type: (str, str) -> bool if self._supportF: self._send("echo:changed F value") return False @@ -454,56 +467,75 @@ class VirtualPrinter(object): return True def _gcode_M104(self, data): + # type: (str) -> None self._parseHotendCommand(data) def _gcode_M109(self, data): + # type: (str) -> None self._parseHotendCommand(data, wait=True, support_r=True) def _gcode_M140(self, data): + # type: (str) -> None self._parseBedCommand(data) def _gcode_M190(self, data): + # type: (str) -> None self._parseBedCommand(data, wait=True, support_r=True) + # noinspection PyUnusedLocal def _gcode_M105(self, data): + # type: (str) -> bool self._processTemperatureQuery() return True + # noinspection PyUnusedLocal def _gcode_M20(self, data): + # type: (str) -> None if self._sdCardReady: self._listSd() + # noinspection PyUnusedLocal def _gcode_M21(self, data): + # type: (str) -> None self._sdCardReady = True self._send("SD card ok") + # noinspection PyUnusedLocal def _gcode_M22(self, data): + # type: (str) -> None self._sdCardReady = False def _gcode_M23(self, data): + # type: (str) -> None if self._sdCardReady: filename = data.split(None, 1)[1].strip() self._selectSdFile(filename) + # noinspection PyUnusedLocal def _gcode_M24(self, data): + # type: (str) -> None if self._sdCardReady: self._startSdPrint() + # noinspection PyUnusedLocal def _gcode_M25(self, data): + # type: (str) -> None if self._sdCardReady: self._pauseSdPrint() def _gcode_M26(self, data): + # type: (str) -> None if self._sdCardReady: - pos = int(re.search(b"S([0-9]+)", data).group(1)) + pos = int(re.search(r"S([0-9]+)", data).group(1)) self._setSdPos(pos) def _gcode_M27(self, data): + # type: (str) -> None def report(): if self._sdCardReady: self._reportSdStatus() - match = re.search(b"S([0-9]+)", data) + match = re.search(r"S([0-9]+)", data) if match: interval = int(match.group(1)) if self._sdstatus_reporter is not None: @@ -518,25 +550,32 @@ class VirtualPrinter(object): report() def _gcode_M28(self, data): + # type: (str) -> None if self._sdCardReady: filename = data.split(None, 1)[1].strip() self._writeSdFile(filename) + # noinspection PyUnusedLocal def _gcode_M29(self, data): + # type: (str) -> None if self._sdCardReady: self._finishSdFile() def _gcode_M30(self, data): + # type: (str) -> None if self._sdCardReady: filename = data.split(None, 1)[1].strip() self._deleteSdFile(filename) def _gcode_M113(self, data): - interval = int(re.search(b"S([0-9]+)", data).group(1)) + # type: (str) -> None + interval = int(re.search(r"S([0-9]+)", data).group(1)) if 0 <= interval <= 60: self._busyInterval = interval + # noinspection PyUnusedLocal def _gcode_M114(self, data): + # type: (str) -> bool m114FormatString = settings().get(["devel", "virtualPrinter", "m114FormatString"]) e = dict((index, value) for index, value in enumerate(self._lastE)) e["current"] = self._lastE[self.currentExtruder] @@ -557,7 +596,9 @@ class VirtualPrinter(object): self._send(output) return True + # noinspection PyUnusedLocal def _gcode_M115(self, data): + # type: (str) -> None output = self._m115FormatString.format(firmware_name=self._firmwareName) self._send(output) @@ -566,12 +607,14 @@ class VirtualPrinter(object): self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0")) def _gcode_M117(self, data): + # type: (str) -> None # 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(b"M117\\s+(.*)", data).group(1)) + self._send("echo:%s" % re.search(r"M117\\s+(.*)", data).group(1)) def _gcode_M155(self, data): - interval = int(re.search(b"S([0-9]+)", data).group(1)) + # type: (str) -> None + interval = int(re.search(r"S([0-9]+)", data).group(1)) if self._temperature_reporter is not None: self._temperature_reporter.cancel() @@ -582,19 +625,27 @@ class VirtualPrinter(object): self._temperature_reporter = None def _gcode_M220(self, data): - self._feedrate_multiplier = float(re.search(b'S([0-9]+)', data).group(1)) + # type: (str) -> None + self._feedrate_multiplier = float(re.search(r'S([0-9]+)', data).group(1)) def _gcode_M221(self, data): - self._flowrate_multiplier = float(re.search(b'S([0-9]+)', data).group(1)) + # type: (str) -> None + self._flowrate_multiplier = float(re.search(r'S([0-9]+)', data).group(1)) + # noinspection PyUnusedLocal def _gcode_M400(self, data): + # type: (str) -> None self.buffered.join() + # noinspection PyUnusedLocal def _gcode_M999(self, data): + # type: (str) -> None # mirror Marlin behaviour self._send("Resend: 1") + # noinspection PyUnusedLocal def _gcode_G20(self, data): + # type: (str) -> None self._unitModifier = 1.0 / 2.54 if self._lastX is not None: self._lastX *= 2.54 @@ -605,7 +656,9 @@ class VirtualPrinter(object): if self._lastE is not None: self._lastE = [e * 2.54 if e is not None else None for e in self._lastE] + # noinspection PyUnusedLocal def _gcode_G21(self, data): + # type: (str) -> None self._unitModifier = 1.0 if self._lastX is not None: self._lastX /= 2.54 @@ -616,19 +669,26 @@ class VirtualPrinter(object): if self._lastE is not None: self._lastE = [e / 2.54 if e is not None else None for e in self._lastE] + # noinspection PyUnusedLocal def _gcode_G90(self, data): + # type: (str) -> None self._relative = False + # noinspection PyUnusedLocal def _gcode_G91(self, data): + # type: (str) -> None self._relative = True def _gcode_G92(self, data): + # type: (str) -> None self._setPosition(data) def _gcode_G28(self, data): + # type: (str) -> None self._performMove(data) def _gcode_G0(self, data): + # type: (str) -> None # simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves self.buffered.put(data) _gcode_G1 = _gcode_G0 @@ -636,8 +696,9 @@ class VirtualPrinter(object): _gcode_G3 = _gcode_G0 def _gcode_G4(self, data): - matchS = re.search(b'S([0-9]+)', data) - matchP = re.search(b'P([0-9]+)', data) + # type: (str) -> None + matchS = re.search(r'S([0-9]+)', data) + matchP = re.search(r'P([0-9]+)', data) _timeout = 0 if matchP: @@ -653,7 +714,9 @@ class VirtualPrinter(object): else: time.sleep(_timeout) + # noinspection PyUnusedLocal def _gcode_G33(self, data): + # type: (str) -> None self._send("G33 Auto Calibrate") self._send("Will take ~60s") timeout = 60 @@ -668,7 +731,9 @@ class VirtualPrinter(object): ##~~ further helpers + # noinspection PyMethodMayBeStatic def _calculate_checksum(self, line): + # type: (bytes) -> int checksum = 0 for c in bytearray(line): checksum ^= c @@ -681,6 +746,7 @@ class VirtualPrinter(object): self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.") def _triggerResend(self, expected=None, actual=None, checksum=None): + # type: (int, int, int) -> None with self._incoming_lock: if expected is None: expected = self.lastN + 1 @@ -703,6 +769,7 @@ class VirtualPrinter(object): request_resend() def _debugTrigger(self, data): + # type: (str) -> None if data == "" or data == "help" or data == "?": usage = """ OctoPrint Virtual Printer debug commands @@ -785,13 +852,13 @@ class VirtualPrinter(object): elif data == "dont_answer": self._dont_answer = True elif data == "trigger_resend_lineno": - self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, actual=last+1)) + self._prepared_errors.append(lambda cur, last, ln: self._triggerResend(expected=last, actual=last+1)) elif data == "trigger_resend_checksum": - self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, checksum=True)) + self._prepared_errors.append(lambda cur, last, ln: self._triggerResend(expected=last, checksum=True)) elif data == "trigger_missing_checksum": - self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, checksum=False)) + self._prepared_errors.append(lambda cur, last, ln: self._triggerResend(expected=last, checksum=False)) elif data == "trigger_missing_lineno": - self._prepared_errors.append(lambda cur, last, line: self._send(self._error("lineno_missing", last))) + self._prepared_errors.append(lambda cur, last, ln: self._send(self._error("lineno_missing", last))) elif data == "trigger_fatal_error_marlin": self._send("Error:Thermal Runaway, system stopped! Heater_ID: bed") self._send("Error:Printer halted. kill() called!") @@ -879,6 +946,7 @@ class VirtualPrinter(object): self._send("End file list") def _selectSdFile(self, filename, check_already_open=False): + # type: (str, bool) -> None if filename.startswith("/"): filename = filename[1:] @@ -918,6 +986,7 @@ class VirtualPrinter(object): self._send("Not SD printing") def _generateTemperatureOutput(self): + # type: () -> str includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]) # send simulated temperature data @@ -963,9 +1032,10 @@ class VirtualPrinter(object): self._send(output) def _parseHotendCommand(self, line, wait=False, support_r=False): + # type: (str, bool, bool) -> None only_wait_if_higher = True tool = 0 - toolMatch = re.search(b'T([0-9]+)', line) + toolMatch = re.search(r'T([0-9]+)', line) if toolMatch: tool = int(toolMatch.group(1)) @@ -973,11 +1043,11 @@ class VirtualPrinter(object): return try: - self.targetTemp[tool] = float(re.search(b'S([0-9]+)', line).group(1)) + self.targetTemp[tool] = float(re.search(r'S([0-9]+)', line).group(1)) except Exception: if support_r: try: - self.targetTemp[tool] = float(re.search(b'R([0-9]+)', line).group(1)) + self.targetTemp[tool] = float(re.search(r'R([0-9]+)', line).group(1)) only_wait_if_higher = False except Exception: pass @@ -988,13 +1058,14 @@ class VirtualPrinter(object): self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool])) def _parseBedCommand(self, line, wait=False, support_r=False): + # type: (str, bool, bool) -> None only_wait_if_higher = True try: - self.bedTargetTemp = float(re.search(b'S([0-9]+)', line).group(1)) + self.bedTargetTemp = float(re.search(r'S([0-9]+)', line).group(1)) except Exception: if support_r: try: - self.bedTargetTemp = float(re.search(b'R([0-9]+)', line).group(1)) + self.bedTargetTemp = float(re.search(r'R([0-9]+)', line).group(1)) only_wait_if_higher = False except Exception: pass @@ -1005,11 +1076,12 @@ class VirtualPrinter(object): self._send("TargetBed:%d" % self.bedTargetTemp) def _performMove(self, line): - matchX = re.search(b"X([0-9.]+)", line) - matchY = re.search(b"Y([0-9.]+)", line) - matchZ = re.search(b"Z([0-9.]+)", line) - matchE = re.search(b"E([0-9.]+)", line) - matchF = re.search(b"F([0-9.]+)", line) + # type: (str) -> None + matchX = re.search(r"X([0-9.]+)", line) + matchY = re.search(r"Y([0-9.]+)", line) + matchZ = re.search(r"Z([0-9.]+)", line) + matchE = re.search(r"E([0-9.]+)", line) + matchF = re.search(r"F([0-9.]+)", line) duration = 0.0 if matchF is not None: @@ -1098,10 +1170,11 @@ class VirtualPrinter(object): time.sleep(duration) def _setPosition(self, line): - matchX = re.search(b"X([0-9.]+)", line) - matchY = re.search(b"Y([0-9.]+)", line) - matchZ = re.search(b"Z([0-9.]+)", line) - matchE = re.search(b"E([0-9.]+)", line) + # type: (str) -> None + matchX = re.search(r"X([0-9.]+)", line) + matchY = re.search(r"Y([0-9.]+)", line) + matchZ = re.search(r"Z([0-9.]+)", line) + matchE = re.search(r"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[self.currentExtruder] = 0 @@ -1128,7 +1201,8 @@ class VirtualPrinter(object): pass def _writeSdFile(self, filename): - filename = filename.decode("utf-8") + # type: (str) -> None + filename = filename if filename.startswith("/"): filename = filename[1:] file = os.path.join(self._virtualSd, filename).lower() @@ -1142,7 +1216,7 @@ class VirtualPrinter(object): try: handle = io.open(file, 'wt', encoding='utf-8') except Exception: - self._output("error writing to file") + self._send("error writing to file") self._writingToSdHandle = handle self._writingToSd = True self._selectedSdFile = file @@ -1157,7 +1231,7 @@ class VirtualPrinter(object): self._writingToSdHandle = None self._writingToSd = False self._selectedSdFile = None - self._output("Done saving file") + self._send("Done saving file") def _sdPrintingWorker(self): self._selectedSdFilePos = 0 @@ -1175,7 +1249,7 @@ class VirtualPrinter(object): # read current file position self._selectedSdFilePos = f.tell() - # if we are paused, wait for unpausing + # if we are paused, wait for resuming self._sdPrintingSemaphore.wait() if self._killed or not self._sdPrinting: break @@ -1198,12 +1272,13 @@ class VirtualPrinter(object): def _finishSdPrint(self): if not self._killed: self._sdPrintingSemaphore.clear() - self._output("Done printing file") + self._send("Done printing file") self._selectedSdFilePos = 0 self._sdPrinting = False self._sdPrinter = None def _waitForHeatup(self, heater, only_wait_if_higher): + # type: (str, bool) -> None delta = 1 delay = 1 last_busy = time.time() @@ -1222,9 +1297,9 @@ class VirtualPrinter(object): while not self._killed and self._heatingUp and test(): self._simulateTemps(delta=delta) - self._output(output()) + self._send(output()) if self._sendBusy and time.time() - last_busy >= self._busyInterval: - self._output("echo:busy: processing") + self._send("echo:busy: processing") last_busy = time.time() time.sleep(delay) except AttributeError: @@ -1234,6 +1309,7 @@ class VirtualPrinter(object): self._heatingUp = False def _deleteSdFile(self, filename): + # type: (str) -> None if filename.startswith("/"): filename = filename[1:] f = os.path.join(self._virtualSd, filename) @@ -1284,14 +1360,8 @@ class VirtualPrinter(object): self._logger.info("Closing down buffer loop") - def _output(self, line): - try: - self.outgoing.put(line) - except Exception: - if self.outgoing is not None: - raise - def write(self, data): + # type: (bytes) -> int if self._debug_awol: return len(data) @@ -1317,6 +1387,7 @@ class VirtualPrinter(object): raise SerialTimeoutException() def readline(self): + # type: () -> bytes if self._debug_awol: time.sleep(self._read_timeout) return b"" @@ -1372,6 +1443,7 @@ class VirtualPrinter(object): self._send("wait") def _send(self, line): + # type: (str) -> None if self.outgoing is not None: self.outgoing.put(line) @@ -1385,8 +1457,11 @@ class VirtualPrinter(object): return ok.format(ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize()) def _error(self, error, *args, **kwargs): + # type: (str, Any, Any) -> str return "Error: {}".format(self._errors.get(error).format(*args, **kwargs)) + +# noinspection PyUnresolvedReferences class CharCountingQueue(queue.Queue): def __init__(self, maxsize, name=None): @@ -1431,10 +1506,11 @@ class CharCountingQueue(queue.Queue): finally: self.not_full.release() + # noinspection PyMethodMayBeStatic def _len(self, item): return len(item) - def _qsize(self, len=len): + def _qsize(self, l=len): return self._size # Put a new item in the queue From 058dbd0c2e978d2d2d66e0aa09c22a4dd340a01b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 22 Feb 2019 18:46:45 +0100 Subject: [PATCH 5/5] =?UTF-8?q?=F0=9F=90=9B=20virtual:=20fix=20regexes=20a?= =?UTF-8?q?gain?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/plugins/virtual_printer/virtual.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index a9134b505..50ae20429 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -30,14 +30,14 @@ from typing import Any # noinspection PyBroadException class VirtualPrinter(object): - command_regex = re.compile(r"^([GMTF])(\\d+)") - sleep_regex = re.compile(r"sleep (\\d+)") - sleep_after_regex = re.compile(r"sleep_after ([GMTF]\\d+) (\\d+)") - sleep_after_next_regex = re.compile(r"sleep_after_next ([GMTF]\\d+) (\\d+)") - custom_action_regex = re.compile(r"action_custom ([a-zA-Z0-9_]+)(\\s+.*)?") + command_regex = re.compile(r"^([GMTF])(\d+)") + sleep_regex = re.compile(r"sleep (\d+)") + sleep_after_regex = re.compile(r"sleep_after ([GMTF]\d+) (\d+)") + sleep_after_next_regex = re.compile(r"sleep_after_next ([GMTF]\d+) (\d+)") + custom_action_regex = re.compile(r"action_custom ([a-zA-Z0-9_]+)(\s+.*)?") prepare_ok_regex = re.compile(r"prepare_ok (.*)") send_regex = re.compile(r"send (.*)") - set_ambient_regex = re.compile(r"set_ambient ([-+]?[0-9]*\\.?[0-9]+)") + set_ambient_regex = re.compile(r"set_ambient ([-+]?[0-9]*\.?[0-9]+)") start_sd_regex = re.compile(r"start_sd (.*)") select_sd_regex = re.compile(r"select_sd (.*)") @@ -377,7 +377,7 @@ class VirtualPrinter(object): data += b"\n" - data = data.decode("ascii") + data = data.decode("ascii").strip() if data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG": debug_command = "" @@ -610,7 +610,7 @@ class VirtualPrinter(object): # type: (str) -> None # 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(r"M117\\s+(.*)", data).group(1)) + self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1)) def _gcode_M155(self, data): # type: (str) -> None