From a2ccf414e62e74f6330a73df3accc522131da3e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 9 Mar 2018 10:40:02 +0100 Subject: [PATCH] comm: compat fix for pyserial 2.7 vs 3.4 Closes #2468 --- src/octoprint/util/comm.py | 53 +++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index dccd65189..1e4d9f9e4 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -19,7 +19,58 @@ except ImportError: from past.builtins import basestring import logging + import serial + +# TODO 1.3.8 remove after pyserial upgrade to 3.4 +try: + serial.Timeout(0) +except AttributeError: + # pyserial < 3.2: add backported Timeout abstraction, slightly modified since we have monotonic available + + import monotonic + class _Timeout(object): + def __init__(self, duration): + """Initialize a timeout with given duration""" + self.is_infinite = (duration is None) + self.is_non_blocking = (duration == 0) + self.duration = duration + if duration is not None: + self.target_time = monotonic.monotonic() + duration + else: + self.target_time = None + + def expired(self): + """Return a boolean, telling if the timeout has expired""" + return self.target_time is not None and self.time_left() <= 0 + + def time_left(self): + """Return how many seconds are left until the timeout expires""" + if self.is_non_blocking: + return 0 + elif self.is_infinite: + return None + else: + delta = self.target_time - monotonic.monotonic() + if delta > self.duration: + # clock jumped, recalculate + self.target_time = monotonic.monotonic() + self.duration + return self.duration + else: + return max(0, delta) + + def restart(self, duration): + """\ + Restart a timeout, only supported if a timeout was already set up + before. + """ + self.duration = duration + self.target_time = monotonic.monotonic() + duration + + serial.Timeout = _Timeout + del _Timeout + + import wrapt import octoprint.plugin @@ -4187,7 +4238,7 @@ class BufferedReadlineWrapper(wrapt.ObjectProxy): while True: # make sure we always read everything that is waiting - data += bytearray(self.read(self.in_waiting)) + data += bytearray(self.read(self.inWaiting())) # TODO 1.3.8 migrate to in_waiting after pyserial upgrade to 3.4 # check for terminator, if it's there we have found our line termpos = data.find(terminator)