]> kaliko git repositories - python-musicpd.git/blob - doc/source/use.rst
Document context manager
[python-musicpd.git] / doc / source / use.rst
1 Using the client library
2 =========================
3
4 Introduction
5 ------------
6
7 The client library can be used as follows:
8
9 .. code-block:: python
10
11     client = musicpd.MPDClient()       # create client object
12     client.connect()                   # use MPD_HOST/MPD_PORT if set else
13                                        #   test ${XDG_RUNTIME_DIR}/mpd/socket for existence
14                                        #   fallback to localhost:6600
15                                        # connect support host/port argument as well
16     print(client.mpd_version)          # print the mpd protocol version
17     print(client.cmd('foo', 42))       # print result of the request "cmd foo 42"
18                                        # (nb. for actual command, see link to the protocol below)
19     client.disconnect()                # disconnect from the server
20
21 In the example above `cmd` in not an actual MPD command, for a list of
22 supported commands, their arguments (as MPD currently understands
23 them), and the functions used to parse their responses see :ref:`commands`.
24
25 See the `MPD protocol documentation`_ for more details.
26
27 .. _environment_variables:
28
29 Environment variables
30 ---------------------
31
32 The client honors the following environment variables:
33
34   * ``MPD_HOST`` MPD host (:abbr:`FQDN (fully qualified domain name)`, socket path or abstract socket) and password.
35
36     | To define a password set MPD_HOST to "`password@host`" (password only "`password@`")
37     | For abstract socket use "@" as prefix : "`@socket`" and then with a password  "`pass@@socket`"
38     | Regular unix socket are set with an absolute path: "`/run/mpd/socket`"
39   * ``MPD_PORT`` MPD port, relevant for TCP socket only, ie with :abbr:`FQDN (fully qualified domain name)` defined host
40   * ``MPD_TIMEOUT`` timeout for connecting to MPD and waiting for MPD’s response in seconds
41   * ``XDG_RUNTIME_DIR`` path to look for potential socket: ``${XDG_RUNTIME_DIR}/mpd/socket``
42
43 .. _default_settings:
44
45 Default settings
46 ----------------
47
48   * If ``MPD_HOST`` is not set, then look for a socket in ``${XDG_RUNTIME_DIR}/mpd/socket``
49   * If there is no socket use ``localhost``
50   * If ``MPD_PORT`` is not set, then use ``6600``
51   * If ``MPD_TIMEOUT`` is not set, then uses :py:obj:`musicpd.CONNECTION_TIMEOUT`
52
53
54 Context manager
55 ---------------
56
57 Calling MPDClient in a context manager :py:obj:`musicpd.MPDClient.connect` is
58 transparently called with :ref:`default setting<default_settings>` (use
59 :ref:`environment variables<environment_variables>` to override defaults).
60 Leaving the context manager :py:obj:`musicpd.MPDClient.disconnect` is called.
61
62 .. code-block:: python
63
64     import os
65     os.environ['MPD_HOST'] = 'mpdhost'
66     with MPDClient() as c:
67         c.status()
68         c.next()
69
70 Command lists
71 -------------
72
73 Command lists are also supported using `command_list_ok_begin()` and
74 `command_list_end()` :
75
76 .. code-block:: python
77
78     client.command_list_ok_begin()       # start a command list
79     client.update()                      # insert the update command into the list
80     client.status()                      # insert the status command into the list
81     results = client.command_list_end()  # results will be a list with the results
82
83 Ranges
84 ------
85
86 Provide a 2-tuple as argument for command supporting ranges (cf. `MPD protocol documentation`_ for more details).
87 Possible ranges are: "START:END", "START:" and ":" :
88
89 .. code-block:: python
90
91     # An intelligent clear
92     # clears played track in the queue, currentsong included
93     pos = client.currentsong().get('pos', 0)
94     # the 2-tuple range object accepts str, no need to convert to int
95     client.delete((0, pos))
96     # missing end interpreted as highest value possible, pay attention still need a tuple.
97     client.delete((pos,))  # purge queue from current to the end
98
99 A notable case is the `rangeid` command allowing an empty range specified
100 as a single colon as argument (i.e. sending just ":"):
101
102 .. code-block:: python
103
104     # sending "rangeid :" to clear the range, play everything
105     client.rangeid(())  # send an empty tuple
106
107 Empty start in range (i.e. ":END") are not possible and will raise a CommandError.
108
109 Iterators
110 ----------
111
112 Commands may also return iterators instead of lists if `iterate` is set to
113 `True`:
114
115 .. code-block:: python
116
117     client.iterate = True
118     for song in client.playlistinfo():
119         print song['file']
120
121 Idle prefixed commands
122 ----------------------
123
124 Each command have a *send\_<CMD>* and a *fetch\_<CMD>* variant, which allows to
125 send a MPD command and then fetch the result later.
126 This is useful for the idle command:
127
128 .. code-block:: python
129
130     >>> client.send_idle()
131     # do something else or use function like select()
132     # http://docs.python.org/howto/sockets.html#non-blocking-sockets
133     # ex. select([client], [], [])
134     >>> events = client.fetch_idle()
135
136     # more complex use for example, with glib/gobject:
137     >>> def callback(source, condition):
138     >>>    changes = client.fetch_idle()
139     >>>    print changes
140     >>>    return False  # removes the IO watcher
141
142     >>> client.send_idle()
143     >>> gobject.io_add_watch(client, gobject.IO_IN, callback)
144     >>> gobject.MainLoop().run()
145
146 Fetching binary content (cover art)
147 -----------------------------------
148
149 Fetching album covers is possible with albumart, here is an example:
150
151 .. code-block:: python
152
153     >>> cli = musicpd.MPDClient()
154     >>> cli.connect()
155     >>> track = "Steve Reich/1978-Music for 18 Musicians"
156     >>> aart = cli.albumart(track, 0)
157     >>> received = int(aart.get('binary'))
158     >>> size = int(aart.get('size'))
159     >>> with open('/tmp/cover', 'wb') as cover:
160     >>>     # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
161     >>>     cover.write(aart.get('data'))
162     >>>     while received < size:
163     >>>         aart = cli.albumart(track, received)
164     >>>         cover.write(aart.get('data'))
165     >>>         received += int(aart.get('binary'))
166     >>>     if received != size:
167     >>>         print('something went wrong', file=sys.stderr)
168     >>> cli.disconnect()
169
170 A `CommandError` is raised if the album does not expose a cover.
171
172 You can also use `readpicture` command to fetch embedded picture:
173
174 .. code-block:: python
175
176     >>> cli = musicpd.MPDClient()
177     >>> cli.connect()
178     >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
179     >>> rpict = cli.readpicture(track, 0)
180     >>> if not rpict:
181     >>>     print('No embedded picture found', file=sys.stderr)
182     >>>     sys.exit(1)
183     >>> size = int(rpict['size'])
184     >>> done = int(rpict['binary'])
185     >>> with open('/tmp/cover', 'wb') as cover:
186     >>>     cover.write(rpict['data'])
187     >>>     while size > done:
188     >>>         rpict = cli.readpicture(track, done)
189     >>>         done += int(rpict['binary'])
190     >>>         print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
191     >>>         cover.write(rpict['data'])
192     >>> cli.disconnect()
193
194 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
195
196 Socket timeout
197 --------------
198
199 .. note::
200   When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
201
202 A timeout is used for the initial MPD connection (``connect`` command), then
203 the socket is put in blocking mode with no timeout. Its value is set in
204 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
205 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
206 is possible to set socket timeout for all command setting
207 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
208
209 Having ``socket_timeout`` enabled can help to detect "half-open connection".
210 For instance loosing connectivity without the server explicitly closing the
211 connection (switching network interface ethernet/wifi, router down, etc…).
212
213 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
214 timeout. A couple of seconds should be enough for commands to complete except
215 for the special case of ``idle`` command which by definition *“ waits until
216 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
217 protocol documentation`_).
218
219 Here is a solution to use ``idle`` command with ``socket_timeout``:
220
221 .. code-block:: python
222
223     import musicpd
224     import select
225     import socket
226
227     cli = musicpd.MPDClient()
228     try:
229         cli.socket_timeout = 10  # seconds
230         select_timeout = 5 # second
231         cli.connect()
232         while True:
233             cli.send_idle()  # use send_ API to avoid blocking on read
234             _read, _, _ = select.select([cli], [], [], select_timeout)
235             if _read:  # tries to read response
236                 ret = cli.fetch_idle()
237                 print(', '.join(ret))  # Do something
238             else: # cancels idle
239                 cli.noidle()
240     except socket.timeout as err:
241         print(f'{err} (timeout {cli.socket_timeout})')
242     except (OSError, musicpd.MPDError) as err:
243         print(f'{err!r}')
244         if cli._sock is not None:
245             cli.disconnect()
246     except KeyboardInterrupt:
247         pass
248
249 Some explanations:
250
251   * First launch a non blocking ``idle`` command. This call do not wait for a
252     response to avoid socket timeout waiting for an MPD event.
253   * ``select`` waits for something to read on the socket (the idle response
254     in this case), returns after ``select_timeout`` seconds anyway.
255   * In case there is something to read read it using ``fetch_idle``
256   * Nothing to read, cancel idle with ``noidle``
257
258 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
259 triggering a socket timeout unless the connection is actually lost (actually it
260 could also be that MPD took to much time to answer, but MPD taking more than a
261 couple of seconds for these commands should never occur).
262
263
264 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
265 .. vim: spell spelllang=en