LIRC libraries: /tmp/work/src/lirc-0.10.2/python-pkg/lirc/async_client.py Source File

LIRC libraries Linux Infrared Remote Control

Loading...
Searching...
No Matches
async_client.py
1''' Asynchronous python bindings for the lircd socket interface. '''
2
8
9
39
40# pylint: disable=W0613
41
42import asyncio
43from lirc.client import AbstractConnection as AbstractConnection
44
45
46class AsyncConnection(object):
47 ''' Asynchronous read interface on top of an AbstractConnection.
48
49 Parameters:
50 - connection: Typically a lirc.RawConnection or lirc.LircdConnection.
51 - loop: AbstractEventLoop, typically obtained using
52 asyncio.get_event_loop().
53 '''
54
55 def __init__(self, connection: AbstractConnection,
56 loop: asyncio.AbstractEventLoop):
57
58 def read_from_fd():
59 ''' Read data from the connection fd and put into queue. '''
60 try:
61 line = self._conn.readline(0)
62 if line:
63 asyncio.ensure_future(self._queue.put(line))
64 except Exception as e:
65 self.close()
66 self._queue.put_nowait(e)
67
68 self._conn = connection
69 self._loop = loop
70 self._queue = asyncio.Queue()
71 self._loop.add_reader(self._conn.fileno(), read_from_fd)
72
73 def close(self):
74 ''' Clean up loop and the base connection. '''
75 self._loop.remove_reader(self._conn.fileno())
76
77 async def readline(self) -> str:
78 ''' Asynchronous get next line from the connection. '''
79 line = await self._queue.get()
80 if isinstance(line, Exception):
81 raise line
82 return line
83
84 def __aiter__(self):
85 ''' Return async iterator. '''
86 return self
87
88 async def __anext__(self):
89 ''' Implement async iterator.next(). '''
90 line = await self._queue.get()
91 if isinstance(line, Exception):
92 raise StopAsyncIteration
93 return line
94
95 async def __aenter__(self):
96 ''' Implement "async with". '''
97 return self
98
99 async def __aexit__(self, exc_type, exc, traceback):
100 ''' Implement exit from "async with". '''
101 self.close()
102
103