Loading...
Searching...
No Matches
async_client.py
''' Asynchronous python bindings for the lircd socket interface. '''
# pylint: disable=W0613
import asyncio
from lirc.client import AbstractConnection as AbstractConnection
class AsyncConnection(object):
''' Asynchronous read interface on top of an AbstractConnection.
Parameters:
- connection: Typically a lirc.RawConnection or lirc.LircdConnection.
- loop: AbstractEventLoop, typically obtained using
asyncio.get_event_loop().
'''
def __init__(self, connection: AbstractConnection,
loop: asyncio.AbstractEventLoop):
def read_from_fd():
''' Read data from the connection fd and put into queue. '''
try:
line = self._conn.readline(0)
if line:
asyncio.ensure_future(self._queue.put(line))
except Exception as e:
self.close()
self._queue.put_nowait(e)
self._conn = connection
self._loop = loop
self._queue = asyncio.Queue()
self._loop.add_reader(self._conn.fileno(), read_from_fd)
def close(self):
''' Clean up loop and the base connection. '''
self._loop.remove_reader(self._conn.fileno())
async def readline(self) -> str:
''' Asynchronous get next line from the connection. '''
line = await self._queue.get()
if isinstance(line, Exception):
raise line
return line
def __aiter__(self):
''' Return async iterator. '''
return self
async def __anext__(self):
''' Implement async iterator.next(). '''
line = await self._queue.get()
if isinstance(line, Exception):
raise StopAsyncIteration
return line
async def __aenter__(self):
''' Implement "async with". '''
return self
async def __aexit__(self, exc_type, exc, traceback):
''' Implement exit from "async with". '''
self.close()