From: kaliko Date: Fri, 24 Apr 2015 17:33:16 +0000 (+0200) Subject: Handles connection problems X-Git-Url: https://git.kaliko.me/?a=commitdiff_plain;h=ad463ee08066709b52ba3bd2907e2c7a51189a02;p=python-musicpdaio.git Handles connection problems --- diff --git a/musicpdasio.py b/musicpdasio.py index df730e0..665674d 100644 --- a/musicpdasio.py +++ b/musicpdasio.py @@ -21,7 +21,7 @@ try: except ImportError: print('Failed to import asyncio, need python >= 3.4') -import sys +import logging HELLO_PREFIX = "OK MPD " ERROR_PREFIX = "ACK " @@ -80,10 +80,8 @@ class MPDProto(asyncio.Protocol): err = ConnectionError('Connection lost while reading line') self.future.set_exception(err) - #def connection_lost(self): - # self.eof_received() - def data_received(self, data): + #logging.debug(data.decode('utf-8')) rcv = self._hello(data.decode('utf-8')) if rcv.startswith(ERROR_PREFIX): @@ -97,8 +95,8 @@ class MPDProto(asyncio.Protocol): def _hello(self, rcv): """Consume HELLO_PREFIX""" - if rcv.startswith(HELLO_PREFIX): + logging.debug('consumed 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:] @@ -127,17 +125,23 @@ class MPDClient: (self.__class__.__name__, attr)) return lambda *args: wrapper(command, args) + @asyncio.coroutine + def _connect(self, proto): + # coroutine allowing Exception handling + # src: http://comments.gmane.org/gmane.comp.python.tulip/1401 + try: + yield from MPDClient.loop.create_connection(lambda: proto, + host=self._host, + port=self._port) + except Exception as err: + proto.future.set_exception(ConnectionError(err)) + def _command(self, command, args): - payload = '{} {}'.format(command ,''.join(args)) + 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, self._cred), - host=self._host, - port=self._port)) + # kick off a task to create the connection to MPD + coro = self._connect(MPDProto(future, payload, self._cred)) + asyncio.async(coro) MPDClient.loop.run_until_complete(future) - #Useless? - #if future.exception(): - # raise future.exception() # return once completed. return future.result().resp