|
11 | 11 | """ |
12 | 12 | from xbee.frame import APIFrame |
13 | 13 | from xbee.backend.base import XBeeBase as _XBeeBase |
| 14 | +from xbee.backend.base import TimeoutException as _TimeoutException |
14 | 15 | from tornado import ioloop, gen |
15 | 16 | from tornado.locks import Event |
16 | 17 | from tornado.concurrent import Future |
@@ -45,27 +46,28 @@ class XBeeBase(_XBeeBase): |
45 | 46 | argument is also used. |
46 | 47 | """ |
47 | 48 | def __init__(self, *args, **kwargs): |
| 49 | + if 'io_loop' in kwargs: |
| 50 | + self._ioloop = kwargs.pop('io_loop') |
| 51 | + else: |
| 52 | + self._ioloop = ioloop.IOLoop.current() |
| 53 | + |
48 | 54 | super(XBeeBase, self).__init__(*args, **kwargs) |
49 | 55 |
|
50 | 56 | self._running = Event() |
51 | 57 | self._running.set() |
52 | 58 |
|
53 | | - if 'io_loop' in kwargs: |
54 | | - self._ioloop = kwargs['io_loop'] |
55 | | - else: |
56 | | - self._ioloop = ioloop.IOLoop.current() |
57 | | - |
58 | 59 | self._frame_future = None |
59 | 60 | self._frame_queue = deque() |
60 | 61 |
|
61 | 62 | if self._callback: |
62 | 63 | # Make Non-Blocking |
63 | 64 | self.serial.timeout = 0 |
64 | | - self._ioloop.add_handler(self.serial.fd, |
65 | | - self._process_input, |
66 | | - ioloop.IOLoop.READ) |
67 | 65 | self.process_frames() |
68 | 66 |
|
| 67 | + self._ioloop.add_handler(self.serial.fd, |
| 68 | + self._process_input, |
| 69 | + ioloop.IOLoop.READ) |
| 70 | + |
69 | 71 | def halt(self): |
70 | 72 | """ |
71 | 73 | halt: None -> None |
@@ -99,15 +101,25 @@ def process_frames(self): |
99 | 101 | self._error_callback(e) |
100 | 102 |
|
101 | 103 | @gen.coroutine |
102 | | - def wait_read_frame(self): |
103 | | - frame = yield self._get_frame() |
| 104 | + def wait_read_frame(self, timeout=None): |
| 105 | + frame = yield self._get_frame(timeout=timeout) |
104 | 106 | raise gen.Return(self._split_response(frame.data)) |
105 | 107 |
|
106 | | - def _get_frame(self): |
| 108 | + def _get_frame(self, timeout=None): |
107 | 109 | future = Future() |
108 | 110 | if self._frame_queue: |
109 | 111 | future.set_result(self._frame_queue.popleft()) |
110 | 112 | else: |
| 113 | + if timeout is not None: |
| 114 | + def on_timeout(): |
| 115 | + future.set_exception(_TimeoutException()) |
| 116 | + |
| 117 | + handle = self._ioloop.add_timeout( |
| 118 | + self._ioloop.time() + timeout, on_timeout |
| 119 | + ) |
| 120 | + future.add_done_callback(lambda _: |
| 121 | + self._ioloop.remove_timeout(handle)) |
| 122 | + |
111 | 123 | self._frame_future = future |
112 | 124 |
|
113 | 125 | return future |
|
0 commit comments