]> kaliko git repositories - python-musicpdaio.git/commitdiff
Handles connection problems
authorkaliko <kaliko@azylum.org>
Fri, 24 Apr 2015 17:33:16 +0000 (19:33 +0200)
committerkaliko <kaliko@azylum.org>
Fri, 24 Apr 2015 17:33:16 +0000 (19:33 +0200)
musicpdasio.py

index df730e063342fa5bda252f2a1467f0523e8cb3ce..665674d32df7456a96a867babfab10c776e8f124 100644 (file)
@@ -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