diff options
author | Anton Khirnov <wyskas@gmail.com> | 2009-09-08 16:53:13 +0200 |
---|---|---|
committer | Anton Khirnov <wyskas@gmail.com> | 2009-09-08 17:25:36 +0200 |
commit | 9d38f9d17149e137b3f0404605a82f741a57fee1 (patch) | |
tree | 4142da99cef22807739c695cf70237157c6e0939 | |
parent | deeda78d5ccfb6a33e214f639cebd34dd790accd (diff) |
mpd: rewrite connecting/disconnecting functions to use signals.
-rw-r--r-- | nephilim/mpclient.py | 93 | ||||
-rw-r--r-- | nephilim/mpd.py | 59 |
2 files changed, 79 insertions, 73 deletions
diff --git a/nephilim/mpclient.py b/nephilim/mpclient.py index a7b09de..e691989 100644 --- a/nephilim/mpclient.py +++ b/nephilim/mpclient.py @@ -30,6 +30,7 @@ class MPClient(QtCore.QObject): outputs = None # private + __password = None _client = None _cur_song = None _status = {'volume' : 0, 'repeat' : 0, 'random' : 0, @@ -71,7 +72,7 @@ class MPClient(QtCore.QObject): #### public #### def __init__(self, mpclient, name, id, state): - QtCore.QObject.__init__(self, mpclient) + QtCore.QObject.__init__(self) self.mpclient = mpclient self.name = name @@ -97,65 +98,24 @@ class MPClient(QtCore.QObject): self.logger = logging.getLogger('mpclient') def connect_mpd(self, host, port, password = None): - """Connect to MPD@host:port, optionally using password. - Returns True at success, False otherwise.""" - + """Connect to MPD@host:port, optionally using password.""" self.logger.info('Connecting to MPD...') if self._client: self.logger.warning('Attempted to connect when already connected.') - return True - - try: - self._client = mpd.MPDClient() - self._client.connect(host, port) - except socket.error, e: - self.logger.error('Socket error: %s.'%e) - self.disconnect_mpd() - return False - - if password: - self.password(password) - else: - self._commands = list(self._client.commands()) - - if not self.__check_command_ok('listallinfo'): - self.logger.error('Don\'t have MPD read permission, diconnecting.') - return self.disconnect_mpd() + return - self.__update_current_song() - self.__update_outputs() - self._db_update = self.stats()['db_update'] + self._client = mpd.MPDClient() + self._client.connect_changed.connect(lambda val:self.__finish_connect() if val else self.__finish_disconnect()) + self._client.connect_mpd(host, port) + self.__password = password - self.connect_changed.emit(True) - self.logger.info('Successfully connected to MPD.') - self._timer_id = self.startTimer(500) - self._db_timer_id = self.startTimer(10000) - return True def disconnect_mpd(self): """Disconnect from MPD.""" self.logger.info('Disconnecting from MPD...') - if self._client: - try: - self._client.close() - self._client.disconnect() - except (mpd.ConnectionError, socket.error): - pass - self._client = None - else: + if not self._client: self.logger.warning('Attempted to disconnect when not connected.') + self._client.disconnect_mpd() - if self._timer_id: - self.killTimer(self._timer_id) - self._timer_id = None - if self._db_timer_id: - self.killTimer(self._db_timer_id) - self._db_timer_id = None - self._status = dict(MPClient._status) - self._cur_song = None - self._commands = [] - self.outputs = [] - self.connect_changed.emit(False) - self.logger.info('Disconnected from MPD.') def password(self, password): """Use the password to authenticate with MPD.""" self.logger.info('Authenticating with MPD.') @@ -387,6 +347,39 @@ class MPClient(QtCore.QObject): self._client.command_list_end() #### private #### + def __finish_connect(self): + if self.__password: + self.password(self.__password) + else: + self._commands = list(self._client.commands()) + + if not self.__check_command_ok('listallinfo'): + self.logger.error('Don\'t have MPD read permission, diconnecting.') + return self.disconnect_mpd() + + self.__update_current_song() + self.__update_outputs() + self._db_update = self.stats()['db_update'] + + self.connect_changed.emit(True) + self.logger.info('Successfully connected to MPD.') + self._timer_id = self.startTimer(500) + self._db_timer_id = self.startTimer(1000) + def __finish_disconnect(self): + self._client = None + + if self._timer_id: + self.killTimer(self._timer_id) + self._timer_id = None + if self._db_timer_id: + self.killTimer(self._db_timer_id) + self._db_timer_id = None + self._status = dict(MPClient._status) + self._cur_song = None + self._commands = [] + self.outputs = [] + self.connect_changed.emit(False) + self.logger.info('Disconnected from MPD.') def __update_current_song(self): """Update the current song.""" song = self._client.currentsong() diff --git a/nephilim/mpd.py b/nephilim/mpd.py index cae2bcb..97aa54f 100644 --- a/nephilim/mpd.py +++ b/nephilim/mpd.py @@ -15,6 +15,8 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. import socket +import logging +from PyQt4 import QtCore HELLO_PREFIX = "OK MPD " @@ -46,8 +48,15 @@ class _NotConnected(object): def _dummy(*args): raise ConnectionError("Not connected") -class MPDClient(object): +class MPDClient(QtCore.QObject): + # public + logger = None + + # SIGNALS + connect_changed = QtCore.pyqtSignal(bool) def __init__(self): + QtCore.QObject.__init__(self) + self.logger = logging.getLogger('mpclient.mpdsocket') self._reset() self._commands = { # Admin Commands @@ -272,15 +281,6 @@ class MPDClient(object): self._commandlist = None raise - def _hello(self): - line = self._rfile.readline() - if not line.endswith("\n"): - raise ConnectionError("Connection lost while reading MPD hello") - line = line.rstrip("\n") - if not line.startswith(HELLO_PREFIX): - raise ProtocolError("Got invalid MPD hello: '%s'" % line) - self.mpd_version = line[len(HELLO_PREFIX):].strip() - def _reset(self): self.mpd_version = None self._commandlist = None @@ -288,9 +288,9 @@ class MPDClient(object): self._rfile = _NotConnected() self._wfile = _NotConnected() - def connect(self, host, port): + def connect_mpd(self, host, port): if self._sock: - raise ConnectionError("Already connected") + self.logger.error('Already connected.') msg = "getaddrinfo returns an empty list" try: flags = socket.AI_ADDRCONFIG @@ -300,10 +300,11 @@ class MPDClient(object): try: self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self._sock.connect(host) - except socket.error, msg: + except socket.error, e: if self._sock: self._sock.close() self._sock = None + self.logger.error('Error connecting to MPD: %s.'%e) else: for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, @@ -312,27 +313,39 @@ class MPDClient(object): try: self._sock = socket.socket(af, socktype, proto) self._sock.connect(sa) - except socket.error, msg: + except socket.error, e: if self._sock: self._sock.close() self._sock = None + self.logger.error('Error connecting to MPD: %s.'%e) continue break if not self._sock: - raise socket.error(msg) - self._rfile = self._sock.makefile("rb") - self._wfile = self._sock.makefile("wb") - try: - self._hello() - except: - self.disconnect() - raise + return + self._rfile = self._sock.makefile('rb') + self._wfile = self._sock.makefile('wb') + + # read MPD hello + line = self._rfile.readline() + if not line.endswith("\n"): + self.logger.error('Connnection lost while reading MPD hello') + self.disconnect_mpd() + return False + line = line.rstrip("\n") + if not line.startswith(HELLO_PREFIX): + self.logger.error('Got invalid MPD hello: %s' % line) + self.disconnect_mpd() + return + self.mpd_version = line[len(HELLO_PREFIX):].strip() + + self.connect_changed.emit(True) - def disconnect(self): + def disconnect_mpd(self): self._rfile.close() self._wfile.close() self._sock.close() self._reset() + self.connect_changed.emit(False) def command_list_ok_begin(self): if self._commandlist is not None: |