summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorChris Liechti <cliechti@gmx.net>2016-09-04 23:35:53 +0200
committerChris Liechti <cliechti@gmx.net>2016-09-04 23:35:53 +0200
commit0351332d818a320191d54fb05456836084b9f60b (patch)
tree5cc5a346f7ec622702a287e38719530bd1a9f86e
parent06ed4a518ddb1cb894f616e8d3e1d0e5f87033c8 (diff)
downloadpyserial-git-0351332d818a320191d54fb05456836084b9f60b.tar.gz
serialutil: Improve Timeout class to handle clock adjustments
only applies to older Python versions where time.monotonic is not available, see also #155
-rw-r--r--serial/serialutil.py12
1 files changed, 10 insertions, 2 deletions
diff --git a/serial/serialutil.py b/serial/serialutil.py
index 60558fc..547dc56 100644
--- a/serial/serialutil.py
+++ b/serial/serialutil.py
@@ -129,6 +129,7 @@ class Timeout(object):
"""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 = self.TIME() + duration
else:
@@ -136,7 +137,7 @@ class Timeout(object):
def expired(self):
"""Return a boolean, telling if the timeout has expired"""
- return self.target_time is not None and self.TIME() > self.target_time
+ 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"""
@@ -145,13 +146,20 @@ class Timeout(object):
elif self.is_infinite:
return None
else:
- return max(0, self.target_time - self.TIME())
+ delta = self.target_time - self.TIME()
+ if delta > self.duration:
+ # clock jumped, recalculate
+ self.target_time = self.TIME() + 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 = self.TIME() + duration