10 class MyClient(musicpd.MPDClient):
11 """Plain client inheriting from MPDClient"""
14 # Set logging to debug level
15 logging.basicConfig(level=logging.DEBUG,
16 format='%(levelname)-8s %(module)-8s %(message)s')
17 self.log = logging.getLogger(__name__)
19 # Set host/port/password after init to overrides defaults
20 # self.host = 'example.org'
25 """Overriding explicitly MPDClient.connect()"""
27 super().connect(host=self.host, port=self.port)
28 if hasattr(self, 'pwd') and self.pwd:
29 self.password(self.pwd)
30 except musicpd.ConnectionError as err:
32 self.log.error('Failed to connect: %s', err)
35 def _wait_for_changes(self, callback):
36 select_timeout = 10 # second
38 self.send_idle() # use send_ API to avoid blocking on read
39 _read, _, _ = select.select([self], [], [], select_timeout)
40 if _read: # tries to read response
41 ret = self.fetch_idle()
47 def callback(self, *args):
48 """Method launch on MPD event, cf. monitor method"""
49 self.log.info('%s', args)
52 """Continuously monitor MPD activity.
53 Launch callback method on event.
56 self._wait_for_changes(self.callback)
57 except (OSError, musicpd.MPDError) as err:
58 self.log.error('%s: Something went wrong: %s',
59 type(err).__name__, err)
61 if __name__ == '__main__':
63 # You can overrides host here or in init
64 #cli.host = 'example.org'
68 except musicpd.ConnectionError as err:
71 # Monitor MPD changes, blocking/timeout idle approach
73 cli.socket_timeout = 20 # seconds
75 cli.log.info('Leaving idle, got: %s', ret)
76 except TimeoutError as err:
77 cli.log.info('Nothing occured the last %ss', cli.socket_timeout)
81 cli.socket_timeout = None
84 except musicpd.ConnectionError as err:
87 # Monitor MPD changes, non blocking idle approach
90 except KeyboardInterrupt as err:
91 cli.log.info(type(err).__name__)