soco.services module

Classes representing Sonos UPnP services.

>>> import soco
>>> device = soco.SoCo('192.168.1.102')
>>> print(RenderingControl(device).GetMute([('InstanceID', 0),
...     ('Channel', 'Master')]))
{'CurrentMute': '0'}
>>> r = ContentDirectory(device).Browse([
...    ('ObjectID', 'Q:0'),
...    ('BrowseFlag', 'BrowseDirectChildren'),
...    ('Filter', '*'),
...    ('StartingIndex', '0'),
...    ('RequestedCount', '100'),
...    ('SortCriteria', '')
...    ])
>>> print(r['Result'])
<?xml version="1.0" ?><DIDL-Lite xmlns="urn:schemas-upnp-org:metadata ...
>>> for action, in_args, out_args in AlarmClock(device).iter_actions():
...    print(action, in_args, out_args)
...
SetFormat [Argument(name='DesiredTimeFormat', vartype='string'), Argument(
name='DesiredDateFormat', vartype='string')] []
GetFormat [] [Argument(name='CurrentTimeFormat', vartype='string'),
Argument(name='CurrentDateFormat', vartype='string')] ...
class soco.services.Action(name, in_args, out_args)

A UPnP Action and its arguments.

__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__getstate__()

Exclude the OrderedDict from pickling

static __new__(_cls, name, in_args, out_args)

Create new instance of Action(name, in_args, out_args)

__repr__()

Return a nicely formatted representation string

in_args

Alias for field number 1

name

Alias for field number 0

out_args

Alias for field number 2

class soco.services.Argument(name, vartype)

A UPnP Argument and its type.

__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__getstate__()

Exclude the OrderedDict from pickling

static __new__(_cls, name, vartype)

Create new instance of Argument(name, vartype)

__repr__()

Return a nicely formatted representation string

name

Alias for field number 0

vartype

Alias for field number 1

class soco.services.Service(soco)[source]

A class representing a UPnP service.

This is the base class for all Sonos Service classes. This class has a dynamic method dispatcher. Calls to methods which are not explicitly defined here are dispatched automatically to the service action with the same name.

Parameters:soco (SoCo) – A SoCo instance to which the UPnP Actions will be sent
soco = None

SoCo: The SoCo instance to which UPnP Actions are sent

service_type = None

str: The UPnP service type.

version = None

str: The UPnP service version.

base_url = None

str: The base URL for sending UPnP Actions.

control_url = None

str: The UPnP Control URL.

scpd_url = None

str: The service control protocol description URL.

event_subscription_url = None

str: The service eventing subscription URL.

cache = None

A cache for storing the result of network calls. By default, this is a TimedCache with a default timeout=0.

__getattr__(action)[source]

Called when a method on the instance cannot be found.

Causes an action to be sent to UPnP server. See also object.__getattr__.

Parameters:action (str) – The name of the unknown method.
Returns:The callable to be invoked. .
Return type:callable
static wrap_arguments(args=None)[source]

Wrap a list of tuples in xml ready to pass into a SOAP request.

Parameters:args (list) – a list of (name, value) tuples specifying the name of each argument and its value, eg [('InstanceID', 0), ('Speed', 1)]. The value can be a string or something with a string representation. The arguments are escaped and wrapped in <name> and <value> tags.

Example

>>> from soco import SoCo
>>> device = SoCo('192.168.1.101')
>>> s = Service(device)
>>> print(s.wrap_arguments([('InstanceID', 0), ('Speed', 1)]))
<InstanceID>0</InstanceID><Speed>1</Speed>'
static unwrap_arguments(xml_response)[source]

Extract arguments and their values from a SOAP response.

Parameters:xml_response (str) – SOAP/xml response text (unicode, not utf-8).
Returns:a dict of {argument_name, value)} items.
Return type:dict
build_command(action, args=None)[source]

Build a SOAP request.

Parameters:
  • action (str) – the name of an action (a string as specified in the service description XML file) to be sent.
  • args (list, optional) – Relevant arguments as a list of (name, value) tuples.
Returns:

a tuple containing the POST headers (as a dict) and a string containing the relevant SOAP body. Does not set content-length, or host headers, which are completed upon sending.

