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)[source]

A UPnP Action and its arguments.

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

class soco.services.Argument(name, vartype)[source]

A UPnP Argument and its type.

Create new instance of ArgumentBase(name, vartype)

class soco.services.Vartype(datatype, default, list, range)[source]

An argument type with default value and range.

Create new instance of VartypeBase(datatype, default, list, range)

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

The SoCo instance to which UPnP Actions are sent

Type

SoCo

service_type

The UPnP service type.

Type

str

version

The UPnP service version.

Type

str

base_url

The base URL for sending UPnP Actions.

Type

str

control_url

The UPnP Control URL.

Type

str

scpd_url

The service control protocol description URL.

Type

str

event_subscription_url

The service eventing subscription URL.

Type

str

cache

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

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

compose_args(action_name, in_argdict)[source]

Compose the argument list from an argument dictionary, with respect for default values.

Parameters
  • action_name (str) – The name of the action to be performed.

  • in_argdict (dict) – Arguments as a dict, e.g. {'InstanceID': 0, 'Speed': 1}. The values can be a string or something with a string representation.

Returns

a list of (name, value) tuples.

Return type

list

Raises
  • AttributeError – If this service does not support the action.

  • ValueError – If the argument lists do not match the action signature.

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, **kwargs)[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, as an alternative to kwargs.

  • 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.

  • kwargs – Relevant arguments for the command.

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, strict=True)[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 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.

  • strict (bool, optional) – If True and an Exception occurs during execution, the Exception will be raised or, if False, the Exception will be logged and the Subscription instance will be returned. Default True.

Returns

an instance of Subscription, representing the new subscription. If config.EVENTS_MODULE has been set to refer to events_twisted, a deferred will be returned with the Subscription as its result and deferred.subscription will be set to refer to the Subscription.

Return type

Subscription

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

property actions

The service’s actions with their arguments.

Returns

A list of Action namedtuples, consisting of action_name (str), in_args (list of Argument namedtuples, consisting of name and argtype), and out_args (ditto).

Return type

list(Action)

The return value looks like this:

[
    Action(
        name='GetMute',
        in_args=[
            Argument(name='InstanceID', ...),
            Argument(
                name='Channel',
                vartype='string',
                list=['Master', 'LF', 'RF', 'SpeakerOnly'],
                range=None
            )
        ],
        out_args=[
            Argument(name='CurrentMute, ...)
        ]
    )
    Action(...)
]

Its string representation will look like this:

GetMute(InstanceID: ui4, Channel: [Master, LF, RF, SpeakerOnly])

-> {CurrentMute: boolean}
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=<Vartype>),
        Argument(name='DesiredDateFormat', vartype=<Vartype>)],
    out_args=[]
)
property event_vars

The service’s eventable variables.

Returns

A list of (variable name, data type) tuples.

Return type

list(tuple)

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.

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

Sonos audio in service, for functions related to RCA audio input.

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

Sonos group management service, for services relating to groups.

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

Sonos Tencent QPlay service (a Chinese music service)

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

UPnP standard connection manager service for the media server.

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

UPnP standard connection manager service for the media renderer.

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent

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

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

Parameters
  • soco (SoCo) – A SoCo instance to which the UPnP Actions will be

  • sent