1 # -*- coding: utf-8 -*-
3 # python-musicpd: Python MPD client library
4 # Copyright (C) 2014-2015 Kaliko Jack <kaliko@azylum.org>
6 # python-musicpdasio is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Lesser General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # python-musicpd is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU Lesser General Public License for more details.
16 # You should have received a copy of the GNU Lesser General Public License
17 # along with python-musicpd. If not, see <http://www.gnu.org/licenses/>.
23 print('Failed to import asyncio, need python >= 3.4')
28 from os import environ
29 if 'DEBUG' in environ or 'PYTHONASYNCIODEBUG' in environ:
30 logging.basicConfig(level=logging.DEBUG)
32 HELLO_PREFIX = "OK MPD "
39 class MPDError(Exception):
42 class ConnectionError(MPDError):
45 class ProtocolError(MPDError):
48 class CommandError(MPDError):
51 class CommandListError(MPDError):
54 class PendingCommandError(MPDError):
57 class IteratingError(MPDError):
67 return '"{0}…" ({1})'.format(
68 ' '.join(self.resp.split('\n')[:2]),
71 class MPDProto(asyncio.Protocol):
72 def __init__(self, future, payload, cred):
75 self.payload = payload
76 self.sess = Response()
78 def connection_made(self, transport):
79 self.transport = transport
80 self.transport.write(bytes('{}\n'.format(self.payload), 'utf-8'))
82 def eof_received(self):
83 self.transport.close()
84 err = ConnectionError('Connection lost while reading line')
85 self.future.set_exception(err)
87 def data_received(self, data):
88 #logging.debug(data.decode('utf-8'))
89 rcv = self._hello(data.decode('utf-8'))
91 if rcv.startswith(ERROR_PREFIX):
92 err = rcv[len(ERROR_PREFIX):].strip()
93 self.future.set_exception(CommandError(err))
96 if rcv.endswith(SUCCESS+'\n'):
97 logging.debug('set future result')
98 self.transport.close()
99 self.future.set_result(self.sess)
101 def _hello(self, rcv):
102 """Consume HELLO_PREFIX"""
103 if rcv.startswith(HELLO_PREFIX):
104 logging.debug('consumed hello prefix')
105 self.sess.version = rcv.split('\n')[0][len(HELLO_PREFIX):]
106 return rcv[rcv.find('\n')+1:]
111 def __init__(self, host='localhost', port=6600, cred=None):
112 self.eloop = asyncio.get_event_loop()
124 def __getattr__(self, attr):
127 wrapper = self._command
128 if command not in self._commands:
129 command = command.replace("_", " ")
130 if command not in self._commands:
131 raise AttributeError("'%s' object has no attribute '%s'" %
132 (self.__class__.__name__, attr))
133 return lambda *args: wrapper(command, args)
136 def _connect(self, proto):
137 # coroutine allowing Exception handling
138 # src: http://comments.gmane.org/gmane.comp.python.tulip/1401
140 yield from self.eloop.create_connection(lambda: proto,
143 except Exception as err:
144 proto.future.set_exception(ConnectionError(err))
146 def _command(self, command, args):
147 payload = '{} {}'.format(command, ''.join(args))
148 future = asyncio.Future()
149 # kick off a task to create the connection to MPD
150 coro = self._connect(MPDProto(future, payload, self._cred))
152 self.futures.append(future)
154 # return once completed.
155 self.eloop.run_until_complete(future)
157 # alternative w/ callback
159 # future.add_done_callback(lambda ftr: MPDClient.loop.stop())
160 # self.eloop.run_forever()
165 self.eloop.run_until_complete(asyncio.gather(*self.futures))
168 logging.info('No task found in queue, need to set self.asio?')