]> kaliko git repositories - python-musicpd.git/blob - doc/source/use.rst
Improved Range object to deal with window parameter
[python-musicpd.git] / doc / source / use.rst
1 .. SPDX-FileCopyrightText: 2018-2023  kaliko <kaliko@azylum.org>
2 .. SPDX-License-Identifier: LGPL-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 Some commands (e.g. delete) allow specifying a range in the form `"START:END"` (cf. `MPD protocol documentation`_ for more details).
90
91 Possible ranges are: `"START:END"`, `"START:"` and `":"` :
92
93 Instead of giving the plain string as `"START:END"`, you **can** provide a :py:obj:`tuple` as `(START,END)`. The module is then ensuring the format is correct and raises an :py:obj:`musicpd.CommandError` exception otherwise. Empty start or end can be specified as en empty string `''` or :py:obj:`None`.
94
95 .. code-block:: python
96
97     # An intelligent clear
98     # clears played track in the queue, currentsong included
99     pos = client.currentsong().get('pos', 0)
100     # the range object accepts str, no need to convert to int
101     client.delete((0, pos))
102     # missing end interpreted as highest value possible, pay attention still need a tuple.
103     client.delete((pos,))  # purge queue from current to the end
104
105 A notable case is the `rangeid` command allowing an empty range specified
106 as a single colon as argument (i.e. sending just ":"):
107
108 .. code-block:: python
109
110     # sending "rangeid :" to clear the range, play everything
111     client.rangeid(())  # send an empty tuple
112
113 Empty start in range (i.e. ":END") are not possible and will raise a CommandError.
114
115 Remember the of the tuple is optional, range can still be specified as single string `START:END`. In case of malformed range a CommandError is still raised.
116
117 Iterators
118 ----------
119
120 Commands may also return iterators instead of lists if `iterate` is set to
121 `True`:
122
123 .. code-block:: python
124
125     client.iterate = True
126     for song in client.playlistinfo():
127         print song['file']
128
129 Idle prefixed commands
130 ----------------------
131
132 Each command have a *send\_<CMD>* and a *fetch\_<CMD>* variant, which allows to
133 send a MPD command and then fetch the result later (non-blocking call).
134 This is useful for the idle command:
135
136 .. code-block:: python
137
138     >>> client.send_idle()
139     # do something else or use function like select()
140     # http://docs.python.org/howto/sockets.html#non-blocking-sockets
141     # ex. select([client], [], [])
142     >>> events = client.fetch_idle()
143
144     # more complex use for example, with glib/gobject:
145     >>> def callback(source, condition):
146     >>>    changes = client.fetch_idle()
147     >>>    print changes
148     >>>    return False  # removes the IO watcher
149
150     >>> client.send_idle()
151     >>> gobject.io_add_watch(client, gobject.IO_IN, callback)
152     >>> gobject.MainLoop().run()
153
154 See also use of :ref:`socket timeout<socket_timeout>` with idle command.
155
156 Fetching binary content (cover art)
157 -----------------------------------
158
159 Fetching album covers is possible with albumart, here is an example:
160
161 .. code-block:: python
162
163     >>> cli = musicpd.MPDClient()
164     >>> cli.connect()
165     >>> track = "Steve Reich/1978-Music for 18 Musicians"
166     >>> aart = cli.albumart(track, 0)
167     >>> received = int(aart.get('binary'))
168     >>> size = int(aart.get('size'))
169     >>> with open('/tmp/cover', 'wb') as cover:
170     >>>     # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
171     >>>     cover.write(aart.get('data'))
172     >>>     while received < size:
173     >>>         aart = cli.albumart(track, received)
174     >>>         cover.write(aart.get('data'))
175     >>>         received += int(aart.get('binary'))
176     >>>     if received != size:
177     >>>         print('something went wrong', file=sys.stderr)
178     >>> cli.disconnect()
179
180 A `CommandError` is raised if the album does not expose a cover.
181
182 You can also use `readpicture` command to fetch embedded picture:
183
184 .. code-block:: python
185
186     >>> cli = musicpd.MPDClient()
187     >>> cli.connect()
188     >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
189     >>> rpict = cli.readpicture(track, 0)
190     >>> if not rpict:
191     >>>     print('No embedded picture found', file=sys.stderr)
192     >>>     sys.exit(1)
193     >>> size = int(rpict['size'])
194     >>> done = int(rpict['binary'])
195     >>> with open('/tmp/cover', 'wb') as cover:
196     >>>     cover.write(rpict['data'])
197     >>>     while size > done:
198     >>>         rpict = cli.readpicture(track, done)
199     >>>         done += int(rpict['binary'])
200     >>>         print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
201     >>>         cover.write(rpict['data'])
202     >>> cli.disconnect()
203
204 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
205
206 .. _socket_timeout:
207
208 Socket timeout
209 --------------
210
211 .. note::
212   When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
213
214 A timeout is used for the initial MPD connection (``connect`` command), then
215 the socket is put in blocking mode with no timeout. Its value is set in
216 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
217 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
218 is possible to set socket timeout for all command setting
219 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
220
221 Having ``socket_timeout`` enabled can help to detect "half-open connection".
222 For instance loosing connectivity without the server explicitly closing the
223 connection (switching network interface ethernet/wifi, router down, etc…).
224
225 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
226 timeout. A couple of seconds should be enough for commands to complete except
227 for the special case of ``idle`` command which by definition *“ waits until
228 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
229 protocol documentation`_).
230
231 Here is a solution to use ``idle`` command with ``socket_timeout``:
232
233 .. code-block:: python
234
235     import musicpd
236     import select
237     import socket
238
239     cli = musicpd.MPDClient()
240     try:
241         cli.socket_timeout = 10  # seconds
242         select_timeout = 5 # second
243         cli.connect()
244         while True:
245             cli.send_idle()  # use send_ API to avoid blocking on read
246             _read, _, _ = select.select([cli], [], [], select_timeout)
247             if _read:  # tries to read response
248                 ret = cli.fetch_idle()
249                 print(', '.join(ret))  # Do something
250             else: # cancels idle
251                 cli.noidle()
252     except socket.timeout as err:
253         print(f'{err} (timeout {cli.socket_timeout})')
254     except (OSError, musicpd.MPDError) as err:
255         print(f'{err!r}')
256         if cli._sock is not None:
257             cli.disconnect()
258     except KeyboardInterrupt:
259         pass
260
261 Some explanations:
262
263   * First launch a non blocking ``idle`` command. This call do not wait for a
264     response to avoid socket timeout waiting for an MPD event.
265   * ``select`` waits for something to read on the socket (the idle response
266     in this case), returns after ``select_timeout`` seconds anyway.
267   * In case there is something to read read it using ``fetch_idle``
268   * Nothing to read, cancel idle with ``noidle``
269
270 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
271 triggering a socket timeout unless the connection is actually lost (actually it
272 could also be that MPD took too much time to answer, but MPD taking more than a
273 couple of seconds for these commands should never occur).
274
275
276 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
277 .. vim: spell spelllang=en