Return type:

tuple

send_command(action, args=None, cache=None, cache_timeout=None)[source]

Send a command to a Sonos device.

Parameters:
  • action (str) – the name of an action (a string as specified in the service description XML file) to be sent.
  • args (list, optional) – Relevant arguments as a list of (name, value) tuples.
  • cache (Cache) – A cache is operated so that the result will be stored for up to cache_timeout seconds, and a subsequent call with the same arguments within that period will be returned from the cache, saving a further network call. The cache may be invalidated or even primed from another thread (for example if a UPnP event is received to indicate that the state of the Sonos device has changed). If cache_timeout is missing or None, the cache will use a default value (which may be 0 - see cache). By default, the cache identified by the service’s cache attribute will be used, but a different cache object may be specified in the cache parameter.
Returns:

a dict of {argument_name, value)} items.

Return type:

dict

Raises:
handle_upnp_error(xml_error)[source]

Disect a UPnP error, and raise an appropriate exception.

Parameters:xml_error (str) – a unicode string containing the body of the UPnP/SOAP Fault response. Raises an exception containing the error code.
subscribe(requested_timeout=None, auto_renew=False, event_queue=None)[source]

Subscribe to the service’s events.

Parameters:
  • requested_timeout (int, optional) – If requested_timeout is provided, a subscription valid for that number of seconds will be requested, but not guaranteed. Check Subscription.timeout on return to find out what period of validity is actually allocated.
  • auto_renew (bool) – If auto_renew is True, the subscription will automatically be renewed just before it expires, if possible. Default is False.
  • event_queue (Queue) – a thread-safe queue object on which received events will be put. If not specified, a (Queue) will be created and used.
Returns:

an insance of Subscription, representing the new subscription.

Return type:

Subscription

To unsubscribe, call the unsubscribe method on the returned object.

iter_actions()[source]

Yield the service’s actions with their arguments.

Yields:Action – the next action.

Each action is an Action namedtuple, consisting of action_name (a string), in_args (a list of Argument namedtuples consisting of name and argtype), and out_args (ditto), eg:

Action(
    name='SetFormat',
    in_args=[
        Argument(name='DesiredTimeFormat', vartype='string'),
        Argument(name='DesiredDateFormat', vartype='string')],
    out_args=[]
)
iter_event_vars()[source]

Yield the services eventable variables.

Yields:tuple – a tuple of (variable name, data type).
class soco.services.AlarmClock(soco)[source]

Sonos alarm service, for setting and getting time and alarms.

class soco.services.MusicServices(soco)[source]

Sonos music services service, for functions related to 3rd party music services.

class soco.services.DeviceProperties(soco)[source]

Sonos device properties service, for functions relating to zones, LED state, stereo pairs etc.

class soco.services.SystemProperties(soco)[source]

Sonos system properties service, for functions relating to authentication etc.

class soco.services.ZoneGroupTopology(soco)[source]

Sonos zone group topology service, for functions relating to network topology, diagnostics and updates.

GetZoneGroupState(*args, **kwargs)[source]

Overrides default handling to use the global shared zone group state cache, unless another cache is specified.

class soco.services.GroupManagement(soco)[source]

Sonos group management service, for services relating to groups.

class soco.services.QPlay(soco)[source]

Sonos Tencent QPlay service (a Chinese music service)

class soco.services.ContentDirectory(soco)[source]

UPnP standard Content Directory service, for functions relating to browsing, searching and listing available music.

class soco.services.MS_ConnectionManager(soco)[source]

UPnP standard connection manager service for the media server.

class soco.services.RenderingControl(soco)[source]

UPnP standard rendering control service, for functions relating to playback rendering, eg bass, treble, volume and EQ.

class soco.services.MR_ConnectionManager(soco)[source]

UPnP standard connection manager service for the media renderer.

class soco.services.AVTransport(soco)[source]

UPnP standard AV Transport service, for functions relating to transport management, eg play, stop, seek, playlists etc.

class soco.services.Queue(soco)[source]

Sonos queue service, for functions relating to queue management, saving queues etc.

class soco.services.GroupRenderingControl(soco)[source]

Sonos group rendering control service, for functions relating to group volume etc.