self.version)
class MPDProto(asyncio.Protocol):
- def __init__(self, future, payload):
+ def __init__(self, future, payload, cred):
+ self.transport = None
self.future = future
self.payload = payload
self.sess = Response()
self.transport = transport
self.transport.write(bytes('{}\n'.format(self.payload), 'utf-8'))
- def data_received(self, data):
- rcv = data.decode('utf-8')
- if '\n' not in rcv:
- self.sess.err = ConnectionError('Connection lost while reading line')
- self.future.set_result(self.sess)
- raise ConnectionError('Connection lost while reading line')
+ def eof_received(self):
+ self.transport.close()
+ err = ConnectionError('Connection lost while reading line')
+ self.future.set_exception(err)
- rcv = rcv.strip('\n')
+ #def connection_lost(self):
+ # self.eof_received()
- if rcv.startswith(HELLO_PREFIX):
- self.sess.version = rcv[len(HELLO_PREFIX):]
- return
- self.transport.close()
+ def data_received(self, data):
+ rcv = self._hello(data.decode('utf-8'))
- # set the result on the Future so that the coroutine can
- # resume
if rcv.startswith(ERROR_PREFIX):
- self.sess.err = rcv[len(ERROR_PREFIX):].strip()
- self.future.set_result(self.sess)
- return
- else:
- self.sess.resp = rcv
+ err = rcv[len(ERROR_PREFIX):].strip()
+ self.future.set_exception(CommandError(err))
+
+ self.sess.resp += rcv
+ if rcv.endswith(SUCCESS+'\n'):
+ self.transport.close()
self.future.set_result(self.sess)
+ def _hello(self, rcv):
+ """Consume HELLO_PREFIX"""
+
+ if rcv.startswith(HELLO_PREFIX):
+ self.sess.version = rcv.split('\n')[0][len(HELLO_PREFIX):]
+ #print('consumed hello prefix: %s' % self.sess.version)
+ return rcv[rcv.find('\n')+1:]
+ return rcv
+
class MPDClient:
loop = asyncio.get_event_loop()
- def __init__(self, host='localhost', port=6600):
+ def __init__(self, host='localhost', port=6600, cred=None):
self._host = host
self._port = port
+ self._cred = cred
self._commands = {
'currentsong',
'stats',
+ 'playlistinfo',
}
def __getattr__(self, attr):
return lambda *args: wrapper(command, args)
def _command(self, command, args):
- # TODO: deal with encoding
payload = '{} {}'.format(command ,''.join(args))
future = asyncio.Future()
# kick off a task to create the connection to MPD.
asyncio.async(MPDClient.loop.create_connection(
- lambda: MPDProto(future, payload),
+ lambda: MPDProto(future, payload, self._cred),
host=self._host,
port=self._port))
MPDClient.loop.run_until_complete(future)
- # return the future once completed.
- return future.result()
-
+ #Useless?
+ #if future.exception():
+ # raise future.exception()
+ # return once completed.
+ return future.result().resp