]> kaliko git repositories - python-musicpd.git/blob - doc/source/examples/client.py
Releasing 0.9.0
[python-musicpd.git] / doc / source / examples / client.py
1 """Plain client class
2 """
3 import logging
4 import select
5 import sys
6
7 import musicpd
8
9
10 class MyClient(musicpd.MPDClient):
11     """Plain client inheriting from MPDClient"""
12
13     def __init__(self):
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__)
18         super().__init__()
19         # Set host/port/password after init to overrides defaults
20         # self.host = 'example.org'
21         # self.port = 4242
22         # self.pwd = 'secret'
23
24     def connect(self):
25         """Overriding explicitly MPDClient.connect()"""
26         try:
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:
31             # Catch socket error
32             self.log.error('Failed to connect: %s', err)
33             sys.exit(42)
34
35     def _wait_for_changes(self, callback):
36         select_timeout = 10  # second
37         while True:
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()
42                 # do something
43                 callback(ret)
44             else:  # cancels idle
45                 self.noidle()
46
47     def callback(self, *args):
48         """Method launch on MPD event, cf. monitor method"""
49         self.log.info('%s', args)
50
51     def monitor(self):
52         """Continuously monitor MPD activity.
53         Launch callback method on event.
54         """
55         try:
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)
60
61 if __name__ == '__main__':
62     cli = MyClient()
63     # You can overrides host here or in init
64     #cli.host = 'example.org'
65     # Connect MPD server
66     try:
67         cli.connect()
68     except musicpd.ConnectionError as err:
69         cli.log.error(err)
70
71     # Monitor MPD changes, blocking/timeout idle approach
72     try:
73         cli.socket_timeout =  20 # seconds
74         ret = cli.idle()
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)
78
79     # Reset connection
80     try:
81         cli.socket_timeout = None
82         cli.disconnect()
83         cli.connect()
84     except musicpd.ConnectionError as err:
85         cli.log.error(err)
86
87     # Monitor MPD changes, non blocking idle approach
88     try:
89         cli.monitor()
90     except KeyboardInterrupt as err:
91         cli.log.info(type(err).__name__)
92         cli.send_noidle()
93         cli.disconnect()
94