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