diff --git a/amodem/stream.py b/amodem/stream.py index 20123d5..25844ff 100644 --- a/amodem/stream.py +++ b/amodem/stream.py @@ -1,21 +1,25 @@ import time +import logging +log = logging.getLogger(__name__) + + +class Timeout(Exception): + pass class Reader(object): - SAMPLES = 4096 - BUFSIZE = int(SAMPLES * wave.bytes_per_sample) - WAIT = 0.1 - TIMEOUT = 2.0 - - def __init__(self, fd, data_type=None, bufsize=None, eof=False): + def __init__(self, fd, data_type=None, bufsize=4096, + eof=False, timeout=2.0, wait=0.2): self.fd = fd - self.check = None - self.total = 0 - self.bufsize = bufsize if (bufsize is not None) else self.BUFSIZE - self.eof = eof self.data_type = data_type if (data_type is not None) else lambda x: x + self.bufsize = bufsize + self.eof = eof + self.timeout = timeout + self.wait = wait + self.total = 0 + self.check = None def __iter__(self): return self @@ -26,7 +30,7 @@ class Reader(object): def next(self): block = bytearray() if self.eof: - data = self.fd.read(self.BUFSIZE) + data = self.fd.read(self.bufsize) if data: self.total += len(data) block.extend(data) @@ -34,20 +38,20 @@ class Reader(object): else: raise StopIteration() - finish_time = time.time() + self.TIMEOUT + finish_time = time.time() + self.timeout while time.time() <= finish_time: - left = self.BUFSIZE - len(block) + left = self.bufsize - len(block) data = self.fd.read(left) if data: self.total += len(data) block.extend(data) - if len(block) == self.BUFSIZE: + if len(block) == self.bufsize: values = self.data_type(block) if self.check: self.check(values) return values - time.sleep(self.WAIT) + time.sleep(self.wait) - raise IOError('timeout') + raise Timeout(self.timeout) diff --git a/tests/test_stream.py b/tests/test_stream.py index e220e26..8805bd1 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -31,5 +31,5 @@ def test_read(): try: for buf in f: pass - except IOError as e: - assert str(e) == 'timeout' + except stream.Timeout as e: + assert e.args == (f.timeout,)