Make read(...) clearer and easier to manage

This commit is contained in:
Pedro Ferreira 2017-07-30 22:28:42 +02:00
parent 3d652d11cd
commit 69394936ee

View File

@ -110,7 +110,7 @@ class PSConnection(object):
def is_connected(self): def is_connected(self):
return self._connected return self._connected
async def read(self): async def _read(self):
try: try:
header = await self.connection.read() header = await self.connection.read()
if not header: if not header:
@ -130,6 +130,21 @@ class PSConnection(object):
await self.connection.disconnect() await self.connection.disconnect()
return None return None
async def read(self):
msg = await self._read()
if not msg:
return None
# check whether it's a reply and handle accordingly
if msg.req < 0:
t, handler = self._event_map[-msg.req]
await handler.process(msg)
logger.info('RESPONSE [%d]: %r', -msg.req, msg)
if msg.end_err:
await handler.stop()
del self._event_map[-msg.req]
logger.info('RESPONSE [%d]: EOS', -msg.req)
return msg
async def __await__(self): async def __await__(self):
async for data in self: async for data in self:
logger.info('RECV: %r', data) logger.info('RECV: %r', data)
@ -144,15 +159,8 @@ class PSConnection(object):
msg = await self.read() msg = await self.read()
if not msg: if not msg:
return return
if msg.req < 0: # filter out replies
t, handler = self._event_map[-msg.req] if msg.req >= 0:
await handler.process(msg)
logger.info('RESPONSE [%d]: %r', -msg.req, msg)
if msg.end_err:
await handler.stop()
del self._event_map[-msg.req]
logger.info('RESPONSE [%d]: EOS', -msg.req)
else:
yield msg yield msg
def _write(self, msg): def _write(self, msg):