]> kaliko git repositories - python-musicpd.git/blob - doc/source/use.rst
Add cross reference to socket timeout
[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 (non-blocking call).
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 See also use of :ref:`socket timeout<socket_timeout>` with idle command.
147
148 Fetching binary content (cover art)
149 -----------------------------------
150
151 Fetching album covers is possible with albumart, here is an example:
152
153 .. code-block:: python
154
155     >>> cli = musicpd.MPDClient()
156     >>> cli.connect()
157     >>> track = "Steve Reich/1978-Music for 18 Musicians"
158     >>> aart = cli.albumart(track, 0)
159     >>> received = int(aart.get('binary'))
160     >>> size = int(aart.get('size'))
161     >>> with open('/tmp/cover', 'wb') as cover:
162     >>>     # aart = {'size': 42, 'binary': 2051, data: bytes(...)}
163     >>>     cover.write(aart.get('data'))
164     >>>     while received < size:
165     >>>         aart = cli.albumart(track, received)
166     >>>         cover.write(aart.get('data'))
167     >>>         received += int(aart.get('binary'))
168     >>>     if received != size:
169     >>>         print('something went wrong', file=sys.stderr)
170     >>> cli.disconnect()
171
172 A `CommandError` is raised if the album does not expose a cover.
173
174 You can also use `readpicture` command to fetch embedded picture:
175
176 .. code-block:: python
177
178     >>> cli = musicpd.MPDClient()
179     >>> cli.connect()
180     >>> track = 'muse/Amon Tobin/2011-ISAM/01-Amon Tobin - Journeyman.mp3'
181     >>> rpict = cli.readpicture(track, 0)
182     >>> if not rpict:
183     >>>     print('No embedded picture found', file=sys.stderr)
184     >>>     sys.exit(1)
185     >>> size = int(rpict['size'])
186     >>> done = int(rpict['binary'])
187     >>> with open('/tmp/cover', 'wb') as cover:
188     >>>     cover.write(rpict['data'])
189     >>>     while size > done:
190     >>>         rpict = cli.readpicture(track, done)
191     >>>         done += int(rpict['binary'])
192     >>>         print(f'writing {rpict["binary"]}, done {100*done/size:03.0f}%')
193     >>>         cover.write(rpict['data'])
194     >>> cli.disconnect()
195
196 Refer to `MPD protocol documentation`_ for the meaning of `binary`, `size` and `data`.
197
198 .. _socket_timeout:
199
200 Socket timeout
201 --------------
202
203 .. note::
204   When the timeout is reached it raises a :py:obj:`socket.timeout` exception. An :py:obj:`OSError` subclass.
205
206 A timeout is used for the initial MPD connection (``connect`` command), then
207 the socket is put in blocking mode with no timeout. Its value is set in
208 :py:obj:`musicpd.CONNECTION_TIMEOUT` at module level and
209 :py:obj:`musicpd.MPDClient.mpd_timeout` in MPDClient instances . However it
210 is possible to set socket timeout for all command setting
211 :py:obj:`musicpd.MPDClient.socket_timeout` attribute to a value in second.
212
213 Having ``socket_timeout`` enabled can help to detect "half-open connection".
214 For instance loosing connectivity without the server explicitly closing the
215 connection (switching network interface ethernet/wifi, router down, etc…).
216
217 **Nota bene**: with ``socket_timeout`` enabled each command sent to MPD might
218 timeout. A couple of seconds should be enough for commands to complete except
219 for the special case of ``idle`` command which by definition *“ waits until
220 there is a noteworthy change in one or more of MPD’s subsystems.”* (cf. `MPD
221 protocol documentation`_).
222
223 Here is a solution to use ``idle`` command with ``socket_timeout``:
224
225 .. code-block:: python
226
227     import musicpd
228     import select
229     import socket
230
231     cli = musicpd.MPDClient()
232     try:
233         cli.socket_timeout = 10  # seconds
234         select_timeout = 5 # second
235         cli.connect()
236         while True:
237             cli.send_idle()  # use send_ API to avoid blocking on read
238             _read, _, _ = select.select([cli], [], [], select_timeout)
239             if _read:  # tries to read response
240                 ret = cli.fetch_idle()
241                 print(', '.join(ret))  # Do something
242             else: # cancels idle
243                 cli.noidle()
244     except socket.timeout as err:
245         print(f'{err} (timeout {cli.socket_timeout})')
246     except (OSError, musicpd.MPDError) as err:
247         print(f'{err!r}')
248         if cli._sock is not None:
249             cli.disconnect()
250     except KeyboardInterrupt:
251         pass
252
253 Some explanations:
254
255   * First launch a non blocking ``idle`` command. This call do not wait for a
256     response to avoid socket timeout waiting for an MPD event.
257   * ``select`` waits for something to read on the socket (the idle response
258     in this case), returns after ``select_timeout`` seconds anyway.
259   * In case there is something to read read it using ``fetch_idle``
260   * Nothing to read, cancel idle with ``noidle``
261
262 All three commands in the while loop (send_idle, fetch_idle, noidle) are not
263 triggering a socket timeout unless the connection is actually lost (actually it
264 could also be that MPD took too much time to answer, but MPD taking more than a
265 couple of seconds for these commands should never occur).
266
267
268 .. _MPD protocol documentation: http://www.musicpd.org/doc/protocol/
269 .. vim: spell spelllang=en